| 1 |
import re |
| 2 |
import six |
| 3 |
|
| 4 |
known_bad = set(( |
| 5 |
'addressed', |
| 6 |
'app_id', |
| 7 |
'data', |
| 8 |
'eta', |
| 9 |
'radio', |
| 10 |
'regional', |
| 11 |
'reserved', |
| 12 |
'structured', |
| 13 |
)) |
| 14 |
|
| 15 |
precision = 5.0 |
| 16 |
|
| 17 |
def TextToNumber(text): |
| 18 |
try: |
| 19 |
return float(text) |
| 20 |
except (TypeError, ValueError): |
| 21 |
return text |
| 22 |
|
| 23 |
|
| 24 |
def IsNumber(value): |
| 25 |
if isinstance(value, float): |
| 26 |
return True |
| 27 |
if isinstance(value, six.integer_types): |
| 28 |
return True |
| 29 |
return False |
| 30 |
|
| 31 |
|
| 32 |
def DictDiff(a, b): |
| 33 |
"""Compares two dictionaries. Intended to be used in a test to |
| 34 |
compare the actual return value from some function with a |
| 35 |
known-good value. |
| 36 |
|
| 37 |
Returns a dictionary with the following keys: |
| 38 |
|
| 39 |
removed: Dict of all key/value pairs in a but not in b. |
| 40 |
|
| 41 |
added: Dict of all key/value pairs in b but not in a. |
| 42 |
|
| 43 |
changed: Dict with all keys with different values in a and b. |
| 44 |
Values are pairs of the values from a and b. |
| 45 |
""" |
| 46 |
|
| 47 |
def Compare(x, y): |
| 48 |
if x == y: |
| 49 |
return True |
| 50 |
x = TextToNumber(x) |
| 51 |
y = TextToNumber(y) |
| 52 |
if isinstance(x, six.string_types) and isinstance(y, six.string_types): |
| 53 |
|
| 54 |
new_x = re.sub(r'[^a-z]', r'', six.text_type(x).lower()) |
| 55 |
new_y = re.sub(r'[^a-z]', r'', six.text_type(y).lower()) |
| 56 |
if new_x == new_y: |
| 57 |
return True |
| 58 |
if IsNumber(x) and IsNumber(y): |
| 59 |
if abs(float(x) - float(y)) < precision: |
| 60 |
return True |
| 61 |
return False |
| 62 |
|
| 63 |
|
| 64 |
return { |
| 65 |
'removed': {key: a[key] for key in a |
| 66 |
if key not in b and key not in known_bad}, |
| 67 |
'changed': {key: (a[key], b[key]) for key in a |
| 68 |
if key in b |
| 69 |
and key not in known_bad |
| 70 |
and not Compare(a[key], b[key])}, |
| 71 |
'added': {key: b[key] for key in b |
| 72 |
if key not in a and key not in known_bad} |
| 73 |
} |