带有 Flask 的 pytest 无法定位模块

HuL*_*iCa 6 python pytest flask

我正在按照本教程https://flask.palletsprojects.com/en/1.1.x/#user-s-guide学习Flask但是,当我尝试运行时,出现此错误: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'
Run Code Online (Sandbox Code Playgroud)

这是引发错误 ( 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()
Run Code Online (Sandbox Code Playgroud)

这是教程中显示的此类模块的代码(唯一的区别是我的模块大写):

在此处输入图片说明

我虽然我的文件位置可能有问题,但我正确地映射了教程项目布局:

在此处输入图片说明

我不知道我错过了什么。

Ane*_*way 12

您可能需要在 python 中将 pytest 作为模块运行(它将当前目录添加到 sys.path)。我记得有过类似的情况,这为我解决了:

python -m pytest -vv
Run Code Online (Sandbox Code Playgroud)

来源:https : //docs.pytest.org/en/latest/usage.html#calling-pytest-through-python-m-pytest

您可以从命令行通过 Python 解释器调用测试:

python -m pytest [...] 这几乎等同于直接调用命令行脚本pytest [...],只是通过python调用还会将当前目录添加到sys.path。