Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

python - Import error when running pytest with both a src and test directory

I am having a hard time understanding why my Flask app runs fine, and all imports work. But when I run pytest the same code can't resolve imports. Here is a sample app structure:

+-- mainFolder
|   +-- src
|       +-- app.py
|       +-- resources
|           +-- AppConfig.py
|   +-- test
|       +-- v1
|           +-- test_someTest.py
|   +-- conftest.py

Like I said, running app.py works. I can import AppConfig no problem. Everything works. However, when I run python -m pytest I get:

ImportError while loading conftest 'C:...conftest.py'.
conftest.py:2: in <module>
    from src.app import app as flask_app
srcapp.py:3: in <module>
    from resources.AppConfig import AppConfig
E   ModuleNotFoundError: No module named 'resources'

Here is conftest.py:

import pytest
from src.app import app as flask_app


@pytest.fixture
def app():
    yield flask_app


@pytest.fixture
def client(app):
    return app.test_client()

Here is the relevant code in app.py:

from resources.AppConfig import AppConfig

with app.app_context():
    current_app.appConfig = AppConfig.getAppConfig()

Doesn't work. I have moved conftest.py to both directories. I have exported both directories to PYTHONPATH.

The only way this works is when I move the test folder buck into the src directory... then there are no issues.

Does anyone have insight? I am using Python 3.8. I do not want to use virtual environments, or setup.py at this point. I had them configured already and they are overkill at this point. I just need something simple.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...