From 452ffc7676f451ed22f4f7a2af07d65a09389233 Mon Sep 17 00:00:00 2001 From: Robbe Sneyders Date: Sun, 29 Oct 2023 09:40:43 +0100 Subject: [PATCH] Add testing documentation (#1760) Contributes towards https://github.com/spec-first/connexion/issues/1531 --- connexion/apps/abstract.py | 3 ++- docs/testing.rst | 50 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) create mode 100644 docs/testing.rst diff --git a/connexion/apps/abstract.py b/connexion/apps/abstract.py index c8912be1e..75daa1cc2 100644 --- a/connexion/apps/abstract.py +++ b/connexion/apps/abstract.py @@ -267,7 +267,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): diff --git a/docs/testing.rst b/docs/testing.rst new file mode 100644 index 000000000..5166b2e2f --- /dev/null +++ b/docs/testing.rst @@ -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.