程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of Python pytest testing framework

編輯:Python

pytest Introduce :
pytest Is a very mature full-featured Python The test framework :
1. Simple and flexible , Easy to use
2. Support parameterization
3. Of test cases skip and xfail, Automatic failure retry and other processing
4. Support simple unit testing and complex functional testing , It can also be used to make selenium/appnium Wait for automated testing 、 Interface automation testing (pytest+request)
5.pytest There are many third-party plug-ins , And you can customize the extension , It's easy to use pytest- allure( perfect html Test report generation )、pytest-xdist( many CPU distribution ) etc.
6. It can be very good and jenkins Integrate

install pytest:pip install -U pytest among -U It's right pytest updated pytest – version: View version number
Identification and operation of test cases :
distinguish :
The test file :
1.test_.py
2.
test.py
Use case identification :
1.Test* Class contains all test
* Methods ( Test class cannot have __init__ Method )
2. be not in class All in test_* Method
pytest It can also be executed unittest Use cases and methods written in framework
function :
pytest -v : You can run detailed log information
pytest -s : You can print out the test samples print The content of
pytest file name .py:: Class name : Run the classes in a module
pytest file name .py:: Class name :: Method name : Run a method of a class in a module
pytest -v -k" Class name and not Method name ": Skip running a use case
pytest -m[ Tagnames ]:@pytest.mark.[ Tagnames ] The test case with this tag will be run
pytest -x file name : Stop running once an error is reported
pytest --maxfail=[num]: When the running error reaches num It stops running when it's running

pytest perform - Failed to rerun :
scene : Rerun the test after it fails n Time , To add a delay between reruns , interval n Seconds running
install :pip install pytest-rerunfailures
perform :
1.pytest – reruns 3 -v -s test_class.py( Set to run again n Time )
2.pytest -v – reruns 5 --reruns-delay 1( Set the delay time )
pytest perform - Multiple assertions run even if they fail
scene : Write multiple assertions in a method , Usually the first one doesn't pass , I won't do it now , If we want to report an error, we'll do it
install :pip install pytest-assume
perform :
1.pytest.assume(1==4)

2.pytest.assume(2==4)

pytest Frame structure
import pytest Allied setup,teardown Also more flexible
1. Module level (setup_module/teardown_module) Module beginning and end , Overall ( Highest priority )
2. Function level (setup_function/teardown_function) Only for function use cases ( Not in class )
3. Class level (setup_class/teardown_class) Run back and forth in the class only once ( In class )
4. Method level (setup_method/teardown_method) Start from the beginning and end of the method ( In class )
5. In class (setup/teardown) Run before and after calling the method

pytest-fixtrue Usage of
scene :
1. Use cases 1 You need to log in first
2. Use cases 2 You don't need to log in
3. Use cases 3 Need to log in
This scenario doesn't work setup and teardown Realization
usage : Add... Before the method @pytest.fixture()
scene : When the test case is executed , Some use cases need login to execute , Some use cases do not require login ,setup and teardown Unable to meet .fixture Sure , Default scope( Range )function
step :
1. Import pytest
2. Add... Before the login function @pytest.fixture()
3. In the test method to be used, pass ( Login function name ), Just log in first
4. If you don't pass in, you don't log in and directly execute the test method
Application in front-end automation -conftest
scene : When you work with other test engineers to develop , Common modules should be in different files , Where everyone can visit
solve :conftest.py This file is used for data sharing , And it can be placed in different positions to play the role of sharing in different ranges
perform : The system executes to the parameter login First, look for the variable with this name from this file , After the conftest.py Find out if there is
step : Bring the login module to @pytest.fixture() Written in conftest.py in
conftest.py Configuration needs attention :
1.conftest The file name cannot be changed
2.conftest.py The same as the running use case package Next , And there are __init__ file
3. Unwanted import Import conftest.py file ,pytest Use cases are automatically found
4. The global configuration and preliminary work can be written here , Put it under a bag , This is where the package is shared
Application in front-end automation -yieid
scene : You can solve the problems that the test method needs to execute or depend on , How to destroy clear data after testing methods ? The scope is at the module level . similar setupClass
solve : By adding the first mock exam module yieid keyword ,yield Is the result returned for the first time , The second execution of the following statement returns
step : stay @pytest.fixture(scope=module)
Add... To the login method yieid, Then add clear steps to destroy , Be careful , This method does not return a value , If you want to return to use addfinalizer
fixture Automatic application of
scene : I don't want to make any changes to the original test method , Or all of them automatically , No exception , You can choose to apply automatically when you don't need a return value
solve : Use fixture In the parameter autouse=True Realization
step :
1. Add... To the method @pytest.fixture(autouse=True)
2. Add... To the test method @pytest.mark.usefixtures(“start”)
autouse: You can use the method in every test case
fixture Passing with parameters
scene : Testing is inseparable from data , For data flexibility , General data is transmitted through parameters
solve :fixture By fixing parameters request Pass on
step : stay fixture add @pytest.fixture(params=[1,2,3,‘linda’]) Write... In the method parameters request

