问题
I'm working on a project and would like to write some unit tests for my code. Here is a minimal example of my project structure
myproject
└── scripts
├── tests
│ └── test_func.py
└── tools
├── __init__.py
└── func.py
func.py
contains
def f(x):
return 0
and test_func.py
contains
import pytest
from ..tools import f
def test_f():
assert f(1)==0
When I try to run my tests with pytest pytest scripts/tests/test_func.py
, I get the following error ImportError: attempted relative import with no known parent package
.
Clearly, there is a problem with the structure of my project. There is a solution here which involves adding something to my path but I'd rather not do that if there is a way I can just structure my project to avoid this instead.
回答1:
You need to add (empty) __init__.py
files to the directories scripts/
and scripts/tests/
. These files provide the scaffolding that lets import
find modules, especially when using relative imports.
The
__init__.py
files are required to make Python treat directories containing the file as packages.
From https://docs.python.org/3/tutorial/modules.html
来源:https://stackoverflow.com/questions/64623668/how-can-i-structure-my-folders-to-test-my-code