我搜索了 stackoverflow 并尝试了几种不同的解决方案,但我的测试代码总是转到登录重定向。
这就是我所拥有的:
class LoggedInSetup(TestCase):
def setUp(self):
self.client = Client()
self.user = User.objects.create(username="lolwutboi", password="whatisthepassword")
self.client.login(username='lolwutboi', password='whatisthepassword')
number_of_submissions = 13
for sub in range(number_of_submissions):
Submission.objects.create(title='Amazing', description='This is the body of the post',
author=str(self.user), pub_date=timezone.now())
class LoggedInTestCases(LoggedInSetup):
def test_logged_in_post_reachable(self):
self.client.login(username='lolwutboi', password='whatisthepassword')
resp = self.client.get(reverse('submission_post'))
self.assertEqual(resp.status_code, 200)
最佳答案
您不能这样设置密码 - 存储在数据库中的密码是哈希值,而您将其设置为密码字符串本身。这意味着验证将失败。
您需要set the password像这样:
self.user = User.objects.create(username="lolwutboi")
self.user.set_password("whatisthepassword")
self.user.save()
但是,由于您真正需要的只是登录测试用户,因此请使用 force_login
在测试中:
self.client.force_login(self.user)
这将登录用户,而无需担心密码。
关于python - django 测试用例无法通过 View 函数上的 @login_required 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47825519/