AidaP
AidaP

Reputation: 9

Import "flask" could not be resolved from sourcePylancereportMissingModuleSource

Appreciate that this has been asked before, but I have tried the suggestions to no avail.

a snip of flask not loading, with pip show flask output

VSCode is telling me that: Import "flask" could not be resolved from sourcePylancereportMissingModuleSource)

Running export shows me:

FLASK_APP=app.py
FLASK_ENV=development

I can run flask run and my app works, but when I run pytest, I receive:

______________________ ERROR collecting tests/unit/test_app.py ______________________
ImportError while importing test module '/Users/myname/projects/flask-stock-portfolio/tests/unit/test_app.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/unit/test_app.py:4: in <module>
    from app import app
E   ModuleNotFoundError: No module named 'app'

Where test_app.py reads:

"""
This file (test_app.py) contains the unit tests for the app.py file.
"""
from app import app

def test_index_page():
    """
    GIVEN a Flask application
    WHEN the '/' page is requested (GET)
    THEN check the response is valid
    """
    with app.test_client() as client:
        response = client.get('/')
        assert response.status_code == 200
        assert b'Flask Stock Portfolio App' in response.data
        assert b'Welcome to the Flask Stock Portfolio App!' in response.data

Anything you can do to point me in the right direction would be greatly appreciated.

Upvotes: 0

Views: 3149

Answers (1)

Snorfalorpagus
Snorfalorpagus

Reputation: 3489

You need to add your current working directory to the python search path. This can be done with an environment variable:

export PYTHONPATH=.

Alternatively you can do it from within Python. I usually put this in my conftest.py file in my tests folder, which is executed when pytest starts up.

import sys
from pathlib import Path
path = Path(__file__).parent.parent  # i.e. the folder above the tests folder, which has app
sys.path.append(path)

The VS Code error is a separate issue. It sounds like you might not have the correct Python environment selected. See https://code.visualstudio.com/docs/python/environments

Upvotes: 1

Related Questions