from django.test import RequestFactory
from django.contrib.auth import models

from generic.decorators import user_is_cid_user_manager

from django.contrib.auth.decorators import login_required, permission_required
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.test import TestCase, override_settings
from django.test.client import RequestFactory


class TestDecorators(TestCase):
    def setUp(self):
        self.user = models.User.objects.create(username="foo", password="bar")
        self.user2 = models.User.objects.create(username="foo2", password="bar")
        self.user_super = models.User.objects.create_superuser(
            username="super", password="bar"
        )
        self.factory = RequestFactory()

        self.group = models.Group(name="cid_user_manager")
        self.group.save()
        self.group.user_set.add(self.user)

        @user_is_cid_user_manager
        def a_view(request):
            return HttpResponse()

        self.view = a_view

    def test_cid_user_manager_decorator_pass(self):
        request = self.factory.get("/foo")
        request.user = self.user
        resp = self.view(request)
        self.assertEqual(resp.status_code, 200)

    def test_cid_user_manager_decorator_super(self):
        request = self.factory.get("/foo")
        request.user = self.user_super
        resp = self.view(request)
        self.assertEqual(resp.status_code, 200)

    def test_cid_user_manager_decorator_fail(self):
        request = self.factory.get("/foo")
        request.user = self.user2
        self.assertRaises(PermissionDenied, self.view, request)
