【发布时间】:2026-01-30 04:45:01
【问题描述】:
我已经看了很多答案,也尝试了其中的大部分,但仍然面临同样的问题
我的结构
-- backend
-- app
-- __init__.py
-- utils.py
-- models.py
-- pytest
-- test_utils.py`
现在我想将 utils 导入 test_utils 以便能够调用该函数并对其进行测试。我的 init.py 不是空的,我的 test_utils.py 看起来像这样
import sys, os.path
sys.path.insert(0 ,(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/'))
from utils import test_function
def test_test_function():
a = test_function(5)
assert a == 5
我检查了我的 sys 路径也指向正确的目录,但不断收到此错误,我在 Linux 中使用 Python 2.7
ImportError while importing test module '/home/richie/Documents/Project/backend/pytest/test_utils.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../virenv/local/lib/python2.7/site-packages/six.py:709: in exec_
exec("""exec _code_ in _globs_, _locs_""")
test_utils.py:3: in <module>
from utils import test_function
../app/utils.py:15: in <module>
from models import Users, Accounts
../app/models.py:2: in <module>
from app import db
E ImportError: No module named app
【问题讨论】:
-
您的代码显示
from utils import test_function,但错误提示您导入了app。这不是产生该错误的代码。 -
@zvone 我已经添加了完整的错误报告,希望这会有所帮助,但请放心,这是运行的代码,因为我只有 1 个测试文件和 1 个测试用例
-
尝试将您的
pytest文件夹重命名为另一个名称?它可能与实际的 pytest 模块冲突。 -
你的 PYTHONPATH 上有后端吗?
-
这不对。必须列出实际的后端文件夹,才能将子文件夹作为模块拾取。
标签: python python-2.7 python-import pytest importerror