python - 如何在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'
解决方案
尝试获取 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 的整个理念背道而驰。在进行单元测试时,您应该模拟所有导入的依赖项,但您应该保持函数内的变量和数据保持不变。
推荐阅读
- javascript - 调用时 Express Route 未触发
- node.js - Mongoose 日期时间和时区,如何根据服务器时区获取日期时间
- qt - QT:在无头 AMI 服务器中生成条形图。无法启动 X 显示
- microsoft-graph-api - 尝试删除权限返回 HTTP 403 - 不允许操作
- python - 绘制抛物线 - NotImplementedError
- javascript - 部署的节点应用程序未运行静态 JavaScript 文件
- python - Python:为什么我在 mac 上调用 osgeo 时会出错?
- kubernetes - 在 GKE 中带有 Web 应用程序的 pod 可以有一个子域 appspot.com?
- sql - 如何在 SQL 查询中产生异常 (Access to Excel)
- windows - Windows 将文本文件转换为 postscript 并打印