简体   繁体   English

python如何模拟一个方法?

[英]python how to mock a method?

I want to test a http post method, this method will call some service, but the service cannot work in local test machine, so I want to mock it.我想测试一个http post方法,这个方法会调用一些服务,但是该服务不能在本地测试机上工作,所以我想模拟它。

test.py:测试.py:

@route(bp, '/count', methods=['POST'])
def count():
   from module import service
   ...
   total, ids = service(id, page, count) // total is a integer, ids is a list.
   ...
   return {'total': total, 'ids': ids}

test case:测试用例:

@mock.patch("module.service")
def test_search_user(self, mock_service):
    mock_service.return_value=(1, [])

    url = url_for('users.count')
    params = { .... }

    response = self._test_app.post_json(
        url, params, headers=self.request_headers, expect_errors=True)

    self.assertEqual(response.status_code, 200)

but test case is always failed, it tried to call service method, but it cannot work on my machine.但是测试用例总是失败,它试图调用service方法,但它不能在我的机器上工作。 I just want to mock it, but doesn't work.我只是想嘲笑它,但不起作用。

Anyone can help me!任何人都可以帮助我! Thanks in advance!提前致谢!

According to @syntonym answer, my test case should be wrote like this:根据@syntonym 的回答,我的测试用例应该这样写:

@mock.patch("test.service")
def test_search_user(self, mock_service):
    mock_service.return_value=(1, [])

@mock.patch actually takes the lookup name - not the place where the object you want to patch acutally resides. @mock.patch实际上采用查找名称 - 而不是您要修补的对象实际驻留的位置。 The documentation reads : 文档内容如下

patch() works by (temporarily) changing the object that a name points to with another one. patch() 通过(临时)将名称指向的对象更改为另一个对象。 [...] The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined. [...] 基本原则是在查找对象的位置打补丁,这不一定与定义它的位置相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM