2

I'm trying to create a test for my Flask app using the Flask Test tutorial but when I run the tests using pytest it throws the following error:

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'

I'm using Windows 10, virtual enviroment for the flask app and Python 3.8. How can I solve this?

My project structure is:

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'])

and init.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
luturol
  • 565
  • 8
  • 12

1 Answers1

3

I've solved creating a setup.py in the root directory of the project and building my package so the test directory could access the app package.

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',
)

After just run:

pip install -e .

This links helped me solved this issue

luturol
  • 565
  • 8
  • 12