Debian Codegraph @

tests/test_utils.py

raw
1 """
2 Tests for various datasette helper functions.
3 """
4
5 from datasette.app import Datasette
6 from datasette import utils
7 from datasette.utils.asgi import Request
8 from datasette.utils.sqlite import sqlite3
9 import json
10 import os
11 import pathlib
12 import pytest
13 import tempfile
14 from unittest.mock import patch
15
16
17 @pytest.mark.parametrize(
18 "path,expected",
19 [
20 ("foo", ["foo"]),
21 ("foo,bar", ["foo", "bar"]),
22 ("123,433,112", ["123", "433", "112"]),
23 ("123~2C433,112", ["123,433", "112"]),
24 ("123~2F433~2F112", ["123/433/112"]),
25 ],
26 )
27 def test_urlsafe_components(path, expected):
28 assert expected == utils.urlsafe_components(path)
29
30
31 @pytest.mark.parametrize(
32 "path,added_args,expected",
33 [
34 ("/foo", {"bar": 1}, "/foo?bar=1"),
35 ("/foo?bar=1", {"baz": 2}, "/foo?bar=1&baz=2"),
36 ("/foo?bar=1&bar=2", {"baz": 3}, "/foo?bar=1&bar=2&baz=3"),
37 ("/foo?bar=1", {"bar": None}, "/foo"),
38 # Test order is preserved
39 (
40 "/?_facet=prim_state&_facet=area_name",
41 (("prim_state", "GA"),),
42 "/?_facet=prim_state&_facet=area_name&prim_state=GA",
43 ),
44 (
45 "/?_facet=state&_facet=city&state=MI",
46 (("city", "Detroit"),),
47 "/?_facet=state&_facet=city&state=MI&city=Detroit",
48 ),
49 (
50 "/?_facet=state&_facet=city",
51 (("_facet", "planet_int"),),
52 "/?_facet=state&_facet=city&_facet=planet_int",
53 ),
54 ],
55 )
56 def test_path_with_added_args(path, added_args, expected):
57 request = Request.fake(path)
58 actual = utils.path_with_added_args(request, added_args)
59 assert expected == actual
60
61
62 @pytest.mark.parametrize(
63 "path,args,expected",
64 [
65 ("/foo?bar=1", {"bar"}, "/foo"),
66 ("/foo?bar=1&baz=2", {"bar"}, "/foo?baz=2"),
67 ("/foo?bar=1&bar=2&bar=3", {"bar": "2"}, "/foo?bar=1&bar=3"),
68 ],
69 )
70 def test_path_with_removed_args(path, args, expected):
71 request = Request.fake(path)
72 actual = utils.path_with_removed_args(request, args)
73 assert expected == actual
74 # Run the test again but this time use the path= argument
75 request = Request.fake("/")
76 actual = utils.path_with_removed_args(request, args, path=path)
77 assert expected == actual
78
79
80 @pytest.mark.parametrize(
81 "path,args,expected",
82 [
83 ("/foo?bar=1", {"bar": 2}, "/foo?bar=2"),
84 ("/foo?bar=1&baz=2", {"bar": None}, "/foo?baz=2"),
85 ],
86 )
87 def test_path_with_replaced_args(path, args, expected):
88 request = Request.fake(path)
89 actual = utils.path_with_replaced_args(request, args)
90 assert expected == actual
91
92
93 @pytest.mark.parametrize(
94 "row,pks,expected_path",
95 [
96 ({"A": "foo", "B": "bar"}, ["A", "B"], "foo,bar"),
97 ({"A": "f,o", "B": "bar"}, ["A", "B"], "f~2Co,bar"),
98 ({"A": 123}, ["A"], "123"),
99 (
100 utils.CustomRow(
101 ["searchable_id", "tag"],
102 [
103 ("searchable_id", {"value": 1, "label": "1"}),
104 ("tag", {"value": "feline", "label": "feline"}),
105 ],
106 ),
107 ["searchable_id", "tag"],
108 "1,feline",
109 ),
110 ],
111 )
112 def test_path_from_row_pks(row, pks, expected_path):
113 actual_path = utils.path_from_row_pks(row, pks, False)
114 assert expected_path == actual_path
115
116
117 @pytest.mark.parametrize(
118 "obj,expected",
119 [
120 (
121 {
122 "Description": "Soft drinks",
123 "Picture": b"\x15\x1c\x02\xc7\xad\x05\xfe",
124 "CategoryID": 1,
125 },
126 """
127 {"CategoryID": 1, "Description": "Soft drinks", "Picture": {"$base64": true, "encoded": "FRwCx60F/g=="}}
128 """.strip(),
129 )
130 ],
131 )
132 def test_custom_json_encoder(obj, expected):
133 actual = json.dumps(obj, cls=utils.CustomJSONEncoder, sort_keys=True)
134 assert expected == actual
135
136
137 @pytest.mark.parametrize(
138 "bad_sql",
139 [
140 "update blah;",
141 "-- sql comment to skip\nupdate blah;",
142 "update blah set some_column='# Hello there\n\n* This is a list\n* of items\n--\n[And a link](https://github.com/simonw/datasette-render-markdown).'\nas demo_markdown",
143 "PRAGMA case_sensitive_like = true",
144 "SELECT * FROM pragma_not_on_allow_list('idx52')",
145 "/* This comment is not valid. select 1",
146 "/**/\nupdate foo set bar = 1\n/* test */ select 1",
147 ],
148 )
149 def test_validate_sql_select_bad(bad_sql):
150 with pytest.raises(utils.InvalidSql):
151 utils.validate_sql_select(bad_sql)
152
153
154 @pytest.mark.parametrize(
155 "good_sql",
156 [
157 "select count(*) from airports",
158 "select foo from bar",
159 "--sql comment to skip\nselect foo from bar",
160 "select '# Hello there\n\n* This is a list\n* of items\n--\n[And a link](https://github.com/simonw/datasette-render-markdown).'\nas demo_markdown",
161 "select 1 + 1",
162 "explain select 1 + 1",
163 "explain\nselect 1 + 1",
164 "explain query plan select 1 + 1",
165 "explain query plan\nselect 1 + 1",
166 "SELECT\nblah FROM foo",
167 "WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt;",
168 "explain WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt;",
169 "explain query plan WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt LIMIT 10) SELECT x FROM cnt;",
170 "SELECT * FROM pragma_index_info('idx52')",
171 "select * from pragma_table_xinfo('table')",
172 # Various types of comment
173 "-- comment\nselect 1",
174 "-- one line\n -- two line\nselect 1",
175 " /* comment */\nselect 1",
176 " /* comment */select 1",
177 "/* comment */\n -- another\n /* one more */ select 1",
178 "/* This comment \n has multiple lines */\nselect 1",
179 ],
180 )
181 def test_validate_sql_select_good(good_sql):
182 utils.validate_sql_select(good_sql)
183
184
185 @pytest.mark.parametrize("open_quote,close_quote", [('"', '"'), ("[", "]")])
186 def test_detect_fts(open_quote, close_quote):
187 sql = """
188 CREATE TABLE "Dumb_Table" (
189 "TreeID" INTEGER,
190 "qSpecies" TEXT
191 );
192 CREATE TABLE "Street_Tree_List" (
193 "TreeID" INTEGER,
194 "qSpecies" TEXT,
195 "qAddress" TEXT,
196 "SiteOrder" INTEGER,
197 "qSiteInfo" TEXT,
198 "PlantType" TEXT,
199 "qCaretaker" TEXT
200 );
201 CREATE VIEW Test_View AS SELECT * FROM Dumb_Table;
202 CREATE VIRTUAL TABLE {open}Street_Tree_List_fts{close} USING FTS4 ("qAddress", "qCaretaker", "qSpecies", content={open}Street_Tree_List{close});
203 CREATE VIRTUAL TABLE r USING rtree(a, b, c);
204 """.format(
205 open=open_quote, close=close_quote
206 )
207 conn = utils.sqlite3.connect(":memory:")
208 conn.executescript(sql)
209 assert None is utils.detect_fts(conn, "Dumb_Table")
210 assert None is utils.detect_fts(conn, "Test_View")
211 assert None is utils.detect_fts(conn, "r")
212 assert "Street_Tree_List_fts" == utils.detect_fts(conn, "Street_Tree_List")
213
214
215 @pytest.mark.parametrize(
216 "identifier,expected",
217 (
218 ("plain", "plain"),
219 ("plain\n", "[plain\n]"),
220 ("select\n", "[select\n]"),
221 ("select", "[select]"),
222 ("has space", "[has space]"),
223 ("has]bracket", '"has]bracket"'),
224 ('has"quote]', '"has""quote]"'),
225 ),
226 )
227 def test_escape_sqlite(identifier, expected):
228 assert utils.escape_sqlite(identifier) == expected
229
230
231 def test_escape_sqlite_closing_bracket_works_in_query():
232 conn = utils.sqlite3.connect(":memory:")
233 table = "has]bracket"
234 escaped_table = utils.escape_sqlite(table)
235 conn.execute(f"create table {escaped_table} (id integer)")
236 conn.execute(f"insert into {escaped_table} values (1)")
237 assert conn.execute(f"select id from {escaped_table}").fetchall() == [(1,)]
238 conn.close()
239
240
241 @pytest.mark.parametrize("table", ("regular", "has'single quote"))
242 def test_detect_fts_different_table_names(table):
243 sql = """
244 CREATE TABLE [{table}] (
245 "TreeID" INTEGER,
246 "qSpecies" TEXT
247 );
248 CREATE VIRTUAL TABLE [{table}_fts] USING FTS4 ("qSpecies", content="{table}");
249 """.format(
250 table=table
251 )
252 conn = utils.sqlite3.connect(":memory:")
253 conn.executescript(sql)
254 assert "{table}_fts".format(table=table) == utils.detect_fts(conn, table)
255
256
257 @pytest.mark.parametrize(
258 "url,expected",
259 [
260 ("http://www.google.com/", True),
261 ("https://example.com/", True),
262 ("www.google.com", False),
263 ("http://www.google.com/ is a search engine", False),
264 ],
265 )
266 def test_is_url(url, expected):
267 assert expected == utils.is_url(url)
268
269
270 @pytest.mark.parametrize(
271 "s,expected",
272 [
273 ("simple", "simple"),
274 ("MixedCase", "MixedCase"),
275 ("-no-leading-hyphens", "no-leading-hyphens-65bea6"),
276 ("_no-leading-underscores", "no-leading-underscores-b921bc"),
277 ("no spaces", "no-spaces-7088d7"),
278 ("-", "336d5e"),
279 ("no $ characters", "no--characters-59e024"),
280 ],
281 )
282 def test_to_css_class(s, expected):
283 assert expected == utils.to_css_class(s)
284
285
286 def test_temporary_docker_directory_uses_hard_link():
287 with tempfile.TemporaryDirectory() as td:
288 os.chdir(td)
289 with open("hello", "w") as fp:
290 fp.write("world")
291 # Default usage of this should use symlink
292 with utils.temporary_docker_directory(
293 files=["hello"],
294 name="t",
295 metadata=None,
296 extra_options=None,
297 branch=None,
298 template_dir=None,
299 plugins_dir=None,
300 static=[],
301 install=[],
302 spatialite=False,
303 version_note=None,
304 secret="secret",
305 ) as temp_docker:
306 hello = os.path.join(temp_docker, "hello")
307 with open(hello) as fp:
308 assert "world" == fp.read()
309 # It should be a hard link
310 assert 2 == os.stat(hello).st_nlink
311
312
313 @patch("os.link")
314 def test_temporary_docker_directory_uses_copy_if_hard_link_fails(mock_link):
315 # Copy instead if os.link raises OSError (normally due to different device)
316 mock_link.side_effect = OSError
317 with tempfile.TemporaryDirectory() as td:
318 os.chdir(td)
319 with open("hello", "w") as fp:
320 fp.write("world")
321 # Default usage of this should use symlink
322 with utils.temporary_docker_directory(
323 files=["hello"],
324 name="t",
325 metadata=None,
326 extra_options=None,
327 branch=None,
328 template_dir=None,
329 plugins_dir=None,
330 static=[],
331 install=[],
332 spatialite=False,
333 version_note=None,
334 secret=None,
335 ) as temp_docker:
336 hello = os.path.join(temp_docker, "hello")
337 with open(hello) as fp:
338 assert "world" == fp.read()
339 # It should be a copy, not a hard link
340 assert 1 == os.stat(hello).st_nlink
341
342
343 def test_temporary_docker_directory_quotes_args():
344 with tempfile.TemporaryDirectory() as td:
345 os.chdir(td)
346 with open("hello", "w") as fp:
347 fp.write("world")
348 with utils.temporary_docker_directory(
349 files=["hello"],
350 name="t",
351 metadata=None,
352 extra_options="--$HOME",
353 branch=None,
354 template_dir=None,
355 plugins_dir=None,
356 static=[],
357 install=[],
358 spatialite=False,
359 version_note="$PWD",
360 secret="secret",
361 ) as temp_docker:
362 df = os.path.join(temp_docker, "Dockerfile")
363 with open(df) as fp:
364 df_contents = fp.read()
365 assert "'$PWD'" in df_contents
366 assert "'--$HOME'" in df_contents
367 assert "ENV DATASETTE_SECRET 'secret'" in df_contents
368
369
370 def test_compound_keys_after_sql():
371 assert "((a > :p0))" == utils.compound_keys_after_sql(["a"])
372 assert """
373 ((a > :p0)
374 or
375 (a = :p0 and b > :p1))
376 """.strip() == utils.compound_keys_after_sql(
377 ["a", "b"]
378 )
379 assert """
380 ((a > :p0)
381 or
382 (a = :p0 and b > :p1)
383 or
384 (a = :p0 and b = :p1 and c > :p2))
385 """.strip() == utils.compound_keys_after_sql(
386 ["a", "b", "c"]
387 )
388
389
390 def test_table_columns():
391 conn = sqlite3.connect(":memory:")
392 conn.executescript(
393 """
394 create table places (id integer primary key, name text, bob integer)
395 """
396 )
397 assert ["id", "name", "bob"] == utils.table_columns(conn, "places")
398
399
400 @pytest.mark.parametrize(
401 "path,format,extra_qs,expected",
402 [
403 ("/foo?sql=select+1", "csv", {}, "/foo.csv?sql=select+1"),
404 ("/foo?sql=select+1", "json", {}, "/foo.json?sql=select+1"),
405 ("/foo/bar", "json", {}, "/foo/bar.json"),
406 ("/foo/bar", "csv", {}, "/foo/bar.csv"),
407 ("/foo/bar", "csv", {"_dl": 1}, "/foo/bar.csv?_dl=1"),
408 (
409 "/sf-trees/Street_Tree_List?_search=cherry&_size=1000",
410 "csv",
411 {"_dl": 1},
412 "/sf-trees/Street_Tree_List.csv?_search=cherry&_size=1000&_dl=1",
413 ),
414 ],
415 )
416 def test_path_with_format(path, format, extra_qs, expected):
417 request = Request.fake(path)
418 actual = utils.path_with_format(request=request, format=format, extra_qs=extra_qs)
419 assert expected == actual
420
421
422 @pytest.mark.parametrize(
423 "bytes,expected",
424 [
425 (120, "120 bytes"),
426 (1024, "1.0 KB"),
427 (1024 * 1024, "1.0 MB"),
428 (1024 * 1024 * 1024, "1.0 GB"),
429 (1024 * 1024 * 1024 * 1.3, "1.3 GB"),
430 (1024 * 1024 * 1024 * 1024, "1.0 TB"),
431 ],
432 )
433 def test_format_bytes(bytes, expected):
434 assert expected == utils.format_bytes(bytes)
435
436
437 @pytest.mark.parametrize(
438 "query,expected",
439 [
440 ("dog", '"dog"'),
441 ("cat,", '"cat,"'),
442 ("cat dog", '"cat" "dog"'),
443 # If a phrase is already double quoted, leave it so
444 ('"cat dog"', '"cat dog"'),
445 ('"cat dog" fish', '"cat dog" "fish"'),
446 # Sensibly handle unbalanced double quotes
447 ('cat"', '"cat"'),
448 ('"cat dog" "fish', '"cat dog" "fish"'),
449 ],
450 )
451 def test_escape_fts(query, expected):
452 assert expected == utils.escape_fts(query)
453
454
455 @pytest.mark.parametrize(
456 "input,expected",
457 [
458 ("dog", "dog"),
459 ('dateutil_parse("1/2/2020")', r"dateutil_parse(\0000221/2/2020\000022)"),
460 ("this\r\nand\r\nthat", r"this\00000Aand\00000Athat"),
461 ],
462 )
463 def test_escape_css_string(input, expected):
464 assert expected == utils.escape_css_string(input)
465
466
467 def test_check_connection_spatialite_raises():
468 path = str(pathlib.Path(__file__).parent / "spatialite.db")
469 conn = sqlite3.connect(path)
470 with pytest.raises(utils.SpatialiteConnectionProblem):
471 utils.check_connection(conn)
472
473
474 def test_check_connection_passes():
475 conn = sqlite3.connect(":memory:")
476 utils.check_connection(conn)
477
478
479 def test_call_with_supported_arguments():
480 def foo(a, b):
481 return f"{a}+{b}"
482
483 assert "1+2" == utils.call_with_supported_arguments(foo, a=1, b=2)
484 assert "1+2" == utils.call_with_supported_arguments(foo, a=1, b=2, c=3)
485
486 with pytest.raises(TypeError):
487 utils.call_with_supported_arguments(foo, a=1)
488
489
490 @pytest.mark.parametrize(
491 "data,should_raise",
492 [
493 ([["foo", "bar"], ["foo", "baz"]], False),
494 ([("foo", "bar"), ("foo", "baz")], False),
495 ((["foo", "bar"], ["foo", "baz"]), False),
496 ([["foo", "bar"], ["foo", "baz", "bax"]], True),
497 ({"foo": ["bar", "baz"]}, False),
498 ({"foo": ("bar", "baz")}, False),
499 ({"foo": "bar"}, True),
500 ],
501 )
502 def test_multi_params(data, should_raise):
503 if should_raise:
504 with pytest.raises(AssertionError):
505 utils.MultiParams(data)
506 return
507 p1 = utils.MultiParams(data)
508 assert "bar" == p1["foo"]
509 assert ["bar", "baz"] == list(p1.getlist("foo"))
510
511
512 @pytest.mark.parametrize(
513 "actor,allow,expected",
514 [
515 # Default is to allow:
516 (None, None, True),
517 # {} means deny-all:
518 (None, {}, False),
519 ({"id": "root"}, {}, False),
520 # true means allow-all
521 ({"id": "root"}, True, True),
522 (None, True, True),
523 # false means deny-all
524 ({"id": "root"}, False, False),
525 (None, False, False),
526 # Special case for "unauthenticated": true
527 (None, {"unauthenticated": True}, True),
528 (None, {"unauthenticated": False}, False),
529 # Match on just one property:
530 (None, {"id": "root"}, False),
531 ({"id": "root"}, None, True),
532 ({"id": "simon", "staff": True}, {"staff": True}, True),
533 ({"id": "simon", "staff": False}, {"staff": True}, False),
534 # Special "*" value for any key:
535 ({"id": "root"}, {"id": "*"}, True),
536 ({}, {"id": "*"}, False),
537 ({"name": "root"}, {"id": "*"}, False),
538 # Supports single strings or list of values:
539 ({"id": "root"}, {"id": "bob"}, False),
540 ({"id": "root"}, {"id": ["bob"]}, False),
541 ({"id": "root"}, {"id": "root"}, True),
542 ({"id": "root"}, {"id": ["root"]}, True),
543 # Any matching role will work:
544 ({"id": "garry", "roles": ["staff", "dev"]}, {"roles": ["staff"]}, True),
545 ({"id": "garry", "roles": ["staff", "dev"]}, {"roles": ["dev"]}, True),
546 ({"id": "garry", "roles": ["staff", "dev"]}, {"roles": ["otter"]}, False),
547 ({"id": "garry", "roles": ["staff", "dev"]}, {"roles": ["dev", "otter"]}, True),
548 ({"id": "garry", "roles": []}, {"roles": ["staff"]}, False),
549 ({"id": "garry"}, {"roles": ["staff"]}, False),
550 # Any single matching key works:
551 ({"id": "root"}, {"bot_id": "my-bot", "id": ["root"]}, True),
552 ],
553 )
554 def test_actor_matches_allow(actor, allow, expected):
555 assert expected == utils.actor_matches_allow(actor, allow)
556
557
558 @pytest.mark.parametrize(
559 "config,expected",
560 [
561 ({"foo": "bar"}, {"foo": "bar"}),
562 ({"$env": "FOO"}, "x"),
563 ({"k": {"$env": "FOO"}}, {"k": "x"}),
564 ([{"k": {"$env": "FOO"}}, {"z": {"$env": "FOO"}}], [{"k": "x"}, {"z": "x"}]),
565 ({"k": [{"in_a_list": {"$env": "FOO"}}]}, {"k": [{"in_a_list": "x"}]}),
566 ],
567 )
568 def test_resolve_env_secrets(config, expected):
569 assert expected == utils.resolve_env_secrets(config, {"FOO": "x"})
570
571
572 @pytest.mark.parametrize(
573 "actor,expected",
574 [
575 ({"id": "blah"}, "blah"),
576 ({"id": "blah", "login": "l"}, "l"),
577 ({"id": "blah", "login": "l"}, "l"),
578 ({"id": "blah", "login": "l", "username": "u"}, "u"),
579 ({"login": "l", "name": "n"}, "n"),
580 (
581 {"id": "blah", "login": "l", "username": "u", "name": "n", "display": "d"},
582 "d",
583 ),
584 ({"weird": "shape"}, "{'weird': 'shape'}"),
585 ],
586 )
587 def test_display_actor(actor, expected):
588 assert expected == utils.display_actor(actor)
589
590
591 @pytest.mark.asyncio
592 @pytest.mark.parametrize(
593 "dbs,expected_path",
594 [
595 (["one_table"], "/one/one"),
596 (["two_tables"], "/two"),
597 (["one_table", "two_tables"], "/"),
598 ],
599 )
600 async def test_initial_path_for_datasette(tmp_path_factory, dbs, expected_path):
601 db_dir = tmp_path_factory.mktemp("dbs")
602 one_table = str(db_dir / "one.db")
603 sqlite3.connect(one_table).execute("create table one (id integer primary key)")
604 two_tables = str(db_dir / "two.db")
605 sqlite3.connect(two_tables).execute("create table two (id integer primary key)")
606 sqlite3.connect(two_tables).execute("create table three (id integer primary key)")
607 datasette = Datasette(
608 [{"one_table": one_table, "two_tables": two_tables}[db] for db in dbs]
609 )
610 path = await utils.initial_path_for_datasette(datasette)
611 assert path == expected_path
612
613
614 @pytest.mark.parametrize(
615 "content,expected",
616 (
617 ("title: Hello", {"title": "Hello"}),
618 ('{"title": "Hello"}', {"title": "Hello"}),
619 ("{{ this }} is {{ bad }}", None),
620 ),
621 )
622 def test_parse_metadata(content, expected):
623 if expected is None:
624 with pytest.raises(utils.BadMetadataError):
625 utils.parse_metadata(content)
626 else:
627 assert utils.parse_metadata(content) == expected
628
629
630 @pytest.mark.asyncio
631 @pytest.mark.parametrize(
632 "sql,expected",
633 (
634 ("select 1", []),
635 ("select 1 + :one", ["one"]),
636 ("select 1 + :one + :two", ["one", "two"]),
637 ("select 'bob' || '0:00' || :cat", ["cat"]),
638 ("select this is invalid :one, :two, :three", ["one", "two", "three"]),
639 ),
640 )
641 async def test_derive_named_parameters(sql, expected):
642 ds = Datasette([], memory=True)
643 db = ds.get_database("_memory")
644 params = await utils.derive_named_parameters(db, sql)
645 assert params == expected
646
647
648 @pytest.mark.parametrize(
649 "original,expected",
650 (
651 ("abc", "abc"),
652 ("/foo/bar", "~2Ffoo~2Fbar"),
653 ("/-/bar", "~2F-~2Fbar"),
654 ("-/db-/table.csv", "-~2Fdb-~2Ftable~2Ecsv"),
655 (r"%~-/", "~25~7E-~2F"),
656 ("~25~7E~2D~2F", "~7E25~7E7E~7E2D~7E2F"),
657 ("with space", "with+space"),
658 ),
659 )
660 def test_tilde_encoding(original, expected):
661 actual = utils.tilde_encode(original)
662 assert actual == expected
663 # And test round-trip
664 assert original == utils.tilde_decode(actual)
665
666
667 @pytest.mark.parametrize(
668 "url,length,expected",
669 (
670 ("https://example.com/", 5, "http…"),
671 ("https://example.com/foo/bar", 15, "https://exampl…"),
672 ("https://example.com/foo/bar/baz.jpg", 30, "https://example.com/foo/ba….jpg"),
673 # Extensions longer than 4 characters are not treated specially:
674 ("https://example.com/foo/bar/baz.jpeg2", 30, "https://example.com/foo/bar/b…"),
675 (
676 "https://example.com/foo/bar/baz.jpeg2",
677 None,
678 "https://example.com/foo/bar/baz.jpeg2",
679 ),
680 ),
681 )
682 def test_truncate_url(url, length, expected):
683 actual = utils.truncate_url(url, length)
684 assert actual == expected