如何在pytest中正确正确变量

发布于 2025-01-21 14:25:20 字数 824 浏览 6 评论 0原文

我有一些环境变量集,在运行测试时需要模拟,但是当我尝试使用monkeypatch.setenv时,它只是不起作用,并继续从.env 文件。我什至之前曾尝试过delenv,但仍然无法弄清楚如何正确设置测试ENV变量。我之前曾使用过setAttr,它工作正常,但无法弄清楚如何正确进行env修补。

测试固定装置:

@pytest.fixture
def engine(monkeypatch):
    monkeypatch.delenv('DATABASE_URL', raising=False)
    monkeypatch.setenv('DATABASE_URL', 'postgres://root:password@localhost:5432/db_name')
    return DatabaseEngine().get()

.env文件包含database_url保存到名为db_config的变量的 在名为config的模块中

    load_dotenv()
    DB_CONFIG = os.getenv('DATABASE_URL')

,并在databaseEngine中使用。

这不是我第一次试图将envy变量蒙基,并且失败了,还有任何线索如何进行?

I have some environment variable set that I need to mock when running my tests but when I try using monkeypatch.setenv it just doesn't work and keep fetching the variables from .env file. I even tried delenv before but still can't figure out how to set the test env variables correctly. I've used the setattr before and it worked just fine but can't figure out how to do env patching correctly.

The test fixture:

@pytest.fixture
def engine(monkeypatch):
    monkeypatch.delenv('DATABASE_URL', raising=False)
    monkeypatch.setenv('DATABASE_URL', 'postgres://root:password@localhost:5432/db_name')
    return DatabaseEngine().get()

The .env file contains that DATABASE_URL which is saved to a variable named DB_CONFIG
in a module named config

    load_dotenv()
    DB_CONFIG = os.getenv('DATABASE_URL')

and used in the DatabaseEngine.

It's not the first time that I tried to monkeypatch the env variables and failed, any clue how to proceed please ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文