From e737df8e8ca76f5016c5a16187ada5138c579931 Mon Sep 17 00:00:00 2001 From: Vinicius Moreira Date: Fri, 4 Mar 2022 11:58:47 -0300 Subject: [PATCH] [api] refactoring: implementing __eq__ and __hash__ for PackageUpdate --- bauh/api/abstract/model.py | 12 +++++++++++- tests/api/__init__.py | 0 tests/api/abstract/__init__.py | 0 tests/api/abstract/test_model.py | 18 ++++++++++++++++++ 4 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 tests/api/__init__.py create mode 100644 tests/api/abstract/__init__.py create mode 100644 tests/api/abstract/test_model.py diff --git a/bauh/api/abstract/model.py b/bauh/api/abstract/model.py index 06c352ff..8e63e257 100644 --- a/bauh/api/abstract/model.py +++ b/bauh/api/abstract/model.py @@ -263,7 +263,17 @@ class PackageUpdate: self.type = pkg_type def __str__(self): - return '{} (id={}, name={}, version={}, type={})'.format(self.__class__.__name__, self.id, self.name, self.version, self.type) + attrs = ', '.join(f'{p}={v}' for p, v in sorted(self.__dict__.items())) + return f'{self.__class__.__name__} ({attrs})' + + def __eq__(self, other): + if isinstance(other, PackageUpdate): + return self.__dict__ == other.__dict__ + + return False + + def __hash__(self): + return sum(hash(v) for v in self.__dict__.values()) class PackageHistory: diff --git a/tests/api/__init__.py b/tests/api/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/api/abstract/__init__.py b/tests/api/abstract/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/api/abstract/test_model.py b/tests/api/abstract/test_model.py new file mode 100644 index 00000000..1c1ae843 --- /dev/null +++ b/tests/api/abstract/test_model.py @@ -0,0 +1,18 @@ +from unittest import TestCase + +from bauh.api.abstract.model import PackageUpdate + + +class PackageUpdateTest(TestCase): + + def test__hash__return_same_hash_for_equal_packages(self): + a = PackageUpdate(pkg_id='a', name='b', version='c', pkg_type='d') + b = PackageUpdate(pkg_id='a', name='b', version='c', pkg_type='d') + self.assertEqual(a, b) + self.assertEqual(hash(a), hash(b)) + + def test__hash__return_different_hash_for_not_equal_packages(self): + a = PackageUpdate(pkg_id='a', name='b', version='c', pkg_type='d') + b = PackageUpdate(pkg_id='a', name='b', version='c', pkg_type='e') + self.assertNotEqual(a, b) + self.assertNotEqual(hash(a), hash(b))