首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pytest,fastapi和tortoise-orm对每个测试进行回滚?

如何使用pytest,fastapi和tortoise-orm对每个测试进行回滚?
EN

Stack Overflow用户
提问于 2020-08-11 17:51:57
回答 1查看 2.9K关注 0票数 5

我正在为crud编写单元测试,我使用的框架是FastAPI,ORM是乌龟,测试模块是pytest。

我有一个配置文件:

代码语言:javascript
复制
import os

import pytest
from starlette.testclient import TestClient
from tortoise.contrib.fastapi import register_tortoise

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


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

@pytest.fixture(scope="module")
def test_app_with_db():
    # set up
    app = create_application()
    app.dependency_overrides[get_settings] = get_settings_override

    # Link with DB for testing
    register_tortoise(
        app,
        db_url=os.environ.get("DATABASE_TEST_URL"),
        modules={"models": ["app.infra.postgres.models"]},
        generate_schemas=True,
        add_exception_handlers=True,
    )
    with TestClient(app) as test_client:

        # testing
        yield test_client

    # tear down

此外,我有这些测试,第一次创造了一个新的载体。第二个,创建一个载体,然后搜索数据库中的所有现有载波。

代码语言:javascript
复制
import json
from app.infra.postgres.crud.cft import cft as pg_cft
from app.services.cft import CFTService

cft_crud = CFTService(pg_cft)

PREFIX = "/api/cft/"


def test_create_carrier(test_app_with_db):
    response = test_app_with_db.post(
        f"{PREFIX}",
        data=json.dumps(
            {
                "broker_id": 1,
                "carrier_id": 1,
                "lower_limit": 10,
                "upper_limit": 100,
                "fee": 50,
                "is_active": True,
            }
        ),
    )
    assert response.status_code == 201
    assert type(response.json()["id"]) == int


def test_get_carriers(test_app_with_db):
    response = test_app_with_db.post(
        f"{PREFIX}",
        data=json.dumps(
            {
                "broker_id": 1,
                "carrier_id": 1,
                "lower_limit": 10,
                "upper_limit": 100,
                "fee": 50,
                "is_active": True,
            }
        ),
    )
    summary_id = response.json()["id"]

    response = test_app_with_db.get(f"{PREFIX}")
    assert response.status_code == 200

    response_list = response.json()

    assert (
        len(list(filter(lambda d: d["id"] == summary_id, response_list))) == 1
    )

问题是,当我使用命令docker-compose -f Docker-compose.dev.yml exec web python -m pytest (是、web、、容器的名称)运行测试时,我会得到一个错误,因为已经有了broker_id和carrier_id的组合。我想要的是为每个测试还原数据库。我怎么能这么做?

编辑:

我就是这样做我想做的

代码语言:javascript
复制
import os

import pytest
from starlette.testclient import TestClient
from tortoise.contrib.test import finalizer, initializer

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


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


@pytest.fixture(scope="function")
def test_app():
    # set up
    app = create_application()
    app.dependency_overrides[get_settings] = get_settings_override

    with TestClient(app) as test_client:

        # testing
        yield test_client

    # tear down


@pytest.fixture(scope="function")
def test_app_with_db():
    # set up
    app = create_application()
    app.dependency_overrides[get_settings] = get_settings_override

    # Link with DB for testing
    initializer(
        ["app.infra.postgres.models"],
        db_url=os.environ.get("DATABASE_TEST_URL"),
    )

    with TestClient(app) as test_client:
        # testing
        yield test_client

    # tear down
    finalizer()
EN

回答 1

Stack Overflow用户

发布于 2020-08-12 13:06:49

正如MrBean所说,您需要让夹具运行于每个测试,而不是每个模块。

您可以这样更改范围:

代码语言:javascript
复制
@pytest.fixture(scope="function")
def test_app_with_db():
    # set up
...

或者可以完全删除scope参数,因为它默认为function

https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session

这是假设您实际上在夹具的# teardown部分中有一些内容。否则就没有什么可以清理数据库了。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63363776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档