Last active
June 18, 2018 14:26
-
-
Save lukaszb/d997d809384c7474918e354218712eb3 to your computer and use it in GitHub Desktop.
pytest dicts comparison
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Run it with: | |
pytest dicts.py --tb=short | |
""" | |
import dictdiffer | |
import json | |
import pytest | |
@pytest.fixture | |
def dicts_are_same(pytestconfig): | |
verbose = pytestconfig.getoption('verbose') | |
def check_objects(d1, d2, verbose=1): | |
if d1 == d2: | |
return True | |
else: | |
diff_chunks = dictdiffer.diff(d1, d2) | |
diff = '\n'.join([ | |
' => %s: at key %r values are different | Left: %r | Right: %r' % ( | |
action.upper(), path, values[0], values[1] | |
) | |
for action, path, values in diff_chunks | |
]) | |
sep = '\n' + ('=' * 80) + '\n' | |
msg_lines = [ | |
'Provided items are NOT the same.', | |
'Left:', | |
as_json(d1), | |
sep, | |
'Right:', | |
as_json(d2), | |
sep, | |
'Diff:', | |
diff, | |
] | |
pytest.fail('\n\n'.join(msg_lines)) | |
def as_json(d): | |
return json.dumps(d, sort_keys=True, indent=2) | |
return check_objects | |
def test_compare_dicts(dicts_are_same): | |
result = { | |
"name": { | |
"first": "juvena", | |
"last": "rodrigues", | |
"title": "miss" | |
}, | |
"nat": "BR", | |
"phone": "(75) 9072-2545", | |
"email": "[email protected]", | |
"gender": "female", | |
"location": { | |
"city": "arapiraca", | |
"postcode": 27146, | |
"state": "minas gerais", | |
"street": "4903 rua bela vista ", | |
} | |
} | |
expected_data = { | |
"name": { | |
"first": "Juvena", | |
"last": "Rodrigues", | |
"title": "miss" | |
}, | |
"nat": "BR", | |
"phone": "(75) 9072-2545", | |
"email": "[email protected]", | |
"gender": "female", | |
"location": { | |
"city": "Arapiraca", | |
"postcode": 21746, | |
"state": "minas gerais", | |
"street": "4903 rua bela vista ", | |
} | |
} | |
assert dicts_are_same(result, expected_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment