gpt4 book ai didi

python - 如何在测试期间覆盖 "env_file"?

转载 作者:行者123 更新时间:2023-12-05 08:03:24 25 4
gpt4 key购买 nike

我正在从我的 config.py 中的 .prod.env 文件中读取环境变量:

from pydantic import BaseSettings


class Settings(BaseSettings):
A: int

class Config:
env_file = ".prod.env"
env_file_encoding = "utf-8"

settings = Settings()

在我的 main.py 中,我正在创建 app,如下所示:

from fastapi import FastAPI
from app.config import settings

app = FastAPI()
print(settings.A)

我可以在我的 conftest.py 中像这样覆盖设置变量:

import pytest
from fastapi.testclient import TestClient

from app.main import app
from app.config import settings

settings.A = 42

@pytest.fixture(scope="module")
def test_clinet():
with TestClient(app) as client:
yield client

这很好用,每当我使用 settings.A 时,我都会得到 42。

但是是否可以将整个 env_file.prod.env 覆盖到另一个环境文件 .test.env

此外,我可能想在导入 app 之前在 conftest.py 中调用 settings.A = 42,对吗?

最佳答案

您可以通过使用 _env_file 关键字参数创建一个 Settings 实例来覆盖您使用的 env 文件。

来自 documentation :

Passing a file path via the _env_file keyword argument on instantiation (method 2) will override the value (if any) set on the Config class. If the above snippets were used in conjunction, prod.env would be loaded while .env would be ignored.

例如,这应该适用于您的测试-

import pytest
from fastapi.testclient import TestClient

import app.config as conf
from app.config import Settings

# replace the settings object that you created in the module
conf.settings = Settings(_env_file='.test.env')

from app.main import app

# just to show you that you changed the module-level
# settings
from app.config import settings

@pytest.fixture(scope="module")
def test_client():
with TestClient(app) as client:
yield client

def test_settings():
print(conf.settings)
print(settings)

你可以创建一个.test.env,设置A=10000000,然后运行

pytest -rP conftest.py

# stuff
----- Captured stdout call -----
A=10000000
A=10000000

这看起来有点乱(虽然这可能只用于测试目的),所以我建议不要创建一个可由代码中的所有内容导入的 settings 对象,而是创建它您在实际创建和运行应用程序的 __main__ 中创建的东西,但这是您做出的设计选择。

关于python - 如何在测试期间覆盖 "env_file"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73375390/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com