Question
How can I import helper functions in test files without creating packages in the test
directory?
Contex
You could define a helper class in conftest.py, then create a fixture that returns that class (or an instance of it, depending on what you need).
import pytest
class Helpers:
@staticmethod
def help_me():
return "no"
@pytest.fixture
def helpers():
return Helpers
Then in your tests, you can use the fixture:
def test_with_help(helpers):
helpers.help_me()
To access a method from different modules without creating packages, and have that function operate as a helper function I found the following helpful:
conftest.py:
@pytest.fixture
def compare_test_vs_actual():
def a_function(test, actual):
print(test, actual)
return a_function
test_file.py:
def test_service_command_add(compare_test_vs_actual):
compare_test_vs_actual("hello", "world")
As another option, this directory structure worked for me:
mypkg/
...
test_helpers/
__init__.py
utils.py
...
tests/
my_test.py
...
And then in my_test.py
import the utilities using:
from test_helpers import utils
It is possible that some of you will be completely uphold by my suggestion. However, very simple way of using common function or value from other modules is to inject it directly into a common workspace. Example:
conftest.py:
import sys
def my_function():
return 'my_function() called'
sys.modules['pytest'].common_funct = my_function
test_me.py
import pytest
def test_A():
print(pytest.common_funct())
Create a helpers package in tests folder:
tests/
helpers/
__init__.py
utils.py
...
# make sure no __init__.py in here!
setup.cfg
in setup.cfg:
[pytest]
norecursedirs=tests/helpers
the helpers will be available with import helpers
.
my option is to create an extra dir in tests
dir and add it to pythonpath in the conftest so.
tests/
helpers/
utils.py
...
conftest.py
setup.cfg
in the conftest.py
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'helpers'))
in setup.cfg
[pytest]
norecursedirs=tests/helpers
this module will be available with import utils
, only be careful to name clashing.