Python单元测试unittest加载方式之二:加载测试套件_python 测试套加载环境文件-程序员宅基地

技术标签: 测试  单元测试  unittest  Python  

Python单元测试unittest加载方式之二:加载测试套件


在运用测试套件进行单元测试之前,还是稍微研究一下unittest模块的内容有哪些,其大概的运行方式是什么样的。而后在给出根据各种情况如何制定单元测试套件。


一、查看unittest模块有哪些成员

>>> import unittest
>>> dir(unittest)
['BaseTestSuite', 'FunctionTestCase', 'SkipTest', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult', 'TestSuite', 'TextTestResult', 'TextTestRunner', '_TextTestResult', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', '__unittest', 'case', 'defaultTestLoader', 'expectedFailure', 'findTestCases', 'getTestCaseNames', 'installHandler', 'loader', 'main', 'makeSuite', 'registerResult', 'removeHandler', 'removeResult', 'result', 'runner', 'signals', 'skip', 'skipIf', 'skipUnless', 'suite', 'util']
在IDLE中查看如下图:



可以看到其自身的成员也不是很多,大概包括有:
['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult',
 'TestSuite','TextTestRunner', '_CmpToKey', '_TextTestResult', '_WritelnDecorator',
 'defaultTestLoader','findTestCases', 'getTestCaseNames', 'main', 'makeSuite']


我们来看看他们到底是干什么的?



>>> import unittest
>>> memblist = ['FunctionTestCase', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult',\
 'TestSuite','TextTestRunner', 'defaultTestLoader','findTestCases', 'getTestCaseNames', \
 'main', 'makeSuite']
>>> for memb in memblist:
	cur = getattr(unittest, memb)
	print help(cur)

IDLE中返回的结果为: 待插入

 'FunctionTestCase':函数测试用例,即给一个函数作为参数,返回一个testcase实例,可选参数有set-up,tear-down方法
 'TestCase':所有测试用例的基本类,给一个测试方法的名字,返回一个测试用例实例
 'TestLoader':测试用例加载器,其包括多个加载测试用例的方法。返回一个测试套件
 loadTestsFromModule(self, module)--根据给定的模块实例来获取测试用例套件
 loadTestsFromName(self, name, module=None)
 --根据给定的字符串来获取测试用例套件,字符串可以是模块名,测试类名,测试类中的测试方法名,或者一个可调用的是实例对象
 这个实例对象返回一个测试用例或一个测试套件
 loadTestsFromNames(self, names, module=None) --和上面功能相同,只不过接受的是字符串列表
 loadTestsFromTestCase(self, testCaseClass)--根据给定的测试类,获取其中的所有测试方法,并返回一个测试套件
'TestProgram':命令行进行单元测试的调用方法,作用是执行一个测试用例。其实unittest.main()方法执行的就是这个命令,
而这个类实例时默认加载当前执行的作为测试对象,
原型为 __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=xx, testLoader=xx)
其中module='__main__'就是默认加载自身
'TestResult':测试用例的结果保存实例,通常有测试框架调用
 'TestSuite':组织测试用例的实例,支持测试用例的添加和删除,最终将传递给testRunner进行测试执行
 'TextTestRunner':进行测试用例执行的实例,其中Text的意思是以文本形式显示测试结果。显示测试名称,即完成的测试结果,其过同执行单元测试脚本时添加-v参数
 'defaultTestLoader':其实就是TestLoader
 'findTestCases', 'getTestCaseNames':这个2个就不用解释了
 'main': 其实就是TestProgram
 'makeSuite':通常是由单元测试框架调用的,用于生产testsuite对象的实例

IDLE中返回的结果为:

Help on class FunctionTestCase in module unittest.case:

