简体   繁体   English

Pydantic 设置管理 + FastAPI:如何在 pytest 测试期间忽略 a.env 文件?

[英]Pydantic settings management + FastAPI: how to ignore a .env file during tests with pytest?

I'm using Pydantic settings management in a FastAPI-based project.我在基于 FastAPI 的项目中使用Pydantic 设置管理 I have a Settings class like this one:我有一个这样的Settings class:

class Settings(BaseSettings):
    FOO: str = ''
    BAR: int = 0

    class Config:
        env_file = "path/to/.my_env_file")
        env_nested_delimiter = "__"

The file path/to/.my_env_file contains FOO and BAR values.文件path/to/.my_env_file包含FOOBAR值。

During tests, I need to selectively patch Settings , and I do not want to read anything from path/to/.my_env_file .在测试期间,我需要有选择地修补Settings ,并且我不想从path/to/.my_env_file读取任何内容。 Eg,例如,

path/to/.my_env_file

FOO=i_do_not_wanna_read_this
BAR=100

my test file:我的测试文件:

@lru_cache()
def get_settings():
    return Settings()

def get_settings_override() -> Settings:
    return Settings(
        FOO = 'foo'
    )

app.dependency_overrides[get_settings] = get_settings_override

I want to run tests with FOO='foo' and with the default value of BAR (ie, BAR=0 , ignoring the content of path/to/.my_env_file . In the code above, I get FOO='foo' but BAR is still read from path/to/.my_env_file (ie, BAR=100 )我想使用FOO='foo'和默认值 BAR 运行测试(即BAR=0 ,忽略path/to/.my_env_file的内容。在上面的代码中,我得到FOO='foo'BAR仍然从path/to/.my_env_file (即BAR=100

Is there a straightforward way to handle that?有没有一种直接的方法来处理这个问题?

While I couldn't find a straightforward solution in the docs, or any other page, this worked for my tests:虽然我无法在文档或任何其他页面中找到直接的解决方案,但这对我的测试有效:

When using tox, put this into your tox.ini , as per this Stack Overflow question :使用 tox 时,将其放入您的tox.ini中,按照这个 Stack Overflow 问题

[testenv]
setenv = TOX_TESTENV = true

You can then simply use the following snippet to override your env_file settings:然后您可以简单地使用以下代码片段来覆盖您的env_file设置:

import os

# ... snip ...

if os.environ.get("TOX_TESTENV") is not None:
    Settings.Config.env_file = ""

Similar approaches, for example by checking sys.argv for the existence of "test" or checking if unittest is loaded should work fine too:类似的方法,例如通过检查sys.argv是否存在“test”或检查是否加载了unittest应该可以正常工作:

import sys

# ... snip ...

if len(sys.argv) > 1 and "pytest" in sys.argv[0]:
    Settings.Config.env_file = ""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM