# (c) cavaliba.com - test_dashboard_malformed_yaml

from django.test import TestCase

import app_home.cache as cache
from app_home.configuration import set_configuration
from app_home.dashboard import compute_dashboard

AAA_ADMIN = {"perms": ["p_data_admin"], "is_admin": True, "username": "admin"}
AAA_USER = {"perms": [], "is_admin": False, "username": "bob"}


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

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

    def test_invalid_yaml_syntax_falls_back_empty_for_regular_user(self):
        self._set_content("not: [valid, yaml, structure")
        sections = compute_dashboard(AAA_USER)
        self.assertEqual(sections, [])

    def test_invalid_yaml_syntax_falls_back_to_fix_link_for_admin(self):
        self._set_content("not: [valid, yaml, structure")
        sections = compute_dashboard(AAA_ADMIN)
        self.assertEqual(len(sections), 1)
        card = sections[0]["cards"][0]
        self.assertEqual(card["url"], "/home/private/conf/")

    def test_non_list_top_level_falls_back(self):
        self._set_content("just_a_string_not_a_list")
        sections = compute_dashboard(AAA_USER)
        self.assertEqual(sections, [])

    def test_unrecognized_item_shape_falls_back(self):
        self._set_content("- section: X\n  entries:\n    - neither_schema_app_nor_link: yes\n")
        sections = compute_dashboard(AAA_USER)
        self.assertEqual(sections, [])

    def test_section_missing_entries_list_falls_back(self):
        self._set_content("- section: X\n  entries: not_a_list\n")
        sections = compute_dashboard(AAA_USER)
        self.assertEqual(sections, [])

    def test_link_entry_missing_value_falls_back(self):
        self._set_content("- section: X\n  entries:\n    - link: \n")
        sections = compute_dashboard(AAA_USER)
        self.assertEqual(sections, [])
