Package: fakeapi
fakeapiFaking/Mocking API Rest Call requestsFaking API calls using static fixtures with FakeAPI class.Mocking API calls using FakeAPI get/post/patch/delete methods.Create HTTP server Rest API with a single json response file.FakeAPI classFakes http requests calls (get/post/put/patch/delete).Instead of doing http calls to urls, FakeAPI class will returns response with data from url dict data or json file.Can be used during development of Application that must use 3rd party API without actually calling the API, but using static tests sets data for url calls.Another purpose is to use FakeAPI class to mock http requests when doing Unit testing of application that is using 3rd party API calls (the tests won't actually call the 3rd party API that is not to be tested)FakeAPI class is also able to act as a HTTP Rest API server using a single json description of responses to calls.Quick examples:Start http server usingpython -m fakeapiresponding to 'GEThttp://localhost:8080/api'$python-mfakeapi<<<'{ "GET http://localhost:8080/api": { "data": { "message": "Call successfull" }}}'Startinghttpserver:http://localhost:8080127.0.0.1--[15/Jan/202313:00:20]GETlocalhost:8080/api
fakeapi:Calling:GEThttp://localhost:8080/api127.0.0.1--[15/Jan/202313:00:20]"GET /api HTTP/1.1"200-On Client side:$curlhttp://localost:8080/api{"message":"Call successfull"}Using FakeAPI class>>>fromfakeapiimportFakeAPI>>>api=FakeAPI({'GET http://localhost/api':{'status_code':200,'data':{'message':'Call successfull'}}})>>>response=api.get('http://localhost/api')>>>response.status_code200>>>response.json(){'message':'Call successfull'}>>>api.http_server()Startinghttpserver:http://localhost:8080...FakeAPI class can easily mock requests calls in unittest.Usefull to test Application that is calling 3rd party API that is not to be tested.mycli.py:importrequestsdefcall_api():response=requests.get('http://localhost/api')returnresponse.json()test_mycli.py:importunittest,myclifromfakeapiimportFakeAPIclassTestMyCLI(unittest.TestCase):fakeapi=FakeAPI({'GET http://localhost/api':{'data':{'message':'Call successfull'}}})defsetUp(self):# mock 'mycli.requests' get/post/patch/put/delete calls to fakeapiself.mocks=self.fakeapi.mock_module(self,'mycli.requests')deftest_mycli(self):data=mycli.call_api()# requests calls are mocked to fakeAPIself.mocks.get.assert_called_with('http://localhost/api')print(data)if__name__=="__main__":unittest.main(failfast=True,verbosity=2)$pythontest_mycli.pytest_mycli(__main__.TestMyCLI)...{'message':'Call successfull'}ok----------------------------------------------------------------------Ran1testin0.002sOKfakeapi server usagepython -m fakeapiis starting an http server responding to http calls defined in json description.
json url description :{"<METHOD> <url>":{"status_code":<status_code>,"data":<url_data>},...}$ python -m fakeapi -h
usage: python -m fakeapi [-h] [-s SERVER] [-p PORT] [-P PREFIX] [jsonfile]

positional arguments:
  jsonfile              Json file for FakeAPI

options:
  -h, --help            show this help message and exit
  -s SERVER, --server SERVER
                        HTTP server address
  -p PORT, --port PORT  HTTP server port
  -P PREFIX, --prefix PREFIX
                        HTTP prefix (http://server:port)FakeAPI class UsageFakeAPI class defines the 5 methods:getpostputpatchdeleteFakeAPI provides the mocking methods to be used in unittest.TestCase.setUp():mock_module(test_case: TestCase, module: str)mock_class(apicli: Object)Mapping Static data to urls callsInstead of calling 3rd party API, FakeAPI will use static data (from dict or json files).
static data can be defined several ways :passing FakeAPI url_config parameter with data:api = FakeAPI(url_config={'METHOD url':{'data':{...}},...})passing FakeAPI url_json parameter with json file containing url_config data:api = FakeAPI(url_json='url_config.json')FakeAPI.url_config property can be modified after creationUsing url_configEach different url calls can be configured in url_config to provide specific status_code or data.Providing data in url_config for url{"<METHOD> <url>":{"status_code":<status_code>,"data":<url_data>},...}<METHOD>: http method : GET/POST/PUT/PATCH/DELETE<url>: full url that is called (with query string)<status_code>: http code to return in repsonse (200/201/404/500...)<url_data>: data to retrieve for url call on method.When a request method occurs on<url>if the key<METHOD> <url>has a entry in url_config, returns 'data'/'status_code' if defined.FakeAPI returns FakeResponse or jsonFakeAPI methods by default returnsFakeResponsewith following :status_code = 200/201 (for post) or status_code defined in url_configjson() : return json from json file corresponding to METHOD urlurl : url calledcontent : byte texttext : textok : True if status_code <400fakeapi = FakeAPI(returns='json')is to be used to return directly 'json', instead of response.To be used with api-client module class APIClient(response_handler=JsonResponseHandler) as get/post/patch/delete returns directly json() from response.Mocking http requests using FakeAPIMocking can be done using mock_module or mock_class methods in unittest.TestCase.setUp() method.Example to mock requests with api-client APIClient():mycli.py:fromapiclientimportAPIClientclassMyClient(APIClient):defcall_api(self):returnself.get('http://localhost/api').json()importunittestfromfakeapiimportFakeAPIfrommycliimportMyClientclassUnitTest(unittest.TestCase):""" Unit Testing mocking MyClient get/post/put/patch """fakeapi=FakeAPI({'GET http://localhost/api':{'data':{'message':'Call successfull'}}})apicli=MyClient()defsetUp(self):""" Mock API calls """self.apicli=self.fakeapi.mock_class(self.apicli)deftest_call_api(self):""" test_call_api """data=self.apicli.call_api()self.apicli.get.assert_called_with('http://localhost/api')print(data)Generating test setsTo have url_config corresponding to API calls, you can generate url_config from real calls to API,
then use the result in your tests.The urlconfighelper module can help, as can create a class derived from your class,
supercharging the get/post/put/pach/delete method to generate url_config for all calls.You can then save the url_config containing all calls you made to a json file to be used as url_config in tests.Example:""" Generate url_config for tests from MyClient real API calls """importjsonfrommycliimportMyClientfromfakeapiimportUrlConfigHelperapi=UrlConfigHelper(MyClient)api.call_api()# make calls to the API and updates api.url_configapi.save_urlconfig('mytests.json')print(json.dumps(api.url_config,indent=2))