我想将单元测试引入 Django 应用程序。虽然我开始在我想测试的第一件事上失败了。你能告诉我我做错了什么吗?
我要测试的视图
@user_passes_test(lambda u: u.has_module_perms('myModule'))
def myView(request):
...someCode...
我想测试 user_passes_test 位,我还有更复杂的测试,所以我想知道我的测试是否让正确的用户并且只有他们才能访问视图。我专注于不起作用的部分并对其进行了一些简化。
from django.contrib.auth.models import User
from django.test import TestCase
from settings import DJANGO_ROOT
class PermissionsTestCase(TestCase):
fixtures = [DJANGO_ROOT + 'testdata.json']
def setUp(self):
self.user = User.objects.create(username='user', password='pass')
self.user.save()
def test_permissions_overview(self):
url = '/secret/'
#User not logged in (guest)
response = self.client.get(url)
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/secret/')
#Logged in user that should not be able to see this page
response = self.client.get(url)
self.client.login(username='user', password='pass')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/secret/')
#Logged in user that has 'myModule' module permissions
self.user.user_permissions.add('myModule.view_myThing')
self.user.save()
self.assertTrue(self.user.has_module_perms('myModule')) #This one fails
self.client.login(username='user',password='pass')
response = self.client.get(url)
self.assertContains(response, "What to look for") #This one too
最后一点一直失败。权限没有通过。有任何想法吗?