mocking for testing import external_module from unittest mock import from unittest import testcase from unittest import main import json def some_func()calls out to external api which we want to mock response external_module api_call(return responseclass test_some_func_calling_api(testcase)class test_some_func_calling_api(testcase)@patch('external_module api_call'def test_some_func(selfmock_api_call)sets up mock version of api_call mock_api_call return_value magicmock(status_code= response=json dumps({'key':'value'})calls some_func(that calls the (mockapi_call(function result some_func(check that the result returned from some_func(is what was expected self assertequal(result status_code "returned status code is not "self assertequal(result response'{"key""value"}'"response json incorrect"in this example the function being tested is some_func(but some_func(calls out to the mocked function external_module api_call(this mocked function returns magicmock object with pre-specified status_code and response the assertions then validate that the object returned by some_func(contains the correct status code and response validating mocks have been called using unittest mock it is possible to validate that mocked function or method was called appropriately using assert_called()assert_called_with(or assert_called_once_with(depending on whether the function takes parameters or not