Python UnitTest Learning

Source: Internet
Author: User

ImportUnitTestclassutest (unittest. TestCase):defTest_upper (self): self.assertequal ('Foo'. Upper (),'FOO')defTest_isupper (self): Self.asserttrue ('FOO'. Isupper ()) Self.assertfalse ('Foo'. Isupper ())if __name__=='__main__': Unittest.main ()

Note: 0. Unnitest is a python-brought library that requires no additional installation for 1. Test Cases (testcase) are all made up of unittest. The TestCase class creates a test method that corresponds to the beginning of tests, as in the example above, Test_upper 2. The SetUp () and TearDown () method is used to define some initialization and cleanup instructions, which are executed before and after each test case. If only one execution is performed before and after all test cases, use SetupClass () and Teardownclass () if all the test cases require some common steps to be placed in Setup (), If you do this once for all the test cases are put into effect on setupclass (), such as landing (Coolie for all test cases can be shared) SetupClass () and Teardownclass () must add adorner @classmethod, Otherwise, there will be an error. SetUp () and TearDown () are not used. 3. Unittest.main () provides a command-line interface for a test script. 4. Other ways to run test cases are:
Suite = UnitTest. Testloader (). Loadtestsfromtestcase (utest) unittest. Texttestrunner (verbosity=2). Run (Suite)

5. Command line: Python-m unittest test_module. TestClass and Python-m unittest test_module. Testclass.test_method As above example: Python-m unittest utest.utestpython-m unittest utest.utest.test_upper  can also pass a-v flag For more detailed test results: python-m unittest-v Test_module above example: d:\python>python-m unittest-v utest Result: Test_isupper (UTest.UTest) ... oktest_upper (utest.utest) ... ok 6. To run all the test cases in a class (all methods at the beginning of test), there are several ways to do this: a. Unittest.main () corresponds to the command line Ptyon Module.pyb. Suite = UnitTest. Testloader (). Loadtestsfromtestcase (utest) unittest. The command line for Texttestrunner (verbosity=2). Run (suite) is Python-m unittest test_module. TESTCLASSC. Create a new Testsuite instance, and then add all the test cases to the test set one after the other, and finally run the test set through the Run method of the Texttestrunner object, for example, this method is more cumbersome, adding 50 test cases, Need to manually add 50 use cases one to the Testsuite
Suite = UnitTest. TestSuite () suite.addtest (utest ('test_isupper')) suite.addtest (Utest ( ' Test_upper '  = unittest. Texttestrunner () Runner.run (suite)

However, if there is only one test method in class, but the test requires different test data, the C method comes in handy:

A. First, rewrite the constructor of the TestCase class and use input as the parameter of the constructor (because the test method cannot pass parameters, it can only be passed in the constructor to the required input), such as:
def __init__ (self, marketcode, Stockcode, stocktype,methodname):    super (Comparison, self). __init__ (methodName)     = Marketcode    = stockcode    = Stocktype
B. Then a reference to the test case method to input
defTest_getpriceinfo (self): stime=Utils.gettimestamp () Mkt_price=Parseresponse.getmarketlastprice (self.marketcode,self.stockcode,self.stocktype) Position_price=Parseresponse.getpositionlastprice (Self.loginkey,self.logincookie,self.stockcode,self.marketcode) self.infodir["timestamp"] =stime self.infodir["Ticker"] = Self.marketcode +Self.stockcode self.infodir["Postionprice"] =Position_price self.infodir["Marketprice"] =mkt_price alertrecorder.cmpmktposition (self.infodir)PrintSelf.infodir

C. Finally define a running method outside class, where Comparison (Stockinfo[0],stockinfo[1],stockinfo[2], "Test_getpriceinfo") is the creation of a test class example, Test_ Getpriceinfo is the test case method name, and this is unittest. The parameters required by the TestCase class.

def run ():     = UnitTest. TestSuite ()    = scheduler.get_mktpostion_stocks ()    for in  stockinfolist:        suite.addtest (Comparison (stockinfo[0],stockinfo["test_getpriceinfo" ) )    = unittest. Texttestrunner ()    Runner.run (Suite)

In combination, the package is: A. . Main (verbosity=2), where verbosity=2 is to make the result output more detailed B.
def== unittest. Texttestrunner (verbosity=2) Runner.run (suite)
C.
def= unittest. TestSuite () suite.addtest (Testcaseclassname ('test_method'= unittest. Texttestrunner (verbosity=2) Runner.run (suite)

Note: The above three methods of running the test are somewhat different from the output on the IDE. Results for A and C outputs: set up for Classtest_isupper (__main__. Utest) ... oktest_sum (__main__. Utest) ... oktest_upper (__main__. Utest) ... ok  and b output is: Test_sum (__main__. Utest) ... oktest_upper (__main__. Utest) ... okset up for Classtest_isupper (__main__. Utest) ... ok  preferred or unittest.main () and UnitTest. Texttestrunner (). Run (unittest. Testloader (). Loadtestsfromtestcase (Testcaseclassname))   7. If you want to skip the test, you can use the adorner @unittest. Skip ("Reason") and @unittest. SkipIf (condition, ' reason '). If it is for an individual test case, the test case method is added to the adorner. If you need to skip all tests (such as holidays), add adorners on the SetupClass. In this case, attention should be paid to the order of two adorners, first @classmethod after @unittest. SkipIf (). Example: @classmethod @unittest.skipif (True, "to skip the test") def setupclass (CLS):p rint ' Set up for class '   Additionally, setUp () You can also skip all the tests, but it's different from SetupClass: SetupClass is skipping all the tests at once, running the results shows running 0 tests: ran 0 tests in 0.000s OK (skipped=1) but setup is skipping every test case Run, show the result is run N, skip N: Test_isupper (__main__. utest) ... skipped ' ... reason ... ' Test_sum (__main__. utest) ... skipped ' ... reason ... ' tesT_upper (__main__. utest) ... skipped ' ... reason ... '   8. If you want to get the total number of test cases running in the test results and the total number of successes and failures, you can do so from UnitTest. Number of failures in TestResult and total number of runs
Suite == unittest. Texttestrunner (verbosity=2= Runner.run (suite)print# Total number of test cases run Print# number of failed test cases

About Failures:a list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure is explicitlysignalled using the testcase.assert* () methods.

Python UnitTest Learning

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.