user6216224
user6216224

Reputation:

Assertion fails with same object

The unit test fails with the following exception:

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>

After some manual assertion the object seem to be equal, what am I doing wrong?

Upvotes: 0

Views: 58

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78556

Since your instances are not saved, the model instance returned by form.save with commit=False and the original unsaved object will never be equal (except you override the __eq__ method of your model to handle this):

From the 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

Upvotes: 1

Related Questions