假设我的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}
当.env
存在时
ENVIRONMENT=dev
假设我想测试我的代码,并且我想设置ENVIRONMENT=test
以使用测试数据库。 我该怎么做? 在FastAPI文档(https://fastapi.tiangolo.com/advanced/settings/#settings-and-testing)中有一个很好的例子,但是它是关于依赖项的,所以据我所知,这是一个不同的情况。
我的想法是以下内容(test.py
):
import pytest
from fastapi.testclient import TestClient
from main import app
@pytest.fixture(scope="session", autouse=True)
def test_config(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "test")
@pytest.fixture(scope="session")
def client():
return TestClient(app)
def test_root(client):
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Environment": "Testing"}
但是它并没有起作用。
此外,我遇到了这个错误:
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()
虽然从 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-and-fixtures)。我是不是在错误的方向上解决问题?
allow_mutation = False
传递给设置的Config
对象,否则为真。 - jhrrmonkeypatch.setattr(settings, 'ENVIRONMENT', 'test')
。 - Albert Tugushev