fixture的autouse

autouse=True,可以使作用域内的测试方法都运行该fixture,而无需手动添加fixture的方法名或者使用pytest.mark.usefixtures。《pytest测试实战》中有个很好的例子:

#test_autouse.py
import pytest
import time


#在每个session结束的时候打印时间
@pytest.fixture(scope="session", autouse=True)
def footer_session_scope():
    yield
    now = time.time()
    print("--")
    print(f"finished: {time.strftime('%d %b %X', time.localtime(now))}")
    print("----------------------------------")



#在每个function结束的时候打印测试时间
@pytest.fixture(autouse=True)
def footer_function_scope():
    start = time.time()
    yield
    stop = time.time()
    delta = stop - start
    print("\ntest duration:{:0.3} seconds".format(delta))     #{:0.3}或者{:.3}表示截取小数点后三位
  


def test_1():
    time.sleep(1)


def test_2():
    time.sleep(1.23)



#运行结果
============================= test session starts =============================
platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 -- D:\program\Python37\python.exe
cachedir: .pytest_cache
metadata: {'Python': '3.7.3', 'Platform': 'Windows-7-6.1.7601-SP1', 'Packages': {'pytest': '5.1.2', 'py': '1.8.0', 'pluggy': '0.12.0'}, 'Plugins': {'html': '2.1.1', 'metadata': '1.8.0', 'rerunfailures': '9.0'}, 'JAVA_HOME': 'D:\\program\\Java\\jdk1.8.0_171'}
rootdir: E:\virtual_workshop\pytest-demo\test_demo5
plugins: html-2.1.1, metadata-1.8.0, rerunfailures-9.0
collecting ... collected 2 items

test_autouse.py::test_1 PASSED                                           [ 50%]
test duration:1.01 seconds

test_autouse.py::test_2 PASSED                                           [100%]
test duration:1.23 seconds
--
finished: 18 Apr 14:00:13
----------------------------------


============================== 2 passed in 2.27s ==============================

 

posted @ 2020-04-18 14:04  cnhkzyy  阅读(180)  评论(0编辑  收藏  举报