运行 pytest 时导入文件不匹配

问题描述 投票:0回答:1

我正在关注 testdriven.io 使用 FastAPI 和 Docker 进行测试驱动开发教程,但我陷入了 Pytest 设置步骤。我已经一遍又一遍地检查,看看我遗漏了什么,并且不断出现不足。

本教程中的代码示例显示,在 conftest.py 中,您将拥有以下

from
语句:

from app import main
from app.config import get_settings, Settings

首先,Pycharm 告诉我它无法从上面导入任何内容。 我的文件夹结构: enter image description here

main.py:

import os

from fastapi import FastAPI, Depends
from tortoise.contrib.fastapi import register_tortoise

from .config import get_settings, Settings

app = FastAPI()

register_tortoise(
    app,
    db_url=os.environ.get("DATABASE_URL"),
    modules={"models": ["app.models.tortoise"]},
    generate_schemas=False,
    add_exception_handlers=True,
)


@app.get("/ping")
async def pong(settings: Settings = Depends(get_settings)):
    return {"ping": "pong", "environment": settings.environment, "testing": settings.testing}

conftest.py

import os

import pytest
from starlette.testclient import TestClient

from app import main
from app.config import get_settings, Settings


def get_settings_override():
    return Settings(testing=1, database_url=os.environ.get("DATABASE_TEST_URL"))


@pytest.fixture(scope="module")
def test_app():
    # set up
    main.app.dependency_overrides[get_settings] = get_settings_override
    with TestClient(main.app) as test_client:
        # testing
        yield test_client

    # tear down

本教程让您使用

docker-compose exec web python -m pytest

运行测试

这是我运行测试时得到的输出: enter image description here

如有任何帮助,我们将不胜感激。我觉得这是入门级的东西,导致极度头痛。

python pytest fastapi
1个回答
0
投票

感谢@MatsLindh 的帮助。正如他在上面的评论中提到的,本教程让您在整个项目上运行 pytest 而不仅仅是测试文件夹。直接运行测试解决了我的 pytest 失败问题。他还建议查看 pytest 文档以了解进一步的集成步骤,从而就如何让导入在 IDE 中正常工作提供了很好的建议。

© www.soinside.com 2019 - 2024. All rights reserved.