How to use _formatMessage method in autotest

Best Python code snippet using autotest_python Github


Full Screen

...338 raise self.failureException(msg)339 def assertFalse(self, expr, msg=None):340 """Check that the expression is false."""341 if expr:342 msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))343 raise self.failureException(msg)344 def assertTrue(self, expr, msg=None):345 """Check that the expression is true."""346 if not expr:347 msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))348 raise self.failureException(msg)349 def _formatMessage(self, msg, standardMsg):350 """Honour the longMessage attribute when generating failure messages.351 If longMessage is False this means:352 * Use only an explicit message if it is provided353 * Otherwise use the standard message for the assert354 If longMessage is True:355 * Use the standard message356 * If an explicit message is provided, plus ' : ' and the explicit message357 """358 if not self.longMessage:359 return msg or standardMsg360 if msg is None:361 return standardMsg362 try:363 # don't switch to '{}' formatting in Python 2.X364 # it changes the way unicode input is handled365 return '%s : %s' % (standardMsg, msg)366 except UnicodeDecodeError:367 return '%s : %s' % (safe_repr(standardMsg), safe_repr(msg))368 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):369 """Fail unless an exception of class excClass is raised370 by callableObj when invoked with arguments args and keyword371 arguments kwargs. If a different type of exception is372 raised, it will not be caught, and the test case will be373 deemed to have suffered an error, exactly as for an374 unexpected exception.375 If called with callableObj omitted or None, will return a376 context object used like this::377 with self.assertRaises(SomeException):378 do_something()379 The context manager keeps a reference to the exception as380 the 'exception' attribute. This allows you to inspect the381 exception after the assertion::382 with self.assertRaises(SomeException) as cm:383 do_something()384 the_exception = cm.exception385 self.assertEqual(the_exception.error_code, 3)386 """387 context = _AssertRaisesContext(excClass, self)388 if callableObj is None:389 return context390 with context:391 callableObj(*args, **kwargs)392 def _getAssertEqualityFunc(self, first, second):393 """Get a detailed comparison function for the types of the two args.394 Returns: A callable accepting (first, second, msg=None) that will395 raise a failure exception if first != second with a useful human396 readable error message for those types.397 """398 #399 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))400 # and vice versa. I opted for the conservative approach in case401 # subclasses are not intended to be compared in detail to their super402 # class instances using a type equality func. This means testing403 # subtypes won't automagically use the detailed comparison. Callers404 # should use their type specific assertSpamEqual method to compare405 # subclasses if the detailed comparison is desired and appropriate.406 # See the discussion in #408 if type(first) is type(second):409 asserter = self._type_equality_funcs.get(type(first))410 if asserter is not None:411 if isinstance(asserter, basestring):412 asserter = getattr(self, asserter)413 return asserter414 return self._baseAssertEqual415 def _baseAssertEqual(self, first, second, msg=None):416 """The default assertEqual implementation, not type specific."""417 if not first == second:418 standardMsg = '%s != %s' % (safe_repr(first), safe_repr(second))419 msg = self._formatMessage(msg, standardMsg)420 raise self.failureException(msg)421 def assertEqual(self, first, second, msg=None):422 """Fail if the two objects are unequal as determined by the '=='423 operator.424 """425 assertion_func = self._getAssertEqualityFunc(first, second)426 assertion_func(first, second, msg=msg)427 def assertNotEqual(self, first, second, msg=None):428 """Fail if the two objects are equal as determined by the '!='429 operator.430 """431 if not first != second:432 msg = self._formatMessage(msg, '%s == %s' % (safe_repr(first),433 safe_repr(second)))434 raise self.failureException(msg)435 def assertAlmostEqual(self, first, second, places=None, msg=None, delta=None):436 """Fail if the two objects are unequal as determined by their437 difference rounded to the given number of decimal places438 (default 7) and comparing to zero, or by comparing that the439 between the two objects is more than the given delta.440 Note that decimal places (from zero) are usually not the same441 as significant digits (measured from the most signficant digit).442 If the two objects compare equal then they will automatically443 compare almost equal.444 """445 if first == second:446 # shortcut447 return448 if delta is not None and places is not None:449 raise TypeError("specify delta or places not both")450 if delta is not None:451 if abs(first - second) <= delta:452 return453 standardMsg = '%s != %s within %s delta' % (safe_repr(first),454 safe_repr(second),455 safe_repr(delta))456 else:457 if places is None:458 places = 7459 if round(abs(second-first), places) == 0:460 return461 standardMsg = '%s != %s within %r places' % (safe_repr(first),462 safe_repr(second),463 places)464 msg = self._formatMessage(msg, standardMsg)465 raise self.failureException(msg)466 def assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None):467 """Fail if the two objects are equal as determined by their468 difference rounded to the given number of decimal places469 (default 7) and comparing to zero, or by comparing that the470 between the two objects is less than the given delta.471 Note that decimal places (from zero) are usually not the same472 as significant digits (measured from the most signficant digit).473 Objects that are equal automatically fail.474 """475 if delta is not None and places is not None:476 raise TypeError("specify delta or places not both")477 if delta is not None:478 if not (first == second) and abs(first - second) > delta:479 return480 standardMsg = '%s == %s within %s delta' % (safe_repr(first),481 safe_repr(second),482 safe_repr(delta))483 else:484 if places is None:485 places = 7486 if not (first == second) and round(abs(second-first), places) != 0:487 return488 standardMsg = '%s == %s within %r places' % (safe_repr(first),489 safe_repr(second),490 places)491 msg = self._formatMessage(msg, standardMsg)492 raise self.failureException(msg)493 # Synonyms for assertion methods494 # The plurals are undocumented. Keep them that way to discourage use.495 # Do not add more. Do not remove.496 # Going through a deprecation cycle on these would annoy many people.497 assertEquals = assertEqual498 assertNotEquals = assertNotEqual499 assertAlmostEquals = assertAlmostEqual500 assertNotAlmostEquals = assertNotAlmostEqual501 assert_ = assertTrue502 # These fail* assertion method names are pending deprecation and will503 # be a DeprecationWarning in 3.2; def _deprecate(original_func):505 def deprecated_func(*args, **kwargs):506 warnings.warn(507 'Please use {0} instead.'.format(original_func.__name__),508 PendingDeprecationWarning, 2)509 return original_func(*args, **kwargs)510 return deprecated_func511 failUnlessEqual = _deprecate(assertEqual)512 failIfEqual = _deprecate(assertNotEqual)513 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)514 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)515 failUnless = _deprecate(assertTrue)516 failUnlessRaises = _deprecate(assertRaises)517 failIf = _deprecate(assertFalse)518 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):519 """An equality assertion for ordered sequences (like lists and tuples).520 For the purposes of this function, a valid ordered sequence type is one521 which can be indexed, has a length, and has an equality operator.522 Args:523 seq1: The first sequence to compare.524 seq2: The second sequence to compare.525 seq_type: The expected datatype of the sequences, or None if no526 datatype should be enforced.527 msg: Optional message to use on failure instead of a list of528 differences.529 """530 if seq_type is not None:531 seq_type_name = seq_type.__name__532 if not isinstance(seq1, seq_type):533 raise self.failureException('First sequence is not a %s: %s'534 % (seq_type_name, safe_repr(seq1)))535 if not isinstance(seq2, seq_type):536 raise self.failureException('Second sequence is not a %s: %s'537 % (seq_type_name, safe_repr(seq2)))538 else:539 seq_type_name = "sequence"540 differing = None541 try:542 len1 = len(seq1)543 except (TypeError, NotImplementedError):544 differing = 'First %s has no length. Non-sequence?' % (545 seq_type_name)546 if differing is None:547 try:548 len2 = len(seq2)549 except (TypeError, NotImplementedError):550 differing = 'Second %s has no length. Non-sequence?' % (551 seq_type_name)552 if differing is None:553 if seq1 == seq2:554 return555 seq1_repr = safe_repr(seq1)556 seq2_repr = safe_repr(seq2)557 if len(seq1_repr) > 30:558 seq1_repr = seq1_repr[:30] + '...'559 if len(seq2_repr) > 30:560 seq2_repr = seq2_repr[:30] + '...'561 elements = (seq_type_name.capitalize(), seq1_repr, seq2_repr)562 differing = '%ss differ: %s != %s\n' % elements563 for i in xrange(min(len1, len2)):564 try:565 item1 = seq1[i]566 except (TypeError, IndexError, NotImplementedError):567 differing += ('\nUnable to index element %d of first %s\n' %568 (i, seq_type_name))569 break570 try:571 item2 = seq2[i]572 except (TypeError, IndexError, NotImplementedError):573 differing += ('\nUnable to index element %d of second %s\n' %574 (i, seq_type_name))575 break576 if item1 != item2:577 differing += ('\nFirst differing element %d:\n%s\n%s\n' %578 (i, item1, item2))579 break580 else:581 if (len1 == len2 and seq_type is None and582 type(seq1) != type(seq2)):583 # The sequences are the same, but have differing types.584 return585 if len1 > len2:586 differing += ('\nFirst %s contains %d additional '587 'elements.\n' % (seq_type_name, len1 - len2))588 try:589 differing += ('First extra element %d:\n%s\n' %590 (len2, seq1[len2]))591 except (TypeError, IndexError, NotImplementedError):592 differing += ('Unable to index element %d '593 'of first %s\n' % (len2, seq_type_name))594 elif len1 < len2:595 differing += ('\nSecond %s contains %d additional '596 'elements.\n' % (seq_type_name, len2 - len1))597 try:598 differing += ('First extra element %d:\n%s\n' %599 (len1, seq2[len1]))600 except (TypeError, IndexError, NotImplementedError):601 differing += ('Unable to index element %d '602 'of second %s\n' % (len1, seq_type_name))603 standardMsg = differing604 diffMsg = '\n' + '\n'.join(605 difflib.ndiff(pprint.pformat(seq1).splitlines(),606 pprint.pformat(seq2).splitlines()))607 standardMsg = self._truncateMessage(standardMsg, diffMsg)608 msg = self._formatMessage(msg, standardMsg)609 def _truncateMessage(self, message, diff):611 max_diff = self.maxDiff612 if max_diff is None or len(diff) <= max_diff:613 return message + diff614 return message + (DIFF_OMITTED % len(diff))615 def assertListEqual(self, list1, list2, msg=None):616 """A list-specific equality assertion.617 Args:618 list1: The first list to compare.619 list2: The second list to compare.620 msg: Optional message to use on failure instead of a list of621 differences.622 """623 self.assertSequenceEqual(list1, list2, msg, seq_type=list)624 def assertTupleEqual(self, tuple1, tuple2, msg=None):625 """A tuple-specific equality assertion.626 Args:627 tuple1: The first tuple to compare.628 tuple2: The second tuple to compare.629 msg: Optional message to use on failure instead of a list of630 differences.631 """632 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)633 def assertSetEqual(self, set1, set2, msg=None):634 """A set-specific equality assertion.635 Args:636 set1: The first set to compare.637 set2: The second set to compare.638 msg: Optional message to use on failure instead of a list of639 differences.640 assertSetEqual uses ducktyping to support different types of sets, and641 is optimized for sets specifically (parameters must support a642 difference method).643 """644 try:645 difference1 = set1.difference(set2)646 except TypeError, e:647'invalid type when attempting set difference: %s' % e)648 except AttributeError, e:649'first argument does not support set difference: %s' % e)650 try:651 difference2 = set2.difference(set1)652 except TypeError, e:653'invalid type when attempting set difference: %s' % e)654 except AttributeError, e:655'second argument does not support set difference: %s' % e)656 if not (difference1 or difference2):657 return658 lines = []659 if difference1:660 lines.append('Items in the first set but not the second:')661 for item in difference1:662 lines.append(repr(item))663 if difference2:664 lines.append('Items in the second set but not the first:')665 for item in difference2:666 lines.append(repr(item))667 standardMsg = '\n'.join(lines)668, standardMsg))669 def assertIn(self, member, container, msg=None):670 """Just like self.assertTrue(a in b), but with a nicer default message."""671 if member not in container:672 standardMsg = '%s not found in %s' % (safe_repr(member),673 safe_repr(container))674, standardMsg))675 def assertNotIn(self, member, container, msg=None):676 """Just like self.assertTrue(a not in b), but with a nicer default message."""677 if member in container:678 standardMsg = '%s unexpectedly found in %s' % (safe_repr(member),679 safe_repr(container))680, standardMsg))681 def assertIs(self, expr1, expr2, msg=None):682 """Just like self.assertTrue(a is b), but with a nicer default message."""683 if expr1 is not expr2:684 standardMsg = '%s is not %s' % (safe_repr(expr1),685 safe_repr(expr2))686, standardMsg))687 def assertIsNot(self, expr1, expr2, msg=None):688 """Just like self.assertTrue(a is not b), but with a nicer default message."""689 if expr1 is expr2:690 standardMsg = 'unexpectedly identical: %s' % (safe_repr(expr1),)691, standardMsg))692 def assertDictEqual(self, d1, d2, msg=None):693 self.assertIsInstance(d1, dict, 'First argument is not a dictionary')694 self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')695 if d1 != d2:696 standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))697 diff = ('\n' + '\n'.join(difflib.ndiff(698 pprint.pformat(d1).splitlines(),699 pprint.pformat(d2).splitlines())))700 standardMsg = self._truncateMessage(standardMsg, diff)701, standardMsg))702 def assertDictContainsSubset(self, expected, actual, msg=None):703 """Checks whether actual is a superset of expected."""704 missing = []705 mismatched = []706 for key, value in expected.iteritems():707 if key not in actual:708 missing.append(key)709 elif value != actual[key]:710 mismatched.append('%s, expected: %s, actual: %s' %711 (safe_repr(key), safe_repr(value),712 safe_repr(actual[key])))713 if not (missing or mismatched):714 return715 standardMsg = ''716 if missing:717 standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in718 missing)719 if mismatched:720 if standardMsg:721 standardMsg += '; '722 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)723, standardMsg))724 def assertItemsEqual(self, expected_seq, actual_seq, msg=None):725 """An unordered sequence specific comparison. It asserts that726 actual_seq and expected_seq have the same element counts.727 Equivalent to::728 self.assertEqual(Counter(iter(actual_seq)),729 Counter(iter(expected_seq)))730 Asserts that each element has the same count in both sequences.731 Example:732 - [0, 1, 1] and [1, 0, 1] compare equal.733 - [0, 0, 1] and [0, 1] compare unequal.734 """735 first_seq, second_seq = list(expected_seq), list(actual_seq)736 with warnings.catch_warnings():737 if sys.py3kwarning:738 # Silence Py3k warning raised during the sorting739 for _msg in ["(code|dict|type) inequality comparisons",740 "builtin_function_or_method order comparisons",741 "comparing unequal types"]:742 warnings.filterwarnings("ignore", _msg, DeprecationWarning)743 try:744 first = collections.Counter(first_seq)745 second = collections.Counter(second_seq)746 except TypeError:747 # Handle case with unhashable elements748 differences = _count_diff_all_purpose(first_seq, second_seq)749 else:750 if first == second:751 return752 differences = _count_diff_hashable(first_seq, second_seq)753 if differences:754 standardMsg = 'Element counts were not equal:\n'755 lines = ['First has %d, Second has %d: %r' % diff for diff in differences]756 diffMsg = '\n'.join(lines)757 standardMsg = self._truncateMessage(standardMsg, diffMsg)758 msg = self._formatMessage(msg, standardMsg)759 def assertMultiLineEqual(self, first, second, msg=None):761 """Assert that two multi-line strings are equal."""762 self.assertIsInstance(first, basestring,763 'First argument is not a string')764 self.assertIsInstance(second, basestring,765 'Second argument is not a string')766 if first != second:767 # don't use difflib if the strings are too long768 if (len(first) > self._diffThreshold or769 len(second) > self._diffThreshold):770 self._baseAssertEqual(first, second, msg)771 firstlines = first.splitlines(True)772 secondlines = second.splitlines(True)773 if len(firstlines) == 1 and first.strip('\r\n') == first:774 firstlines = [first + '\n']775 secondlines = [second + '\n']776 standardMsg = '%s != %s' % (safe_repr(first, True),777 safe_repr(second, True))778 diff = '\n' + ''.join(difflib.ndiff(firstlines, secondlines))779 standardMsg = self._truncateMessage(standardMsg, diff)780, standardMsg))781 def assertLess(self, a, b, msg=None):782 """Just like self.assertTrue(a < b), but with a nicer default message."""783 if not a < b:784 standardMsg = '%s not less than %s' % (safe_repr(a), safe_repr(b))785, standardMsg))786 def assertLessEqual(self, a, b, msg=None):787 """Just like self.assertTrue(a <= b), but with a nicer default message."""788 if not a <= b:789 standardMsg = '%s not less than or equal to %s' % (safe_repr(a), safe_repr(b))790, standardMsg))791 def assertGreater(self, a, b, msg=None):792 """Just like self.assertTrue(a > b), but with a nicer default message."""793 if not a > b:794 standardMsg = '%s not greater than %s' % (safe_repr(a), safe_repr(b))795, standardMsg))796 def assertGreaterEqual(self, a, b, msg=None):797 """Just like self.assertTrue(a >= b), but with a nicer default message."""798 if not a >= b:799 standardMsg = '%s not greater than or equal to %s' % (safe_repr(a), safe_repr(b))800, standardMsg))801 def assertIsNone(self, obj, msg=None):802 """Same as self.assertTrue(obj is None), with a nicer default message."""803 if obj is not None:804 standardMsg = '%s is not None' % (safe_repr(obj),)805, standardMsg))806 def assertIsNotNone(self, obj, msg=None):807 """Included for symmetry with assertIsNone."""808 if obj is None:809 standardMsg = 'unexpectedly None'810, standardMsg))811 def assertIsInstance(self, obj, cls, msg=None):812 """Same as self.assertTrue(isinstance(obj, cls)), with a nicer813 default message."""814 if not isinstance(obj, cls):815 standardMsg = '%s is not an instance of %r' % (safe_repr(obj), cls)816, standardMsg))817 def assertNotIsInstance(self, obj, cls, msg=None):818 """Included for symmetry with assertIsInstance."""819 if isinstance(obj, cls):820 standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)821, standardMsg))822 def assertRaisesRegexp(self, expected_exception, expected_regexp,823 callable_obj=None, *args, **kwargs):824 """Asserts that the message in a raised exception matches a regexp.825 Args:826 expected_exception: Exception class expected to be raised.827 expected_regexp: Regexp (re pattern object or string) expected828 to be found in error message.829 callable_obj: Function to be called.830 args: Extra args.831 kwargs: Extra kwargs.832 """833 if expected_regexp is not None:834 expected_regexp = re.compile(expected_regexp)835 context = _AssertRaisesContext(expected_exception, self, expected_regexp)...

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:


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

Run autotest 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?