Unittest unit automated testing framework-summary of knowledge points

unittest unit testing framework
1. Import the unittest package
============================================ ===============================
2. When creating a class, you must inherit unittest.TestCase class
2.1. The setUp method is in 2.2 is the initialization work before the test is executed in the class
. The tearDown method is the cleanup work after the test is executed in the class
2.3. The test case function method starting with test is an ordinary test case method
. The test cases are loaded in the order of the ACSII code. The numbers and The order of letters is: 0~9, A~Z, a~z
2.4. In the main entrance main, use the unittest.main() method to execute the method starting with test.
Note: When executing, the specified module under run should be used. Execution cannot be executed with unittest in module, otherwise it will be executed repeatedly
======================================= ===================================
3. Set assertion You can set self.assertEqual
in the function of the test case
(4, demo02_calc.sum(2,2), "Test whether sum passes")
Commonly used assertions
self.assertEqual(4,4) # Determine whether they are equal
self.assertTrue(a) # Determine whether they are true
self.assertIn(" Ma Nu",name) # Determine whether it is inside
self.assertGreater(4,2) # Determine whether it is greater than
============================ =============================================
4. Ignore use cases:
@unittest.skip("Skip unconditionally"),
@unittest.skipIf(True,"Skip if the condition is true")
@unittest.skipUnless(False,"Skip if the condition is false False"),
@unittest.expectedFailure #Execution failures are not counted in the number of failures

================================================== ======================
5. Test case execution sequence: (If the test suite is not used, it is executed in the order of the ASCII code. If the test suite is used, Executed in the order in which the test suite is added)
5.1, Method 1: (Executed through the addTest method (test cases that do not start with test executed through the test suite can also be executed))
Create an instance of the test suite in the main entrance: suite = unittest .TestSuite()
then uses the addTest(class name (method name)) method to execute the test cases in order (executed one by one) through the instance
suite.addTest(class name ("method name 1"))
suite.addTest(class name ( "Method name 2"))
suite.addTest(class name("Method name 3"))
unittest.main(defaultTest="suite")
or (similar to method 1, the method of writing a test suite is as follows)
put unittest.Testsuite Write the method
def suite():
suite = unittest.TestSuite()
suite.addTest(test_case("test_bbb")) # addTest(class name ("method name"))
suite.addTest(test_case("ccc"))
return suite
if __name__ == '__main__':
unittest.main(defaultTest="suite")

5.2, Method 2: (unittest.makeSuite() adds the entire test class)
if __name__ == '__main__':
# Note: Methods that do not start with test will not be added to the test suite at this time
# Note: makeSuite may need to be manually executed Add
suite = unittest.TestSuite(unittest.makeSuite(test_case)) # Inside is the class name
unittest.main(defaultTest="suite")

5.3, method three (unittest.TestLoader().loadTestsFromName() adds the test class under the entire .py file)
if __name__ == "__main__":
# Load test cases through the string method in TestLoader
# 1, add a test case module Name. Class name. Method name
# suite = unittest.TestLoader().loadTestsFromName("demo11_test suite 4.test_case1.test_aaa")
# 2, add the entire test class
# suite = unittest.TestLoader().loadTestsFromName("demo11 _Test Suite 4.test_case1")
# 3, add all test classes under the entire .py module
suite = unittest.TestLoader().loadTestsFromName("demo11_Test Suite 4")
unittest.main(defaultTest='suite')

5.4, ​​method four (create multiple sub-suites and then integrate them into a large main suite):
first import the packages of other py modules, then create multiple sub-suites and then
create a main suite, and pass the multiple sub-suites through the addTest() method Add to the main suite
import unittest
from unittest framework import demo11_test suite 4
from unittest framework import demo08_test suite 1
# Create multiple suites
#1 in sequence, single use case suite
suite01 = unittest.TestLoader().loadTestsFromName('demo08_ Test suite 1.test_case.test_aaa')
# 2, the entire class
suite02 = unittest.TestLoader().loadTestsFromName("demo08_test suite 1.test_case")
# 3, the entire .py module
suite03 = unittest.TestLoader().loadTestsFromName ("demo11_Test Suite 4")
main_suite = unittest.TestSuite() # Main suite
main_suite.addTest(suite01) # Add sub-suite to the main suite
main_suite.addTest(suite02)
main_suite.addTest(suite03)
unittest.main(defaultTest ="main_suite")

5.5, Method 5: (Use discover() to add and execute all test cases in the entire directory)
First import the required package, then find the path to the all_case directory through os, and then use the unittest.defaultTestLoader.discover() method to match the All use cases
create a suite, add discover through the addTest(discover) method, and finally execute
import os
import unittest
import HTMLTestRunner
import time
curren_path = os.path.dirname(__file__)
print( curren_path)
case_path = os.path.join(curren_path,"all_case")

# Return to the previous path from the current path
# case_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
print(case_path)

discover = unittest.defaultTestLoader.discover(start_dir=case_path, # Use case path
pattern="*_case*.py",
top_level_dir=None) # File type
# print(discover)
main_suite = unittest.TestSuite()
main_suite.addTest(discover)
unittest.main(defaultTest="main_suite")
========================================== ================================
6. Use the unittest.main() method to execute code
6.1. If you use the test suite, Use unittest.main(defaultTest="suite")

================================================== ======================
7. Convert unicode code to Chinese
name.encode("utf-8").decode("unicode_escape") # Convert to Chinese

================================================== ======================
8. Import the HTMLTestRunner package to generate a test report
# Execute and generate a test report
# Add a timestamp
now = time.strftime( "%y-%m_%d_%H_%M_%S_",time.localtime(time.time()))
file_obj = open("D:/pythonProject/P7_P8_Requests/"
"unittest framework/test_report/"
"{} test_report.html".format(now),"w+",encoding="utf-8")
# Create a test report object and write the execution process to file_obj
runner = HTMLTestRunner.HTMLTestRunner(stream=file_obj,
title=" The first test report",
description="I am the description information of the test report")
runner.run(main_suite)
======================== ================================================

Display of detailed information unittest.main(verbosity=2)
0 (silent mode): You can only get the total number of test cases and the total results.
1 (default mode): Very similar to silent mode except that there is an "." in front of each successful test case and an "E" in front of each failed test case.
2 (verbose mode): The test results will display all test cases for each test case. Related information and you can have the same effect by adding different parameters to the command line

Below the method of the test case---write the annotation information of the test---reflect it in the report
self._testMethodName = "API_CASE_01"
self._testMethodDoc = "Verify that the token acquisition interface can be called normally"

Python interface automated testing from zero foundation to mastery (2023 latest version)

Guess you like

Origin blog.csdn.net/ada4656/article/details/134494179