aioresponses


Nameaioresponses JSON
Version 0.7.5 PyPI version JSON
download
home_pagehttps://github.com/pnuckowski/aioresponses
SummaryMock out requests made by ClientSession from aiohttp package
upload_time2023-11-13 18:05:58
maintainer
docs_urlNone
authorPawel Nuckowski
requires_python
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage
            ===============================
aioresponses
===============================

.. image:: https://travis-ci.org/pnuckowski/aioresponses.svg?branch=master
        :target: https://travis-ci.org/pnuckowski/aioresponses

.. image:: https://coveralls.io/repos/github/pnuckowski/aioresponses/badge.svg?branch=master
        :target: https://coveralls.io/github/pnuckowski/aioresponses?branch=master

.. image:: https://landscape.io/github/pnuckowski/aioresponses/master/landscape.svg?style=flat
        :target: https://landscape.io/github/pnuckowski/aioresponses/master
        :alt: Code Health

.. image:: https://pyup.io/repos/github/pnuckowski/aioresponses/shield.svg
        :target: https://pyup.io/repos/github/pnuckowski/aioresponses/
        :alt: Updates

.. image:: https://img.shields.io/pypi/v/aioresponses.svg
        :target: https://pypi.python.org/pypi/aioresponses

.. image:: https://readthedocs.org/projects/aioresponses/badge/?version=latest
        :target: https://aioresponses.readthedocs.io/en/latest/?badge=latest
        :alt: Documentation Status


Aioresponses is a helper to mock/fake web requests in python aiohttp package.

For *requests* module there are a lot of packages that help us with testing (eg. *httpretty*, *responses*, *requests-mock*).

When it comes to testing asynchronous HTTP requests it is a bit harder (at least at the beginning).
The purpose of this package is to provide an easy way to test asynchronous HTTP requests.

Installing
----------

.. code:: bash

    $ pip install aioresponses

Supported versions
------------------
- Python 3.7+
- aiohttp>=3.3.0,<4.0.0

Usage
--------

To mock out HTTP request use *aioresponses* as a method decorator or as a context manager.

Response *status* code, *body*, *payload* (for json response) and *headers* can be mocked.

Supported HTTP methods: **GET**, **POST**, **PUT**, **PATCH**, **DELETE** and **OPTIONS**.

.. code:: python

    import aiohttp
    import asyncio
    from aioresponses import aioresponses

    @aioresponses()
    def test_request(mocked):
        loop = asyncio.get_event_loop()
        mocked.get('http://example.com', status=200, body='test')
        session = aiohttp.ClientSession()
        resp = loop.run_until_complete(session.get('http://example.com'))

        assert resp.status == 200
        mocked.assert_called_once_with('http://example.com')


for convenience use *payload* argument to mock out json response. Example below.

**as a context manager**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    def test_ctx():
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()
        with aioresponses() as m:
            m.get('http://test.example.com', payload=dict(foo='bar'))

            resp = loop.run_until_complete(session.get('http://test.example.com'))
            data = loop.run_until_complete(resp.json())

            assert dict(foo='bar') == data
            m.assert_called_once_with('http://test.example.com')

**aioresponses allows to mock out any HTTP headers**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    @aioresponses()
    def test_http_headers(m):
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()
        m.post(
            'http://example.com',
            payload=dict(),
            headers=dict(connection='keep-alive'),
        )

        resp = loop.run_until_complete(session.post('http://example.com'))

        # note that we pass 'connection' but get 'Connection' (capitalized)
        # under the neath `multidict` is used to work with HTTP headers
        assert resp.headers['Connection'] == 'keep-alive'
        m.assert_called_once_with('http://example.com', method='POST')

**allows to register different responses for the same url**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    @aioresponses()
    def test_multiple_responses(m):
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()
        m.get('http://example.com', status=500)
        m.get('http://example.com', status=200)

        resp1 = loop.run_until_complete(session.get('http://example.com'))
        resp2 = loop.run_until_complete(session.get('http://example.com'))

        assert resp1.status == 500
        assert resp2.status == 200


**Repeat response for the same url**  

E.g. for cases you want to test retrying mechanisms

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    @aioresponses()
    def test_multiple_responses(m):
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()
        m.get('http://example.com', status=500, repeat=True)
        m.get('http://example.com', status=200)  # will not take effect

        resp1 = loop.run_until_complete(session.get('http://example.com'))
        resp2 = loop.run_until_complete(session.get('http://example.com'))

        assert resp1.status == 500
        assert resp2.status == 500


