8

我想将单元测试引入 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

最后一点一直失败。权限没有通过。有任何想法吗?

4

2 回答 2

5

这不会将密码转换为哈希

User.objects.create(username='user', password='pass')

创建用户的正确方法是:

User.objects.create_user(username='user', password='pass')

这是完整的摘要

>>> from django.contrib.auth.models import User
>>> x=User.objects.create(username='user', password='pass')    
>>> x.password
'pass'
>>> from django.test import Client
>>> c = Client()
>>> c.login(username='user',password='pass')
False

# But create_user works
>>> y=User.objects.create_user(username='user2', password='pass')    
>>> y.password
u'pbkdf2_sha256$12000$oh55gfrnCZn5$hwGrkUZx38siegWHLXSYoNDT2SSP1M5+Whh5PnJZD8I='
>>> c.login(username='user2',password='pass')
True
于 2014-07-13T22:14:08.523 回答
-3

权限是字符串。

# this tests to see if a user has 'myModule'
@user_passes_test(lambda u: u.has_module_perms('myModule'))

#gives the user a completely different permission called 'myModule.view_myThing'
self.user.user_permissions.add('myModule.view_myThing')

#tests to see if user has a permission called 'myModule' which is not 'myModule.view_myThing'
self.assertTrue(self.user.has_module_perms('myModule'))

根据您所写的内容,我无法推断您的意图,但您至少有 2 个尝试添加/检查的不同权限。我将更改您授予用户的权限,如下所示: self.user.user_permissions.add('myModule')

于 2013-02-02T21:14:05.900 回答