| 1 |
|
| 2 |
|
| 3 |
> |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
from __future__ import unicode_literals |
| 18 |
|
| 19 |
import os |
| 20 |
|
| 21 |
try: |
| •22 |
from unittest.mock import _CallList |
| 23 |
except ImportError: |
| 24 |
from mock.mock import _CallList |
| 25 |
|
| 26 |
import inspect |
| 27 |
from six import ( |
| 28 |
text_type, integer_types, string_types, binary_type, |
| 29 |
get_function_code |
| 30 |
) |
| 31 |
|
| 32 |
from sure.terminal import red, green, yellow |
| 33 |
from sure.compat import safe_repr, OrderedDict |
| 34 |
|
| 35 |
|
| 36 |
class Anything(object): |
| 37 |
"""Represents any possible value. Its existence is solely for |
| 38 |
idiomatic purposes. |
| 39 |
""" |
| 40 |
def __eq__(self, _): |
| 41 |
return True |
| 42 |
|
| 43 |
anything = Anything() |
| 44 |
|
| 45 |
|
| 46 |
class DeepExplanation(text_type): |
| 47 |
def get_header(self, X, Y, suffix): |
| 48 |
params = (safe_repr(X), safe_repr(Y), text_type(suffix)) |
| 49 |
header = "given\nX = {0}\n and\nY = {1}\n{2}".format(*params) |
| 50 |
|
| 51 |
return yellow(header).strip() |
| 52 |
|
| 53 |
def get_assertion(self, X, Y): |
| 54 |
return AssertionError(self.get_header(X, Y, self)) |
| 55 |
|
| 56 |
def as_assertion(self, X, Y): |
| 57 |
raise self.get_assertion(X, Y) |
| 58 |
|
| 59 |
|
| 60 |
class DeepComparison(object): |
| 61 |
def __init__(self, X, Y, epsilon=None, parent=None): |
| 62 |
self.complex_cmp_funcs = { |
| 63 |
float: self.compare_floats, |
| 64 |
dict: self.compare_dicts, |
| 65 |
list: self.compare_iterables, |
| 66 |
tuple: self.compare_iterables, |
| 67 |
OrderedDict: self.compare_ordereddict |
| 68 |
} |
| 69 |
|
| 70 |
self.operands = X, Y |
| 71 |
self.epsilon = epsilon |
| 72 |
self.parent = parent |
| 73 |
self._context = None |
| 74 |
|
| 75 |
def is_simple(self, obj): |
| 76 |
return isinstance(obj, ( |
| 77 |
string_types, integer_types, binary_type, Anything |
| 78 |
)) |
| 79 |
|
| 80 |
def is_complex(self, obj): |
| 81 |
return isinstance(obj, tuple(self.complex_cmp_funcs.keys())) |
| 82 |
|
| 83 |
def compare_complex_stuff(self, X, Y): |
| 84 |
return self.complex_cmp_funcs.get(type(X), self.compare_generic)(X, Y) |
| 85 |
|
| 86 |
def compare_generic(self, X, Y, msg_format='X{0} != Y{1}'): |
| 87 |
c = self.get_context() |
| 88 |
if X == Y: |
| 89 |
return True |
| 90 |
else: |
| 91 |
m = msg_format.format(red(c.current_X_keys), green(c.current_Y_keys)) |
| 92 |
return DeepExplanation(m) |
| 93 |
|
| 94 |
def compare_floats(self, X, Y): |
| 95 |
c = self.get_context() |
| 96 |
if self.epsilon is None: |
| 97 |
return self.compare_generic(X, Y) |
| 98 |
|
| 99 |
if abs(X - Y) <= self.epsilon: |
| 100 |
return True |
| 101 |
else: |
| 102 |
m = 'X{0}±{1} != Y{2}±{3}'.format( |
| 103 |
red(c.current_X_keys), self.epsilon, green(c.current_Y_keys), self.epsilon) |
| 104 |
return DeepExplanation(m) |
| 105 |
|
| 106 |
def compare_dicts(self, X, Y): |
| 107 |
c = self.get_context() |
| 108 |
|
| 109 |
x_keys = list(X.keys()) |
| 110 |
y_keys = list(Y.keys()) |
| 111 |
|
| 112 |
diff_x = list(set(x_keys).difference(set(y_keys))) |
| 113 |
diff_y = list(set(y_keys).difference(set(x_keys))) |
| 114 |
if diff_x: |
| 115 |
msg = "X{0} has the key {1!r} whereas Y{2} does not".format( |
| 116 |
red(c.current_X_keys), |
| 117 |
safe_repr(diff_x[0]), |
| 118 |
green(c.current_Y_keys)) |
| 119 |
return DeepExplanation(msg) |
| 120 |
|
| 121 |
elif diff_y: |
| 122 |
msg = "X{0} does not have the key {1!r} whereas Y{2} has it".format( |
| 123 |
red(c.current_X_keys), |
| 124 |
safe_repr(diff_y[0]), |
| 125 |
green(c.current_Y_keys)) |
| 126 |
return DeepExplanation(msg) |
| 127 |
|
| 128 |
elif X == Y: |
| 129 |
return True |
| 130 |
|
| 131 |
else: |
| 132 |
for key_X in x_keys: |
| 133 |
self.key_X = key_X |
| 134 |
self.key_Y = key_X |
| 135 |
value_X = X[key_X] |
| 136 |
value_Y = Y[key_X] |
| 137 |
child = DeepComparison( |
| 138 |
value_X, |
| 139 |
value_Y, |
| 140 |
epsilon=self.epsilon, |
| 141 |
parent=self, |
| 142 |
).compare() |
| 143 |
if isinstance(child, DeepExplanation): |
| 144 |
return child |
| 145 |
|
| 146 |
def compare_ordereddict(self, X, Y): |
| 147 |
"""Compares two instances of an OrderedDict.""" |
| 148 |
|
| 149 |
|
| 150 |
child = self.compare_dicts(X, Y) |
| 151 |
if isinstance(child, DeepExplanation): |
| 152 |
return child |
| 153 |
|
| 154 |
|
| 155 |
for i, j in zip(X.items(), Y.items()): |
| 156 |
if i[0] != j[0]: |
| 157 |
c = self.get_context() |
| 158 |
msg = "X{0} and Y{1} are in a different order".format( |
| 159 |
red(c.current_X_keys), green(c.current_Y_keys) |
| 160 |
) |
| 161 |
return DeepExplanation(msg) |
| 162 |
return True |
| 163 |
|
| 164 |
def get_context(self): |
| 165 |
if self._context: |
| 166 |
return self._context |
| 167 |
|
| 168 |
X_keys = [] |
| 169 |
Y_keys = [] |
| 170 |
|
| 171 |
comp = self |
| 172 |
while comp.parent: |
| 173 |
X_keys.insert(0, comp.parent.key_X) |
| 174 |
Y_keys.insert(0, comp.parent.key_Y) |
| 175 |
comp = comp.parent |
| 176 |
|
| 177 |
def get_keys(i): |
| 178 |
if not i: |
| 179 |
return '' |
| 180 |
|
| 181 |
return '[{0}]'.format(']['.join(map(safe_repr, i))) |
| 182 |
|
| 183 |
class ComparisonContext: |
| 184 |
current_X_keys = get_keys(X_keys) |
| 185 |
current_Y_keys = get_keys(Y_keys) |
| 186 |
parent = comp |
| 187 |
|
| 188 |
self._context = ComparisonContext() |
| 189 |
return self._context |
| 190 |
|
| 191 |
def compare_iterables(self, X, Y): |
| 192 |
len_X, len_Y = map(len, (X, Y)) |
| 193 |
if len_X > len_Y: |
| 194 |
msg = "X has {0} items whereas Y has only {1}".format(len_X, len_Y) |
| 195 |
return DeepExplanation(msg) |
| 196 |
elif len_X < len_Y: |
| 197 |
msg = "Y has {0} items whereas X has only {1}".format(len_Y, len_X) |
| 198 |
return DeepExplanation(msg) |
| 199 |
elif X == Y: |
| 200 |
return True |
| 201 |
else: |
| 202 |
for i, (value_X, value_Y) in enumerate(zip(X, Y)): |
| 203 |
self.key_X = self.key_Y = i |
| 204 |
child = DeepComparison( |
| 205 |
value_X, |
| 206 |
value_Y, |
| 207 |
epsilon=self.epsilon, |
| 208 |
parent=self, |
| 209 |
).compare() |
| 210 |
if isinstance(child, DeepExplanation): |
| 211 |
return child |
| 212 |
|
| 213 |
def compare(self): |
| 214 |
X, Y = self.operands |
| 215 |
|
| 216 |
if isinstance(X, _CallList): |
| 217 |
X = list(X) |
| 218 |
|
| 219 |
if isinstance(Y, _CallList): |
| 220 |
X = list(Y) |
| 221 |
|
| 222 |
c = self.get_context() |
| 223 |
if self.is_complex(X) and type(X) is type(Y): |
| 224 |
return self.compare_complex_stuff(X, Y) |
| 225 |
|
| 226 |
def safe_format_repr(string): |
| 227 |
"Escape '{' and '}' in string for use with str.format()" |
| 228 |
if not isinstance(string, (string_types, binary_type)): |
| 229 |
return string |
| 230 |
|
| 231 |
orig_str_type = type(string) |
| 232 |
if isinstance(string, binary_type): |
| 233 |
safe_repr = string.replace(b'{', b'{{').replace(b'}', b'}}') |
| 234 |
else: |
| 235 |
safe_repr = string.replace('{', '{{').replace('}', '}}') |
| 236 |
|
| 237 |
|
| 238 |
return orig_str_type(safe_repr) |
| 239 |
|
| 240 |
|
| 241 |
safe_X, safe_Y = safe_format_repr(X), safe_format_repr(Y) |
| 242 |
|
| 243 |
|
| 244 |
kwargs = {} |
| 245 |
if self.is_simple(X) and self.is_simple(Y): |
| 246 |
kwargs['msg_format'] = 'X{{0}} is {0!r} whereas Y{{1}} is {1!r}'.format(safe_X, safe_Y) |
| 247 |
elif type(X) is not type(Y): |
| 248 |
kwargs['msg_format'] = 'X{{0}} is a {0} and Y{{1}} is a {1} instead'.format( |
| 249 |
type(X).__name__, type(Y).__name__) |
| 250 |
exp = self.compare_generic(X, Y, **kwargs) |
| 251 |
|
| 252 |
if isinstance(exp, DeepExplanation): |
| 253 |
original_X, original_Y = c.parent.operands |
| 254 |
raise exp.as_assertion(original_X, original_Y) |
| 255 |
|
| 256 |
return exp |
| 257 |
|
| 258 |
def explanation(self): |
| 259 |
return self._explanation |
| 260 |
|
| 261 |
|
| 262 |
def _get_file_name(func): |
| 263 |
try: |
| 264 |
name = inspect.getfile(func) |
| 265 |
except AttributeError: |
| 266 |
name = get_function_code(func).co_filename |
| 267 |
|
| 268 |
return os.path.abspath(name) |
| 269 |
|
| 270 |
|
| 271 |
def _get_line_number(func): |
| 272 |
try: |
| 273 |
return inspect.getlineno(func) |
| 274 |
except AttributeError: |
| 275 |
return get_function_code(func).co_firstlineno |
| 276 |
|
| 277 |
|
| 278 |
def itemize_length(items): |
| 279 |
length = len(items) |
| 280 |
return '{0} item{1}'.format(length, length > 1 and "s" or "") |