python unit testing framework Unitest

About a .unitest
unittest is built python unit testing framework includes written cases, tissues embodiment, the execution condition with the embodiment, the output report automation framework.

Before using five unittest need to understand the concept of the framework:

test case: a complete test unit, to perform the test unit may fulfill the verification of a particular problem, the complete reflected in: Prior to testing environment preparation (the setUp), execute the test code (RUN), and after the test environment to restore (the tearDown);

test suite: more than a collection of test cases, test suites or test plan;

testLoader: loading into TestSuite TestCase, wherein loadTestsFrom __ () method is used to find TestCase, and create instances of them, and then added to the TestSuite, returns TestSuite instance;

test runner: Save execute test cases and test results to TextTestResult examples, including running a number of test cases, the number of successful, failed and so much information;

test fixture: a test preparation and environment initialization reduction, mainly setUp () and setDown () method;

Two, unittest works

Three, unittest following properties:

['BaseTestSuite', 'FunctionTestCase','SkipTest', 'TestCase', 'TestLoader', 'TestProgram', 'TestResult', 'TestSuite','TextTestResult', 'TextTestRunner', '_TextTestResult', '__all__','__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__','__package__', '__path__', '__spec__', '__unittest', 'case', 'defaultTestLoader', 'expectedFailure','findTestCases', 'getTestCaseNames', 'installHandler', 'load_tests', 'loader','main', 'makeSuite', 'registerResult','removeHandler', 'removeResult', 'result', 'runner', 'signals', 'skip', 'skipIf', 'skipUnless', 'suite', 'util']

DESCRIPTION :( common to the class )

(1) unittest.TestCase: TestCase class, all of the basic classes of test case class inheritance

 class TestAppLogin(unittest.TestCase):

(2) unittest.main (): facilitate a test module unit becomes the test scripts can be run directly, main () method uses the class to search all TestLoader test methods contained in the module in order to "test" the beginning of the name, and they performed automatically. The default order of execution of the method is: according to the test load ASCII code order, the sequence of numbers and letters: 0-9, AZ, az. Therefore, in the beginning of the test method A there is a preference to be executed after a beginning

(3) unittest.TestSuit (): unittest framework TestSuite () class is used to create test suites

(. 4) unittest.TextTestRunner (): the unittest frame TextTextRunner (), a () method to run the test suite is assembled through the following class RUN, the parameters for the test suite suite

(. 5) unittest.defaultTestLoader () : defaultTestLoader () class, by such a method may automatically discover the following test case match lookup file (test * .py) () according to the test directory start_dir, and assembled to test to find test suite, it is possible () method performs discover directly run. Usage is as follows:

discover=unittest.defaultTestLoader.discover(case_dir,pattern="test*.py",top_level_dir=None)

 1.discover method there are three parameters:

-case_dir:这个是待执行用例的目录。

-pattern:这个是匹配脚本名称的规则,test*.py意思是匹配test开头的所有.py文件。

-top_level_dir:这个是顶层目录的名称,一般默认等于None就行了。

(6)unittest.skip():装饰器,当运行用例时,有些用例可能不想执行等,可用装饰器暂时屏蔽该条测试用例。一种常见的用法就是比如说想调试某一个测试用例,想先屏蔽其他用例就可以用装饰器屏蔽

@unittest.skip(reason):skip(reason)装饰器:无条件跳过装饰的测试,并说明跳过测试的原因。

@unittest.skipIf(reason):skipIf(condition,reason)装饰器:条件为真时,跳过装饰的测试,并说明跳过测试的原因。

@unittest.skipUnless(reason):skipUnless(condition,reason)装饰器:条件为假时,跳过装饰的测试,并说明跳过测试的原因。

@unittest.expectedFailure():expectedFailure()测试标记为失败。

(7)unittest.TestLoader():加载测试用例到测试套件中,提供了一下几种方法:

 

   suit=unittest.TestLoader().loadTestsFromTestCase(类名)————常用
   suit=unittest.TestLoader().loadTestsFromMoudule(模块名)但是我看源码提示是说在3.5已经移除使用,那就不用这个了

   suit=unittest.TestLoader().loadTestsFromName(方法名)

   suit=unittest.TestLoader().loadTestsFromNames(方法名,复数形式)

四、TestCase类的属性:

