Code review changes (removed safe_dict_descend)

This commit is contained in:
Roger Ostrander 2018-02-06 01:16:10 -05:00
parent 3fdde0f4ce
commit d8e1738f27
2 changed files with 28 additions and 57 deletions

View file

@ -134,31 +134,15 @@ def get_sd_hash(stream_info):
return None
if isinstance(stream_info, ClaimDict):
return stream_info.source_hash
path = ['claim', 'value', 'stream', 'source', 'source']
result = safe_dict_descend(stream_info, *path)
result = stream_info.get('claim', {}).\
get('value', {}).\
get('stream', {}).\
get('source', {}).\
get('source')
if not result:
log.warn("Unable to get sd_hash via path %s" % path)
log.warn("Unable to get sd_hash")
return result
def json_dumps_pretty(obj, **kwargs):
return json.dumps(obj, sort_keys=True, indent=2, separators=(',', ': '), **kwargs)
def safe_dict_descend(source, *path):
"""
For when you want to do something like
stream_info['claim']['value']['stream']['source']['source']"
but don't trust that every last one of those keys exists
"""
cur_source = source
for path_entry in path:
try:
if path_entry not in cur_source:
return None
except TypeError:
# This happens if we try to keep going along a path that isn't
# a dictionary (see e.g. test_safe_dict_descend_typeerror)
return None
cur_source = cur_source[path_entry]
return cur_source

View file

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from lbrynet.core import utils
from lbryschema.claim import ClaimDict
from twisted.trial import unittest
@ -33,45 +34,31 @@ class ObfuscationTest(unittest.TestCase):
self.assertEqual(plain, utils.deobfuscate(obf))
class SafeDictDescendTest(unittest.TestCase):
class SdHashTests(unittest.TestCase):
def test_safe_dict_descend_happy(self):
nested = {
'foo': {
'bar': {
'baz': 3
def test_none_in_none_out(self):
self.assertIsNone(utils.get_sd_hash(None))
def test_ordinary_dict(self):
claim = {
"claim": {
"value": {
"stream": {
"source": {
"source": "0123456789ABCDEF"
}
}
}
}
}
self.assertEqual(
utils.safe_dict_descend(nested, 'foo', 'bar', 'baz'),
3
)
self.assertEqual("0123456789ABCDEF", utils.get_sd_hash(claim))
def test_safe_dict_descend_typeerror(self):
nested = {
'foo': {
'bar': 7
def test_old_shape_fails(self):
claim = {
"stream": {
"source": {
"source": "0123456789ABCDEF"
}
}
}
self.assertIsNone(utils.safe_dict_descend(nested, 'foo', 'bar', 'baz'))
def test_safe_dict_descend_missing(self):
nested = {
'foo': {
'barn': 7
}
}
self.assertIsNone(utils.safe_dict_descend(nested, 'foo', 'bar', 'baz'))
def test_empty_dict_doesnt_explode(self):
nested = {}
self.assertIsNone(utils.safe_dict_descend(nested, 'foo', 'bar', 'baz'))
def test_identity(self):
nested = {
'foo': {
'bar': 7
}
}
self.assertIs(nested, utils.safe_dict_descend(nested))
self.assertIsNone(utils.get_sd_hash(claim))