Search code examples
pythonpython-3.xpython-importimporterrorpytest

Importing modules from a sibling directory for use with py.test


I am having problems importing anything into my testing files that I intend to run with py.test.

I have a project structure as follows:

/ProjectName
|
|-- /Title
|    |-- file1.py
|    |-- file2.py
|    |-- file3.py
|    |-- __init__.py
|
|-- /test
|    |-- test_file1.py

I have not been able to get any import statements working with pytest inside the test_file1.py file, and so am currently just attempting to use a variable declared in file_1.py and print it out when test_file1.py is run.

file1.py contains:

file1_variable = "Hello"

test_file1.py contains:

import sys
import os
sys.path.append(os.path.abspath('../Title'))
import file1

def test_something():
    assert file1.file1_variable == "Hello"

print(file1.file1_variable)

The import statement from my testing file is taken from https://stackoverflow.com/a/10272919/5477580 which works by editing the PYTHONPATH variable. This allows me to run the test_file1.py script and successfully execute the print statement.

However, attempting to run py.test from the /ProjectName directory gives me an error saying ImportError: No module named 'file1'

Is there some way in which I can structure things better so that pytest will be possible? Do I need to add something to my __init__.py file?


Solution

  • No, you don't need to add anything to __init__.py. This file tells Python to treat the parent directory as a module that can be imported as described here. Just add it to your Title directory and import it like

    from ..Title.file import file1_variable
    

    here we are moving 1 hierarchy above in the directory just like cd ..

    Note .. is for reaching the Title package from test directory. If you need to run your file from ProjectName directory, you will have to do

    from Title.file import file1_variable