conftest.py 脚手架工具
在做自动化测试的时候,需要进行接口的执行时的控制,比如接口运行之前,以及接口运行之后的进行操作。
在pytest中,可以将这些操作都放在 conftest.py 文件中进行配置。
注意: conftest.py 文件名为固定用法。(文件名必须要这样定义)
conftest.py
"""
pytest 运行时的配置文件
"""
import pytest
# 定义函数级别的脚手架
@pytest.fixture(scope='function',autouse=True)
def func():
print('测试用例执行之前操作')
yield
print('测试用例执行之后的操作')
test_cases.py
def test_01():
print('test_01')
def test_02():
print('test_02')
def test_03():
print('test_03')
执行效果
运行 test_cases.py 文件
pytest -s -v test_cases.py
可以看到,会自动执行 conftest.py 文件中定义的操作。
conftest.py
"""
pytest 运行时的配置文件
"""
import pytest
# 函数的运行级别
@pytest.fixture(scope='function',autouse=True)
def func():
print('测试用例执行之前操作')
yield
print('测试用例执行之后的操作')
# 类运行之前,之后执行
@pytest.fixture(scope='class',autouse=True)
def classes():
print('类运行之前执行')
yield
print('类运行之后操作')
# 整个py文件执行
@pytest.fixture(scope='module',autouse=True)
def module():
print('py文件执行之前')
yield
print('py文件执行之后')
# 整个包执行
@pytest.fixture(scope='package',autouse=True)
def package ():
print('包执行之前')
yield
print('包执行之后')
# 所有的用例执行之前
@pytest.fixture(scope='session',autouse=True)
def session():
print('所有用例执行之前')
yield
print('所有的用例执行之后')
conftest.py 文件主要就是定义了测试用例执行的先后顺序。
主要的级别有:
- function 函数级别
- class 类级别
- module 模块级别
- package 包级别
- session 所有用例级别
pytest-order 执行测试用例的执行顺序
默认的测试用例执行的顺序是按照编写测试用例的先后顺序来执行。
pytest-order 可以用看控制测试用例的执行顺序。
安装pytest-order
也可以在命令行模式下进行安装
pip install pytest-order
如何使用
在测试用例上面指定执行顺序。
test_cases.py
import pytest
@pytest.mark.order(2)
def test_01():
print('test_01')
@pytest.mark.order(3)
def test_02():
print('test_02')
@pytest.mark.order(1)
def test_03():
print('test_03')
在用例上面 通过 使用 pytest.mark.order() 指定执行的先后顺序。
@pytest.mark.order(1) 第一个执行。