Debian Codegraph @

tests/test_table_html.py

raw
1 from datasette.app import Datasette, Database
2 from bs4 import BeautifulSoup as Soup
3 from .fixtures import ( # noqa
4 app_client,
5 make_app_client,
6 )
7 import pathlib
8 import pytest
9 import urllib.parse
10 from .utils import assert_footer_links, inner_html
11
12
13 @pytest.mark.parametrize(
14 "path,expected_definition_sql",
15 [
16 (
17 "/fixtures/facet_cities",
18 """
19 CREATE TABLE facet_cities (
20 id integer primary key,
21 name text
22 );
23 """.strip(),
24 ),
25 (
26 "/fixtures/compound_three_primary_keys",
27 """
28 CREATE TABLE compound_three_primary_keys (
29 pk1 varchar(30),
30 pk2 varchar(30),
31 pk3 varchar(30),
32 content text,
33 PRIMARY KEY (pk1, pk2, pk3)
34 );
35 CREATE INDEX idx_compound_three_primary_keys_content ON compound_three_primary_keys(content);
36 """.strip(),
37 ),
38 ],
39 )
40 def test_table_definition_sql(path, expected_definition_sql, app_client):
41 response = app_client.get(path)
42 pre = Soup(response.body, "html.parser").select_one("pre.wrapped-sql")
43 assert expected_definition_sql == pre.string
44
45
46 def test_table_cell_truncation():
47 with make_app_client(settings={"truncate_cells_html": 5}) as client:
48 response = client.get("/fixtures/facetable")
49 assert response.status == 200
50 table = Soup(response.body, "html.parser").find("table")
51 assert table["class"] == ["rows-and-columns"]
52 assert [
53 "Missi…",
54 "Dogpa…",
55 "SOMA",
56 "Tende…",
57 "Berna…",
58 "Hayes…",
59 "Holly…",
60 "Downt…",
61 "Los F…",
62 "Korea…",
63 "Downt…",
64 "Greek…",
65 "Corkt…",
66 "Mexic…",
67 "Arcad…",
68 ] == [
69 td.string
70 for td in table.find_all("td", {"class": "col-neighborhood-b352a7"})
71 ]
72 # URLs should be truncated too
73 response2 = client.get("/fixtures/roadside_attractions")
74 assert response2.status == 200
75 table = Soup(response2.body, "html.parser").find("table")
76 tds = table.find_all("td", {"class": "col-url"})
77 assert [str(td) for td in tds] == [
78 '<td class="col-url type-str"><a href="https://www.mysteryspot.com/">http…</a></td>',
79 '<td class="col-url type-str"><a href="https://winchestermysteryhouse.com/">http…</a></td>',
80 '<td class="col-url type-none">\xa0</td>',
81 '<td class="col-url type-str"><a href="https://www.bigfootdiscoveryproject.com/">http…</a></td>',
82 ]
83
84
85 def test_add_filter_redirects(app_client):
86 filter_args = urllib.parse.urlencode(
87 {"_filter_column": "content", "_filter_op": "startswith", "_filter_value": "x"}
88 )
89 path_base = "/fixtures/simple_primary_key"
90 path = path_base + "?" + filter_args
91 response = app_client.get(path)
92 assert response.status == 302
93 assert response.headers["Location"].endswith("?content__startswith=x")
94
95 # Adding a redirect to an existing query string:
96 path = path_base + "?foo=bar&" + filter_args
97 response = app_client.get(path)
98 assert response.status == 302
99 assert response.headers["Location"].endswith("?foo=bar&content__startswith=x")
100
101 # Test that op with a __x suffix overrides the filter value
102 path = (
103 path_base
104 + "?"
105 + urllib.parse.urlencode(
106 {
107 "_filter_column": "content",
108 "_filter_op": "isnull__5",
109 "_filter_value": "x",
110 }
111 )
112 )
113 response = app_client.get(path)
114 assert response.status == 302
115 assert response.headers["Location"].endswith("?content__isnull=5")
116
117
118 def test_existing_filter_redirects(app_client):
119 filter_args = {
120 "_filter_column_1": "name",
121 "_filter_op_1": "contains",
122 "_filter_value_1": "hello",
123 "_filter_column_2": "age",
124 "_filter_op_2": "gte",
125 "_filter_value_2": "22",
126 "_filter_column_3": "age",
127 "_filter_op_3": "lt",
128 "_filter_value_3": "30",
129 "_filter_column_4": "name",
130 "_filter_op_4": "contains",
131 "_filter_value_4": "world",
132 }
133 path_base = "/fixtures/simple_primary_key"
134 path = path_base + "?" + urllib.parse.urlencode(filter_args)
135 response = app_client.get(path)
136 assert response.status == 302
137 assert_querystring_equal(
138 "name__contains=hello&age__gte=22&age__lt=30&name__contains=world",
139 response.headers["Location"].split("?")[1],
140 )
141
142 # Setting _filter_column_3 to empty string should remove *_3 entirely
143 filter_args["_filter_column_3"] = ""
144 path = path_base + "?" + urllib.parse.urlencode(filter_args)
145 response = app_client.get(path)
146 assert response.status == 302
147 assert_querystring_equal(
148 "name__contains=hello&age__gte=22&name__contains=world",
149 response.headers["Location"].split("?")[1],
150 )
151
152 # ?_filter_op=exact should be removed if unaccompanied by _fiter_column
153 response = app_client.get(path_base + "?_filter_op=exact")
154 assert response.status == 302
155 assert "?" not in response.headers["Location"]
156
157
158 @pytest.mark.parametrize(
159 "qs,expected_hidden",
160 (
161 # Things that should be reflected in hidden form fields:
162 ("_facet=_neighborhood", {"_facet": "_neighborhood"}),
163 ("_where=1+=+1&_col=_city_id", {"_where": "1 = 1", "_col": "_city_id"}),
164 # Things that should NOT be reflected in hidden form fields:
165 (
166 "_facet=_neighborhood&_neighborhood__exact=Downtown",
167 {"_facet": "_neighborhood"},
168 ),
169 ("_facet=_neighborhood&_city_id__gt=1", {"_facet": "_neighborhood"}),
170 ),
171 )
172 def test_reflected_hidden_form_fields(app_client, qs, expected_hidden):
173 # https://github.com/simonw/datasette/issues/1527
174 response = app_client.get("/fixtures/facetable?{}".format(qs))
175 # In this case we should NOT have a hidden _neighborhood__exact=Downtown field
176 form = Soup(response.body, "html.parser").find("form")
177 hidden_inputs = {
178 input["name"]: input["value"] for input in form.select("input[type=hidden]")
179 }
180 assert hidden_inputs == expected_hidden
181
182
183 def test_empty_search_parameter_gets_removed(app_client):
184 path_base = "/fixtures/simple_primary_key"
185 path = (
186 path_base
187 + "?"
188 + urllib.parse.urlencode(
189 {
190 "_search": "",
191 "_filter_column": "name",
192 "_filter_op": "exact",
193 "_filter_value": "chidi",
194 }
195 )
196 )
197 response = app_client.get(path)
198 assert response.status == 302
199 assert response.headers["Location"].endswith("?name__exact=chidi")
200
201
202 def test_searchable_view_persists_fts_table(app_client):
203 # The search form should persist ?_fts_table as a hidden field
204 response = app_client.get(
205 "/fixtures/searchable_view?_fts_table=searchable_fts&_fts_pk=pk"
206 )
207 inputs = Soup(response.body, "html.parser").find("form").find_all("input")
208 hiddens = [i for i in inputs if i["type"] == "hidden"]
209 assert [("_fts_table", "searchable_fts"), ("_fts_pk", "pk")] == [
210 (hidden["name"], hidden["value"]) for hidden in hiddens
211 ]
212
213
214 def test_sort_by_desc_redirects(app_client):
215 path_base = "/fixtures/sortable"
216 path = (
217 path_base
218 + "?"
219 + urllib.parse.urlencode({"_sort": "sortable", "_sort_by_desc": "1"})
220 )
221 response = app_client.get(path)
222 assert response.status == 302
223 assert response.headers["Location"].endswith("?_sort_desc=sortable")
224
225
226 def test_sort_links(app_client):
227 response = app_client.get("/fixtures/sortable?_sort=sortable")
228 assert response.status == 200
229 ths = Soup(response.body, "html.parser").find_all("th")
230 attrs_and_link_attrs = [
231 {
232 "attrs": th.attrs,
233 "a_href": (th.find("a")["href"] if th.find("a") else None),
234 }
235 for th in ths
236 ]
237 assert attrs_and_link_attrs == [
238 {
239 "attrs": {
240 "class": ["col-Link"],
241 "scope": "col",
242 "data-column": "Link",
243 "data-column-type": "",
244 "data-column-not-null": "0",
245 "data-is-pk": "0",
246 },
247 "a_href": None,
248 },
249 {
250 "attrs": {
251 "class": ["col-pk1"],
252 "scope": "col",
253 "data-column": "pk1",
254 "data-column-type": "varchar(30)",
255 "data-column-not-null": "0",
256 "data-is-pk": "1",
257 },
258 "a_href": None,
259 },
260 {
261 "attrs": {
262 "class": ["col-pk2"],
263 "scope": "col",
264 "data-column": "pk2",
265 "data-column-type": "varchar(30)",
266 "data-column-not-null": "0",
267 "data-is-pk": "1",
268 },
269 "a_href": None,
270 },
271 {
272 "attrs": {
273 "class": ["col-content"],
274 "scope": "col",
275 "data-column": "content",
276 "data-column-type": "text",
277 "data-column-not-null": "0",
278 "data-is-pk": "0",
279 },
280 "a_href": None,
281 },
282 {
283 "attrs": {
284 "class": ["col-sortable"],
285 "scope": "col",
286 "data-column": "sortable",
287 "data-column-type": "integer",
288 "data-column-not-null": "0",
289 "data-is-pk": "0",
290 },
291 "a_href": "/fixtures/sortable?_sort_desc=sortable",
292 },
293 {
294 "attrs": {
295 "class": ["col-sortable_with_nulls"],
296 "scope": "col",
297 "data-column": "sortable_with_nulls",
298 "data-column-type": "real",
299 "data-column-not-null": "0",
300 "data-is-pk": "0",
301 },
302 "a_href": "/fixtures/sortable?_sort=sortable_with_nulls",
303 },
304 {
305 "attrs": {
306 "class": ["col-sortable_with_nulls_2"],
307 "scope": "col",
308 "data-column": "sortable_with_nulls_2",
309 "data-column-type": "real",
310 "data-column-not-null": "0",
311 "data-is-pk": "0",
312 },
313 "a_href": "/fixtures/sortable?_sort=sortable_with_nulls_2",
314 },
315 {
316 "attrs": {
317 "class": ["col-text"],
318 "scope": "col",
319 "data-column": "text",
320 "data-column-type": "text",
321 "data-column-not-null": "0",
322 "data-is-pk": "0",
323 },
324 "a_href": "/fixtures/sortable?_sort=text",
325 },
326 ]
327
328
329 def test_facet_display(app_client):
330 response = app_client.get(
331 "/fixtures/facetable?_facet=planet_int&_facet=_city_id&_facet=on_earth"
332 )
333 assert response.status == 200
334 soup = Soup(response.body, "html.parser")
335 divs = soup.find("div", {"class": "facet-results"}).find_all("div")
336 actual = []
337 for div in divs:
338 actual.append(
339 {
340 "name": div.find("strong").text.split()[0],
341 "items": [
342 {
343 "name": a.text,
344 "qs": a["href"].split("?")[-1],
345 "count": int(str(a.parent).split("</a>")[1].split("<")[0]),
346 }
347 for a in div.find("ul").find_all("a")
348 ],
349 }
350 )
351 assert actual == [
352 {
353 "name": "_city_id",
354 "items": [
355 {
356 "name": "San Francisco",
357 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=1",
358 "count": 6,
359 },
360 {
361 "name": "Los Angeles",
362 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=2",
363 "count": 4,
364 },
365 {
366 "name": "Detroit",
367 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=3",
368 "count": 4,
369 },
370 {
371 "name": "Memnonia",
372 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=4",
373 "count": 1,
374 },
375 ],
376 },
377 {
378 "name": "planet_int",
379 "items": [
380 {
381 "name": "1",
382 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&planet_int=1",
383 "count": 14,
384 },
385 {
386 "name": "2",
387 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&planet_int=2",
388 "count": 1,
389 },
390 ],
391 },
392 {
393 "name": "on_earth",
394 "items": [
395 {
396 "name": "1",
397 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&on_earth=1",
398 "count": 14,
399 },
400 {
401 "name": "0",
402 "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&on_earth=0",
403 "count": 1,
404 },
405 ],
406 },
407 ]
408
409
410 def test_facets_persist_through_filter_form(app_client):
411 response = app_client.get(
412 "/fixtures/facetable?_facet=planet_int&_facet=_city_id&_facet_array=tags"
413 )
414 assert response.status == 200
415 inputs = Soup(response.body, "html.parser").find("form").find_all("input")
416 hiddens = [i for i in inputs if i["type"] == "hidden"]
417 assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == [
418 ("_facet", "planet_int"),
419 ("_facet", "_city_id"),
420 ("_facet_array", "tags"),
421 ]
422
423
424 def test_next_does_not_persist_in_hidden_field(app_client):
425 response = app_client.get("/fixtures/searchable?_size=1&_next=1")
426 assert response.status == 200
427 inputs = Soup(response.body, "html.parser").find("form").find_all("input")
428 hiddens = [i for i in inputs if i["type"] == "hidden"]
429 assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == [
430 ("_size", "1"),
431 ]
432
433
434 def test_table_html_simple_primary_key(app_client):
435 response = app_client.get("/fixtures/simple_primary_key?_size=3")
436 assert response.status == 200
437 table = Soup(response.body, "html.parser").find("table")
438 assert table["class"] == ["rows-and-columns"]
439 ths = table.find_all("th")
440 assert "id\xa0▼" == ths[0].find("a").string.strip()
441 for expected_col, th in zip(("content",), ths[1:]):
442 a = th.find("a")
443 assert expected_col == a.string
444 assert a["href"].endswith(f"/simple_primary_key?_size=3&_sort={expected_col}")
445 assert ["nofollow"] == a["rel"]
446 assert [
447 [
448 '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/1">1</a></td>',
449 '<td class="col-content type-str">hello</td>',
450 ],
451 [
452 '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/2">2</a></td>',
453 '<td class="col-content type-str">world</td>',
454 ],
455 [
456 '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/3">3</a></td>',
457 '<td class="col-content type-str">\xa0</td>',
458 ],
459 ] == [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
460
461
462 def test_table_csv_json_export_interface(app_client):
463 response = app_client.get("/fixtures/simple_primary_key?id__gt=2")
464 assert response.status == 200
465 # The links at the top of the page
466 links = (
467 Soup(response.body, "html.parser")
468 .find("p", {"class": "export-links"})
469 .find_all("a")
470 )
471 actual = [l["href"] for l in links]
472 expected = [
473 "/fixtures/simple_primary_key.json?id__gt=2",
474 "/fixtures/simple_primary_key.testall?id__gt=2",
475 "/fixtures/simple_primary_key.testnone?id__gt=2",
476 "/fixtures/simple_primary_key.testresponse?id__gt=2",
477 "/fixtures/simple_primary_key.csv?id__gt=2&_size=max",
478 "#export",
479 ]
480 assert expected == actual
481 # And the advaced export box at the bottom:
482 div = Soup(response.body, "html.parser").find("div", {"class": "advanced-export"})
483 json_links = [a["href"] for a in div.find("p").find_all("a")]
484 assert [
485 "/fixtures/simple_primary_key.json?id__gt=2",
486 "/fixtures/simple_primary_key.json?id__gt=2&_shape=array",
487 "/fixtures/simple_primary_key.json?id__gt=2&_shape=array&_nl=on",
488 "/fixtures/simple_primary_key.json?id__gt=2&_shape=object",
489 ] == json_links
490 # And the CSV form
491 form = div.find("form")
492 assert form["action"].endswith("/simple_primary_key.csv")
493 inputs = [str(input) for input in form.find_all("input")]
494 assert [
495 '<input name="_dl" type="checkbox"/>',
496 '<input type="submit" value="Export CSV"/>',
497 '<input name="id__gt" type="hidden" value="2"/>',
498 '<input name="_size" type="hidden" value="max"/>',
499 ] == inputs
500
501
502 def test_csv_json_export_links_include_labels_if_foreign_keys(app_client):
503 response = app_client.get("/fixtures/facetable")
504 assert response.status == 200
505 links = (
506 Soup(response.body, "html.parser")
507 .find("p", {"class": "export-links"})
508 .find_all("a")
509 )
510 actual = [l["href"] for l in links]
511 expected = [
512 "/fixtures/facetable.json?_labels=on",
513 "/fixtures/facetable.testall?_labels=on",
514 "/fixtures/facetable.testnone?_labels=on",
515 "/fixtures/facetable.testresponse?_labels=on",
516 "/fixtures/facetable.csv?_labels=on&_size=max",
517 "#export",
518 ]
519 assert expected == actual
520
521
522 def test_table_not_exists(app_client):
523 assert "Table not found" in app_client.get("/fixtures/blah").text
524
525
526 def test_table_html_no_primary_key(app_client):
527 response = app_client.get("/fixtures/no_primary_key")
528 assert response.status == 200
529 table = Soup(response.body, "html.parser").find("table")
530 # We have disabled sorting for this table using metadata.json
531 assert ["content", "a", "b", "c"] == [
532 th.string.strip() for th in table.select("thead th")[2:]
533 ]
534 expected = [
535 [
536 '<td class="col-Link type-pk"><a href="/fixtures/no_primary_key/{}">{}</a></td>'.format(
537 i, i
538 ),
539 f'<td class="col-rowid type-int">{i}</td>',
540 f'<td class="col-content type-str">{i}</td>',
541 f'<td class="col-a type-str">a{i}</td>',
542 f'<td class="col-b type-str">b{i}</td>',
543 f'<td class="col-c type-str">c{i}</td>',
544 ]
545 for i in range(1, 51)
546 ]
547 assert expected == [
548 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
549 ]
550
551
552 def test_rowid_sortable_no_primary_key(app_client):
553 response = app_client.get("/fixtures/no_primary_key")
554 assert response.status == 200
555 table = Soup(response.body, "html.parser").find("table")
556 assert table["class"] == ["rows-and-columns"]
557 ths = table.find_all("th")
558 assert "rowid\xa0▼" == ths[1].find("a").string.strip()
559
560
561 def test_table_html_compound_primary_key(app_client):
562 response = app_client.get("/fixtures/compound_primary_key")
563 assert response.status == 200
564 table = Soup(response.body, "html.parser").find("table")
565 ths = table.find_all("th")
566 assert "Link" == ths[0].string.strip()
567 for expected_col, th in zip(("pk1", "pk2", "content"), ths[1:]):
568 a = th.find("a")
569 assert expected_col == a.string
570 assert th["class"] == [f"col-{expected_col}"]
571 assert a["href"].endswith(f"/compound_primary_key?_sort={expected_col}")
572 expected = [
573 [
574 '<td class="col-Link type-pk"><a href="/fixtures/compound_primary_key/a,b">a,b</a></td>',
575 '<td class="col-pk1 type-str">a</td>',
576 '<td class="col-pk2 type-str">b</td>',
577 '<td class="col-content type-str">c</td>',
578 ],
579 [
580 '<td class="col-Link type-pk"><a href="/fixtures/compound_primary_key/a~2Fb,~2Ec-d">a/b,.c-d</a></td>',
581 '<td class="col-pk1 type-str">a/b</td>',
582 '<td class="col-pk2 type-str">.c-d</td>',
583 '<td class="col-content type-str">c</td>',
584 ],
585 ]
586 assert [
587 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
588 ] == expected
589
590
591 def test_table_html_foreign_key_links(app_client):
592 response = app_client.get("/fixtures/foreign_key_references")
593 assert response.status == 200
594 table = Soup(response.body, "html.parser").find("table")
595 actual = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
596 assert actual == [
597 [
598 '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/1">1</a></td>',
599 '<td class="col-foreign_key_with_label type-str"><a href="/fixtures/simple_primary_key/1">hello</a>\xa0<em>1</em></td>',
600 '<td class="col-foreign_key_with_blank_label type-str"><a href="/fixtures/simple_primary_key/3">-</a>\xa0<em>3</em></td>',
601 '<td class="col-foreign_key_with_no_label type-str"><a href="/fixtures/primary_key_multiple_columns/1">1</a></td>',
602 '<td class="col-foreign_key_compound_pk1 type-str">a</td>',
603 '<td class="col-foreign_key_compound_pk2 type-str">b</td>',
604 ],
605 [
606 '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/2">2</a></td>',
607 '<td class="col-foreign_key_with_label type-none">\xa0</td>',
608 '<td class="col-foreign_key_with_blank_label type-none">\xa0</td>',
609 '<td class="col-foreign_key_with_no_label type-none">\xa0</td>',
610 '<td class="col-foreign_key_compound_pk1 type-none">\xa0</td>',
611 '<td class="col-foreign_key_compound_pk2 type-none">\xa0</td>',
612 ],
613 ]
614
615
616 def test_table_html_foreign_key_facets(app_client):
617 response = app_client.get(
618 "/fixtures/foreign_key_references?_facet=foreign_key_with_blank_label"
619 )
620 assert response.status == 200
621 assert (
622 '<li><a href="http://localhost/fixtures/foreign_key_references?_facet=foreign_key_with_blank_label&amp;foreign_key_with_blank_label=3">'
623 "-</a> 1</li>"
624 ) in response.text
625
626
627 def test_table_html_disable_foreign_key_links_with_labels(app_client):
628 response = app_client.get("/fixtures/foreign_key_references?_labels=off&_size=1")
629 assert response.status == 200
630 table = Soup(response.body, "html.parser").find("table")
631 actual = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
632 assert actual == [
633 [
634 '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/1">1</a></td>',
635 '<td class="col-foreign_key_with_label type-str">1</td>',
636 '<td class="col-foreign_key_with_blank_label type-str">3</td>',
637 '<td class="col-foreign_key_with_no_label type-str">1</td>',
638 '<td class="col-foreign_key_compound_pk1 type-str">a</td>',
639 '<td class="col-foreign_key_compound_pk2 type-str">b</td>',
640 ]
641 ]
642
643
644 def test_table_html_foreign_key_custom_label_column(app_client):
645 response = app_client.get("/fixtures/custom_foreign_key_label")
646 assert response.status == 200
647 table = Soup(response.body, "html.parser").find("table")
648 expected = [
649 [
650 '<td class="col-pk type-pk"><a href="/fixtures/custom_foreign_key_label/1">1</a></td>',
651 '<td class="col-foreign_key_with_custom_label type-str"><a href="/fixtures/primary_key_multiple_columns_explicit_label/1">world2</a>\xa0<em>1</em></td>',
652 ]
653 ]
654 assert expected == [
655 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
656 ]
657
658
659 @pytest.mark.parametrize(
660 "path,expected_column_options",
661 [
662 ("/fixtures/infinity", ["- column -", "rowid", "value"]),
663 (
664 "/fixtures/primary_key_multiple_columns",
665 ["- column -", "id", "content", "content2"],
666 ),
667 ("/fixtures/compound_primary_key", ["- column -", "pk1", "pk2", "content"]),
668 ],
669 )
670 def test_table_html_filter_form_column_options(
671 path, expected_column_options, app_client
672 ):
673 response = app_client.get(path)
674 assert response.status == 200
675 form = Soup(response.body, "html.parser").find("form")
676 column_options = [
677 o.attrs.get("value") or o.string
678 for o in form.select("select[name=_filter_column] option")
679 ]
680 assert expected_column_options == column_options
681
682
683 def test_table_html_filter_form_still_shows_nocol_columns(app_client):
684 # https://github.com/simonw/datasette/issues/1503
685 response = app_client.get("/fixtures/sortable?_nocol=sortable")
686 assert response.status == 200
687 form = Soup(response.body, "html.parser").find("form")
688 assert [
689 o.string
690 for o in form.select("select[name='_filter_column']")[0].select("option")
691 ] == [
692 "- column -",
693 "pk1",
694 "pk2",
695 "content",
696 "sortable_with_nulls",
697 "sortable_with_nulls_2",
698 "text",
699 # Moved to the end because it is no longer returned by the query:
700 "sortable",
701 ]
702
703
704 def test_compound_primary_key_with_foreign_key_references(app_client):
705 # e.g. a many-to-many table with a compound primary key on the two columns
706 response = app_client.get("/fixtures/searchable_tags")
707 assert response.status == 200
708 table = Soup(response.body, "html.parser").find("table")
709 expected = [
710 [
711 '<td class="col-Link type-pk"><a href="/fixtures/searchable_tags/1,feline">1,feline</a></td>',
712 '<td class="col-searchable_id type-int"><a href="/fixtures/searchable/1">1</a>\xa0<em>1</em></td>',
713 '<td class="col-tag type-str"><a href="/fixtures/tags/feline">feline</a></td>',
714 ],
715 [
716 '<td class="col-Link type-pk"><a href="/fixtures/searchable_tags/2,canine">2,canine</a></td>',
717 '<td class="col-searchable_id type-int"><a href="/fixtures/searchable/2">2</a>\xa0<em>2</em></td>',
718 '<td class="col-tag type-str"><a href="/fixtures/tags/canine">canine</a></td>',
719 ],
720 ]
721 assert expected == [
722 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
723 ]
724
725
726 def test_view_html(app_client):
727 response = app_client.get("/fixtures/simple_view?_size=3")
728 assert response.status == 200
729 table = Soup(response.body, "html.parser").find("table")
730 ths = table.select("thead th")
731 assert 2 == len(ths)
732 assert ths[0].find("a") is not None
733 assert ths[0].find("a")["href"].endswith("/simple_view?_size=3&_sort=content")
734 assert ths[0].find("a").string.strip() == "content"
735 assert ths[1].find("a") is None
736 assert ths[1].string.strip() == "upper_content"
737 expected = [
738 [
739 '<td class="col-content type-str">hello</td>',
740 '<td class="col-upper_content type-str">HELLO</td>',
741 ],
742 [
743 '<td class="col-content type-str">world</td>',
744 '<td class="col-upper_content type-str">WORLD</td>',
745 ],
746 [
747 '<td class="col-content type-str">\xa0</td>',
748 '<td class="col-upper_content type-str">\xa0</td>',
749 ],
750 ]
751 assert expected == [
752 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
753 ]
754
755
756 def test_table_metadata(app_client):
757 response = app_client.get("/fixtures/simple_primary_key")
758 assert response.status == 200
759 soup = Soup(response.body, "html.parser")
760 # Page title should be custom and should be HTML escaped
761 assert "This &lt;em&gt;HTML&lt;/em&gt; is escaped" == inner_html(soup.find("h1"))
762 # Description should be custom and NOT escaped (we used description_html)
763 assert "Simple <em>primary</em> key" == inner_html(
764 soup.find("div", {"class": "metadata-description"})
765 )
766 # The source/license should be inherited
767 assert_footer_links(soup)
768
769
770 @pytest.mark.parametrize(
771 "path,has_object,has_stream,has_expand",
772 [
773 ("/fixtures/no_primary_key", False, True, False),
774 ("/fixtures/complex_foreign_keys", True, False, True),
775 ],
776 )
777 def test_advanced_export_box(app_client, path, has_object, has_stream, has_expand):
778 response = app_client.get(path)
779 assert response.status == 200
780 soup = Soup(response.body, "html.parser")
781 # JSON shape options
782 expected_json_shapes = ["default", "array", "newline-delimited"]
783 if has_object:
784 expected_json_shapes.append("object")
785 div = soup.find("div", {"class": "advanced-export"})
786 assert expected_json_shapes == [a.text for a in div.find("p").find_all("a")]
787 # "stream all rows" option
788 if has_stream:
789 assert "stream all rows" in str(div)
790 # "expand labels" option
791 if has_expand:
792 assert "expand labels" in str(div)
793
794
795 def test_extra_where_clauses(app_client):
796 response = app_client.get(
797 "/fixtures/facetable?_where=_neighborhood='Dogpatch'&_where=_city_id=1"
798 )
799 soup = Soup(response.body, "html.parser")
800 div = soup.select(".extra-wheres")[0]
801 assert "2 extra where clauses" == div.find("h3").text
802 hrefs = [a["href"] for a in div.find_all("a")]
803 assert [
804 "/fixtures/facetable?_where=_city_id%3D1",
805 "/fixtures/facetable?_where=_neighborhood%3D%27Dogpatch%27",
806 ] == hrefs
807 # These should also be persisted as hidden fields
808 inputs = soup.find("form").find_all("input")
809 hiddens = [i for i in inputs if i["type"] == "hidden"]
810 assert [("_where", "_neighborhood='Dogpatch'"), ("_where", "_city_id=1")] == [
811 (hidden["name"], hidden["value"]) for hidden in hiddens
812 ]
813
814
815 @pytest.mark.parametrize(
816 "path,expected_hidden",
817 [
818 ("/fixtures/facetable?_size=10", [("_size", "10")]),
819 (
820 "/fixtures/facetable?_size=10&_ignore=1&_ignore=2",
821 [
822 ("_size", "10"),
823 ("_ignore", "1"),
824 ("_ignore", "2"),
825 ],
826 ),
827 ],
828 )
829 def test_other_hidden_form_fields(app_client, path, expected_hidden):
830 response = app_client.get(path)
831 soup = Soup(response.body, "html.parser")
832 inputs = soup.find("form").find_all("input")
833 hiddens = [i for i in inputs if i["type"] == "hidden"]
834 assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == expected_hidden
835
836
837 @pytest.mark.parametrize(
838 "path,expected_hidden",
839 [
840 ("/fixtures/searchable?_search=terry", []),
841 ("/fixtures/searchable?_sort=text2", []),
842 ("/fixtures/searchable?_sort_desc=text2", []),
843 ("/fixtures/searchable?_sort=text2&_where=1", [("_where", "1")]),
844 ],
845 )
846 def test_search_and_sort_fields_not_duplicated(app_client, path, expected_hidden):
847 # https://github.com/simonw/datasette/issues/1214
848 response = app_client.get(path)
849 soup = Soup(response.body, "html.parser")
850 inputs = soup.find("form").find_all("input")
851 hiddens = [i for i in inputs if i["type"] == "hidden"]
852 assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == expected_hidden
853
854
855 def test_binary_data_display_in_table(app_client):
856 response = app_client.get("/fixtures/binary_data")
857 assert response.status == 200
858 table = Soup(response.body, "html.parser").find("table")
859 expected_tds = [
860 [
861 '<td class="col-Link type-pk"><a href="/fixtures/binary_data/1">1</a></td>',
862 '<td class="col-rowid type-int">1</td>',
863 '<td class="col-data type-bytes"><a class="blob-download" href="/fixtures/binary_data/1.blob?_blob_column=data">&lt;Binary:\xa07\xa0bytes&gt;</a></td>',
864 ],
865 [
866 '<td class="col-Link type-pk"><a href="/fixtures/binary_data/2">2</a></td>',
867 '<td class="col-rowid type-int">2</td>',
868 '<td class="col-data type-bytes"><a class="blob-download" href="/fixtures/binary_data/2.blob?_blob_column=data">&lt;Binary:\xa07\xa0bytes&gt;</a></td>',
869 ],
870 [
871 '<td class="col-Link type-pk"><a href="/fixtures/binary_data/3">3</a></td>',
872 '<td class="col-rowid type-int">3</td>',
873 '<td class="col-data type-none">\xa0</td>',
874 ],
875 ]
876 assert expected_tds == [
877 [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
878 ]
879
880
881 def test_custom_table_include():
882 with make_app_client(
883 template_dir=str(pathlib.Path(__file__).parent / "test_templates")
884 ) as client:
885 response = client.get("/fixtures/complex_foreign_keys")
886 assert response.status == 200
887 assert (
888 '<div class="custom-table-row">'
889 '1 - 2 - <a href="/fixtures/simple_primary_key/1">hello</a> <em>1</em>'
890 "</div>"
891 ) == str(Soup(response.text, "html.parser").select_one("div.custom-table-row"))
892
893
894 def test_metadata_sort(app_client):
895 response = app_client.get("/fixtures/facet_cities")
896 assert response.status == 200
897 table = Soup(response.body, "html.parser").find("table")
898 assert table["class"] == ["rows-and-columns"]
899 ths = table.find_all("th")
900 assert ["id", "name\xa0▼"] == [th.find("a").string.strip() for th in ths]
901 rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
902 expected = [
903 [
904 '<td class="col-id type-pk"><a href="/fixtures/facet_cities/3">3</a></td>',
905 '<td class="col-name type-str">Detroit</td>',
906 ],
907 [
908 '<td class="col-id type-pk"><a href="/fixtures/facet_cities/2">2</a></td>',
909 '<td class="col-name type-str">Los Angeles</td>',
910 ],
911 [
912 '<td class="col-id type-pk"><a href="/fixtures/facet_cities/4">4</a></td>',
913 '<td class="col-name type-str">Memnonia</td>',
914 ],
915 [
916 '<td class="col-id type-pk"><a href="/fixtures/facet_cities/1">1</a></td>',
917 '<td class="col-name type-str">San Francisco</td>',
918 ],
919 ]
920 assert expected == rows
921 # Make sure you can reverse that sort order
922 response = app_client.get("/fixtures/facet_cities?_sort_desc=name")
923 assert response.status == 200
924 table = Soup(response.body, "html.parser").find("table")
925 rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
926 assert list(reversed(expected)) == rows
927
928
929 def test_metadata_sort_desc(app_client):
930 response = app_client.get("/fixtures/attraction_characteristic")
931 assert response.status == 200
932 table = Soup(response.body, "html.parser").find("table")
933 assert table["class"] == ["rows-and-columns"]
934 ths = table.find_all("th")
935 assert ["pk\xa0▲", "name"] == [th.find("a").string.strip() for th in ths]
936 rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
937 expected = [
938 [
939 '<td class="col-pk type-pk"><a href="/fixtures/attraction_characteristic/2">2</a></td>',
940 '<td class="col-name type-str">Paranormal</td>',
941 ],
942 [
943 '<td class="col-pk type-pk"><a href="/fixtures/attraction_characteristic/1">1</a></td>',
944 '<td class="col-name type-str">Museum</td>',
945 ],
946 ]
947 assert expected == rows
948 # Make sure you can reverse that sort order
949 response = app_client.get("/fixtures/attraction_characteristic?_sort=pk")
950 assert response.status == 200
951 table = Soup(response.body, "html.parser").find("table")
952 rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
953 assert list(reversed(expected)) == rows
954
955
956 @pytest.mark.parametrize(
957 "max_returned_rows,path,expected_num_facets,expected_ellipses,expected_ellipses_url",
958 (
959 (
960 5,
961 # Default should show 2 facets
962 "/fixtures/facetable?_facet=_neighborhood",
963 2,
964 True,
965 "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
966 ),
967 # _facet_size above max_returned_rows should show max_returned_rows (5)
968 (
969 5,
970 "/fixtures/facetable?_facet=_neighborhood&_facet_size=50",
971 5,
972 True,
973 "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
974 ),
975 # If max_returned_rows is high enough, should return all
976 (
977 20,
978 "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
979 14,
980 False,
981 None,
982 ),
983 # If num facets > max_returned_rows, show ... without a link
984 # _facet_size above max_returned_rows should show max_returned_rows (5)
985 (
986 5,
987 "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
988 5,
989 True,
990 None,
991 ),
992 ),
993 )
994 def test_facet_more_links(
995 max_returned_rows,
996 path,
997 expected_num_facets,
998 expected_ellipses,
999 expected_ellipses_url,
1000 ):
1001 with make_app_client(
1002 settings={"max_returned_rows": max_returned_rows, "default_facet_size": 2}
1003 ) as client:
1004 response = client.get(path)
1005 soup = Soup(response.body, "html.parser")
1006 lis = soup.select("#facet-neighborhood-b352a7 ul li:not(.facet-truncated)")
1007 facet_truncated = soup.select_one(".facet-truncated")
1008 assert len(lis) == expected_num_facets
1009 if not expected_ellipses:
1010 assert facet_truncated is None
1011 else:
1012 if expected_ellipses_url:
1013 assert facet_truncated.find("a")["href"] == expected_ellipses_url
1014 else:
1015 assert facet_truncated.find("a") is None
1016
1017
1018 def test_unavailable_table_does_not_break_sort_relationships():
1019 # https://github.com/simonw/datasette/issues/1305
1020 with make_app_client(
1021 metadata={
1022 "databases": {
1023 "fixtures": {"tables": {"foreign_key_references": {"allow": False}}}
1024 }
1025 }
1026 ) as client:
1027 response = client.get("/?_sort=relationships")
1028 assert response.status == 200
1029
1030
1031 def test_column_metadata(app_client):
1032 response = app_client.get("/fixtures/roadside_attractions")
1033 soup = Soup(response.body, "html.parser")
1034 dl = soup.find("dl")
1035 assert [(dt.text, dt.next_sibling.text) for dt in dl.find_all("dt")] == [
1036 ("name", "The name of the attraction"),
1037 ("address", "The street address for the attraction"),
1038 ]
1039 assert (
1040 soup.select("th[data-column=name]")[0]["data-column-description"]
1041 == "The name of the attraction"
1042 )
1043 assert (
1044 soup.select("th[data-column=address]")[0]["data-column-description"]
1045 == "The street address for the attraction"
1046 )
1047
1048
1049 def test_facet_total():
1050 # https://github.com/simonw/datasette/issues/1423
1051 # https://github.com/simonw/datasette/issues/1556
1052 with make_app_client(settings={"max_returned_rows": 100}) as client:
1053 path = "/fixtures/sortable?_facet=content&_facet=pk1"
1054 response = client.get(path)
1055 assert response.status == 200
1056 fragments = (
1057 '<span class="facet-info-total">&gt;30</span>',
1058 '<span class="facet-info-total">8</span>',
1059 )
1060 for fragment in fragments:
1061 assert fragment in response.text
1062
1063
1064 def test_sort_rowid_with_next(app_client):
1065 # https://github.com/simonw/datasette/issues/1470
1066 response = app_client.get("/fixtures/binary_data?_size=1&_next=1&_sort=rowid")
1067 assert response.status == 200
1068
1069
1070 def assert_querystring_equal(expected, actual):
1071 assert sorted(expected.split("&")) == sorted(actual.split("&"))
1072
1073
1074 @pytest.mark.parametrize(
1075 "path,expected",
1076 (
1077 (
1078 "/fixtures/facetable",
1079 "fixtures: facetable: 15 rows",
1080 ),
1081 (
1082 "/fixtures/facetable?on_earth__exact=1",
1083 "fixtures: facetable: 14 rows where on_earth = 1",
1084 ),
1085 ),
1086 )
1087 def test_table_page_title(app_client, path, expected):
1088 response = app_client.get(path)
1089 title = Soup(response.text, "html.parser").find("title").text
1090 assert title == expected
1091
1092
1093 @pytest.mark.parametrize("allow_facet", (True, False))
1094 def test_allow_facet_off(allow_facet):
1095 with make_app_client(settings={"allow_facet": allow_facet}) as client:
1096 response = client.get("/fixtures/facetable")
1097 expected = "DATASETTE_ALLOW_FACET = {};".format(
1098 "true" if allow_facet else "false"
1099 )
1100 assert expected in response.text
1101 if allow_facet:
1102 assert "Suggested facets" in response.text
1103 else:
1104 assert "Suggested facets" not in response.text
1105
1106
1107 @pytest.mark.asyncio
1108 @pytest.mark.parametrize(
1109 "size,title,length_bytes",
1110 (
1111 (2000, ' title="2.0 KB"', "2,000"),
1112 (20000, ' title="19.5 KB"', "20,000"),
1113 (20, "", "20"),
1114 ),
1115 )
1116 async def test_format_of_binary_links(size, title, length_bytes):
1117 ds = Datasette()
1118 db_name = "binary-links-{}".format(size)
1119 db = ds.add_memory_database(db_name)
1120 sql = "select zeroblob({}) as blob".format(size)
1121 await db.execute_write("create table blobs as {}".format(sql))
1122 response = await ds.client.get("/{}/blobs".format(db_name))
1123 assert response.status_code == 200
1124 expected = "{}>&lt;Binary:&nbsp;{}&nbsp;bytes&gt;</a>".format(title, length_bytes)
1125 assert expected in response.text
1126 # And test with arbitrary SQL query too
1127 sql_response = await ds.client.get("/{}".format(db_name), params={"sql": sql})
1128 assert sql_response.status_code == 200
1129 assert expected in sql_response.text