【问题标题】:Django Test key associationDjango 测试键关联
【发布时间】:2022-01-21 23:07:54
【问题描述】:

我是 Django 和单元测试的新手。

我正在为我的应用程序编写测试,该应用程序是一个由多个实验室组成的学习平台,其中包括课程和问题(3 种不同类型),问题和实验室之间的关系是通过外键完成的。

我正在尝试编写测试,其中我向数据库添加了一个实验室和一个多项选择题。

问题是测试总是以同样的错误结束:

DETAIL: Key (lab_id)=(1) is not present in table "labs_lab".

我理解这句话的意思,但是如果我为问题提供一个 ID 以将它们链接到相应的测试实验室,怎么会发生这种情况?

谢谢

模型.py

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

test.py

class TestData(TestCase):
    @classmethod
    def setUpTestData(cls):
        past_date = date(1997, 3, 2)
        future_date = date(2050, 3, 2)
        Lab.objects.create(lab_name="testlab", pub_date=datetime.now(), lab_theory="test theory")
        Lab.objects.create(lab_name="test lab past question", pub_date=past_date, lab_theory="test lab past question")
        Lab.objects.create(lab_name="test lab future question", pub_date=future_date, lab_theory="test lab future question")
        

class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        """
        If no questions exist, an appropriate message is displayed.
        """
        response = self.client.get(reverse('labs:index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No labs are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_past_question(self):
        """
        Questions with a pub_date in the past are displayed on the
        index page.
        """
        past_question = QuestionMultipleChoice.objects.create(question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1', lab_id=2)
        response = self.client.get(reverse('labs:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [past_question],
        )

更新:

更新: 我改变了测试,我给了“QuestionMultipleChoice”不同的参数:


question1 = QuestionMultipleChoice.objects.create(lab=1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1')        

现在的结果是:

ValueError: Cannot assign "1": "QuestionMultipleChoice.lab" must be a "Lab" instance.

【问题讨论】:

  • 您好@mdem99 请edit您的问题并在其中添加更新

标签: python django unit-testing django-models


【解决方案1】:

ValueError:无法分配“1”:“QuestionMultipleChoice.lab”必须是“Lab”实例。

这意味着尝试获取 Lab 实例的实验室属性,您可以提供一个实验室实例来分配您必须这样做的实验室实例

lab1 = Lab.objects.create(lab_name="testlab", pub_date=datetime.now(), lab_theory="test theory")

QuestionMultipleChoice.objects.create(question='This is a test question', lab=lab1)

【讨论】:

  • 谢谢,这里仍然有一些问题:TypeError: QuestionMultipleChoice() got an unexpected keyword argument 'lab__id'
猜你喜欢
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
相关资源
最近更新 更多