File: test_table_html.py

package info (click to toggle)
datasette 0.65.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 3,540 kB
  • sloc: python: 19,371; javascript: 10,089; sh: 71; makefile: 47; ansic: 26
file content (1129 lines) | stat: -rw-r--r-- 41,884 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
from datasette.app import Datasette, Database
from bs4 import BeautifulSoup as Soup
from .fixtures import (  # noqa
    app_client,
    make_app_client,
)
import pathlib
import pytest
import urllib.parse
from .utils import assert_footer_links, inner_html


@pytest.mark.parametrize(
    "path,expected_definition_sql",
    [
        (
            "/fixtures/facet_cities",
            """
CREATE TABLE facet_cities (
    id integer primary key,
    name text
);
        """.strip(),
        ),
        (
            "/fixtures/compound_three_primary_keys",
            """
CREATE TABLE compound_three_primary_keys (
  pk1 varchar(30),
  pk2 varchar(30),
  pk3 varchar(30),
  content text,
  PRIMARY KEY (pk1, pk2, pk3)
);
CREATE INDEX idx_compound_three_primary_keys_content ON compound_three_primary_keys(content);
            """.strip(),
        ),
    ],
)
def test_table_definition_sql(path, expected_definition_sql, app_client):
    response = app_client.get(path)
    pre = Soup(response.body, "html.parser").select_one("pre.wrapped-sql")
    assert expected_definition_sql == pre.string


def test_table_cell_truncation():
    with make_app_client(settings={"truncate_cells_html": 5}) as client:
        response = client.get("/fixtures/facetable")
        assert response.status == 200
        table = Soup(response.body, "html.parser").find("table")
        assert table["class"] == ["rows-and-columns"]
        assert [
            "Missi…",
            "Dogpa…",
            "SOMA",
            "Tende…",
            "Berna…",
            "Hayes…",
            "Holly…",
            "Downt…",
            "Los F…",
            "Korea…",
            "Downt…",
            "Greek…",
            "Corkt…",
            "Mexic…",
            "Arcad…",
        ] == [
            td.string
            for td in table.find_all("td", {"class": "col-neighborhood-b352a7"})
        ]
        # URLs should be truncated too
        response2 = client.get("/fixtures/roadside_attractions")
        assert response2.status == 200
        table = Soup(response2.body, "html.parser").find("table")
        tds = table.find_all("td", {"class": "col-url"})
        assert [str(td) for td in tds] == [
            '<td class="col-url type-str"><a href="https://www.mysteryspot.com/">http…</a></td>',
            '<td class="col-url type-str"><a href="https://winchestermysteryhouse.com/">http…</a></td>',
            '<td class="col-url type-none">\xa0</td>',
            '<td class="col-url type-str"><a href="https://www.bigfootdiscoveryproject.com/">http…</a></td>',
        ]


def test_add_filter_redirects(app_client):
    filter_args = urllib.parse.urlencode(
        {"_filter_column": "content", "_filter_op": "startswith", "_filter_value": "x"}
    )
    path_base = "/fixtures/simple_primary_key"
    path = path_base + "?" + filter_args
    response = app_client.get(path)
    assert response.status == 302
    assert response.headers["Location"].endswith("?content__startswith=x")

    # Adding a redirect to an existing query string:
    path = path_base + "?foo=bar&" + filter_args
    response = app_client.get(path)
    assert response.status == 302
    assert response.headers["Location"].endswith("?foo=bar&content__startswith=x")

    # Test that op with a __x suffix overrides the filter value
    path = (
        path_base
        + "?"
        + urllib.parse.urlencode(
            {
                "_filter_column": "content",
                "_filter_op": "isnull__5",
                "_filter_value": "x",
            }
        )
    )
    response = app_client.get(path)
    assert response.status == 302
    assert response.headers["Location"].endswith("?content__isnull=5")


def test_existing_filter_redirects(app_client):
    filter_args = {
        "_filter_column_1": "name",
        "_filter_op_1": "contains",
        "_filter_value_1": "hello",
        "_filter_column_2": "age",
        "_filter_op_2": "gte",
        "_filter_value_2": "22",
        "_filter_column_3": "age",
        "_filter_op_3": "lt",
        "_filter_value_3": "30",
        "_filter_column_4": "name",
        "_filter_op_4": "contains",
        "_filter_value_4": "world",
    }
    path_base = "/fixtures/simple_primary_key"
    path = path_base + "?" + urllib.parse.urlencode(filter_args)
    response = app_client.get(path)
    assert response.status == 302
    assert_querystring_equal(
        "name__contains=hello&age__gte=22&age__lt=30&name__contains=world",
        response.headers["Location"].split("?")[1],
    )

    # Setting _filter_column_3 to empty string should remove *_3 entirely
    filter_args["_filter_column_3"] = ""
    path = path_base + "?" + urllib.parse.urlencode(filter_args)
    response = app_client.get(path)
    assert response.status == 302
    assert_querystring_equal(
        "name__contains=hello&age__gte=22&name__contains=world",
        response.headers["Location"].split("?")[1],
    )

    # ?_filter_op=exact should be removed if unaccompanied by _fiter_column
    response = app_client.get(path_base + "?_filter_op=exact")
    assert response.status == 302
    assert "?" not in response.headers["Location"]