@pytest.mark.skip(‘ Do not execute this article case’): This use case may not be executed on the method
@pytest.mark.skipif(sys.platform==‘darwin’,reason=‘ be not in macOS perform ’): By judging the current system Give the reason for not executing this use case

import pytest
# Method name as parameter
test_user_data = ['jerry','Tome']
@pytest.fixture(scope='module')
def login_r(request):
# This is the parameter that is accepted and passed in
user = request.param
print(f"\n Open the home page and get ready to log in Landing user {user}")
return user
@pytest.mark.skip(' Do not execute this test case ')
# indirect=True, You can execute the passed parameter as a function 
@pytest.mark.parametrize("login_r",test_user_data,indirect=True)
def test_case01(login_r):
a = login_r
print(f" In the test case login The return value of :{a}")
assert a != ''
if __name__ == '__main__':
pytest.main()

skip Use scenarios
1. You don't want to run this test case while debugging
2. Mark test functions that cannot be run on some platforms
3. In some versions , Skip in other versions
4. Skip when current external resources are not available ( If the test data is taken from the database , The function of connecting to the database. If the result is not successful, skip , Because the execution also reports errors )
solve :
@pytest.mark.skip(): Skip this test case , You can add conditions skipIf, Only when certain conditions are met can we hope to pass , Otherwise, skip this test
Xfail scene
1. Errors that have not been implemented or repaired by functional tests , When the test passes, though it is expected to fail ( Marked as pytest.mark.xfail), He is a xpass Will be reported in the test summary
2. You want the test to fail for some reason
solve :
@pytest.mark.xfail
Use custom tags mark Execute only some use cases
scene :
1. Execute only a part of the use case that meets the requirements , You can put a web The project is divided into several modules , Then specify the module name to execute
2.App When automating , If you want to Android and IOS When sharing a set of codes , You can also use the tagging function , Indicate what is IOS The use case , Which are Android The runtime knows mark Just run by name
solve : Add... To the test case method @pytest.mark.webtest
perform :
1.-s Parameters : Output the... Of the test cases used print Information
2.-m: Execute relevant use cases of custom tags ( Use the command to execute )
pytest -s test.py -m=search
pytest -s test.py -m apptest
pytest -s test.py -m ‘not ios’
Multithreading, parallel and distributed execution
scene : The test case 1000 strip , A test case executes for one minute , A tester needs to perform 1000 minute , Usually, the cost of labor is exchanged for the cost of time , Add a few people to execute together , Time will be shortened , If 10 Individual execution only needs 1000 minute , This is a parallel test , Distributed scenarios .
solve :pytest Distributed execution plug-ins :pytest-xdist, Multiple cpu Or host execution Premise : Use cases are all independent , There is no order , It can be executed at random , Repeatable execution does not affect other use cases .
install :pip install pytest-xdist
Multiple CPU Execute use cases in parallel , direct -n 3 It's the parallel number :pytest test.py -n 3
Execute together under multiple terminals
pytest-html Generate test reports
install :pip install pytest-httml
Generate test reports :pytest -v -s --html=report.html --self-contained-html


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved