# (c) cavaliba.com - test_revision_diff.py

import json

from django.test import TestCase

import app_home.cache as cache
from app_data.models import DataRevision
from app_data.revision import revision_add, revision_add_raw
from tests import helper

AAA = {"username": "testuser"}


class TestRevisionDiff(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(classname="rdtest")
        helper.add_instance(classname="rdtest", keyname="obj01")

    def test_revision_add_with_diff_stores_json(self):
        diff = {"displayname": {"before": "Old", "after": "New"}}
        revision_add_raw(aaa=AAA, classname="rdtest", keyname="obj01", action="edit")
        rev = DataRevision.objects.filter(classname="rdtest", keyname="obj01").first()
        # revision_add_raw doesn't support diff; use revision_add directly
        from app_data.data import Instance

        instance = Instance.from_keyname("rdtest", "obj01")
        revision_add(aaa=AAA, instance=instance, action="edit", diff=diff)
        rev = DataRevision.objects.filter(classname="rdtest", keyname="obj01", action="edit").last()
        self.assertIsNotNone(rev)
        self.assertNotEqual(rev.data_diff, "")
        parsed = json.loads(rev.data_diff)
        self.assertIn("displayname", parsed)

    def test_revision_add_without_diff_stores_empty(self):
        from app_data.data import Instance

        instance = Instance.from_keyname("rdtest", "obj01")
        revision_add(aaa=AAA, instance=instance, action="edit")
        rev = DataRevision.objects.filter(classname="rdtest", keyname="obj01", action="edit").last()
        self.assertIsNotNone(rev)
        self.assertEqual(rev.data_diff, "")

    def test_revision_add_raw_data_diff_empty(self):
        revision_add_raw(aaa=AAA, classname="rdtest", keyname="obj01", action="test")
        rev = DataRevision.objects.filter(
            classname="rdtest", keyname="obj01", action="test"
        ).first()
        self.assertIsNotNone(rev)
        self.assertEqual(rev.data_diff, "")
