# (c) cavaliba.com - test_instance_aaa_revision.py


from django.test import TestCase

import app_home.cache as cache
from app_data.data import Instance
from app_data.models import DataInstance, DataRevision
from tests import helper

AAA = {"username": "apiuser", "perms": ["p_data_admin"]}


class TestAaaRevision(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(classname="aatest")

    def test_aaa_revision_empty_on_init(self):
        instance = Instance(classname="aatest")
        self.assertEqual(instance.aaa_revision, {})

    def test_aaa_revision_set_by_merge_import(self):
        instance = Instance(classname="aatest")
        instance.merge_import({"classname": "aatest", "keyname": "obj01"}, aaa=AAA)
        self.assertEqual(instance.aaa_revision.get("username"), "apiuser")

    def test_aaa_revision_set_by_merge_request(self):
        instance = Instance(classname="aatest")
        from django.test import RequestFactory

        rf = RequestFactory()
        request = rf.post("/", {"keyname": "obj02", "displayname": "Test"})
        instance.merge_request(request, aaa=AAA)
        self.assertEqual(instance.aaa_revision.get("username"), "apiuser")

    def test_aaa_revision_not_in_data_json(self):
        instance = Instance(classname="aatest")
        instance.merge_import({"classname": "aatest", "keyname": "obj03"}, aaa=AAA)
        instance.create()
        iobj = DataInstance.objects.get(classname="aatest", keyname="obj03")
        self.assertNotIn("aaa_revision", iobj.data_json)

    def test_revision_username_from_aaa_revision(self):
        instance = Instance(classname="aatest")
        instance.merge_import({"classname": "aatest", "keyname": "obj04"}, aaa=AAA)
        instance.create()
        rev = DataRevision.objects.filter(classname="aatest", keyname="obj04").first()
        self.assertIsNotNone(rev)
        self.assertEqual(rev.username, "apiuser")

    def test_no_revision_without_aaa_revision(self):
        instance = Instance(classname="aatest")
        instance.merge_import({"classname": "aatest", "keyname": "obj05"})
        instance.create()
        self.assertEqual(
            DataRevision.objects.filter(classname="aatest", keyname="obj05").count(), 0
        )
