pytest fixture autouse

So far, all firmware uses are manually specified, either as parameters, or used usefixtures.

If we want the firmware to execute automatically, we can specify the autouseparameters when defining .

The following are two automatic timing firmwares, one for counting the running time of each function (function scope), and the other for calculating the total test time (session scope):

# test_autouse.py

DATE_FORMAT = '%Y-%m-%d %H:%M:%S'


@pytest.fixture(scope='session', autouse=True)
def timer_session_scope():
    start = time.time()
    print('\nstart: {}'.format(time.strftime(DATE_FORMAT, time.localtime(start))))

    yield

    finished = time.time()
    print('finished: {}'.format(time.strftime(DATE_FORMAT, time.localtime(finished))))
    print('Total time cost: {:.3f}s'.format(finished - start))


@pytest.fixture(autouse=True)
def timer_function_scope():
    start = time.time()
    yield
    print(' Time cost: {:.3f}s'.format(time.time() - start))

Note that the following two test functions do not explicitly use firmware:

def test_1():
    time.sleep(1)


def test_2():
    time.sleep(2)

Performing the test can see that the firmware automatically executes and completes the timing task:

$ pytest -s tests/fixture/test_autouse.py
============================= test session starts =============================
platform win32 -- Python 3.6.4, pytest-3.6.1, py-1.5.2, pluggy-0.6.0
rootdir: F:\self-repo\learning-pytest, inifile:
collected 2 items

tests\fixture\test_autouse.py
start: 2018-06-12 10:16:27
. Time cost: 1.003s.
. Time cost: 2.003s.
finished: 2018-06-12 10:16:30
Total time cost: 3.016s.


========================== 2 passed in 3.11 seconds ===========================

reference

《learning-pytest》

Guess you like

Origin blog.csdn.net/qq_42648305/article/details/112992362