代码之家  ›  专栏  ›  技术社区  ›  Shiny_and_Chrome

django测试用例无法通过视图函数上所需的@login\u修饰符

  •  1
  • Shiny_and_Chrome  · 技术社区  · 7 年前

    我搜索了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)
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   solarissmoke    7 年前

    您不能这样设置密码-存储在数据库中的密码是一个散列值,您将其设置为密码字符串本身。这意味着验证将失败。

    你需要 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)
    

    它将登录用户而无需担心密码。