【问题标题】:Django Unit Test not executed未执行 Django 单元测试
【发布时间】:2022-01-25 11:00:04
【问题描述】:

我仍在为 Django 中的测试而苦苦挣扎。现在我重写了一个测试,但它没有被执行,所以当我运行测试命令时我看不到任何结果。是因为测试错误还是我遗漏了什么? 再次感谢你:)

型号:

class Lab(models.Model):
    lab_name = models.CharField(max_length=200)
    category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT)
    pub_date = models.DateTimeField('date published')
    lab_theory = models.TextField()
    def __str__(self):
        return self.lab_name

class QuestionMultipleChoice(models.Model):
    lab = models.ForeignKey(Lab, on_delete=models.CASCADE)
    type = QuestionType.multiplechoice
    question = models.CharField(max_length=200,null=True)
    option1 = models.CharField(max_length=200,null=True)
    option2 = models.CharField(max_length=200,null=True)
    option3 = models.CharField(max_length=200,null=True)
    option4 = models.CharField(max_length=200,null=True)
    answer = models.IntegerField(max_length=200,null=True)
    
    def __str__(self):
        return self.question

    @property
    def html_name(self):
        return "q_mc_{}".format(self.pk)

    @property
    def correct_answer(self):
        correct_answer_number = int(self.answer)
        correct_answer = getattr(self, "option{}".format(correct_answer_number))
        return correct_answer

    def check_answer(self, given):
        return self.correct_answer == given


测试:

    def test_past_question(self):
        """
        Questions with a pub_date in the past are displayed on the
        index page.
        """
        past_date = date(1997, 3, 2)
        lab2 = Lab.objects.create(lab_name="test lab past question", pub_date=past_date, lab_theory="test lab past question")
        past_question = QuestionMultipleChoice.objects.create(lab=lab2, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1')
        response = self.client.get(reverse('labs:index'))
        print (response)
        self.assertEqual(str(past_question),'This is a test question')

【问题讨论】:

  • 测试有 self 参数但没有类?

标签: python django unit-testing django-models


【解决方案1】:

对于被 Django 的DiscoverRunner 发现的测试,它应该满足以下条件:

  • 方法必须以test_开头
  • 该方法应该在一个继承自django.test.TestCase的类中
  • TestCase 应位于遵循 test*.py 全局模式的文件中。
  • 如果您将myapp.tests 作为一个模块,则它下的所有文件仍必须满足test*.py 全局匹配并且tests 模块中必须有一个__init__.py。李>

除非您将 TEST_RUNNER 换成 Pytest 或其他东西,否则这些都应该成立。我可能遗漏了一些东西,所以请告诉我这些是否属实,我可以编辑评论,提供有关您的具体情况的更多详细信息。

一些documentationDiscoverRunner source

【讨论】:

  • 嗨,丹,是的,我已经掌握了所有要点。我只是把未执行的测试的“代码部分”。实际执行其他测试。这与我制作的另一个 question 有关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-18
  • 1970-01-01
  • 2019-08-10
  • 2013-03-20
  • 2016-04-15
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多