from django.conf import settings
from django.contrib.auth import models
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.tests.test_views import AuthViewsTestCase
from django.contrib.auth.tests.utils import skipIfCustomUser
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from django.test import TestCase
from django.test.client import RequestFactory


@skipIfCustomUser
class LoginRequiredTestCase(AuthViewsTestCase):
    """
    Tests the login_required decorators
    """
    urls = 'django.contrib.auth.tests.urls'

    def testCallable(self):
        """
        Check that login_required is assignable to callable objects.
        """
        class CallableView(object):
            def __call__(self, *args, **kwargs):
                pass
        login_required(CallableView())

    def testView(self):
        """
        Check that login_required is assignable to normal views.
        """
        def normal_view(request):
            pass
        login_required(normal_view)

    def testLoginRequired(self, view_url='/login_required/', login_url=None):
        """
        Check that login_required works on a simple view wrapped in a
        login_required decorator.
        """
        if login_url is None:
            login_url = settings.LOGIN_URL
        response = self.client.get(view_url)
        self.assertEqual(response.status_code, 302)
        self.assertTrue(login_url in response.url)
        self.login()
        response = self.client.get(view_url)
        self.assertEqual(response.status_code, 200)

    def testLoginRequiredNextUrl(self):
        """
        Check that login_required works on a simple view wrapped in a
        login_required decorator with a login_url set.
        """
        self.testLoginRequired(view_url='/login_required_login_url/',
            login_url='/somewhere/')


class PermissionsRequiredDecoratorTest(TestCase):
    """
    Tests for the permission_required decorator
    """
    def setUp(self):
        self.user = models.User.objects.create(username='joe', password='qwerty')
        self.factory = RequestFactory()
        # Add permissions auth.add_customuser and auth.change_customuser
        perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser'))
        self.user.user_permissions.add(*perms)

    def test_many_permissions_pass(self):

        @permission_required(['auth.add_customuser', 'auth.change_customuser'])
        def a_view(request):
            return HttpResponse()
        request = self.factory.get('/rand')
        request.user = self.user
        resp = a_view(request)
        self.assertEqual(resp.status_code, 200)

    def test_single_permission_pass(self):

        @permission_required('auth.add_customuser')
        def a_view(request):
            return HttpResponse()
        request = self.factory.get('/rand')
        request.user = self.user
        resp = a_view(request)
        self.assertEqual(resp.status_code, 200)

    def test_permissioned_denied_redirect(self):

        @permission_required(['auth.add_customuser', 'auth.change_customuser', 'non-existent-permission'])
        def a_view(request):
            return HttpResponse()
        request = self.factory.get('/rand')
        request.user = self.user
        resp = a_view(request)
        self.assertEqual(resp.status_code, 302)

    def test_permissioned_denied_exception_raised(self):

        @permission_required(['auth.add_customuser', 'auth.change_customuser', 'non-existent-permission'], raise_exception=True)
        def a_view(request):
            return HttpResponse()
        request = self.factory.get('/rand')
        request.user = self.user
        self.assertRaises(PermissionDenied, a_view, request)