class FunctionTestCase(TestCase)
 |  A test case that wraps a test function.
 |  
 |  This is useful for slipping pre-existing test functions into the
 |  unittest framework. Optionally, set-up and tidy-up functions can be
 |  supplied. As with TestCase, the tidy-up ('tearDown') function will
 |  always be called if the set-up ('setUp') function ran successfully.
 |  
 |  Method resolution order:
 |      FunctionTestCase
 |      TestCase
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  __eq__(self, other)
 |  
 |  __hash__(self)
 |  
 |  __init__(self, testFunc, setUp=None, tearDown=None, description=None)
 |  
 |  __ne__(self, other)
 |  
 |  __repr__(self)
 |  
 |  __str__(self)
 |  
 |  id(self)
 |  
 |  runTest(self)
 |  
 |  setUp(self)
 |  
 |  shortDescription(self)
 |  
 |  tearDown(self)
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from TestCase:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  addCleanup(self, function, *args, **kwargs)
 |      Add a function, with arguments, to be called when the test is
 |      completed. Functions added are called on a LIFO basis and are
 |      called after tearDown on test failure or success.
 |      
 |      Cleanup items are called even if setUp fails (unlike tearDown).
 |  
 |  addTypeEqualityFunc(self, typeobj, function)
 |      Add a type specific assertEqual style function to compare a type.
 |      
 |      This method is for use by TestCase subclasses that need to register
 |      their own type equality functions to provide nicer error messages.
 |      
 |      Args:
 |          typeobj: The data type to call this function on when both values
 |                  are of the same type in assertEqual().
 |          function: The callable taking two arguments and an optional
 |                  msg= argument that raises self.failureException with a
 |                  useful error message when the two arguments are not equal.
 |  
 |  assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are unequal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is more than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      If the two objects compare equal then they will automatically
 |      compare almost equal.
 |  
 |  assertAlmostEquals = assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are unequal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is more than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      If the two objects compare equal then they will automatically
 |      compare almost equal.
 |  
 |  assertDictContainsSubset(self, expected, actual, msg=None)
 |      Checks whether actual is a superset of expected.
 |  
 |  assertDictEqual(self, d1, d2, msg=None)
 |  
 |  assertEqual(self, first, second, msg=None)
 |      Fail if the two objects are unequal as determined by the '=='
 |      operator.
 |  
 |  assertEquals = assertEqual(self, first, second, msg=None)
 |      Fail if the two objects are unequal as determined by the '=='
 |      operator.
 |  
 |  assertFalse(self, expr, msg=None)
 |      Check that the expression is false.
 |  
 |  assertGreater(self, a, b, msg=None)
 |      Just like self.assertTrue(a > b), but with a nicer default message.
 |  
 |  assertGreaterEqual(self, a, b, msg=None)
 |      Just like self.assertTrue(a >= b), but with a nicer default message.
 |  
 |  assertIn(self, member, container, msg=None)
 |      Just like self.assertTrue(a in b), but with a nicer default message.
 |  
 |  assertIs(self, expr1, expr2, msg=None)
 |      Just like self.assertTrue(a is b), but with a nicer default message.
 |  
 |  assertIsInstance(self, obj, cls, msg=None)
 |      Same as self.assertTrue(isinstance(obj, cls)), with a nicer
 |      default message.
 |  
 |  assertIsNone(self, obj, msg=None)
 |      Same as self.assertTrue(obj is None), with a nicer default message.
 |  
 |  assertIsNot(self, expr1, expr2, msg=None)
 |      Just like self.assertTrue(a is not b), but with a nicer default message.
 |  
 |  assertIsNotNone(self, obj, msg=None)
 |      Included for symmetry with assertIsNone.
 |  
 |  assertItemsEqual(self, expected_seq, actual_seq, msg=None)
 |      An unordered sequence specific comparison. It asserts that
 |      actual_seq and expected_seq have the same element counts.
 |      Equivalent to::
 |      
 |          self.assertEqual(Counter(iter(actual_seq)),
 |                           Counter(iter(expected_seq)))
 |      
 |      Asserts that each element has the same count in both sequences.
 |      Example:
 |          - [0, 1, 1] and [1, 0, 1] compare equal.
 |          - [0, 0, 1] and [0, 1] compare unequal.
 |  
 |  assertLess(self, a, b, msg=None)
 |      Just like self.assertTrue(a < b), but with a nicer default message.
 |  
 |  assertLessEqual(self, a, b, msg=None)
 |      Just like self.assertTrue(a <= b), but with a nicer default message.
 |  
 |  assertListEqual(self, list1, list2, msg=None)
 |      A list-specific equality assertion.
 |      
 |      Args:
 |          list1: The first list to compare.
 |          list2: The second list to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assertMultiLineEqual(self, first, second, msg=None)
 |      Assert that two multi-line strings are equal.
 |  
 |  assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are equal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is less than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      Objects that are equal automatically fail.
 |  
 |  assertNotAlmostEquals = assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are equal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is less than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      Objects that are equal automatically fail.
 |  
 |  assertNotEqual(self, first, second, msg=None)
 |      Fail if the two objects are equal as determined by the '!='
 |      operator.
 |  
 |  assertNotEquals = assertNotEqual(self, first, second, msg=None)
 |      Fail if the two objects are equal as determined by the '!='
 |      operator.
 |  
 |  assertNotIn(self, member, container, msg=None)
 |      Just like self.assertTrue(a not in b), but with a nicer default message.
 |  
 |  assertNotIsInstance(self, obj, cls, msg=None)
 |      Included for symmetry with assertIsInstance.
 |  
 |  assertNotRegexpMatches(self, text, unexpected_regexp, msg=None)
 |      Fail the test if the text matches the regular expression.
 |  
 |  assertRaises(self, excClass, callableObj=None, *args, **kwargs)
 |      Fail unless an exception of class excClass is raised
 |      by callableObj when invoked with arguments args and keyword
 |      arguments kwargs. If a different type of exception is
 |      raised, it will not be caught, and the test case will be
 |      deemed to have suffered an error, exactly as for an
 |      unexpected exception.
 |      
 |      If called with callableObj omitted or None, will return a
 |      context object used like this::
 |      
 |           with self.assertRaises(SomeException):
 |               do_something()
 |      
 |      The context manager keeps a reference to the exception as
 |      the 'exception' attribute. This allows you to inspect the
 |      exception after the assertion::
 |      
 |          with self.assertRaises(SomeException) as cm:
 |              do_something()
 |          the_exception = cm.exception
 |          self.assertEqual(the_exception.error_code, 3)
 |  
 |  assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs)
 |      Asserts that the message in a raised exception matches a regexp.
 |      
 |      Args:
 |          expected_exception: Exception class expected to be raised.
 |          expected_regexp: Regexp (re pattern object or string) expected
 |                  to be found in error message.
 |          callable_obj: Function to be called.
 |          args: Extra args.
 |          kwargs: Extra kwargs.
 |  
 |  assertRegexpMatches(self, text, expected_regexp, msg=None)
 |      Fail the test unless the text matches the regular expression.
 |  
 |  assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
 |      An equality assertion for ordered sequences (like lists and tuples).
 |      
 |      For the purposes of this function, a valid ordered sequence type is one
 |      which can be indexed, has a length, and has an equality operator.
 |      
 |      Args:
 |          seq1: The first sequence to compare.
 |          seq2: The second sequence to compare.
 |          seq_type: The expected datatype of the sequences, or None if no
 |                  datatype should be enforced.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assertSetEqual(self, set1, set2, msg=None)
 |      A set-specific equality assertion.
 |      
 |      Args:
 |          set1: The first set to compare.
 |          set2: The second set to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |      
 |      assertSetEqual uses ducktyping to support different types of sets, and
 |      is optimized for sets specifically (parameters must support a
 |      difference method).
 |  
 |  assertTrue(self, expr, msg=None)
 |      Check that the expression is true.
 |  
 |  assertTupleEqual(self, tuple1, tuple2, msg=None)
 |      A tuple-specific equality assertion.
 |      
 |      Args:
 |          tuple1: The first tuple to compare.
 |          tuple2: The second tuple to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assert_ = assertTrue(self, expr, msg=None)
 |      Check that the expression is true.
 |  
 |  countTestCases(self)
 |  
 |  debug(self)
 |      Run the test without collecting errors in a TestResult
 |  
 |  defaultTestResult(self)
 |  
 |  doCleanups(self)
 |      Execute all cleanup functions. Normally called for you after
 |      tearDown.
 |  
 |  fail(self, msg=None)
 |      Fail immediately, with the given message.
 |  
 |  failIf = deprecated_func(*args, **kwargs)
 |  
 |  failIfAlmostEqual = deprecated_func(*args, **kwargs)
 |  
 |  failIfEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnless = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessAlmostEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessRaises = deprecated_func(*args, **kwargs)
 |  
 |  run(self, result=None)
 |  
 |  skipTest(self, reason)
 |      Skip this test.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods inherited from TestCase:
 |  
 |  setUpClass(cls) from __builtin__.type
 |      Hook method for setting up class fixture before running tests in the class.
 |  
 |  tearDownClass(cls) from __builtin__.type
 |      Hook method for deconstructing the class fixture after running all tests in the class.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from TestCase:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from TestCase:
 |  
 |  failureException = <type 'exceptions.AssertionError'>
 |      Assertion failed.
 |  
 |  longMessage = False
 |  
 |  maxDiff = 640

