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

时间:2016-10-25 12:14:49

标签: python django

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

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")

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

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

1 个答案:

答案 0 :(得分:3)

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

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