Best Python code snippet using Testify_python
core.py
Source:core.py
...166 def _subtract_features(self, user_id, features):167 try:168 self.users_history[user_id]['count'] -= 1169 for feature, value in features.items():170 self._dict_subtract(self.users_history[user_id],171 feature, value)172 if len(self.users_history[user_id]) == 1:173 del self.users_history[user_id]174 self._dict_subtract(self.total_history,175 feature, value)176 except KeyError:177 raise AssertionError('Inconsistancy in history.')178 try:179 if self.users_history[user_id]['count'] <= 0:180 raise AssertionError('Inconsistancy in history.')181 except KeyError:182 pass183 def _dict_subtract(self, dictionary, feature, value):184 try:185 dictionary[feature][value] -= 1186 if dictionary[feature][value] == 0:187 del dictionary[feature][value]188 if len(dictionary[feature]) == 0:189 del dictionary[feature]190 except KeyError:191 raise AssertionError('Inconsistancy in dictionary.')192 def _filter_features(self, features):193 filtered_values = {}194 for key in CONF.rba.features:195 filtered_values[key] = features.get(196 key, '')197 return filtered_values...
assertions.py
Source:assertions.py
...33 val_diff = list_subtractor(val1, val2)34 else:35 val_diff = val136 return val_diff37def _dict_subtract(dict1, dict2):38 """39 Return key,value pairs from dict1 that are not in dict240 Returns:41 A new dict 'res_dict' with the following properties:42 For all (key, val) pairs where key appears in dict2:43 if dict1[val] == dict2[val] then res_dict[val] is not defined44 else res_dict[val] == dict1[val]45 If vals are themselves dictionaries the algorim is applied recursively.46 Example:47 _dict_subtract({48 1: 'one',49 2: 'two',50 3: {'a': 'A', 'b': 'B'},51 4: {'c': 'C', 'd': 'D'}52 },53 {54 2: 'two',55 3: {'a': 'A', 'b': 'B'},56 4: {'d': 'D'},57 5: {'e': 'E'}58 }) => {1: 'one', 4: {'c': 'C'}}59 """60 # make a result we can edit61 result = dict(dict1)62 # find the common keys -- i.e., the ones we might need to subtract63 common_keys = set(dict1.keys()) & set(dict2.keys())64 for key in common_keys:65 val1, val2 = dict1[key], dict2[key]66 if val1 == val2:67 # values are the same: subtract68 del result[key]69 else:70 # values are different: set the output key to the different between the values71 result[key] = _val_subtract(val1, val2, _dict_subtract, _list_subtract)72 return result73def _list_subtract(list1, list2):74 """75 Returns the difference between list1 and list2.76 _list_subtract([1,2,3], [3,2,1]) == [1,3]77 If any items in the list are container types, the method recursively calls78 itself or _dict_subtract() to subtract the child79 containers.80 """81 # call val_subtract on all items that are not the same82 res_list = [_val_subtract(val1, val2, _dict_subtract, _list_subtract)83 for val1, val2 in zip(list1, list2) if val1 != val2]84 # now append items that come after any item in list185 res_list += list1[len(list2):]86 # return a tuple of list1 is a tuple87 if isinstance(list1, tuple):88 return tuple(res_list)89 else:90 return res_list91def assert_raises(*args, **kwargs):92 """Assert an exception is raised as a context manager or by passing in a93 callable and its arguments.94 As a context manager:95 >>> with assert_raises(Exception):96 ... raise Exception97 Pass in a callable:98 >>> def raise_exception(arg, kwarg=None):99 ... raise Exception100 >>> assert_raises(Exception, raise_exception, 1, kwarg=234)101 """102 if (len(args) == 1) and not kwargs:103 return _assert_raises_context_manager(args[0])104 else:105 return _assert_raises(*args, **kwargs)106def assert_raises_and_contains(expected_exception_class, strings, callable_obj, *args, **kwargs):107 """Assert an exception is raised by passing in a callable and its108 arguments and that the string representation of the exception109 contains the case-insensetive list of passed in strings.110 Args111 strings -- can be a string or an iterable of strings112 """113 try:114 callable_obj(*args, **kwargs)115 except:116 _, e, _ = sys.exc_info()117 assert_isinstance(e, expected_exception_class)118 message = str(e).lower()119 if isinstance(strings, STRING_TYPE):120 strings = [strings]121 for string in strings:122 assert_in(string.lower(), message)123 else:124 assert_not_reached("No exception was raised (expected %s)" % expected_exception_class)125@contextlib.contextmanager126def _assert_raises_context_manager(exception_class):127 try:128 yield129 except:130 _, ex, _ = sys.exc_info()131 assert_isinstance(ex, exception_class)132 else:133 assert_not_reached("No exception was raised (expected %r)" %134 exception_class)135def _assert_raises(exception_class, callable, *args, **kwargs):136 with _assert_raises_context_manager(exception_class):137 callable(*args, **kwargs)138def _diff_message(lhs, rhs):139 """If `lhs` and `rhs` are strings, return the a formatted message140 describing their differences. If they're not strings, describe the141 differences in their `repr()`s.142 NOTE: Only works well for strings not containing newlines.143 """144 lhs = repr(lhs) if not isinstance(lhs, STRING_TYPE) else lhs145 rhs = repr(rhs) if not isinstance(rhs, STRING_TYPE) else rhs146 return 'Diff:\nl: %s\nr: %s' % utils.highlight(lhs, rhs)147def assert_equal(lval, rval, message=None):148 """Assert that lval and rval are equal."""149 if message:150 assert lval == rval, message151 else:152 assert lval == rval, \153 "assertion failed: l == r\nl: %r\nr: %r\n\n%s" % \154 (lval, rval, _diff_message(lval, rval))155assert_equals = assert_equal156def assert_almost_equal(lval, rval, digits, message=None):157 """Assert that lval and rval, when rounded to the specified number of digits, are the same."""158 real_message = message or "%r !~= %r" % (lval, rval)159 assert round(lval, digits) == round(rval, digits), real_message160def assert_within_tolerance(lval, rval, tolerance, message=None):161 """Assert that the difference between the two values, as a fraction of the left value, is smaller than the tolerance specified.162 That is, abs(float(lval) - float(rval)) / float(lval) < tolerance"""163 real_message = message or "%r !~= %r" % (lval, rval)164 assert abs(float(lval) - float(rval)) / float(lval) < tolerance, real_message165def assert_not_equal(lval, rval, message=None):166 """Assert that lval and rval are unequal to each other."""167 assert lval != rval, message or 'assertion failed: %r != %r' % (lval, rval)168def assert_lt(lval, rval, message=None):169 """Assert that lval is less than rval."""170 assert lval < rval, message or 'assertion failed: %r < %r' % (lval, rval)171def assert_lte(lval, rval, message=None):172 """Assert that lval is less than or equal to rval"""173 assert lval <= rval, message or 'assertion failed: %r <= %r' % (lval, rval)174def assert_gt(lval, rval, message=None):175 """Assert that lval is greater than rval."""176 assert lval > rval, message or 'assertion failed: %r > %r' % (lval, rval)177def assert_gte(lval, rval, message=None):178 """Assert that lval is greater than or equal to rval"""179 assert lval >= rval, message or 'assertion failed: %r >= %r' % (lval, rval)180def assert_in_range(val, start, end, message=None, inclusive=False):181 """Assert that val is greater than start and less than end. If inclusive is true, val may be equal to start or end."""182 if inclusive:183 real_message = message or "! %s <= %r <= %r" % (start, val, end)184 assert start <= val <= end, real_message185 else:186 real_message = message or "! %s < %r < %r" % (start, val, end)187 assert start < val < end, real_message188def assert_between(a, b, c):189 """Assert that b is between a and c, inclusive."""190 assert_in_range(b, a, c, inclusive=True)191def assert_in(item, sequence, message=None):192 """Assert that the item is in the sequence."""193 if not message:194 message = (195 "assertion failed: expected %(item)r in %(sequence)r" % locals()196 )197 assert item in sequence, message198def assert_not_in(item, sequence, message=None):199 """Assert that the item is not in the sequence."""200 assert item not in sequence, (201 "assertion failed: expected %(item)r not in %(sequence)r" % locals()202 )203def assert_all_in(left, right):204 """Assert that everything in `left` is also in `right`205 Note: This is different than `assert_subset()` because python sets use206 `__hash__()` for comparision whereas `in` uses `__eq__()`.207 """208 unmatching = []209 for item in left:210 if item not in right:211 unmatching.append(item)212 if unmatching:213 raise AssertionError(214 "%(unmatching)r missing from %(right)r" % locals()215 )216def assert_starts_with(val, prefix, message=None):217 """Assert that val starts with prefix.218 Applies to any iterable, not just strings.219 """220 try:221 iter(val)222 except:223 raise TypeError("%(val)r is not iterable" % locals())224 try:225 iter(prefix)226 except:227 raise TypeError("%(prefix)r is not iterable" % locals())228 msg = message or "%(val)r does not start with %(prefix)r" % locals()229 for i, (l, r) in enumerate(zip(val, prefix)):230 assert_equal(l, r, msg)231 msg = (232 message or233 "%(val)r shorter than %(prefix)r, so can't start with it" % locals()234 )235 length = len(list(prefix))236 assert_equal(length, i + 1, msg)237def assert_not_reached(message=None):238 """Raise an AssertionError with a message."""239 if message:240 assert False, message241 else:242 assert False, 'egads! this line ought not to have been reached'243def assert_rows_equal(rows1, rows2):244 """Check that two sequences contain the same lists of dictionaries"""245 def norm_row(row):246 if isinstance(row, dict):247 return tuple((k, row[k]) for k in sorted(row))248 else:249 return tuple(sorted(row))250 def norm_rows(rows):251 return tuple(sorted(norm_row(row) for row in rows))252 assert_equal(norm_rows(rows1), norm_rows(rows2))253def assert_length(sequence, expected, message=None):254 """Assert a sequence or iterable has an expected length."""255 length = len(list(sequence))256 assert length == expected, (message or257 "%(sequence)s has length %(length)s expected %(expected)s" % locals()258 )259def assert_is(left, right, message=None):260 """Assert that left and right are the same object"""261 assert left is right, (262 message or "expected %(left)r is %(right)r" % locals()263 )264def assert_is_not(left, right, message=None):265 """Assert that left and right are not the same object"""266 assert left is not right, (267 message or "expected %(left)r is not %(right)r" % locals()268 )269def assert_all_match_regex(pattern, values, message=None):270 """Assert that all values in an iterable match a regex pattern.271 Args:272 pattern -- a regex.273 values -- an iterable of values to test.274 Raises AssertionError if any value does not match.275 """276 for value in values:277 if not message:278 message = "expected %(value)r to match %(pattern)r" % locals()279 assert re.match(pattern, value), message280def assert_match_regex(pattern, value, *args, **kwargs):281 """Assert that a single value matches a regex pattern."""282 assert_all_match_regex(pattern, [value], *args, **kwargs)283assert_matches_regex = assert_match_regex284def assert_any_match_regex(pattern, values, message=None):285 """Assert that at least one value in an iterable matches a regex pattern.286 Args:287 pattern -- a regex.288 values -- an iterable of values to test.289 Raises AssertionError if all values don't match.290 """291 for value in values:292 if re.match(pattern, value) is not None:293 return294 if not message:295 message = (296 "expected at least one %(values)r to match %(pattern)r" % locals()297 )298 raise AssertionError(message)299def assert_all_not_match_regex(pattern, values, message=None):300 """Assert that all values don't match a regex pattern.301 Args:302 pattern -- a regex.303 values -- an iterable of values to test.304 Raises AssertionError if any values matches.305 """306 for value in values:307 if not message:308 message = "expected %(value)r to not match %(pattern)r" % locals()309 assert not re.match(pattern, value), message310assert_none_match_regex = assert_all_not_match_regex311def assert_sets_equal(left, right, message=None):312 """Assert that two sets are equal."""313 if left != right:314 extra_left = left - right315 extra_right = right - left316 if not message:317 message = (318 "expected %(left)r == %(right)r "319 "[left has:%(extra_left)r, "320 "right has:%(extra_right)r]"321 ) % locals()322 raise AssertionError(message)323def assert_dicts_equal(left, right, ignore_keys=None, message=None):324 """Assert that two dictionarys are equal (optionally ignoring certain keys)."""325 if ignore_keys is not None:326 left = dict((k, left[k]) for k in left if k not in ignore_keys)327 right = dict((k, right[k]) for k in right if k not in ignore_keys)328 if left == right:329 return330 extra_left = _dict_subtract(left, right)331 extra_right = _dict_subtract(right, left)332 if not message:333 message = (334 "expected %(left)r == %(right)r "335 "[left has:%(extra_left)r, "336 "right has:%(extra_right)r]"337 ) % locals()338 raise AssertionError(message)339def assert_dict_subset(left, right, message=None):340 """Assert that a dictionary is a strict subset of another dictionary.341 Checks both keys and values.342 """343 difference_dict = _dict_subtract(left, right)344 if not difference_dict:345 return346 extra_left = difference_dict347 small_right = dict((k, right[k]) for k in right if k in list(left.keys()))348 extra_right = _dict_subtract(small_right, left)349 if not message:350 message = (351 "[subset has:%(extra_left)r, superset has:%(extra_right)s]"352 ) % locals()353 raise AssertionError(message)354def assert_subset(left, right, message=None):355 """Assert that the left set is a subset of the right set."""356 set_left = set(left)357 set_right = set(right)358 if not (set_left <= set_right):359 extra = set_left - set_right360 if not message:361 message = (362 "expected %(set_left)r <= %(set_right)r [left has:%(extra)r]"...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!