gpt4 book ai didi

python - 如何使 python 模拟函数返回一个特定的值以函数的参数为​​条件?

转载 作者:太空狗 更新时间:2023-10-29 22:28:35 25 4
gpt4 key购买 nike

我有一个 python 2.7x Tornado 应用程序,它在运行时会提供一些 RESTful api 端点。

我的项目文件夹包含许多依赖于 python mock 模块的测试用例,如下所示。

from tornado.testing import AsyncHTTPTestCase
from mock import Mock, patch
import json
from my_project import my_model

class APITestCases(AsyncHTTPTestCase):

def setUp(self):
pass

def tearDown(self):
pass

@patch('my_project.my_model.my_method')
def test_something(
self,
mock_my_method
):

response = self.fetch(
path='http://localhost/my_service/my_endpoint',
method='POST',
headers={'Content-Type': 'application/json'},
body=json.dumps({'hello':'world'})
)

RESTful 端点 http://localhost/my_service/my_endpoint 有两个内部调用 my_method 分别是:my_method(my_arg=1)my_method(my_arg=2)

我想在这个测试用例中模拟出 my_method,如果用 my_arg==2 调用它,它会返回 0,但否则它应该返回它通常会返回的内容。我该怎么做?

我知道我应该这样做:

mock_my_method.return_value = SOMETHING

但我不知道如何正确指定某些东西,以便它的行为取决于调用 my_method 时使用的参数。有人可以给我看或给我举个例子吗??

最佳答案

I want to mock out my_method in this test-case such that it returns 0 if it is called with my_arg==2, but otherwise it should return what it would always normally return. How can I do it?

编写你自己的方法,根据条件模拟调用原始方法:

from my_project import my_model

my_method_orig = my_project.my_model.my_method
def my_method_mocked(self, *args, my_arg=1, **kwargs):
if my_arg == 2: # fake call
return 0
# otherwise, dispatch to real method
return my_method_orig(self, *args, **kwargs, my_arg=my_arg)

对于修补:如果您不需要断言模拟方法被调用的频率以及使用什么参数等,通过 new 参数传递模拟就足够了:

@patch('my_project.my_model.my_method', new=my_method_mocked)
def test_something(
self,
mock_my_method
):

response = self.fetch(...)
# this will not work here:
mock_my_method.assert_called_with(2)

如果您想调用整个模拟断言机制,请按照其他答案中的建议使用 side_effect。示例:

@patch('my_project.my_model.my_method', side_effect=my_method_mocked, autospec=True)
def test_something(
self,
mock_my_method
):

response = self.fetch(...)
# mock is assertable here
mock_my_method.assert_called_with(2)

关于python - 如何使 python 模拟函数返回一个特定的值以函数的参数为​​条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51794954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com