What is firmware
Fixture Translated into Chinese means firmware . It's actually some functions , Will execute the test method / Before testing the function ( Or after ) Load and run them , Common examples are the initial connection of the database before the interface is requested , And closing the database after the request .
We were APP UI Automation series Has been introduced in unittest Relevant test firmware , Such as setup、teardown etc. . and pytest It provides more functions Fixture, Used to implement setup、teardown function .
Define the way
Use @pytest.fixture() Define , A simple example is as follows :
import pytest
@pytest.fixture()
def before():
print(" Connect to database ")
Call mode
Call single fixture function
Mode one , Use fixture Function name as argument
import pytest @pytest.fixture() def before(): print(" Connect to database ") # call before def test_01(before): print(" perform test_01")Mode two , Use
@pytest.mark.usefixtures('fixture Function name ')Decoratorimport pytest @pytest.fixture() def before(): print(" Connect to database ") # call before @pytest.mark.usefixtures('before') def test_01(): print(" perform test_01")Mode three , Use
autouseParameter automatic executionfixturefunctionimport pytest # fixture Used when defining functions autouse Parameters , This is called automatically by test cases within the scope fixture function @pytest.fixture(autouse=True) def before(): print(" Connect to database ") # Automatically call before def test_01(): print(" perform test_01")
The results of the three methods are as follows :

We can see , First executed. fixture function , Then execute the test function .
Call multiple fixture function
import pytest
@pytest.fixture()
def before():
print(" Connect to database ")
@pytest.fixture()
def before_s():
print(" Initialization data ")
def test_01(before, before_s):
print(" perform test_01")
Call multiple fixture Function time , From front to back , therefore test_01() Execute... Before calling before, Re execution before_s.
Yes fixture Function renaming
Definition fixture Function time , You can use name Parameter to rename , Convenient for calling , Examples are as follows :
import pytest
@pytest.fixture(name='db')
def connect_order_db():
print(" Connect to database ")
def test_01(db):
print(" perform test_01")
Use fixture Passing test data
The execution of the fixture After the function , Sometimes it is necessary to fixture Some data obtained in the test function is passed to the test function / The test method , For subsequent execution .
fixture There are two data transfer methods: general transfer and parametric transfer .
Ordinary transmission
Examples are as follows :
import pytest
@pytest.fixture()
def before():
print(" Connect to database ")
return " Successful connection !"
def test_01(before):
print(" perform test_01")
assert before == " Successful connection !"
Be careful , If customized fixture Function has return value , You need to use the above-mentioned method to obtain fixture Function and pass it into the test function , The return value cannot be obtained in mode 2 .
Parameterized transfer
Yes fixture When a function is parameterized , You need to use parameters params, Parameters are passed in and required request, A simple example is as follows :
import pytest
test_params = [1, 2, 0]
@pytest.fixture(params=test_params)
def before(request):
result = request.param
return result
def test_02(before):
print(" perform test_02")
assert before
if __name__ == '__main__':
pytest.main()
Execution results :

You can see , Because the called fixture The function is parameterized , Although there is only one test function, it is executed 3 Time .
conftest.py
The above examples are all fixture The function is placed in the test case module , But if many test modules need to reference the same fixture What about functions , It's time to put it in a place named conftest In the module of , such Same level or below The test cases in the can call these custom test cases fixture function .
for example , There is a list of :
├─testcase
│ │
│ ├─test_module_01
│ │ test_case_1.py
│ │ test_case_2.py
│ │
│ ├─test_module_02
│ │ test_case_3.py
test_module_01 Medium test_case_1.py And test_case_2.py All need to call the same fixture function , Then we just need to test_module_01 New China conftest.py And write this fixture Function , Examples are as follows :
├─testcase
│ │
│ ├─test_module_01
│ │ conftest.py
│ │ test_case_1.py
│ │ test_case_2.py
│ │
│ ├─test_module_02
│ │ test_case_3.py
conftest.py:
import pytest
@pytest.fixture(autouse=True)
def before():
print(" Connect to database ")
test_case_1.py:
def test_01():
print(" perform test_01")
test_case_2.py:
def test_02():
print(" perform test_02")
such , When the two test cases are called, they will be automatically executed first conftest.py Medium before() function .
hypothesis test_module_02 Medium test_case_3.py You also need to call this before() function , Then at this time, we need to be on the upper layer, that is testcase New China conftest.py And write this before() function , Can be in test_case_3.py Call in , as follows :
├─testcase
│ │ conftest.py
│ │
│ ├─test_module_01
│ │ conftest.py
│ │ test_case_1.py
│ │ test_case_2.py
│ │
│ ├─test_module_02
│ │ test_case_3.py
conftest.py Only for At the same level or following Test modules in the directory , And we need Be careful , When following There is another in the hierarchy conftest.py, Then the following levels will be determined by another conftest.py File take over .
Scope
pytest Of fixture The scope is divided into session、module、class、function Four levels . In defining fixture Function through scope Parameter specifies the scope of action , The default is function.
session, Execute once per sessionmodule, Once per test moduleclass, Execute once per test classfunction, Once per test method
Be careful , For separately defined test functions ,class、function It all works , You can see from the following example .
The test directory structure is as follows :
├─apiAutoTest
│ │ run.py
│ │
│ ├─testcase
│ │ │ conftest.py
│ │ │
│ │ ├─test_module_02
│ │ │ │ conftest.py
│ │ │ │ test_case_3.py
│ │ │ │ test_case_4.py
among conftest.py The code is as follows :
import pytest
@pytest.fixture(scope="session", autouse=True)
def session_fixture():
print(" This is a function of session Of fixture")
@pytest.fixture(scope="module", autouse=True)
def module_fixture():
print(" This is a function of module Of fixture")
@pytest.fixture(scope="class", autouse=True)
def class_fixture():
print(" This is a function of class Of fixture")
@pytest.fixture(scope="function", autouse=True)
def function_fixture():
print(" This is a function of function Of fixture")
test_case_3.py The code is as follows :
import pytest
class TestOrder:
def test_a(self):
print("test_a")
def test_b(self):
print("test_b")
def test_c():
print("test_c")
test_case_4.py The code is as follows :
def test_e():
print("test_e")
run.py The code is as follows :
import pytest
if __name__ == '__main__':
pytest.main(["-s"])
function run.py, give the result as follows :
collected 4 items
testcase\test_module_02\test_case_3.py
This is a function of session Of fixture
This is a function of module Of fixture
This is a function of class Of fixture
This is a function of function Of fixture
test_a
. This is a function of function Of fixture
test_b
. This is a function of class Of fixture
This is a function of function Of fixture
test_c
.
testcase\test_module_02\test_case_4.py
This is a function of module Of fixture
This is a function of class Of fixture
This is a function of function Of fixture
test_e
.
============================== 4 passed in 0.04s ==============================
It can be seen from the result that :
- Act on
sessionOf fixture The function is called once before all test cases are executed. - Act on
moduleOf fixture The function is called once before each test module is executed. - Act on
classOf fixture The function is called once before each test class is executed. - Act on
functionOf fixture Function in each test method / The test function was called once before it was executed.
Be careful , In the defined test function ( Such as test_c()、test_e()) Before execution, it will also call scope=class Of fixture function .
summary
And unittest Frame comparison ,pytest Medium Fixture More abundant , More scalability .
Fixture There are many more elegant uses for automated test projects , This article is just the simplest example .








![Error when installing MySQL in Linux: starting mysql The server quit without updating PID file ([FAILED]al/mysql/data/l.pid](/img/32/25771baad1ed06c5a592087df748f1.jpg)