literalinclude with markers for showing code in documentation#
I wanted to include some example Python tests in the Datasette documentation - but since they were tests, I also wanted to execute them as part of my test suite to make sure they worked correctly.
I solved this with the Sphinx literalinclude directive.
Here’s what I put in my docs/testing_plugins.rst#L92-L111 file:
1A simple test looks like this:2
3.. literalinclude:: ../tests/test_docs.py4 :language: python5 :start-after: # -- start test_homepage --6 :end-before: # -- end test_homepage --7
8Or for a JSON API:9
10.. literalinclude:: ../tests/test_docs.py11 :language: python12 :start-after: # -- start test_actor_is_null --13 :end-before: # -- end test_actor_is_null --14
15To 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:16
17.. literalinclude:: ../tests/test_docs.py18 :language: python19 :start-after: # -- start test_signed_cookie_actor --20 :end-before: # -- end test_signed_cookie_actor --
Note that the paths like ../tests/test_docs.py
are relative to the root docs/
folder, which is a sibling of tests/
.
Then in tests/test_docs.py:
1# fmt: off2
3# -- start test_homepage --4@pytest.mark.asyncio5async def test_homepage():6 ds = Datasette(memory=True)7 response = await ds.client.get("/")8 html = response.text9 assert "<h1>" in html10# -- end test_homepage --11
12# -- start test_actor_is_null --13@pytest.mark.asyncio14async def test_actor_is_null():15 ds = Datasette(memory=True)16 response = await ds.client.get("/-/actor.json")17 assert response.json() == {"actor": None}18# -- end test_actor_is_null --19
20# -- start test_signed_cookie_actor --21@pytest.mark.asyncio22async def test_signed_cookie_actor():23 ds = Datasette(memory=True)24 cookies = {"ds_actor": ds.client.actor_cookie({"id": "root"})}25 response = await ds.client.get("/-/actor.json", cookies=cookies)26 assert response.json() == {"actor": {"id": "root"}}27# -- end test_signed_cookie_actor --
The rendered documentation can be seen here.
The # fmt: off
line at the start is an instruction to Black to ignore that section of the file. Without that, running Black would insist on adding newlines before the closing # -- end
comments, which would show up as blank space in the documentation.