question 243 Testing & Code Quality · easy
Explain why two records differ
When a test compares a whole record, assert expected == actual only says *False*. A good failure message says exactly what differs. Write diff_records(expected, actual) that returns one line per difference between two dictionaries, the way unittest explains a failed comparison.
Function
diff_records(expected, actual)Returnsa list of texts,
[] when the records are equalOrderfirst walk
expected in its key order: a key actual lacks gives missing key 'k'; a different value gives 'k': expected <value>, got <value>. Then walk actual: a key expected lacks gives unexpected key 'k'Valuesshown with
repr, so text keeps its quotes: 'qty': expected 12, got '12'Examples
calldiff_records({'order_id': 'O100282', 'status': 'paid', 'total': 35.84}, {'order_id': 'O100282', 'total': 35.8, 'state': 'paid'})returns["missing key 'status'", "'total': expected 35.84, got 35.8", "unexpected key 'state'"]
calldiff_records({'sku': 'SPO-11681', 'qty': 2}, {'sku': 'SPO-11681', 'qty': 2})returns[]
calldiff_records({'customer_id': 'C00077'}, {'customer_id': 'C00078'})returns["'customer_id': expected 'C00077', got 'C00078'"]