[英]Mocking an entire function with parameters in Python
我有这个 Python 代码通常在我想在本地测试的远程服务器上运行:
from af.data import Variable
def create_file():
main_client = file.Client()
directory = main_client.create(Variable.get("DIR_NAME"))
由于我在本地开发并且无法访问提供af.data.Variable
class 的远程服务,我想模拟Variable.get(str)
function,但我希望能够 - 在我自己的模拟——根据传递的str
参数返回一些值。 到目前为止,我只找到了使用 unittest 的 side_effect 将 function 模拟为一些预定义的 static 值的方法。
我怎样才能做到这一点?
在彼得的评论之后,这是解决方案(非常简单):
from unittest.mock import Mock
from af.data import Variable
import os
def side_effect(arg):
"""Put here whatever logic you want to put in your mock, here's an example of reading a system environment variable"""
return os.getenv(arg)
mock = Mock()
mock.get.side_effect = side_effect
Variable = mock
"""Then just use the Variable.get method as you would do in production environment, it should be mocked to the side_effect function declared above"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.