| 1 |
from datasette.cli import cli, serve |
| 2 |
from datasette.plugins import pm |
| 3 |
from click.testing import CliRunner |
| 4 |
import textwrap |
| 5 |
import json |
| 6 |
|
| 7 |
|
| 8 |
def test_serve_with_get(tmp_path_factory): |
| 9 |
plugins_dir = tmp_path_factory.mktemp("plugins_for_serve_with_get") |
| 10 |
(plugins_dir / "init_for_serve_with_get.py").write_text( |
| 11 |
textwrap.dedent( |
| 12 |
""" |
| 13 |
from datasette import hookimpl |
| 14 |
|
| 15 |
@hookimpl |
| 16 |
def startup(datasette): |
| 17 |
with open("{}", "w") as fp: |
| 18 |
fp.write("hello") |
| 19 |
""".format( |
| 20 |
str(plugins_dir / "hello.txt") |
| 21 |
), |
| 22 |
), |
| 23 |
"utf-8", |
| 24 |
) |
| 25 |
runner = CliRunner() |
| 26 |
result = runner.invoke( |
| 27 |
cli, |
| 28 |
[ |
| 29 |
"serve", |
| 30 |
"--memory", |
| 31 |
"--plugins-dir", |
| 32 |
str(plugins_dir), |
| 33 |
"--get", |
| 34 |
"/_memory.json?sql=select+sqlite_version()", |
| 35 |
], |
| 36 |
) |
| 37 |
assert 0 == result.exit_code, result.output |
| 38 |
assert { |
| 39 |
"database": "_memory", |
| 40 |
"truncated": False, |
| 41 |
"columns": ["sqlite_version()"], |
| 42 |
}.items() <= json.loads(result.output).items() |
| 43 |
|
| 44 |
# The plugin should have created hello.txt |
| 45 |
assert (plugins_dir / "hello.txt").read_text() == "hello" |
| 46 |
|
| 47 |
# Annoyingly that new test plugin stays resident - we need |
| 48 |
# to manually unregister it to avoid conflict with other tests |
| 49 |
to_unregister = [ |
| 50 |
p for p in pm.get_plugins() if p.__name__ == "init_for_serve_with_get.py" |
| 51 |
][0] |
| 52 |
pm.unregister(to_unregister) |
| 53 |
|
| 54 |
|
| 55 |
def test_serve_with_get_exit_code_for_error(tmp_path_factory): |
| 56 |
runner = CliRunner() |
| 57 |
result = runner.invoke( |
| 58 |
cli, |
| 59 |
[ |
| 60 |
"serve", |
| 61 |
"--memory", |
| 62 |
"--get", |
| 63 |
"/this-is-404", |
| 64 |
], |
| 65 |
catch_exceptions=False, |
| 66 |
) |
| 67 |
assert result.exit_code == 1 |
| 68 |
assert "404" in result.output |