fixture(固件)可以直接定义在各测试脚本中,就像上面的例子 更多时候,我们希望一个固件可以在更大的程度上复用,这就需要对固件进行集中管理.Pytest使用文件
conftest.py
集中管理固件.在复杂的项目中,可以在不同的目录层级定义conftest.py,其作用域为其所在的目录和子目录
注意: 不要显示的调用conftest.py,pytest会自动调用,可以把conftest当做插件来理解.
例:
setup和teardown可以实现在测试用例之前或之后加入一些操作,但这种是整个脚本全局生效的,如果我想实现以下场景: 用例1需要先登录,用例2不需要登录,用例3需要先登录。很显然这就无法用setup和teardown来实现了
fixture优势
firture相对于setup和teardown来说应该有以下几点优势
- 命名方式灵活,不局限于setup和teardown这几个命名
- conftest.py 配置里可以实现数据共享,不需要import就能自动找到一些配置
- scope="module" 可以实现多个.py跨文件共享前置, 每一个.py文件调用一次
- scope="session" 以实现多个.py跨文件使用一个session来完成多个用例
etc
├── __pycache__
├── conftest.py
├── test_data.py
conftest.py
import pytest
@pytest.fixture()
def login():
print("输入账号,密码先登录")
@pytest.fixture()
def write_data():
print("写入数据..")
test_data
def test_s1(login, write_data):
print("用例1:登录之后其它动作111")
def test_s2(): # 不传login
print("用例2:不需要登录,操作222")
def test_s3(login, write_data):
print("用例3:登录之后其它动作333")
运行结果:
╰ pytest -v -s test_data.py
========================== test session starts ==========================
platform darwin -- Python 3.7.4, pytest-4.4.0, py-1.8.0, pluggy-0.13.0 -- /Users/zhouwanghua/Code/Leyan/python/robocop/bin/python
cachedir: .pytest_cache
metadata: {'Python': '3.7.4', 'Platform': 'Darwin-18.6.0-x86_64-i386-64bit', 'Packages': {'pytest': '4.4.0', 'py': '1.8.0', 'pluggy': '0.13.0'}, 'Plugins': {'bdd': '3.1.0', 'html': '1.20.0', 'metadata': '1.8.0'}}
rootdir: /Users/zhouwanghua/Code/Leyan/robocop, inifile: pytest.ini
plugins: bdd-3.1.0, html-1.20.0, metadata-1.8.0
collected 3 items
test_data.py::test_s1 输入账号,密码先登录
写入数据..
用例1:登录之后其它动作111
PASSED
test_data.py::test_s2 用例2:不需要登录,操作222
PASSED
test_data.py::test_s3 输入账号,密码先登录
写入数据..
用例3:登录之后其它动作333
PASSED
========================== 3 passed in 0.03 seconds ==========================