I have a script which imports millions of records from a legacy database into a Django database using raw SQL for efficiency. The legacy database does not have ID primary keys, so these are created from a sequence when inserting rows.
I'm testing that this import process is working properly by creating rows in the legacy database, running the import and verifying that I get the proper Django objects back out. The last part of a test typically looks a bit like this:
actual = MyModel.objects.get(code=legacy_object_code)
expected = MyModel(
id=actual.id,
code=legacy_object_code,
other_property=other_value,
…
)
I have to pull the ID in from the actual object because otherwise there's no way the two objects could be tested for equality. But the problem is that self.assertEqual(expected, actual)
always succeeds! This is because Django object equality is defined as having the same type and ID/PK.
My workaround to actually check the properties of the model instances is this:
def assert_model_instance_field_equality(self, expected, actual):
expected_dict = expected.__dict__
expected_dict.pop('_state')
actual_dict = actual.__dict__
actual_dict.pop('_state')
self.assertDictEqual(expected_dict, actual_dict)
I couldn't find this sort of assertion method, but maybe I'm missing something. Is there such a method, am I missing something, or is this really the best way to check field equality?