【发布时间】:2019-12-16 21:25:47
【问题描述】:
我有一个类似的项目
.
|-application
|---foo.py
|---bar.py
|-tests
|---test_foo.py
内容是:
bar.py
def myfunc():
return "hello from bar"
foo.py
from bar import myfunc
def do_work():
return myfunc()
if __name__ == "__main__":
print(do_work())
test_bar.py
from application import foo
class TestFoo:
def test_foo_do_work(self):
assert foo.do_work() == "hello from bar"
运行python application/foo.py 效果很好,但运行python -m pytest tests/ 返回错误ModuleNotFoundError: No module named 'bar'
在foo.py 中解决此问题的一种方法是将导入行从from bar import myfunc 更改为from application.bar import myfunc。这会导致 pytest 通过,但运行 python application/foo.py 会出现错误 ModuleNotFoundError: No module named 'application'
我不知道我做错了什么。我使用的是 python 3.7,所以我听说 __init__.py 是不必要的。
【问题讨论】:
标签: python-3.x pytest python-import