Question
How can I import helper functions in test files without creating packages in the test
directory?
Context
I'd like to create a test helper function that I can import in several tests. Say, something like this:
# In common_file.py
def assert_a_general_property_between(x, y):
# test a specific relationship between x and y
assert ...
# In test/my_test.py
def test_something_with(x):
some_value = some_function_of_(x)
assert_a_general_property_between(x, some_value)
Using Python 3.5, with py.test 2.8.2
Current "solution"
I'm currently doing this via importing a module inside my project's test
directory (which is now a package), but I'd like to do it with some other mechanism if possible (so that my test
directory doesn't have packages but just tests, and the tests can be run on an installed version of the package, as is recommended here in the py.test documentation on good practices).
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).
Then in your tests, you can use the fixture:
my option is to create an extra dir in
tests
dir and add it to pythonpath in the conftest so.in the
conftest.py
in
setup.cfg
this module will be available with
import utils
, only be careful to name clashing.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
:And then, within a test case function body just use it like
Its pretty simple and the documentation pretty small. Take a look and tell me if it addresses your problem too.
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:
test_file.py:
As another option, this directory structure worked for me:
And then in
my_test.py
import the utilities using:from test_helpers import utils
Create a helpers package in tests folder:
in setup.cfg:
the helpers will be available with
import helpers
.