datasette --get --token option, closes #1946, refs #1855

pull/1823/merge
Simon Willison 2022-12-12 20:36:42 -08:00
rodzic 14f1cc4984
commit c13dada2f8
3 zmienionych plików z 43 dodań i 1 usunięć

Wyświetl plik

@ -435,6 +435,10 @@ def uninstall(packages, yes):
"--get",
help="Run an HTTP GET request against this path, print results and exit",
)
@click.option(
"--token",
help="API token to send with --get requests",
)
@click.option("--version-note", help="Additional note to show on /-/versions")
@click.option("--help-settings", is_flag=True, help="Show available settings")
@click.option("--pdb", is_flag=True, help="Launch debugger on any errors")
@ -488,6 +492,7 @@ def serve(
secret,
root,
get,
token,
version_note,
help_settings,
pdb,
@ -594,9 +599,15 @@ def serve(
# Run async soundness checks - but only if we're not under pytest
asyncio.get_event_loop().run_until_complete(check_databases(ds))
if token and not get:
raise click.ClickException("--token can only be used with --get")
if get:
client = TestClient(ds)
response = client.get(get)
headers = {}
if token:
headers["Authorization"] = "Bearer {}".format(token)
response = client.get(get, headers=headers)
click.echo(response.text)
exit_code = 0 if response.status == 200 else 1
sys.exit(exit_code)

Wyświetl plik

@ -122,6 +122,7 @@ Once started you can access it at ``http://localhost:8001``
the root user
--get TEXT Run an HTTP GET request against this path,
print results and exit
--token TEXT API token to send with --get requests
--version-note TEXT Additional note to show on /-/versions
--help-settings Show available settings
--pdb Launch debugger on any errors
@ -189,6 +190,8 @@ For example::
}
}
You can use the ``--token TOKEN`` option to send an :ref:`API token <CreateTokenView>` with the simulated request.
The exit code will be 0 if the request succeeds and 1 if the request produced an HTTP status code other than 200 - e.g. a 404 or 500 error.
This lets you use ``datasette --get /`` to run tests against a Datasette application in a continuous integration environment such as GitHub Actions.

Wyświetl plik

@ -52,6 +52,34 @@ def test_serve_with_get(tmp_path_factory):
pm.unregister(to_unregister)
def test_serve_with_get_and_token():
runner = CliRunner()
result1 = runner.invoke(
cli,
[
"create-token",
"--secret",
"sekrit",
"root",
],
)
token = result1.output.strip()
result2 = runner.invoke(
cli,
[
"serve",
"--secret",
"sekrit",
"--get",
"/-/actor.json",
"--token",
token,
],
)
assert 0 == result2.exit_code, result2.output
assert json.loads(result2.output) == {"actor": {"id": "root", "token": "dstok"}}
def test_serve_with_get_exit_code_for_error(tmp_path_factory):
runner = CliRunner()
result = runner.invoke(