From 84ad71e9587b92937602fab49839beeb04e15b9b Mon Sep 17 00:00:00 2001 From: Samuele Maci Date: Tue, 22 Oct 2019 14:48:55 +0200 Subject: [PATCH] Models equality depends on self and other be instances of the same class (isinstance instead of is) --- bravado_core/model.py | 7 +++++-- tests/model/model_test.py | 10 +++++++++- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/bravado_core/model.py b/bravado_core/model.py index cf01eeb9..183ead37 100644 --- a/bravado_core/model.py +++ b/bravado_core/model.py @@ -471,8 +471,11 @@ def __eq__(self, other): Two model instances are equal if they have the same type and the same properties and values (including additional properties). """ - # Check same type as self - if type(self) is not type(other): + # Double check is needed to properly deal with polymorphic models + # Example: Dog is a discriminated version of Animal. + # assert isinstance(dog, Animal) is True + # assert isinstance(animal, Dog) is False + if not isinstance(other, self.__class__) or not isinstance(self, other.__class__): return False # Ignore any '_raw' keys diff --git a/tests/model/model_test.py b/tests/model/model_test.py index 19a28143..d07d1c21 100644 --- a/tests/model/model_test.py +++ b/tests/model/model_test.py @@ -131,12 +131,20 @@ def test_model_issubclass_inherits_from(pet_type, cat_type): assert issubclass(cat_type, pet_type) -def test_model_isinstance_model_class_generate_by_different_Spec_object(cat_swagger_spec, cat_type, cat_kwargs): +def test_model_isinstance_model_class_generated_by_different_Spec_object(cat_swagger_spec, cat_type, cat_kwargs): cat = cat_type(**cat_kwargs) new_cat_spec = Spec.from_dict(cat_swagger_spec.client_spec_dict) assert isinstance(cat, new_cat_spec.definitions['Cat']) +def test_model_equality_if_model_class_generated_by_different_Spec_object(cat_swagger_spec, cat_type, cat_kwargs): + cat = cat_type(**cat_kwargs) + new_cat_spec = Spec.from_dict(cat_swagger_spec.client_spec_dict) + new_cat_type = new_cat_spec.definitions['Cat'] + new_cat = new_cat_type(**cat_kwargs) + assert cat == new_cat + + def test_model_deepcopy(user_type, user_kwargs): user = user_type(**user_kwargs) user_copy = deepcopy(user)