['__call__', '__class__', '__delattr__','__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__','__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', '__weakref__', '_addExpectedFailure', '_addSkip','_addUnexpectedSuccess', '_baseAssertEqual', '_classSetupFailed', '_deprecate','_diffThreshold', '_feedErrorsToResult', '_formatMessage','_getAssertEqualityFunc', '_truncateMessage', 'addCleanup', 'addTypeEqualityFunc','assertAlmostEqual', 'assertAlmostEquals', 'assertCountEqual','assertDictContainsSubset', 'assertDictEqual', 'assertEqual','assertEquals', 'assertFalse','assertGreater', 'assertGreaterEqual', 'assertIn','assertIs', 'assertIsInstance','assertIsNone', 'assertIsNot','assertIsNotNone', 'assertLess','assertLessEqual', 'assertListEqual', 'assertLogs', 'assertMultiLineEqual','assertNotAlmostEqual', 'assertNotAlmostEquals', 'assertNotEqual','assertNotEquals', 'assertNotIn', 'assertNotIsInstance', 'assertNotRegex','assertNotRegexpMatches', 'assertRaises', 'assertRaisesRegex','assertRaisesRegexp', 'assertRegex', 'assertRegexpMatches','assertSequenceEqual', 'assertSetEqual', 'assertTrue','assertTupleEqual', 'assertWarns', 'assertWarnsRegex', 'assert_','countTestCases', 'debug', 'defaultTestResult', 'doCleanups', 'fail', 'failIf','failIfAlmostEqual', 'failIfEqual', 'failUnless', 'failUnlessAlmostEqual','failUnlessEqual', 'failUnlessRaises', 'failureException', 'id', 'longMessage','maxDiff', 'run', 'setUp', 'setUpClass','shortDescription', 'skipTest', 'subTest', 'tearDown','tearDownClass']

说明:(常用到的类)

(1)setup():用于测试用例执行前的初始化工作. 如测试用例中需要访问数据库,可以在setUp中建立数据库连接并进行初始化。如测试用例需要登录web,可以先实例化浏览器

(2)tearDown():用于测试用例执行之后的善后工作。如关闭数据库连接。关闭浏览器

(3)assert*():一些断言方法:在执行测试用例的过程中,最终用例是否执行通过,是通过判断测试得到的实际结果和预期结果是否相等决定的

assertEqual(a,b,[msg='测试成功时打印的信息']):断言a和b是否相等,相等则测试用例通过。

assertNotEqual(a,b,[msg='测试失败时打印的信息']):断言a和b是否相等,不相等则测试用例通过。

assertTrue(x,[msg='测试成功时打印的信息']):断言x是否True,是True则测试用例通过。

assertFalse(x,[msg='测试失败时打印的信息']):断言x是否False,是False则测试用例通过。

assertIs(a,b,[msg='测试成功时打印的信息']):断言a是否是b,是则测试用例通过。

assertNotIs(a,b,[msg='测试失败时打印的信息']):断言a是否是b,不是则测试用例通过。

assertIsNone(x,[msg='测成试功时打印的信息']):断言x是否None,是None则测试用例通过。

assertIsNotNone(x,[msg='测试失败时打印的信息']):断言x是否None,不是None则测试用例通过。

assertIn(a,b,[msg='测试成功时打印的信息']):断言a是否在b中,在b中则测试用例通过。

assertNotIn(a,b,[msg='测试失败时打印的信息']):断言a是否在b中,不在b中则测试用例通过。

assertIsInstance(a,b,[msg='测试成功时打印的信息']):断言a是是b的一个实例,是则测试用例通过。

assertNotIsInstance(a,b,[msg='测试失败时打印的信息']):断言a是是b的一个实例,不是则测试用例通过。

五、TestSuite类的属性

['__call__', '__class__', '__delattr__','__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__','__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__','__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__','__str__', '__subclasshook__', '__weakref__','_addClassOrModuleLevelException', '_cleanup', '_get_previous_module','_handleClassSetUp', '_handleModuleFixture', '_handleModuleTearDown','_removeTestAtIndex', '_tearDownPreviousClass', 'addTest','addTests', 'countTestCases', 'debug', 'run']

常用的方法:

(1) addTest():addTest()方法是将测试用例添加到测试套件中,如下方,是将test_baidu模块下的BaiduTest类下的test_login测试方法添加到测试套件。

suite = unittest.TestSuite()

suite.addTest(test_baidu.BaiduTest(' test_login '))

六.TextTestRunner的属性如下

['__class__', '__delattr__', '__dict__','__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__','__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__','__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__','__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__','_makeResult', 'resultclass', 'run']

说明:(常用到的类)

(1) run():是运行测试套件的测试用例,入参为suite测试套件

runner = unittest.TextTestRunner()

runner.run(suite)

 

Guess you like

Origin www.cnblogs.com/yhms/p/12076513.html