断言失败,对象相同

2024-04-20 03:16:57 发布

您现在位置:Python中文网/ 问答频道 /正文

单元测试失败,出现以下异常:

def test_question_form(self):
    question = Question(question_text='Dummy question', pub_date=timezone.now(
    ) + datetime.timedelta(days=1), allow_multiple_choices=True)
    question_form = QuestionForm(
        {'question_text': question.question_text, 'pub_date': question.pub_date, 'allow_multiple_choices': 'on' if question.allow_multiple_choices else 'off'})
    self.assertTrue(question_form.is_valid())
    self.assertEqual(question_form.save(commit=False), question)

AssertionError: <Question: Dummy question> != <Question: Dummy question>

经过人工断言,物体似乎是相等的,我做错了什么?你知道吗


Tags: texttestselfformdatedef单元测试multiple
1条回答
网友
1楼 · 发布于 2024-04-20 03:16:57

由于实例未保存,form.save返回的带有commit=False的模型实例和原始未保存的对象将永远不相等(除非您重写模型的__eq__方法来处理此问题):

docs

The equality method is defined such that instances with the same primary key value and the same concrete class are considered equal, except that instances with a primary key value of None aren’t equal to anything except themselves

相关问题 更多 >