fixture(固件)能够直接定义在各测试脚本中,就像上面的例子 更多时候,咱们但愿一个固件能够在更大的程度上复用,这就须要对固件进行集中管理.Pytest使用文件
conftest.py
集中管理固件.在复杂的项目中,能够在不一样的目录层级定义conftest.py,其做用域为其所在的目录和子目录
注意: 不要显示的调用conftest.py,pytest会自动调用,能够把conftest当作插件来理解.html
setup和teardown能够实如今测试用例以前或以后加入一些操做,但这种是整个脚本全局生效的,若是我想实现如下场景: 用例1须要先登陆,用例2不须要登陆,用例3须要先登陆。很显然这就没法用setup和teardown来实现了python
firture相对于setup和teardown来讲应该有如下几点优点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")
运行结果:code
╰ 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 ==========================