unittest python unit testing framework

unittest

Providing two methods loading unit testing:

1. The loading unit test test module directly through unittest.main () method;

2. Add all of the test suite to test cells set, and then loading all the test objects at once.

Unit test cases

Unittest framework constructed by TestCase Class test, and requires all the custom test classes must inherit the class, which is the base class for all test cases. Create a custom test method must start with "test".

Several special method TestCase class defined as follows:

1. setUpClass (): Before running any test method is run, the unit test preparation, must be modified to use @classmethod decorator, executed before setUp function, the entire testing process is performed only once.

2. setUp (): method before each test run, the initialization operation before the test;

3. tearDown (): method after the end of each test run operation, clean up after the test;

After the implementation of all the test method execution after the end of the run, unit testing late to clean up, you must use @classmethod decorator modified, tearDown (), the entire testing process is performed only once: 4. tearDownClass ().

# Introducing time 
Import Time
# introduced webdriver library
from selenium import webdriver
Introducing unittest module # 
Import unittest

class Visit (of unittest.TestCase):
    DEF the setUp (Self):
        self.driver webdriver.Chrome = ()
   # calls the API code contained in the process starts with the "test" command
    def test_visit (self) :
        self.driver.get ( "http://www.baidu.com" )
        self.driver.find_element_by_id ( "kw" ) .send_keys ( "selenuim" )
        the time.sleep (2)
        Print (self.driver.current_url)

    tearDown DEF (Self):
        self.driver.quit ()
# main () method is the default method of classes at the beginning of test execution, not necessarily a top-down implementation of test cases, but the name of the method in accordance with the ASCII coding according to the location of the order execution.
the __name__ == IF '__main__' :
    unittest.main ()
Assertion methods

By unittest provided assertEqual () method to assert that the result is the same as the expected results. There are many assertion methods, not listed here.

Test Results:

. "" Dot represents a test case by using the operation;

With "F" means a failure to run test cases;

With "s" represents a skipped test run;

With "E" represents a running error test cases;

Ignore test

Ignore test is divided into unconditional and conditional ignored ignored. When you run the test, and sometimes need to skip some of the test cases, or skip the test when the test case meet a certain criteria, or directly to the test cases to fail.

unittest provides an implementation of these requirements decorator.

Import the unittest
class the MyTest (of unittest.TestCase):
    @ unittest.skip ( "unconditional skip decorative test, the test needs to skip the reasons" )
    DEF test_skip (Self):
        Print ( "Test A" )
    @ unittest.skipIf (3> 2, "when the condition is true, the test is skipped decoration" )
    DEF test_skipIf (Self):
        Print ( "test B" )
    @ unittest.skipUnless (3> 2, "when the condition is true, execution decorated test " )
    DEF test_skip_unless (Self):
        Print ( " the test c " )
    # downstream decorator regardless of whether the results of failure are marked as failed the test, but do not throw the failure information
   
@ unittest.expectedFailure
    DEF test_expected_failure ( self):
        self.assertEqual(2, 3)

Use HTMLTestRunner generate HTML test report

After completion of the test unit, the test report may be generated by HTML HTMLTestRunner. Before performing the test results are output to the console, is neither easy to read nor attractive.

Download HTMLTestRunner.py file:

1) Download the file HTMLTestRunner.py: http://tungwaiyip.info/software/HTMLTestRunner.html

2) windows operating system files will be downloaded into the python lib installation file folder path;

Ubuntu operating system files will be downloaded into the file dist-packages python installation path folder;

 

MacOSX operating system files will be downloaded into the site-packages python installation file folder path;

Open a command terminal switches to the red line of the catalog file folder:

cd /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/

Then copy the downloaded file to HTMLTestRunner.py the current folder:

 

HTMLTestRunner is python2 in due python2 and 3 are part of the syntax changes, so it is necessary to modify the downloaded file to use in python3 in.

Modify the file HTMLTestRunner.py file:

Line 94 will be modified to import io import StringIO

Line 539, the self.outputBuffer = StringIO.StringIO () modified self.outputBuffer = io.StringIO ()

The first 642 rows will if not rmap.has_key (cls): modified if not cls in rmap:

The first line 766, the uo = o.decode ( 'latin-1') modified uo = e

Line 772, the ue = e.decode ( 'latin-1') modified ue = e

第631行,将print >> sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime)修改成print(sys.stderr, '\nTime Elapsed: %s' % (self.stopTime-self.startTime))

3, the introduction of use:

1)引包:from HTMLTestRunner import *

2), such as:

if __name__ == '__main__':
    report = REPORT_PATH + '\\report.html'
    with open(report, 'wb') as f:
        runner = HTMLTestRunner(f, verbosity=2, title='Test', description='测试报告')
        runner.run(TestBaidu('test_search'))

备注:

1) I started with the import HTMLTestRunner, when the execution of the above

2) the penultimate line error: TypeError: 'module' object is not callable.
Out of two ways when using the difference, import module: module name for an add defined use, and from HTMLTestRunner import * need not be added. Can be the following two ways:
. 1,
from HTMLTestRunner Import *
Runner HTMLTestRunner = (F, the verbosity = 2, title = 'the Test', Description = 'test report')

2、
import HTMLTestRunner
runner = HTMLTestRunner.HTMLTestRunner(f, verbosity=2, title='Test', description='测试报告')

for example:

# Introducing time Import Time, os # introduced webdriver library from the Selenium Import webdriver # introduced unittest module Import unittest # introduced HMTL test report module Import HTMLTestRunner class from Visit (unittest.TestCase): DEF the setUp (Self):         self.driver = webdriver.Chrome () # API calling code will be included in order to "test" process starting command DEF test_visit (Self):         self.driver.get ( "http://www.baidu.com" )









   

  
   


        self.driver.find_element_by_id ( "kw" ) .send_keys ( "the Selenium" )
        self.driver.find_element_by_css_selector ( "the INPUT # su.bg.s_btn" ) .click ()
        the time.sleep (2)
        self.assertEqual ( "selenium_ Baidu Search " , self.driver.title)

    DEF tearDown (Self):
        self.driver.quit ()

IF __name__ == '__main__' :
    # test suite
   
TestUnit = unittest.TestSuite ()
    # add a test case to a test suite
   
testunit. addTest (from Visit ( "test_visit" ))
    # get the current time
   
nowtime = time.strftime ("% D%% m_Low Y_% H:% M:% S" )
    # define a report storage path, and a different distinguished names generate multiple reports by the script execution time
   
REPORT_PATH = '/ the Users / yuandaping / Downloads /'
   
Report = + REPORT_PATH '/' + + nowtime 'report.html'
   
# define test report with Open (report, 'WB' ) AS F:         Runner = HTMLTestRunner.HTMLTestRunner (F = Stream, title = ' Baidu Search test report ' , Description = ' implementation Example used: ' ) # run test runner.run (TestUnit) # close the report file f.close ()
   


       
       

       
       

After running the script generated report files: / Users / yuandaping / Downloads / 2019_09_23 17: 53: 54report.html

 

Note:

DDT is a unit testing framework designed for unittest extension libraries. It allows the use of different test data to a test run, and by displaying a plurality of test cases.

Installation: pip3 install ddt

Parameterized Python is a parameter of the library, while supporting unittest, nose and pytest unit testing framework.

Installation: pip3 install parameterized

Guess you like

Origin www.cnblogs.com/douyini/p/12650635.html