简体   繁体   中英

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.

test.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. 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:

@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. The documentation reads :

patch() works by (temporarily) changing the object that a name points to with another one. [...] 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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