Debian Codegraph @

docs/testing_plugins.rst

raw
1 .. _testing_plugins:
2
3 Testing plugins
4 ===============
5
6 We recommend using `pytest <https://docs.pytest.org/>`__ to write automated tests for your plugins.
7
8 If you use the template described in :ref:`writing_plugins_cookiecutter` your plugin will start with a single test in your ``tests/`` directory that looks like this:
9
10 .. code-block:: python
11
12 from datasette.app import Datasette
13 import pytest
14
15
16 @pytest.mark.asyncio
17 async def test_plugin_is_installed():
18 datasette = Datasette(memory=True)
19 response = await datasette.client.get("/-/plugins.json")
20 assert response.status_code == 200
21 installed_plugins = {p["name"] for p in response.json()}
22 assert (
23 "datasette-plugin-template-demo"
24 in installed_plugins
25 )
26
27
28 This test uses the :ref:`internals_datasette_client` object to exercise a test instance of Datasette. ``datasette.client`` is a wrapper around the `HTTPX <https://www.python-httpx.org/>`__ Python library which can imitate HTTP requests using ASGI. This is the recommended way to write tests against a Datasette instance.
29
30 This test also uses the `pytest-asyncio <https://pypi.org/project/pytest-asyncio/>`__ package to add support for ``async def`` test functions running under pytest.
31
32 You can install these packages like so::
33
34 pip install pytest pytest-asyncio
35
36 If you are building an installable package you can add them as test dependencies to your ``setup.py`` module like this:
37
38 .. code-block:: python
39
40 setup(
41 name="datasette-my-plugin",
42 # ...
43 extras_require={"test": ["pytest", "pytest-asyncio"]},
44 tests_require=["datasette-my-plugin[test]"],
45 )
46
47 You can then install the test dependencies like so::
48
49 pip install -e '.[test]'
50
51 Then run the tests using pytest like so::
52
53 pytest
54
55 .. _testing_plugins_datasette_test_instance:
56
57 Setting up a Datasette test instance
58 ------------------------------------
59
60 The above example shows the easiest way to start writing tests against a Datasette instance:
61
62 .. code-block:: python
63
64 from datasette.app import Datasette
65 import pytest
66
67
68 @pytest.mark.asyncio
69 async def test_plugin_is_installed():
70 datasette = Datasette(memory=True)
71 response = await datasette.client.get("/-/plugins.json")
72 assert response.status_code == 200
73
74 Creating a ``Datasette()`` instance like this as useful shortcut in tests, but there is one detail you need to be aware of. It's important to ensure that the async method ``.invoke_startup()`` is called on that instance. You can do that like this:
75
76 .. code-block:: python
77
78 datasette = Datasette(memory=True)
79 await datasette.invoke_startup()
80
81 This method registers any :ref:`plugin_hook_startup` or :ref:`plugin_hook_prepare_jinja2_environment` plugins that might themselves need to make async calls.
82
83 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.
84
85 .. _testing_plugins_pdb:
86
87 Using pdb for errors thrown inside Datasette
88 --------------------------------------------
89
90 If an exception occurs within Datasette itself during a test, the response returned to your plugin will have a ``response.status_code`` value of 500.
91
92 You can add ``pdb=True`` to the ``Datasette`` constructor to drop into a Python debugger session inside your test run instead of getting back a 500 response code. This is equivalent to running the ``datasette`` command-line tool with the ``--pdb`` option.
93
94 Here's what that looks like in a test function:
95
96 .. code-block:: python
97
98 def test_that_opens_the_debugger_or_errors():
99 ds = Datasette([db_path], pdb=True)
100 response = await ds.client.get("/")
101
102 If you use this pattern you will need to run ``pytest`` with the ``-s`` option to avoid capturing stdin/stdout in order to interact with the debugger prompt.
103
104 .. _testing_plugins_fixtures:
105
106 Using pytest fixtures
107 ---------------------
108
109 `Pytest fixtures <https://docs.pytest.org/en/stable/fixture.html>`__ can be used to create initial testable objects which can then be used by multiple tests.
110
111 A common pattern for Datasette plugins is to create a fixture which sets up a temporary test database and wraps it in a Datasette instance.
112
113 Here's an example that uses the `sqlite-utils library <https://sqlite-utils.datasette.io/en/stable/python-api.html>`__ to populate a temporary test database. It also sets the title of that table using a simulated ``metadata.json`` configuration:
114
115 .. code-block:: python
116
117 from datasette.app import Datasette
118 import pytest
119 import sqlite_utils
120
121
122 @pytest.fixture(scope="session")
123 def datasette(tmp_path_factory):
124 db_directory = tmp_path_factory.mktemp("dbs")
125 db_path = db_directory / "test.db"
126 db = sqlite_utils.Database(db_path)
127 db["dogs"].insert_all(
128 [
129 {"id": 1, "name": "Cleo", "age": 5},
130 {"id": 2, "name": "Pancakes", "age": 4},
131 ],
132 pk="id",
133 )
134 datasette = Datasette(
135 [db_path],
136 metadata={
137 "databases": {
138 "test": {
139 "tables": {
140 "dogs": {"title": "Some dogs"}
141 }
142 }
143 }
144 },
145 )
146 return datasette
147
148
149 @pytest.mark.asyncio
150 async def test_example_table_json(datasette):
151 response = await datasette.client.get(
152 "/test/dogs.json?_shape=array"
153 )
154 assert response.status_code == 200
155 assert response.json() == [
156 {"id": 1, "name": "Cleo", "age": 5},
157 {"id": 2, "name": "Pancakes", "age": 4},
158 ]
159
160
161 @pytest.mark.asyncio
162 async def test_example_table_html(datasette):
163 response = await datasette.client.get("/test/dogs")
164 assert ">Some dogs</h1>" in response.text
165
166 Here the ``datasette()`` function defines the fixture, which is than automatically passed to the two test functions based on pytest automatically matching their ``datasette`` function parameters.
167
168 The ``@pytest.fixture(scope="session")`` line here ensures the fixture is reused for the full ``pytest`` execution session. This means that the temporary database file will be created once and reused for each test.
169
170 If you want to create that test database repeatedly for every individual test function, write the fixture function like this instead. You may want to do this if your plugin modifies the database contents in some way:
171
172 .. code-block:: python
173
174 @pytest.fixture
175 def datasette(tmp_path_factory):
176 # This fixture will be executed repeatedly for every test
177 ...
178
179 .. _testing_plugins_pytest_httpx:
180
181 Testing outbound HTTP calls with pytest-httpx
182 ---------------------------------------------
183
184 If your plugin makes outbound HTTP calls - for example datasette-auth-github or datasette-import-table - you may need to mock those HTTP requests in your tests.
185
186 The `pytest-httpx <https://pypi.org/project/pytest-httpx/>`__ package is a useful library for mocking calls. It can be tricky to use with Datasette though since it mocks all HTTPX requests, and Datasette's own testing mechanism uses HTTPX internally.
187
188 To avoid breaking your tests, you can return ``["localhost"]`` from the ``non_mocked_hosts()`` fixture.
189
190 As an example, here's a very simple plugin which executes an HTTP response and returns the resulting content:
191
192 .. code-block:: python
193
194 from datasette import hookimpl
195 from datasette.utils.asgi import Response
196 import httpx
197
198
199 @hookimpl
200 def register_routes():
201 return [
202 (r"^/-/fetch-url$", fetch_url),
203 ]
204
205
206 async def fetch_url(datasette, request):
207 if request.method == "GET":
208 return Response.html(
209 """
210 <form action="/-/fetch-url" method="post">
211 <input type="hidden" name="csrftoken" value="{}">
212 <input name="url"><input type="submit">
213 </form>""".format(
214 request.scope["csrftoken"]()
215 )
216 )
217 vars = await request.post_vars()
218 url = vars["url"]
219 return Response.text(httpx.get(url).text)
220
221 Here's a test for that plugin that mocks the HTTPX outbound request:
222
223 .. code-block:: python
224
225 from datasette.app import Datasette
226 import pytest
227
228
229 @pytest.fixture
230 def non_mocked_hosts():
231 # This ensures httpx-mock will not affect Datasette's own
232 # httpx calls made in the tests by datasette.client:
233 return ["localhost"]
234
235
236 async def test_outbound_http_call(httpx_mock):
237 httpx_mock.add_response(
238 url="https://www.example.com/",
239 text="Hello world",
240 )
241 datasette = Datasette([], memory=True)
242 response = await datasette.client.post(
243 "/-/fetch-url",
244 data={"url": "https://www.example.com/"},
245 )
246 assert response.text == "Hello world"
247
248 outbound_request = httpx_mock.get_request()
249 assert (
250 outbound_request.url == "https://www.example.com/"
251 )
252
253 .. _testing_plugins_register_in_test:
254
255 Registering a plugin for the duration of a test
256 -----------------------------------------------
257
258 When writing tests for plugins you may find it useful to register a test plugin just for the duration of a single test. You can do this using ``pm.register()`` and ``pm.unregister()`` like this:
259
260 .. code-block:: python
261
262 from datasette import hookimpl
263 from datasette.app import Datasette
264 from datasette.plugins import pm
265 import pytest
266
267
268 @pytest.mark.asyncio
269 async def test_using_test_plugin():
270 class TestPlugin:
271 __name__ = "TestPlugin"
272
273 # Use hookimpl and method names to register hooks
274 @hookimpl
275 def register_routes(self):
276 return [
277 (r"^/error$", lambda: 1 / 0),
278 ]
279
280 pm.register(TestPlugin(), name="undo")
281 try:
282 # The test implementation goes here
283 datasette = Datasette()
284 response = await datasette.client.get("/error")
285 assert response.status_code == 500
286 finally:
287 pm.unregister(name="undo")