Best Python code snippet using autotest_python
unittest.py
Source:unittest.py
...72 self.obj = obj73 def __lt__(self, other):74 return mycmp(self.obj, other.obj) == -175 return K76def _EmulateWith(context, func):77 context.__enter__()78 try:79 func()80 except:81 if not context.__exit__(sys.exc_type, sys.exc_value, sys.exc_traceback):82 raise83 else:84 context.__exit__(None, None, None)85##############################################################################86# Test framework core87##############################################################################88def _strclass(cls):89 return "%s.%s" % (cls.__module__, cls.__name__)90class SkipTest(Exception):91 """92 Raise this exception in a test to skip it.93 Usually you can use TestResult.skip() or one of the skipping decorators94 instead of raising this directly.95 """96 pass97class _ExpectedFailure(Exception):98 """99 Raise this when a test is expected to fail.100 This is an implementation detail.101 """102 def __init__(self, exc_info):103 super(_ExpectedFailure, self).__init__()104 self.exc_info = exc_info105class _UnexpectedSuccess(Exception):106 """107 The test was supposed to fail, but it didn't!108 """109 pass110def _id(obj):111 return obj112def skip(reason):113 """114 Unconditionally skip a test.115 """116 def decorator(test_item):117 if isinstance(test_item, type) and issubclass(test_item, TestCase):118 test_item.__unittest_skip__ = True119 test_item.__unittest_skip_why__ = reason120 return test_item121 @functools.wraps(test_item)122 def skip_wrapper(*args, **kwargs):123 raise SkipTest(reason)124 return skip_wrapper125 return decorator126def skipIf(condition, reason):127 """128 Skip a test if the condition is true.129 """130 if condition:131 return skip(reason)132 return _id133def skipUnless(condition, reason):134 """135 Skip a test unless the condition is true.136 """137 if not condition:138 return skip(reason)139 return _id140def expectedFailure(func):141 @functools.wraps(func)142 def wrapper(*args, **kwargs):143 try:144 func(*args, **kwargs)145 except Exception:146 raise _ExpectedFailure(sys.exc_info())147 raise _UnexpectedSuccess148 return wrapper149__unittest = 1150class TestResult(object):151 """Holder for test result information.152 Test results are automatically managed by the TestCase and TestSuite153 classes, and do not need to be explicitly manipulated by writers of tests.154 Each instance holds the total number of tests run, and collections of155 failures and errors that occurred among those test runs. The collections156 contain tuples of (testcase, exceptioninfo), where exceptioninfo is the157 formatted traceback of the error that occurred.158 """159 def __init__(self):160 self.failures = []161 self.errors = []162 self.testsRun = 0163 self.skipped = []164 self.expectedFailures = []165 self.unexpectedSuccesses = []166 self.shouldStop = False167 def startTest(self, test):168 "Called when the given test is about to be run"169 self.testsRun = self.testsRun + 1170 def stopTest(self, test):171 "Called when the given test has been run"172 pass173 def addError(self, test, err):174 """Called when an error has occurred. 'err' is a tuple of values as175 returned by sys.exc_info().176 """177 self.errors.append((test, self._exc_info_to_string(err, test)))178 def addFailure(self, test, err):179 """Called when an error has occurred. 'err' is a tuple of values as180 returned by sys.exc_info()."""181 self.failures.append((test, self._exc_info_to_string(err, test)))182 def addSuccess(self, test):183 "Called when a test has completed successfully"184 pass185 def addSkip(self, test, reason):186 """Called when a test is skipped."""187 self.skipped.append((test, reason))188 def addExpectedFailure(self, test, err):189 """Called when an expected failure/error occured."""190 self.expectedFailures.append(191 (test, self._exc_info_to_string(err, test)))192 def addUnexpectedSuccess(self, test):193 """Called when a test was expected to fail, but succeed."""194 self.unexpectedSuccesses.append(test)195 def wasSuccessful(self):196 "Tells whether or not this result was a success"197 return len(self.failures) == len(self.errors) == 0198 def stop(self):199 "Indicates that the tests should be aborted"200 self.shouldStop = True201 def _exc_info_to_string(self, err, test):202 """Converts a sys.exc_info()-style tuple of values into a string."""203 exctype, value, tb = err204 # Skip test runner traceback levels205 while tb and self._is_relevant_tb_level(tb):206 tb = tb.tb_next207 if exctype is test.failureException:208 # Skip assert*() traceback levels209 length = self._count_relevant_tb_levels(tb)210 return ''.join(traceback.format_exception(exctype, value, tb, length))211 return ''.join(traceback.format_exception(exctype, value, tb))212 def _is_relevant_tb_level(self, tb):213 return '__unittest' in tb.tb_frame.f_globals214 def _count_relevant_tb_levels(self, tb):215 length = 0216 while tb and not self._is_relevant_tb_level(tb):217 length += 1218 tb = tb.tb_next219 return length220 def __repr__(self):221 return "<%s run=%i errors=%i failures=%i>" % \222 (_strclass(self.__class__), self.testsRun, len(self.errors),223 len(self.failures))224class _AssertRaisesContext(object):225 """A context manager used to implement TestCase.assertRaises* methods."""226 def __init__(self, expected, test_case, expected_regexp=None):227 self.expected = expected228 self.failureException = test_case.failureException229 self.expected_regex = expected_regexp230 def __enter__(self):231 pass232 def __exit__(self, exc_type, exc_value, tb):233 if exc_type is None:234 try:235 exc_name = self.expected.__name__236 except AttributeError:237 exc_name = str(self.expected)238 raise self.failureException(239 "%s not raised" % exc_name)240 if not issubclass(exc_type, self.expected):241 # let unexpected exceptions pass through242 return False243 if self.expected_regex is None:244 return True245 expected_regexp = self.expected_regex246 if isinstance(expected_regexp, basestring):247 expected_regexp = re.compile(expected_regexp)248 if not expected_regexp.search(str(exc_value)):249 raise self.failureException('"%s" does not match "%s"' %250 (expected_regexp.pattern, str(exc_value)))251 return True252class _AssertWrapper(object):253 """Wrap entries in the _type_equality_funcs registry to make them deep254 copyable."""255 def __init__(self, function):256 self.function = function257 def __deepcopy__(self, memo):258 memo[id(self)] = self259class TestCase(object):260 """A class whose instances are single test cases.261 By default, the test code itself should be placed in a method named262 'runTest'.263 If the fixture may be used for many test cases, create as264 many test methods as are needed. When instantiating such a TestCase265 subclass, specify in the constructor arguments the name of the test method266 that the instance is to execute.267 Test authors should subclass TestCase for their own tests. Construction268 and deconstruction of the test's environment ('fixture') can be269 implemented by overriding the 'setUp' and 'tearDown' methods respectively.270 If it is necessary to override the __init__ method, the base class271 __init__ method must always be called. It is important that subclasses272 should not change the signature of their __init__ method, since instances273 of the classes are instantiated automatically by parts of the framework274 in order to be run.275 """276 # This attribute determines which exception will be raised when277 # the instance's assertion methods fail; test methods raising this278 # exception will be deemed to have 'failed' rather than 'errored'279 failureException = AssertionError280 # This attribute determines whether long messages (including repr of281 # objects used in assert methods) will be printed on failure in *addition*282 # to any explicit message passed.283 longMessage = False284 def __init__(self, methodName='runTest'):285 """Create an instance of the class that will use the named test286 method when executed. Raises a ValueError if the instance does287 not have a method with the specified name.288 """289 self._testMethodName = methodName290 try:291 testMethod = getattr(self, methodName)292 except AttributeError:293 raise ValueError("no such test method in %s: %s" % \294 (self.__class__, methodName))295 self._testMethodDoc = testMethod.__doc__296 # Map types to custom assertEqual functions that will compare297 # instances of said type in more detail to generate a more useful298 # error message.299 self._type_equality_funcs = {}300 self.addTypeEqualityFunc(dict, self.assertDictEqual)301 self.addTypeEqualityFunc(list, self.assertListEqual)302 self.addTypeEqualityFunc(tuple, self.assertTupleEqual)303 self.addTypeEqualityFunc(set, self.assertSetEqual)304 self.addTypeEqualityFunc(frozenset, self.assertSetEqual)305 def addTypeEqualityFunc(self, typeobj, function):306 """Add a type specific assertEqual style function to compare a type.307 This method is for use by TestCase subclasses that need to register308 their own type equality functions to provide nicer error messages.309 Args:310 typeobj: The data type to call this function on when both values311 are of the same type in assertEqual().312 function: The callable taking two arguments and an optional313 msg= argument that raises self.failureException with a314 useful error message when the two arguments are not equal.315 """316 self._type_equality_funcs[typeobj] = _AssertWrapper(function)317 def setUp(self):318 "Hook method for setting up the test fixture before exercising it."319 pass320 def tearDown(self):321 "Hook method for deconstructing the test fixture after testing it."322 pass323 def countTestCases(self):324 return 1325 def defaultTestResult(self):326 return TestResult()327 def shortDescription(self):328 """Returns both the test method name and first line of its docstring.329 If no docstring is given, only returns the method name.330 This method overrides unittest.TestCase.shortDescription(), which331 only returns the first line of the docstring, obscuring the name332 of the test upon failure.333 """334 desc = str(self)335 doc_first_line = None336 if self._testMethodDoc:337 doc_first_line = self._testMethodDoc.split("\n")[0].strip()338 if doc_first_line:339 desc = '\n'.join((desc, doc_first_line))340 return desc341 def id(self):342 return "%s.%s" % (_strclass(self.__class__), self._testMethodName)343 def __eq__(self, other):344 if type(self) is not type(other):345 return NotImplemented346 return self._testMethodName == other._testMethodName347 def __ne__(self, other):348 return not self == other349 def __hash__(self):350 return hash((type(self), self._testMethodName))351 def __str__(self):352 return "%s (%s)" % (self._testMethodName, _strclass(self.__class__))353 def __repr__(self):354 return "<%s testMethod=%s>" % \355 (_strclass(self.__class__), self._testMethodName)356 def run(self, result=None):357 if result is None:358 result = self.defaultTestResult()359 result.startTest(self)360 testMethod = getattr(self, self._testMethodName)361 try:362 try:363 self.setUp()364 except SkipTest, e:365 result.addSkip(self, str(e))366 return367 except Exception:368 result.addError(self, sys.exc_info())369 return370 success = False371 try:372 testMethod()373 except self.failureException:374 result.addFailure(self, sys.exc_info())375 except _ExpectedFailure, e:376 result.addExpectedFailure(self, e.exc_info)377 except _UnexpectedSuccess:378 result.addUnexpectedSuccess(self)379 except SkipTest, e:380 result.addSkip(self, str(e))381 except Exception:382 result.addError(self, sys.exc_info())383 else:384 success = True385 try:386 self.tearDown()387 except Exception:388 result.addError(self, sys.exc_info())389 success = False390 if success:391 result.addSuccess(self)392 finally:393 result.stopTest(self)394 def __call__(self, *args, **kwds):395 return self.run(*args, **kwds)396 def debug(self):397 """Run the test without collecting errors in a TestResult"""398 self.setUp()399 getattr(self, self._testMethodName)()400 self.tearDown()401 def skipTest(self, reason):402 """Skip this test."""403 raise SkipTest(reason)404 def fail(self, msg=None):405 """Fail immediately, with the given message."""406 raise self.failureException(msg)407 def assertFalse(self, expr, msg=None):408 "Fail the test if the expression is true."409 if expr:410 msg = self._formatMessage(msg, "%r is not False" % expr)411 raise self.failureException(msg)412 def assertTrue(self, expr, msg=None):413 """Fail the test unless the expression is true."""414 if not expr:415 msg = self._formatMessage(msg, "%r is not True" % expr)416 raise self.failureException(msg)417 def _formatMessage(self, msg, standardMsg):418 """Honour the longMessage attribute when generating failure messages.419 If longMessage is False this means:420 * Use only an explicit message if it is provided421 * Otherwise use the standard message for the assert422 If longMessage is True:423 * Use the standard message424 * If an explicit message is provided, plus ' : ' and the explicit message425 """426 if not self.longMessage:427 return msg or standardMsg428 if msg is None:429 return standardMsg430 return standardMsg + ' : ' + msg431 def assertRaises(self, excClass, callableObj=None, *args, **kwargs):432 """Fail unless an exception of class excClass is thrown433 by callableObj when invoked with arguments args and keyword434 arguments kwargs. If a different type of exception is435 thrown, it will not be caught, and the test case will be436 deemed to have suffered an error, exactly as for an437 unexpected exception.438 If called with callableObj omitted or None, will return a439 context object used like this::440 with self.assertRaises(some_error_class):441 do_something()442 """443 context = _AssertRaisesContext(excClass, self)444 if callableObj is None:445 return context446 # XXX (garrcoop): `with context' isn't supported lexigram with 2.4/2.5,447 # even though PEP 343 (sort of) implies that based on the publishing448 # date. There may be another PEP which changed the syntax...449 _EmulateWith(context, lambda: callableObj(*args, **kwargs))450 def _getAssertEqualityFunc(self, first, second):451 """Get a detailed comparison function for the types of the two args.452 Returns: A callable accepting (first, second, msg=None) that will453 raise a failure exception if first != second with a useful human454 readable error message for those types.455 """456 #457 # NOTE(gregory.p.smith): I considered isinstance(first, type(second))458 # and vice versa. I opted for the conservative approach in case459 # subclasses are not intended to be compared in detail to their super460 # class instances using a type equality func. This means testing461 # subtypes won't automagically use the detailed comparison. Callers462 # should use their type specific assertSpamEqual method to compare463 # subclasses if the detailed comparison is desired and appropriate.464 # See the discussion in http://bugs.python.org/issue2578.465 #466 if type(first) is type(second):467 asserter = self._type_equality_funcs.get(type(first))468 if asserter is not None:469 return asserter.function470 return self._baseAssertEqual471 def _baseAssertEqual(self, first, second, msg=None):472 """The default assertEqual implementation, not type specific."""473 if not first == second:474 standardMsg = '%r != %r' % (first, second)475 msg = self._formatMessage(msg, standardMsg)476 raise self.failureException(msg)477 def assertEqual(self, first, second, msg=None):478 """Fail if the two objects are unequal as determined by the '=='479 operator.480 """481 assertion_func = self._getAssertEqualityFunc(first, second)482 assertion_func(first, second, msg=msg)483 def assertNotEqual(self, first, second, msg=None):484 """Fail if the two objects are equal as determined by the '=='485 operator.486 """487 if not first != second:488 msg = self._formatMessage(msg, '%r == %r' % (first, second))489 raise self.failureException(msg)490 def assertAlmostEqual(self, first, second, places=7, msg=None):491 """Fail if the two objects are unequal as determined by their492 difference rounded to the given number of decimal places493 (default 7) and comparing to zero.494 Note that decimal places (from zero) are usually not the same495 as significant digits (measured from the most signficant digit).496 """497 if round(abs(second-first), places) != 0:498 standardMsg = '%r != %r within %r places' % (first, second, places)499 msg = self._formatMessage(msg, standardMsg)500 raise self.failureException(msg)501 def assertNotAlmostEqual(self, first, second, places=7, msg=None):502 """Fail if the two objects are equal as determined by their503 difference rounded to the given number of decimal places504 (default 7) and comparing to zero.505 Note that decimal places (from zero) are usually not the same506 as significant digits (measured from the most signficant digit).507 """508 if round(abs(second-first), places) == 0:509 standardMsg = '%r == %r within %r places' % (first, second, places)510 msg = self._formatMessage(msg, standardMsg)511 raise self.failureException(msg)512 # Synonyms for assertion methods513 # The plurals are undocumented. Keep them that way to discourage use.514 # Do not add more. Do not remove.515 # Going through a deprecation cycle on these would annoy many people.516 assertEquals = assertEqual517 assertNotEquals = assertNotEqual518 assertAlmostEquals = assertAlmostEqual519 assertNotAlmostEquals = assertNotAlmostEqual520 assert_ = assertTrue521 # These fail* assertion method names are pending deprecation and will522 # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578523 def _deprecate(original_func):524 def deprecated_func(*args, **kwargs):525 warnings.warn(526 'Please use %s instead.' % original_func.__name__,527 PendingDeprecationWarning, 2)528 return original_func(*args, **kwargs)529 return deprecated_func530 failUnlessEqual = _deprecate(assertEqual)531 failIfEqual = _deprecate(assertNotEqual)532 failUnlessAlmostEqual = _deprecate(assertAlmostEqual)533 failIfAlmostEqual = _deprecate(assertNotAlmostEqual)534 failUnless = _deprecate(assertTrue)535 failUnlessRaises = _deprecate(assertRaises)536 failIf = _deprecate(assertFalse)537 def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):538 """An equality assertion for ordered sequences (like lists and tuples).539 For the purposes of this function, a valid orderd sequence type is one540 which can be indexed, has a length, and has an equality operator.541 Args:542 seq1: The first sequence to compare.543 seq2: The second sequence to compare.544 seq_type: The expected datatype of the sequences, or None if no545 datatype should be enforced.546 msg: Optional message to use on failure instead of a list of547 differences.548 """549 if seq_type != None:550 seq_type_name = seq_type.__name__551 if not isinstance(seq1, seq_type):552 raise self.failureException('First sequence is not a %s: %r'553 % (seq_type_name, seq1))554 if not isinstance(seq2, seq_type):555 raise self.failureException('Second sequence is not a %s: %r'556 % (seq_type_name, seq2))557 else:558 seq_type_name = "sequence"559 differing = None560 try:561 len1 = len(seq1)562 except (TypeError, NotImplementedError):563 differing = 'First %s has no length. Non-sequence?' % (564 seq_type_name)565 if differing is None:566 try:567 len2 = len(seq2)568 except (TypeError, NotImplementedError):569 differing = 'Second %s has no length. Non-sequence?' % (570 seq_type_name)571 if differing is None:572 if seq1 == seq2:573 return574 for i in xrange(min(len1, len2)):575 try:576 item1 = seq1[i]577 except (TypeError, IndexError, NotImplementedError):578 differing = ('Unable to index element %d of first %s\n' %579 (i, seq_type_name))580 break581 try:582 item2 = seq2[i]583 except (TypeError, IndexError, NotImplementedError):584 differing = ('Unable to index element %d of second %s\n' %585 (i, seq_type_name))586 break587 if item1 != item2:588 differing = ('First differing element %d:\n%s\n%s\n' %589 (i, item1, item2))590 break591 else:592 if (len1 == len2 and seq_type is None and593 type(seq1) != type(seq2)):594 # The sequences are the same, but have differing types.595 return596 # A catch-all message for handling arbitrary user-defined597 # sequences.598 differing = '%ss differ:\n' % seq_type_name.capitalize()599 if len1 > len2:600 differing = ('First %s contains %d additional '601 'elements.\n' % (seq_type_name, len1 - len2))602 try:603 differing += ('First extra element %d:\n%s\n' %604 (len2, seq1[len2]))605 except (TypeError, IndexError, NotImplementedError):606 differing += ('Unable to index element %d '607 'of first %s\n' % (len2, seq_type_name))608 elif len1 < len2:609 differing = ('Second %s contains %d additional '610 'elements.\n' % (seq_type_name, len2 - len1))611 try:612 differing += ('First extra element %d:\n%s\n' %613 (len1, seq2[len1]))614 except (TypeError, IndexError, NotImplementedError):615 differing += ('Unable to index element %d '616 'of second %s\n' % (len1, seq_type_name))617 standardMsg = differing + '\n'.join(difflib.ndiff(pprint.pformat(seq1).splitlines(),618 pprint.pformat(seq2).splitlines()))619 msg = self._formatMessage(msg, standardMsg)620 self.fail(msg)621 def assertListEqual(self, list1, list2, msg=None):622 """A list-specific equality assertion.623 Args:624 list1: The first list to compare.625 list2: The second list to compare.626 msg: Optional message to use on failure instead of a list of627 differences.628 """629 self.assertSequenceEqual(list1, list2, msg, seq_type=list)630 def assertTupleEqual(self, tuple1, tuple2, msg=None):631 """A tuple-specific equality assertion.632 Args:633 tuple1: The first tuple to compare.634 tuple2: The second tuple to compare.635 msg: Optional message to use on failure instead of a list of636 differences.637 """638 self.assertSequenceEqual(tuple1, tuple2, msg, seq_type=tuple)639 def assertSetEqual(self, set1, set2, msg=None):640 """A set-specific equality assertion.641 Args:642 set1: The first set to compare.643 set2: The second set to compare.644 msg: Optional message to use on failure instead of a list of645 differences.646 For more general containership equality, assertSameElements will work647 with things other than sets. This uses ducktyping to support648 different types of sets, and is optimized for sets specifically649 (parameters must support a difference method).650 """651 try:652 difference1 = set1.difference(set2)653 except TypeError, e:654 self.fail('invalid type when attempting set difference: %s' % e)655 except AttributeError, e:656 self.fail('first argument does not support set difference: %s' % e)657 try:658 difference2 = set2.difference(set1)659 except TypeError, e:660 self.fail('invalid type when attempting set difference: %s' % e)661 except AttributeError, e:662 self.fail('second argument does not support set difference: %s' % e)663 if not (difference1 or difference2):664 return665 lines = []666 if difference1:667 lines.append('Items in the first set but not the second:')668 for item in difference1:669 lines.append(repr(item))670 if difference2:671 lines.append('Items in the second set but not the first:')672 for item in difference2:673 lines.append(repr(item))674 standardMsg = '\n'.join(lines)675 self.fail(self._formatMessage(msg, standardMsg))676 def assertIn(self, member, container, msg=None):677 """Just like self.assertTrue(a in b), but with a nicer default message."""678 if member not in container:679 standardMsg = '%r not found in %r' % (member, container)680 self.fail(self._formatMessage(msg, standardMsg))681 def assertNotIn(self, member, container, msg=None):682 """Just like self.assertTrue(a not in b), but with a nicer default message."""683 if member in container:684 standardMsg = '%r unexpectedly found in %r' % (member, container)685 self.fail(self._formatMessage(msg, standardMsg))686 def assertIs(self, expr1, expr2, msg=None):687 """Just like self.assertTrue(a is b), but with a nicer default message."""688 if expr1 is not expr2:689 standardMsg = '%r is not %r' % (expr1, expr2)690 self.fail(self._formatMessage(msg, standardMsg))691 def assertIsNot(self, expr1, expr2, msg=None):692 """Just like self.assertTrue(a is not b), but with a nicer default message."""693 if expr1 is expr2:694 standardMsg = 'unexpectedly identical: %r' % (expr1,)695 self.fail(self._formatMessage(msg, standardMsg))696 def assertDictEqual(self, d1, d2, msg=None):697 self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')698 self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')699 if d1 != d2:700 standardMsg = ('\n' + '\n'.join(difflib.ndiff(701 pprint.pformat(d1).splitlines(),702 pprint.pformat(d2).splitlines())))703 self.fail(self._formatMessage(msg, standardMsg))704 def assertDictContainsSubset(self, expected, actual, msg=None):705 """Checks whether actual is a superset of expected."""706 missing = []707 mismatched = []708 for key, value in expected.iteritems():709 if key not in actual:710 missing.append(key)711 elif value != actual[key]:712 mismatched.append('%s, expected: %s, actual: %s' % (key, value, actual[key]))713 if not (missing or mismatched):714 return715 standardMsg = ''716 if missing:717 standardMsg = 'Missing: %r' % ','.join(missing)718 if mismatched:719 if standardMsg:720 standardMsg += '; '721 standardMsg += 'Mismatched values: %s' % ','.join(mismatched)722 self.fail(self._formatMessage(msg, standardMsg))723 def assertSameElements(self, expected_seq, actual_seq, msg=None):724 """An unordered sequence specific comparison.725 Raises with an error message listing which elements of expected_seq726 are missing from actual_seq and vice versa if any.727 """728 try:729 expected = set(expected_seq)730 actual = set(actual_seq)731 missing = list(expected.difference(actual))732 unexpected = list(actual.difference(expected))733 missing.sort()734 unexpected.sort()735 except TypeError:736 # Fall back to slower list-compare if any of the objects are737 # not hashable.738 expected = list(expected_seq)739 actual = list(actual_seq)740 expected.sort()741 actual.sort()742 missing, unexpected = _SortedListDifference(expected, actual)743 errors = []744 if missing:745 errors.append('Expected, but missing:\n %r' % missing)746 if unexpected:747 errors.append('Unexpected, but present:\n %r' % unexpected)748 if errors:749 standardMsg = '\n'.join(errors)750 self.fail(self._formatMessage(msg, standardMsg))751 def assertMultiLineEqual(self, first, second, msg=None):752 """Assert that two multi-line strings are equal."""753 self.assert_(isinstance(first, basestring), (754 'First argument is not a string'))755 self.assert_(isinstance(second, basestring), (756 'Second argument is not a string'))757 if first != second:758 standardMsg = '\n' + ''.join(difflib.ndiff(first.splitlines(True), second.splitlines(True)))759 self.fail(self._formatMessage(msg, standardMsg))760 def assertLess(self, a, b, msg=None):761 """Just like self.assertTrue(a < b), but with a nicer default message."""762 if not a < b:763 standardMsg = '%r not less than %r' % (a, b)764 self.fail(self._formatMessage(msg, standardMsg))765 def assertLessEqual(self, a, b, msg=None):766 """Just like self.assertTrue(a <= b), but with a nicer default message."""767 if not a <= b:768 standardMsg = '%r not less than or equal to %r' % (a, b)769 self.fail(self._formatMessage(msg, standardMsg))770 def assertGreater(self, a, b, msg=None):771 """Just like self.assertTrue(a > b), but with a nicer default message."""772 if not a > b:773 standardMsg = '%r not greater than %r' % (a, b)774 self.fail(self._formatMessage(msg, standardMsg))775 def assertGreaterEqual(self, a, b, msg=None):776 """Just like self.assertTrue(a >= b), but with a nicer default message."""777 if not a >= b:778 standardMsg = '%r not greater than or equal to %r' % (a, b)779 self.fail(self._formatMessage(msg, standardMsg))780 def assertIsNone(self, obj, msg=None):781 """Same as self.assertTrue(obj is None), with a nicer default message."""782 if obj is not None:783 standardMsg = '%r is not None' % obj784 self.fail(self._formatMessage(msg, standardMsg))785 def assertIsNotNone(self, obj, msg=None):786 """Included for symmetry with assertIsNone."""787 if obj is None:788 standardMsg = 'unexpectedly None'789 self.fail(self._formatMessage(msg, standardMsg))790 def assertRaisesRegexp(self, expected_exception, expected_regexp,791 callable_obj=None, *args, **kwargs):792 """Asserts that the message in a raised exception matches a regexp.793 Args:794 expected_exception: Exception class expected to be raised.795 expected_regexp: Regexp (re pattern object or string) expected796 to be found in error message.797 callable_obj: Function to be called.798 args: Extra args.799 kwargs: Extra kwargs.800 """801 context = _AssertRaisesContext(expected_exception, self, expected_regexp)802 if callable_obj is None:803 return context804 # XXX (garrcoop): See comment above about `with context'.805 _EmulateWith(context, lambda: callable_obj(*args, **kwargs))806 def assertRegexpMatches(self, text, expected_regex, msg=None):807 if isinstance(expected_regex, basestring):808 expected_regex = re.compile(expected_regex)809 if not expected_regex.search(text):810 msg = msg or "Regexp didn't match"811 msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)812 raise self.failureException(msg)813def _SortedListDifference(expected, actual):814 """Finds elements in only one or the other of two, sorted input lists.815 Returns a two-element tuple of lists. The first list contains those816 elements in the "expected" list but not in the "actual" list, and the817 second contains those elements in the "actual" list but not in the818 "expected" list. Duplicate elements in either input list are ignored.819 """...
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!!