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

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

import app_home.cache as cache
from app_data.loader import load_broker
from app_data.user import User
from tests import helper


class PipelineUserTest(TestCase):
    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, keyname, '^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.from_keyname(keyname="alice")
        bob = User.from_keyname(keyname="bob")
        charlie = User.from_keyname(keyname="charlie")

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