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

只愿长相守 提交于 2019-12-10 09:23:11

问题


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?


回答1:


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

from ..Tiltle.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 Tiltle.file import file1_variable


来源:https://stackoverflow.com/questions/37469473/importing-modules-from-a-sibling-directory-for-use-with-py-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!