How to use _to_characters method in Testify

Best Python code snippet using Testify_python

assertions.py

Source:assertions.py Github

copy

Full Screen

...192 describing their differences. If they're not strings, describe the193 differences in their `repr()`s.194 NOTE: Only works well for strings not containing newlines.195 """196 lhs = _to_characters(lhs)197 rhs = _to_characters(rhs)198 message = u'Diff:\nl: %s\nr: %s' % stringdiffer.highlight(lhs, rhs)199 # Python2 exceptions require bytes.200 if six.PY2:201 return message.encode('UTF-8')202 else:203 return message204def assert_equal(lval, rval, message=None):205 """Assert that lval and rval are equal."""206 if message:207 assert lval == rval, message208 else:209 assert lval == rval, \210 "assertion failed: l == r\nl: %r\nr: %r\n\n%s" % \211 (lval, rval, _diff_message(lval, rval))212assert_equals = assert_equal213def _get_msg(args, kwargs, suggestion):214 if args:215 raise TypeError(216 '`message` is kwargs only. Perhaps you meant `{}`?'.format(217 suggestion,218 ),219 )220 message = kwargs.pop('message', None)221 if kwargs:222 raise TypeError('Unexpected kwargs {!r}'.format(kwargs))223 return message224def assert_truthy(lval, *args, **kwargs):225 """Assert that lval evaluates truthy, not identity."""226 message = _get_msg(args, kwargs, 'assert_equal')227 if message:228 assert lval, message229 else:230 assert lval, "assertion failed: l == r\nl: %r\nr: %r\n\n%s" % (231 lval, True, _diff_message(lval, True),232 )233def assert_falsey(lval, *args, **kwargs):234 """Assert that lval evaluates falsey, not identity."""235 message = _get_msg(args, kwargs, 'assert_not_equal')236 if message:237 assert not lval, message238 else:239 assert not lval, "assertion failed: l == r\nl: %r\nr: %r\n\n%s" % (240 lval, False, _diff_message(lval, False),241 )242def assert_almost_equal(lval, rval, digits, message=None):243 """Assert that lval and rval, when rounded to the specified number of digits, are the same."""244 real_message = message or "%r !~= %r" % (lval, rval)245 assert round(lval, digits) == round(rval, digits), real_message246def assert_within_tolerance(lval, rval, tolerance, message=None):247 """Assert that the difference between the two values, as a fraction of the left value, is smaller than the tolerance specified.248 That is, abs(float(lval) - float(rval)) / float(lval) < tolerance"""249 real_message = message or "%r !~= %r" % (lval, rval)250 assert abs(float(lval) - float(rval)) / float(lval) < tolerance, real_message251def assert_not_equal(lval, rval, message=None):252 """Assert that lval and rval are unequal to each other."""253 if message:254 assert lval != rval, message255 else:256 assert lval != rval, 'assertion failed: %r != %r' % (lval, rval)257def assert_lt(lval, rval, message=None):258 """Assert that lval is less than rval."""259 if message:260 assert lval < rval, message261 else:262 assert lval < rval, 'assertion failed: %r < %r' % (lval, rval)263def assert_lte(lval, rval, message=None):264 """Assert that lval is less than or equal to rval"""265 if message:266 assert lval <= rval, message267 else:268 assert lval <= rval, 'assertion failed: %r <= %r' % (lval, rval)269def assert_gt(lval, rval, message=None):270 """Assert that lval is greater than rval."""271 if message:272 assert lval > rval, message273 else:274 assert lval > rval, 'assertion failed: %r > %r' % (lval, rval)275def assert_gte(lval, rval, message=None):276 """Assert that lval is greater than or equal to rval"""277 if message:278 assert lval >= rval, message279 else:280 assert lval >= rval, 'assertion failed: %r >= %r' % (lval, rval)281def assert_in_range(val, start, end, message=None, inclusive=False):282 """Assert that val is greater than start and less than end. If inclusive is true, val may be equal to start or end."""283 if inclusive:284 real_message = message or "! %s <= %r <= %r" % (start, val, end)285 assert start <= val <= end, real_message286 else:287 real_message = message or "! %s < %r < %r" % (start, val, end)288 assert start < val < end, real_message289def assert_between(a, b, c):290 """Assert that b is between a and c, inclusive."""291 assert_in_range(b, a, c, inclusive=True)292def assert_in(item, sequence, message="assertion failed: expected %(item)r in %(sequence)r", msg=None):293 """Assert that the item is in the sequence."""294 if msg:295 warnings.warn("msg is deprecated", DeprecationWarning)296 message = msg297 assert item in sequence, message % {'item': item, 'sequence': sequence}298def assert_not_in(item, sequence, message="assertion failed: expected %(item)r not in %(sequence)r", msg=None):299 """Assert that the item is not in the sequence."""300 if msg:301 warnings.warn("msg is deprecated", DeprecationWarning)302 message = msg303 assert item not in sequence, message % {'item': item, 'sequence': sequence}304def assert_all_in(left, right):305 """Assert that everything in `left` is also in `right`306 Note: This is different than `assert_subset()` because python sets use307 `__hash__()` for comparision whereas `in` uses `__eq__()`.308 """309 unmatching = []310 for item in left:311 if item not in right:312 unmatching.append(item)313 if unmatching:314 raise AssertionError(315 'The following items were not found in %s: %s' % (right, unmatching)316 )317def assert_starts_with(val, prefix):318 """Assert that val.startswith(prefix)."""319 message = "%(val)r does not start with %(prefix)r" % locals()320 assert val.startswith(prefix), message321def assert_not_reached(message=None):322 """Raise an AssertionError with a message."""323 if message:324 assert False, message325 else:326 assert False, 'egads! this line ought not to have been reached'327def assert_rows_equal(rows1, rows2):328 """Check that two sequences contain the same lists of dictionaries"""329 def norm_row(row):330 if isinstance(row, dict):331 return tuple((k, row[k]) for k in sorted(row))332 else:333 return tuple(sorted(row))334 def norm_rows(rows):335 return tuple(sorted(norm_row(row) for row in rows))336 assert_equal(norm_rows(rows1), norm_rows(rows2))337def assert_empty(iterable, max_elements_to_print=None, message=None):338 """339 Assert that an iterable contains no values.340 Args:341 iterable - any iterable object342 max_elements_to_print - int or None, maximum number of elements from343 iterable to include in the error message. by default, includes all344 elements from iterables with a len(), and 10 elements otherwise.345 if max_elements_to_print is 0, no sample is printed.346 message - str or None, custom message to print if the iterable yields.347 a sample is appended to the end unless max_elements_to_print is 0.348 """349 # Determine whether or not we can print all of iterable, which could be350 # an infinite (or very slow) generator.351 if max_elements_to_print is None:352 try:353 max_elements_to_print = len(iterable)354 except TypeError:355 max_elements_to_print = 10356 # Build the message *before* touching iterable since that might modify it.357 message = message or "iterable {} was unexpectedly non-empty.".format(iterable)358 # Get the first max_elements_to_print + 1 items from iterable, or just359 # the first item if max_elements_to_print is 0. Trying to get an360 # extra item by adding 1 to max_elements_to_print lets us tell whether361 # we got everything in iterator, regardless of if it has len() defined.362 if max_elements_to_print == 0:363 sample = list(islice(iterable, 0, 1))364 else:365 sample_plus_extra = list(islice(iterable, 0, max_elements_to_print + 1))366 sample_is_whole_iterable = len(sample_plus_extra) <= max_elements_to_print367 sample = sample_plus_extra[:max_elements_to_print]368 if sample_is_whole_iterable:369 message += ' elements: %s' % sample370 else:371 message += ' first %s elements: %s' % (len(sample), sample)372 assert len(sample) == 0, message373def assert_not_empty(iterable, message=None):374 """375 Assert that an iterable is not empty (by trying to loop over it).376 Args:377 iterable - any iterable object378 message - str or None, message to print if the iterable doesn't yield379 """380 for value in iterable:381 break382 else:383 # The else clause of a for loop is reached iff you break out of the loop.384 raise AssertionError(message if message else385 "iterable {} is unexpectedly empty".format(iterable)386 )387def assert_length(sequence, expected, message=None):388 """Assert a sequence or iterable has an expected length."""389 message = message or "%(sequence)s has length %(length)s expected %(expected)s"390 length = len(list(sequence))391 assert length == expected, message % locals()392def assert_call(turtle, call_idx, *args, **kwargs):393 """Assert that a function was called on turtle with the correct args."""394 actual = turtle.calls[call_idx] if turtle.calls else None395 message = "Call %s expected %s, was %s" % (call_idx, (args, kwargs), actual)396 assert actual == (args, kwargs), message397def assert_is(left, right, message="expected %(left)r is %(right)r", msg=None):398 """Assert that left and right are the same object"""399 if msg:400 warnings.warn("msg is deprecated", DeprecationWarning)401 message = msg402 assert left is right, message % {'left': left, 'right': right}403def assert_is_not(left, right, message="expected %(left)r is not %(right)r", msg=None):404 """Assert that left and right are NOT the same object"""405 if msg:406 warnings.warn("msg is deprecated", DeprecationWarning)407 message = msg408 assert left is not right, message % {'left': left, 'right': right}409def assert_all_match_regex(pattern, values, message="expected %(value)r to match %(pattern)r", msg=None):410 """Assert that all values in an iterable match a regex pattern.411 Args:412 pattern -- a regex.413 values -- an iterable of values to test.414 Raises AssertionError if any value does not match.415 """416 if msg:417 warnings.warn("msg is deprecated", DeprecationWarning)418 message = msg419 for value in values:420 assert re.match(pattern, value), message % {'value': value, 'pattern': pattern}421def assert_match_regex(pattern, value, *args, **kwargs):422 """Assert that a single value matches a regex pattern."""423 assert_all_match_regex(pattern, [value], *args, **kwargs)424def assert_any_match_regex(pattern, values, message="expected at least one %(values)r to match %(pattern)r", msg=None):425 """Assert that at least one value in an iterable matches a regex pattern.426 Args:427 pattern -- a regex.428 values -- an iterable of values to test.429 Raises AssertionError if all values don't match.430 """431 if msg:432 warnings.warn("msg is deprecated", DeprecationWarning)433 message = msg434 for value in values:435 if re.match(pattern, value) is not None:436 return437 raise AssertionError(message % {'values': values, 'pattern': pattern})438def assert_all_not_match_regex(pattern, values, message="expected %(value)r to not match %(pattern)r", msg=None):439 """Assert that all values don't match a regex pattern.440 Args:441 pattern -- a regex.442 values -- an iterable of values to test.443 Raises AssertionError if any values matches.444 """445 if msg:446 warnings.warn("msg is deprecated", DeprecationWarning)447 message = msg448 for value in values:449 assert not re.match(pattern, value), message % {'value': value, 'pattern': pattern}450def assert_sets_equal(451 left,452 right,453 message="expected %(left)r == %(right)r [left has:%(extra_left)r, right has:%(extra_right)r]",454 msg=None,455):456 """Assert that two sets are equal."""457 if msg:458 warnings.warn("msg is deprecated", DeprecationWarning)459 message = msg460 if left != right:461 extra_left = left - right462 extra_right = right - left463 raise AssertionError(message % {464 'left': left,465 'right': right,466 'extra_left': extra_left,467 'extra_right': extra_right,468 })469def assert_dicts_equal(470 left,471 right,472 ignore_keys=None,473 message="expected %(left)r == %(right)r [left has:%(extra_left)r, right has:%(extra_right)r]",474 msg=None,475):476 """Assert that two dictionarys are equal (optionally ignoring certain keys)."""477 if msg:478 warnings.warn("msg is deprecated", DeprecationWarning)479 message = msg480 if ignore_keys is not None:481 left = {k: left[k] for k in left if k not in ignore_keys}482 right = {k: right[k] for k in right if k not in ignore_keys}483 if left == right:484 return485 extra_left = _dict_subtract(left, right)486 extra_right = _dict_subtract(right, left)487 raise AssertionError(message % {488 'left': left,489 'right': right,490 'extra_left': extra_left,491 'extra_right': extra_right,492 })493def assert_dict_subset(left, right, message="expected [subset has:%(extra_left)r, superset has:%(extra_right)s]", msg=None):494 """Assert that a dictionary is a strict subset of another dictionary (both keys and values)."""495 if msg:496 warnings.warn("msg is deprecated", DeprecationWarning)497 message = msg498 difference_dict = _dict_subtract(left, right)499 if not difference_dict:500 return501 extra_left = difference_dict502 small_right = {k: right[k] for k in right if k in left.keys()}503 extra_right = _dict_subtract(small_right, left)504 raise AssertionError(message % {505 'left': left,506 'right': right,507 'extra_left': extra_left,508 'extra_right': extra_right,509 })510def assert_subset(left, right, message="expected %(set_left)r <= %(set_right)r [left has:%(extra)r]", msg=None):511 """Assert that the left set is a subset of the right set."""512 if msg:513 warnings.warn("msg is deprecated", DeprecationWarning)514 message = msg515 set_left = set(left)516 set_right = set(right)517 if not (set_left <= set_right):518 extra = set_left - set_right519 raise AssertionError(message % {520 'left': left,521 'right': right,522 'set_left': set_left,523 'set_right': set_right,524 'extra': extra,525 })526def assert_list_prefix(left, right):527 """Assert that the left list is a prefix of the right list."""528 assert_equal(left, right[:len(left)])529def assert_sorted_equal(left, right, **kwargs):530 """Assert equality, but without respect to ordering of elements. Basically for multisets."""531 assert_equal(sorted(left), sorted(right), **kwargs)532def assert_isinstance(object_, type_):533 """Assert that an object is an instance of a given type."""534 assert isinstance(object_, type_), "Expected type %r but got type %r" % (type_, type(object_))535def assert_datetimes_equal(a, b):536 """Tests for equality of times by only testing up to the millisecond."""537 assert_equal(a.utctimetuple()[:-3], b.utctimetuple()[:-3], "%r != %r" % (a, b))538def assert_exactly_one(*args, **kwargs):539 """Assert that only one of the given arguments passes the provided truthy function (non-None by default).540 Args:541 truthy_fxn: a filter to redefine truthy behavior. Should take an object and return542 True if desired conditions are satisfied. For example:543 >>> assert_exactly_one(True, False, truthy_fxn=bool) # Success544 True545 >>> assert_exactly_one(0, None) # Success546 0547 >>> assert_exactly_one(True, False)548 Traceback (most recent call last):549 ...550 AssertionError: Expected exactly one True (got 2) args: (True, False)551 Returns:552 The argument that passes the truthy function553 """554 truthy_fxn = kwargs.pop('truthy_fxn', lambda x: x is not None)555 assert not kwargs, "Unexpected kwargs: %r" % kwargs556 true_args = [arg for arg in args if truthy_fxn(arg)]557 if len(true_args) != 1:558 raise AssertionError("Expected exactly one True (got %d) args: %r" % (len(true_args), args))559 return true_args[0]560@contextlib.contextmanager561def _assert_warns_context_manager(warning_class=None, warnings_test=None):562 """563 Builds a context manager for testing code that should throw a warning.564 This will look for a given class, call a custom test, or both.565 Args:566 warning_class - a class or subclass of Warning. If not None, then567 the context manager will raise an AssertionError if the block568 does not throw at least one warning of that type.569 warnings_test - a function which takes a list of warnings caught,570 and makes a number of assertions about the result. If the function571 returns without an exception, the context manager will consider572 this a successful assertion.573 """574 with warnings.catch_warnings(record=True) as caught:575 # All warnings should be triggered.576 warnings.resetwarnings()577 if warning_class:578 warnings.simplefilter('ignore')579 warnings.simplefilter('always', category=warning_class)580 else:581 warnings.simplefilter('always')582 # Do something that ought to trigger a warning.583 yield584 # We should have received at least one warning.585 assert_gt(len(caught), 0, 'expected at least one warning to be thrown')586 # Run the custom test against the warnings we caught.587 if warnings_test:588 warnings_test(caught)589def assert_warns(warning_class=None, callable=None, *args, **kwargs):590 """Assert that the given warning class is thrown as a context manager591 or by passing in a callable and its arguments.592 As a context manager:593 >>> with assert_warns():594 ... warnings.warn('Hey!')595 Passing in a callable:596 >>> def throw_warning():597 ... warnings.warn('Hey!')598 >>> assert_warns(UserWarning, throw_warning)599 """600 if callable is None:601 return _assert_warns_context_manager(warning_class=warning_class)602 else:603 with _assert_warns_context_manager(warning_class=warning_class):604 callable(*args, **kwargs)605def assert_warns_such_that(warnings_test, callable=None, *args, **kwargs):606 """607 Assert that the given warnings_test function returns True when608 called with a full list of warnings that were generated by either609 a code block (when this is used as a context manager in a `with` statement)610 or the given callable (when called with the appropriate args and kwargs).611 As a context manager:612 >>> def two_warnings_thrown(warnings):613 ... assert len(warnings) == 2614 >>> with assert_warns_such_that(two_warnings_thrown):615 ... warnings.warn('Hey!')616 ... warnings.warn('Seriously!')617 Passing in a callable:618 >>> def throw_warnings(count):619 ... for n in range(count):620 ... warnings.warn('Warning #%i' % n)621 >>> assert_warns_such_that(two_warnings_thrown, throw_warnings, 2)622 """623 if callable is None:624 return _assert_warns_context_manager(warnings_test=warnings_test)625 else:626 with _assert_warns_context_manager(warnings_test=warnings_test):627 callable(*args, **kwargs)628def _to_characters(x):629 """Return characters that represent the object `x`, come hell or high water."""630 if isinstance(x, six.text_type):631 return x632 try:633 return six.text_type(x, 'UTF-8')634 except UnicodeDecodeError:635 return six.text_type(x, 'latin1')636 except TypeError:637 # We're only allowed to specify an encoding for str values, for whatever reason.638 try:639 return six.text_type(x)640 except UnicodeDecodeError:641 # You get this (for example) when an error object contains utf8 bytes.642 try:...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful