Pytest: Create reusable code in conftest.py

Viewed 503

Due to the way pytest works, it is not possible (or recommended) to import other modules in a pytest module. Instead, one should properly edit it's conftest.py file.

Several times, I am put in a situation where I need to share constants/functions to several tests modules. And fixture fails to be as practical as functions. Even if they can be indirectly parametrized with the indirect parameter, they are still situations where it's not possible, or simple, to use this approach.

For constants, I am in the following situation, here is an extract of my conftest.py:

TARGET_NAME_1 = 'MY_OP4510'
TARGET_NAME_2 = 'MY_ML605'
TARGET_NAME_3 = 'TARGET_WITH_CHILD'
CONFIG_FILE_NAME = 'config.ini'

@pytest.fixture()
def target_name_1():
    """This fixture returns a target name"""

    return TARGET_NAME_1


@pytest.fixture()
def target_name_2():
    """This fixture returns a target name"""

    return TARGET_NAME_2

@pytest.fixture()
def target_name_3():
    """This fixture returns a target name"""

    return TARGET_NAME_3

@pytest.fixture()
def target_config_path():
    """This fixture returns the config path"""

    return CONFIG_FILE_NAME

Every time I have to add a constant, I have to add a fixture. Also, this increase the number of parameters the tests functions will receive (if in this case, I could use the autouse parameter, for some other fixtures that actually execute code, I do not necessary want to auto-use them as they could prevent other test cases from working).

I am looking for a way to simplify this code, would you have a good pattern/implementation to suggest ?

0 Answers
Related