Skip to content

Commit

Permalink
Docs on temporary plugins in fixtures, closes #2234
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw committed Jan 12, 2024
1 parent a25bf6b commit 7a5adb5
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
16 changes: 16 additions & 0 deletions docs/testing_plugins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,19 @@ When writing tests for plugins you may find it useful to register a test plugin
assert response.status_code == 500
finally:
pm.unregister(name="undo")
To reuse the same temporary plugin in multiple tests, you can register it inside a fixture in your ``conftest.py`` file like this:

.. literalinclude:: ../tests/test_docs_plugins.py
:language: python
:start-after: # -- start datasette_with_plugin_fixture --
:end-before: # -- end datasette_with_plugin_fixture --

Note the ``yield`` statement here - this ensures that the ``finally:`` block that unregisters the plugin is executed only after the test function itself has completed.

Then in a test:

.. literalinclude:: ../tests/test_docs_plugins.py
:language: python
:start-after: # -- start datasette_with_plugin_test --
:end-before: # -- end datasette_with_plugin_test --
34 changes: 34 additions & 0 deletions tests/test_docs_plugins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# fmt: off
# -- start datasette_with_plugin_fixture --
from datasette import hookimpl
from datasette.app import Datasette
from datasette.plugins import pm
import pytest
import pytest_asyncio


@pytest_asyncio.fixture
async def datasette_with_plugin():
class TestPlugin:
__name__ = "TestPlugin"

@hookimpl
def register_routes(self):
return [
(r"^/error$", lambda: 1 / 0),
]

pm.register(TestPlugin(), name="undo")
try:
yield Datasette()
finally:
pm.unregister(name="undo")
# -- end datasette_with_plugin_fixture --


# -- start datasette_with_plugin_test --
@pytest.mark.asyncio
async def test_error(datasette_with_plugin):
response = await datasette_with_plugin.client.get("/error")
assert response.status_code == 500
# -- end datasette_with_plugin_test --

0 comments on commit 7a5adb5

Please sign in to comment.