gpt4 book ai didi

python - 如何对使用环境变量的装饰器进行单元测试?

转载 作者:行者123 更新时间:2023-11-30 22:48:17 27 4
gpt4 key购买 nike

我创建了一个装饰器以允许函数仅在特定环境中运行:

def accepted_environments(*envs):
"""
The decorated function can be executed only in specified envs
"""
def my_decorator(func_to_be_decorated):
def wrapper():
if settings.ENV_NAME not in envs:
raise EnvironmentException
return func_to_be_decorated()
return wrapper
return my_decorator

# Usage example
@accepted_environments('local', 'prod')
def hello():
print("hello")

这似乎可行,但我想对其进行单元测试。问题是:我的测试可能在每个环境(本地、临时、产品)中运行。另外,我认为我的测试能够更改环境变量并不安全。

我应该“ mock ”这种行为吗?你会怎么做?谢谢!

最佳答案

使用 mock 覆盖 settings.ENV_NAME 的值进行测试。

def test_not_in_dev(self):
with mock.patch.dict(settings.__dict__, ENV_NAME="dev"):
self.assertRaises(EnvironmentException, hello)

关于python - 如何对使用环境变量的装饰器进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40239707/

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