python - django 测试用例无法通过 View 函数上的 @login_required 装饰器

标签 python django django-views django-testing

我搜索了 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/

相关文章:

python 重复程序而为真

python - 反向 Django 管理 URL

javascript - 无法使用javascript检索django序列化的json

django - 在 Django 的 View 函数中调用函数

python - 具有基于类的 View 的装饰器

python - 使用 K 均值聚类 OpenCV 进行交通标志分割

python - 需要动态查找表时的迭代与递归

Python REST API 发布列表

python Django : how to select the index type?

django - 装饰基于类的 View 的两种方法有什么区别?