None
Help on class TestCase in module unittest.case:

class TestCase(__builtin__.object)
 |  A class whose instances are single test cases.
 |  
 |  By default, the test code itself should be placed in a method named
 |  'runTest'.
 |  
 |  If the fixture may be used for many test cases, create as
 |  many test methods as are needed. When instantiating such a TestCase
 |  subclass, specify in the constructor arguments the name of the test method
 |  that the instance is to execute.
 |  
 |  Test authors should subclass TestCase for their own tests. Construction
 |  and deconstruction of the test's environment ('fixture') can be
 |  implemented by overriding the 'setUp' and 'tearDown' methods respectively.
 |  
 |  If it is necessary to override the __init__ method, the base class
 |  __init__ method must always be called. It is important that subclasses
 |  should not change the signature of their __init__ method, since instances
 |  of the classes are instantiated automatically by parts of the framework
 |  in order to be run.
 |  
 |  When subclassing TestCase, you can set these attributes:
 |  * failureException: determines which exception will be raised when
 |      the instance's assertion methods fail; test methods raising this
 |      exception will be deemed to have 'failed' rather than 'errored'.
 |  * longMessage: determines whether long messages (including repr of
 |      objects used in assert methods) will be printed on failure in *addition*
 |      to any explicit message passed.
 |  * maxDiff: sets the maximum length of a diff in failure messages
 |      by assert methods using difflib. It is looked up as an instance
 |      attribute so can be configured by individual tests if required.
 |  
 |  Methods defined here:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  __eq__(self, other)
 |  
 |  __hash__(self)
 |  
 |  __init__(self, methodName='runTest')
 |      Create an instance of the class that will use the named test
 |      method when executed. Raises a ValueError if the instance does
 |      not have a method with the specified name.
 |  
 |  __ne__(self, other)
 |  
 |  __repr__(self)
 |  
 |  __str__(self)
 |  
 |  addCleanup(self, function, *args, **kwargs)
 |      Add a function, with arguments, to be called when the test is
 |      completed. Functions added are called on a LIFO basis and are
 |      called after tearDown on test failure or success.
 |      
 |      Cleanup items are called even if setUp fails (unlike tearDown).
 |  
 |  addTypeEqualityFunc(self, typeobj, function)
 |      Add a type specific assertEqual style function to compare a type.
 |      
 |      This method is for use by TestCase subclasses that need to register
 |      their own type equality functions to provide nicer error messages.
 |      
 |      Args:
 |          typeobj: The data type to call this function on when both values
 |                  are of the same type in assertEqual().
 |          function: The callable taking two arguments and an optional
 |                  msg= argument that raises self.failureException with a
 |                  useful error message when the two arguments are not equal.
 |  
 |  assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are unequal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is more than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      If the two objects compare equal then they will automatically
 |      compare almost equal.
 |  
 |  assertAlmostEquals = assertAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |  
 |  assertDictContainsSubset(self, expected, actual, msg=None)
 |      Checks whether actual is a superset of expected.
 |  
 |  assertDictEqual(self, d1, d2, msg=None)
 |  
 |  assertEqual(self, first, second, msg=None)
 |      Fail if the two objects are unequal as determined by the '=='
 |      operator.
 |  
 |  assertEquals = assertEqual(self, first, second, msg=None)
 |  
 |  assertFalse(self, expr, msg=None)
 |      Check that the expression is false.
 |  
 |  assertGreater(self, a, b, msg=None)
 |      Just like self.assertTrue(a > b), but with a nicer default message.
 |  
 |  assertGreaterEqual(self, a, b, msg=None)
 |      Just like self.assertTrue(a >= b), but with a nicer default message.
 |  
 |  assertIn(self, member, container, msg=None)
 |      Just like self.assertTrue(a in b), but with a nicer default message.
 |  
 |  assertIs(self, expr1, expr2, msg=None)
 |      Just like self.assertTrue(a is b), but with a nicer default message.
 |  
 |  assertIsInstance(self, obj, cls, msg=None)
 |      Same as self.assertTrue(isinstance(obj, cls)), with a nicer
 |      default message.
 |  
 |  assertIsNone(self, obj, msg=None)
 |      Same as self.assertTrue(obj is None), with a nicer default message.
 |  
 |  assertIsNot(self, expr1, expr2, msg=None)
 |      Just like self.assertTrue(a is not b), but with a nicer default message.
 |  
 |  assertIsNotNone(self, obj, msg=None)
 |      Included for symmetry with assertIsNone.
 |  
 |  assertItemsEqual(self, expected_seq, actual_seq, msg=None)
 |      An unordered sequence specific comparison. It asserts that
 |      actual_seq and expected_seq have the same element counts.
 |      Equivalent to::
 |      
 |          self.assertEqual(Counter(iter(actual_seq)),
 |                           Counter(iter(expected_seq)))
 |      
 |      Asserts that each element has the same count in both sequences.
 |      Example:
 |          - [0, 1, 1] and [1, 0, 1] compare equal.
 |          - [0, 0, 1] and [0, 1] compare unequal.
 |  
 |  assertLess(self, a, b, msg=None)
 |      Just like self.assertTrue(a < b), but with a nicer default message.
 |  
 |  assertLessEqual(self, a, b, msg=None)
 |      Just like self.assertTrue(a <= b), but with a nicer default message.
 |  
 |  assertListEqual(self, list1, list2, msg=None)
 |      A list-specific equality assertion.
 |      
 |      Args:
 |          list1: The first list to compare.
 |          list2: The second list to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assertMultiLineEqual(self, first, second, msg=None)
 |      Assert that two multi-line strings are equal.
 |  
 |  assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |      Fail if the two objects are equal as determined by their
 |      difference rounded to the given number of decimal places
 |      (default 7) and comparing to zero, or by comparing that the
 |      between the two objects is less than the given delta.
 |      
 |      Note that decimal places (from zero) are usually not the same
 |      as significant digits (measured from the most signficant digit).
 |      
 |      Objects that are equal automatically fail.
 |  
 |  assertNotAlmostEquals = assertNotAlmostEqual(self, first, second, places=None, msg=None, delta=None)
 |  
 |  assertNotEqual(self, first, second, msg=None)
 |      Fail if the two objects are equal as determined by the '!='
 |      operator.
 |  
 |  assertNotEquals = assertNotEqual(self, first, second, msg=None)
 |  
 |  assertNotIn(self, member, container, msg=None)
 |      Just like self.assertTrue(a not in b), but with a nicer default message.
 |  
 |  assertNotIsInstance(self, obj, cls, msg=None)
 |      Included for symmetry with assertIsInstance.
 |  
 |  assertNotRegexpMatches(self, text, unexpected_regexp, msg=None)
 |      Fail the test if the text matches the regular expression.
 |  
 |  assertRaises(self, excClass, callableObj=None, *args, **kwargs)
 |      Fail unless an exception of class excClass is raised
 |      by callableObj when invoked with arguments args and keyword
 |      arguments kwargs. If a different type of exception is
 |      raised, it will not be caught, and the test case will be
 |      deemed to have suffered an error, exactly as for an
 |      unexpected exception.
 |      
 |      If called with callableObj omitted or None, will return a
 |      context object used like this::
 |      
 |           with self.assertRaises(SomeException):
 |               do_something()
 |      
 |      The context manager keeps a reference to the exception as
 |      the 'exception' attribute. This allows you to inspect the
 |      exception after the assertion::
 |      
 |          with self.assertRaises(SomeException) as cm:
 |              do_something()
 |          the_exception = cm.exception
 |          self.assertEqual(the_exception.error_code, 3)
 |  
 |  assertRaisesRegexp(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs)
 |      Asserts that the message in a raised exception matches a regexp.
 |      
 |      Args:
 |          expected_exception: Exception class expected to be raised.
 |          expected_regexp: Regexp (re pattern object or string) expected
 |                  to be found in error message.
 |          callable_obj: Function to be called.
 |          args: Extra args.
 |          kwargs: Extra kwargs.
 |  
 |  assertRegexpMatches(self, text, expected_regexp, msg=None)
 |      Fail the test unless the text matches the regular expression.
 |  
 |  assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None)
 |      An equality assertion for ordered sequences (like lists and tuples).
 |      
 |      For the purposes of this function, a valid ordered sequence type is one
 |      which can be indexed, has a length, and has an equality operator.
 |      
 |      Args:
 |          seq1: The first sequence to compare.
 |          seq2: The second sequence to compare.
 |          seq_type: The expected datatype of the sequences, or None if no
 |                  datatype should be enforced.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assertSetEqual(self, set1, set2, msg=None)
 |      A set-specific equality assertion.
 |      
 |      Args:
 |          set1: The first set to compare.
 |          set2: The second set to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |      
 |      assertSetEqual uses ducktyping to support different types of sets, and
 |      is optimized for sets specifically (parameters must support a
 |      difference method).
 |  
 |  assertTrue(self, expr, msg=None)
 |      Check that the expression is true.
 |  
 |  assertTupleEqual(self, tuple1, tuple2, msg=None)
 |      A tuple-specific equality assertion.
 |      
 |      Args:
 |          tuple1: The first tuple to compare.
 |          tuple2: The second tuple to compare.
 |          msg: Optional message to use on failure instead of a list of
 |                  differences.
 |  
 |  assert_ = assertTrue(self, expr, msg=None)
 |  
 |  countTestCases(self)
 |  
 |  debug(self)
 |      Run the test without collecting errors in a TestResult
 |  
 |  defaultTestResult(self)
 |  
 |  doCleanups(self)
 |      Execute all cleanup functions. Normally called for you after
 |      tearDown.
 |  
 |  fail(self, msg=None)
 |      Fail immediately, with the given message.
 |  
 |  failIf = deprecated_func(*args, **kwargs)
 |  
 |  failIfAlmostEqual = deprecated_func(*args, **kwargs)
 |  
 |  failIfEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnless = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessAlmostEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessEqual = deprecated_func(*args, **kwargs)
 |  
 |  failUnlessRaises = deprecated_func(*args, **kwargs)
 |  
 |  id(self)
 |  
 |  run(self, result=None)
 |  
 |  setUp(self)
 |      Hook method for setting up the test fixture before exercising it.
 |  
 |  shortDescription(self)
 |      Returns a one-line description of the test, or None if no
 |      description has been provided.
 |      
 |      The default implementation of this method returns the first line of
 |      the specified test method's docstring.
 |  
 |  skipTest(self, reason)
 |      Skip this test.
 |  
 |  tearDown(self)
 |      Hook method for deconstructing the test fixture after testing it.
 |  
 |  ----------------------------------------------------------------------
 |  Class methods defined here:
 |  
 |  setUpClass(cls) from __builtin__.type
 |      Hook method for setting up class fixture before running tests in the class.
 |  
 |  tearDownClass(cls) from __builtin__.type
 |      Hook method for deconstructing the class fixture after running all tests in the class.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  failureException = <type 'exceptions.AssertionError'>
 |      Assertion failed.
 |  
 |  longMessage = False
 |  
 |  maxDiff = 640

