gpt4 book ai didi

django - 单元测试权限

转载 作者:行者123 更新时间:2023-12-04 15:24:26 25 4
gpt4 key购买 nike

我想向 Django 应用程序引入单元测试。虽然我开始在我想测试的第一件事上失败。你能告诉我我做错了什么吗?

我要测试的 View

@user_passes_test(lambda u: u.has_module_perms('myModule'))
def myView(request):
...someCode...

我想测试 user_passes_test 位,我还有更复杂的测试,所以我想知道我的测试是否让正确的用户并且只有他们才能访问 View 。我专注于不起作用的部分并对其进行了一些简化。
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

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

最佳答案

这不会将密码转换为哈希

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

关于django - 单元测试权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14663558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com