Question
How can I import helper functions in test files without creating packages in the test
directory?
Contex
While searching for a solution for this problem I came across this SO question and ended up adopting the same approach. Creating a helpers package, munging sys.path
to make it importable and then just importing it...
This did not seem the best approach, so, I created pytest-helpers-namespace. This plugin allows you to register helper functions on your conftest.py
:
import pytest
pytest_plugins = ['helpers_namespace']
@pytest.helpers.register
def my_custom_assert_helper(blah):
assert blah
# One can even specify a custom name for the helper
@pytest.helpers.register(name='assertme')
def my_custom_assert_helper_2(blah):
assert blah
# And even namespace helpers
@pytest.helpers.asserts.register(name='me')
def my_custom_assert_helper_3(blah):
assert blah
And then, within a test case function body just use it like
def test_this():
assert pytest.helpers.my_custom_assert_helper(blah)
def test_this_2():
assert pytest.helpers.assertme(blah)
def test_this_3():
assert pytest.helpers.asserts.me(blah)
Its pretty simple and the documentation pretty small. Take a look and tell me if it addresses your problem too.