None
Help on class TestLoader in module unittest.loader:

class TestLoader(__builtin__.object)
 |  This class is responsible for loading tests according to various criteria
 |  and returning them wrapped in a TestSuite
 |  
 |  Methods defined here:
 |  
 |  discover(self, start_dir, pattern='test*.py', top_level_dir=None)
 |      Find and return all test modules from the specified start
 |      directory, recursing into subdirectories to find them. Only test files
 |      that match the pattern will be loaded. (Using shell style pattern
 |      matching.)
 |      
 |      All test modules must be importable from the top level of the project.
 |      If the start directory is not the top level directory then the top
 |      level directory must be specified separately.
 |      
 |      If a test package name (directory with '__init__.py') matches the
 |      pattern then the package will be checked for a 'load_tests' function. If
 |      this exists then it will be called with loader, tests, pattern.
 |      
 |      If load_tests exists then discovery does  *not* recurse into the package,
 |      load_tests is responsible for loading all tests in the package.
 |      
 |      The pattern is deliberately not stored as a loader attribute so that
 |      packages can continue discovery themselves. top_level_dir is stored so
 |      load_tests does not need to pass this argument in to loader.discover().
 |  
 |  getTestCaseNames(self, testCaseClass)
 |      Return a sorted sequence of method names found within testCaseClass
 |  
 |  loadTestsFromModule(self, module, use_load_tests=True)
 |      Return a suite of all tests cases contained in the given module
 |  
 |  loadTestsFromName(self, name, module=None)
 |      Return a suite of all tests cases given a string specifier.
 |      
 |      The name may resolve either to a module, a test case class, a
 |      test method within a test case class, or a callable object which
 |      returns a TestCase or TestSuite instance.
 |      
 |      The method optionally resolves the names relative to a given module.
 |  
 |  loadTestsFromNames(self, names, module=None)
 |      Return a suite of all tests cases found using the given sequence
 |      of string specifiers. See 'loadTestsFromName()'.
 |  
 |  loadTestsFromTestCase(self, testCaseClass)
 |      Return a suite of all tests cases contained in testCaseClass
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  sortTestMethodsUsing = <built-in function cmp>
 |      cmp(x, y) -> integer
 |      
 |      Return negative if x<y, zero if x==y, positive if x>y.
 |  
 |  suiteClass = <class 'unittest.suite.TestSuite'>
 |      A test suite is a composite test consisting of a number of TestCases.
 |      
 |      For use, create an instance of TestSuite, then add test case instances.
 |      When all tests have been added, the suite can be passed to a test
 |      runner, such as TextTestRunner. It will run the individual test cases
 |      in the order in which they were added, aggregating the results. When
 |      subclassing, do not forget to call the base class constructor.
 |  
 |  testMethodPrefix = 'test'

