在 FastAPI 中测试 Pydantic 设置

Mat*_*tro 18 python testing pydantic fastapi

假设我的main.py是这样的(这是一个简化的示例,在我的应用程序中我使用实际的数据库,并且有两个不同的数据库 URI 用于开发和测试):

from fastapi import FastAPI
from pydantic import BaseSettings

app = FastAPI()

class Settings(BaseSettings):
    ENVIRONMENT: str

    class Config:
        env_file = ".env"
        case_sensitive = True

settings = Settings()

databases = {
    "dev": "Development",
    "test": "Testing"
}
database = databases[settings.ENVIRONMENT]

@app.get("/")
def read_root():
    return {"Environment": database}
Run Code Online (Sandbox Code Playgroud)

而这.env

ENVIRONMENT=dev
Run Code Online (Sandbox Code Playgroud)

假设我想测试我的代码并且我想设置ENVIRONMENT=test为使用测试数据库。我应该怎么办?在FastAPI文档(https://fastapi.tiangolo.com/advanced/settings/#settings-and-testing)中有一个很好的例子,但它是关于依赖关系的,所以据我所知这是一个不同的情况。

我的想法如下(test.py):

ENVIRONMENT=dev
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

此外,我收到此错误:

ScopeMismatch: You tried to access the 'function' scoped fixture 'monkeypatch' with a 'session' scoped request object, involved factories
test.py:7:  def test_config(monkeypatch)
env\lib\site-packages\_pytest\monkeypatch.py:16:  def monkeypatch()
Run Code Online (Sandbox Code Playgroud)

虽然从pytest官方文档来看它应该可以工作(https://docs.pytest.org/en/3.0.1/monkeypatch.html#example-setting-an-environment-variable-for-the-test-session)。我已经安装了最新版本pytest

因此,我尝试使用特定的测试环境变量: https: //pydantic-docs.helpmanual.io/usage/settings/#field-value-priority

说实话,我迷路了,我唯一的真正目标是拥有不同的测试配置(与 Flask 的工作方式相同:https ://flask.palletsprojects.com/en/1.1.x/tutorial/tests/#setup-和-固定装置)。我是否以错误的方式处理问题?

erh*_*sen 18

PydanticSettings是可变的,所以你可以简单地在你的test.py

from main import settings

settings.ENVIRONMENT = 'test'
Run Code Online (Sandbox Code Playgroud)

  • 除非将“allow_mutation = False”传递给设置的“Config”对象,否则为 True。 (6认同)
  • 使用 `monkeypatch.setattr(settings, 'ENVIRONMENT', 'test')`。 (2认同)