# (c) cavaliba.com - test_api_sync_mode.py

from django.test import TestCase

import app_home.cache as cache
from app_data.models import DataInstance
from tests import helper


class TestApiSyncMode(TestCase):
    def setUp(self):
        cache.clear()
        helper.add_schema(classname="smtest")
        self.headers = helper.add_apikey_admin()

    def _post_rawfile(self, body, content_type="application/json", params=""):
        url = f"/api/rawfile/{params}"
        return self.client.post(url, data=body, content_type=content_type, headers=self.headers)

    def test_no_sync_param_last_sync_null(self):
        body = '[{"classname": "smtest", "_action": "create", "keyname": "obj01"}]'
        self._post_rawfile(body)
        iobj = DataInstance.objects.get(classname="smtest", keyname="obj01")
        self.assertIsNone(iobj.last_sync)

    def test_sync_param_1_sets_last_sync(self):
        body = '[{"classname": "smtest", "_action": "create", "keyname": "obj02"}]'
        self._post_rawfile(body, params="?sync=1")
        iobj = DataInstance.objects.get(classname="smtest", keyname="obj02")
        self.assertIsNotNone(iobj.last_sync)

    def test_sync_param_true_sets_last_sync(self):
        body = '[{"classname": "smtest", "_action": "create", "keyname": "obj03"}]'
        self._post_rawfile(body, params="?sync=true")
        iobj = DataInstance.objects.get(classname="smtest", keyname="obj03")
        self.assertIsNotNone(iobj.last_sync)

    def test_sync_param_yes_sets_last_sync(self):
        body = '[{"classname": "smtest", "_action": "create", "keyname": "obj04"}]'
        self._post_rawfile(body, params="?sync=yes")
        iobj = DataInstance.objects.get(classname="smtest", keyname="obj04")
        self.assertIsNotNone(iobj.last_sync)
