From 2c1e02b897f0990575d158f840af0a4d070afc60 Mon Sep 17 00:00:00 2001 From: Valentin Lorentz <vlorentz@softwareheritage.org> Date: Fri, 14 Feb 2020 18:07:44 +0100 Subject: [PATCH] Add method BaseModel.hashes(). Can be useful to deduplicate code in swh-storage. --- swh/model/model.py | 4 ++++ swh/model/tests/test_model.py | 7 +++++++ 2 files changed, 11 insertions(+) diff --git a/swh/model/model.py b/swh/model/model.py index 512824d6..26accb65 100644 --- a/swh/model/model.py +++ b/swh/model/model.py @@ -384,6 +384,10 @@ class BaseContent(BaseModel): raise ValueError('{} is not a valid hash name.'.format(hash_name)) return getattr(self, hash_name) + def hashes(self) -> Dict[str, bytes]: + """Returns a dictionary {hash_name: hash_value}""" + return {algo: getattr(self, algo) for algo in DEFAULT_ALGORITHMS} + @attr.s(frozen=True) class Content(BaseContent): diff --git a/swh/model/tests/test_model.py b/swh/model/tests/test_model.py index 5560127e..e905725d 100644 --- a/swh/model/tests/test_model.py +++ b/swh/model/tests/test_model.py @@ -62,6 +62,13 @@ def test_content_get_hash(): assert c.get_hash(hash_name) == hash_ +def test_content_hashes(): + hashes = dict( + sha1=b'foo', sha1_git=b'bar', sha256=b'baz', blake2s256=b'qux') + c = Content(length=42, status='visible', **hashes) + assert c.hashes() == hashes + + def test_directory_model_id_computation(): dir_dict = dict(directory_example) del dir_dict['id'] -- GitLab