**match URLs with regular expressions**

.. code:: python

    import asyncio
    import aiohttp
    import re
    from aioresponses import aioresponses

    @aioresponses()
    def test_regexp_example(m):
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()
        pattern = re.compile(r'^http://example\.com/api\?foo=.*$')
        m.get(pattern, status=200)

        resp = loop.run_until_complete(session.get('http://example.com/api?foo=bar'))

        assert resp.status == 200

**allows to make redirects responses**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    @aioresponses()
    def test_redirect_example(m):
        loop = asyncio.get_event_loop()
        session = aiohttp.ClientSession()

        # absolute urls are supported
        m.get(
            'http://example.com/',
            headers={'Location': 'http://another.com/'},
            status=307
        )

        resp = loop.run_until_complete(
            session.get('http://example.com/', allow_redirects=True)
        )
        assert resp.url == 'http://another.com/'

        # and also relative
        m.get(
            'http://example.com/',
            headers={'Location': '/test'},
            status=307
        )
        resp = loop.run_until_complete(
            session.get('http://example.com/', allow_redirects=True)
        )
        assert resp.url == 'http://example.com/test'

**allows to passthrough to a specified list of servers**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import aioresponses

    @aioresponses(passthrough=['http://backend'])
    def test_passthrough(m, test_client):
        session = aiohttp.ClientSession()
        # this will actually perform a request
        resp = loop.run_until_complete(session.get('http://backend/api'))


**aioresponses allows to throw an exception**

.. code:: python

    import asyncio
    from aiohttp import ClientSession
    from aiohttp.http_exceptions import HttpProcessingError
    from aioresponses import aioresponses

    @aioresponses()
    def test_how_to_throw_an_exception(m, test_client):
        loop = asyncio.get_event_loop()
        session = ClientSession()
        m.get('http://example.com/api', exception=HttpProcessingError('test'))

        # calling
        # loop.run_until_complete(session.get('http://example.com/api'))
        # will throw an exception.


**aioresponses allows to use callbacks to provide dynamic responses**

.. code:: python

    import asyncio
    import aiohttp
    from aioresponses import CallbackResult, aioresponses

    def callback(url, **kwargs):
        return CallbackResult(status=418)

    @aioresponses()
    def test_callback(m, test_client):
        loop = asyncio.get_event_loop()
        session = ClientSession()
        m.get('http://example.com', callback=callback)

        resp = loop.run_until_complete(session.get('http://example.com'))

        assert resp.status == 418


**aioresponses can be used in a pytest fixture**

.. code:: python

    import pytest
    from aioresponses import aioresponses

    @pytest.fixture
    def mock_aioresponse():
        with aioresponses() as m:
            yield m


Features
--------
* Easy to mock out HTTP requests made by *aiohttp.ClientSession*


License
-------
* Free software: MIT license

Credits
-------

This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.

