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

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.group import Group
from tests import helper


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

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_group_list(self):
        helper.add_admin_user(login="unittest")
        response = self.client.get(
            reverse("app_data:instance_list", kwargs={"classname": "group"}), follow=True
        )
        self.assertEqual(response.status_code, 200)

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

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

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

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_group_edit_post(self):
        helper.add_admin_user(login="unittest")
        group = helper.add_group(name="testgroup01")
        url = reverse("app_data:instance_edit", kwargs={"id": group.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_group_delete_1(self):
        helper.add_admin_user(login="unittest")
        group = helper.add_group(name="testgroup01")
        response = self.client.post(
            reverse("app_data:instance_delete", kwargs={"id": group.id}), follow=True
        )
        self.assertEqual(response.status_code, 200)
        group2 = Group.from_id(group.id)
        self.assertIsNone(group2)
