首页 > 解决方案 > 如何在pytest中对单个变量值进行monkeypatch

问题描述

我有一个功能:

def test():
    url = "/test/pvc/name"
    if "pvc" in url:
        return True
    else:
        return False

现在要测试这个函数,我想修补url变量。我怎样才能做到这一点?我试过了:

monkeypatch.setattr('url', "/test")

但这似乎不起作用。我不断得到:

    def derive_importpath(import_path, raising):
        if not isinstance(import_path, six.string_types) or "." not in import_path:
>           raise TypeError("must be absolute import path string, not %r" % (import_path,))
E           TypeError: must be absolute import path string, not 'url'

标签: pythonpython-2.7

解决方案


尝试获取 URL 作为具有默认值的参数,如下所示:

def test(url='/test/pvc/name'):
    if "pvc" in url:
        return True
    else:
        return False

现在,当您调用它时,您可以设置所需的 URL。您的功能更加抽象和有用。

稍微拉伸一下,您可以像这样重写该函数:

def test(url='test/pvc/name'):
    return 'pvc' in url

True如果 pvc 在变量中,它将返回,False否则返回


此外,monkeypatch用于修补导入的模块。我们从不模拟函数内部的变量。这与 TDD 的整个理念背道而驰。在进行单元测试时,您应该模拟所有导入的依赖项,但您应该保持函数内的变量和数据保持不变。


推荐阅读