我正在按照本教程学习Flask https://flask.palletsprojects.com/en/1.1.x/#user-s-guide但是,当我尝试运行 pytest
时,我收到此错误:
(FlaskVenv) MacBook-Pro-de-Hugo:FlaskProject hugovillalobos$ pytest
ImportError while loading conftest '/Users/hugovillalobos/Documents/Code/FlaskProject/tests/conftest.py'.
tests/conftest.py:4: in <module>
from Flaskr import create_app
E ModuleNotFoundError: No module named 'Flaskr'
这是引发错误的模块 ( conftest.py
):
import os
import tempfile
import pytest
from Flaskr import create_app
from Flaskr.db import get_db, init_db
with open(os.path.join(os.path.dirname(__file__), 'data.sql'), 'rb') as f:
_data_sql = f.read().decode('utf8')
@pytest.fixture
def app():
db_fd, db_path = tempfile.mkstemp()
app = create_app({
'TESTING': True,
'DATABASE': db_path,
})
with app.app_context():
init_db()
get_db().executescript(_data_sql)
yield app
os.close(db_fd)
os.unlink(db_path)
@pytest.fixture
def client(app):
return app.test_client()
@pytest.fixture
def runner(app):
return app.test_cli_runner()
这是教程中所示的此类模块的代码(唯一的区别是我的模块是大写的):
我虽然这可能是我的文件位置的问题,但我正确映射了教程项目布局:
我不知道我错过了什么。
最佳答案
您可能需要将 pytest 作为 python 中的模块运行(这会将当前目录添加到 sys.path)。我记得有过类似的情况,这为我解决了这个问题:
python -m pytest -vv
<小时/>
来源:https://docs.pytest.org/en/latest/usage.html#calling-pytest-through-python-m-pytest
您可以从命令行通过 Python 解释器调用测试:
python -m pytest [...] 这几乎相当于直接调用命令行脚本 pytest [...],只不过通过 python 调用还会将当前目录添加到 sys.path 中。
关于python - 使用 Flask 进行 pytest 无法找到模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57314940/