# (c) cavaliba.com - test_sidebar_link_permission

from django.test import TestCase

import app_home.cache as cache
from app_home.configuration import set_configuration
from app_home.sidebar import compute_sidebar

AAA_GRANTED = {"perms": ["p_this_link_allowed"], "is_admin": False, "username": "granted"}
AAA_NONE = {"perms": [], "is_admin": False, "username": "nobody"}


class SidebarLinkPermissionTest(TestCase):
    def setUp(self):
        cache.clear()

    def _set_content(self, yaml_text):
        set_configuration(
            appname="home", keyname="SIDEBAR_CONTENT", value=yaml_text, description="", page="",
            order=100,
        )  # fmt: skip
        cache.clear()

    def test_link_without_permission_is_always_visible(self):
        self._set_content('- link: "/path/to/a/link"\n  label: "my label"\n')
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows[0]["url"], "/path/to/a/link")
        self.assertEqual(rows[0]["label"], "my label")

    def test_link_with_permission_hidden_when_not_granted(self):
        self._set_content('- link: "/path/to/a/link"\n  permission: p_this_link_allowed\n')
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows, [])

    def test_link_with_permission_visible_when_granted(self):
        self._set_content('- link: "/path/to/a/link"\n  permission: p_this_link_allowed\n')
        rows = compute_sidebar(AAA_GRANTED)
        self.assertEqual(len(rows), 1)

    def test_link_label_defaults_to_url(self):
        self._set_content('- link: "/no-label-here/"\n')
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows[0]["label"], "/no-label-here/")
