/
test_wrappers.py
1389 lines (1130 loc) · 45 KB
/
test_wrappers.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 contextlib
import json
import os
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from io import BytesIO
import pytest
from werkzeug import Response
from werkzeug import wrappers
from werkzeug.datastructures import Accept
from werkzeug.datastructures import CharsetAccept
from werkzeug.datastructures import CombinedMultiDict
from werkzeug.datastructures import Headers
from werkzeug.datastructures import ImmutableList
from werkzeug.datastructures import ImmutableMultiDict
from werkzeug.datastructures import ImmutableOrderedMultiDict
from werkzeug.datastructures import LanguageAccept
from werkzeug.datastructures import MIMEAccept
from werkzeug.datastructures import MultiDict
from werkzeug.exceptions import BadRequest
from werkzeug.exceptions import RequestedRangeNotSatisfiable
from werkzeug.exceptions import SecurityError
from werkzeug.http import COEP
from werkzeug.http import COOP
from werkzeug.http import generate_etag
from werkzeug.test import Client
from werkzeug.test import create_environ
from werkzeug.test import run_wsgi_app
from werkzeug.wsgi import LimitedStream
from werkzeug.wsgi import wrap_file
@wrappers.Request.application
def request_demo_app(request):
assert "werkzeug.request" in request.environ
return Response()
def assert_environ(environ, method):
assert environ["REQUEST_METHOD"] == method
assert environ["PATH_INFO"] == "/"
assert environ["SCRIPT_NAME"] == ""
assert environ["SERVER_NAME"] == "localhost"
assert environ["wsgi.version"] == (1, 0)
assert environ["wsgi.url_scheme"] == "http"
def test_base_request():
client = Client(request_demo_app)
# get requests
response = client.get("/?foo=bar&foo=hehe")
request = response.request
assert request.args == MultiDict([("foo", "bar"), ("foo", "hehe")])
assert request.form == MultiDict()
assert request.data == b""
assert_environ(request.environ, "GET")
# post requests with form data
response = client.post(
"/?blub=blah",
data="foo=blub+hehe&blah=42",
content_type="application/x-www-form-urlencoded",
)
request = response.request
assert request.args == MultiDict([("blub", "blah")])
assert request.form == MultiDict([("foo", "blub hehe"), ("blah", "42")])
assert request.data == b""
# currently we do not guarantee that the values are ordered correctly
# for post data.
# assert response['form_as_list'] == [('foo', ['blub hehe']), ('blah', ['42'])]
assert_environ(request.environ, "POST")
# patch requests with form data
response = client.patch(
"/?blub=blah",
data="foo=blub+hehe&blah=42",
content_type="application/x-www-form-urlencoded",
)
request = response.request
assert request.args == MultiDict([("blub", "blah")])
assert request.form == MultiDict([("foo", "blub hehe"), ("blah", "42")])
assert request.data == b""
assert_environ(request.environ, "PATCH")
# post requests with json data
json = b'{"foo": "bar", "blub": "blah"}'
response = client.post("/?a=b", data=json, content_type="application/json")
request = response.request
assert request.data == json
assert request.args == MultiDict([("a", "b")])
assert request.form == MultiDict()
def test_query_string_is_bytes():
req = wrappers.Request.from_values("/?foo=%2f")
assert req.query_string == b"foo=%2f"
def test_request_repr():
req = wrappers.Request.from_values("/foobar")
assert "<Request 'http://localhost/foobar' [GET]>" == repr(req)
req = wrappers.Request.from_values("/привет")
assert "<Request 'http://localhost/привет' [GET]>" == repr(req)
def test_access_route():
req = wrappers.Request.from_values(
headers={"X-Forwarded-For": "192.168.1.2, 192.168.1.1"},
environ_base={"REMOTE_ADDR": "192.168.1.3"},
)
assert req.access_route == ["192.168.1.2", "192.168.1.1"]
assert req.remote_addr == "192.168.1.3"
req = wrappers.Request.from_values(environ_base={"REMOTE_ADDR": "192.168.1.3"})
assert list(req.access_route) == ["192.168.1.3"]
def test_url_request_descriptors():
req = wrappers.Request.from_values("/bar?foo=baz", "http://example.com/test")
assert req.path == "/bar"
assert req.full_path == "/bar?foo=baz"
assert req.script_root == "/test"
assert req.url == "http://example.com/test/bar?foo=baz"
assert req.base_url == "http://example.com/test/bar"
assert req.url_root == "http://example.com/test/"
assert req.host_url == "http://example.com/"
assert req.host == "example.com"
assert req.scheme == "http"
req = wrappers.Request.from_values("/bar?foo=baz", "https://example.com/test")
assert req.scheme == "https"
def test_url_request_descriptors_query_quoting():
next = "http%3A%2F%2Fwww.example.com%2F%3Fnext%3D%2Fbaz%23my%3Dhash"
req = wrappers.Request.from_values(f"/bar?next={next}", "http://example.com/")
assert req.path == "/bar"
assert req.full_path == f"/bar?next={next}"
assert req.url == f"http://example.com/bar?next={next}"
def test_url_request_descriptors_hosts():
req = wrappers.Request.from_values("/bar?foo=baz", "http://example.com/test")
req.trusted_hosts = ["example.com"]
assert req.path == "/bar"
assert req.full_path == "/bar?foo=baz"
assert req.script_root == "/test"
assert req.url == "http://example.com/test/bar?foo=baz"
assert req.base_url == "http://example.com/test/bar"
assert req.url_root == "http://example.com/test/"
assert req.host_url == "http://example.com/"
assert req.host == "example.com"
assert req.scheme == "http"
req = wrappers.Request.from_values("/bar?foo=baz", "https://example.com/test")
assert req.scheme == "https"
req = wrappers.Request.from_values("/bar?foo=baz", "http://example.com/test")
req.trusted_hosts = ["example.org"]
pytest.raises(SecurityError, lambda: req.url)
pytest.raises(SecurityError, lambda: req.base_url)
pytest.raises(SecurityError, lambda: req.url_root)
pytest.raises(SecurityError, lambda: req.host_url)
pytest.raises(SecurityError, lambda: req.host)
def test_authorization():
request = wrappers.Request.from_values(
headers={"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="}
)
a = request.authorization
assert a.type == "basic"
assert a.username == "Aladdin"
assert a.password == "open sesame"
def test_authorization_with_unicode():
request = wrappers.Request.from_values(
headers={"Authorization": "Basic 0YDRg9GB0YHQutC40IE60JHRg9C60LLRiw=="}
)
a = request.authorization
assert a.type == "basic"
assert a.username == "русскиЁ"
assert a.password == "Буквы"
def test_request_application():
@wrappers.Request.application
def application(request):
return wrappers.Response("Hello World!")
@wrappers.Request.application
def failing_application(request):
raise BadRequest()
resp = wrappers.Response.from_app(application, create_environ())
assert resp.data == b"Hello World!"
assert resp.status_code == 200
resp = wrappers.Response.from_app(failing_application, create_environ())
assert b"Bad Request" in resp.data
assert resp.status_code == 400
def test_request_access_control():
request = wrappers.Request.from_values(
headers={
"Origin": "https://palletsprojects.com",
"Access-Control-Request-Headers": "X-A, X-B",
"Access-Control-Request-Method": "PUT",
}
)
assert request.origin == "https://palletsprojects.com"
assert request.access_control_request_headers == {"X-A", "X-B"}
assert request.access_control_request_method == "PUT"
def test_response_access_control():
response = wrappers.Response("Hello World")
assert response.access_control_allow_credentials is False
response.access_control_allow_credentials = True
response.access_control_allow_headers = ["X-A", "X-B"]
assert response.headers["Access-Control-Allow-Credentials"] == "true"
assert set(response.headers["Access-Control-Allow-Headers"].split(", ")) == {
"X-A",
"X-B",
}
def test_base_response():
response = wrappers.Response("öäü")
assert response.get_data() == "öäü".encode()
# writing
response = wrappers.Response("foo")
response.stream.write("bar")
assert response.get_data() == b"foobar"
# set cookie
response = wrappers.Response()
response.set_cookie(
"foo",
value="bar",
max_age=60,
expires=0,
path="/blub",
domain="example.org",
samesite="Strict",
)
assert response.headers.to_wsgi_list() == [
("Content-Type", "text/plain; charset=utf-8"),
(
"Set-Cookie",
"foo=bar; Domain=example.org;"
" Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=60;"
" Path=/blub; SameSite=Strict",
),
]
# delete cookie
response = wrappers.Response()
response.delete_cookie("foo")
assert response.headers.to_wsgi_list() == [
("Content-Type", "text/plain; charset=utf-8"),
(
"Set-Cookie",
"foo=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/",
),
]
# close call forwarding
closed = []
class Iterable:
def __next__(self):
raise StopIteration()
def __iter__(self):
return self
def close(self):
closed.append(True)
response = wrappers.Response(Iterable())
response.call_on_close(lambda: closed.append(True))
app_iter, status, headers = run_wsgi_app(response, create_environ(), buffered=True)
assert status == "200 OK"
assert "".join(app_iter) == ""
assert len(closed) == 2
# with statement
del closed[:]
response = wrappers.Response(Iterable())
with response:
pass
assert len(closed) == 1
@pytest.mark.parametrize(
("status_code", "expected_status"),
[
(200, "200 OK"),
(404, "404 NOT FOUND"),
(588, "588 UNKNOWN"),
(999, "999 UNKNOWN"),
],
)
def test_response_set_status_code(status_code, expected_status):
response = wrappers.Response()
response.status_code = status_code
assert response.status_code == status_code
assert response.status == expected_status
@pytest.mark.parametrize(
("status", "expected_status_code", "expected_status"),
[
("404", 404, "404 NOT FOUND"),
("588", 588, "588 UNKNOWN"),
("999", 999, "999 UNKNOWN"),
("200 OK", 200, "200 OK"),
("999 WTF", 999, "999 WTF"),
("wtf", 0, "0 wtf"),
("200 TEA POT", 200, "200 TEA POT"),
(200, 200, "200 OK"),
(400, 400, "400 BAD REQUEST"),
],
)
def test_response_set_status(status, expected_status_code, expected_status):
response = wrappers.Response()
response.status = status
assert response.status_code == expected_status_code
assert response.status == expected_status
response = wrappers.Response(status=status)
assert response.status_code == expected_status_code
assert response.status == expected_status
def test_response_init_status_empty_string():
# invalid status codes
with pytest.raises(ValueError) as info:
wrappers.Response(None, "")
assert "Empty status argument" in str(info.value)
def test_response_init_status_tuple():
with pytest.raises(TypeError) as info:
wrappers.Response(None, tuple())
assert "Invalid status argument" in str(info.value)
def test_type_forcing():
def wsgi_application(environ, start_response):
start_response("200 OK", [("Content-Type", "text/html")])
return ["Hello World!"]
base_response = wrappers.Response("Hello World!", content_type="text/html")
class SpecialResponse(wrappers.Response):
def foo(self):
return 42
# good enough for this simple application, but don't ever use that in
# real world examples!
fake_env = {}
for orig_resp in wsgi_application, base_response:
response = SpecialResponse.force_type(orig_resp, fake_env)
assert response.__class__ is SpecialResponse
assert response.foo() == 42
assert response.get_data() == b"Hello World!"
assert response.content_type == "text/html"
# without env, no arbitrary conversion
pytest.raises(TypeError, SpecialResponse.force_type, wsgi_application)
def test_accept():
request = wrappers.Request(
{
"HTTP_ACCEPT": "text/xml,application/xml,application/xhtml+xml,"
"text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
"HTTP_ACCEPT_CHARSET": "ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"HTTP_ACCEPT_ENCODING": "gzip,deflate",
"HTTP_ACCEPT_LANGUAGE": "en-us,en;q=0.5",
"SERVER_NAME": "eggs",
"SERVER_PORT": "80",
}
)
assert request.accept_mimetypes == MIMEAccept(
[
("text/xml", 1),
("application/xml", 1),
("application/xhtml+xml", 1),
("image/png", 1),
("text/html", 0.9),
("text/plain", 0.8),
("*/*", 0.5),
]
)
assert request.accept_charsets == CharsetAccept(
[("ISO-8859-1", 1), ("utf-8", 0.7), ("*", 0.7)]
)
assert request.accept_encodings == Accept([("gzip", 1), ("deflate", 1)])
assert request.accept_languages == LanguageAccept([("en-us", 1), ("en", 0.5)])
request = wrappers.Request(
{"HTTP_ACCEPT": "", "SERVER_NAME": "example.org", "SERVER_PORT": "80"}
)
assert request.accept_mimetypes == MIMEAccept()
def test_etag_request():
request = wrappers.Request(
{
"HTTP_CACHE_CONTROL": "no-store, no-cache",
"HTTP_IF_MATCH": 'W/"foo", bar, "baz"',
"HTTP_IF_NONE_MATCH": 'W/"foo", bar, "baz"',
"HTTP_IF_MODIFIED_SINCE": "Tue, 22 Jan 2008 11:18:44 GMT",
"HTTP_IF_UNMODIFIED_SINCE": "Tue, 22 Jan 2008 11:18:44 GMT",
"SERVER_NAME": "eggs",
"SERVER_PORT": "80",
}
)
assert request.cache_control.no_store
assert request.cache_control.no_cache
for etags in request.if_match, request.if_none_match:
assert etags("bar")
assert etags.contains_raw('W/"foo"')
assert etags.contains_weak("foo")
assert not etags.contains("foo")
dt = datetime(2008, 1, 22, 11, 18, 44, tzinfo=timezone.utc)
assert request.if_modified_since == dt
assert request.if_unmodified_since == dt
def test_user_agent():
user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0"
request = wrappers.Request({"HTTP_USER_AGENT": user_agent})
assert request.user_agent.to_header() == user_agent
assert str(request.user_agent) == user_agent
assert request.user_agent.string == user_agent
def test_stream_wrapping():
class LowercasingStream:
def __init__(self, stream):
self._stream = stream
def read(self, size=-1):
return self._stream.read(size).lower()
def readline(self, size=-1):
return self._stream.readline(size).lower()
data = b"foo=Hello+World"
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
req.stream = LowercasingStream(req.stream)
assert req.form["foo"] == "hello world"
def test_data_descriptor_triggers_parsing():
data = b"foo=Hello+World"
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
assert req.data == b""
assert req.form["foo"] == "Hello World"
def test_get_data_method_parsing_caching_behavior():
data = b"foo=Hello+World"
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
# get_data() caches, so form stays available
assert req.get_data() == data
assert req.form["foo"] == "Hello World"
assert req.get_data() == data
# here we access the form data first, caching is bypassed
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
assert req.form["foo"] == "Hello World"
assert req.get_data() == b""
# Another case is uncached get data which trashes everything
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
assert req.get_data(cache=False) == data
assert req.get_data(cache=False) == b""
assert req.form == {}
# Or we can implicitly start the form parser which is similar to
# the old .data behavior
req = wrappers.Request.from_values(
"/", method="POST", data=data, content_type="application/x-www-form-urlencoded"
)
assert req.get_data(parse_form_data=True) == b""
assert req.form["foo"] == "Hello World"
def test_etag_response():
response = wrappers.Response("Hello World")
assert response.get_etag() == (None, None)
response.add_etag()
assert response.get_etag() == ("0a4d55a8d778e5022fab701977c5d840bbc486d0", False)
assert not response.cache_control
response.cache_control.must_revalidate = True
response.cache_control.max_age = 60
response.headers["Content-Length"] = len(response.get_data())
assert response.headers["Cache-Control"] in (
"must-revalidate, max-age=60",
"max-age=60, must-revalidate",
)
assert "date" not in response.headers
env = create_environ()
env.update({"REQUEST_METHOD": "GET", "HTTP_IF_NONE_MATCH": response.get_etag()[0]})
response.make_conditional(env)
assert "date" in response.headers
# after the thing is invoked by the server as wsgi application
# (we're emulating this here), there must not be any entity
# headers left and the status code would have to be 304
resp = wrappers.Response.from_app(response, env)
assert resp.status_code == 304
assert "content-length" not in resp.headers
# make sure date is not overriden
response = wrappers.Response("Hello World")
response.date = 1337
d = response.date
response.make_conditional(env)
assert response.date == d
# make sure content length is only set if missing
response = wrappers.Response("Hello World")
response.content_length = 999
response.make_conditional(env)
assert response.content_length == 999
def test_etag_response_412():
response = wrappers.Response("Hello World")
assert response.get_etag() == (None, None)
response.add_etag()
assert response.get_etag() == ("0a4d55a8d778e5022fab701977c5d840bbc486d0", False)
assert not response.cache_control
response.cache_control.must_revalidate = True
response.cache_control.max_age = 60
response.headers["Content-Length"] = len(response.get_data())
assert response.headers["Cache-Control"] in (
"must-revalidate, max-age=60",
"max-age=60, must-revalidate",
)
assert "date" not in response.headers
env = create_environ()
env.update(
{"REQUEST_METHOD": "GET", "HTTP_IF_MATCH": f"{response.get_etag()[0]}xyz"}
)
response.make_conditional(env)
assert "date" in response.headers
# after the thing is invoked by the server as wsgi application
# (we're emulating this here), there must not be any entity
# headers left and the status code would have to be 412
resp = wrappers.Response.from_app(response, env)
assert resp.status_code == 412
# Make sure there is a body still
assert resp.data != b""
# make sure date is not overriden
response = wrappers.Response("Hello World")
response.date = 1337
d = response.date
response.make_conditional(env)
assert response.date == d
# make sure content length is only set if missing
response = wrappers.Response("Hello World")
response.content_length = 999
response.make_conditional(env)
assert response.content_length == 999
def test_range_request_basic():
env = create_environ()
response = wrappers.Response("Hello World")
env["HTTP_RANGE"] = "bytes=0-4"
response.make_conditional(env, accept_ranges=True, complete_length=11)
assert response.status_code == 206
assert response.headers["Accept-Ranges"] == "bytes"
assert response.headers["Content-Range"] == "bytes 0-4/11"
assert response.headers["Content-Length"] == "5"
assert response.data == b"Hello"
def test_range_request_out_of_bound():
env = create_environ()
response = wrappers.Response("Hello World")
env["HTTP_RANGE"] = "bytes=6-666"
response.make_conditional(env, accept_ranges=True, complete_length=11)
assert response.status_code == 206
assert response.headers["Accept-Ranges"] == "bytes"
assert response.headers["Content-Range"] == "bytes 6-10/11"
assert response.headers["Content-Length"] == "5"
assert response.data == b"World"
def test_range_request_with_file():
env = create_environ()
resources = os.path.join(os.path.dirname(__file__), "res")
fname = os.path.join(resources, "test.txt")
with open(fname, "rb") as f:
fcontent = f.read()
with open(fname, "rb") as f:
response = wrappers.Response(wrap_file(env, f))
env["HTTP_RANGE"] = "bytes=0-0"
response.make_conditional(
env, accept_ranges=True, complete_length=len(fcontent)
)
assert response.status_code == 206
assert response.headers["Accept-Ranges"] == "bytes"
assert response.headers["Content-Range"] == f"bytes 0-0/{len(fcontent)}"
assert response.headers["Content-Length"] == "1"
assert response.data == fcontent[:1]
def test_range_request_with_complete_file():
env = create_environ()
resources = os.path.join(os.path.dirname(__file__), "res")
fname = os.path.join(resources, "test.txt")
with open(fname, "rb") as f:
fcontent = f.read()
with open(fname, "rb") as f:
fsize = os.path.getsize(fname)
response = wrappers.Response(wrap_file(env, f))
env["HTTP_RANGE"] = f"bytes=0-{fsize - 1}"
response.make_conditional(env, accept_ranges=True, complete_length=fsize)
assert response.status_code == 206
assert response.headers["Accept-Ranges"] == "bytes"
assert response.headers["Content-Range"] == f"bytes 0-{fsize - 1}/{fsize}"
assert response.headers["Content-Length"] == str(fsize)
assert response.data == fcontent
@pytest.mark.parametrize("value", [None, 0])
def test_range_request_without_complete_length(value):
env = create_environ(headers={"Range": "bytes=0-10"})
response = wrappers.Response("Hello World")
response.make_conditional(env, accept_ranges=True, complete_length=value)
assert response.status_code == 200
assert response.data == b"Hello World"
def test_invalid_range_request():
env = create_environ()
response = wrappers.Response("Hello World")
env["HTTP_RANGE"] = "bytes=-"
with pytest.raises(RequestedRangeNotSatisfiable):
response.make_conditional(env, accept_ranges=True, complete_length=11)
def test_etag_response_freezing():
response = Response("Hello World")
response.freeze()
assert response.get_etag() == (str(generate_etag(b"Hello World")), False)
def test_authenticate():
resp = wrappers.Response()
resp.www_authenticate.type = "basic"
resp.www_authenticate.realm = "Testing"
assert resp.headers["WWW-Authenticate"] == 'Basic realm="Testing"'
resp.www_authenticate.realm = None
resp.www_authenticate.type = None
assert "WWW-Authenticate" not in resp.headers
def test_authenticate_quoted_qop():
# Example taken from https://github.com/pallets/werkzeug/issues/633
resp = wrappers.Response()
resp.www_authenticate.set_digest("REALM", "NONCE", qop=("auth", "auth-int"))
actual = set(f"{resp.headers['WWW-Authenticate']},".split())
expected = set('Digest nonce="NONCE", realm="REALM", qop="auth, auth-int",'.split())
assert actual == expected
resp.www_authenticate.set_digest("REALM", "NONCE", qop=("auth",))
actual = set(f"{resp.headers['WWW-Authenticate']},".split())
expected = set('Digest nonce="NONCE", realm="REALM", qop="auth",'.split())
assert actual == expected
def test_response_stream():
response = wrappers.Response()
response.stream.write("Hello ")
response.stream.write("World!")
assert response.response == ["Hello ", "World!"]
assert response.get_data() == b"Hello World!"
def test_common_response_descriptors():
response = wrappers.Response()
response.mimetype = "text/html"
assert response.mimetype == "text/html"
assert response.content_type == "text/html; charset=utf-8"
assert response.mimetype_params == {"charset": "utf-8"}
response.mimetype_params["x-foo"] = "yep"
del response.mimetype_params["charset"]
assert response.content_type == "text/html; x-foo=yep"
now = datetime.now(timezone.utc).replace(microsecond=0)
assert response.content_length is None
response.content_length = "42"
assert response.content_length == 42
for attr in "date", "expires":
assert getattr(response, attr) is None
setattr(response, attr, now)
assert getattr(response, attr) == now
assert response.age is None
age_td = timedelta(days=1, minutes=3, seconds=5)
response.age = age_td
assert response.age == age_td
response.age = 42
assert response.age == timedelta(seconds=42)
assert response.retry_after is None
response.retry_after = now
assert response.retry_after == now
assert not response.vary
response.vary.add("Cookie")
response.vary.add("Content-Language")
assert "cookie" in response.vary
assert response.vary.to_header() == "Cookie, Content-Language"
response.headers["Vary"] = "Content-Encoding"
assert response.vary.as_set() == {"content-encoding"}
response.allow.update(["GET", "POST"])
assert response.headers["Allow"] == "GET, POST"
response.content_language.add("en-US")
response.content_language.add("fr")
assert response.headers["Content-Language"] == "en-US, fr"
def test_common_request_descriptors():
request = wrappers.Request.from_values(
content_type="text/html; charset=utf-8",
content_length="23",
headers={
"Referer": "http://www.example.com/",
"Date": "Sat, 28 Feb 2009 19:04:35 GMT",
"Max-Forwards": "10",
"Pragma": "no-cache",
"Content-Encoding": "gzip",
"Content-MD5": "9a3bc6dbc47a70db25b84c6e5867a072",
},
)
assert request.content_type == "text/html; charset=utf-8"
assert request.mimetype == "text/html"
assert request.mimetype_params == {"charset": "utf-8"}
assert request.content_length == 23
assert request.referrer == "http://www.example.com/"
assert request.date == datetime(2009, 2, 28, 19, 4, 35, tzinfo=timezone.utc)
assert request.max_forwards == 10
assert "no-cache" in request.pragma
assert request.content_encoding == "gzip"
assert request.content_md5 == "9a3bc6dbc47a70db25b84c6e5867a072"
def test_request_mimetype_always_lowercase():
request = wrappers.Request.from_values(content_type="APPLICATION/JSON")
assert request.mimetype == "application/json"
def test_shallow_mode():
request = wrappers.Request(
{"QUERY_STRING": "foo=bar", "SERVER_NAME": "eggs", "SERVER_PORT": "80"},
shallow=True,
)
assert request.args["foo"] == "bar"
pytest.raises(RuntimeError, lambda: request.stream)
pytest.raises(RuntimeError, lambda: request.data)
pytest.raises(RuntimeError, lambda: request.form)
def test_form_parsing_failed():
data = b"--blah\r\n"
request = wrappers.Request.from_values(
input_stream=BytesIO(data),
content_length=len(data),
content_type="multipart/form-data; boundary=foo",
method="POST",
)
assert not request.files
assert not request.form
# Bad Content-Type
data = b"test"
request = wrappers.Request.from_values(
input_stream=BytesIO(data),
content_length=len(data),
content_type=", ",
method="POST",
)
assert not request.form
def test_file_closing():
data = (
b"--foo\r\n"
b'Content-Disposition: form-data; name="foo"; filename="foo.txt"\r\n'
b"Content-Type: text/plain; charset=utf-8\r\n\r\n"
b"file contents, just the contents\r\n"
b"--foo--"
)
req = wrappers.Request.from_values(
input_stream=BytesIO(data),
content_length=len(data),
content_type="multipart/form-data; boundary=foo",
method="POST",
)
foo = req.files["foo"]
assert foo.mimetype == "text/plain"
assert foo.filename == "foo.txt"
assert foo.closed is False
req.close()
assert foo.closed is True
def test_file_closing_with():
data = (
b"--foo\r\n"
b'Content-Disposition: form-data; name="foo"; filename="foo.txt"\r\n'
b"Content-Type: text/plain; charset=utf-8\r\n\r\n"
b"file contents, just the contents\r\n"
b"--foo--"
)
req = wrappers.Request.from_values(
input_stream=BytesIO(data),
content_length=len(data),
content_type="multipart/form-data; boundary=foo",
method="POST",
)
with req:
foo = req.files["foo"]
assert foo.mimetype == "text/plain"
assert foo.filename == "foo.txt"
assert foo.closed is True
def test_url_charset_reflection():
req = wrappers.Request.from_values()
req.charset = "utf-7"
assert req.url_charset == "utf-7"
def test_response_streamed():
r = wrappers.Response()
assert not r.is_streamed
r = wrappers.Response("Hello World")
assert not r.is_streamed
r = wrappers.Response(["foo", "bar"])
assert not r.is_streamed
def gen():
if 0:
yield None
r = wrappers.Response(gen())
assert r.is_streamed
def test_response_iter_wrapping():
def uppercasing(iterator):
for item in iterator:
yield item.upper()
def generator():
yield "foo"
yield "bar"
req = wrappers.Request.from_values()
resp = wrappers.Response(generator())
del resp.headers["Content-Length"]
resp.response = uppercasing(resp.iter_encoded())
actual_resp = wrappers.Response.from_app(resp, req.environ, buffered=True)
assert actual_resp.get_data() == b"FOOBAR"
def test_response_freeze():
def generate():
yield "foo"
yield "bar"
resp = wrappers.Response(generate())
resp.freeze()
assert resp.response == [b"foo", b"bar"]
assert resp.headers["content-length"] == "6"
def test_response_content_length_uses_encode():
r = wrappers.Response("你好")
assert r.calculate_content_length() == 6
def test_other_method_payload():
data = b"Hello World"
req = wrappers.Request.from_values(
input_stream=BytesIO(data),
content_length=len(data),
content_type="text/plain",
method="WHAT_THE_FUCK",
)
assert req.get_data() == data
assert isinstance(req.stream, LimitedStream)
def test_urlfication():
resp = wrappers.Response()
resp.headers["Location"] = "http://üser:pässword@☃.net/påth"
resp.headers["Content-Location"] = "http://☃.net/"
headers = resp.get_wsgi_headers(create_environ())
assert headers["location"] == "http://%C3%BCser:p%C3%A4ssword@xn--n3h.net/p%C3%A5th"
assert headers["content-location"] == "http://xn--n3h.net/"
def test_new_response_iterator_behavior():
req = wrappers.Request.from_values()
resp = wrappers.Response("Hello Wörld!")
def get_content_length(resp):
headers = resp.get_wsgi_headers(req.environ)
return headers.get("content-length", type=int)
def generate_items():
yield "Hello "
yield "Wörld!"
# werkzeug encodes when set to `data` now, which happens
# if a string is passed to the response object.
assert resp.response == ["Hello Wörld!".encode()]
assert resp.get_data() == "Hello Wörld!".encode()
assert get_content_length(resp) == 13
assert not resp.is_streamed
assert resp.is_sequence
# try the same for manual assignment
resp.set_data("Wörd")
assert resp.response == ["Wörd".encode()]
assert resp.get_data() == "Wörd".encode()
assert get_content_length(resp) == 5
assert not resp.is_streamed
assert resp.is_sequence
# automatic generator sequence conversion
resp.response = generate_items()
assert resp.is_streamed
assert not resp.is_sequence
assert resp.get_data() == "Hello Wörld!".encode()
assert resp.response == [b"Hello ", "Wörld!".encode()]
assert not resp.is_streamed
assert resp.is_sequence
# automatic generator sequence conversion
resp.response = generate_items()
resp.implicit_sequence_conversion = False
assert resp.is_streamed
assert not resp.is_sequence
pytest.raises(RuntimeError, lambda: resp.get_data())
resp.make_sequence()
assert resp.get_data() == "Hello Wörld!".encode()
assert resp.response == [b"Hello ", "Wörld!".encode()]
assert not resp.is_streamed