我有一个foo
调用另一个函数的函数get_info_from_tags
。
这是get_info_from_tags
实现:
def get_info_from_tags(*args):
instance_id = get_instance_id()
proc = subprocess.Popen(["aws", "ec2", "describe-tags", "--filters", f"Name=resource-id,Values={instance_id}"],
stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
em_json = json.loads(out.decode('utf8'))
tags = em_json['Tags'] # tags list
results = []
for arg in args:
for tag in tags:
if tag['Key'] == arg:
results.append(tag['Value'])
return results
有一组10个可能的args可以传递给get_info_from_tags
,而我需要返回正确的数组(我不想调用aws服务,这就是我的模拟的目的,我将手动设置值一本字典)。
我get_info_from_tags
该如何嘲笑,以便我打电话时
get_info_from_tags('key1', 'key2' ...)
在foo函数中,我得到想要的结果吗?
我已经尝试过pytest的某些功能,但似乎我不太了解。
一个可能的解决方案是创建另一个函数:
def mocked_get_info_from_tags(*args):
values = []
for arg in args:
values.append(my_dictionary[arg])
return values
但是我不知道如何在测试环境中实现此替代。
谢谢。
unittest.mock.patch
是你的朋友。
您没有指定模块名称,因此我在其中放置了一些<placeholders>
。
from unittest.mock import patch
from <module_with_foo> import foo
from <module_with_mock> import mocked_get_info_from_tags
with patch('<module_with_foo>.get_info_from_tags', mocked_get_info_from_tags):
foo()
这将替换get_info_from_tags
为该函数的模拟版本。替换是在模块级别完成的,因此模块<module_with_foo>
中调用的所有内容get_info_from_tags
现在都将调用您的模拟。
请注意以下路径patch
:
patch
替换模块属性的值。因此,如果您有一个moo
带有function的模块foo
,该bar
模块从module调用moo2
:
# moo module
from moo2 import bar
def foo():
bar()
......从角度看patch
,moo.foo
电话moo.bar
,不是moo2.bar
。因此,您必须在使用功能的地方(而不是在定义功能的地方)修补模块。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句