除了使用pytest.fixture.userfixtures和传参两种显式的调用fixture之外.也可以自动的执行fixture,在定义fixture的时候设置autouser=True即可
from datetime import datetime
from time import sleep
import pytest
@pytest.fixture(autouse=True)
def timer_session_scope():
start = datetime.now()
print(f"\nstart:{start}")
yield
end = datetime.now()
print(f"total time cost:{end - start}")
def test_timer():
sleep(1.3)
assert 2 == 2
运行结果:
╰ 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 1 item
test_data.py::test_timer
start:2019-09-27 11:12:13.526151
PASSEDtotal time cost:0:00:01.305416
===================================================== 1 passed in 1.33 seconds =====================================================