-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_urldispatch.py
1406 lines (1060 loc) · 46.5 KB
/
test_urldispatch.py
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
import asyncio
import pathlib
import re
from collections.abc import Container, Iterable, Mapping, MutableMapping, Sized
from functools import partial
from typing import Awaitable, Callable, Dict, List, NoReturn, Optional, Type
from urllib.parse import quote, unquote
import pytest
from yarl import URL
import aiohttp
from aiohttp import hdrs, web
from aiohttp.test_utils import make_mocked_request
from aiohttp.web_urldispatcher import (
PATH_SEP,
Domain,
MaskDomain,
SystemRoute,
_default_expect_handler,
)
def make_handler() -> Callable[[web.Request], Awaitable[NoReturn]]:
async def handler(request: web.Request) -> NoReturn:
assert False
return handler
def make_partial_handler() -> Callable[[web.Request], Awaitable[NoReturn]]:
async def handler(a: int, request: web.Request) -> NoReturn:
assert False
return partial(handler, 5)
@pytest.fixture
def app() -> web.Application:
return web.Application()
@pytest.fixture
def router(app: web.Application) -> web.UrlDispatcher:
return app.router
@pytest.fixture
def fill_routes(router: web.UrlDispatcher) -> Callable[[], List[web.AbstractRoute]]:
def go() -> List[web.AbstractRoute]:
route1 = router.add_route("GET", "/plain", make_handler())
route2 = router.add_route("GET", "/variable/{name}", make_handler())
resource = router.add_static("/static", pathlib.Path(aiohttp.__file__).parent)
return [route1, route2] + list(resource)
return go
def test_register_uncommon_http_methods(router: web.UrlDispatcher) -> None:
uncommon_http_methods = {
"PROPFIND",
"PROPPATCH",
"COPY",
"LOCK",
"UNLOCK",
"MOVE",
"SUBSCRIBE",
"UNSUBSCRIBE",
"NOTIFY",
}
for method in uncommon_http_methods:
router.add_route(method, "/handler/to/path", make_handler())
async def test_add_partial_handler(router: web.UrlDispatcher) -> None:
handler = make_partial_handler()
router.add_get("/handler/to/path", handler)
async def test_add_sync_handler(router: web.UrlDispatcher) -> None:
def handler(request: web.Request) -> NoReturn:
assert False
with pytest.raises(TypeError):
router.add_get("/handler/to/path", handler)
async def test_add_route_root(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_simple(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path", handler)
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_with_matchdict(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/{to}", handler)
req = make_mocked_request("GET", "/handler/tail")
info = await router.resolve(req)
assert info is not None
assert {"to": "tail"} == info
assert handler is info.handler
assert info.route.name is None
async def test_add_with_matchdict_with_colon(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/{to}", handler)
req = make_mocked_request("GET", "/handler/1:2:3")
info = await router.resolve(req)
assert info is not None
assert {"to": "1:2:3"} == info
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_get_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_get("/handler/to/path", handler)
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_post_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_post("/handler/to/path", handler)
req = make_mocked_request("POST", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_put_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_put("/handler/to/path", handler)
req = make_mocked_request("PUT", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_patch_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_patch("/handler/to/path", handler)
req = make_mocked_request("PATCH", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_delete_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_delete("/handler/to/path", handler)
req = make_mocked_request("DELETE", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_route_with_add_head_shortcut(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_head("/handler/to/path", handler)
req = make_mocked_request("HEAD", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert 0 == len(info)
assert handler is info.handler
assert info.route.name is None
async def test_add_with_name(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path", handler, name="name")
req = make_mocked_request("GET", "/handler/to/path")
info = await router.resolve(req)
assert info is not None
assert "name" == info.route.name
async def test_add_with_tailing_slash(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/handler/to/path/", handler)
req = make_mocked_request("GET", "/handler/to/path/")
info = await router.resolve(req)
assert info is not None
assert {} == info
assert handler is info.handler
def test_add_invalid_path(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("GET", "/{/", handler)
def test_add_url_invalid1(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id", handler)
def test_add_url_invalid2(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id{}}", handler)
def test_add_url_invalid3(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", "/post/{id{}", handler)
def test_add_url_invalid4(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError):
router.add_route("post", '/post/{id"}', handler)
async def test_add_url_escaping(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/+$", handler)
req = make_mocked_request("GET", "/+$")
info = await router.resolve(req)
assert info is not None
assert handler is info.handler
async def test_any_method(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route(hdrs.METH_ANY, "/", handler)
req = make_mocked_request("GET", "/")
info1 = await router.resolve(req)
assert info1 is not None
assert route is info1.route
req = make_mocked_request("POST", "/")
info2 = await router.resolve(req)
assert info2 is not None
assert info1.route is info2.route
async def test_any_method_appears_in_routes(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route(hdrs.METH_ANY, "/", handler)
assert route in router.routes()
async def test_match_second_result_in_table(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/h1", handler1)
router.add_route("POST", "/h2", handler2)
req = make_mocked_request("POST", "/h2")
info = await router.resolve(req)
assert info is not None
assert {} == info
assert handler2 is info.handler
async def test_raise_method_not_allowed(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/", handler1)
router.add_route("POST", "/", handler2)
req = make_mocked_request("PUT", "/")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPMethodNotAllowed) as ctx:
await match_info.handler(req)
exc = ctx.value
assert "PUT" == exc.method
assert 405 == exc.status
assert {"POST", "GET"} == exc.allowed_methods
async def test_raise_method_not_found(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/a", handler)
req = make_mocked_request("GET", "/b")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPNotFound) as ctx:
await match_info.handler(req)
exc = ctx.value
assert 404 == exc.status
def test_double_add_url_with_the_same_name(router: web.UrlDispatcher) -> None:
handler1 = make_handler()
handler2 = make_handler()
router.add_route("GET", "/get", handler1, name="name")
with pytest.raises(ValueError) as ctx:
router.add_route("GET", "/get_other", handler2, name="name")
assert str(ctx.value).startswith("Duplicate 'name', already handled by")
def test_route_plain(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", "/get", handler, name="name")
route2 = next(iter(router["name"]))
url = route2.url_for()
assert "/get" == str(url)
assert route is route2
def test_route_unknown_route_name(router: web.UrlDispatcher) -> None:
with pytest.raises(KeyError):
router["unknown"]
def test_route_dynamic(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", "/get/{name}", handler, name="name")
route2 = next(iter(router["name"]))
url = route2.url_for(name="John")
assert "/get/John" == str(url)
assert route is route2
def test_add_static_path_checks(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
"""Test that static paths must exist and be directories."""
with pytest.raises(ValueError, match="does not exist"):
router.add_static("/", tmp_path / "does-not-exist")
with pytest.raises(ValueError, match="is not a directory"):
router.add_static("/", __file__)
def test_add_static_path_resolution(router: web.UrlDispatcher) -> None:
"""Test that static paths are expanded and absolute."""
res = router.add_static("/", "~/..")
directory = str(res.get_info()["directory"])
assert directory == str(pathlib.Path.home().parent)
def test_add_static(router: web.UrlDispatcher) -> None:
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
assert router["static"] is resource
url = resource.url_for(filename="/dir/a.txt")
assert "/st/dir/a.txt" == str(url)
assert len(resource) == 2
def test_add_static_append_version(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="/data.unknown_mime_type", append_version=True)
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_set_from_constructor(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static(
"/st", pathlib.Path(__file__).parent, append_version=True, name="static"
)
url = resource.url_for(filename="/data.unknown_mime_type")
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_override_constructor(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static(
"/st", pathlib.Path(__file__).parent, append_version=True, name="static"
)
url = resource.url_for(filename="/data.unknown_mime_type", append_version=False)
expect_url = "/st/data.unknown_mime_type"
assert expect_url == str(url)
def test_add_static_append_version_filename_without_slash(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="data.unknown_mime_type", append_version=True)
expect_url = (
"/st/data.unknown_mime_type?v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_non_exists_file(router: web.UrlDispatcher) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="/non_exists_file", append_version=True)
assert "/st/non_exists_file" == str(url)
def test_add_static_append_version_non_exists_file_without_slash(
router: web.UrlDispatcher,
) -> None:
resource = router.add_static("/st", pathlib.Path(__file__).parent, name="static")
url = resource.url_for(filename="non_exists_file", append_version=True)
assert "/st/non_exists_file" == str(url)
def test_add_static_append_version_follow_symlink(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
# Tests the access to a symlink, in static folder with apeend_version
symlink_path = tmp_path / "append_version_symlink"
symlink_target_path = pathlib.Path(__file__).parent
pathlib.Path(str(symlink_path)).symlink_to(str(symlink_target_path), True)
# Register global static route:
resource = router.add_static(
"/st", str(tmp_path), follow_symlinks=True, append_version=True
)
url = resource.url_for(filename="/append_version_symlink/data.unknown_mime_type")
expect_url = (
"/st/append_version_symlink/data.unknown_mime_type?"
"v=aUsn8CHEhhszc81d28QmlcBW0KQpfS2F4trgQKhOYd8%3D"
)
assert expect_url == str(url)
def test_add_static_append_version_not_follow_symlink(
router: web.UrlDispatcher, tmp_path: pathlib.Path
) -> None:
# Tests the access to a symlink, in static folder with apeend_version
symlink_path = tmp_path / "append_version_symlink"
symlink_target_path = pathlib.Path(__file__).parent
pathlib.Path(str(symlink_path)).symlink_to(str(symlink_target_path), True)
# Register global static route:
resource = router.add_static(
"/st", str(tmp_path), follow_symlinks=False, append_version=True
)
filename = "/append_version_symlink/data.unknown_mime_type"
url = resource.url_for(filename=filename)
assert "/st/append_version_symlink/data.unknown_mime_type" == str(url)
def test_add_static_quoting(router: web.UrlDispatcher) -> None:
resource = router.add_static(
"/пре %2Fфикс", pathlib.Path(aiohttp.__file__).parent, name="static"
)
assert router["static"] is resource
url = resource.url_for(filename="/1 2/файл%2F.txt")
assert url.path == "/пре /фикс/1 2/файл%2F.txt"
assert str(url) == (
"/%D0%BF%D1%80%D0%B5%20%2F%D1%84%D0%B8%D0%BA%D1%81"
"/1%202/%D1%84%D0%B0%D0%B9%D0%BB%252F.txt"
)
assert len(resource) == 2
def test_plain_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/path", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert route._match("/another/path") is None
def test_dynamic_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert route._match("/another/path") is None
async def test_static_not_match(router: web.UrlDispatcher) -> None:
router.add_static("/pre", pathlib.Path(aiohttp.__file__).parent, name="name")
resource = router["name"]
ret = await resource.resolve(make_mocked_request("GET", "/another/path"))
assert (None, set()) == ret
async def test_add_static_access_resources(router: web.UrlDispatcher) -> None:
"""Test accessing resource._routes externally.
aiohttp-cors accesses the resource._routes, this test ensures that this
continues to work.
"""
# https://github.com/aio-libs/aiohttp-cors/blob/38c6c17bffc805e46baccd7be1b4fd8c69d95dc3/aiohttp_cors/urldispatcher_router_adapter.py#L187
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
resource._routes[hdrs.METH_OPTIONS] = resource._routes[hdrs.METH_GET]
resource._allowed_methods.add(hdrs.METH_OPTIONS)
mapping, allowed_methods = await resource.resolve(
make_mocked_request("OPTIONS", "/st/path")
)
assert mapping is not None
assert allowed_methods == {hdrs.METH_GET, hdrs.METH_OPTIONS, hdrs.METH_HEAD}
async def test_add_static_set_options_route(router: web.UrlDispatcher) -> None:
"""Ensure set_options_route works as expected."""
resource = router.add_static(
"/st", pathlib.Path(aiohttp.__file__).parent, name="static"
)
async def handler(request: web.Request) -> NoReturn:
assert False
resource.set_options_route(handler)
mapping, allowed_methods = await resource.resolve(
make_mocked_request("OPTIONS", "/st/path")
)
assert mapping is not None
assert allowed_methods == {hdrs.METH_GET, hdrs.METH_OPTIONS, hdrs.METH_HEAD}
def test_dynamic_with_trailing_slash(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}/", handler, name="name")
route = router["name"]
assert isinstance(route, web.Resource)
assert {"name": "John"} == route._match("/get/John/")
def test_len(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert 2 == len(router)
def test_iter(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert {"name1", "name2"} == set(iter(router))
def test_contains(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get1", handler, name="name1")
router.add_route("GET", "/get2", handler, name="name2")
assert "name1" in router
assert "name3" not in router
def test_static_repr(router: web.UrlDispatcher) -> None:
router.add_static("/get", pathlib.Path(aiohttp.__file__).parent, name="name")
assert repr(router["name"]).startswith("<StaticResource 'name' /get")
def test_static_adds_slash(router: web.UrlDispatcher) -> None:
route = router.add_static("/prefix", pathlib.Path(aiohttp.__file__).parent)
assert "/prefix" == route._prefix
def test_static_remove_trailing_slash(router: web.UrlDispatcher) -> None:
route = router.add_static("/prefix/", pathlib.Path(aiohttp.__file__).parent)
assert "/prefix" == route._prefix
@pytest.mark.parametrize(
"pattern,url,expected",
(
(r"{to:\d+}", r"1234", {"to": "1234"}),
("{name}.html", "test.html", {"name": "test"}),
(r"{fn:\w+ \d+}", "abc 123", {"fn": "abc 123"}),
(r"{fn:\w+\s\d+}", "abc 123", {"fn": "abc 123"}),
),
)
async def test_add_route_with_re(
router: web.UrlDispatcher, pattern: str, url: str, expected: Dict[str, str]
) -> None:
handler = make_handler()
router.add_route("GET", f"/handler/{pattern}", handler)
req = make_mocked_request("GET", f"/handler/{url}")
info = await router.resolve(req)
assert info is not None
assert info == expected
async def test_add_route_with_re_and_slashes(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:[^/]+/?}", handler)
req = make_mocked_request("GET", "/handler/1234/")
info = await router.resolve(req)
assert info is not None
assert {"to": "1234/"} == info
router.add_route("GET", r"/handler/{to:.+}", handler)
req = make_mocked_request("GET", "/handler/1234/5/6/7")
info = await router.resolve(req)
assert info is not None
assert {"to": "1234/5/6/7"} == info
async def test_add_route_with_re_not_match(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:\d+}", handler)
req = make_mocked_request("GET", "/handler/tail")
match_info = await router.resolve(req)
assert isinstance(match_info.route, SystemRoute)
assert {} == match_info
with pytest.raises(web.HTTPNotFound):
await match_info.handler(req)
async def test_add_route_with_re_including_slashes(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", r"/handler/{to:.+}/tail", handler)
req = make_mocked_request("GET", "/handler/re/with/slashes/tail")
info = await router.resolve(req)
assert info is not None
assert {"to": "re/with/slashes"} == info
def test_add_route_with_invalid_re(router: web.UrlDispatcher) -> None:
handler = make_handler()
with pytest.raises(ValueError) as ctx:
router.add_route("GET", r"/handler/{to:+++}", handler)
s = str(ctx.value)
assert s.startswith(
"Bad pattern '"
+ PATH_SEP
+ "handler"
+ PATH_SEP
+ "(?P<to>+++)': nothing to repeat"
)
assert ctx.value.__cause__ is None
def test_route_dynamic_with_regex_spec(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/get/{num:^\d+}", handler, name="name")
url = route.url_for(num="123")
assert "/get/123" == str(url)
def test_route_dynamic_with_regex_spec_and_trailing_slash(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
route = router.add_route("GET", r"/get/{num:^\d+}/", handler, name="name")
url = route.url_for(num="123")
assert "/get/123/" == str(url)
def test_route_dynamic_with_regex(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/{one}/{two:.+}", handler)
url = route.url_for(one="1", two="2")
assert "/1/2" == str(url)
def test_route_dynamic_quoting(router: web.UrlDispatcher) -> None:
handler = make_handler()
route = router.add_route("GET", r"/пре %2Fфикс/{arg}", handler)
url = route.url_for(arg="1 2/текст%2F")
assert url.path == "/пре /фикс/1 2/текст%2F"
assert str(url) == (
"/%D0%BF%D1%80%D0%B5%20%2F%D1%84%D0%B8%D0%BA%D1%81"
"/1%202/%D1%82%D0%B5%D0%BA%D1%81%D1%82%252F"
)
async def test_regular_match_info(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{name}", handler)
req = make_mocked_request("GET", "/get/john")
match_info = await router.resolve(req)
assert {"name": "john"} == match_info
assert repr(match_info).startswith("<MatchInfo {'name': 'john'}:")
assert "<Dynamic" in repr(match_info)
async def test_match_info_with_plus(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/get/{version}", handler)
req = make_mocked_request("GET", "/get/1.0+test")
match_info = await router.resolve(req)
assert {"version": "1.0+test"} == match_info
async def test_not_found_repr(router: web.UrlDispatcher) -> None:
req = make_mocked_request("POST", "/path/to")
match_info = await router.resolve(req)
assert "<MatchInfoError 404: Not Found>" == repr(match_info)
async def test_not_allowed_repr(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/path/to", handler)
handler2 = make_handler()
router.add_route("POST", "/path/to", handler2)
req = make_mocked_request("PUT", "/path/to")
match_info = await router.resolve(req)
assert "<MatchInfoError 405: Method Not Allowed>" == repr(match_info)
def test_default_expect_handler(router: web.UrlDispatcher) -> None:
route = router.add_route("GET", "/", make_handler())
assert route._expect_handler is _default_expect_handler
def test_custom_expect_handler_plain(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
route = router.add_route("GET", "/", make_handler(), expect_handler=handler)
assert route._expect_handler is handler
assert isinstance(route, web.ResourceRoute)
def test_custom_expect_handler_dynamic(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
route = router.add_route(
"GET", "/get/{name}", make_handler(), expect_handler=handler
)
assert route._expect_handler is handler
assert isinstance(route, web.ResourceRoute)
def test_expect_handler_non_coroutine(router: web.UrlDispatcher) -> None:
def handler(request: web.Request) -> NoReturn:
assert False
with pytest.raises(AssertionError):
router.add_route("GET", "/", make_handler(), expect_handler=handler)
async def test_dynamic_match_non_ascii(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{var}", handler)
req = make_mocked_request(
"GET", "/%D1%80%D1%83%D1%81%20%D1%82%D0%B5%D0%BA%D1%81%D1%82"
)
match_info = await router.resolve(req)
assert {"var": "рус текст"} == match_info
async def test_dynamic_match_with_static_part(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{name}.html", handler)
req = make_mocked_request("GET", "/file.html")
match_info = await router.resolve(req)
assert {"name": "file"} == match_info
async def test_dynamic_match_two_part2(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{name}.{ext}", handler)
req = make_mocked_request("GET", "/file.html")
match_info = await router.resolve(req)
assert {"name": "file", "ext": "html"} == match_info
async def test_dynamic_match_unquoted_path(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{path}/{subpath}", handler)
resource_id = "my%2Fpath%7Cwith%21some%25strange%24characters"
req = make_mocked_request("GET", f"/path/{resource_id}")
match_info = await router.resolve(req)
assert match_info == {"path": "path", "subpath": unquote(resource_id)}
async def test_dynamic_match_double_quoted_path(router: web.UrlDispatcher) -> None:
"""Verify that double-quoted path is unquoted only once."""
handler = make_handler()
router.add_route("GET", "/{path}/{subpath}", handler)
resource_id = quote("my/path|with!some%strange$characters", safe="")
double_quoted_resource_id = quote(resource_id, safe="")
req = make_mocked_request("GET", f"/path/{double_quoted_resource_id}")
match_info = await router.resolve(req)
assert match_info == {"path": "path", "subpath": resource_id}
def test_add_route_not_started_with_slash(router: web.UrlDispatcher) -> None:
with pytest.raises(ValueError):
handler = make_handler()
router.add_route("GET", "invalid_path", handler)
def test_add_route_invalid_method(router: web.UrlDispatcher) -> None:
sample_bad_methods = {
"BAD METHOD",
"B@D_METHOD",
"[BAD_METHOD]",
"{BAD_METHOD}",
"(BAD_METHOD)",
"B?D_METHOD",
}
for bad_method in sample_bad_methods:
with pytest.raises(ValueError):
handler = make_handler()
router.add_route(bad_method, "/path", handler)
def test_routes_view_len(
router: web.UrlDispatcher, fill_routes: Callable[[], List[web.AbstractRoute]]
) -> None:
fill_routes()
assert 4 == len(router.routes())
def test_routes_view_iter(
router: web.UrlDispatcher, fill_routes: Callable[[], List[web.AbstractRoute]]
) -> None:
routes = fill_routes()
assert list(routes) == list(router.routes())
def test_routes_view_contains(
router: web.UrlDispatcher, fill_routes: Callable[[], List[web.AbstractRoute]]
) -> None:
routes = fill_routes()
for route in routes:
assert route in router.routes()
def test_routes_abc(router: web.UrlDispatcher) -> None:
assert isinstance(router.routes(), Sized)
assert isinstance(router.routes(), Iterable)
assert isinstance(router.routes(), Container)
def test_named_resources_abc(router: web.UrlDispatcher) -> None:
assert isinstance(router.named_resources(), Mapping)
assert not isinstance(router.named_resources(), MutableMapping)
def test_named_resources(router: web.UrlDispatcher) -> None:
route1 = router.add_route("GET", "/plain", make_handler(), name="route1")
route2 = router.add_route("GET", "/variable/{name}", make_handler(), name="route2")
route3 = router.add_static(
"/static", pathlib.Path(aiohttp.__file__).parent, name="route3"
)
names = {route1.name, route2.name, route3.name}
assert 3 == len(router.named_resources())
for name in names:
assert name is not None
assert name in router.named_resources()
assert isinstance(router.named_resources()[name], web.AbstractResource)
def test_resource_iter(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
r1 = resource.add_route("GET", handler)
r2 = resource.add_route("POST", handler)
assert 2 == len(resource)
assert [r1, r2] == list(resource)
def test_view_route(router: web.UrlDispatcher) -> None:
resource = router.add_resource("/path")
route = resource.add_route("*", web.View)
assert web.View is route.handler
def test_resource_route_match(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
route = resource.add_route("GET", handler)
assert isinstance(route.resource, web.Resource)
assert {} == route.resource._match("/path")
def test_error_on_double_route_adding(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
resource.add_route("GET", handler)
with pytest.raises(RuntimeError):
resource.add_route("GET", handler)
def test_error_on_adding_route_after_wildcard(router: web.UrlDispatcher) -> None:
async def handler(request: web.Request) -> NoReturn:
assert False
resource = router.add_resource("/path")
resource.add_route("*", handler)
with pytest.raises(RuntimeError):
resource.add_route("GET", handler)
async def test_http_exception_is_none_when_resolved(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info.http_exception is None
async def test_http_exception_is_not_none_when_not_resolved(
router: web.UrlDispatcher,
) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/abc")
info = await router.resolve(req)
assert info.http_exception is not None
assert info.http_exception.status == 404
async def test_match_info_get_info_plain(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/", handler)
req = make_mocked_request("GET", "/")
info = await router.resolve(req)
assert info.get_info() == {"path": "/"}
async def test_match_info_get_info_dynamic(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{a}", handler)
req = make_mocked_request("GET", "/value")
info = await router.resolve(req)
assert info.get_info() == {
"pattern": re.compile(PATH_SEP + "(?P<a>[^{}/]+)"),
"formatter": "/{a}",
}
async def test_match_info_get_info_dynamic2(router: web.UrlDispatcher) -> None:
handler = make_handler()
router.add_route("GET", "/{a}/{b}", handler)
req = make_mocked_request("GET", "/path/to")
info = await router.resolve(req)
assert info.get_info() == {
"pattern": re.compile(
PATH_SEP + "(?P<a>[^{}/]+)" + PATH_SEP + "(?P<b>[^{}/]+)"
),