如何模拟嵌套函数?

编程入门 行业动态 更新时间:2024-10-24 08:28:49
本文介绍了如何模拟嵌套函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用的模拟库是... mock .

The mocking library I use is ... mock.

当我尝试为某个功能(旧版代码)编写测试用例时,遇到了这个模拟嵌套功能"问题.

I came across this "mock nested functions" problem when I tried to write test case for a function(legacy code).

此函数使用了非常复杂的嵌套函数,对其他模块的依赖性很大.

This function used a very complex nested function with heavy dependencies on other modules.

我想知道是否可以用mock模拟嵌套函数.

I wonder if it's possible to mock nested functions with mock.

推荐答案

例如,您需要模拟来自Google DRIVE API的嵌套函数调用(链接函数)

for example you need to mock nested function calls (chained functions) from Google DRIVE API

result = get_drive_service().files().insert(body='body', convert=True).execute()

因此,您需要通过以下功能进行修补:service_mock(),files(),insert(),直到最后一次execute()响应:

so you need to patch through functions: service_mock(), files(), insert(), till last execute() response:

from mock import patch with patch('path.to.import.get_drive_service') as service_mock: service_mock.return_value.files.return_value.insert.\ return_value.execute.return_value = {'key': 'value', 'status': 200}

主要方案: return_value .第二. return_value .第三. return_value .last. return_value = rsp

Main scheme: first.return_value.second.return_value.third.return_value.last.return_value = rsp

更多推荐

如何模拟嵌套函数?

本文发布于:2023-10-31 05:58:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545213.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!