From 01a5d4cea166a71d96bbe4e8c3648128b06b9d3c Mon Sep 17 00:00:00 2001 From: Valentin Lorentz <vlorentz@softwareheritage.org> Date: Mon, 19 Aug 2019 14:35:41 +0200 Subject: [PATCH] Add a get_hash helper method to Content. Code manipulating a Content object may want to access a hash of configurable name; this method allows it to do that without using getattr directly. --- swh/model/model.py | 6 ++++++ swh/model/tests/test_model.py | 9 +++++++++ 2 files changed, 15 insertions(+) diff --git a/swh/model/model.py b/swh/model/model.py index b741ae7c..36f8ef3f 100644 --- a/swh/model/model.py +++ b/swh/model/model.py @@ -11,6 +11,7 @@ import attr import dateutil.parser from .identifiers import normalize_timestamp +from .hashutil import DEFAULT_ALGORITHMS SHA1_SIZE = 20 @@ -362,3 +363,8 @@ class Content(BaseModel): if content[field] is None: del content[field] return content + + def get_hash(self, hash_name): + if hash_name not in DEFAULT_ALGORITHMS: + raise ValueError('{} is not a valid hash name.'.format(hash_name)) + return getattr(self, hash_name) diff --git a/swh/model/tests/test_model.py b/swh/model/tests/test_model.py index 220ba324..f9186857 100644 --- a/swh/model/tests/test_model.py +++ b/swh/model/tests/test_model.py @@ -7,6 +7,7 @@ import copy from hypothesis import given +from swh.model.model import Content from swh.model.hypothesis_strategies import objects @@ -24,3 +25,11 @@ def test_todict_inverse_fromdict(objtype_and_obj): # Check the composition of from_dict and to_dict is the identity assert obj_as_dict == type(obj).from_dict(obj_as_dict).to_dict() + + +def test_content_get_hash(): + hashes = dict( + sha1=b'foo', sha1_git=b'bar', sha256=b'baz', blake2s256=b'qux') + c = Content(length=42, status='visible', **hashes) + for (hash_name, hash_) in hashes.items(): + assert c.get_hash(hash_name) == hash_ -- GitLab