Pytest相关组件pytest.ini和conftest.py介绍(二)
pytest.ini配置文件(作用:用来修改配置pytest默认的运行规则)
- pytest.ini放在项目根目录,文件名字固定
- 常用配置介绍(⚠️不能出现中文注释)
#coding=utf-8
[pytest]
filterwarnings =
error
ignore::UserWarning
ignore:function ham\(\) is deprecated:DeprecationWarning
addopts = -v -s
--strict
-m "level0 or level1"
--cache-clear
norecursedird = .svn -build tmp* .git .idea .pytest_cache
python_files = test_*.py
python_functions = test_run
markers =
level0 : smoketest
level1 : systemtest
- 配置参数含义
- filterwarnings:消除pytest执行警告(从版本开始3.1,pytest现在会在测试执行期间自动捕获警告并在会话结束时显示它们)
- addopts: 更改默认命令行选项,当我们用命令行运行时,需要输入多个参数,可在这里配置(比如:pytest -s test_001.py 配置后只需要 pytest test_001.py)
- norecursedird: pytest收集用例排除的文件
- python_files: 用例收集规则
- python_classes/python_functions: 类/函数收集规则
- markers: 指定mark标签
Demo(采用上面ini文件)
import pytest
class TestCase001:
def sum(self, x):
return x + 3
def test_001(self):
assert self.sum(1) == 3
def test_002(self):
assert self.sum(2) == 5
@pytest.mark.level0
def test_run(self):
assert sum(5) == 7
=================================== FAILURES ===================================
_____________________________ TestCase001.test_run _____________________________
self = <TestCase.Demo.test_demo_001.TestCase001 object at 0x13be5a3c8>
@pytest.mark.level0
def test_run(self):
> assert sum(5) == 7
E TypeError: 'int' object is not iterable
test_demo_001.py:16: TypeError
=========================== short test summary info ============================
FAILED test_demo_001.py::TestCase001::test_run - TypeError: 'int' object is n...
============================== 1 failed in 0.09s ===============================
Process finished with exit code 0
这里只运行了test_run(在ini中我们指定了python_functions和运行的mark)
conftest.py详解
- 介绍:
- conftest.py文件名固定,不能被其它文件导入,无需import导入pytest会自动识别
- 可以有多个conftest.py,放在项目根目录就可以全局调用,放在某个package下就只对当前peckage有效(package下要有__init__.py)
- 所有同级别目录下的测试文件运行前都会执行conftest.py
- 用法:
结合fixture使用
conftest.py
@pytest.fixture(scope='session', autouse=True)
#scope: function 每一个函数或方法都会调用;
#class 每一个类调用一次,一个类可以有多个方法;
#module,每一个.py文件调用一次,该文件内又有多个function和class;
#session 是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
def set_up():
print('开启服务')
#case.py
def test_run():
print('开始执行用例')
#autouse=False用法
def test_run(self,set_up):
print('开始执行用例')
#结果
test_001_case.py::TestCase001::test_run 开启服务
PASSED [100%]开始执行用例

浙公网安备 33010602011771号