pytestフィクスチャの自動使用

これまでのところ、すべてのファームウェアの使用は、パラメーターとして手動で指定されるか、使用されusefixturesます。

ファームウェアを自動的に実行する場合は、を定義するときにautouseパラメーターを指定できます

以下は、2つの自動タイミングファームウェアです。1つは各機能の実行時間をカウントするためのもの(機能スコープ)、もう1つは合計テスト時間を計算するためのもの(セッションスコープ)です。

# 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))

次の2つのテスト関数は、ファームウェアを明示的に使用しないことに注意してください。

def test_1():
    time.sleep(1)


def test_2():
    time.sleep(2)

テストを実行すると、ファームウェアが自動的に実行され、タイミングタスクが完了することがわかります。

$ 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 ===========================

参照

《学習-pytest》

おすすめ

転載: blog.csdn.net/qq_42648305/article/details/112992362