Create and import helper functions in tests without creating packages in test directory using py.test
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).
Solution 1:
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()
Solution 2:
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.