@pytest.mark.parametrize(
    "qs,expected_hidden",
    (
        # Things that should be reflected in hidden form fields:
        ("_facet=_neighborhood", {"_facet": "_neighborhood"}),
        ("_where=1+=+1&_col=_city_id", {"_where": "1 = 1", "_col": "_city_id"}),
        # Things that should NOT be reflected in hidden form fields:
        (
            "_facet=_neighborhood&_neighborhood__exact=Downtown",
            {"_facet": "_neighborhood"},
        ),
        ("_facet=_neighborhood&_city_id__gt=1", {"_facet": "_neighborhood"}),
    ),
)
def test_reflected_hidden_form_fields(app_client, qs, expected_hidden):
    # https://github.com/simonw/datasette/issues/1527
    response = app_client.get("/fixtures/facetable?{}".format(qs))
    # In this case we should NOT have a hidden _neighborhood__exact=Downtown field
    form = Soup(response.body, "html.parser").find("form")
    hidden_inputs = {
        input["name"]: input["value"] for input in form.select("input[type=hidden]")
    }
    assert hidden_inputs == expected_hidden


def test_empty_search_parameter_gets_removed(app_client):
    path_base = "/fixtures/simple_primary_key"
    path = (
        path_base
        + "?"
        + urllib.parse.urlencode(
            {
                "_search": "",
                "_filter_column": "name",
                "_filter_op": "exact",
                "_filter_value": "chidi",
            }
        )
    )
    response = app_client.get(path)
    assert response.status == 302
    assert response.headers["Location"].endswith("?name__exact=chidi")


def test_searchable_view_persists_fts_table(app_client):
    # The search form should persist ?_fts_table as a hidden field
    response = app_client.get(
        "/fixtures/searchable_view?_fts_table=searchable_fts&_fts_pk=pk"
    )
    inputs = Soup(response.body, "html.parser").find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [("_fts_table", "searchable_fts"), ("_fts_pk", "pk")] == [
        (hidden["name"], hidden["value"]) for hidden in hiddens
    ]


def test_sort_by_desc_redirects(app_client):
    path_base = "/fixtures/sortable"
    path = (
        path_base
        + "?"
        + urllib.parse.urlencode({"_sort": "sortable", "_sort_by_desc": "1"})
    )
    response = app_client.get(path)
    assert response.status == 302
    assert response.headers["Location"].endswith("?_sort_desc=sortable")


