# (c) cavaliba.com - test_bootstrap.py

from django.test import TestCase

from app_data.models import DataClass
from app_data.user import User
from app_home.models import CavalibaConfiguration
from app_user.models import SirenePermission
from tests import helper


class BootstrapTest(TestCase):
    def test_permissions_loaded(self):
        count = SirenePermission.objects.count()
        self.assertGreater(count, 20)

    def test_configuration_loaded(self):
        count = CavalibaConfiguration.objects.count()
        self.assertGreater(count, 20)

    def test_builtin_schemas_exist(self):
        expected = [
            "user",
            "group",
            "role",
            "_pipeline",
            "_dataview",
            "_apikey",
            "_enumerate",
            "app",
            "site",
            "sirene_message",
            "sirene_template",
            "sirene_public",
            "sitegroup",
        ]
        for keyname in expected:
            with self.subTest(schema=keyname):
                self.assertTrue(DataClass.objects.filter(keyname=keyname).exists(), keyname)

    def test_admin_user_exists(self):
        user = User.from_keyname(keyname="admin")
        self.assertIsNotNone(user)
        self.assertEqual(user.keyname, "admin")
        self.assertEqual(user.displayname, "Built-in Global Admin user")

    def test_admin_role_all_permission(self):
        helper.add_admin_user(login="unittest")
        user = User.from_keyname(keyname="unittest")
        user.compute_aaa()
        perm_keynames = [p.keyname for p in user.permissions]

        for perm in [
            "p_data_access",
            "p_data_create",
            "p_data_admin",
            "p_schema_write",
            "p_user_read",
            "p_pipeline_run",
        ]:
            with self.subTest(perm=perm):
                self.assertIn(perm, perm_keynames)
