【问题标题】:How to test get_success_url in ClassBasedView for Django?如何在 Django 的 ClassBasedView 中测试 get_success_url?
【发布时间】:2020-05-12 06:26:28
【问题描述】:

我正在尝试测试我的 success_url 方法,但找不到正确测试它并增加代码覆盖率的方法。

#views.py

def get_success_url(self):
    if self.question.type in [
        Question.MULTIPLE_TYPE,
        Question.SINGLE_TYPE
    ]:
        return reverse("question")
    else:
        return reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})

这是我在我的 tests.py 文件中尝试过的。

#tests.py
from factories import QuestionFactory

def test_get_success_url(self):
    self.client.force_login(user=self.user)
    question = QuestionFactory(owner=self.user)
    if question.type in [
        Question.MULTIPLE_TYPE,
        Question.SINGLE_TYPE
    ]:
        response = self.client.get(reverse("question"))
    else:
        response = self.client.get(
            reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})
        )
    self.assertEqual(response.status_code, 200)

【问题讨论】:

    标签: django django-views django-class-based-views django-testing django-tests


    【解决方案1】:

    如果要在 CBV 中测试 get_success_url() 方法,则需要调用 CBV 本身。比如:

    # views.py
    class SuccessTestingView(FormView):
        def get_success_url():
            # Your that you want to test here.
    

    测试:

    # tests.py
    from factories import QuestionFactory
    
        class SuccessfullRedirect(TestCase):
    
            def test_successfull_redirect_1(self):
                self.client.force_login(user=self.user)
                response = self.client.post(path_to_cbv, criteria_that_leads_to_first_result)
                self.assertRedirects(response, reverse("question"))
    
            def test_succesfull_redirect_2(self):
                self.client.force_login(user=self.user)
                response = self.client.post(path_to_cbv, criteria_that_leads_to_second_result)
                self.assertRedirects(response, reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE}))
    

    您需要测试视图本身,而不是成功 url 调用的结果。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2018-09-27
      • 2016-06-14
      相关资源
      最近更新 更多