Best Python code snippet using autotest_python
unittest.py
Source:unittest.py
...775 actual.sort()776 except TypeError:777 missing, unexpected = _UnorderableListDifference(expected, actual)778 else:779 missing, unexpected = _SortedListDifference(expected, actual)780 errors = []781 if missing:782 errors.append('Expected, but missing:\n %r' % missing)783 if unexpected:784 errors.append('Unexpected, but present:\n %r' % unexpected)785 if errors:786 standardMsg = '\n'.join(errors)787 self.fail(self._formatMessage(msg, standardMsg))788 def assertMultiLineEqual(self, first, second, msg=None):789 """Assert that two multi-line strings are equal."""790 self.assert_(isinstance(first, str), (791 'First argument is not a string'))792 self.assert_(isinstance(second, str), (793 'Second argument is not a string'))794 if first != second:795 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))796 self.fail(self._formatMessage(msg, standardMsg))797 def assertLess(self, a, b, msg=None):798 """Just like self.assertTrue(a < b), but with a nicer default message."""799 if not a < b:800 standardMsg = '%r not less than %r' % (a, b)801 self.fail(self._formatMessage(msg, standardMsg))802 def assertLessEqual(self, a, b, msg=None):803 """Just like self.assertTrue(a <= b), but with a nicer default message."""804 if not a <= b:805 standardMsg = '%r not less than or equal to %r' % (a, b)806 self.fail(self._formatMessage(msg, standardMsg))807 def assertGreater(self, a, b, msg=None):808 """Just like self.assertTrue(a > b), but with a nicer default message."""809 if not a > b:810 standardMsg = '%r not greater than %r' % (a, b)811 self.fail(self._formatMessage(msg, standardMsg))812 def assertGreaterEqual(self, a, b, msg=None):813 """Just like self.assertTrue(a >= b), but with a nicer default message."""814 if not a >= b:815 standardMsg = '%r not greater than or equal to %r' % (a, b)816 self.fail(self._formatMessage(msg, standardMsg))817 def assertIsNone(self, obj, msg=None):818 """Same as self.assertTrue(obj is None), with a nicer default message."""819 if obj is not None:820 standardMsg = '%r is not None' % obj821 self.fail(self._formatMessage(msg, standardMsg))822 def assertIsNotNone(self, obj, msg=None):823 """Included for symmetry with assertIsNone."""824 if obj is None:825 standardMsg = 'unexpectedly None'826 self.fail(self._formatMessage(msg, standardMsg))827 def assertRaisesRegexp(self, expected_exception, expected_regexp,828 callable_obj=None, *args, **kwargs):829 """Asserts that the message in a raised exception matches a regexp.830 Args:831 expected_exception: Exception class expected to be raised.832 expected_regexp: Regexp (re pattern object or string) expected833 to be found in error message.834 callable_obj: Function to be called.835 args: Extra args.836 kwargs: Extra kwargs.837 """838 context = _AssertRaisesContext(expected_exception, self, callable_obj,839 expected_regexp)840 if callable_obj is None:841 return context842 with context:843 callable_obj(*args, **kwargs)844 def assertRegexpMatches(self, text, expected_regex, msg=None):845 if isinstance(expected_regex, (str, bytes)):846 expected_regex = re.compile(expected_regex)847 if not expected_regex.search(text):848 msg = msg or "Regexp didn't match"849 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)850 raise self.failureException(msg)851def _SortedListDifference(expected, actual):852 """Finds elements in only one or the other of two, sorted input lists.853 Returns a two-element tuple of lists. The first list contains those854 elements in the "expected" list but not in the "actual" list, and the855 second contains those elements in the "actual" list but not in the856 "expected" list. Duplicate elements in either input list are ignored.857 """858 i = j = 0859 missing = []860 unexpected = []861 while True:862 try:863 e = expected[i]864 a = actual[j]865 if e < a:...
basetest.py
Source:basetest.py
...331 expected = list(expected_seq)332 actual = list(actual_seq)333 expected.sort()334 actual.sort()335 missing, unexpected = _SortedListDifference(expected, actual)336 errors = []337 if missing:338 errors.append('Expected, but missing:\n %r\n' % missing)339 if unexpected:340 errors.append('Unexpected, but present:\n %r\n' % unexpected)341 if errors:342 self.fail(msg or ''.join(errors))343 # unittest2.TestCase.assertMulitilineEqual works very similarly, but it344 # has a different error format. However, I find this slightly more readable.345 def assertMultiLineEqual(self, first, second, msg=None):346 """Assert that two multi-line strings are equal."""347 assert isinstance(first, types.StringTypes), (348 'First argument is not a string: %r' % (first,))349 assert isinstance(second, types.StringTypes), (350 'Second argument is not a string: %r' % (second,))351 if first == second:352 return353 if msg:354 raise self.failureException(msg)355 failure_message = ['\n']356 for line in difflib.ndiff(first.splitlines(True), second.splitlines(True)):357 failure_message.append(line)358 if not line.endswith('\n'):359 failure_message.append('\n')360 raise self.failureException(''.join(failure_message))361 def assertBetween(self, value, minv, maxv, msg=None):362 """Asserts that value is between minv and maxv (inclusive)."""363 if msg is None:364 msg = '"%r" unexpectedly not between "%r" and "%r"' % (value, minv, maxv)365 self.assert_(minv <= value, msg)366 self.assert_(maxv >= value, msg)367 def assertRegexMatch(self, actual_str, regexes, message=None):368 """Asserts that at least one regex in regexes matches str.369 If possible you should use assertRegexpMatches, which is a simpler370 version of this method. assertRegexpMatches takes a single regular371 expression (a string or re compiled object) instead of a list.372 Notes:373 1. This function uses substring matching, i.e. the matching374 succeeds if *any* substring of the error message matches *any*375 regex in the list. This is more convenient for the user than376 full-string matching.377 2. If regexes is the empty list, the matching will always fail.378 3. Use regexes=[''] for a regex that will always pass.379 4. '.' matches any single character *except* the newline. To380 match any character, use '(.|\n)'.381 5. '^' matches the beginning of each line, not just the beginning382 of the string. Similarly, '$' matches the end of each line.383 6. An exception will be thrown if regexes contains an invalid384 regex.385 Args:386 actual_str: The string we try to match with the items in regexes.387 regexes: The regular expressions we want to match against str.388 See "Notes" above for detailed notes on how this is interpreted.389 message: The message to be printed if the test fails.390 """391 if isinstance(regexes, basestring):392 self.fail('regexes is a string; it needs to be a list of strings.')393 if not regexes:394 self.fail('No regexes specified.')395 regex = '(?:%s)' % ')|(?:'.join(regexes)396 if not re.search(regex, actual_str, re.MULTILINE):397 self.fail(message or ('String "%s" does not contain any of these '398 'regexes: %s.' % (actual_str, regexes)))399 def assertCommandSucceeds(self, command, regexes=[''], env=None,400 close_fds=True):401 """Asserts that a shell command succeeds (i.e. exits with code 0).402 Args:403 command: List or string representing the command to run.404 regexes: List of regular expression strings.405 env: Dictionary of environment variable settings.406 close_fds: Whether or not to close all open fd's in the child after407 forking.408 """409 (ret_code, err) = GetCommandStderr(command, env, close_fds)410 command_string = GetCommandString(command)411 self.assert_(412 ret_code == 0,413 'Running command\n'414 '%s failed with error code %s and message\n'415 '%s' % (416 _QuoteLongString(command_string),417 ret_code,418 _QuoteLongString(err)))419 self.assertRegexMatch(420 err,421 regexes,422 message=(423 'Running command\n'424 '%s failed with error code %s and message\n'425 '%s which matches no regex in %s' % (426 _QuoteLongString(command_string),427 ret_code,428 _QuoteLongString(err),429 regexes)))430 def assertCommandFails(self, command, regexes, env=None, close_fds=True):431 """Asserts a shell command fails and the error matches a regex in a list.432 Args:433 command: List or string representing the command to run.434 regexes: the list of regular expression strings.435 env: Dictionary of environment variable settings.436 close_fds: Whether or not to close all open fd's in the child after437 forking.438 """439 (ret_code, err) = GetCommandStderr(command, env, close_fds)440 command_string = GetCommandString(command)441 self.assert_(442 ret_code != 0,443 'The following command succeeded while expected to fail:\n%s' %444 _QuoteLongString(command_string))445 self.assertRegexMatch(446 err,447 regexes,448 message=(449 'Running command\n'450 '%s failed with error code %s and message\n'451 '%s which matches no regex in %s' % (452 _QuoteLongString(command_string),453 ret_code,454 _QuoteLongString(err),455 regexes)))456 def assertRaisesWithPredicateMatch(self, expected_exception, predicate,457 callable_obj, *args,458 **kwargs):459 """Asserts that exception is thrown and predicate(exception) is true.460 Args:461 expected_exception: Exception class expected to be raised.462 predicate: Function of one argument that inspects the passed-in exception463 and returns True (success) or False (please fail the test).464 callable_obj: Function to be called.465 args: Extra args.466 kwargs: Extra keyword args.467 """468 try:469 callable_obj(*args, **kwargs)470 except expected_exception, err:471 self.assert_(predicate(err),472 '%r does not match predicate %r' % (err, predicate))473 else:474 self.fail(expected_exception.__name__ + ' not raised')475 def assertRaisesWithLiteralMatch(self, expected_exception,476 expected_exception_message, callable_obj,477 *args, **kwargs):478 """Asserts that the message in a raised exception equals the given string.479 Unlike assertRaisesWithRegexpMatch this method takes a literal string, not480 a regular expression.481 Args:482 expected_exception: Exception class expected to be raised.483 expected_exception_message: String message expected in the raised484 exception. For a raise exception e, expected_exception_message must485 equal str(e).486 callable_obj: Function to be called.487 args: Extra args.488 kwargs: Extra kwargs.489 """490 try:491 callable_obj(*args, **kwargs)492 except expected_exception, err:493 actual_exception_message = str(err)494 self.assert_(expected_exception_message == actual_exception_message,495 'Exception message does not match.\n'496 'Expected: %r\n'497 'Actual: %r' % (expected_exception_message,498 actual_exception_message))499 else:500 self.fail(expected_exception.__name__ + ' not raised')501 def assertRaisesWithRegexpMatch(self, expected_exception, expected_regexp,502 callable_obj, *args, **kwargs):503 """Asserts that the message in a raised exception matches the given regexp.504 This is just a wrapper around assertRaisesRegexp. Please use505 assertRaisesRegexp instead of assertRaisesWithRegexpMatch.506 Args:507 expected_exception: Exception class expected to be raised.508 expected_regexp: Regexp (re pattern object or string) expected to be509 found in error message.510 callable_obj: Function to be called.511 args: Extra args.512 kwargs: Extra keyword args.513 """514 # TODO(user): this is a good candidate for a global515 # search-and-replace.516 self.assertRaisesRegexp(517 expected_exception,518 expected_regexp,519 callable_obj,520 *args,521 **kwargs)522 def assertContainsInOrder(self, strings, target):523 """Asserts that the strings provided are found in the target in order.524 This may be useful for checking HTML output.525 Args:526 strings: A list of strings, such as [ 'fox', 'dog' ]527 target: A target string in which to look for the strings, such as528 'The quick brown fox jumped over the lazy dog'.529 """530 if not isinstance(strings, list):531 strings = [strings]532 current_index = 0533 last_string = None534 for string in strings:535 index = target.find(str(string), current_index)536 if index == -1 and current_index == 0:537 self.fail("Did not find '%s' in '%s'" %538 (string, target))539 elif index == -1:540 self.fail("Did not find '%s' after '%s' in '%s'" %541 (string, last_string, target))542 last_string = string543 current_index = index544 def assertTotallyOrdered(self, *groups):545 """Asserts that total ordering has been implemented correctly.546 For example, say you have a class A that compares only on its attribute x.547 Comparators other than __lt__ are omitted for brevity.548 class A(object):549 def __init__(self, x, y):550 self.x = xio551 self.y = y552 def __hash__(self):553 return hash(self.x)554 def __lt__(self, other):555 try:556 return self.x < other.x557 except AttributeError:558 return NotImplemented559 assertTotallyOrdered will check that instances can be ordered correctly.560 For example,561 self.assertTotallyOrdered(562 [None], # None should come before everything else.563 [1], # Integers sort earlier.564 ['foo'], # As do strings.565 [A(1, 'a')],566 [A(2, 'b')], # 2 is after 1.567 [A(2, 'c'), A(2, 'd')], # The second argument is irrelevant.568 [A(3, 'z')])569 Args:570 groups: A list of groups of elements. Each group of elements is a list571 of objects that are equal. The elements in each group must be less than572 the elements in the group after it. For example, these groups are573 totally ordered: [None], [1], [2, 2], [3].574 """575 def CheckOrder(small, big):576 """Ensures small is ordered before big."""577 self.assertFalse(small == big,578 '%r unexpectedly equals %r' % (small, big))579 self.assertTrue(small != big,580 '%r unexpectedly equals %r' % (small, big))581 self.assertLess(small, big)582 self.assertFalse(big < small,583 '%r unexpectedly less than %r' % (big, small))584 self.assertLessEqual(small, big)585 self.assertFalse(big <= small,586 '%r unexpectedly less than or equal to %r'587 % (big, small))588 self.assertGreater(big, small)589 self.assertFalse(small > big,590 '%r unexpectedly greater than %r' % (small, big))591 self.assertGreaterEqual(big, small)592 self.assertFalse(small >= big,593 '%r unexpectedly greater than or equal to %r'594 % (small, big))595 def CheckEqual(a, b):596 """Ensures that a and b are equal."""597 self.assertEqual(a, b)598 self.assertFalse(a != b, '%r unexpectedly equals %r' % (a, b))599 self.assertEqual(hash(a), hash(b),600 'hash %d of %r unexpectedly not equal to hash %d of %r'601 % (hash(a), a, hash(b), b))602 self.assertFalse(a < b, '%r unexpectedly less than %r' % (a, b))603 self.assertFalse(b < a, '%r unexpectedly less than %r' % (b, a))604 self.assertLessEqual(a, b)605 self.assertLessEqual(b, a)606 self.assertFalse(a > b, '%r unexpectedly greater than %r' % (a, b))607 self.assertFalse(b > a, '%r unexpectedly greater than %r' % (b, a))608 self.assertGreaterEqual(a, b)609 self.assertGreaterEqual(b, a)610 # For every combination of elements, check the order of every pair of611 # elements.612 for elements in itertools.product(*groups):613 elements = list(elements)614 for index, small in enumerate(elements[:-1]):615 for big in elements[index + 1:]:616 CheckOrder(small, big)617 # Check that every element in each group is equal.618 for group in groups:619 for a in group:620 CheckEqual(a, a)621 for a, b in itertools.product(group, group):622 CheckEqual(a, b)623 def getRecordedProperties(self):624 """Return any properties that the user has recorded."""625 return self.__recorded_properties626 def recordProperty(self, property_name, property_value):627 """Record an arbitrary property for later use.628 Args:629 property_name: str, name of property to record; must be a valid XML630 attribute name631 property_value: value of property; must be valid XML attribute value632 """633 self.__recorded_properties[property_name] = property_value634 def _getAssertEqualityFunc(self, first, second):635 try:636 return super(TestCase, self)._getAssertEqualityFunc(first, second)637 except AttributeError:638 # This happens if unittest2.TestCase.__init__ was never run. It639 # usually means that somebody created a subclass just for the640 # assertions and has overriden __init__. "assertTrue" is a safe641 # value that will not make __init__ raise a ValueError (this is642 # a bit hacky).643 test_method = getattr(self, '_testMethodName', 'assertTrue')644 super(TestCase, self).__init__(test_method)645 return super(TestCase, self)._getAssertEqualityFunc(first, second)646# This is not really needed here, but some unrelated code calls this647# function.648# TODO(user): sort it out.649def _SortedListDifference(expected, actual):650 """Finds elements in only one or the other of two, sorted input lists.651 Returns a two-element tuple of lists. The first list contains those652 elements in the "expected" list but not in the "actual" list, and the653 second contains those elements in the "actual" list but not in the654 "expected" list. Duplicate elements in either input list are ignored.655 Args:656 expected: The list we expected.657 actual: The list we actualy got.658 Returns:659 (missing, unexpected)660 missing: items in expected that are not in actual.661 unexpected: items in actual that are not in expected.662 """663 i = j = 0...
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!!