09、自动执行

大兔子大兔子 提交于 2019-11-30 14:26:53

除了使用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 =====================================================
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!