Pytest: Are there hooks for module setup/teardown?

Created on 10 Jul 2018  路  5Comments  路  Source: pytest-dev/pytest

There are many hooks around setting up/tearing down functions and there are hooks for session start/finish, but are there any for modules?

question

Most helpful comment

This might be helpful:

import pytest

@pytest.fixture(autouse=True, scope='module')
def module_setup_teardown():
    print("MODULE SETUP!!!")
    yield
    print("MODULE TEARDOWN!!!")


def test1():
    print("TEST1!!!")


def test2():
    print("TEST2!!!")
$ pytest -s test.py
============================== test session starts ===============================
platform darwin -- Python 3.7.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: /private/tmp/t, inifile:
collected 2 items                                                                

test.py MODULE SETUP!!!
TEST1!!!
.TEST2!!!
.MODULE TEARDOWN!!!


============================ 2 passed in 0.01 seconds ============================

All 5 comments

GitMate.io thinks possibly related issues are https://github.com/pytest-dev/pytest/issues/265 (teardown method called even for skipped tests (and setup isn't)), https://github.com/pytest-dev/pytest/issues/2205 (optimize io capture setup/teardown), https://github.com/pytest-dev/pytest/issues/91 (Package-level setup and teardown), https://github.com/pytest-dev/pytest/issues/2718 (Please consider adding context manager versions of setup/teardown), and https://github.com/pytest-dev/pytest/issues/377 (nose's .setUp() and .tearDown() are not supported).

Hi @yoyoyopcp,

The short answer is no, the closest I can think of are the pytest_fixture_setup and pytest_fixture_post_finalizer hooks when they are used for module-scoped fixtures.

This might be helpful:

import pytest

@pytest.fixture(autouse=True, scope='module')
def module_setup_teardown():
    print("MODULE SETUP!!!")
    yield
    print("MODULE TEARDOWN!!!")


def test1():
    print("TEST1!!!")


def test2():
    print("TEST2!!!")
$ pytest -s test.py
============================== test session starts ===============================
platform darwin -- Python 3.7.0, pytest-3.6.3, py-1.5.4, pluggy-0.6.0
rootdir: /private/tmp/t, inifile:
collected 2 items                                                                

test.py MODULE SETUP!!!
TEST1!!!
.TEST2!!!
.MODULE TEARDOWN!!!


============================ 2 passed in 0.01 seconds ============================

oh but for plugin hooks, 馃

Plugins can just make a internal fixtures

Was this page helpful?
0 / 5 - 0 ratings