Chapter 16 documentation and testing

Generate documents with pydoc

Classification and order of document information

  1. Documentation of the module
  2. CLASSES: lists all CLASSES contained in the module
  3. FUNCTIONS: lists all FUNCTIONS contained in the module
  4. DATA: lists all class member variables contained in the module
  5. FILE: the source FILE corresponding to the module

Operating in the console

python -m pydoc Module name     #To view the help document, press the spacebar to open the next page
python -m pydoc -w Module name  #Help documents generate HTML files
python -m pydoc -w Directory name  #HTML files are generated from the help documents of all modules in the directory
python -m pydoc -p Port number  #View document information in the local server (browser)
python -m pydoc -k Module name  #Find module
  • When generating help documents by directory, the description documents of sub files should be found manually and cannot be displayed directly

Software Testing Overview

Concept: use manual and automatic means to run and test the whole system, check whether it meets the requirements, or clarify the difference between the expected results and the actual results.

Objective: to systematically find out the errors and defects in the software with the least time and manpower

Common tools: Bugzilla, BugFree, MantisBT

principle

  1. Test early
  2. Planned testing. Write test plans and prepare test cases before testing
  3. Comprehensive. All possible results are executed at least once. Each statement is executed at least once
  4. Save test results

classification

It is usually divided into unit test and comprehensive test. It can also be divided into static test and dynamic test.

  1. Code review. Consistency, standardization, readability and structural rationality of code
  2. Code analysis. Process analysis, interface analysis and expression analysis of the program
  3. Document check.
  4. Defects are found through operation and exploration

#Document test

The functions and expected results to be tested are written in annotations, and then called doctest.. Testmod(), if all tests pass, the run result is empty. Otherwise, all error lines and functions will be displayed.

'''
>>> test()  #Function to run
2
'''

def test():   #Function to be tested
    return 1

import doctest
doctest.testmod()

**********************************************************************
File "C:\Users\Administrator\Desktop\test.py", line 2, in __main__
Failed example:
    test()  #Function to run
Expected:
    2
Got:
    1
**********************************************************************
1 items had failures:
   1 of   1 in __main__
***Test Failed*** 1 failures.

PyUnit(unitest)

usage

Used to write and run repeatable tests

The test class needs to inherit unittest Testcase, and its method meets the following requirements:

  1. no return value
  2. No parameters
  3. Start with [test_]
import unitest
from To be tested.py import *
class TestModule(unittest.TestCase):
    def test_1(self):
        self.assertEqual(Function 1 (parameter), result)
    def test_2(self):
        self.assertEqual(Function 2 (parameter), result)

unittest. Assertion method in testcase

Most commonly used

Method - yesMethod - negativeparameter
assertIsNone()assertIsNotNone()x
assertTrue()assertFlase()
assertEqual()assertNotEqual()a, b
assertIs()assertIsNot()
assertIn()assertNotIn()
assertInstance()assertNotInstance()

For specific inspection

methodparameterInspection conditions
assertGreater()a, ba > b
assertLess()a < b
assertGreaterEqual()a >= b
assertLessEqual()a <= b
assertCountEqual()Two sequence elements are the same - ignore order
assertRegex()s, rr.search(s)
assertNotRegex()not r.search(s)

Exception, error, warning, log

methodparameterInspection conditions
assertRaise()exc, fun, *args, **kwdsfun() threw exc exception
assertRaiseRegex()exc, r, fun, *args, **kwdsfun() throws an exc exception,
And the exception information matches the r regular expression
assertWarns()warn, fun, *args, **kwdsfun() raises a warn
assertWarnsRegex()warn, r, fun, *args, **kwdsfun() raises a warn,
And the warning information matches the r regular expression
assertLogs()logger, levelThe With statement block uses a logger,
Generate level logs
  • *args, **kwds is the location parameter and keyword parameter of fun

Run test

In the test code, enter: unittest main()

Enter: python -m unittest test test file in CMD

Run all test cases in the directory: py -m unittest

In the test results, each character represents a test case (a method starting with test)

character[.]F - FailureE - errors - skipOK
meaningTest passedfailerrorskipAll tests passed

Run results in python

Note: be sure to use class. If you use def, the program will be interrupted when the first error is encountered

import unittest

def fun1(x):    return x+1
def fun2(y):    return x+2

class A(unittest.TestCase):
    def test_1(self):
        self.assertEqual(fun1(1),2)
    def test_2(self):
        self.assertEqual(fun1(1),1)    
    
unittest.main()  #Run the program (this line is not required when running under CMD)

Operation results

.F
=============================================================
FAIL: test_2 (__main__.A)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\test.py", line 10, in test_2
    self.assertEqual(fun1(1),1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=1)

Run results under CMD

Using the test package TestSuite

Test package: multiple test code py files can be put together; Multiple test packages can also be nested with each other

import unittest

testcase = (A, B)  #Put multiple class names to be tested together

def whole_suit():
    loader = unittest.TestLoader()
    suite = unittest.TestSuite()
    for test_class in testcase:
        tests = loader.loadTestsFromTestCase(testcase)
        suite.addTests(tests)
    return suite

if __name__ == '__main__':
    runner = unittest.TextTestRunner(verbosity=2, stream=f)
    runner.run(whole_suite())

Keywords: Python

Added by pagod on Wed, 22 Dec 2021 15:47:38 +0200