.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/pnuckowski/aioresponses",
    "name": "aioresponses",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Pawel Nuckowski",
    "author_email": "p.nuckowski@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/9d/4d/39ad2808e9a32bb5fc8b240ac5d2439c390a667c76c9df1a2b6c57a0e47c/aioresponses-0.7.5.tar.gz",
    "platform": null,
    "description": "===============================\naioresponses\n===============================\n\n.. image:: https://travis-ci.org/pnuckowski/aioresponses.svg?branch=master\n        :target: https://travis-ci.org/pnuckowski/aioresponses\n\n.. image:: https://coveralls.io/repos/github/pnuckowski/aioresponses/badge.svg?branch=master\n        :target: https://coveralls.io/github/pnuckowski/aioresponses?branch=master\n\n.. image:: https://landscape.io/github/pnuckowski/aioresponses/master/landscape.svg?style=flat\n        :target: https://landscape.io/github/pnuckowski/aioresponses/master\n        :alt: Code Health\n\n.. image:: https://pyup.io/repos/github/pnuckowski/aioresponses/shield.svg\n        :target: https://pyup.io/repos/github/pnuckowski/aioresponses/\n        :alt: Updates\n\n.. image:: https://img.shields.io/pypi/v/aioresponses.svg\n        :target: https://pypi.python.org/pypi/aioresponses\n\n.. image:: https://readthedocs.org/projects/aioresponses/badge/?version=latest\n        :target: https://aioresponses.readthedocs.io/en/latest/?badge=latest\n        :alt: Documentation Status\n\n\nAioresponses is a helper to mock/fake web requests in python aiohttp package.\n\nFor *requests* module there are a lot of packages that help us with testing (eg. *httpretty*, *responses*, *requests-mock*).\n\nWhen it comes to testing asynchronous HTTP requests it is a bit harder (at least at the beginning).\nThe purpose of this package is to provide an easy way to test asynchronous HTTP requests.\n\nInstalling\n----------\n\n.. code:: bash\n\n    $ pip install aioresponses\n\nSupported versions\n------------------\n- Python 3.7+\n- aiohttp>=3.3.0,<4.0.0\n\nUsage\n--------\n\nTo mock out HTTP request use *aioresponses* as a method decorator or as a context manager.\n\nResponse *status* code, *body*, *payload* (for json response) and *headers* can be mocked.\n\nSupported HTTP methods: **GET**, **POST**, **PUT**, **PATCH**, **DELETE** and **OPTIONS**.\n\n.. code:: python\n\n    import aiohttp\n    import asyncio\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_request(mocked):\n        loop = asyncio.get_event_loop()\n        mocked.get('http://example.com', status=200, body='test')\n        session = aiohttp.ClientSession()\n        resp = loop.run_until_complete(session.get('http://example.com'))\n\n        assert resp.status == 200\n        mocked.assert_called_once_with('http://example.com')\n\n\nfor convenience use *payload* argument to mock out json response. Example below.\n\n**as a context manager**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    def test_ctx():\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n        with aioresponses() as m:\n            m.get('http://test.example.com', payload=dict(foo='bar'))\n\n            resp = loop.run_until_complete(session.get('http://test.example.com'))\n            data = loop.run_until_complete(resp.json())\n\n            assert dict(foo='bar') == data\n            m.assert_called_once_with('http://test.example.com')\n\n**aioresponses allows to mock out any HTTP headers**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_http_headers(m):\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n        m.post(\n            'http://example.com',\n            payload=dict(),\n            headers=dict(connection='keep-alive'),\n        )\n\n        resp = loop.run_until_complete(session.post('http://example.com'))\n\n        # note that we pass 'connection' but get 'Connection' (capitalized)\n        # under the neath `multidict` is used to work with HTTP headers\n        assert resp.headers['Connection'] == 'keep-alive'\n        m.assert_called_once_with('http://example.com', method='POST')\n\n**allows to register different responses for the same url**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_multiple_responses(m):\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n        m.get('http://example.com', status=500)\n        m.get('http://example.com', status=200)\n\n        resp1 = loop.run_until_complete(session.get('http://example.com'))\n        resp2 = loop.run_until_complete(session.get('http://example.com'))\n\n        assert resp1.status == 500\n        assert resp2.status == 200\n\n\n**Repeat response for the same url**  \n\nE.g. for cases you want to test retrying mechanisms\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_multiple_responses(m):\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n        m.get('http://example.com', status=500, repeat=True)\n        m.get('http://example.com', status=200)  # will not take effect\n\n        resp1 = loop.run_until_complete(session.get('http://example.com'))\n        resp2 = loop.run_until_complete(session.get('http://example.com'))\n\n        assert resp1.status == 500\n        assert resp2.status == 500\n\n\n**match URLs with regular expressions**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    import re\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_regexp_example(m):\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n        pattern = re.compile(r'^http://example\\.com/api\\?foo=.*$')\n        m.get(pattern, status=200)\n\n        resp = loop.run_until_complete(session.get('http://example.com/api?foo=bar'))\n\n        assert resp.status == 200\n\n**allows to make redirects responses**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_redirect_example(m):\n        loop = asyncio.get_event_loop()\n        session = aiohttp.ClientSession()\n\n        # absolute urls are supported\n        m.get(\n            'http://example.com/',\n            headers={'Location': 'http://another.com/'},\n            status=307\n        )\n\n        resp = loop.run_until_complete(\n            session.get('http://example.com/', allow_redirects=True)\n        )\n        assert resp.url == 'http://another.com/'\n\n        # and also relative\n        m.get(\n            'http://example.com/',\n            headers={'Location': '/test'},\n            status=307\n        )\n        resp = loop.run_until_complete(\n            session.get('http://example.com/', allow_redirects=True)\n        )\n        assert resp.url == 'http://example.com/test'\n\n**allows to passthrough to a specified list of servers**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import aioresponses\n\n    @aioresponses(passthrough=['http://backend'])\n    def test_passthrough(m, test_client):\n        session = aiohttp.ClientSession()\n        # this will actually perform a request\n        resp = loop.run_until_complete(session.get('http://backend/api'))\n\n\n**aioresponses allows to throw an exception**\n\n.. code:: python\n\n    import asyncio\n    from aiohttp import ClientSession\n    from aiohttp.http_exceptions import HttpProcessingError\n    from aioresponses import aioresponses\n\n    @aioresponses()\n    def test_how_to_throw_an_exception(m, test_client):\n        loop = asyncio.get_event_loop()\n        session = ClientSession()\n        m.get('http://example.com/api', exception=HttpProcessingError('test'))\n\n        # calling\n        # loop.run_until_complete(session.get('http://example.com/api'))\n        # will throw an exception.\n\n\n**aioresponses allows to use callbacks to provide dynamic responses**\n\n.. code:: python\n\n    import asyncio\n    import aiohttp\n    from aioresponses import CallbackResult, aioresponses\n\n    def callback(url, **kwargs):\n        return CallbackResult(status=418)\n\n    @aioresponses()\n    def test_callback(m, test_client):\n        loop = asyncio.get_event_loop()\n        session = ClientSession()\n        m.get('http://example.com', callback=callback)\n\n        resp = loop.run_until_complete(session.get('http://example.com'))\n\n        assert resp.status == 418\n\n\n**aioresponses can be used in a pytest fixture**\n\n.. code:: python\n\n    import pytest\n    from aioresponses import aioresponses\n\n    @pytest.fixture\n    def mock_aioresponse():\n        with aioresponses() as m:\n            yield m\n\n\nFeatures\n--------\n* Easy to mock out HTTP requests made by *aiohttp.ClientSession*\n\n\nLicense\n-------\n* Free software: MIT license\n\nCredits\n-------\n\nThis package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.\n\n.. _Cookiecutter: https://github.com/audreyr/cookiecutter\n.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage\n\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Mock out requests made by ClientSession from aiohttp package",
    "version": "0.7.5",
    "project_urls": {
        "Homepage": "https://github.com/pnuckowski/aioresponses"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "65e6e0bfedfb71372017f07f2d30709b125033fa517cbd16f766214cfbfbe4a3",
                "md5": "7fdb46ab1f6d98ad9422d97f86b10481",
                "sha256": "0af13b077bde04ae965bc21981a1c6afd7dd17b861150d858de477d1c39c26a6"
            },
            "downloads": -1,
            "filename": "aioresponses-0.7.5-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "7fdb46ab1f6d98ad9422d97f86b10481",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 11839,
            "upload_time": "2023-11-13T18:05:52",
            "upload_time_iso_8601": "2023-11-13T18:05:52.303602Z",
            "url": "https://files.pythonhosted.org/packages/65/e6/e0bfedfb71372017f07f2d30709b125033fa517cbd16f766214cfbfbe4a3/aioresponses-0.7.5-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "9d4d39ad2808e9a32bb5fc8b240ac5d2439c390a667c76c9df1a2b6c57a0e47c",
                "md5": "d5e6f03a0c9ac0083a47d48340bf7822",
                "sha256": "794b3e04837a683fd2c0c099bdf77f8d7ecdd284bc2c15203003518bf5cb8da8"
            },
            "downloads": -1,
            "filename": "aioresponses-0.7.5.tar.gz",
            "has_sig": false,
            "md5_digest": "d5e6f03a0c9ac0083a47d48340bf7822",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 35676,
            "upload_time": "2023-11-13T18:05:58",
            "upload_time_iso_8601": "2023-11-13T18:05:58.382587Z",
            "url": "https://files.pythonhosted.org/packages/9d/4d/39ad2808e9a32bb5fc8b240ac5d2439c390a667c76c9df1a2b6c57a0e47c/aioresponses-0.7.5.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-13 18:05:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "pnuckowski",
    "github_project": "aioresponses",
    "travis_ci": false,
    "coveralls": true,
    "github_actions": true,
    "landscape": true,
    "requirements": [],
    "tox": true,
    "lcname": "aioresponses"
}
        
Elapsed time: 0.14887s