gpt4 book ai didi

python - 如何在 conftest.py 中使用 pytest 对环境进行猴子补丁?

转载 作者:行者123 更新时间:2023-12-04 15:30:33 24 4
gpt4 key购买 nike

我的主文件中有一个全局对象

# reporter.py

from os import environ
from influxdb import InfluxDBClient

influxdb_client = InfluxDBClient(host=environ['INFLUXCLOUD_HOST'],
username=environ['INFLUXCLOUD_USERNAME'],
password=environ['INFLUXCLOUD_PASSWORD'],
ssl=True,
timeout=4*60)

def foo():
pass

我正在使用 pytest,我想为这些环境变量设置虚假值。我的 conftest.py 中有以下内容:
# conftest.py

import pytest

@pytest.fixture(scope='session', autouse=True)
def setup_env(monkeypatch):
monkeypatch.setenv('INFLUXCLOUD_HOST', 'host')
monkeypatch.setenv('INFLUXCLOUD_USERNAME', 'username')
monkeypatch.setenv('INFLUXCLOUD_PASSWORD', 'password')

但是,当我 import reporter在我的测试文件中,我得到一个 KeyError环境中缺少 INFLUXCLOUD_HOST。

为什么 pytest 不执行 setup_env和猴子补丁我的环境?有没有办法这样做?

最佳答案

截至pytest 6.2 ,您可以使用 MonkeyPatch直接对象而不是 monkeypatch固定装置,作为实例或上下文管理器。
(谢尔盖已经 provided solid background 回答了“为什么”的问题;这试图解决“如何”的问题。)
上下文管理器(推荐):

since unlike the monkeypatch fixture, an instance created directly is not undo()-ed automatically.

# test_reporter.py

from pytest import MonkeyPatch


def test_get_client_username():
with MonkeyPatch.context() as mp:
mp.setenv('INFLUXCLOUD_HOST', 'host')
mp.setenv('INFLUXCLOUD_USERNAME', 'username')
mp.setenv('INFLUXCLOUD_PASSWORD', 'password')

from src.reporter import influxdb_client

assert influxdb_client._username == 'username'
直接使用实例:
# conftest.py

from pytest import MonkeyPatch


mp = pytest.MonkeyPatch()
mp.setenv('INFLUXCLOUD_HOST', 'host')
mp.setenv('INFLUXCLOUD_USERNAME', 'username')
mp.setenv('INFLUXCLOUD_PASSWORD', 'password')

假定的文件结构供引用:
src/
reporter.py
__init__.py
test/
conftest.py
test_reporter.py

关于python - 如何在 conftest.py 中使用 pytest 对环境进行猴子补丁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46733332/

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