# (c) cavaliba.com - tests / pipeline user

import yaml

from django.test import TestCase
from django.core.cache import cache as cache_django

from tests import helper

import app_home.cache as cache

from app_data.loader import load_broker
from app_user.user import user_get_by_login


class PipelineUserTest(TestCase):

    fixtures = ["init"]

    def setUp(self):
        helper.add_admin_user(login="unittest")
        cache.clear()
        cache_django.clear()

        helper.add_user(login="alice")
        helper.add_user(login="bob")
        helper.add_user(login="charlie")


    def test_pipeline_user_disable_on_criteria(self):

        datalist = yaml.safe_load('''
            - classname: _pipeline
              keyname: pipeline_user_disable
              displayname: pipeline_user_disable
              description: disable users matching login criteria
              is_enabled: True
              content: |
                  tasks:
                  - field_set: ['', _action, noop]
                  - set_condition: [MATCH, field_match, login, '^b']
                  - field_set: [MATCH, _action, disable]
            ''')
        aaa = {'perms': ['p_pipeline_create']}
        load_broker(datalist=datalist, aaa=aaa)

        aaa = {'perms': ['p_user_update', 'p_pipeline_run']}
        count_ok, count_discarded, errors = helper.run_pipeline("pipeline_user_disable", ["_user"], aaa=aaa)

        self.assertEqual(errors, [])
        self.assertEqual(count_discarded, 0)

        alice = user_get_by_login("alice")
        bob = user_get_by_login("bob")
        charlie = user_get_by_login("charlie")

        self.assertTrue(alice.is_enabled)
        self.assertFalse(bob.is_enabled)
        self.assertTrue(charlie.is_enabled)
