diff --git a/datasette/cli.py b/datasette/cli.py index 1b5d78e3..e8595321 100644 --- a/datasette/cli.py +++ b/datasette/cli.py @@ -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) diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index 0b39126d..80f31924 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -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 ` 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. diff --git a/tests/test_cli_serve_get.py b/tests/test_cli_serve_get.py index 90fbfe3b..ac44e1e2 100644 --- a/tests/test_cli_serve_get.py +++ b/tests/test_cli_serve_get.py @@ -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(