None
Help on class TestProgram in module unittest.main:

class TestProgram(__builtin__.object)
 |  A command-line program that runs a set of tests; this is primarily
 |  for making test modules conveniently executable.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=<unittest.loader.TestLoader object>, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
 |  
 |  createTests(self)
 |  
 |  parseArgs(self, argv)
 |  
 |  runTests(self)
 |  
 |  usageExit(self, msg=None)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  USAGE = 'Usage: %(progName)s [options] [test] [...]\n\nOpti...        ...
 |  
 |  buffer = None
 |  
 |  catchbreak = None
 |  
 |  failfast = None
 |  
 |  progName = None

None
Help on class TestResult in module unittest.result:

class TestResult(__builtin__.object)
 |  Holder for test result information.
 |  
 |  Test results are automatically managed by the TestCase and TestSuite
 |  classes, and do not need to be explicitly manipulated by writers of tests.
 |  
 |  Each instance holds the total number of tests run, and collections of
 |  failures and errors that occurred among those test runs. The collections
 |  contain tuples of (testcase, exceptioninfo), where exceptioninfo is the
 |  formatted traceback of the error that occurred.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, stream=None, descriptions=None, verbosity=None)
 |  
 |  __repr__(self)
 |  
 |  addError(self, *args, **kw)
 |      Called when an error has occurred. 'err' is a tuple of values as
 |      returned by sys.exc_info().
 |  
 |  addExpectedFailure(self, test, err)
 |      Called when an expected failure/error occured.
 |  
 |  addFailure(self, *args, **kw)
 |      Called when an error has occurred. 'err' is a tuple of values as
 |      returned by sys.exc_info().
 |  
 |  addSkip(self, test, reason)
 |      Called when a test is skipped.
 |  
 |  addSuccess(self, test)
 |      Called when a test has completed successfully
 |  
 |  addUnexpectedSuccess(self, *args, **kw)
 |      Called when a test was expected to fail, but succeed.
 |  
 |  printErrors(self)
 |      Called by TestRunner after test run
 |  
 |  startTest(self, test)
 |      Called when the given test is about to be run
 |  
 |  startTestRun(self)
 |      Called once before any tests are executed.
 |      
 |      See startTest for a method called before each test.
 |  
 |  stop(self)
 |      Indicates that the tests should be aborted
 |  
 |  stopTest(self, test)
 |      Called when the given test has been run
 |  
 |  stopTestRun(self)
 |      Called once after all tests are executed.
 |      
 |      See stopTest for a method called after each test.
 |  
 |  wasSuccessful(self)
 |      Tells whether or not this result was a success
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

