| 1 |
from bs4 import BeautifulSoup as Soup |
| 2 |
from .fixtures import ( |
| 3 |
app_client, |
| 4 |
make_app_client, |
| 5 |
TABLES, |
| 6 |
TEMP_PLUGIN_SECRET_FILE, |
| 7 |
TestClient as _TestClient, |
| 8 |
) # noqa |
| 9 |
from click.testing import CliRunner |
| 10 |
from datasette.app import Datasette |
| 11 |
from datasette import cli, hookimpl |
| 12 |
from datasette.filters import FilterArguments |
| 13 |
from datasette.plugins import get_plugins, DEFAULT_PLUGINS, pm |
| 14 |
from datasette.utils.sqlite import sqlite3 |
| 15 |
from datasette.utils import CustomRow |
| 16 |
from jinja2.environment import Template |
| 17 |
import base64 |
| 18 |
import importlib |
| 19 |
import json |
| 20 |
import os |
| 21 |
import pathlib |
| 22 |
import re |
| 23 |
import textwrap |
| 24 |
import pytest |
| 25 |
import urllib |
| 26 |
|
| 27 |
at_memory_re = re.compile(r" at 0x\w+") |
| 28 |
|
| 29 |
|
| 30 |
@pytest.mark.parametrize( |
| 31 |
"plugin_hook", [name for name in dir(pm.hook) if not name.startswith("_")] |
| 32 |
) |
| 33 |
def test_plugin_hooks_have_tests(plugin_hook): |
| 34 |
"""Every plugin hook should be referenced in this test module""" |
| 35 |
tests_in_this_module = [t for t in globals().keys() if t.startswith("test_hook_")] |
| 36 |
ok = False |
| 37 |
for test in tests_in_this_module: |
| 38 |
if plugin_hook in test: |
| 39 |
ok = True |
| 40 |
assert ok, f"Plugin hook is missing tests: {plugin_hook}" |
| 41 |
|
| 42 |
|
| 43 |
def test_hook_plugins_dir_plugin_prepare_connection(app_client): |
| 44 |
response = app_client.get( |
| 45 |
"/fixtures.json?sql=select+convert_units(100%2C+'m'%2C+'ft')" |
| 46 |
) |
| 47 |
assert pytest.approx(328.0839) == response.json["rows"][0][0] |
| 48 |
|
| 49 |
|
| 50 |
def test_hook_plugin_prepare_connection_arguments(app_client): |
| 51 |
response = app_client.get( |
| 52 |
"/fixtures.json?sql=select+prepare_connection_args()&_shape=arrayfirst" |
| 53 |
) |
| 54 |
assert [ |
| 55 |
"database=fixtures, datasette.plugin_config(\"name-of-plugin\")={'depth': 'root'}" |
| 56 |
] == response.json |
| 57 |
|
| 58 |
|
| 59 |
@pytest.mark.parametrize( |
| 60 |
"path,expected_decoded_object", |
| 61 |
[ |
| 62 |
( |
| 63 |
"/", |
| 64 |
{ |
| 65 |
"template": "index.html", |
| 66 |
"database": None, |
| 67 |
"table": None, |
| 68 |
"view_name": "index", |
| 69 |
"request_path": "/", |
| 70 |
"added": 15, |
| 71 |
"columns": None, |
| 72 |
}, |
| 73 |
), |
| 74 |
( |
| 75 |
"/fixtures", |
| 76 |
{ |
| 77 |
"template": "database.html", |
| 78 |
"database": "fixtures", |
| 79 |
"table": None, |
| 80 |
"view_name": "database", |
| 81 |
"request_path": "/fixtures", |
| 82 |
"added": 15, |
| 83 |
"columns": None, |
| 84 |
}, |
| 85 |
), |
| 86 |
( |
| 87 |
"/fixtures/sortable", |
| 88 |
{ |
| 89 |
"template": "table.html", |
| 90 |
"database": "fixtures", |
| 91 |
"table": "sortable", |
| 92 |
"view_name": "table", |
| 93 |
"request_path": "/fixtures/sortable", |
| 94 |
"added": 15, |
| 95 |
"columns": [ |
| 96 |
"pk1", |
| 97 |
"pk2", |
| 98 |
"content", |
| 99 |
"sortable", |
| 100 |
"sortable_with_nulls", |
| 101 |
"sortable_with_nulls_2", |
| 102 |
"text", |
| 103 |
], |
| 104 |
}, |
| 105 |
), |
| 106 |
], |
| 107 |
) |
| 108 |
def test_hook_extra_css_urls(app_client, path, expected_decoded_object): |
| 109 |
response = app_client.get(path) |
| 110 |
assert response.status == 200 |
| 111 |
links = Soup(response.body, "html.parser").find_all("link") |
| 112 |
special_href = [ |
| 113 |
l for l in links if l.attrs["href"].endswith("/extra-css-urls-demo.css") |
| 114 |
][0]["href"] |
| 115 |
# This link has a base64-encoded JSON blob in it |
| 116 |
encoded = special_href.split("/")[3] |
| 117 |
assert expected_decoded_object == json.loads( |
| 118 |
base64.b64decode(encoded).decode("utf8") |
| 119 |
) |
| 120 |
|
| 121 |
|
| 122 |
def test_hook_extra_js_urls(app_client): |
| 123 |
response = app_client.get("/") |
| 124 |
scripts = Soup(response.body, "html.parser").find_all("script") |
| 125 |
script_attrs = [s.attrs for s in scripts] |
| 126 |
for attrs in [ |
| 127 |
{ |
| 128 |
"integrity": "SRIHASH", |
| 129 |
"crossorigin": "anonymous", |
| 130 |
"src": "https://plugin-example.datasette.io/jquery.js", |
| 131 |
}, |
| 132 |
{ |
| 133 |
"src": "https://plugin-example.datasette.io/plugin.module.js", |
| 134 |
"type": "module", |
| 135 |
}, |
| 136 |
]: |
| 137 |
assert any(s == attrs for s in script_attrs), "Expected: {}".format(attrs) |
| 138 |
|
| 139 |
|
| 140 |
def test_plugins_with_duplicate_js_urls(app_client): |
| 141 |
# If two plugins both require jQuery, jQuery should be loaded only once |
| 142 |
response = app_client.get("/fixtures") |
| 143 |
# This test is a little tricky, as if the user has any other plugins in |
| 144 |
# their current virtual environment those may affect what comes back too. |
| 145 |
# What matters is that https://plugin-example.datasette.io/jquery.js is only there once |
| 146 |
# and it comes before plugin1.js and plugin2.js which could be in either |
| 147 |
# order |
| 148 |
scripts = Soup(response.body, "html.parser").find_all("script") |
| 149 |
srcs = [s["src"] for s in scripts if s.get("src")] |
| 150 |
# No duplicates allowed: |
| 151 |
assert len(srcs) == len(set(srcs)) |
| 152 |
# jquery.js loaded once: |
| 153 |
assert 1 == srcs.count("https://plugin-example.datasette.io/jquery.js") |
| 154 |
# plugin1.js and plugin2.js are both there: |
| 155 |
assert 1 == srcs.count("https://plugin-example.datasette.io/plugin1.js") |
| 156 |
assert 1 == srcs.count("https://plugin-example.datasette.io/plugin2.js") |
| 157 |
# jquery comes before them both |
| 158 |
assert srcs.index("https://plugin-example.datasette.io/jquery.js") < srcs.index( |
| 159 |
"https://plugin-example.datasette.io/plugin1.js" |
| 160 |
) |
| 161 |
assert srcs.index("https://plugin-example.datasette.io/jquery.js") < srcs.index( |
| 162 |
"https://plugin-example.datasette.io/plugin2.js" |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
def test_hook_render_cell_link_from_json(app_client): |
| 167 |
sql = """ |
| 168 |
select '{"href": "http://example.com/", "label":"Example"}' |
| 169 |
""".strip() |
| 170 |
path = "/fixtures?" + urllib.parse.urlencode({"sql": sql}) |
| 171 |
response = app_client.get(path) |
| 172 |
td = Soup(response.body, "html.parser").find("table").find("tbody").find("td") |
| 173 |
a = td.find("a") |
| 174 |
assert a is not None, str(a) |
| 175 |
assert a.attrs["href"] == "http://example.com/" |
| 176 |
assert a.attrs["data-database"] == "fixtures" |
| 177 |
assert a.text == "Example" |
| 178 |
|
| 179 |
|
| 180 |
def test_hook_render_cell_demo(app_client): |
| 181 |
response = app_client.get("/fixtures/simple_primary_key?id=4") |
| 182 |
soup = Soup(response.body, "html.parser") |
| 183 |
td = soup.find("td", {"class": "col-content"}) |
| 184 |
assert json.loads(td.string) == { |
| 185 |
"row": {"id": "4", "content": "RENDER_CELL_DEMO"}, |
| 186 |
"column": "content", |
| 187 |
"table": "simple_primary_key", |
| 188 |
"database": "fixtures", |
| 189 |
"config": {"depth": "table", "special": "this-is-simple_primary_key"}, |
| 190 |
} |
| 191 |
|
| 192 |
|
| 193 |
@pytest.mark.parametrize( |
| 194 |
"path", ("/fixtures?sql=select+'RENDER_CELL_ASYNC'", "/fixtures/simple_primary_key") |
| 195 |
) |
| 196 |
def test_hook_render_cell_async(app_client, path): |
| 197 |
response = app_client.get(path) |
| 198 |
assert b"RENDER_CELL_ASYNC_RESULT" in response.body |
| 199 |
|
| 200 |
|
| 201 |
def test_plugin_config(app_client): |
| 202 |
assert {"depth": "table"} == app_client.ds.plugin_config( |
| 203 |
"name-of-plugin", database="fixtures", table="sortable" |
| 204 |
) |
| 205 |
assert {"depth": "database"} == app_client.ds.plugin_config( |
| 206 |
"name-of-plugin", database="fixtures", table="unknown_table" |
| 207 |
) |
| 208 |
assert {"depth": "database"} == app_client.ds.plugin_config( |
| 209 |
"name-of-plugin", database="fixtures" |
| 210 |
) |
| 211 |
assert {"depth": "root"} == app_client.ds.plugin_config( |
| 212 |
"name-of-plugin", database="unknown_database" |
| 213 |
) |
| 214 |
assert {"depth": "root"} == app_client.ds.plugin_config("name-of-plugin") |
| 215 |
assert None is app_client.ds.plugin_config("unknown-plugin") |
| 216 |
|
| 217 |
|
| 218 |
def test_plugin_config_env(app_client): |
| 219 |
os.environ["FOO_ENV"] = "FROM_ENVIRONMENT" |
| 220 |
assert {"foo": "FROM_ENVIRONMENT"} == app_client.ds.plugin_config("env-plugin") |
| 221 |
# Ensure secrets aren't visible in /-/metadata.json |
| 222 |
metadata = app_client.get("/-/metadata.json") |
| 223 |
assert {"foo": {"$env": "FOO_ENV"}} == metadata.json["plugins"]["env-plugin"] |
| 224 |
del os.environ["FOO_ENV"] |
| 225 |
|
| 226 |
|
| 227 |
def test_plugin_config_env_from_list(app_client): |
| 228 |
os.environ["FOO_ENV"] = "FROM_ENVIRONMENT" |
| 229 |
assert [{"in_a_list": "FROM_ENVIRONMENT"}] == app_client.ds.plugin_config( |
| 230 |
"env-plugin-list" |
| 231 |
) |
| 232 |
# Ensure secrets aren't visible in /-/metadata.json |
| 233 |
metadata = app_client.get("/-/metadata.json") |
| 234 |
assert [{"in_a_list": {"$env": "FOO_ENV"}}] == metadata.json["plugins"][ |
| 235 |
"env-plugin-list" |
| 236 |
] |
| 237 |
del os.environ["FOO_ENV"] |
| 238 |
|
| 239 |
|
| 240 |
def test_plugin_config_file(app_client): |
| 241 |
with open(TEMP_PLUGIN_SECRET_FILE, "w") as fp: |
| 242 |
fp.write("FROM_FILE") |
| 243 |
assert {"foo": "FROM_FILE"} == app_client.ds.plugin_config("file-plugin") |
| 244 |
# Ensure secrets aren't visible in /-/metadata.json |
| 245 |
metadata = app_client.get("/-/metadata.json") |
| 246 |
assert {"foo": {"$file": TEMP_PLUGIN_SECRET_FILE}} == metadata.json["plugins"][ |
| 247 |
"file-plugin" |
| 248 |
] |
| 249 |
os.remove(TEMP_PLUGIN_SECRET_FILE) |
| 250 |
|
| 251 |
|
| 252 |
@pytest.mark.parametrize( |
| 253 |
"path,expected_extra_body_script", |
| 254 |
[ |
| 255 |
( |
| 256 |
"/", |
| 257 |
{ |
| 258 |
"template": "index.html", |
| 259 |
"database": None, |
| 260 |
"table": None, |
| 261 |
"config": {"depth": "root"}, |
| 262 |
"view_name": "index", |
| 263 |
"request_path": "/", |
| 264 |
"added": 15, |
| 265 |
"columns": None, |
| 266 |
}, |
| 267 |
), |
| 268 |
( |
| 269 |
"/fixtures", |
| 270 |
{ |
| 271 |
"template": "database.html", |
| 272 |
"database": "fixtures", |
| 273 |
"table": None, |
| 274 |
"config": {"depth": "database"}, |
| 275 |
"view_name": "database", |
| 276 |
"request_path": "/fixtures", |
| 277 |
"added": 15, |
| 278 |
"columns": None, |
| 279 |
}, |
| 280 |
), |
| 281 |
( |
| 282 |
"/fixtures/sortable", |
| 283 |
{ |
| 284 |
"template": "table.html", |
| 285 |
"database": "fixtures", |
| 286 |
"table": "sortable", |
| 287 |
"config": {"depth": "table"}, |
| 288 |
"view_name": "table", |
| 289 |
"request_path": "/fixtures/sortable", |
| 290 |
"added": 15, |
| 291 |
"columns": [ |
| 292 |
"pk1", |
| 293 |
"pk2", |
| 294 |
"content", |
| 295 |
"sortable", |
| 296 |
"sortable_with_nulls", |
| 297 |
"sortable_with_nulls_2", |
| 298 |
"text", |
| 299 |
], |
| 300 |
}, |
| 301 |
), |
| 302 |
], |
| 303 |
) |
| 304 |
def test_hook_extra_body_script(app_client, path, expected_extra_body_script): |
| 305 |
r = re.compile(r"<script type=\"module\">var extra_body_script = (.*?);</script>") |
| 306 |
json_data = r.search(app_client.get(path).text).group(1) |
| 307 |
actual_data = json.loads(json_data) |
| 308 |
assert expected_extra_body_script == actual_data |
| 309 |
|
| 310 |
|
| 311 |
def test_hook_asgi_wrapper(app_client): |
| 312 |
response = app_client.get("/fixtures") |
| 313 |
assert "_internal, fixtures" == response.headers["x-databases"] |
| 314 |
|
| 315 |
|
| 316 |
def test_hook_extra_template_vars(restore_working_directory): |
| 317 |
with make_app_client( |
| 318 |
template_dir=str(pathlib.Path(__file__).parent / "test_templates") |
| 319 |
) as client: |
| 320 |
response = client.get("/-/metadata") |
| 321 |
assert response.status == 200 |
| 322 |
extra_template_vars = json.loads( |
| 323 |
Soup(response.body, "html.parser").select("pre.extra_template_vars")[0].text |
| 324 |
) |
| 325 |
assert { |
| 326 |
"template": "show_json.html", |
| 327 |
"scope_path": "/-/metadata", |
| 328 |
"columns": None, |
| 329 |
} == extra_template_vars |
| 330 |
extra_template_vars_from_awaitable = json.loads( |
| 331 |
Soup(response.body, "html.parser") |
| 332 |
.select("pre.extra_template_vars_from_awaitable")[0] |
| 333 |
.text |
| 334 |
) |
| 335 |
assert { |
| 336 |
"template": "show_json.html", |
| 337 |
"awaitable": True, |
| 338 |
"scope_path": "/-/metadata", |
| 339 |
} == extra_template_vars_from_awaitable |
| 340 |
|
| 341 |
|
| 342 |
def test_plugins_async_template_function(restore_working_directory): |
| 343 |
with make_app_client( |
| 344 |
template_dir=str(pathlib.Path(__file__).parent / "test_templates") |
| 345 |
) as client: |
| 346 |
response = client.get("/-/metadata") |
| 347 |
assert response.status == 200 |
| 348 |
extra_from_awaitable_function = ( |
| 349 |
Soup(response.body, "html.parser") |
| 350 |
.select("pre.extra_from_awaitable_function")[0] |
| 351 |
.text |
| 352 |
) |
| 353 |
expected = ( |
| 354 |
sqlite3.connect(":memory:").execute("select sqlite_version()").fetchone()[0] |
| 355 |
) |
| 356 |
assert expected == extra_from_awaitable_function |
| 357 |
|
| 358 |
|
| 359 |
def test_default_plugins_have_no_templates_path_or_static_path(): |
| 360 |
# The default plugins that ship with Datasette should have their static_path and |
| 361 |
# templates_path all set to None |
| 362 |
plugins = get_plugins() |
| 363 |
for plugin in plugins: |
| 364 |
if plugin["name"] in DEFAULT_PLUGINS: |
| 365 |
assert None is plugin["static_path"] |
| 366 |
assert None is plugin["templates_path"] |
| 367 |
|
| 368 |
|
| 369 |
@pytest.fixture(scope="session") |
| 370 |
def view_names_client(tmp_path_factory): |
| 371 |
tmpdir = tmp_path_factory.mktemp("test-view-names") |
| 372 |
templates = tmpdir / "templates" |
| 373 |
templates.mkdir() |
| 374 |
plugins = tmpdir / "plugins" |
| 375 |
plugins.mkdir() |
| 376 |
for template in ( |
| 377 |
"index.html", |
| 378 |
"database.html", |
| 379 |
"table.html", |
| 380 |
"row.html", |
| 381 |
"show_json.html", |
| 382 |
"query.html", |
| 383 |
): |
| 384 |
(templates / template).write_text("view_name:{{ view_name }}", "utf-8") |
| 385 |
(plugins / "extra_vars.py").write_text( |
| 386 |
textwrap.dedent( |
| 387 |
""" |
| 388 |
from datasette import hookimpl |
| 389 |
@hookimpl |
| 390 |
def extra_template_vars(view_name): |
| 391 |
return {"view_name": view_name} |
| 392 |
""" |
| 393 |
), |
| 394 |
"utf-8", |
| 395 |
) |
| 396 |
db_path = str(tmpdir / "fixtures.db") |
| 397 |
conn = sqlite3.connect(db_path) |
| 398 |
conn.executescript(TABLES) |
| 399 |
return _TestClient( |
| 400 |
Datasette([db_path], template_dir=str(templates), plugins_dir=str(plugins)) |
| 401 |
) |
| 402 |
|
| 403 |
|
| 404 |
@pytest.mark.parametrize( |
| 405 |
"path,view_name", |
| 406 |
( |
| 407 |
("/", "index"), |
| 408 |
("/fixtures", "database"), |
| 409 |
("/fixtures/units", "table"), |
| 410 |
("/fixtures/units/1", "row"), |
| 411 |
("/-/metadata", "json_data"), |
| 412 |
("/fixtures?sql=select+1", "database"), |
| 413 |
), |
| 414 |
) |
| 415 |
def test_view_names(view_names_client, path, view_name): |
| 416 |
response = view_names_client.get(path) |
| 417 |
assert response.status == 200 |
| 418 |
assert f"view_name:{view_name}" == response.text |
| 419 |
|
| 420 |
|
| 421 |
def test_hook_register_output_renderer_no_parameters(app_client): |
| 422 |
response = app_client.get("/fixtures/facetable.testnone") |
| 423 |
assert 200 == response.status |
| 424 |
assert b"Hello" == response.body |
| 425 |
|
| 426 |
|
| 427 |
def test_hook_register_output_renderer_all_parameters(app_client): |
| 428 |
response = app_client.get("/fixtures/facetable.testall") |
| 429 |
assert 200 == response.status |
| 430 |
# Lots of 'at 0x103a4a690' in here - replace those so we can do |
| 431 |
# an easy comparison |
| 432 |
body = at_memory_re.sub(" at 0xXXX", response.text) |
| 433 |
assert json.loads(body) == { |
| 434 |
"datasette": "<datasette.app.Datasette object at 0xXXX>", |
| 435 |
"columns": [ |
| 436 |
"pk", |
| 437 |
"created", |
| 438 |
"planet_int", |
| 439 |
"on_earth", |
| 440 |
"state", |
| 441 |
"_city_id", |
| 442 |
"_neighborhood", |
| 443 |
"tags", |
| 444 |
"complex_array", |
| 445 |
"distinct_some_null", |
| 446 |
"n", |
| 447 |
], |
| 448 |
"rows": [ |
| 449 |
"<sqlite3.Row object at 0xXXX>", |
| 450 |
"<sqlite3.Row object at 0xXXX>", |
| 451 |
"<sqlite3.Row object at 0xXXX>", |
| 452 |
"<sqlite3.Row object at 0xXXX>", |
| 453 |
"<sqlite3.Row object at 0xXXX>", |
| 454 |
"<sqlite3.Row object at 0xXXX>", |
| 455 |
"<sqlite3.Row object at 0xXXX>", |
| 456 |
"<sqlite3.Row object at 0xXXX>", |
| 457 |
"<sqlite3.Row object at 0xXXX>", |
| 458 |
"<sqlite3.Row object at 0xXXX>", |
| 459 |
"<sqlite3.Row object at 0xXXX>", |
| 460 |
"<sqlite3.Row object at 0xXXX>", |
| 461 |
"<sqlite3.Row object at 0xXXX>", |
| 462 |
"<sqlite3.Row object at 0xXXX>", |
| 463 |
"<sqlite3.Row object at 0xXXX>", |
| 464 |
], |
| 465 |
"sql": "select pk, created, planet_int, on_earth, state, _city_id, _neighborhood, tags, complex_array, distinct_some_null, n from facetable order by pk limit 51", |
| 466 |
"query_name": None, |
| 467 |
"database": "fixtures", |
| 468 |
"table": "facetable", |
| 469 |
"request": '<asgi.Request method="GET" url="http://localhost/fixtures/facetable.testall">', |
| 470 |
"view_name": "table", |
| 471 |
"1+1": 2, |
| 472 |
} |
| 473 |
# Test that query_name is set correctly |
| 474 |
query_response = app_client.get("/fixtures/pragma_cache_size.testall") |
| 475 |
assert "pragma_cache_size" == json.loads(query_response.body)["query_name"] |
| 476 |
|
| 477 |
|
| 478 |
def test_hook_register_output_renderer_custom_status_code(app_client): |
| 479 |
response = app_client.get("/fixtures/pragma_cache_size.testall?status_code=202") |
| 480 |
assert 202 == response.status |
| 481 |
|
| 482 |
|
| 483 |
def test_hook_register_output_renderer_custom_content_type(app_client): |
| 484 |
response = app_client.get( |
| 485 |
"/fixtures/pragma_cache_size.testall?content_type=text/blah" |
| 486 |
) |
| 487 |
assert "text/blah" == response.headers["content-type"] |
| 488 |
|
| 489 |
|
| 490 |
def test_hook_register_output_renderer_custom_headers(app_client): |
| 491 |
response = app_client.get( |
| 492 |
"/fixtures/pragma_cache_size.testall?header=x-wow:1&header=x-gosh:2" |
| 493 |
) |
| 494 |
assert "1" == response.headers["x-wow"] |
| 495 |
assert "2" == response.headers["x-gosh"] |
| 496 |
|
| 497 |
|
| 498 |
def test_hook_register_output_renderer_returning_response(app_client): |
| 499 |
response = app_client.get("/fixtures/facetable.testresponse") |
| 500 |
assert 200 == response.status |
| 501 |
assert response.json == {"this_is": "json"} |
| 502 |
|
| 503 |
|
| 504 |
def test_hook_register_output_renderer_returning_broken_value(app_client): |
| 505 |
response = app_client.get("/fixtures/facetable.testresponse?_broken=1") |
| 506 |
assert 500 == response.status |
| 507 |
assert "this should break should be dict or Response" in response.text |
| 508 |
|
| 509 |
|
| 510 |
def test_hook_register_output_renderer_can_render(app_client): |
| 511 |
response = app_client.get("/fixtures/facetable?_no_can_render=1") |
| 512 |
assert response.status == 200 |
| 513 |
links = ( |
| 514 |
Soup(response.body, "html.parser") |
| 515 |
.find("p", {"class": "export-links"}) |
| 516 |
.find_all("a") |
| 517 |
) |
| 518 |
actual = [l["href"] for l in links] |
| 519 |
# Should not be present because we sent ?_no_can_render=1 |
| 520 |
assert "/fixtures/facetable.testall?_labels=on" not in actual |
| 521 |
# Check that it was passed the values we expected |
| 522 |
assert hasattr(app_client.ds, "_can_render_saw") |
| 523 |
assert { |
| 524 |
"datasette": app_client.ds, |
| 525 |
"columns": [ |
| 526 |
"pk", |
| 527 |
"created", |
| 528 |
"planet_int", |
| 529 |
"on_earth", |
| 530 |
"state", |
| 531 |
"_city_id", |
| 532 |
"_neighborhood", |
| 533 |
"tags", |
| 534 |
"complex_array", |
| 535 |
"distinct_some_null", |
| 536 |
"n", |
| 537 |
], |
| 538 |
"sql": "select pk, created, planet_int, on_earth, state, _city_id, _neighborhood, tags, complex_array, distinct_some_null, n from facetable order by pk limit 51", |
| 539 |
"query_name": None, |
| 540 |
"database": "fixtures", |
| 541 |
"table": "facetable", |
| 542 |
"view_name": "table", |
| 543 |
}.items() <= app_client.ds._can_render_saw.items() |
| 544 |
|
| 545 |
|
| 546 |
@pytest.mark.asyncio |
| 547 |
async def test_hook_prepare_jinja2_environment(app_client): |
| 548 |
app_client.ds._HELLO = "HI" |
| 549 |
await app_client.ds.invoke_startup() |
| 550 |
template = app_client.ds.jinja_env.from_string( |
| 551 |
"Hello there, {{ a|format_numeric }}, {{ a|to_hello }}, {{ b|select_times_three }}", |
| 552 |
{"a": 3412341, "b": 5}, |
| 553 |
) |
| 554 |
rendered = await app_client.ds.render_template(template) |
| 555 |
assert "Hello there, 3,412,341, HI, 15" == rendered |
| 556 |
|
| 557 |
|
| 558 |
def test_hook_publish_subcommand(): |
| 559 |
# This is hard to test properly, because publish subcommand plugins |
| 560 |
# cannot be loaded using the --plugins-dir mechanism - they need |
| 561 |
# to be installed using "pip install". So I'm cheating and taking |
| 562 |
# advantage of the fact that cloudrun/heroku use the plugin hook |
| 563 |
# to register themselves as default plugins. |
| 564 |
assert ["cloudrun", "heroku"] == cli.publish.list_commands({}) |
| 565 |
|
| 566 |
|
| 567 |
def test_hook_register_facet_classes(app_client): |
| 568 |
response = app_client.get( |
| 569 |
"/fixtures/compound_three_primary_keys.json?_dummy_facet=1" |
| 570 |
) |
| 571 |
assert [ |
| 572 |
{ |
| 573 |
"name": "pk1", |
| 574 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet_dummy=pk1", |
| 575 |
"type": "dummy", |
| 576 |
}, |
| 577 |
{ |
| 578 |
"name": "pk2", |
| 579 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet_dummy=pk2", |
| 580 |
"type": "dummy", |
| 581 |
}, |
| 582 |
{ |
| 583 |
"name": "pk3", |
| 584 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet_dummy=pk3", |
| 585 |
"type": "dummy", |
| 586 |
}, |
| 587 |
{ |
| 588 |
"name": "content", |
| 589 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet_dummy=content", |
| 590 |
"type": "dummy", |
| 591 |
}, |
| 592 |
{ |
| 593 |
"name": "pk1", |
| 594 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet=pk1", |
| 595 |
}, |
| 596 |
{ |
| 597 |
"name": "pk2", |
| 598 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet=pk2", |
| 599 |
}, |
| 600 |
{ |
| 601 |
"name": "pk3", |
| 602 |
"toggle_url": "http://localhost/fixtures/compound_three_primary_keys.json?_dummy_facet=1&_facet=pk3", |
| 603 |
}, |
| 604 |
] == response.json["suggested_facets"] |
| 605 |
|
| 606 |
|
| 607 |
def test_hook_actor_from_request(app_client): |
| 608 |
app_client.get("/") |
| 609 |
# Should have no actor |
| 610 |
assert None == app_client.ds._last_request.scope["actor"] |
| 611 |
app_client.get("/?_bot=1") |
| 612 |
# Should have bot actor |
| 613 |
assert {"id": "bot"} == app_client.ds._last_request.scope["actor"] |
| 614 |
|
| 615 |
|
| 616 |
def test_hook_actor_from_request_async(app_client): |
| 617 |
app_client.get("/") |
| 618 |
# Should have no actor |
| 619 |
assert None == app_client.ds._last_request.scope["actor"] |
| 620 |
app_client.get("/?_bot2=1") |
| 621 |
# Should have bot2 actor |
| 622 |
assert {"id": "bot2", "1+1": 2} == app_client.ds._last_request.scope["actor"] |
| 623 |
|
| 624 |
|
| 625 |
def test_existing_scope_actor_respected(app_client): |
| 626 |
app_client.get("/?_actor_in_scope=1") |
| 627 |
assert {"id": "from-scope"} == app_client.ds._last_request.scope["actor"] |
| 628 |
|
| 629 |
|
| 630 |
@pytest.mark.asyncio |
| 631 |
@pytest.mark.parametrize( |
| 632 |
"action,expected", |
| 633 |
[ |
| 634 |
("this_is_allowed", True), |
| 635 |
("this_is_denied", False), |
| 636 |
("this_is_allowed_async", True), |
| 637 |
("this_is_denied_async", False), |
| 638 |
("no_match", None), |
| 639 |
], |
| 640 |
) |
| 641 |
async def test_hook_permission_allowed(app_client, action, expected): |
| 642 |
actual = await app_client.ds.permission_allowed( |
| 643 |
{"id": "actor"}, action, default=None |
| 644 |
) |
| 645 |
assert expected == actual |
| 646 |
|
| 647 |
|
| 648 |
def test_actor_json(app_client): |
| 649 |
assert {"actor": None} == app_client.get("/-/actor.json").json |
| 650 |
assert {"actor": {"id": "bot2", "1+1": 2}} == app_client.get( |
| 651 |
"/-/actor.json?_bot2=1" |
| 652 |
).json |
| 653 |
|
| 654 |
|
| 655 |
@pytest.mark.parametrize( |
| 656 |
"path,body", |
| 657 |
[ |
| 658 |
("/one/", "2"), |
| 659 |
("/two/Ray?greeting=Hail", "Hail Ray"), |
| 660 |
("/not-async/", "This was not async"), |
| 661 |
], |
| 662 |
) |
| 663 |
def test_hook_register_routes(app_client, path, body): |
| 664 |
response = app_client.get(path) |
| 665 |
assert 200 == response.status |
| 666 |
assert body == response.text |
| 667 |
|
| 668 |
|
| 669 |
@pytest.mark.parametrize("configured_path", ("path1", "path2")) |
| 670 |
def test_hook_register_routes_with_datasette(configured_path): |
| 671 |
with make_app_client( |
| 672 |
metadata={ |
| 673 |
"plugins": { |
| 674 |
"register-route-demo": { |
| 675 |
"path": configured_path, |
| 676 |
} |
| 677 |
} |
| 678 |
} |
| 679 |
) as client: |
| 680 |
response = client.get(f"/{configured_path}/") |
| 681 |
assert response.status == 200 |
| 682 |
assert configured_path.upper() == response.text |
| 683 |
# Other one should 404 |
| 684 |
other_path = [p for p in ("path1", "path2") if configured_path != p][0] |
| 685 |
assert client.get(f"/{other_path}/", follow_redirects=True).status == 404 |
| 686 |
|
| 687 |
|
| 688 |
def test_hook_register_routes_override(): |
| 689 |
"Plugins can over-ride default paths such as /db/table" |
| 690 |
with make_app_client( |
| 691 |
metadata={ |
| 692 |
"plugins": { |
| 693 |
"register-route-demo": { |
| 694 |
"path": "blah", |
| 695 |
} |
| 696 |
} |
| 697 |
} |
| 698 |
) as client: |
| 699 |
response = client.get("/db/table") |
| 700 |
assert response.status == 200 |
| 701 |
assert ( |
| 702 |
response.text |
| 703 |
== "/db/table: [('db_name', 'db'), ('table_and_format', 'table')]" |
| 704 |
) |
| 705 |
|
| 706 |
|
| 707 |
def test_hook_register_routes_post(app_client): |
| 708 |
response = app_client.post("/post/", {"this is": "post data"}, csrftoken_from=True) |
| 709 |
assert 200 == response.status |
| 710 |
assert "csrftoken" in response.json |
| 711 |
assert "post data" == response.json["this is"] |
| 712 |
|
| 713 |
|
| 714 |
def test_hook_register_routes_csrftoken(restore_working_directory, tmpdir_factory): |
| 715 |
templates = tmpdir_factory.mktemp("templates") |
| 716 |
(templates / "csrftoken_form.html").write_text( |
| 717 |
"CSRFTOKEN: {{ csrftoken() }}", "utf-8" |
| 718 |
) |
| 719 |
with make_app_client(template_dir=templates) as client: |
| 720 |
response = client.get("/csrftoken-form/") |
| 721 |
expected_token = client.ds._last_request.scope["csrftoken"]() |
| 722 |
assert f"CSRFTOKEN: {expected_token}" == response.text |
| 723 |
|
| 724 |
|
| 725 |
def test_hook_register_routes_asgi(app_client): |
| 726 |
response = app_client.get("/three/") |
| 727 |
assert {"hello": "world"} == response.json |
| 728 |
assert "1" == response.headers["x-three"] |
| 729 |
|
| 730 |
|
| 731 |
def test_hook_register_routes_add_message(app_client): |
| 732 |
response = app_client.get("/add-message/") |
| 733 |
assert 200 == response.status |
| 734 |
assert "Added message" == response.text |
| 735 |
decoded = app_client.ds.unsign(response.cookies["ds_messages"], "messages") |
| 736 |
assert [["Hello from messages", 1]] == decoded |
| 737 |
|
| 738 |
|
| 739 |
def test_hook_register_routes_render_message(restore_working_directory, tmpdir_factory): |
| 740 |
templates = tmpdir_factory.mktemp("templates") |
| 741 |
(templates / "render_message.html").write_text('{% extends "base.html" %}', "utf-8") |
| 742 |
with make_app_client(template_dir=templates) as client: |
| 743 |
response1 = client.get("/add-message/") |
| 744 |
response2 = client.get("/render-message/", cookies=response1.cookies) |
| 745 |
assert 200 == response2.status |
| 746 |
assert "Hello from messages" in response2.text |
| 747 |
|
| 748 |
|
| 749 |
@pytest.mark.asyncio |
| 750 |
async def test_hook_startup(app_client): |
| 751 |
await app_client.ds.invoke_startup() |
| 752 |
assert app_client.ds._startup_hook_fired |
| 753 |
assert 2 == app_client.ds._startup_hook_calculation |
| 754 |
|
| 755 |
|
| 756 |
def test_hook_canned_queries(app_client): |
| 757 |
queries = app_client.get("/fixtures.json").json["queries"] |
| 758 |
queries_by_name = {q["name"]: q for q in queries} |
| 759 |
assert { |
| 760 |
"sql": "select 2", |
| 761 |
"name": "from_async_hook", |
| 762 |
"private": False, |
| 763 |
} == queries_by_name["from_async_hook"] |
| 764 |
assert { |
| 765 |
"sql": "select 1, 'null' as actor_id", |
| 766 |
"name": "from_hook", |
| 767 |
"private": False, |
| 768 |
} == queries_by_name["from_hook"] |
| 769 |
|
| 770 |
|
| 771 |
def test_hook_canned_queries_non_async(app_client): |
| 772 |
response = app_client.get("/fixtures/from_hook.json?_shape=array") |
| 773 |
assert [{"1": 1, "actor_id": "null"}] == response.json |
| 774 |
|
| 775 |
|
| 776 |
def test_hook_canned_queries_async(app_client): |
| 777 |
response = app_client.get("/fixtures/from_async_hook.json?_shape=array") |
| 778 |
assert [{"2": 2}] == response.json |
| 779 |
|
| 780 |
|
| 781 |
def test_hook_canned_queries_actor(app_client): |
| 782 |
assert [{"1": 1, "actor_id": "bot"}] == app_client.get( |
| 783 |
"/fixtures/from_hook.json?_bot=1&_shape=array" |
| 784 |
).json |
| 785 |
|
| 786 |
|
| 787 |
def test_hook_register_magic_parameters(restore_working_directory): |
| 788 |
with make_app_client( |
| 789 |
extra_databases={"data.db": "create table logs (line text)"}, |
| 790 |
metadata={ |
| 791 |
"databases": { |
| 792 |
"data": { |
| 793 |
"queries": { |
| 794 |
"runme": { |
| 795 |
"sql": "insert into logs (line) values (:_request_http_version)", |
| 796 |
"write": True, |
| 797 |
}, |
| 798 |
"get_uuid": { |
| 799 |
"sql": "select :_uuid_new", |
| 800 |
}, |
| 801 |
} |
| 802 |
} |
| 803 |
} |
| 804 |
}, |
| 805 |
) as client: |
| 806 |
response = client.post("/data/runme", {}, csrftoken_from=True) |
| 807 |
assert 302 == response.status |
| 808 |
actual = client.get("/data/logs.json?_sort_desc=rowid&_shape=array").json |
| 809 |
assert [{"rowid": 1, "line": "1.1"}] == actual |
| 810 |
# Now try the GET request against get_uuid |
| 811 |
response_get = client.get("/data/get_uuid.json?_shape=array") |
| 812 |
assert 200 == response_get.status |
| 813 |
new_uuid = response_get.json[0][":_uuid_new"] |
| 814 |
assert 4 == new_uuid.count("-") |
| 815 |
|
| 816 |
|
| 817 |
def test_hook_forbidden(restore_working_directory): |
| 818 |
with make_app_client( |
| 819 |
extra_databases={"data2.db": "create table logs (line text)"}, |
| 820 |
metadata={"allow": {}}, |
| 821 |
) as client: |
| 822 |
response = client.get("/") |
| 823 |
assert 403 == response.status |
| 824 |
response2 = client.get("/data2") |
| 825 |
assert 302 == response2.status |
| 826 |
assert ( |
| 827 |
response2.headers["Location"] |
| 828 |
== "/login?message=You do not have permission to view this database" |
| 829 |
) |
| 830 |
assert ( |
| 831 |
client.ds._last_forbidden_message |
| 832 |
== "You do not have permission to view this database" |
| 833 |
) |
| 834 |
|
| 835 |
|
| 836 |
def test_hook_handle_exception(app_client): |
| 837 |
app_client.get("/trigger-error?x=123") |
| 838 |
assert hasattr(app_client.ds, "_exception_hook_fired") |
| 839 |
request, exception = app_client.ds._exception_hook_fired |
| 840 |
assert request.url == "http://localhost/trigger-error?x=123" |
| 841 |
assert isinstance(exception, ZeroDivisionError) |
| 842 |
|
| 843 |
|
| 844 |
@pytest.mark.parametrize("param", ("_custom_error", "_custom_error_async")) |
| 845 |
def test_hook_handle_exception_custom_response(app_client, param): |
| 846 |
response = app_client.get("/trigger-error?{}=1".format(param)) |
| 847 |
assert response.text == param |
| 848 |
|
| 849 |
|
| 850 |
def test_hook_menu_links(app_client): |
| 851 |
def get_menu_links(html): |
| 852 |
soup = Soup(html, "html.parser") |
| 853 |
return [ |
| 854 |
{"label": a.text, "href": a["href"]} for a in soup.select(".nav-menu a") |
| 855 |
] |
| 856 |
|
| 857 |
response = app_client.get("/") |
| 858 |
assert get_menu_links(response.text) == [] |
| 859 |
|
| 860 |
response_2 = app_client.get("/?_bot=1&_hello=BOB") |
| 861 |
assert get_menu_links(response_2.text) == [ |
| 862 |
{"label": "Hello, BOB", "href": "/"}, |
| 863 |
{"label": "Hello 2", "href": "/"}, |
| 864 |
] |
| 865 |
|
| 866 |
|
| 867 |
@pytest.mark.parametrize("table_or_view", ["facetable", "simple_view"]) |
| 868 |
def test_hook_table_actions(app_client, table_or_view): |
| 869 |
def get_table_actions_links(html): |
| 870 |
soup = Soup(html, "html.parser") |
| 871 |
details = soup.find("details", {"class": "actions-menu-links"}) |
| 872 |
if details is None: |
| 873 |
return [] |
| 874 |
return [{"label": a.text, "href": a["href"]} for a in details.select("a")] |
| 875 |
|
| 876 |
response = app_client.get(f"/fixtures/{table_or_view}") |
| 877 |
assert get_table_actions_links(response.text) == [] |
| 878 |
|
| 879 |
response_2 = app_client.get(f"/fixtures/{table_or_view}?_bot=1&_hello=BOB") |
| 880 |
assert sorted( |
| 881 |
get_table_actions_links(response_2.text), key=lambda l: l["label"] |
| 882 |
) == [ |
| 883 |
{"label": "Database: fixtures", "href": "/"}, |
| 884 |
{"label": "From async BOB", "href": "/"}, |
| 885 |
{"label": f"Table: {table_or_view}", "href": "/"}, |
| 886 |
] |
| 887 |
|
| 888 |
|
| 889 |
def test_hook_database_actions(app_client): |
| 890 |
def get_table_actions_links(html): |
| 891 |
soup = Soup(html, "html.parser") |
| 892 |
details = soup.find("details", {"class": "actions-menu-links"}) |
| 893 |
if details is None: |
| 894 |
return [] |
| 895 |
return [{"label": a.text, "href": a["href"]} for a in details.select("a")] |
| 896 |
|
| 897 |
response = app_client.get("/fixtures") |
| 898 |
assert get_table_actions_links(response.text) == [] |
| 899 |
|
| 900 |
response_2 = app_client.get("/fixtures?_bot=1&_hello=BOB") |
| 901 |
assert get_table_actions_links(response_2.text) == [ |
| 902 |
{"label": "Database: fixtures - BOB", "href": "/"}, |
| 903 |
] |
| 904 |
|
| 905 |
|
| 906 |
def test_hook_skip_csrf(app_client): |
| 907 |
cookie = app_client.actor_cookie({"id": "test"}) |
| 908 |
csrf_response = app_client.post( |
| 909 |
"/post/", |
| 910 |
post_data={"this is": "post data"}, |
| 911 |
csrftoken_from=True, |
| 912 |
cookies={"ds_actor": cookie}, |
| 913 |
) |
| 914 |
assert csrf_response.status == 200 |
| 915 |
missing_csrf_response = app_client.post( |
| 916 |
"/post/", post_data={"this is": "post data"}, cookies={"ds_actor": cookie} |
| 917 |
) |
| 918 |
assert missing_csrf_response.status == 403 |
| 919 |
# But "/skip-csrf" should allow |
| 920 |
allow_csrf_response = app_client.post( |
| 921 |
"/skip-csrf", post_data={"this is": "post data"}, cookies={"ds_actor": cookie} |
| 922 |
) |
| 923 |
assert allow_csrf_response.status == 405 # Method not allowed |
| 924 |
# /skip-csrf-2 should not |
| 925 |
second_missing_csrf_response = app_client.post( |
| 926 |
"/skip-csrf-2", post_data={"this is": "post data"}, cookies={"ds_actor": cookie} |
| 927 |
) |
| 928 |
assert second_missing_csrf_response.status == 403 |
| 929 |
|
| 930 |
|
| 931 |
def test_hook_get_metadata(app_client): |
| 932 |
app_client.ds._metadata_local = { |
| 933 |
"title": "Testing get_metadata hook!", |
| 934 |
"databases": {"from-local": {"title": "Hello from local metadata"}}, |
| 935 |
} |
| 936 |
og_pm_hook_get_metadata = pm.hook.get_metadata |
| 937 |
|
| 938 |
def get_metadata_mock(*args, **kwargs): |
| 939 |
return [ |
| 940 |
{ |
| 941 |
"databases": { |
| 942 |
"from-hook": {"title": "Hello from the plugin hook"}, |
| 943 |
"from-local": {"title": "This will be overwritten!"}, |
| 944 |
} |
| 945 |
} |
| 946 |
] |
| 947 |
|
| 948 |
pm.hook.get_metadata = get_metadata_mock |
| 949 |
meta = app_client.ds.metadata() |
| 950 |
assert "Testing get_metadata hook!" == meta["title"] |
| 951 |
assert "Hello from local metadata" == meta["databases"]["from-local"]["title"] |
| 952 |
assert "Hello from the plugin hook" == meta["databases"]["from-hook"]["title"] |
| 953 |
pm.hook.get_metadata = og_pm_hook_get_metadata |
| 954 |
|
| 955 |
|
| 956 |
def _extract_commands(output): |
| 957 |
lines = output.split("Commands:\n", 1)[1].split("\n") |
| 958 |
return {line.split()[0].replace("*", "") for line in lines if line.strip()} |
| 959 |
|
| 960 |
|
| 961 |
def test_hook_register_commands(): |
| 962 |
# Without the plugin should have seven commands |
| 963 |
runner = CliRunner() |
| 964 |
result = runner.invoke(cli.cli, "--help") |
| 965 |
commands = _extract_commands(result.output) |
| 966 |
assert commands == { |
| 967 |
"serve", |
| 968 |
"inspect", |
| 969 |
"install", |
| 970 |
"package", |
| 971 |
"plugins", |
| 972 |
"publish", |
| 973 |
"uninstall", |
| 974 |
} |
| 975 |
|
| 976 |
# Now install a plugin |
| 977 |
class VerifyPlugin: |
| 978 |
__name__ = "VerifyPlugin" |
| 979 |
|
| 980 |
@hookimpl |
| 981 |
def register_commands(self, cli): |
| 982 |
@cli.command() |
| 983 |
def verify(): |
| 984 |
pass |
| 985 |
|
| 986 |
@cli.command() |
| 987 |
def unverify(): |
| 988 |
pass |
| 989 |
|
| 990 |
pm.register(VerifyPlugin(), name="verify") |
| 991 |
importlib.reload(cli) |
| 992 |
result2 = runner.invoke(cli.cli, "--help") |
| 993 |
commands2 = _extract_commands(result2.output) |
| 994 |
assert commands2 == { |
| 995 |
"serve", |
| 996 |
"inspect", |
| 997 |
"install", |
| 998 |
"package", |
| 999 |
"plugins", |
| 1000 |
"publish", |
| 1001 |
"uninstall", |
| 1002 |
"verify", |
| 1003 |
"unverify", |
| 1004 |
} |
| 1005 |
pm.unregister(name="verify") |
| 1006 |
importlib.reload(cli) |
| 1007 |
|
| 1008 |
|
| 1009 |
def test_hook_filters_from_request(app_client): |
| 1010 |
class ReturnNothingPlugin: |
| 1011 |
__name__ = "ReturnNothingPlugin" |
| 1012 |
|
| 1013 |
@hookimpl |
| 1014 |
def filters_from_request(self, request): |
| 1015 |
if request.args.get("_nothing"): |
| 1016 |
return FilterArguments(["1 = 0"], human_descriptions=["NOTHING"]) |
| 1017 |
|
| 1018 |
pm.register(ReturnNothingPlugin(), name="ReturnNothingPlugin") |
| 1019 |
response = app_client.get("/fixtures/facetable?_nothing=1") |
| 1020 |
assert "0 rows\n where NOTHING" in response.text |
| 1021 |
json_response = app_client.get("/fixtures/facetable.json?_nothing=1") |
| 1022 |
assert json_response.json["rows"] == [] |
| 1023 |
pm.unregister(name="ReturnNothingPlugin") |