simplified claims comparison logic; refactored unit tests

This commit is contained in:
Sergey Rozhnov 2018-05-17 13:36:32 +04:00 committed by jleute
parent c7ba82dc07
commit b770b2de6a
3 changed files with 70 additions and 68 deletions

View file

@ -1,36 +1,10 @@
_comparison_order = ['height', 'name', 'claim_id'] # TODO outpoint
def arrange_results(claims):
for claim in claims:
results = claim['result']
sorted_results = sorted(results, cmp=_compare_results)
sorted_results = sorted(results, key=lambda d: (d['height'], d['name'], d['claim_id'], _outpoint(d)))
claim['result'] = sorted_results
return claims
def _compare_results(left, right):
"""
:type left: dict
:type right: dict
"""
result = 0
for attribute in _comparison_order:
left_value = left[attribute]
right_value = right[attribute]
sub_result = _cmp(left_value, right_value)
if sub_result is not 0:
result = sub_result
break
return result
def _cmp(left, right):
if left == right:
return 0
elif left < right:
return -1
else:
return 1
def _outpoint(claim):
return '{}:{}'.format(claim['txid'], claim['nout'])

View file

@ -0,0 +1,53 @@
{
"cases": [
{
"description": "sort by claim_id",
"results": [
{
"height": 1,
"name": "res",
"claim_id": "ccc",
"nout": 0,
"txid": "fdsafa"
},
{
"height": 1,
"name": "res",
"claim_id": "aaa",
"nout": 0,
"txid": "w5tv8uorgt"
},
{
"height": 1,
"name": "res",
"claim_id": "bbb",
"nout": 0,
"txid": "aecfaewcfa"
}
],
"expected": [
{
"height": 1,
"name": "res",
"claim_id": "aaa",
"nout": 0,
"txid": "w5tv8uorgt"
},
{
"height": 1,
"name": "res",
"claim_id": "bbb",
"nout": 0,
"txid": "aecfaewcfa"
},
{
"height": 1,
"name": "res",
"claim_id": "ccc",
"nout": 0,
"txid": "fdsafa"
}
]
}
]
}

View file

@ -1,51 +1,26 @@
import json
import unittest
from lbrynet.daemon.claims_comparator import arrange_results
class ClaimsComparatorTest(unittest.TestCase):
def setUp(self):
with open('claims_comparator_cases.json') as f:
document = json.load(f)
self.cases = document['cases']
def test_arrange_results(self):
results = [
{
'height': 1,
'name': 'res',
'claim_id': 'ccc'
},
{
'height': 1,
'name': 'res',
'claim_id': 'aaa'
},
{
'height': 1,
'name': 'res',
'claim_id': 'bbb'
}
]
data = {'result': results}
for case in self.cases:
results = case['results']
data = {'result': results}
expected = case['expected']
expected = [
{
'height': 1,
'name': 'res',
'claim_id': 'aaa'
},
{
'height': 1,
'name': 'res',
'claim_id': 'bbb'
},
{
'height': 1,
'name': 'res',
'claim_id': 'ccc'
}
]
claims = arrange_results([data])
claim = claims[0]
actual = claim['result']
claims = arrange_results([data])
claim = claims[0]
actual = claim['result']
self.assertEqual(expected, actual)
self.assertEqual(expected, actual, case['description'])
if __name__ == '__main__':