简体   繁体   中英

How to override a function python?

I have some code I'd like to quickly test. This code includes a line that needs to query a server and obtain a True/False answer:

result = server.queryServer(data)

Is there a way to override this function call so that it just calls a local function that always returns True (so that I can debug without running the server)?

Mock is your friend. It allows you to mock entire classes or functions of them.

What you want is called mocking , replacing existing objects with temporary objects that act differently just for a test.

Use the unittest.mock library to do this. It will create the temporary objects for you, and give you the tools to replace the object, and restore the old situation, for the duration of a test.

The module provides patchers to do the replacement. For example, you could use a context manager:

from unittest import mock

with mock.patch('server.queryServer') as mocked_queryServer:
    mocked_queryServer.return_value = True  # always return True when called
    # test your code
    # ...

    # afterwards, check if the mock has been called at least once.
    mocked_queryServer.assert_called()

I added an assertion at the end there; mock objects not only let you replace functions transparently, they then also record what happens to them, letting you check if your code worked correctly by calling the mock.

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