# (c) cavaliba.com - test / views / IAM role

from django.core.cache import cache as cache_django
from django.test import TestCase, override_settings
from django.urls import reverse

import app_home.cache as cache
from app_data.role import Role
from tests import helper


class TestViewsIAMRole(TestCase):
    def setUp(self):
        cache.clear()
        cache_django.clear()

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_list(self):
        helper.add_admin_user(login="unittest")
        role = helper.add_role(name="testrole01")
        response = self.client.get(
            reverse("app_data:instance_list", kwargs={"classname": "role"}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, role.keyname)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_detail(self):
        helper.add_admin_user(login="unittest")
        role = helper.add_role(name="testrole01")
        response = self.client.get(
            reverse("app_data:instance_detail", kwargs={"id": role.id}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, role.keyname)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_edit_new(self):
        helper.add_admin_user(login="unittest")
        response = self.client.get(
            reverse("app_data:instance_new", kwargs={"classname": "role"}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "csrfmiddlewaretoken")

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_edit(self):
        helper.add_admin_user(login="unittest")
        role = helper.add_role(name="testrole01")
        response = self.client.get(
            reverse("app_data:instance_edit", kwargs={"id": role.id}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, role.keyname)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_edit_post(self):
        helper.add_admin_user(login="unittest")
        role = helper.add_role(name="testrole01")
        url = reverse("app_data:instance_edit", kwargs={"id": role.id})

        response = self.client.get(url, follow=True)
        self.assertEqual(response.status_code, 200)

        response = self.client.post(url, data={}, follow=True)
        self.assertEqual(response.status_code, 200)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_role_delete(self):
        helper.add_admin_user(login="unittest")
        role = helper.add_role(name="testrole01")
        response = self.client.post(
            reverse("app_data:instance_delete", kwargs={"id": role.id}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        role2 = Role.from_id(role.id)
        self.assertIsNone(role2)
