Docs on datasette.client for tests, closes #1830

Also covers ds.client.actor_cookie() helper
This commit is contained in:
Simon Willison 2024-01-10 13:04:34 -08:00
commit 7506a89be0
2 changed files with 67 additions and 2 deletions

View file

@ -82,6 +82,34 @@ This method registers any :ref:`plugin_hook_startup` or :ref:`plugin_hook_prepar
If you are using ``await datasette.client.get()`` and similar methods then you don't need to worry about this - Datasette automatically calls ``invoke_startup()`` the first time it handles a request.
.. _testing_datasette_client:
Using datasette.client in tests
-------------------------------
The :ref:`internals_datasette_client` mechanism is designed for use in tests. It provides access to a pre-configured `HTTPX async client <https://www.python-httpx.org/async/>`__ instance that can make GET, POST and other HTTP requests against a Datasette instance from inside a test.
I simple test looks like this:
.. literalinclude:: ../tests/test_docs.py
:language: python
:start-after: # -- start test_homepage --
:end-before: # -- end test_homepage --
Or for a JSON API:
.. literalinclude:: ../tests/test_docs.py
:language: python
:start-after: # -- start test_actor_is_null --
:end-before: # -- end test_actor_is_null --
To make requests as an authenticated actor, create a signed ``ds_cookie`` using the ``datasette.client.actor_cookie()`` helper function and pass it in ``cookies=`` like this:
.. literalinclude:: ../tests/test_docs.py
:language: python
:start-after: # -- start test_signed_cookie_actor --
:end-before: # -- end test_signed_cookie_actor --
.. _testing_plugins_pdb:
Using pdb for errors thrown inside Datasette