Debian Codegraph @

tests/test_api.py

raw
1 from datasette.app import Datasette
2 from datasette.plugins import DEFAULT_PLUGINS
3 from datasette.utils.sqlite import supports_table_xinfo
4 from datasette.version import __version__
5 from .fixtures import ( # noqa
6 app_client,
7 app_client_no_files,
8 app_client_with_dot,
9 app_client_shorter_time_limit,
10 app_client_two_attached_databases_one_immutable,
11 app_client_larger_cache_size,
12 app_client_with_cors,
13 app_client_two_attached_databases,
14 app_client_conflicting_database_names,
15 app_client_immutable_and_inspect_file,
16 make_app_client,
17 EXPECTED_PLUGINS,
18 METADATA,
19 )
20 import pathlib
21 import pytest
22 import sys
23 import urllib
24
25
26 def test_homepage(app_client):
27 response = app_client.get("/.json")
28 assert response.status == 200
29 assert "application/json; charset=utf-8" == response.headers["content-type"]
30 assert response.json.keys() == {"fixtures": 0}.keys()
31 d = response.json["fixtures"]
32 assert d["name"] == "fixtures"
33 assert d["tables_count"] == 24
34 assert len(d["tables_and_views_truncated"]) == 5
35 assert d["tables_and_views_more"] is True
36 # 4 hidden FTS tables + no_primary_key (hidden in metadata)
37 assert d["hidden_tables_count"] == 6
38 # 201 in no_primary_key, plus 6 in other hidden tables:
39 assert d["hidden_table_rows_sum"] == 207, response.json
40 assert d["views_count"] == 4
41
42
43 def test_homepage_sort_by_relationships(app_client):
44 response = app_client.get("/.json?_sort=relationships")
45 assert response.status == 200
46 tables = [
47 t["name"] for t in response.json["fixtures"]["tables_and_views_truncated"]
48 ]
49 assert tables == [
50 "simple_primary_key",
51 "foreign_key_references",
52 "complex_foreign_keys",
53 "roadside_attraction_characteristics",
54 "searchable_tags",
55 ]
56
57
58 def test_database_page(app_client):
59 response = app_client.get("/fixtures.json")
60 assert response.status == 200
61 data = response.json
62 assert data["database"] == "fixtures"
63 assert data["tables"] == [
64 {
65 "name": "123_starts_with_digits",
66 "columns": ["content"],
67 "primary_keys": [],
68 "count": 0,
69 "hidden": False,
70 "fts_table": None,
71 "foreign_keys": {"incoming": [], "outgoing": []},
72 "private": False,
73 },
74 {
75 "name": "Table With Space In Name",
76 "columns": ["pk", "content"],
77 "primary_keys": ["pk"],
78 "count": 0,
79 "hidden": False,
80 "fts_table": None,
81 "foreign_keys": {"incoming": [], "outgoing": []},
82 "private": False,
83 },
84 {
85 "name": "attraction_characteristic",
86 "columns": ["pk", "name"],
87 "primary_keys": ["pk"],
88 "count": 2,
89 "hidden": False,
90 "fts_table": None,
91 "foreign_keys": {
92 "incoming": [
93 {
94 "other_table": "roadside_attraction_characteristics",
95 "column": "pk",
96 "other_column": "characteristic_id",
97 }
98 ],
99 "outgoing": [],
100 },
101 "private": False,
102 },
103 {
104 "name": "binary_data",
105 "columns": ["data"],
106 "primary_keys": [],
107 "count": 3,
108 "hidden": False,
109 "fts_table": None,
110 "foreign_keys": {"incoming": [], "outgoing": []},
111 "private": False,
112 },
113 {
114 "name": "complex_foreign_keys",
115 "columns": ["pk", "f1", "f2", "f3"],
116 "primary_keys": ["pk"],
117 "count": 1,
118 "hidden": False,
119 "fts_table": None,
120 "foreign_keys": {
121 "incoming": [],
122 "outgoing": [
123 {
124 "other_table": "simple_primary_key",
125 "column": "f3",
126 "other_column": "id",
127 },
128 {
129 "other_table": "simple_primary_key",
130 "column": "f2",
131 "other_column": "id",
132 },
133 {
134 "other_table": "simple_primary_key",
135 "column": "f1",
136 "other_column": "id",
137 },
138 ],
139 },
140 "private": False,
141 },
142 {
143 "name": "compound_primary_key",
144 "columns": ["pk1", "pk2", "content"],
145 "primary_keys": ["pk1", "pk2"],
146 "count": 2,
147 "hidden": False,
148 "fts_table": None,
149 "foreign_keys": {"incoming": [], "outgoing": []},
150 "private": False,
151 },
152 {
153 "name": "compound_three_primary_keys",
154 "columns": ["pk1", "pk2", "pk3", "content"],
155 "primary_keys": ["pk1", "pk2", "pk3"],
156 "count": 1001,
157 "hidden": False,
158 "fts_table": None,
159 "foreign_keys": {"incoming": [], "outgoing": []},
160 "private": False,
161 },
162 {
163 "name": "custom_foreign_key_label",
164 "columns": ["pk", "foreign_key_with_custom_label"],
165 "primary_keys": ["pk"],
166 "count": 1,
167 "hidden": False,
168 "fts_table": None,
169 "foreign_keys": {
170 "incoming": [],
171 "outgoing": [
172 {
173 "other_table": "primary_key_multiple_columns_explicit_label",
174 "column": "foreign_key_with_custom_label",
175 "other_column": "id",
176 }
177 ],
178 },
179 "private": False,
180 },
181 {
182 "name": "facet_cities",
183 "columns": ["id", "name"],
184 "primary_keys": ["id"],
185 "count": 4,
186 "hidden": False,
187 "fts_table": None,
188 "foreign_keys": {
189 "incoming": [
190 {
191 "other_table": "facetable",
192 "column": "id",
193 "other_column": "_city_id",
194 }
195 ],
196 "outgoing": [],
197 },
198 "private": False,
199 },
200 {
201 "name": "facetable",
202 "columns": [
203 "pk",
204 "created",
205 "planet_int",
206 "on_earth",
207 "state",
208 "_city_id",
209 "_neighborhood",
210 "tags",
211 "complex_array",
212 "distinct_some_null",
213 "n",
214 ],
215 "primary_keys": ["pk"],
216 "count": 15,
217 "hidden": False,
218 "fts_table": None,
219 "foreign_keys": {
220 "incoming": [],
221 "outgoing": [
222 {
223 "other_table": "facet_cities",
224 "column": "_city_id",
225 "other_column": "id",
226 }
227 ],
228 },
229 "private": False,
230 },
231 {
232 "name": "foreign_key_references",
233 "columns": [
234 "pk",
235 "foreign_key_with_label",
236 "foreign_key_with_blank_label",
237 "foreign_key_with_no_label",
238 "foreign_key_compound_pk1",
239 "foreign_key_compound_pk2",
240 ],
241 "primary_keys": ["pk"],
242 "count": 2,
243 "hidden": False,
244 "fts_table": None,
245 "foreign_keys": {
246 "incoming": [],
247 "outgoing": [
248 {
249 "other_table": "primary_key_multiple_columns",
250 "column": "foreign_key_with_no_label",
251 "other_column": "id",
252 },
253 {
254 "other_table": "simple_primary_key",
255 "column": "foreign_key_with_blank_label",
256 "other_column": "id",
257 },
258 {
259 "other_table": "simple_primary_key",
260 "column": "foreign_key_with_label",
261 "other_column": "id",
262 },
263 ],
264 },
265 "private": False,
266 },
267 ] + [
268 {
269 "name": "infinity",
270 "columns": ["value"],
271 "primary_keys": [],
272 "count": 3,
273 "hidden": False,
274 "fts_table": None,
275 "foreign_keys": {"incoming": [], "outgoing": []},
276 "private": False,
277 },
278 {
279 "name": "primary_key_multiple_columns",
280 "columns": ["id", "content", "content2"],
281 "primary_keys": ["id"],
282 "count": 1,
283 "hidden": False,
284 "fts_table": None,
285 "foreign_keys": {
286 "incoming": [
287 {
288 "other_table": "foreign_key_references",
289 "column": "id",
290 "other_column": "foreign_key_with_no_label",
291 }
292 ],
293 "outgoing": [],
294 },
295 "private": False,
296 },
297 {
298 "name": "primary_key_multiple_columns_explicit_label",
299 "columns": ["id", "content", "content2"],
300 "primary_keys": ["id"],
301 "count": 1,
302 "hidden": False,
303 "fts_table": None,
304 "foreign_keys": {
305 "incoming": [
306 {
307 "other_table": "custom_foreign_key_label",
308 "column": "id",
309 "other_column": "foreign_key_with_custom_label",
310 }
311 ],
312 "outgoing": [],
313 },
314 "private": False,
315 },
316 {
317 "name": "roadside_attraction_characteristics",
318 "columns": ["attraction_id", "characteristic_id"],
319 "primary_keys": [],
320 "count": 5,
321 "hidden": False,
322 "fts_table": None,
323 "foreign_keys": {
324 "incoming": [],
325 "outgoing": [
326 {
327 "other_table": "attraction_characteristic",
328 "column": "characteristic_id",
329 "other_column": "pk",
330 },
331 {
332 "other_table": "roadside_attractions",
333 "column": "attraction_id",
334 "other_column": "pk",
335 },
336 ],
337 },
338 "private": False,
339 },
340 {
341 "name": "roadside_attractions",
342 "columns": ["pk", "name", "address", "url", "latitude", "longitude"],
343 "primary_keys": ["pk"],
344 "count": 4,
345 "hidden": False,
346 "fts_table": None,
347 "foreign_keys": {
348 "incoming": [
349 {
350 "other_table": "roadside_attraction_characteristics",
351 "column": "pk",
352 "other_column": "attraction_id",
353 }
354 ],
355 "outgoing": [],
356 },
357 "private": False,
358 },
359 {
360 "name": "searchable",
361 "columns": ["pk", "text1", "text2", "name with . and spaces"],
362 "primary_keys": ["pk"],
363 "count": 2,
364 "hidden": False,
365 "fts_table": "searchable_fts",
366 "foreign_keys": {
367 "incoming": [
368 {
369 "other_table": "searchable_tags",
370 "column": "pk",
371 "other_column": "searchable_id",
372 }
373 ],
374 "outgoing": [],
375 },
376 "private": False,
377 },
378 {
379 "name": "searchable_tags",
380 "columns": ["searchable_id", "tag"],
381 "primary_keys": ["searchable_id", "tag"],
382 "count": 2,
383 "hidden": False,
384 "fts_table": None,
385 "foreign_keys": {
386 "incoming": [],
387 "outgoing": [
388 {"other_table": "tags", "column": "tag", "other_column": "tag"},
389 {
390 "other_table": "searchable",
391 "column": "searchable_id",
392 "other_column": "pk",
393 },
394 ],
395 },
396 "private": False,
397 },
398 {
399 "name": "select",
400 "columns": ["group", "having", "and", "json"],
401 "primary_keys": [],
402 "count": 1,
403 "hidden": False,
404 "fts_table": None,
405 "foreign_keys": {"incoming": [], "outgoing": []},
406 "private": False,
407 },
408 {
409 "name": "simple_primary_key",
410 "columns": ["id", "content"],
411 "primary_keys": ["id"],
412 "count": 5,
413 "hidden": False,
414 "fts_table": None,
415 "foreign_keys": {
416 "incoming": [
417 {
418 "other_table": "foreign_key_references",
419 "column": "id",
420 "other_column": "foreign_key_with_blank_label",
421 },
422 {
423 "other_table": "foreign_key_references",
424 "column": "id",
425 "other_column": "foreign_key_with_label",
426 },
427 {
428 "other_table": "complex_foreign_keys",
429 "column": "id",
430 "other_column": "f3",
431 },
432 {
433 "other_table": "complex_foreign_keys",
434 "column": "id",
435 "other_column": "f2",
436 },
437 {
438 "other_table": "complex_foreign_keys",
439 "column": "id",
440 "other_column": "f1",
441 },
442 ],
443 "outgoing": [],
444 },
445 "private": False,
446 },
447 {
448 "name": "sortable",
449 "columns": [
450 "pk1",
451 "pk2",
452 "content",
453 "sortable",
454 "sortable_with_nulls",
455 "sortable_with_nulls_2",
456 "text",
457 ],
458 "primary_keys": ["pk1", "pk2"],
459 "count": 201,
460 "hidden": False,
461 "fts_table": None,
462 "foreign_keys": {"incoming": [], "outgoing": []},
463 "private": False,
464 },
465 {
466 "name": "table/with/slashes.csv",
467 "columns": ["pk", "content"],
468 "primary_keys": ["pk"],
469 "count": 1,
470 "hidden": False,
471 "fts_table": None,
472 "foreign_keys": {"incoming": [], "outgoing": []},
473 "private": False,
474 },
475 {
476 "name": "tags",
477 "columns": ["tag"],
478 "primary_keys": ["tag"],
479 "count": 2,
480 "hidden": False,
481 "fts_table": None,
482 "foreign_keys": {
483 "incoming": [
484 {
485 "other_table": "searchable_tags",
486 "column": "tag",
487 "other_column": "tag",
488 }
489 ],
490 "outgoing": [],
491 },
492 "private": False,
493 },
494 {
495 "name": "units",
496 "columns": ["pk", "distance", "frequency"],
497 "primary_keys": ["pk"],
498 "count": 3,
499 "hidden": False,
500 "fts_table": None,
501 "foreign_keys": {"incoming": [], "outgoing": []},
502 "private": False,
503 },
504 {
505 "name": "no_primary_key",
506 "columns": ["content", "a", "b", "c"],
507 "primary_keys": [],
508 "count": 201,
509 "hidden": True,
510 "fts_table": None,
511 "foreign_keys": {"incoming": [], "outgoing": []},
512 "private": False,
513 },
514 {
515 "name": "searchable_fts",
516 "columns": [
517 "text1",
518 "text2",
519 "name with . and spaces",
520 ]
521 + (
522 [
523 "searchable_fts",
524 "docid",
525 "__langid",
526 ]
527 if supports_table_xinfo()
528 else []
529 ),
530 "primary_keys": [],
531 "count": 2,
532 "hidden": True,
533 "fts_table": "searchable_fts",
534 "foreign_keys": {"incoming": [], "outgoing": []},
535 "private": False,
536 },
537 {
538 "name": "searchable_fts_docsize",
539 "columns": ["docid", "size"],
540 "primary_keys": ["docid"],
541 "count": 2,
542 "hidden": True,
543 "fts_table": None,
544 "foreign_keys": {"incoming": [], "outgoing": []},
545 "private": False,
546 },
547 {
548 "name": "searchable_fts_segdir",
549 "columns": [
550 "level",
551 "idx",
552 "start_block",
553 "leaves_end_block",
554 "end_block",
555 "root",
556 ],
557 "primary_keys": ["level", "idx"],
558 "count": 1,
559 "hidden": True,
560 "fts_table": None,
561 "foreign_keys": {"incoming": [], "outgoing": []},
562 "private": False,
563 },
564 {
565 "name": "searchable_fts_segments",
566 "columns": ["blockid", "block"],
567 "primary_keys": ["blockid"],
568 "count": 0,
569 "hidden": True,
570 "fts_table": None,
571 "foreign_keys": {"incoming": [], "outgoing": []},
572 "private": False,
573 },
574 {
575 "name": "searchable_fts_stat",
576 "columns": ["id", "value"],
577 "primary_keys": ["id"],
578 "count": 1,
579 "hidden": True,
580 "fts_table": None,
581 "foreign_keys": {"incoming": [], "outgoing": []},
582 "private": False,
583 },
584 ]
585
586
587 def test_no_files_uses_memory_database(app_client_no_files):
588 response = app_client_no_files.get("/.json")
589 assert response.status == 200
590 assert {
591 "_memory": {
592 "name": "_memory",
593 "hash": None,
594 "color": "a6c7b9",
595 "path": "/_memory",
596 "tables_and_views_truncated": [],
597 "tables_and_views_more": False,
598 "tables_count": 0,
599 "table_rows_sum": 0,
600 "show_table_row_counts": False,
601 "hidden_table_rows_sum": 0,
602 "hidden_tables_count": 0,
603 "views_count": 0,
604 "private": False,
605 }
606 } == response.json
607 # Try that SQL query
608 response = app_client_no_files.get(
609 "/_memory.json?sql=select+sqlite_version()&_shape=array"
610 )
611 assert 1 == len(response.json)
612 assert ["sqlite_version()"] == list(response.json[0].keys())
613
614
615 @pytest.mark.parametrize(
616 "path,expected_redirect",
617 (
618 ("/:memory:", "/_memory"),
619 ("/:memory:.json", "/_memory.json"),
620 ("/:memory:?sql=select+1", "/_memory?sql=select+1"),
621 ("/:memory:.json?sql=select+1", "/_memory.json?sql=select+1"),
622 ("/:memory:.csv?sql=select+1", "/_memory.csv?sql=select+1"),
623 ),
624 )
625 def test_old_memory_urls_redirect(app_client_no_files, path, expected_redirect):
626 response = app_client_no_files.get(path)
627 assert response.status == 301
628 assert response.headers["location"] == expected_redirect
629
630
631 def test_database_page_for_database_with_dot_in_name(app_client_with_dot):
632 response = app_client_with_dot.get("/fixtures~2Edot.json")
633 assert response.status == 200
634
635
636 def test_custom_sql(app_client):
637 response = app_client.get(
638 "/fixtures.json?sql=select+content+from+simple_primary_key&_shape=objects"
639 )
640 data = response.json
641 assert {"sql": "select content from simple_primary_key", "params": {}} == data[
642 "query"
643 ]
644 assert [
645 {"content": "hello"},
646 {"content": "world"},
647 {"content": ""},
648 {"content": "RENDER_CELL_DEMO"},
649 {"content": "RENDER_CELL_ASYNC"},
650 ] == data["rows"]
651 assert ["content"] == data["columns"]
652 assert "fixtures" == data["database"]
653 assert not data["truncated"]
654
655
656 def test_sql_time_limit(app_client_shorter_time_limit):
657 response = app_client_shorter_time_limit.get("/fixtures.json?sql=select+sleep(0.5)")
658 assert 400 == response.status
659 assert response.json == {
660 "ok": False,
661 "error": (
662 "<p>SQL query took too long. The time limit is controlled by the\n"
663 '<a href="https://docs.datasette.io/en/stable/settings.html#sql-time-limit-ms">sql_time_limit_ms</a>\n'
664 "configuration option.</p>\n"
665 '<textarea style="width: 90%">select sleep(0.5)</textarea>\n'
666 "<script>\n"
667 'let ta = document.querySelector("textarea");\n'
668 'ta.style.height = ta.scrollHeight + "px";\n'
669 "</script>"
670 ),
671 "status": 400,
672 "title": "SQL Interrupted",
673 }
674
675
676 def test_custom_sql_time_limit(app_client):
677 response = app_client.get("/fixtures.json?sql=select+sleep(0.01)")
678 assert 200 == response.status
679 response = app_client.get("/fixtures.json?sql=select+sleep(0.01)&_timelimit=5")
680 assert 400 == response.status
681 assert "SQL Interrupted" == response.json["title"]
682
683
684 def test_invalid_custom_sql(app_client):
685 response = app_client.get("/fixtures.json?sql=.schema")
686 assert response.status == 400
687 assert response.json["ok"] is False
688 assert "Statement must be a SELECT" == response.json["error"]
689
690
691 def test_row(app_client):
692 response = app_client.get("/fixtures/simple_primary_key/1.json?_shape=objects")
693 assert response.status == 200
694 assert [{"id": "1", "content": "hello"}] == response.json["rows"]
695
696
697 def test_row_strange_table_name(app_client):
698 response = app_client.get(
699 "/fixtures/table~2Fwith~2Fslashes~2Ecsv/3.json?_shape=objects"
700 )
701 assert response.status == 200
702 assert [{"pk": "3", "content": "hey"}] == response.json["rows"]
703
704
705 def test_row_foreign_key_tables(app_client):
706 response = app_client.get(
707 "/fixtures/simple_primary_key/1.json?_extras=foreign_key_tables"
708 )
709 assert response.status == 200
710 assert response.json["foreign_key_tables"] == [
711 {
712 "other_table": "foreign_key_references",
713 "column": "id",
714 "other_column": "foreign_key_with_blank_label",
715 "count": 0,
716 "link": "/fixtures/foreign_key_references?foreign_key_with_blank_label=1",
717 },
718 {
719 "other_table": "foreign_key_references",
720 "column": "id",
721 "other_column": "foreign_key_with_label",
722 "count": 1,
723 "link": "/fixtures/foreign_key_references?foreign_key_with_label=1",
724 },
725 {
726 "other_table": "complex_foreign_keys",
727 "column": "id",
728 "other_column": "f3",
729 "count": 1,
730 "link": "/fixtures/complex_foreign_keys?f3=1",
731 },
732 {
733 "other_table": "complex_foreign_keys",
734 "column": "id",
735 "other_column": "f2",
736 "count": 0,
737 "link": "/fixtures/complex_foreign_keys?f2=1",
738 },
739 {
740 "other_table": "complex_foreign_keys",
741 "column": "id",
742 "other_column": "f1",
743 "count": 1,
744 "link": "/fixtures/complex_foreign_keys?f1=1",
745 },
746 ]
747
748
749 def test_databases_json(app_client_two_attached_databases_one_immutable):
750 response = app_client_two_attached_databases_one_immutable.get("/-/databases.json")
751 databases = response.json
752 assert 2 == len(databases)
753 extra_database, fixtures_database = databases
754 assert "extra database" == extra_database["name"]
755 assert None == extra_database["hash"]
756 assert True == extra_database["is_mutable"]
757 assert False == extra_database["is_memory"]
758
759 assert "fixtures" == fixtures_database["name"]
760 assert fixtures_database["hash"] is not None
761 assert False == fixtures_database["is_mutable"]
762 assert False == fixtures_database["is_memory"]
763
764
765 def test_metadata_json(app_client):
766 response = app_client.get("/-/metadata.json")
767 assert METADATA == response.json
768
769
770 def test_threads_json(app_client):
771 response = app_client.get("/-/threads.json")
772 expected_keys = {"threads", "num_threads"}
773 if sys.version_info >= (3, 7, 0):
774 expected_keys.update({"tasks", "num_tasks"})
775 assert expected_keys == set(response.json.keys())
776
777
778 def test_plugins_json(app_client):
779 response = app_client.get("/-/plugins.json")
780 assert EXPECTED_PLUGINS == sorted(response.json, key=lambda p: p["name"])
781 # Try with ?all=1
782 response = app_client.get("/-/plugins.json?all=1")
783 names = {p["name"] for p in response.json}
784 assert names.issuperset(p["name"] for p in EXPECTED_PLUGINS)
785 assert names.issuperset(DEFAULT_PLUGINS)
786
787
788 def test_versions_json(app_client):
789 response = app_client.get("/-/versions.json")
790 assert "python" in response.json
791 assert "3.0" == response.json.get("asgi")
792 assert "version" in response.json["python"]
793 assert "full" in response.json["python"]
794 assert "datasette" in response.json
795 assert "version" in response.json["datasette"]
796 assert response.json["datasette"]["version"] == __version__
797 assert "sqlite" in response.json
798 assert "version" in response.json["sqlite"]
799 assert "fts_versions" in response.json["sqlite"]
800 assert "compile_options" in response.json["sqlite"]
801
802
803 def test_settings_json(app_client):
804 response = app_client.get("/-/settings.json")
805 assert {
806 "default_page_size": 50,
807 "default_facet_size": 30,
808 "default_allow_sql": True,
809 "facet_suggest_time_limit_ms": 50,
810 "facet_time_limit_ms": 200,
811 "max_returned_rows": 100,
812 "sql_time_limit_ms": 200,
813 "allow_download": True,
814 "allow_facet": True,
815 "suggest_facets": True,
816 "default_cache_ttl": 5,
817 "num_sql_threads": 1,
818 "cache_size_kb": 0,
819 "allow_csv_stream": True,
820 "max_csv_mb": 100,
821 "truncate_cells_html": 2048,
822 "force_https_urls": False,
823 "template_debug": False,
824 "trace_debug": False,
825 "base_url": "/",
826 } == response.json
827
828
829 @pytest.mark.parametrize(
830 "path,expected_redirect",
831 (
832 ("/-/config.json", "/-/settings.json"),
833 ("/-/config", "/-/settings"),
834 ),
835 )
836 def test_config_redirects_to_settings(app_client, path, expected_redirect):
837 response = app_client.get(path)
838 assert response.status == 301
839 assert response.headers["Location"] == expected_redirect
840
841
842 test_json_columns_default_expected = [
843 {"intval": 1, "strval": "s", "floatval": 0.5, "jsonval": '{"foo": "bar"}'}
844 ]
845
846
847 @pytest.mark.parametrize(
848 "extra_args,expected",
849 [
850 ("", test_json_columns_default_expected),
851 ("&_json=intval", test_json_columns_default_expected),
852 ("&_json=strval", test_json_columns_default_expected),
853 ("&_json=floatval", test_json_columns_default_expected),
854 (
855 "&_json=jsonval",
856 [{"intval": 1, "strval": "s", "floatval": 0.5, "jsonval": {"foo": "bar"}}],
857 ),
858 ],
859 )
860 def test_json_columns(app_client, extra_args, expected):
861 sql = """
862 select 1 as intval, "s" as strval, 0.5 as floatval,
863 '{"foo": "bar"}' as jsonval
864 """
865 path = "/fixtures.json?" + urllib.parse.urlencode({"sql": sql, "_shape": "array"})
866 path += extra_args
867 response = app_client.get(path)
868 assert expected == response.json
869
870
871 def test_config_cache_size(app_client_larger_cache_size):
872 response = app_client_larger_cache_size.get("/fixtures/pragma_cache_size.json")
873 assert [[-2500]] == response.json["rows"]
874
875
876 def test_config_force_https_urls():
877 with make_app_client(settings={"force_https_urls": True}) as client:
878 response = client.get("/fixtures/facetable.json?_size=3&_facet=state")
879 assert response.json["next_url"].startswith("https://")
880 assert response.json["facet_results"]["state"]["results"][0][
881 "toggle_url"
882 ].startswith("https://")
883 assert response.json["suggested_facets"][0]["toggle_url"].startswith("https://")
884 # Also confirm that request.url and request.scheme are set correctly
885 response = client.get("/")
886 assert client.ds._last_request.url.startswith("https://")
887 assert client.ds._last_request.scheme == "https"
888
889
890 @pytest.mark.parametrize(
891 "path,status_code",
892 [
893 ("/fixtures.db", 200),
894 ("/fixtures.json", 200),
895 ("/fixtures/no_primary_key.json", 200),
896 # A 400 invalid SQL query should still have the header:
897 ("/fixtures.json?sql=select+blah", 400),
898 ],
899 )
900 def test_cors(app_client_with_cors, path, status_code):
901 response = app_client_with_cors.get(path)
902 assert response.status == status_code
903 assert response.headers["Access-Control-Allow-Origin"] == "*"
904 assert response.headers["Access-Control-Allow-Headers"] == "Authorization"
905 assert response.headers["Access-Control-Expose-Headers"] == "Link"
906
907
908 @pytest.mark.parametrize(
909 "path",
910 (
911 "/",
912 ".json",
913 "/searchable",
914 "/searchable.json",
915 "/searchable_view",
916 "/searchable_view.json",
917 ),
918 )
919 def test_database_with_space_in_name(app_client_two_attached_databases, path):
920 response = app_client_two_attached_databases.get(
921 "/extra~20database" + path, follow_redirects=True
922 )
923 assert response.status == 200
924
925
926 def test_common_prefix_database_names(app_client_conflicting_database_names):
927 # https://github.com/simonw/datasette/issues/597
928 assert ["foo-bar", "foo", "fixtures"] == [
929 d["name"]
930 for d in app_client_conflicting_database_names.get("/-/databases.json").json
931 ]
932 for db_name, path in (("foo", "/foo.json"), ("foo-bar", "/foo-bar.json")):
933 data = app_client_conflicting_database_names.get(path).json
934 assert db_name == data["database"]
935
936
937 def test_inspect_file_used_for_count(app_client_immutable_and_inspect_file):
938 response = app_client_immutable_and_inspect_file.get("/fixtures/sortable.json")
939 assert response.json["filtered_table_rows_count"] == 100
940
941
942 def test_http_options_request(app_client):
943 response = app_client.request("/fixtures", method="OPTIONS")
944 assert response.status == 200
945 assert response.text == "ok"
946
947
948 @pytest.mark.asyncio
949 async def test_db_path(app_client):
950 db = app_client.ds.get_database()
951 path = pathlib.Path(db.path)
952
953 assert path.exists()
954
955 datasette = Datasette([path])
956
957 # Previously this broke if path was a pathlib.Path:
958 await datasette.refresh_schemas()
959
960
961 @pytest.mark.asyncio
962 async def test_hidden_sqlite_stat1_table():
963 ds = Datasette()
964 db = ds.add_memory_database("db")
965 await db.execute_write("create table normal (id integer primary key, name text)")
966 await db.execute_write("create index idx on normal (name)")
967 await db.execute_write("analyze")
968 data = (await ds.client.get("/db.json?_show_hidden=1")).json()
969 tables = [(t["name"], t["hidden"]) for t in data["tables"]]
970 assert tables in (
971 [("normal", False), ("sqlite_stat1", True)],
972 [("normal", False), ("sqlite_stat1", True), ("sqlite_stat4", True)],
973 )
974
975
976 @pytest.mark.asyncio
977 @pytest.mark.parametrize("db_name", ("foo", r"fo%o", "f~/c.d"))
978 async def test_tilde_encoded_database_names(db_name):
979 ds = Datasette()
980 ds.add_memory_database(db_name)
981 response = await ds.client.get("/.json")
982 assert db_name in response.json().keys()
983 path = response.json()[db_name]["path"]
984 # And the JSON for that database
985 response2 = await ds.client.get(path + ".json")
986 assert response2.status_code == 200