None
Help on class TestSuite in module unittest.suite:

class TestSuite(BaseTestSuite)
 |  A test suite is a composite test consisting of a number of TestCases.
 |  
 |  For use, create an instance of TestSuite, then add test case instances.
 |  When all tests have been added, the suite can be passed to a test
 |  runner, such as TextTestRunner. It will run the individual test cases
 |  in the order in which they were added, aggregating the results. When
 |  subclassing, do not forget to call the base class constructor.
 |  
 |  Method resolution order:
 |      TestSuite
 |      BaseTestSuite
 |      __builtin__.object
 |  
 |  Methods defined here:
 |  
 |  debug(self)
 |      Run the tests without collecting errors in a TestResult
 |  
 |  run(self, result, debug=False)
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from BaseTestSuite:
 |  
 |  __call__(self, *args, **kwds)
 |  
 |  __eq__(self, other)
 |  
 |  __init__(self, tests=())
 |  
 |  __iter__(self)
 |  
 |  __ne__(self, other)
 |  
 |  __repr__(self)
 |  
 |  addTest(self, test)
 |  
 |  addTests(self, tests)
 |  
 |  countTestCases(self)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from BaseTestSuite:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes inherited from BaseTestSuite:
 |  
 |  __hash__ = None

None
Help on class TextTestRunner in module unittest.runner:

class TextTestRunner(__builtin__.object)
 |  A test runner class that displays results in textual form.
 |  
 |  It prints out the names of tests as they are run, errors as they
 |  occur, and a summary of the results at the end of the test run.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, stream=<idlelib.PyShell.PseudoOutputFile object>, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None)
 |  
 |  run(self, test)
 |      Run the given test case or test suite.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  resultclass = <class 'unittest.runner.TextTestResult'>
 |      A test result class that can print formatted text results to a stream.
 |      
 |      Used by TextTestRunner.

