Search code examples
pythondjangounit-testingmockingdjango-testing

Mock patch not replacing function correctly


I have a tastypie REST API resource, let's say called Resource, that imports and uses a function called get_token from libs.utils in its obj_get method.

So to test this resource, in my test class I have created a test like what follows:

mock_get_token = Mock(return_value="something")

@patch("path.to.resource.get_token", mock_get_token)
def test_get_token(self):
    params = {"args": "args"}
    # following call should call the get_token function in the resource
    response = self.client.get("path/to/resource", params)
    # do things with the response and make sure I get right output

So when I run the test by itself, the @patch works correctly and as expected, replacing the function with the mock function. However, running the test within our larger test suite for the application causes the patch to fail.

Doing things like manually trying to replace the function with the mocked function also has an unsuccessful patch. I'm wondering what else could be causing the issue, and I find it very curious that the patch works correctly when the test is run by itself or with a smaller subset of our test suite.


Solution

  • We couldn't figure out the exact solution, but a workaround was that since most of the logic in the obj_get method was handled by another function api_call(), we mocked the call to the api_call function instead.

    So the issue appeared to be some import issue as api_call wasn't imported anywhere.