Fixture
pytest fixture 官网:
https://docs.pytest.org/en/stable/fixture.html#fixture
Fixture是在测试函数运行前后,由pytest执行的外壳函数,代码可以定制,满足多变的测试需求,
功能包括:
- 定义传入测试中的数据集
- 配置测试前系统的初始状态
- 为批量测试提供数据源等
pytest fixture 使用
方法1:直接通过函数名,作为参数传递到方法中,有返回值
import pytest
@pytest.fixture
def login():
print("login....")
return "login success"
def test_add_cart2(login):
print(login)
print("添加购物车")
方法2:使用 @pytest.mark.usefixtures(‘login’),测试用例前加上装饰器,没有返回值
import pytest
@pytest.fixture
def login():
print("login....")
return "login success"
@pytest.mark.usefixtures("login")
def test_add_cart():
print("添加购物车")
pytest fixture参数
- autouse 自动应用。默认为False,设置为True自动应用。
- scope指定作用域(session>module>class>function)
- setup-show 回溯 fixture 的执行过程
import pytest
@pytest.fixture(autouse=True)
def login():
print("login....")
return "login success"
@pytest.fixture(scope="class")
def goto_main():
print("goto mian page...")
@pytest.fixture(scope="function")
def login_out():
print("login out....")
@pytest.mark.usefixtures("goto_main")
class TestFixture:
def test_01(self):
print("test_01")
def test_02(self):
print("test_02")
def test_03(self,login_out):
print("test_03")
运行结果
test_fixture.py --setup-show
conftest.py
- conftest.py文件名固定
- conftest.py 文件就近生效
存放fixture
conftest.py
#conftest.py
import pytest
@pytest.fixture(scope="function")
def setup_and_teardown():
print("计算开始".center(30,"*"))
yield "计算中..."
print("计算结束".center(30,"*"))
test_add.py
#test_add.py
import pytest
def add(a,b):
return a + b
class TestAdd:
@pytest.mark.parametrize('a,b,expect',[[0.1,0.2,0.3],]