# (c) cavaliba.com - test_dashboard_cache

from unittest.mock import patch

from django.test import TestCase

import app_home.cache as cache
import app_home.dashboard as dashboard
from app_home.configuration import set_configuration
from app_home.dashboard import get_dashboard_cached, invalidate_dashboard_cache

AAA = {"perms": ["p_data_import"], "is_admin": False, "username": "cacheduser"}

REAL_COMPUTE_DASHBOARD = dashboard.compute_dashboard


class DashboardCacheTest(TestCase):
    def setUp(self):
        cache.clear()
        set_configuration(
            appname="home", keyname="DASHBOARD_CONTENT",
            value="- section: X\n  entries:\n    - app: import\n", description="", page="",
            order=100,
        )  # fmt: skip
        cache.clear()

    def test_second_call_reuses_cached_value(self):
        with patch(
            "app_home.dashboard.compute_dashboard", side_effect=REAL_COMPUTE_DASHBOARD
        ) as mocked:
            get_dashboard_cached(AAA)
            get_dashboard_cached(AAA)
            self.assertEqual(mocked.call_count, 1)

    def test_different_users_get_independent_cache_entries(self):
        other_aaa = {"perms": [], "is_admin": False, "username": "otheruser"}
        with patch(
            "app_home.dashboard.compute_dashboard", side_effect=REAL_COMPUTE_DASHBOARD
        ) as mocked:
            get_dashboard_cached(AAA)
            get_dashboard_cached(other_aaa)
            self.assertEqual(mocked.call_count, 2)

    def test_invalidate_forces_recompute(self):
        with patch(
            "app_home.dashboard.compute_dashboard", side_effect=REAL_COMPUTE_DASHBOARD
        ) as mocked:
            get_dashboard_cached(AAA)
            invalidate_dashboard_cache(username=AAA["username"])
            get_dashboard_cached(AAA)
            self.assertEqual(mocked.call_count, 2)