None
Help on TestLoader in module unittest.loader object:

class TestLoader(__builtin__.object)
 |  This class is responsible for loading tests according to various criteria
 |  and returning them wrapped in a TestSuite
 |  
 |  Methods defined here:
 |  
 |  discover(self, start_dir, pattern='test*.py', top_level_dir=None)
 |      Find and return all test modules from the specified start
 |      directory, recursing into subdirectories to find them. Only test files
 |      that match the pattern will be loaded. (Using shell style pattern
 |      matching.)
 |      
 |      All test modules must be importable from the top level of the project.
 |      If the start directory is not the top level directory then the top
 |      level directory must be specified separately.
 |      
 |      If a test package name (directory with '__init__.py') matches the
 |      pattern then the package will be checked for a 'load_tests' function. If
 |      this exists then it will be called with loader, tests, pattern.
 |      
 |      If load_tests exists then discovery does  *not* recurse into the package,
 |      load_tests is responsible for loading all tests in the package.
 |      
 |      The pattern is deliberately not stored as a loader attribute so that
 |      packages can continue discovery themselves. top_level_dir is stored so
 |      load_tests does not need to pass this argument in to loader.discover().
 |  
 |  getTestCaseNames(self, testCaseClass)
 |      Return a sorted sequence of method names found within testCaseClass
 |  
 |  loadTestsFromModule(self, module, use_load_tests=True)
 |      Return a suite of all tests cases contained in the given module
 |  
 |  loadTestsFromName(self, name, module=None)
 |      Return a suite of all tests cases given a string specifier.
 |      
 |      The name may resolve either to a module, a test case class, a
 |      test method within a test case class, or a callable object which
 |      returns a TestCase or TestSuite instance.
 |      
 |      The method optionally resolves the names relative to a given module.
 |  
 |  loadTestsFromNames(self, names, module=None)
 |      Return a suite of all tests cases found using the given sequence
 |      of string specifiers. See 'loadTestsFromName()'.
 |  
 |  loadTestsFromTestCase(self, testCaseClass)
 |      Return a suite of all tests cases contained in testCaseClass
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  sortTestMethodsUsing = <built-in function cmp>
 |      cmp(x, y) -> integer
 |      
 |      Return negative if x<y, zero if x==y, positive if x>y.
 |  
 |  suiteClass = <class 'unittest.suite.TestSuite'>
 |      A test suite is a composite test consisting of a number of TestCases.
 |      
 |      For use, create an instance of TestSuite, then add test case instances.
 |      When all tests have been added, the suite can be passed to a test
 |      runner, such as TextTestRunner. It will run the individual test cases
 |      in the order in which they were added, aggregating the results. When
 |      subclassing, do not forget to call the base class constructor.
 |  
 |  testMethodPrefix = 'test'

None
Help on function findTestCases in module unittest.loader:

findTestCases(module, prefix='test', sortUsing=<built-in function cmp>, suiteClass=<class 'unittest.suite.TestSuite'>)

None
Help on function getTestCaseNames in module unittest.loader:

getTestCaseNames(testCaseClass, prefix, sortUsing=<built-in function cmp>)

None
Help on class TestProgram in module unittest.main:

class TestProgram(__builtin__.object)
 |  A command-line program that runs a set of tests; this is primarily
 |  for making test modules conveniently executable.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=<unittest.loader.TestLoader object>, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
 |  
 |  createTests(self)
 |  
 |  parseArgs(self, argv)
 |  
 |  runTests(self)
 |  
 |  usageExit(self, msg=None)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  USAGE = 'Usage: %(progName)s [options] [test] [...]\n\nOpti...        ...
 |  
 |  buffer = None
 |  
 |  catchbreak = None
 |  
 |  failfast = None
 |  
 |  progName = None

None
Help on function makeSuite in module unittest.loader:

makeSuite(testCaseClass, prefix='test', sortUsing=<built-in function cmp>, suiteClass=<class 'unittest.suite.TestSuite'>)

None


三、总结

至此,我们知道了。其实整个单元测试框架的逻辑出来了。分三步走:第一步testloader根据传入的参数获得相应的测试用例,即对应具体的测试方法, 然后makesuite在把所有的测试用例组装成testsuite,最后把testsiute传给testrunner进行执行。 而我们通常执行的unittest.main(),其实就是unittest.testprom方法,其执行的功能就是上面分析的三步,在第一步中其传入的参数是自身的模块__main__; 在第二步中把自身模块中的所有测试类中中的测试方法提取出来,并生成测试套件;最后再把测试套件传递给testrunner进行具体的测试。 最后给出一个完整的单元测试组织代码,把该代码放到单元测试用例文件的同一个目录后执行该脚本,即可执行所有的测试用例文件。



参考文章:http://blog.csdn.net/five3/article/details/7104466


版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/jlhx123456/article/details/46653555

智能推荐

websocket支持压缩_websocket gzip-程序员宅基地

