Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add testing documentation #1760

Merged
merged 1 commit into from
Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion connexion/apps/abstract.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,8 @@ def add_error_handler(
"""

def test_client(self, **kwargs):
"""Creates a test client for this application."""
"""Creates a test client for this application. The keywords arguments passed in are
passed to the ``StarletteClient``."""
return TestClient(self, **kwargs)

def run(self, import_string: str = None, **kwargs):
Expand Down
50 changes: 50 additions & 0 deletions docs/testing.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
Testing
=======

test_client
-----------

Connexion exposes a ``test_client`` which you can use to make requests against your
Connexion application during tests.

.. code-block:: python

def test_homepage():
app = ... # Set up app
kwarg = {...}
with app.test_client(**kwargs) as client:
response = client.get("/")
assert response.status_code == 200


The passed in keywords used to create a `Starlette` ``TestClient`` which is then returned.

For more information, please check the `Starlette documentation`_.

.. _Starlette documentation: https://www.starlette.io/testclient/

TestContext
-----------

To have access to the :doc:`context` variables during tests, you can use the :class:`.TestContext`
provided by Connexion.

.. code-block:: python

from unittest.mock import MagicMock

from connexion.context import operation
from connexion.testing import TestContext


def get_method():
"""Function called within TestContext you can access the context variables here."""
return operation.method

def test():
operation = MagicMock(name="operation")
operation.method = "post"
with TestContext(operation=operation):
assert get_method() == "post

If you don't pass in a certain context variable, the `TestContext` will generate a dummy one.
Loading