Debian Codegraph @

tests/test_filters.py

raw
1 from datasette.filters import Filters, through_filters, where_filters, search_filters
2 from datasette.utils.asgi import Request
3 from .fixtures import app_client
4 import pytest
5
6
7 @pytest.mark.parametrize(
8 "args,expected_where,expected_params",
9 [
10 ((("name_english__contains", "foo"),), ['"name_english" like :p0'], ["%foo%"]),
11 (
12 (("foo", "bar"), ("bar__contains", "baz")),
13 ['"bar" like :p0', '"foo" = :p1'],
14 ["%baz%", "bar"],
15 ),
16 (
17 (("foo__startswith", "bar"), ("bar__endswith", "baz")),
18 ['"bar" like :p0', '"foo" like :p1'],
19 ["%baz", "bar%"],
20 ),
21 (
22 (("foo__lt", "1"), ("bar__gt", "2"), ("baz__gte", "3"), ("bax__lte", "4")),
23 ['"bar" > :p0', '"bax" <= :p1', '"baz" >= :p2', '"foo" < :p3'],
24 [2, 4, 3, 1],
25 ),
26 (
27 (("foo__like", "2%2"), ("zax__glob", "3*")),
28 ['"foo" like :p0', '"zax" glob :p1'],
29 ["2%2", "3*"],
30 ),
31 # Multiple like arguments:
32 (
33 (("foo__like", "2%2"), ("foo__like", "3%3")),
34 ['"foo" like :p0', '"foo" like :p1'],
35 ["2%2", "3%3"],
36 ),
37 # notlike:
38 (
39 (("foo__notlike", "2%2"),),
40 ['"foo" not like :p0'],
41 ["2%2"],
42 ),
43 (
44 (("foo__isnull", "1"), ("baz__isnull", "1"), ("bar__gt", "10")),
45 ['"bar" > :p0', '"baz" is null', '"foo" is null'],
46 [10],
47 ),
48 ((("foo__in", "1,2,3"),), ["foo in (:p0, :p1, :p2)"], ["1", "2", "3"]),
49 # date
50 ((("foo__date", "1988-01-01"),), ['date("foo") = :p0'], ["1988-01-01"]),
51 # JSON array variants of __in (useful for unexpected characters)
52 ((("foo__in", "[1,2,3]"),), ["foo in (:p0, :p1, :p2)"], [1, 2, 3]),
53 (
54 (("foo__in", '["dog,cat", "cat[dog]"]'),),
55 ["foo in (:p0, :p1)"],
56 ["dog,cat", "cat[dog]"],
57 ),
58 # Not in, and JSON array not in
59 ((("foo__notin", "1,2,3"),), ["foo not in (:p0, :p1, :p2)"], ["1", "2", "3"]),
60 ((("foo__notin", "[1,2,3]"),), ["foo not in (:p0, :p1, :p2)"], [1, 2, 3]),
61 # JSON arraycontains, arraynotcontains
62 (
63 (("Availability+Info__arraycontains", "yes"),),
64 [":p0 in (select value from json_each([table].[Availability+Info]))"],
65 ["yes"],
66 ),
67 (
68 (("Availability+Info__arraynotcontains", "yes"),),
69 [":p0 not in (select value from json_each([table].[Availability+Info]))"],
70 ["yes"],
71 ),
72 ],
73 )
74 def test_build_where(args, expected_where, expected_params):
75 f = Filters(sorted(args))
76 sql_bits, actual_params = f.build_where_clauses("table")
77 assert expected_where == sql_bits
78 assert {f"p{i}": param for i, param in enumerate(expected_params)} == actual_params
79
80
81 @pytest.mark.parametrize(
82 "key,expected_where",
83 (
84 (
85 'has"quote__exact',
86 '[has"quote] = :p0',
87 ),
88 (
89 'has"quote__isnull',
90 '[has"quote] is null',
91 ),
92 (
93 "has]bracket__arraycontains",
94 ':p0 in (select value from json_each([table]."has]bracket"))',
95 ),
96 ),
97 )
98 def test_build_where_escapes_column_names(key, expected_where):
99 filters = Filters(((key, "value"),))
100 sql_bits, _ = filters.build_where_clauses("table")
101 assert sql_bits == [expected_where]
102
103
104 def test_build_where_escapes_table_name():
105 filters = Filters((("tags__arraycontains", "value"),))
106 sql_bits, _ = filters.build_where_clauses("items]bracket")
107 assert sql_bits == [':p0 in (select value from json_each("items]bracket"."tags"))']
108
109
110 @pytest.mark.asyncio
111 async def test_through_filters_from_request(app_client):
112 request = Request.fake(
113 '/?_through={"table":"roadside_attraction_characteristics","column":"characteristic_id","value":"1"}'
114 )
115 filter_args = await through_filters(
116 request=request,
117 datasette=app_client.ds,
118 table="roadside_attractions",
119 database="fixtures",
120 )()
121 assert filter_args.where_clauses == [
122 "pk in (select attraction_id from roadside_attraction_characteristics where characteristic_id = :p0)"
123 ]
124 assert filter_args.params == {"p0": "1"}
125 assert filter_args.human_descriptions == [
126 'roadside_attraction_characteristics.characteristic_id = "1"'
127 ]
128 assert filter_args.extra_context == {}
129
130
131 @pytest.mark.asyncio
132 async def test_through_filters_from_request(app_client):
133 request = Request.fake(
134 '/?_through={"table":"roadside_attraction_characteristics","column":"characteristic_id","value":"1"}'
135 )
136 filter_args = await through_filters(
137 request=request,
138 datasette=app_client.ds,
139 table="roadside_attractions",
140 database="fixtures",
141 )()
142 assert filter_args.where_clauses == [
143 "pk in (select attraction_id from roadside_attraction_characteristics where characteristic_id = :p0)"
144 ]
145 assert filter_args.params == {"p0": "1"}
146 assert filter_args.human_descriptions == [
147 'roadside_attraction_characteristics.characteristic_id = "1"'
148 ]
149 assert filter_args.extra_context == {}
150
151
152 @pytest.mark.asyncio
153 async def test_where_filters_from_request(app_client):
154 request = Request.fake("/?_where=pk+>+3")
155 filter_args = await where_filters(
156 request=request,
157 datasette=app_client.ds,
158 database="fixtures",
159 )()
160 assert filter_args.where_clauses == ["pk > 3"]
161 assert filter_args.params == {}
162 assert filter_args.human_descriptions == []
163 assert filter_args.extra_context == {
164 "extra_wheres_for_ui": [{"text": "pk > 3", "remove_url": "/"}]
165 }
166
167
168 @pytest.mark.asyncio
169 async def test_search_filters_from_request(app_client):
170 request = Request.fake("/?_search=bobcat")
171 filter_args = await search_filters(
172 request=request,
173 datasette=app_client.ds,
174 database="fixtures",
175 table="searchable",
176 )()
177 assert filter_args.where_clauses == [
178 "rowid in (select rowid from searchable_fts where searchable_fts match escape_fts(:search))"
179 ]
180 assert filter_args.params == {"search": "bobcat"}
181 assert filter_args.human_descriptions == ['search matches "bobcat"']
182 assert filter_args.extra_context == {"supports_search": True, "search": "bobcat"}