Skip to content
Snippets Groups Projects
Commit 01a5d4ce authored by vlorentz's avatar vlorentz
Browse files

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.
parent 19634f25
No related branches found
Tags v0.0.41
Loading
...@@ -11,6 +11,7 @@ import attr ...@@ -11,6 +11,7 @@ import attr
import dateutil.parser import dateutil.parser
from .identifiers import normalize_timestamp from .identifiers import normalize_timestamp
from .hashutil import DEFAULT_ALGORITHMS
SHA1_SIZE = 20 SHA1_SIZE = 20
...@@ -362,3 +363,8 @@ class Content(BaseModel): ...@@ -362,3 +363,8 @@ class Content(BaseModel):
if content[field] is None: if content[field] is None:
del content[field] del content[field]
return content 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)
...@@ -7,6 +7,7 @@ import copy ...@@ -7,6 +7,7 @@ import copy
from hypothesis import given from hypothesis import given
from swh.model.model import Content
from swh.model.hypothesis_strategies import objects from swh.model.hypothesis_strategies import objects
...@@ -24,3 +25,11 @@ def test_todict_inverse_fromdict(objtype_and_obj): ...@@ -24,3 +25,11 @@ def test_todict_inverse_fromdict(objtype_and_obj):
# Check the composition of from_dict and to_dict is the identity # 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() 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_
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment