Recently, in order to share the automation framework , Help functional test understanding , Sort it out unittest Unit test framework

<>Unittest Composition of unit test framework

TestCase Write use cases
TestSuit Organizational use cases
TestRunner Execute use case
TestFixture Processing use cases ,SetUp - Pretreatment , Use case start ,TearTown Clean up data , End of use case

This is our encapsulated calculation function math_method.py Include addition results , Multiplication result
class MathMethod: def __init__(self, a, b): self.a = a self.b = b def add(self)
: # addition return self.a + self.b def multi(self): # multiplication return self.a * self.b
Need validation Addition and multiplication use cases , We used unittest, How do you use it? unittest And ?

1. How to define test cases
1. Guide Package :import unittest
2. Define test class : New test class must inherit unittest.TestCase
3. Define test method : The test method name must be named with test start
4. A use case is a function that cannot pass parameters , only self keyword

2. How to execute test cases
Mode 1 : use pycharm Right click the code , Select use UnitTest function
Mode 2 : call unittest.main() To run

Our new key is called test_01.py Documents , To write MathMethod() Test cases for
class TestMathMethod(unittest.TestCase): # Inherited unittest Inside def
test_add_two_positive(self): res = MathMethod(1, 1).add() print("1+1 The result is :", res)
self.assertEqual(2, res) def test_add_two_zero(self): res = MathMethod(0, 0).
add() print("0+0 The result is :", res) self.assertEqual(0, res) def test_add_two_negative(
self): res = MathMethod(-1, -2).add() print("-1+(-2) The result is :", res) self.
assertEqual(-3, res) # implement if __name__ == '__main__': unittest.main()
Run results after execution , We ran away 3 Article use case , But we found that the execution order is not executed according to the use cases we defined , Why ?

Use case execution sequence : according to ASCII The order is from small to large ,a-z

TestFixure Test fixture

  TestFixure There are two ways to use it , One is written in a common way steup(),teardown(), When this is implemented , One test method in each class is executed , Before implementation setup(), After execution teardown().

   Another way is to write into classes , use @classmethod,setUpClass() and tearDownClass(), This is when executed , Will execute first setupClass(), After executing all test cases in the class , implement tearDownClass() Methods in .
class TestMathMethod(unittest.TestCase): # Inherited unittest Inside def setUp(self): #
step Each test case is executed before it is executed setUp inside print(" I'm going to start executing use cases ") def tearDown(self): # rewrite
#tearDown Each use case is executed after execution print(" I have finished executing the use case ") # if You have operations that must be performed before the use case is executed get ready Then put it setUp
# If you have operations that must be cleared after the use case is executed, put them in tearDown def test_add_two_positive(self): res =
MathMethod(1, 1).add() print("1+1 The result is :", res) # Add an assertion : Judge the comparison structure between expected value and actual value Consensus is passed
Inconsistency is failure self.assertEqual(2, res) def test_add_two_zero(self): res = MathMethod(0
, 0).add() print("0+0 The result is :", res) self.assertEqual(1, res, " Error ") # If the use case fails to execute, it will be prompted
def test_add_two_negative(self): res = MathMethod(-1, -2).add() print(
"-1+(-2) The result is :", res) self.assertEqual(-3, res)
<> Write test cases , It's time to load the use case , Let's find out unittest How to load test cases

<>unittest How to load test cases

When the number of test cases is small, the following methods can be used to load

1, Add one by one
suite = unittest.TestSuite() suite.addTest( Test class name (' Method name ')) # give an example
Test class name :TestMathMethod, Method name :test_add_two_negative #
suite.addTest(TestMathMethod('test_add_two_negative'))
2, Load through test class (loadTestsFromTestCase)
suite = unittest.TestSuite() loader = unittest.TestLoader() # Use case loader suite.
addTest(loader.loadTestsFromTestCase( Test class name )) # give an example : We need to introduce class names , Load the use case under the class name # from
test_01 import TestMathMethod # Specific to class name #
suite.addTest(loader.loadTestsFromTestCase(TestMathMethod))
3, Load by module (loadTestsFromModule)
suite = unittest.TestSuite() loader = unittest.TestLoader()# Use case loader suite.addTest
(loader.loadTestsFromModule( Test module name )) # give an example : We need to introduce the module name , Use cases under load module # from
class_unittest import test_01 # Specific to class name #
suite.addTest(loader.loadTestsFromModule(class01))
When there are many test cases , use defaultTestLoader.discover() mode
discover = unittest.defaultTestLoader.discover(start_dir,pattern='test*.py',
top_level_dir=None) #
1, because unittest Specified in , Test cases must test start , therefore discover Medium pattern Format is test*.py #
2,start_dir Is the directory where test cases are stored
<> understand unittest.TextTestRunner()

test runner As the name suggests, it is used to execute test cases , And the corresponding test report can be generated . The test report can be displayed in two forms , One is text text , One is html format .

suite = addTest(test_class)
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
file: Files written
verbosity:0,1,2, Increase with number , The information written is more detailed

Python Understanding and use of context manager in
A context manager is an object that wraps an arbitrary block of code .
The context manager guarantees that when entering the context manager , Consistency of each code execution .
When exiting the context manager , Relevant resources will be recycled correctly .

Store test results in test.txt file , Ask the manager up and down , Can save resources
# implement Context manager --- original with open("test.txt", 'w+', encoding='UTF-8') as file: runner
= unittest.TextTestRunner(stream=file, verbosity=2) # 0,1,2 verbosity=2 Most detailed
runner.run(suite) #print(file.closed) #file.closed Determine whether to close the file True close
<> Advanced —— use HTMLTestRunner Output beautiful HTML report

We can output txt Format text execution report , But the text report is too crude , Do you want to be taller HTML report ? but unittest I didn't bring it myself HTML report , We can only turn to external libraries .

HTMLTestRunner It's a third party unittest
HTML Report Library , First we download HTMLTestRunner.py, And put it in the current directory , Or yours ’C:\Python27\Lib’ lower , You can import and run .
from tools.HTMLTestRunnerCN import HTMLTestReportCN # Import # Context manager ,, To save resources with
open('test_report.html', 'wb') as file_path: runner = HTMLTestReportCN(stream=
file_path, title=" Little mushy —API Automated test report ", description=' Little mushy —API Module use case ', tester=' Little mushy ',
verbosity=2) runner.run(suite)
establish class02.py File to execute the use case
# Look inside the module from class_unittest import class01 # Specific to module # Will take all test Add all the first test cases to the container
loader= unittest.TestLoader() # Create a loader suite.addTest(loader.loadTestsFromModule
(class01)) # implement with open('test_report.html', 'wb') as file_path: runner =
HTMLTestReportCN(stream=file_path, title=" Little mushy —API Automated test report ", description=
' Little mushy —API Module use case ', tester=' Little mushy ', verbosity=2) runner.run(suite)
results of enforcement , Output test report

Technology
Daily Recommendation