pytest笔记(四)pytest.ini的使用

pytest.ini 可以修改 pytest 的默认行为

注意: pytest.ini 不能使用任何中文符号,包括汉字、空格、引号、冒号等等;

更改默认命令行参数:

将常用的命令行参数设置为默认,省去重复输入的工作;

# pytest.ini

[pytest]

addopts = -rsxX -l -strict --tb=short

注册 mark 标记:

# pytest.ini

[pytest]

markers =

    demo : marks tests as demo

    smoke: marks tests as smoke

    test : marks tests as test

控制台实时输出日志:

# pytest.ini

[pytest]

log_cli = 1

指定 pytest 最低版本号:

# pytest.ini

[pytest]

minversion = 3.0

指定 pytest 忽略某些目录:

pytest 收集测试用例时,会递归遍历所有子目录,包括某些你明知道没必要遍历的目录,遇到这种情况,可以使用 norecursedirs 参数简化 pytest 的搜索工作;norecursedirs 默认的设置是:.* build dist CVS _darcs {arch} *.egg ,多个路径用空格隔开。

# pytest.ini

[pytest]

norecursedirs = .* build dist CVS _darcs {arch} *.egg venv src

指定测试目录:

testpaths 限定测试用例的搜索范围,只有在 pytest 范围指定文件目录参数或测试用例标识符时,该选项才会启用;

testpaths 指定的路径是以 testpaths 所在的目录为基准的相对路径;

# pytest.ini

[pytest]

testpaths = test_path

更改测试用例收集规则:

pytest 默认的用例收集规则:

测试模块必须以 test_ 开头或以 _test 结尾;

测试类必须以 Test 开头,且不能有 __init__() ;

测试方法必须以 test_ 开头;

下面我们来添加自己的收集规则:

添加 check_ 开头的测试模块;

添加 Check 开头的测试类;

添加 check_ 开头的测试方法;

# pytest.ini

[pytest]

python_files =    test_*  *_test  check_*

python_classes =  Test*  Check*

python_functions = test_*  check_*

禁用 XPASS:

将标记为 @pytest.mark.xfail 但实际通过的测试用例报告为失败;

# pytest.ini

[pytest]

xfail_strict = true

避免文件名冲突:

为所有的测试目录添加 __init__.py,当多个测试目录拥有重名文件时,__init__.py 可以避免文件名冲突;

动态添加及获取 ini 配置参数:

# conftest.py

import pytest

def pytest_addoption(parser):

    parser.addini('nice', type='bool', default=True, help='添加 ini 参数')

@pytest.fixture(autouse=True)

def get_ini(pytestconfig):

    """获取 ini 参数"""

    nice = pytestconfig.getini('nice')

    print(nice)

你可能感兴趣的:(pytest笔记(四)pytest.ini的使用)