我經歷了無數的答案,也嘗試了其中的大部分,但仍然面臨同樣的問題我的結構 -- backend -- app -- __init__.py -- utils.py -- models.py -- pytest -- test_utils.py`現在我想將 utils 導入 test_utils 以便能夠調用該函數并對其進行測試。我的init .py 不為空,我的 test_utils.py 看起來像這樣import sys, os.pathsys.path.insert(0 ,(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/'))from utils import test_functiondef test_test_function(): a = test_function(5) assert a == 5我檢查了我的 sys 路徑也指向正確的目錄,但不斷收到此錯誤,我在 Linux 中使用 Python 2.7ImportError 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 dbE ImportError: No module named app
2 回答

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
解決方案是在 pytest/ 文件夾中創(chuàng)建一個 pytest.ini 文件。pytest.ini 的內容將是:--
[測試]
python_paths = . ../應用程序

繁星淼淼
TA貢獻1775條經驗 獲得超11個贊
事實證明,必須為 app 和 utils 添加路徑,然后它才能工作
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append((os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) + '/app/'))
添加回答
舉報
0/150
提交
取消