6

I am creating an object within conftest.py and use it in some fixtures. I also need to use this object within my test-modules. Currently I am importing conftest.py inside my test-modules and make use of that 'helper' object. I am pretty sure that this is not the recommended way. I am looking forward to your suggestions.

Thank you :)

Following is the dummy-coded version of my question:

conftest.py

import pytest

class Helper():

    def __init__(self, img_path:str):
        self.img_path = img_path

    def grayscale(self):
        pass

    def foo(self):
        pass

helper = Helper("sample.png")

@pytest.fixture()
def sample():
    return helper.grayscale()

test_module.py

import conftest

helper = conftest.helper

def test_method1(sample):
    helper.foo()
    ...
  • 3
    I would recommend moving your helpers to a helpers module or to fixtures -- conftest isn't really meant to be imported – anthony sottile Aug 11 '21 at 13:08
  • 2
    You could also think about making `helper` a session-scoped fixture. – MrBean Bremen Aug 11 '21 at 18:01
  • Thank you for your comments :) I applied your recommendation. – PedarePessareShoja Aug 30 '21 at 11:27
  • 1
    @anthonysottile I'm coming in a couple of years late... but can you expand a bit on your answer? From the preferred answer here https://stackoverflow.com/questions/34466027/in-pytest-what-is-the-use-of-conftest-py-files I understood that conftest is the correct place for defining shared fixtures. But if you want to have type annotated test functions then you need to import the types from somewhere. So would the best practice be to create a helper module purely to define these types? – daveraja May 16 '23 at 00:40
  • ime typing tests (beyond check-untyped-defs) is a waste of time -- they're already going to fail during test execution so you're not really helping yourself. that said yes if you need to return complex enough types then define them outside of conftest – anthony sottile May 16 '23 at 02:28

1 Answers1

1

As already commented, I also handled such scenarios by fixtures before if I have a helper class in tests.

conftest.py

import pytest


class Helper():
    def __init__(self, img_path: str):
        self.img_path = img_path

    def grayscale(self):
        pass

    def foo(self):
        pass


@pytest.fixture(scope="session")
def helper():
    return Helper("sample.png")


@pytest.fixture()
def sample(helper):
    return helper.grayscale()

test_module.py

def test_method1(helper, sample):
    helper.foo()