fakeapi


Namefakeapi JSON
Version 1.0.11 PyPI version JSON
download
home_pagehttps://github.com/joknarf/fakeapi
SummaryFake/Mock API Rest Calls requests
upload_time2023-01-22 09:14:36
maintainer
docs_urlNone
authorjoknarf
requires_python
licenseMIT
keywords requests api rest api-client mock http
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            [![Travis CI](https://travis-ci.com/joknarf/fakeapi.svg?branch=main)](https://travis-ci.com/github/joknarf/fakeapi)
[![Codecov](https://codecov.io/github/joknarf/fakeapi/coverage.svg?branch=main)](https://codecov.io/gh/joknarf/fakeapi)
[![Upload Python Package](https://github.com/joknarf/fakeapi/workflows/Upload%20Python%20Package/badge.svg)](https://github.com/joknarf/fakeapi/actions?query=workflow%3A%22Upload+Python+Package%22)
[![Pypi version](https://img.shields.io/pypi/v/fakeapi.svg)](https://pypi.org/project/fakeapi/)
[![Downloads](https://pepy.tech/badge/fakeapi)](https://pepy.tech/project/fakeapi)
[![Python versions](https://img.shields.io/badge/python-3.6-blue.svg)](https://shields.io/)
[![Licence](https://img.shields.io/badge/licence-MIT-blue.svg)](https://shields.io/)

# fakeapi
Faking/Mocking API Rest Call requests

Faking 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 class

Fakes 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 using `python -m fakeapi` responding to 'GET http://localhost:8080/api'
```shell
$ python -m fakeapi <<< '{ "GET http://localhost:8080/api": { "data": { "message": "Call successfull" }}}'
Starting http server : http://localhost:8080
127.0.0.1 - - [15/Jan/2023 13:00:20] GET localhost:8080/api
fakeapi: Calling: GET http://localhost:8080/api
127.0.0.1 - - [15/Jan/2023 13:00:20] "GET /api HTTP/1.1" 200 -
```

On Client side:  
```shell
$ curl http://localost:8080/api
{"message": "Call successfull"}
```

### Using FakeAPI class
```python
>>> from fakeapi import FakeAPI
>>> api = FakeAPI({
  'GET http://localhost/api': {
    'status_code': 200,
    'data': {
      'message': 'Call successfull'
    }
  }
})
>>> response = api.get('http://localhost/api')
>>> response.status_code
200
>>> response.json()
{'message': 'Call successfull'}
>>> api.http_server()
Starting http server : 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.
>```python
>mycli.py:
>import requests
>
>def call_api():
>  response = requests.get('http://localhost/api')
>  return response.json()
>```
>```python
>test_mycli.py:
>import unittest, mycli
>from fakeapi import FakeAPI
>
>class TestMyCLI(unittest.TestCase):
>  fakeapi = FakeAPI({'GET http://localhost/api': {'data': {'message': 'Call successfull'}}})
>  def setUp(self):
>    # mock 'mycli.requests' get/post/patch/put/delete calls to fakeapi
>    self.mocks = self.fakeapi.mock_module(self, 'mycli.requests')
>  
>  def test_mycli(self):
>    data = mycli.call_api()   # requests calls are mocked to fakeAPI
>    self.mocks.get.assert_called_with('http://localhost/api')
>    print(data)
>
>if __name__ == "__main__":
>    unittest.main(failfast=True, verbosity=2)
>```
>```python
>$ python test_mycli.py
>test_mycli (__main__.TestMyCLI) ... {'message': 'Call successfull'}
>ok
>
>----------------------------------------------------------------------
>Ran 1 test in 0.002s
>
>OK
>```

## fakeapi server usage

`python -m fakeapi` is starting an http server responding to http calls defined in json description.
json url description :

```json
{
  "<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 Usage

FakeAPI class defines the 5 methods:
* get
* post
* put
* patch
* delete

FakeAPI 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 calls

Instead 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 creation

## Using url_config

Each different url calls can be configured in url_config to provide specific status_code or data.

Providing data in url_config for url
```json
{
  "<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 json

FakeAPI methods by default returns `FakeResponse` with following :
* status_code = 200/201 (for post) or status_code defined in url_config
* json() : return json from json file corresponding to METHOD url
* url : url called
* content : byte text
* text : text
* ok : True if status_code <400

`fakeapi = 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 FakeAPI

Mocking can be done using mock_module or mock_class methods in unittest.TestCase.setUp() method.

Example to mock requests with api-client APIClient():
```python
mycli.py:
from apiclient import APIClient
class MyClient(APIClient):
  def call_api(self):
    return self.get('http://localhost/api').json()
```

```python
import unittest
from fakeapi import FakeAPI
from mycli import MyClient
class UnitTest(unittest.TestCase):
    """ Unit Testing mocking MyClient get/post/put/patch """
    fakeapi = FakeAPI({'GET http://localhost/api': {'data': {'message': 'Call successfull'}}})
    apicli = MyClient()

    def setUp(self):
        """ Mock API calls """
        self.apicli = self.fakeapi.mock_class(self.apicli)

    def test_call_api(self):
        """ test_call_api """
        data = self.apicli.call_api()
        self.apicli.get.assert_called_with('http://localhost/api')
        print(data)
```

## Generating test sets 

To 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:
```python
""" Generate url_config for tests from MyClient real API calls """
import json
from mycli import MyClient
from fakeapi import UrlConfigHelper

api = UrlConfigHelper(MyClient)
api.call_api()    # make calls to the API and updates api.url_config
api.save_urlconfig('mytests.json')
print(json.dumps(api.url_config, indent=2))
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/joknarf/fakeapi",
    "name": "fakeapi",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "requests API Rest api-client mock http",
    "author": "joknarf",
    "author_email": "joknarf@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/bf/f6/157f1fc3f6939c375affc7957789efe07efc4bf83b11a3ff962d602eef48/fakeapi-1.0.11.tar.gz",
    "platform": null,
    "description": "[![Travis CI](https://travis-ci.com/joknarf/fakeapi.svg?branch=main)](https://travis-ci.com/github/joknarf/fakeapi)\n[![Codecov](https://codecov.io/github/joknarf/fakeapi/coverage.svg?branch=main)](https://codecov.io/gh/joknarf/fakeapi)\n[![Upload Python Package](https://github.com/joknarf/fakeapi/workflows/Upload%20Python%20Package/badge.svg)](https://github.com/joknarf/fakeapi/actions?query=workflow%3A%22Upload+Python+Package%22)\n[![Pypi version](https://img.shields.io/pypi/v/fakeapi.svg)](https://pypi.org/project/fakeapi/)\n[![Downloads](https://pepy.tech/badge/fakeapi)](https://pepy.tech/project/fakeapi)\n[![Python versions](https://img.shields.io/badge/python-3.6-blue.svg)](https://shields.io/)\n[![Licence](https://img.shields.io/badge/licence-MIT-blue.svg)](https://shields.io/)\n\n# fakeapi\nFaking/Mocking API Rest Call requests\n\nFaking API calls using static fixtures with FakeAPI class.  \nMocking API calls using FakeAPI get/post/patch/delete methods.  \nCreate HTTP server Rest API with a single json response file.\n\n# FakeAPI class\n\nFakes http requests calls (get/post/put/patch/delete).  \nInstead of doing http calls to urls, FakeAPI class will returns response with data from url dict data or json file.  \nCan 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.\n\nAnother 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)\n\nFakeAPI class is also able to act as a HTTP Rest API server using a single json description of responses to calls.\n\n## Quick examples:\n\n### Start http server using `python -m fakeapi` responding to 'GET http://localhost:8080/api'\n```shell\n$ python -m fakeapi <<< '{ \"GET http://localhost:8080/api\": { \"data\": { \"message\": \"Call successfull\" }}}'\nStarting http server : http://localhost:8080\n127.0.0.1 - - [15/Jan/2023 13:00:20] GET localhost:8080/api\nfakeapi: Calling: GET http://localhost:8080/api\n127.0.0.1 - - [15/Jan/2023 13:00:20] \"GET /api HTTP/1.1\" 200 -\n```\n\nOn Client side:  \n```shell\n$ curl http://localost:8080/api\n{\"message\": \"Call successfull\"}\n```\n\n### Using FakeAPI class\n```python\n>>> from fakeapi import FakeAPI\n>>> api = FakeAPI({\n  'GET http://localhost/api': {\n    'status_code': 200,\n    'data': {\n      'message': 'Call successfull'\n    }\n  }\n})\n>>> response = api.get('http://localhost/api')\n>>> response.status_code\n200\n>>> response.json()\n{'message': 'Call successfull'}\n>>> api.http_server()\nStarting http server : http://localhost:8080\n...\n```\n\nFakeAPI class can easily mock requests calls in unittest.  \nUsefull to test Application that is calling 3rd party API that is not to be tested.\n>```python\n>mycli.py:\n>import requests\n>\n>def call_api():\n>  response = requests.get('http://localhost/api')\n>  return response.json()\n>```\n>```python\n>test_mycli.py:\n>import unittest, mycli\n>from fakeapi import FakeAPI\n>\n>class TestMyCLI(unittest.TestCase):\n>  fakeapi = FakeAPI({'GET http://localhost/api': {'data': {'message': 'Call successfull'}}})\n>  def setUp(self):\n>    # mock 'mycli.requests' get/post/patch/put/delete calls to fakeapi\n>    self.mocks = self.fakeapi.mock_module(self, 'mycli.requests')\n>  \n>  def test_mycli(self):\n>    data = mycli.call_api()   # requests calls are mocked to fakeAPI\n>    self.mocks.get.assert_called_with('http://localhost/api')\n>    print(data)\n>\n>if __name__ == \"__main__\":\n>    unittest.main(failfast=True, verbosity=2)\n>```\n>```python\n>$ python test_mycli.py\n>test_mycli (__main__.TestMyCLI) ... {'message': 'Call successfull'}\n>ok\n>\n>----------------------------------------------------------------------\n>Ran 1 test in 0.002s\n>\n>OK\n>```\n\n## fakeapi server usage\n\n`python -m fakeapi` is starting an http server responding to http calls defined in json description.\njson url description :\n\n```json\n{\n  \"<METHOD> <url>\": {\n    \"status_code\": <status_code>,\n    \"data\": <url_data>\n  },...\n}\n```\n\n```\n$ python -m fakeapi -h\nusage: python -m fakeapi [-h] [-s SERVER] [-p PORT] [-P PREFIX] [jsonfile]\n\npositional arguments:\n  jsonfile              Json file for FakeAPI\n\noptions:\n  -h, --help            show this help message and exit\n  -s SERVER, --server SERVER\n                        HTTP server address\n  -p PORT, --port PORT  HTTP server port\n  -P PREFIX, --prefix PREFIX\n                        HTTP prefix (http://server:port)\n```\n\n## FakeAPI class Usage\n\nFakeAPI class defines the 5 methods:\n* get\n* post\n* put\n* patch\n* delete\n\nFakeAPI provides the mocking methods to be used in unittest.TestCase.setUp():\n* mock_module(test_case: TestCase, module: str)\n* mock_class(apicli: Object)\n\n## Mapping Static data to urls calls\n\nInstead of calling 3rd party API, FakeAPI will use static data (from dict or json files). \nstatic data can be defined several ways :\n* passing FakeAPI url_config parameter with data: \n  * `api = FakeAPI(url_config={'METHOD url':{'data':{...}},...})`\n* passing FakeAPI url_json parameter with json file containing url_config data: \n  * `api = FakeAPI(url_json='url_config.json')`\n* FakeAPI.url_config property can be modified after creation\n\n## Using url_config\n\nEach different url calls can be configured in url_config to provide specific status_code or data.\n\nProviding data in url_config for url\n```json\n{\n  \"<METHOD> <url>\": {\n    \"status_code\": <status_code>,\n    \"data\": <url_data>\n  },...\n}\n```\n* `<METHOD>      `: http method : GET/POST/PUT/PATCH/DELETE\n* `<url>         `: full url that is called (with query string)\n* `<status_code> `: http code to return in repsonse (200/201/404/500...)\n* `<url_data>    `: data to retrieve for url call on method.\n\nWhen a request method occurs on `<url>` if the key `<METHOD> <url>` has a entry in url_config, returns 'data'/'status_code' if defined.  \n\n## FakeAPI returns FakeResponse or json\n\nFakeAPI methods by default returns `FakeResponse` with following :\n* status_code = 200/201 (for post) or status_code defined in url_config\n* json() : return json from json file corresponding to METHOD url\n* url : url called\n* content : byte text\n* text : text\n* ok : True if status_code <400\n\n`fakeapi = FakeAPI(returns='json')` is to be used to return directly 'json', instead of response.  \nTo be used with api-client module class APIClient(response_handler=JsonResponseHandler) as get/post/patch/delete returns directly json() from response.\n\n\n## Mocking http requests using FakeAPI\n\nMocking can be done using mock_module or mock_class methods in unittest.TestCase.setUp() method.\n\nExample to mock requests with api-client APIClient():\n```python\nmycli.py:\nfrom apiclient import APIClient\nclass MyClient(APIClient):\n  def call_api(self):\n    return self.get('http://localhost/api').json()\n```\n\n```python\nimport unittest\nfrom fakeapi import FakeAPI\nfrom mycli import MyClient\nclass UnitTest(unittest.TestCase):\n    \"\"\" Unit Testing mocking MyClient get/post/put/patch \"\"\"\n    fakeapi = FakeAPI({'GET http://localhost/api': {'data': {'message': 'Call successfull'}}})\n    apicli = MyClient()\n\n    def setUp(self):\n        \"\"\" Mock API calls \"\"\"\n        self.apicli = self.fakeapi.mock_class(self.apicli)\n\n    def test_call_api(self):\n        \"\"\" test_call_api \"\"\"\n        data = self.apicli.call_api()\n        self.apicli.get.assert_called_with('http://localhost/api')\n        print(data)\n```\n\n## Generating test sets \n\nTo have url_config corresponding to API calls, you can generate url_config from real calls to API, \nthen use the result in your tests.\n\nThe urlconfighelper module can help, as can create a class derived from your class,\nsupercharging the get/post/put/pach/delete method to generate url_config for all calls.\n\nYou can then save the url_config containing all calls you made to a json file to be used as url_config in tests.\n\nExample:\n```python\n\"\"\" Generate url_config for tests from MyClient real API calls \"\"\"\nimport json\nfrom mycli import MyClient\nfrom fakeapi import UrlConfigHelper\n\napi = UrlConfigHelper(MyClient)\napi.call_api()    # make calls to the API and updates api.url_config\napi.save_urlconfig('mytests.json')\nprint(json.dumps(api.url_config, indent=2))\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Fake/Mock API Rest Calls requests",
    "version": "1.0.11",
    "split_keywords": [
        "requests",
        "api",
        "rest",
        "api-client",
        "mock",
        "http"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2eda6dfce6644d950b9fa79069f0117cfe162b834c9f1751ac5f32fe096369ff",
                "md5": "49d2669fd15327a2e30c342355d53da1",
                "sha256": "ecc89933c54630bb6a4a1087568dd1315d7dfb28fd14db018129803be02c987d"
            },
            "downloads": -1,
            "filename": "fakeapi-1.0.11-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "49d2669fd15327a2e30c342355d53da1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 10353,
            "upload_time": "2023-01-22T09:14:34",
            "upload_time_iso_8601": "2023-01-22T09:14:34.818296Z",
            "url": "https://files.pythonhosted.org/packages/2e/da/6dfce6644d950b9fa79069f0117cfe162b834c9f1751ac5f32fe096369ff/fakeapi-1.0.11-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "bff6157f1fc3f6939c375affc7957789efe07efc4bf83b11a3ff962d602eef48",
                "md5": "f4e67fbc9081b8b5f0c7e2e1f5e13ec7",
                "sha256": "015836e8480823085a524e9b1dc395cfa24f901d053ec50a7355761e24148bd2"
            },
            "downloads": -1,
            "filename": "fakeapi-1.0.11.tar.gz",
            "has_sig": false,
            "md5_digest": "f4e67fbc9081b8b5f0c7e2e1f5e13ec7",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 11300,
            "upload_time": "2023-01-22T09:14:36",
            "upload_time_iso_8601": "2023-01-22T09:14:36.619535Z",
            "url": "https://files.pythonhosted.org/packages/bf/f6/157f1fc3f6939c375affc7957789efe07efc4bf83b11a3ff962d602eef48/fakeapi-1.0.11.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-01-22 09:14:36",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "joknarf",
    "github_project": "fakeapi",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "fakeapi"
}
        
Elapsed time: 0.03061s