gpt4 book ai didi

python - ModuleNotFoundError : No module named 'app' when trying to create a Test using Pytest and Flask on Windows virtual enviroment

转载 作者:行者123 更新时间:2023-12-03 11:09:28 24 4
gpt4 key购买 nike

我正在尝试使用Flask Test tutorial为我的Flask应用程序创建测试,但是当我使用pytest运行测试时,会引发以下错误:

Hint: make sure your test modules/packages have valid Python names.
Traceback:
test\test_flask.py:6: in <module>
from app import app
E ModuleNotFoundError: No module named 'app'

我正在使用Windows 10,flask应用程序和Python 3.8的虚拟环境。我该如何解决?

我的项目结构是:

Project Tree from VsCode

test_flask.py:
import os
import tempfile

import pytest

from app import app

@pytest.fixture
def client():
db_fd, app.config['DATABASE'] = tempfile.mkstemp()
app.config['TESTING'] = True

with app.app.test_client() as client:
with app.app.context():
app.init_db()
yield client

os.close(db_fd)
os.unlink(app.app.config['DATABASE'])

初始 .py:
from flask import Flask, request, jsonify
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
from flask_jwt_extended import (
JWTManager, jwt_required, create_access_token,
get_jwt_identity
)
from flask_cors import CORS

app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
jwt = JWTManager(app)
CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'


from app import routes, models

mymanhualist.py:
from app import app

最佳答案

我解决了在项目的根目录中创建setup.py并构建我的包的问题,​​以便测试目录可以访问应用程序包。

setup.py:

import setuptools

with open("README.md", "r") as fh:
long_description = fh.read()

setuptools.setup(
name="appPackage-YourUser",
version="0.0.1",
author="Your Name",
author_email="yourownemail@email.com",
description="",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/luturol/MyManhuaListAPI",
packages=setuptools.find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.6',
)

刚运行后:
pip install -e .

此链接帮助我解决了这个问题
  • Flask repository of testing tutorial
  • What is setup.py
  • Flask - ImportError: No module named app
  • 关于python - ModuleNotFoundError : No module named 'app' when trying to create a Test using Pytest and Flask on Windows virtual enviroment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60859997/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com