文章浏览阅读754次。我们平常在项目中,经常会用到websocket,用来传递实时消息,或者类似IM聊天这种场景。但你知道么?websocket消息,也是支持压缩的,只是我们比较少用到她。在客户端向服务端发起连接的时候,在header里面,会带上自己支持压缩的标记,见下:这地方是不是和http header里面带上 Accept-Encoding: gzip, deflate, br,也就是客户端支持gzip压缩有点类似?_websocket gzip

码仔精选,Android面试题-程序员宅基地

文章浏览阅读175次。码个蛋(codeegg) 第 822次推文码妞看世界1.Java创建对象的几种方式使用new关键字使用Class类的newInstance方法使用Constructor类的newIn..._码个蛋 《每日一道面试题》 第一期

实时系统vxWorks - 动态库、静态库建立及调用_vxworks生成静态库-程序员宅基地

文章浏览阅读2.9k次,点赞2次,收藏25次。概述静态库的本质就是将多个目标文件打包成一个文件。在使用时链接静态库就是将库中被调用的代码复制到调用模块中。动态库又名共享库,和静态库最大的不同就是,链接共享库并不需要将库中被调用的代码复..._vxworks生成静态库

Android中asset文件夹和raw文件夹区别-程序员宅基地

文章浏览阅读614次。*res/raw和assets的相同点:1.两者目录下的文件在打包后会原封不动的保存在apk包中,不会被编译成二进制。*res/raw和assets的不同点:1.res/raw中的文件会被映射到R.java文件中,访问的时候直接使用资源ID即R.id.filename;assets文件夹下的文件不会被映射到R.java中,访问的时候需要AssetManager类。2.res

图像去雾算法系统毕业论文【FPGA】_fpga除雾硕士毕业论文-程序员宅基地

文章浏览阅读332次。本团队擅长数据处理、建模仿真、程序设计、论文写作与指导,项目与课题经验交流。_fpga除雾硕士毕业论文

[迁移]关于ejoy2d在win上mingw的编译-程序员宅基地

文章浏览阅读255次。声明:因网易博客将关闭,移到此关于ejoy2d应该有不少人关注最近看到想编下看看demo,感觉编译对于用惯ide来说确实有些麻烦,不过嘛这样也好,简单,方便,不用配置那么多东西,一个make就可以做完,如果调试呢?lua写嘛,网上弄个就可以了,但是如果要写lua导出函数呢?gdb吧,命令行蛮实在的。废话不多少,下面编译过程https://github.com/cloudwu/ejoy2..._ejoy2d

随便推点

【嵌入式开发 Linux 常用命令系列 1-- find 与 xargs 绝佳搭配】_linux find xargs-程序员宅基地

文章浏览阅读702次。通过上一节的命令虽然可以在很多文件中搜索到关键字符串,但是文件太多不好定位,可以使用。在某种类型的文件中搜索关键字符串可以使用下面命令,比如在。命令来过滤掉输出结果中包含。不会去区分文件名的大写。_linux find xargs

Python点云处理(十四)点云特征描述符算法之PFH、FPFH_pfh python-程序员宅基地

文章浏览阅读2.4k次。根据不同的应用需求和点云数据规模,我们可以选择适合的特征描述算法。若对称性、重复性较强的物体需要较高的特征描述准确性,可以选择点特征直方图算法,更具有鲁棒性;若对大规模点云数据进行实时处理,可以选择快速点特征直方图算法,FPFH算法在PFH算法的基础上引入了距离加权因素,从而提高了计算效率和速度,更适合处理大规模数据。_pfh python

Vue的动画与过度_vue播放关键帧动画-程序员宅基地

文章浏览阅读166次。v-enter-active { animation: 配置项 } // 显示动画.v-leave-active { animation: 配置项 } // 隐藏动画from{to{_vue播放关键帧动画

prometheus监控之alertmanager安装配置(2)接入电话报警微信、短信、邮件等告警-程序员宅基地

文章浏览阅读9.4k次,点赞2次,收藏11次。电话报警使用OPSALERT点击了解更多(支持电话报警、短信报警、邮件告警、微信报警)直接使用webhook配置即可,比较简单。介绍Prometheus 将数据采集和报警分成两个模块。报警规则配置在Prometheus Servers上,然后发送报警信息到AlertManger,Alertmanager 对收到的告警信息进行处理,包括去重,降噪,分组,沉默,抑制,策略路由,告警通知。流程Alertmanager 接收到告警,根据labels判断属于哪些Route(可存在多个Route,..._alertmanager

MATLAB | 如何绘制三维曲线、曲面、多边形投影(三视图)?_matlab绘制三维曲面及投影面-程序员宅基地

文章浏览阅读7.5k次,点赞27次,收藏105次。~_matlab绘制三维曲面及投影面

如何搭建一个vue项目(完整步骤)_vue项目搭建-程序员宅基地

文章浏览阅读4.3k次,点赞2次,收藏16次。一、安装node环境1、下载地址为:https://nodejs.org/en/2、检查是否安装成功:如果输出版本号,说明我们安装node环境成功  3、为了提高我们的效率,可以使用淘宝的镜像:http://npm.taobao.org/输入:npm install -g cnpm –registry=https://registry.npm.taobao.org,即可安装npm镜像,以..._vue项目搭建

推荐文章

热门文章

相关标签