def test_sort_links(app_client):
    response = app_client.get("/fixtures/sortable?_sort=sortable")
    assert response.status == 200
    ths = Soup(response.body, "html.parser").find_all("th")
    attrs_and_link_attrs = [
        {
            "attrs": th.attrs,
            "a_href": (th.find("a")["href"] if th.find("a") else None),
        }
        for th in ths
    ]
    assert attrs_and_link_attrs == [
        {
            "attrs": {
                "class": ["col-Link"],
                "scope": "col",
                "data-column": "Link",
                "data-column-type": "",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": None,
        },
        {
            "attrs": {
                "class": ["col-pk1"],
                "scope": "col",
                "data-column": "pk1",
                "data-column-type": "varchar(30)",
                "data-column-not-null": "0",
                "data-is-pk": "1",
            },
            "a_href": None,
        },
        {
            "attrs": {
                "class": ["col-pk2"],
                "scope": "col",
                "data-column": "pk2",
                "data-column-type": "varchar(30)",
                "data-column-not-null": "0",
                "data-is-pk": "1",
            },
            "a_href": None,
        },
        {
            "attrs": {
                "class": ["col-content"],
                "scope": "col",
                "data-column": "content",
                "data-column-type": "text",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": None,
        },
        {
            "attrs": {
                "class": ["col-sortable"],
                "scope": "col",
                "data-column": "sortable",
                "data-column-type": "integer",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": "/fixtures/sortable?_sort_desc=sortable",
        },
        {
            "attrs": {
                "class": ["col-sortable_with_nulls"],
                "scope": "col",
                "data-column": "sortable_with_nulls",
                "data-column-type": "real",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": "/fixtures/sortable?_sort=sortable_with_nulls",
        },
        {
            "attrs": {
                "class": ["col-sortable_with_nulls_2"],
                "scope": "col",
                "data-column": "sortable_with_nulls_2",
                "data-column-type": "real",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": "/fixtures/sortable?_sort=sortable_with_nulls_2",
        },
        {
            "attrs": {
                "class": ["col-text"],
                "scope": "col",
                "data-column": "text",
                "data-column-type": "text",
                "data-column-not-null": "0",
                "data-is-pk": "0",
            },
            "a_href": "/fixtures/sortable?_sort=text",
        },
    ]


def test_facet_display(app_client):
    response = app_client.get(
        "/fixtures/facetable?_facet=planet_int&_facet=_city_id&_facet=on_earth"
    )
    assert response.status == 200
    soup = Soup(response.body, "html.parser")
    divs = soup.find("div", {"class": "facet-results"}).find_all("div")
    actual = []
    for div in divs:
        actual.append(
            {
                "name": div.find("strong").text.split()[0],
                "items": [
                    {
                        "name": a.text,
                        "qs": a["href"].split("?")[-1],
                        "count": int(str(a.parent).split("</a>")[1].split("<")[0]),
                    }
                    for a in div.find("ul").find_all("a")
                ],
            }
        )
    assert actual == [
        {
            "name": "_city_id",
            "items": [
                {
                    "name": "San Francisco",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=1",
                    "count": 6,
                },
                {
                    "name": "Los Angeles",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=2",
                    "count": 4,
                },
                {
                    "name": "Detroit",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=3",
                    "count": 4,
                },
                {
                    "name": "Memnonia",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&_city_id__exact=4",
                    "count": 1,
                },
            ],
        },
        {
            "name": "planet_int",
            "items": [
                {
                    "name": "1",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&planet_int=1",
                    "count": 14,
                },
                {
                    "name": "2",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&planet_int=2",
                    "count": 1,
                },
            ],
        },
        {
            "name": "on_earth",
            "items": [
                {
                    "name": "1",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&on_earth=1",
                    "count": 14,
                },
                {
                    "name": "0",
                    "qs": "_facet=planet_int&_facet=_city_id&_facet=on_earth&on_earth=0",
                    "count": 1,
                },
            ],
        },
    ]


def test_facets_persist_through_filter_form(app_client):
    response = app_client.get(
        "/fixtures/facetable?_facet=planet_int&_facet=_city_id&_facet_array=tags"
    )
    assert response.status == 200
    inputs = Soup(response.body, "html.parser").find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == [
        ("_facet", "planet_int"),
        ("_facet", "_city_id"),
        ("_facet_array", "tags"),
    ]


def test_next_does_not_persist_in_hidden_field(app_client):
    response = app_client.get("/fixtures/searchable?_size=1&_next=1")
    assert response.status == 200
    inputs = Soup(response.body, "html.parser").find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == [
        ("_size", "1"),
    ]


def test_table_html_simple_primary_key(app_client):
    response = app_client.get("/fixtures/simple_primary_key?_size=3")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    assert table["class"] == ["rows-and-columns"]
    ths = table.find_all("th")
    assert "id\xa0▼" == ths[0].find("a").string.strip()
    for expected_col, th in zip(("content",), ths[1:]):
        a = th.find("a")
        assert expected_col == a.string
        assert a["href"].endswith(f"/simple_primary_key?_size=3&_sort={expected_col}")
        assert ["nofollow"] == a["rel"]
    assert [
        [
            '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/1">1</a></td>',
            '<td class="col-content type-str">hello</td>',
        ],
        [
            '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/2">2</a></td>',
            '<td class="col-content type-str">world</td>',
        ],
        [
            '<td class="col-id type-pk"><a href="/fixtures/simple_primary_key/3">3</a></td>',
            '<td class="col-content type-str">\xa0</td>',
        ],
    ] == [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]


def test_table_csv_json_export_interface(app_client):
    response = app_client.get("/fixtures/simple_primary_key?id__gt=2")
    assert response.status == 200
    # The links at the top of the page
    links = (
        Soup(response.body, "html.parser")
        .find("p", {"class": "export-links"})
        .find_all("a")
    )
    actual = [l["href"] for l in links]
    expected = [
        "/fixtures/simple_primary_key.json?id__gt=2",
        "/fixtures/simple_primary_key.testall?id__gt=2",
        "/fixtures/simple_primary_key.testnone?id__gt=2",
        "/fixtures/simple_primary_key.testresponse?id__gt=2",
        "/fixtures/simple_primary_key.csv?id__gt=2&_size=max",
        "#export",
    ]
    assert expected == actual
    # And the advaced export box at the bottom:
    div = Soup(response.body, "html.parser").find("div", {"class": "advanced-export"})
    json_links = [a["href"] for a in div.find("p").find_all("a")]
    assert [
        "/fixtures/simple_primary_key.json?id__gt=2",
        "/fixtures/simple_primary_key.json?id__gt=2&_shape=array",
        "/fixtures/simple_primary_key.json?id__gt=2&_shape=array&_nl=on",
        "/fixtures/simple_primary_key.json?id__gt=2&_shape=object",
    ] == json_links
    # And the CSV form
    form = div.find("form")
    assert form["action"].endswith("/simple_primary_key.csv")
    inputs = [str(input) for input in form.find_all("input")]
    assert [
        '<input name="_dl" type="checkbox"/>',
        '<input type="submit" value="Export CSV"/>',
        '<input name="id__gt" type="hidden" value="2"/>',
        '<input name="_size" type="hidden" value="max"/>',
    ] == inputs


def test_csv_json_export_links_include_labels_if_foreign_keys(app_client):
    response = app_client.get("/fixtures/facetable")
    assert response.status == 200
    links = (
        Soup(response.body, "html.parser")
        .find("p", {"class": "export-links"})
        .find_all("a")
    )
    actual = [l["href"] for l in links]
    expected = [
        "/fixtures/facetable.json?_labels=on",
        "/fixtures/facetable.testall?_labels=on",
        "/fixtures/facetable.testnone?_labels=on",
        "/fixtures/facetable.testresponse?_labels=on",
        "/fixtures/facetable.csv?_labels=on&_size=max",
        "#export",
    ]
    assert expected == actual


def test_table_not_exists(app_client):
    assert "Table not found" in app_client.get("/fixtures/blah").text


def test_table_html_no_primary_key(app_client):
    response = app_client.get("/fixtures/no_primary_key")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    # We have disabled sorting for this table using metadata.json
    assert ["content", "a", "b", "c"] == [
        th.string.strip() for th in table.select("thead th")[2:]
    ]
    expected = [
        [
            '<td class="col-Link type-pk"><a href="/fixtures/no_primary_key/{}">{}</a></td>'.format(
                i, i
            ),
            f'<td class="col-rowid type-int">{i}</td>',
            f'<td class="col-content type-str">{i}</td>',
            f'<td class="col-a type-str">a{i}</td>',
            f'<td class="col-b type-str">b{i}</td>',
            f'<td class="col-c type-str">c{i}</td>',
        ]
        for i in range(1, 51)
    ]
    assert expected == [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ]


def test_rowid_sortable_no_primary_key(app_client):
    response = app_client.get("/fixtures/no_primary_key")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    assert table["class"] == ["rows-and-columns"]
    ths = table.find_all("th")
    assert "rowid\xa0▼" == ths[1].find("a").string.strip()


def test_table_html_compound_primary_key(app_client):
    response = app_client.get("/fixtures/compound_primary_key")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    ths = table.find_all("th")
    assert "Link" == ths[0].string.strip()
    for expected_col, th in zip(("pk1", "pk2", "content"), ths[1:]):
        a = th.find("a")
        assert expected_col == a.string
        assert th["class"] == [f"col-{expected_col}"]
        assert a["href"].endswith(f"/compound_primary_key?_sort={expected_col}")
    expected = [
        [
            '<td class="col-Link type-pk"><a href="/fixtures/compound_primary_key/a,b">a,b</a></td>',
            '<td class="col-pk1 type-str">a</td>',
            '<td class="col-pk2 type-str">b</td>',
            '<td class="col-content type-str">c</td>',
        ],
        [
            '<td class="col-Link type-pk"><a href="/fixtures/compound_primary_key/a~2Fb,~2Ec-d">a/b,.c-d</a></td>',
            '<td class="col-pk1 type-str">a/b</td>',
            '<td class="col-pk2 type-str">.c-d</td>',
            '<td class="col-content type-str">c</td>',
        ],
    ]
    assert [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ] == expected


def test_table_html_foreign_key_links(app_client):
    response = app_client.get("/fixtures/foreign_key_references")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    actual = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    assert actual == [
        [
            '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/1">1</a></td>',
            '<td class="col-foreign_key_with_label type-str"><a href="/fixtures/simple_primary_key/1">hello</a>\xa0<em>1</em></td>',
            '<td class="col-foreign_key_with_blank_label type-str"><a href="/fixtures/simple_primary_key/3">-</a>\xa0<em>3</em></td>',
            '<td class="col-foreign_key_with_no_label type-str"><a href="/fixtures/primary_key_multiple_columns/1">1</a></td>',
            '<td class="col-foreign_key_compound_pk1 type-str">a</td>',
            '<td class="col-foreign_key_compound_pk2 type-str">b</td>',
        ],
        [
            '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/2">2</a></td>',
            '<td class="col-foreign_key_with_label type-none">\xa0</td>',
            '<td class="col-foreign_key_with_blank_label type-none">\xa0</td>',
            '<td class="col-foreign_key_with_no_label type-none">\xa0</td>',
            '<td class="col-foreign_key_compound_pk1 type-none">\xa0</td>',
            '<td class="col-foreign_key_compound_pk2 type-none">\xa0</td>',
        ],
    ]


def test_table_html_foreign_key_facets(app_client):
    response = app_client.get(
        "/fixtures/foreign_key_references?_facet=foreign_key_with_blank_label"
    )
    assert response.status == 200
    assert (
        '<li><a href="http://localhost/fixtures/foreign_key_references?_facet=foreign_key_with_blank_label&amp;foreign_key_with_blank_label=3">'
        "-</a> 1</li>"
    ) in response.text


def test_table_html_disable_foreign_key_links_with_labels(app_client):
    response = app_client.get("/fixtures/foreign_key_references?_labels=off&_size=1")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    actual = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    assert actual == [
        [
            '<td class="col-pk type-pk"><a href="/fixtures/foreign_key_references/1">1</a></td>',
            '<td class="col-foreign_key_with_label type-str">1</td>',
            '<td class="col-foreign_key_with_blank_label type-str">3</td>',
            '<td class="col-foreign_key_with_no_label type-str">1</td>',
            '<td class="col-foreign_key_compound_pk1 type-str">a</td>',
            '<td class="col-foreign_key_compound_pk2 type-str">b</td>',
        ]
    ]


def test_table_html_foreign_key_custom_label_column(app_client):
    response = app_client.get("/fixtures/custom_foreign_key_label")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    expected = [
        [
            '<td class="col-pk type-pk"><a href="/fixtures/custom_foreign_key_label/1">1</a></td>',
            '<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>',
        ]
    ]
    assert expected == [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ]


@pytest.mark.parametrize(
    "path,expected_column_options",
    [
        ("/fixtures/infinity", ["- column -", "rowid", "value"]),
        (
            "/fixtures/primary_key_multiple_columns",
            ["- column -", "id", "content", "content2"],
        ),
        ("/fixtures/compound_primary_key", ["- column -", "pk1", "pk2", "content"]),
    ],
)
def test_table_html_filter_form_column_options(
    path, expected_column_options, app_client
):
    response = app_client.get(path)
    assert response.status == 200
    form = Soup(response.body, "html.parser").find("form")
    column_options = [
        o.attrs.get("value") or o.string
        for o in form.select("select[name=_filter_column] option")
    ]
    assert expected_column_options == column_options


def test_table_html_filter_form_still_shows_nocol_columns(app_client):
    # https://github.com/simonw/datasette/issues/1503
    response = app_client.get("/fixtures/sortable?_nocol=sortable")
    assert response.status == 200
    form = Soup(response.body, "html.parser").find("form")
    assert [
        o.string
        for o in form.select("select[name='_filter_column']")[0].select("option")
    ] == [
        "- column -",
        "pk1",
        "pk2",
        "content",
        "sortable_with_nulls",
        "sortable_with_nulls_2",
        "text",
        # Moved to the end because it is no longer returned by the query:
        "sortable",
    ]


def test_compound_primary_key_with_foreign_key_references(app_client):
    # e.g. a many-to-many table with a compound primary key on the two columns
    response = app_client.get("/fixtures/searchable_tags")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    expected = [
        [
            '<td class="col-Link type-pk"><a href="/fixtures/searchable_tags/1,feline">1,feline</a></td>',
            '<td class="col-searchable_id type-int"><a href="/fixtures/searchable/1">1</a>\xa0<em>1</em></td>',
            '<td class="col-tag type-str"><a href="/fixtures/tags/feline">feline</a></td>',
        ],
        [
            '<td class="col-Link type-pk"><a href="/fixtures/searchable_tags/2,canine">2,canine</a></td>',
            '<td class="col-searchable_id type-int"><a href="/fixtures/searchable/2">2</a>\xa0<em>2</em></td>',
            '<td class="col-tag type-str"><a href="/fixtures/tags/canine">canine</a></td>',
        ],
    ]
    assert expected == [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ]


def test_view_html(app_client):
    response = app_client.get("/fixtures/simple_view?_size=3")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    ths = table.select("thead th")
    assert 2 == len(ths)
    assert ths[0].find("a") is not None
    assert ths[0].find("a")["href"].endswith("/simple_view?_size=3&_sort=content")
    assert ths[0].find("a").string.strip() == "content"
    assert ths[1].find("a") is None
    assert ths[1].string.strip() == "upper_content"
    expected = [
        [
            '<td class="col-content type-str">hello</td>',
            '<td class="col-upper_content type-str">HELLO</td>',
        ],
        [
            '<td class="col-content type-str">world</td>',
            '<td class="col-upper_content type-str">WORLD</td>',
        ],
        [
            '<td class="col-content type-str">\xa0</td>',
            '<td class="col-upper_content type-str">\xa0</td>',
        ],
    ]
    assert expected == [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ]


def test_table_metadata(app_client):
    response = app_client.get("/fixtures/simple_primary_key")
    assert response.status == 200
    soup = Soup(response.body, "html.parser")
    # Page title should be custom and should be HTML escaped
    assert "This &lt;em&gt;HTML&lt;/em&gt; is escaped" == inner_html(soup.find("h1"))
    # Description should be custom and NOT escaped (we used description_html)
    assert "Simple <em>primary</em> key" == inner_html(
        soup.find("div", {"class": "metadata-description"})
    )
    # The source/license should be inherited
    assert_footer_links(soup)


@pytest.mark.parametrize(
    "path,has_object,has_stream,has_expand",
    [
        ("/fixtures/no_primary_key", False, True, False),
        ("/fixtures/complex_foreign_keys", True, False, True),
    ],
)
def test_advanced_export_box(app_client, path, has_object, has_stream, has_expand):
    response = app_client.get(path)
    assert response.status == 200
    soup = Soup(response.body, "html.parser")
    # JSON shape options
    expected_json_shapes = ["default", "array", "newline-delimited"]
    if has_object:
        expected_json_shapes.append("object")
    div = soup.find("div", {"class": "advanced-export"})
    assert expected_json_shapes == [a.text for a in div.find("p").find_all("a")]
    # "stream all rows" option
    if has_stream:
        assert "stream all rows" in str(div)
    # "expand labels" option
    if has_expand:
        assert "expand labels" in str(div)


def test_extra_where_clauses(app_client):
    response = app_client.get(
        "/fixtures/facetable?_where=_neighborhood='Dogpatch'&_where=_city_id=1"
    )
    soup = Soup(response.body, "html.parser")
    div = soup.select(".extra-wheres")[0]
    assert "2 extra where clauses" == div.find("h3").text
    hrefs = [a["href"] for a in div.find_all("a")]
    assert [
        "/fixtures/facetable?_where=_city_id%3D1",
        "/fixtures/facetable?_where=_neighborhood%3D%27Dogpatch%27",
    ] == hrefs
    # These should also be persisted as hidden fields
    inputs = soup.find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [("_where", "_neighborhood='Dogpatch'"), ("_where", "_city_id=1")] == [
        (hidden["name"], hidden["value"]) for hidden in hiddens
    ]


@pytest.mark.parametrize(
    "path,expected_hidden",
    [
        ("/fixtures/facetable?_size=10", [("_size", "10")]),
        (
            "/fixtures/facetable?_size=10&_ignore=1&_ignore=2",
            [
                ("_size", "10"),
                ("_ignore", "1"),
                ("_ignore", "2"),
            ],
        ),
    ],
)
def test_other_hidden_form_fields(app_client, path, expected_hidden):
    response = app_client.get(path)
    soup = Soup(response.body, "html.parser")
    inputs = soup.find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == expected_hidden


@pytest.mark.parametrize(
    "path,expected_hidden",
    [
        ("/fixtures/searchable?_search=terry", []),
        ("/fixtures/searchable?_sort=text2", []),
        ("/fixtures/searchable?_sort_desc=text2", []),
        ("/fixtures/searchable?_sort=text2&_where=1", [("_where", "1")]),
    ],
)
def test_search_and_sort_fields_not_duplicated(app_client, path, expected_hidden):
    # https://github.com/simonw/datasette/issues/1214
    response = app_client.get(path)
    soup = Soup(response.body, "html.parser")
    inputs = soup.find("form").find_all("input")
    hiddens = [i for i in inputs if i["type"] == "hidden"]
    assert [(hidden["name"], hidden["value"]) for hidden in hiddens] == expected_hidden


def test_binary_data_display_in_table(app_client):
    response = app_client.get("/fixtures/binary_data")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    expected_tds = [
        [
            '<td class="col-Link type-pk"><a href="/fixtures/binary_data/1">1</a></td>',
            '<td class="col-rowid type-int">1</td>',
            '<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>',
        ],
        [
            '<td class="col-Link type-pk"><a href="/fixtures/binary_data/2">2</a></td>',
            '<td class="col-rowid type-int">2</td>',
            '<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>',
        ],
        [
            '<td class="col-Link type-pk"><a href="/fixtures/binary_data/3">3</a></td>',
            '<td class="col-rowid type-int">3</td>',
            '<td class="col-data type-none">\xa0</td>',
        ],
    ]
    assert expected_tds == [
        [str(td) for td in tr.select("td")] for tr in table.select("tbody tr")
    ]


def test_custom_table_include():
    with make_app_client(
        template_dir=str(pathlib.Path(__file__).parent / "test_templates")
    ) as client:
        response = client.get("/fixtures/complex_foreign_keys")
        assert response.status == 200
        assert (
            '<div class="custom-table-row">'
            '1 - 2 - <a href="/fixtures/simple_primary_key/1">hello</a> <em>1</em>'
            "</div>"
        ) == str(Soup(response.text, "html.parser").select_one("div.custom-table-row"))


def test_metadata_sort(app_client):
    response = app_client.get("/fixtures/facet_cities")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    assert table["class"] == ["rows-and-columns"]
    ths = table.find_all("th")
    assert ["id", "name\xa0▼"] == [th.find("a").string.strip() for th in ths]
    rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    expected = [
        [
            '<td class="col-id type-pk"><a href="/fixtures/facet_cities/3">3</a></td>',
            '<td class="col-name type-str">Detroit</td>',
        ],
        [
            '<td class="col-id type-pk"><a href="/fixtures/facet_cities/2">2</a></td>',
            '<td class="col-name type-str">Los Angeles</td>',
        ],
        [
            '<td class="col-id type-pk"><a href="/fixtures/facet_cities/4">4</a></td>',
            '<td class="col-name type-str">Memnonia</td>',
        ],
        [
            '<td class="col-id type-pk"><a href="/fixtures/facet_cities/1">1</a></td>',
            '<td class="col-name type-str">San Francisco</td>',
        ],
    ]
    assert expected == rows
    # Make sure you can reverse that sort order
    response = app_client.get("/fixtures/facet_cities?_sort_desc=name")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    assert list(reversed(expected)) == rows


def test_metadata_sort_desc(app_client):
    response = app_client.get("/fixtures/attraction_characteristic")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    assert table["class"] == ["rows-and-columns"]
    ths = table.find_all("th")
    assert ["pk\xa0▲", "name"] == [th.find("a").string.strip() for th in ths]
    rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    expected = [
        [
            '<td class="col-pk type-pk"><a href="/fixtures/attraction_characteristic/2">2</a></td>',
            '<td class="col-name type-str">Paranormal</td>',
        ],
        [
            '<td class="col-pk type-pk"><a href="/fixtures/attraction_characteristic/1">1</a></td>',
            '<td class="col-name type-str">Museum</td>',
        ],
    ]
    assert expected == rows
    # Make sure you can reverse that sort order
    response = app_client.get("/fixtures/attraction_characteristic?_sort=pk")
    assert response.status == 200
    table = Soup(response.body, "html.parser").find("table")
    rows = [[str(td) for td in tr.select("td")] for tr in table.select("tbody tr")]
    assert list(reversed(expected)) == rows


@pytest.mark.parametrize(
    "max_returned_rows,path,expected_num_facets,expected_ellipses,expected_ellipses_url",
    (
        (
            5,
            # Default should show 2 facets
            "/fixtures/facetable?_facet=_neighborhood",
            2,
            True,
            "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
        ),
        # _facet_size above max_returned_rows should show max_returned_rows (5)
        (
            5,
            "/fixtures/facetable?_facet=_neighborhood&_facet_size=50",
            5,
            True,
            "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
        ),
        # If max_returned_rows is high enough, should return all
        (
            20,
            "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
            14,
            False,
            None,
        ),
        # If num facets > max_returned_rows, show ... without a link
        # _facet_size above max_returned_rows should show max_returned_rows (5)
        (
            5,
            "/fixtures/facetable?_facet=_neighborhood&_facet_size=max",
            5,
            True,
            None,
        ),
    ),
)
def test_facet_more_links(
    max_returned_rows,
    path,
    expected_num_facets,
    expected_ellipses,
    expected_ellipses_url,
):
    with make_app_client(
        settings={"max_returned_rows": max_returned_rows, "default_facet_size": 2}
    ) as client:
        response = client.get(path)
        soup = Soup(response.body, "html.parser")
        lis = soup.select("#facet-neighborhood-b352a7 ul li:not(.facet-truncated)")
        facet_truncated = soup.select_one(".facet-truncated")
        assert len(lis) == expected_num_facets
        if not expected_ellipses:
            assert facet_truncated is None
        else:
            if expected_ellipses_url:
                assert facet_truncated.find("a")["href"] == expected_ellipses_url
            else:
                assert facet_truncated.find("a") is None


def test_unavailable_table_does_not_break_sort_relationships():
    # https://github.com/simonw/datasette/issues/1305
    with make_app_client(
        metadata={
            "databases": {
                "fixtures": {"tables": {"foreign_key_references": {"allow": False}}}
            }
        }
    ) as client:
        response = client.get("/?_sort=relationships")
        assert response.status == 200


def test_column_metadata(app_client):
    response = app_client.get("/fixtures/roadside_attractions")
    soup = Soup(response.body, "html.parser")
    dl = soup.find("dl")
    assert [(dt.text, dt.next_sibling.text) for dt in dl.find_all("dt")] == [
        ("name", "The name of the attraction"),
        ("address", "The street address for the attraction"),
    ]
    assert (
        soup.select("th[data-column=name]")[0]["data-column-description"]
        == "The name of the attraction"
    )
    assert (
        soup.select("th[data-column=address]")[0]["data-column-description"]
        == "The street address for the attraction"
    )


def test_facet_total():
    # https://github.com/simonw/datasette/issues/1423
    # https://github.com/simonw/datasette/issues/1556
    with make_app_client(settings={"max_returned_rows": 100}) as client:
        path = "/fixtures/sortable?_facet=content&_facet=pk1"
        response = client.get(path)
        assert response.status == 200
    fragments = (
        '<span class="facet-info-total">&gt;30</span>',
        '<span class="facet-info-total">8</span>',
    )
    for fragment in fragments:
        assert fragment in response.text


def test_sort_rowid_with_next(app_client):
    # https://github.com/simonw/datasette/issues/1470
    response = app_client.get("/fixtures/binary_data?_size=1&_next=1&_sort=rowid")
    assert response.status == 200


def assert_querystring_equal(expected, actual):
    assert sorted(expected.split("&")) == sorted(actual.split("&"))


@pytest.mark.parametrize(
    "path,expected",
    (
        (
            "/fixtures/facetable",
            "fixtures: facetable: 15 rows",
        ),
        (
            "/fixtures/facetable?on_earth__exact=1",
            "fixtures: facetable: 14 rows where on_earth = 1",
        ),
    ),
)
def test_table_page_title(app_client, path, expected):
    response = app_client.get(path)
    title = Soup(response.text, "html.parser").find("title").text
    assert title == expected


@pytest.mark.parametrize("allow_facet", (True, False))
def test_allow_facet_off(allow_facet):
    with make_app_client(settings={"allow_facet": allow_facet}) as client:
        response = client.get("/fixtures/facetable")
        expected = "DATASETTE_ALLOW_FACET = {};".format(
            "true" if allow_facet else "false"
        )
        assert expected in response.text
        if allow_facet:
            assert "Suggested facets" in response.text
        else:
            assert "Suggested facets" not in response.text


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "size,title,length_bytes",
    (
        (2000, ' title="2.0 KB"', "2,000"),
        (20000, ' title="19.5 KB"', "20,000"),
        (20, "", "20"),
    ),
)
async def test_format_of_binary_links(size, title, length_bytes):
    ds = Datasette()
    db_name = "binary-links-{}".format(size)
    db = ds.add_memory_database(db_name)
    sql = "select zeroblob({}) as blob".format(size)
    await db.execute_write("create table blobs as {}".format(sql))
    response = await ds.client.get("/{}/blobs".format(db_name))
    assert response.status_code == 200
    expected = "{}>&lt;Binary:&nbsp;{}&nbsp;bytes&gt;</a>".format(title, length_bytes)
    assert expected in response.text
    # And test with arbitrary SQL query too
    sql_response = await ds.client.get("/{}".format(db_name), params={"sql": sql})
    assert sql_response.status_code == 200
    assert expected in sql_response.text