内置 fixtures:
前面说过我们可以通过自定义 fixture 来实现测试用例的前置和后置工作,其实 pytest 中也有一些内置的 fixture 可供我们调用;
内置 fixture 的作用就是为了使 pytest 更加强大,它可以修改控制 pytest 的行为,以及为我们提供一些更加便利的功能。
pytestconfig:
pytestconfig 可以通过命令行参数、选项、配置文件、插件、运行目录等方式来控制pytest;
pytestconfig 实际上就是 request.config 的快捷方式,被称为“pytest 配置对象”;
源码展示:
# fixtures.py
@fixture(scope="session")
def pytestconfig(request):
"""Session-scoped fixture that returns the :class:`_pytest.config.Config` object.
Example::
def test_foo(pytestconfig):
if pytestconfig.getoption("verbose") > 0:
...
"""
return request.config
源码中的 request 是 FixtureRequest 的实例对象,FixtureRequest 在官方的描述中是这样的:
FixtureRequest 是来自 fixture 或者 测试用例的请求,它有访问测试上下文的权限;
request.config 则是 FixtureRequest 中的属性:
class FixtureRequest:
""" A request for a fixture from a test or fixture function.
A request object gives access to the requesting test context
and has an optional ``param`` attribute in case
the fixture is parametrized indirectly.
"""
...
@property
def config(self):
""" the pytest config object associated with this request. """
return self._pyfuncitem.config
request.config 返回的是 `_pytest.config.Config` (pytest 配置对象):
它可以访问配置值、插件管理器和插件挂钩;
然后 Config 中提供的方法中,我们最长使用的就是 getoption() 和getini():
getoption() 可以获取命令行的值;
getini() 可以获取 pytest.ini 配置文件的参数值;
使用 pytestconfig 获取命令行参数的值:
方法参数:
def getoption(self, name: str, default=notset, skip: bool = False):
""" return command line option value.
"""
...
pytestconfig 这个内置 fixture 是实际使用中最多的,用来获取命令行参数,尤其是一些必须由外部传递给 pytest 的一些自定义参数,下面是项目中的实例,目的是将设备信息传递给 pytest:
# conftest.py
import pytest
# 注册自定义参数 cmdopt 到配置对象
def pytest_addoption(parser):
parser.addoption("--cmdopt", action="store",
default="None",
help="将自定义命令行参数 ’--cmdopt' 添加到 pytest 配置中")
# 从配置对象获取 cmdopt 的值
@pytest.fixture(scope='session')
def cmdopt(pytestconfig):
return pytestconfig.getoption('--cmdopt')
# 然后任何 fixture 或测试用例都可以调用 cmdopt 来获得设备信息
# main.py
device_info = {'id': 'xxx', 'name': '华为', 'version': '10'}
pytest.main(['-m all',
f'--cmdopt={device_info}']) # 使用自定义参数传参
使用 pytestconfig 获取 pytest.ini 配置文件中参数的值:
# pytest.ini
[pytest]
markers =
demo : marks tests as demo
smoke: marks tests as smoke
test : marks tests as test
log_cli = 1
# conftest.py
@pytest.fixture(autouse=True)
def fuc_fix(pytestconfig):
print()
print(pytestconfig.getini('markers'))
print(pytestconfig.getini('log_cli'))
# 控制台输出结果:
============================= test session starts =============================
test_Z.py::TestDemoA::test_A_001
['demo : marks tests as demo', 'smoke: marks tests as smoke', 'test : marks tests as test']
True
PASSED
============================== 1 passed in 0.02s ==============================
注意:部分参数中的值会被转换为布尔值!