1.前言
- conftest.py 测试用例的一些fixture配置
- pytest.ini 它是pytest的主配置文件,可以改变pytest的默认行为
2.conftest.py
对于某些用例都需要执行的功能,比如登陆、切换环境、登陆后进入大模块等。像这样的前置功能或者后置功能写到一个用例里面,其他用例就不能使用了。所以需要配置文件,管理通用的前置操作,类似于通用关键字。pytest中可以使用conftest.py实现。
- conftest.py名称固定,pytest默认读取
- conftest.py 和运行的用例要再一个package下,用例可以放进最顶级的package下的子package下面。保证conftest.py文件在最外层的package下就可以了。
- pytest可以自动找到该文件,读取里面的函数。
目录结构如下:
project
|
└───folder
| | __init__.py
│ │ conftest.py
│ │ test_one.py
│ └───subfolder
| | __init__.py
│ │ test_two.py
│ │
│ │ ...
运行test_two.py文件,可以读取到folder文件夹下conftest.py定义好的前置、后置方法。
运行test_one.py文件,可以读取到folder文件夹下conftest.py定义好的前置、后置方法。
3.pytest.ini
每次执行不同package下的module文件,都会生成一个pytest-cache文件,我是看着不习惯。统一自定义到外层package下。
在pytest.ini 中添加如下配置:可以把pytest-cache文件生成在和pytest.ini同一目录下。
[pytest]
cache_dir = .pytest-cache
如下,每次执行时候等价于 pytest -q *.py
[pytest]
addopts = -q
cache_dir = .pytest-cache
[pytest]
addopts = -q
cache_dir = .pytest-cache
markers =
webtest: mark a test as a webtest
hello: this is a hello tag
-
- 打标记实例
@pytest.mark.hello
def test_one():
x = "this"
assert "" in x
@pytest.mark.webtest
class TestMyClass:
def test_one(self):
x = "this"
assert "" in x
def test_two(self):
x = "hello"
assert x in 'hello'
-
- 通过标记执行用例
cd 进入pytest.ini文件存在目录下
# 终端或者控制台输入
pytest --markers #可以查看到刚刚定义的标记
pytest -m hello #可以运行test_one用例
pytest -m "not hello" #运行不包含hello标记的用例
pytest -m webtest # 可运行TestMyClass 类下的全部用例