pytest的配置文件

pytest有哪些非测试文件:

pytest.ini:pytest的配置文件,可以改变pytest的默认行为,有很多的可配置的选项。需要注意的是:此配置文件不能有:中文字符串:(中文、空格、引号、冒号)---针对的是windows,mac/linux是可以用中文字符的

conftest.py:是本地的插件库,其中的hook函数和fixture将作用于该文件所在的目录以及所在的子目录。

__init__.py:每一个测试子目录都包含改文件。

tox.ini:与pytest.ini类似,只不过是tox的配置文件,可以把pytest的配置都写进tox.ini中,这样就不用同时使用tox.ini和pytest.ini两个文件了。

setup.cfg:也是采用ini的文件格式。而且可以影响setup.py的行为。可以在setup.py里添加几行代码。使用python setup.py test运行所有的pytest测试用例。

ps:不管使用哪种配置文件格式几乎都是一样的。(经常用的就是pytest.ini文件)

pycharm unittest 配置 pytest配置文件_pycharm unittest 配置

 

 

ini文件的配置选项:用pytest --help可以进行查看可用的配置文件参数选项

更改默认命令行选项:

[pytest]
addopts=命令行参数
# 在配置文件中定义了命令行参数之后在实际运行的时候只需要输入pytest的命令就可以,参数会默认读取配置文件中的参数。
-p no:warnings  不显示警告信息

 注册标记:

[pytest]
markers = 
    smoke:Run the smoke test functions for tasks project 
    get:Run test functions that test tasks.get()
    
# 注册好标记之后可以通过pytest  --markers来查看。注册的时候标记名不能写在一行,每写一个需要换行,并且不能顶行头写

指定pytest的最低版本号:minversion参数

[pytest]
minversion=3.0

指定pytest忽略某些目录:

pytest在执行测试搜索时,会遍历所有的子目录,包括某些你明知道没必要遍历的目录,norecurse配置参数可以简化pytest的搜索工作

[pytest]
norecursedirs=.* venv src *.egg dist build

# 被写入的文件夹就不会在遍历了

指定测试目录:

testpaths参数可以指定pytest去哪里访问。testpaths是一系列相对于根目录的路径,用于限定测试用例的搜索范围。只有pytest未指定文件目录参数或测试用例标识符,该选项才会启用。

[pytest]
testpaths=文件夹

更改测试搜索的规则:

[pytest]
python_class=*Test Test* *Suite
python_files=test_* *_test check_*
python_functions=test_* check_*

#  pytest的命名规则不是强制性的,如果不喜欢默认的命令规则,完全可以在配置文件中去修改他们

禁用XPASS状态:

[pytest]
xfail_strict=true
# 这个参数的设置的意义是:被@pytest.mark.xfail标记的用例运行之后如果通过了,会强制的再把这个用例置为失败。

避免文件冲突:不同的文件夹里面都添加__init__.py文件

pytest.ini文件配置日志:

# 如果用ini文件配置日志的配置的话,连loggin日志模块都不用封装,当用这种日志方式的时候,也可以修改日志的输出路径与日志文件对的名称。(前提需要在ini文件中把日志的file输出的配置给去掉,之后再在conftest里面修改)
[pytest]
log_cli = true
log_cli_level = info
log_cli_format = [%(asctime)s][%(filename)s %(lineno)d][%(levelname)s]: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p'
log_cli_date_format = %Y-%m-%d %H:%M:%S
log_file = ./Out/log/test.log
log_file_level = info
log_file_format = %(asctime)s [%(levelname)s] %(message)s (%(filename)s:%(lineno)s)
log_file_date_format = %Y-%m-%d %H:%M:%S
# 在conftest.py里面修改日志文件输出路径
@pytest.fixture(scope="session", autouse=True)
def manage_logs(request):
    """Set log file name same as test name"""
    now = time.strftime("%Y-%m-%d %H-%M-%S")
    log_name = 'output/log/' + now + '.logs'

    request.config.pluginmanager.get_plugin("logging-plugin") \
        .set_log_path(return_path(log_name))