assertpy2 2.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
assertpy2/helpers.py ADDED
@@ -0,0 +1,273 @@
1
+ # Copyright (c) 2015-2019, Activision Publishing, Inc.
2
+ # All rights reserved.
3
+ #
4
+ # Redistribution and use in source and binary forms, with or without modification,
5
+ # are permitted provided that the following conditions are met:
6
+ #
7
+ # 1. Redistributions of source code must retain the above copyright notice, this
8
+ # list of conditions and the following disclaimer.
9
+ #
10
+ # 2. Redistributions in binary form must reproduce the above copyright notice,
11
+ # this list of conditions and the following disclaimer in the documentation
12
+ # and/or other materials provided with the distribution.
13
+ #
14
+ # 3. Neither the name of the copyright holder nor the names of its contributors
15
+ # may be used to endorse or promote products derived from this software without
16
+ # specific prior written permission.
17
+ #
18
+ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22
+ # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+ # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
+
29
+ import collections
30
+ import datetime
31
+ import math
32
+ import numbers
33
+
34
+ __tracebackhide__ = True
35
+
36
+
37
+ class HelpersMixin:
38
+ """Helpers mixin. For internal use only."""
39
+
40
+ def _fmt_items(self, i):
41
+ """Helper to format the given items."""
42
+ if len(i) == 0:
43
+ return "<>"
44
+ elif len(i) == 1 and hasattr(i, "__getitem__"):
45
+ return "<%s>" % (i[0],)
46
+ else:
47
+ s = str(i)
48
+ if s[0] in "([":
49
+ s = s[1:]
50
+ if s[-1] in ")]":
51
+ s = s[:-1]
52
+ return "<%s>" % s
53
+
54
+ def _fmt_args_kwargs(self, *some_args, **some_kwargs):
55
+ """Helper to convert the given args and kwargs into a string."""
56
+ if some_args:
57
+ out_args = str(some_args).lstrip("(").rstrip(",)")
58
+ if some_kwargs:
59
+ out_kwargs = ", ".join(
60
+ [
61
+ str(i).lstrip("(").rstrip(")").replace(", ", ": ")
62
+ for i in [(k, some_kwargs[k]) for k in sorted(some_kwargs.keys())]
63
+ ]
64
+ )
65
+
66
+ if some_args and some_kwargs:
67
+ return out_args + ", " + out_kwargs
68
+ elif some_args:
69
+ return out_args
70
+ elif some_kwargs:
71
+ return out_kwargs
72
+ else:
73
+ return ""
74
+
75
+ def _validate_between_args(self, val_type, low, high):
76
+ """Helper to validate given range args."""
77
+ low_type = type(low)
78
+ high_type = type(high)
79
+
80
+ if val_type in self._NUMERIC_NON_COMPAREABLE:
81
+ raise TypeError("ordering is not defined for type <%s>" % val_type.__name__)
82
+
83
+ if val_type in self._NUMERIC_COMPAREABLE:
84
+ if low_type is not val_type:
85
+ raise TypeError("given low arg must be <%s>, but was <%s>" % (val_type.__name__, low_type.__name__))
86
+ if high_type is not val_type:
87
+ raise TypeError("given high arg must be <%s>, but was <%s>" % (val_type.__name__, low_type.__name__))
88
+ elif isinstance(self.val, numbers.Number):
89
+ if isinstance(low, numbers.Number) is False:
90
+ raise TypeError("given low arg must be numeric, but was <%s>" % low_type.__name__)
91
+ if isinstance(high, numbers.Number) is False:
92
+ raise TypeError("given high arg must be numeric, but was <%s>" % high_type.__name__)
93
+ else:
94
+ raise TypeError("ordering is not defined for type <%s>" % val_type.__name__)
95
+
96
+ if low > high:
97
+ raise ValueError("given low arg must be less than given high arg")
98
+
99
+ def _validate_close_to_args(self, val, other, tolerance):
100
+ """Helper for validate given arg and delta."""
101
+ if type(val) is complex or type(other) is complex or type(tolerance) is complex:
102
+ raise TypeError("ordering is not defined for complex numbers")
103
+
104
+ if isinstance(val, numbers.Number) is False and type(val) is not datetime.datetime:
105
+ raise TypeError("val is not numeric or datetime")
106
+
107
+ if type(val) is datetime.datetime:
108
+ if type(other) is not datetime.datetime:
109
+ raise TypeError("given arg must be datetime, but was <%s>" % type(other).__name__)
110
+ if type(tolerance) is not datetime.timedelta:
111
+ raise TypeError("given tolerance arg must be timedelta, but was <%s>" % type(tolerance).__name__)
112
+ else:
113
+ if isinstance(other, numbers.Number) is False:
114
+ raise TypeError("given arg must be numeric")
115
+ if isinstance(tolerance, numbers.Number) is False:
116
+ raise TypeError("given tolerance arg must be numeric")
117
+ if math.isnan(tolerance):
118
+ raise ValueError("given tolerance arg must not be NaN")
119
+ if tolerance < 0:
120
+ raise ValueError("given tolerance arg must be positive")
121
+
122
+ def _check_dict_like(
123
+ self, d, check_keys=True, check_values=True, check_getitem=True, name="val", return_as_bool=False
124
+ ):
125
+ """Helper to check if given val has various dict-like attributes."""
126
+ if not isinstance(d, collections.abc.Iterable):
127
+ if return_as_bool:
128
+ return False
129
+ else:
130
+ raise TypeError("%s <%s> is not dict-like: not iterable" % (name, type(d).__name__))
131
+ if check_keys and (not hasattr(d, "keys") or not callable(d.keys)):
132
+ if return_as_bool:
133
+ return False
134
+ else:
135
+ raise TypeError("%s <%s> is not dict-like: missing keys()" % (name, type(d).__name__))
136
+ if check_values and (not hasattr(d, "values") or not callable(d.values)):
137
+ if return_as_bool:
138
+ return False
139
+ else:
140
+ raise TypeError("%s <%s> is not dict-like: missing values()" % (name, type(d).__name__))
141
+ if check_getitem and not hasattr(d, "__getitem__"):
142
+ if return_as_bool:
143
+ return False
144
+ else:
145
+ raise TypeError("%s <%s> is not dict-like: missing [] accessor" % (name, type(d).__name__))
146
+ if return_as_bool:
147
+ return True
148
+
149
+ def _check_iterable(self, val, check_getitem=True, name="val"):
150
+ """Helper to check if given val is iterable with optional item access."""
151
+ if not isinstance(val, collections.abc.Iterable):
152
+ raise TypeError("%s <%s> is not iterable" % (name, type(val).__name__))
153
+ if check_getitem and not hasattr(val, "__getitem__"):
154
+ raise TypeError("%s <%s> does not have [] accessor" % (name, type(val).__name__))
155
+
156
+ def _dict_not_equal(self, val, other, ignore=None, include=None):
157
+ """Helper to compare dicts."""
158
+ if ignore or include:
159
+ ignores = self._dict_ignore(ignore)
160
+ includes = self._dict_include(include)
161
+
162
+ # guarantee include keys are in val
163
+ if include:
164
+ missing = []
165
+ for i in includes:
166
+ if i not in val:
167
+ missing.append(i)
168
+ if missing:
169
+ return self.error(
170
+ "Expected <%s> to include key%s %s, but did not include key%s %s."
171
+ % (
172
+ val,
173
+ "" if len(includes) == 1 else "s",
174
+ self._fmt_items(
175
+ [".".join([str(s) for s in i]) if type(i) is tuple else i for i in includes]
176
+ ),
177
+ "" if len(missing) == 1 else "s",
178
+ self._fmt_items(missing),
179
+ )
180
+ )
181
+
182
+ # calc val keys given ignores and includes
183
+ if ignore and include:
184
+ k1 = {k for k in val if k not in ignores and k in includes}
185
+ elif ignore:
186
+ k1 = {k for k in val if k not in ignores}
187
+ else: # include
188
+ k1 = {k for k in val if k in includes}
189
+
190
+ # calc other keys given ignores and includes
191
+ if ignore and include:
192
+ k2 = {k for k in other if k not in ignores and k in includes}
193
+ elif ignore:
194
+ k2 = {k for k in other if k not in ignores}
195
+ else: # include
196
+ k2 = {k for k in other if k in includes}
197
+
198
+ if k1 != k2:
199
+ # different set of keys, so not equal
200
+ return True
201
+ else:
202
+ for k in k1:
203
+ if self._check_dict_like(val[k], check_values=False, return_as_bool=True) and self._check_dict_like(
204
+ other[k], check_values=False, return_as_bool=True
205
+ ):
206
+ subdicts_not_equal = self._dict_not_equal(
207
+ val[k],
208
+ other[k],
209
+ ignore=[i[1:] for i in ignores if type(i) is tuple and i[0] == k] if ignore else None,
210
+ include=[i[1:] for i in self._dict_ignore(include) if type(i) is tuple and i[0] == k]
211
+ if include
212
+ else None,
213
+ )
214
+ if subdicts_not_equal:
215
+ # fast fail inside the loop since sub-dicts are not equal
216
+ return True
217
+ elif val[k] != other[k]:
218
+ # fast fail inside the loop since values are not equal
219
+ return True
220
+ return False
221
+ else:
222
+ return val != other
223
+
224
+ def _dict_ignore(self, ignore):
225
+ """Helper to make list for given ignore kwarg values."""
226
+ return [i[0] if type(i) is tuple and len(i) == 1 else i for i in (ignore if type(ignore) is list else [ignore])]
227
+
228
+ def _dict_include(self, include):
229
+ """Helper to make a list from given include kwarg values."""
230
+ return [i[0] if type(i) is tuple else i for i in (include if type(include) is list else [include])]
231
+
232
+ def _dict_err(self, val, other, ignore=None, include=None):
233
+ """Helper to construct error message for dict comparison."""
234
+
235
+ def _dict_repr(d, other):
236
+ parts = []
237
+ ellip = False
238
+ for k, v in sorted(d.items()):
239
+ if k not in other:
240
+ parts.append("%s: %s" % (repr(k), repr(v)))
241
+ elif v != other[k]:
242
+ val_repr = (
243
+ _dict_repr(v, other[k])
244
+ if self._check_dict_like(v, check_values=False, return_as_bool=True)
245
+ and self._check_dict_like(other[k], check_values=False, return_as_bool=True)
246
+ else repr(v)
247
+ )
248
+ parts.append("%s: %s" % (repr(k), val_repr))
249
+ else:
250
+ ellip = True
251
+ out = ", ".join(parts)
252
+ return "{%s%s}" % (".." if ellip and not parts else ".., " if ellip else "", out)
253
+
254
+ if ignore:
255
+ ignores = self._dict_ignore(ignore)
256
+ ignore_err = " ignoring keys %s" % self._fmt_items(
257
+ [".".join([str(s) for s in i]) if type(i) is tuple else i for i in ignores]
258
+ )
259
+ if include:
260
+ includes = self._dict_ignore(include)
261
+ include_err = " including keys %s" % self._fmt_items(
262
+ [".".join([str(s) for s in i]) if type(i) is tuple else i for i in includes]
263
+ )
264
+
265
+ return self.error(
266
+ "Expected <%s> to be equal to <%s>%s%s, but was not."
267
+ % (
268
+ _dict_repr(val, other),
269
+ _dict_repr(other, val),
270
+ ignore_err if ignore else "",
271
+ include_err if include else "",
272
+ )
273
+ )