-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtests.py
1367 lines (1146 loc) · 53.2 KB
/
tests.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
"""Unittests for the various HTTPServer modules.
Written by Cody A.W. Somerville <[email protected]>,
Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
Updated to test HTTP compression by Pierre Quentel.
"""
from http import HTTPStatus
from httpcompressionserver import BaseHTTPRequestHandler, HTTPServer, \
HTTPCompressionRequestHandler, CGIHTTPRequestHandler
import httpcompressionserver as server
import os
import sys
import re
import base64
import ntpath
import shutil
import email.message
import email.utils
import html
import http.client
import urllib.parse
import tempfile
import time
import datetime
import threading
from unittest import mock
from io import BytesIO
import unittest
from test import support
try:
import gzip
import zlib
except ImportError:
zlib = None
try:
import bz2
except ImportError:
bz2 = None
class NoLogRequestHandler:
def log_message(self, *args):
# don't write log messages to stderr
pass
def read(self, n=None):
return ''
class TestServerThread(threading.Thread):
def __init__(self, test_object, request_handler):
threading.Thread.__init__(self)
self.request_handler = request_handler
self.test_object = test_object
def run(self):
self.server = HTTPServer(('localhost', 0), self.request_handler)
self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
self.test_object.server_started.set()
self.test_object = None
try:
self.server.serve_forever(0.05)
finally:
self.server.server_close()
def stop(self):
self.server.shutdown()
self.join()
class BaseTestCase(unittest.TestCase):
def setUp(self):
self._threads = support.threading_setup()
os.environ = support.EnvironmentVarGuard()
self.server_started = threading.Event()
self.thread = TestServerThread(self, self.request_handler)
self.thread.start()
self.server_started.wait()
def tearDown(self):
self.thread.stop()
self.thread = None
os.environ.__exit__()
support.threading_cleanup(*self._threads)
def request(self, uri, method='GET', body=None, headers={}):
self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
if self.request_handler.protocol_version >= "HTTP/1.1":
headers['Connection'] = 'close'
self.connection.request(method, uri, body, headers)
return self.connection.getresponse()
class BaseHTTPServerTestCase(BaseTestCase):
class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
default_request_version = 'HTTP/1.1'
def do_TEST(self):
self.send_response(HTTPStatus.NO_CONTENT)
self.send_header('Content-Type', 'text/html')
self.send_header('Connection', 'close')
self.end_headers()
def do_KEEP(self):
self.send_response(HTTPStatus.NO_CONTENT)
self.send_header('Content-Type', 'text/html')
self.send_header('Connection', 'keep-alive')
self.end_headers()
def do_KEYERROR(self):
self.send_error(999)
def do_NOTFOUND(self):
self.send_error(HTTPStatus.NOT_FOUND)
def do_EXPLAINERROR(self):
self.send_error(999, "Short Message",
"This is a long \n explanation")
def do_CUSTOM(self):
self.send_response(999)
self.send_header('Content-Type', 'text/html')
self.send_header('Connection', 'close')
self.end_headers()
def do_LATINONEHEADER(self):
self.send_response(999)
self.send_header('X-Special', 'Dängerous Mind')
self.send_header('Connection', 'close')
self.end_headers()
body = self.headers['x-special-incoming'].encode('utf-8')
self.wfile.write(body)
def do_SEND_ERROR(self):
self.send_error(int(self.path[1:]))
def do_HEAD(self):
self.send_error(int(self.path[1:]))
def setUp(self):
BaseTestCase.setUp(self)
self.con = http.client.HTTPConnection(self.HOST, self.PORT)
self.con.connect()
def test_command(self):
self.con.request('GET', '/')
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
def test_request_line_trimming(self):
self.con._http_vsn_str = 'HTTP/1.1\n'
self.con.putrequest('XYZBOGUS', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
def test_version_bogus(self):
self.con._http_vsn_str = 'FUBAR'
self.con.putrequest('GET', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
def test_version_digits(self):
self.con._http_vsn_str = 'HTTP/9.9.9'
self.con.putrequest('GET', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
def test_version_none_get(self):
self.con._http_vsn_str = ''
self.con.putrequest('GET', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
def test_version_none(self):
# Test that a valid method is rejected when not HTTP/1.x
self.con._http_vsn_str = ''
self.con.putrequest('CUSTOM', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
def test_version_invalid(self):
self.con._http_vsn = 99
self.con._http_vsn_str = 'HTTP/9.9'
self.con.putrequest('GET', '/')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
def test_send_blank(self):
self.con._http_vsn_str = ''
self.con.putrequest('', '')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
def test_header_close(self):
self.con.putrequest('GET', '/')
self.con.putheader('Connection', 'close')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
def test_header_keep_alive(self):
self.con._http_vsn_str = 'HTTP/1.1'
self.con.putrequest('GET', '/')
self.con.putheader('Connection', 'keep-alive')
self.con.endheaders()
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
def test_handler(self):
self.con.request('TEST', '/')
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
def test_return_header_keep_alive(self):
self.con.request('KEEP', '/')
res = self.con.getresponse()
self.assertEqual(res.getheader('Connection'), 'keep-alive')
self.con.request('TEST', '/')
self.addCleanup(self.con.close)
def test_internal_key_error(self):
self.con.request('KEYERROR', '/')
res = self.con.getresponse()
self.assertEqual(res.status, 999)
def test_return_custom_status(self):
self.con.request('CUSTOM', '/')
res = self.con.getresponse()
self.assertEqual(res.status, 999)
def test_return_explain_error(self):
self.con.request('EXPLAINERROR', '/')
res = self.con.getresponse()
self.assertEqual(res.status, 999)
self.assertTrue(int(res.getheader('Content-Length')))
def test_latin1_header(self):
self.con.request('LATINONEHEADER', '/', headers={
'X-Special-Incoming': 'Ärger mit Unicode'
})
res = self.con.getresponse()
self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
def test_error_content_length(self):
# Issue #16088: standard error responses should have a content-length
self.con.request('NOTFOUND', '/')
res = self.con.getresponse()
self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
data = res.read()
self.assertEqual(int(res.getheader('Content-Length')), len(data))
def test_send_error(self):
allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
HTTPStatus.RESET_CONTENT)
for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
HTTPStatus.SWITCHING_PROTOCOLS):
self.con.request('SEND_ERROR', '/{}'.format(code))
res = self.con.getresponse()
self.assertEqual(code, res.status)
self.assertEqual(None, res.getheader('Content-Length'))
self.assertEqual(None, res.getheader('Content-Type'))
if code not in allow_transfer_encoding_codes:
self.assertEqual(None, res.getheader('Transfer-Encoding'))
data = res.read()
self.assertEqual(b'', data)
def test_head_via_send_error(self):
allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
HTTPStatus.RESET_CONTENT)
for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
HTTPStatus.SWITCHING_PROTOCOLS):
self.con.request('HEAD', '/{}'.format(code))
res = self.con.getresponse()
self.assertEqual(code, res.status)
if code == HTTPStatus.OK:
self.assertTrue(int(res.getheader('Content-Length')) > 0)
self.assertIn('text/html', res.getheader('Content-Type'))
else:
self.assertEqual(None, res.getheader('Content-Length'))
self.assertEqual(None, res.getheader('Content-Type'))
if code not in allow_transfer_encoding_codes:
self.assertEqual(None, res.getheader('Transfer-Encoding'))
data = res.read()
self.assertEqual(b'', data)
class RequestHandlerLoggingTestCase(BaseTestCase):
class request_handler(BaseHTTPRequestHandler):
protocol_version = 'HTTP/1.1'
default_request_version = 'HTTP/1.1'
def do_GET(self):
self.send_response(HTTPStatus.OK)
self.end_headers()
def do_ERROR(self):
self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
def test_get(self):
self.con = http.client.HTTPConnection(self.HOST, self.PORT)
self.con.connect()
with support.captured_stderr() as err:
self.con.request('GET', '/')
self.con.getresponse()
self.assertTrue(
err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
def test_err(self):
self.con = http.client.HTTPConnection(self.HOST, self.PORT)
self.con.connect()
with support.captured_stderr() as err:
self.con.request('ERROR', '/')
self.con.getresponse()
lines = err.getvalue().split('\n')
self.assertTrue(lines[0].endswith('code 404, message File not found'))
self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
class SimpleHTTPServerTestCase(BaseTestCase):
class request_handler(NoLogRequestHandler, HTTPCompressionRequestHandler):
pass
def setUp(self):
BaseTestCase.setUp(self)
self.cwd = os.getcwd()
basetempdir = tempfile.gettempdir()
os.chdir(basetempdir)
self.data = b'We are the knights who say Ni!'
self.tempdir = tempfile.mkdtemp(dir=basetempdir)
self.tempdir_name = os.path.basename(self.tempdir)
self.base_url = '/' + self.tempdir_name
tempname = os.path.join(self.tempdir, 'test')
with open(tempname, 'wb') as temp:
temp.write(self.data)
temp.flush()
mtime = os.stat(tempname).st_mtime
# compute last modification datetime for browser cache tests
last_modif = datetime.datetime.fromtimestamp(mtime,
datetime.timezone.utc)
self.last_modif_datetime = last_modif.replace(microsecond=0)
self.last_modif_header = email.utils.formatdate(
last_modif.timestamp(), usegmt=True)
def tearDown(self):
try:
os.chdir(self.cwd)
try:
shutil.rmtree(self.tempdir)
except:
pass
finally:
BaseTestCase.tearDown(self)
def check_status_and_reason(self, response, status, data=None):
def close_conn():
"""Don't close reader yet so we can check if there was leftover
buffered input"""
nonlocal reader
reader = response.fp
response.fp = None
reader = None
response._close_conn = close_conn
body = response.read()
self.assertTrue(response)
self.assertEqual(response.status, status)
self.assertIsNotNone(response.reason)
if data:
self.assertEqual(data, body)
# Ensure the server has not set up a persistent connection, and has
# not sent any extra data
self.assertEqual(response.version, 10)
self.assertEqual(response.msg.get("Connection", "close"), "close")
self.assertEqual(reader.read(30), b'', 'Connection should be closed')
reader.close()
return body
@unittest.skipIf(sys.platform == 'darwin',
'undecodable name cannot always be decoded on macOS')
@unittest.skipIf(sys.platform == 'win32',
'undecodable name cannot be decoded on win32')
@unittest.skipUnless(support.TESTFN_UNDECODABLE,
'need support.TESTFN_UNDECODABLE')
def test_undecodable_filename(self):
enc = sys.getfilesystemencoding()
filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
with open(os.path.join(self.tempdir, filename), 'wb') as f:
f.write(support.TESTFN_UNDECODABLE)
response = self.request(self.base_url + '/')
if sys.platform == 'darwin':
# On Mac OS the HFS+ filesystem replaces bytes that aren't valid
# UTF-8 into a percent-encoded value.
for name in os.listdir(self.tempdir):
if name != 'test': # Ignore a filename created in setUp().
filename = name
break
body = self.check_status_and_reason(response, HTTPStatus.OK)
quotedname = urllib.parse.quote(filename, errors='surrogatepass')
self.assertIn(('href="%s"' % quotedname)
.encode(enc, 'surrogateescape'), body)
self.assertIn(('>%s<' % html.escape(filename, quote=False))
.encode(enc, 'surrogateescape'), body)
response = self.request(self.base_url + '/' + quotedname)
self.check_status_and_reason(response, HTTPStatus.OK,
data=support.TESTFN_UNDECODABLE)
def test_get(self):
#constructs the path relative to the root directory of the HTTPServer
response = self.request(self.base_url + '/test')
self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
# check for trailing "/" which should return 404. See Issue17324
response = self.request(self.base_url + '/test/')
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
response = self.request(self.base_url + '/')
self.check_status_and_reason(response, HTTPStatus.OK)
response = self.request(self.base_url)
self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
response = self.request(self.base_url + '/?hi=2')
self.check_status_and_reason(response, HTTPStatus.OK)
response = self.request(self.base_url + '?hi=1')
self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
self.assertEqual(response.getheader("Location"),
self.base_url + "/?hi=1")
response = self.request('/ThisDoesNotExist')
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
response = self.request('/' + 'ThisDoesNotExist' + '/')
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
data = b"Dummy index file\r\n"
with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
f.write(data)
response = self.request(self.base_url + '/')
self.check_status_and_reason(response, HTTPStatus.OK, data)
# chmod() doesn't work as expected on Windows, and filesystem
# permissions are ignored by root on Unix.
if os.name == 'posix' and os.geteuid() != 0:
os.chmod(self.tempdir, 0)
try:
response = self.request(self.base_url + '/')
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
finally:
os.chmod(self.tempdir, 0o755)
def test_head(self):
response = self.request(
self.base_url + '/test', method='HEAD')
self.check_status_and_reason(response, HTTPStatus.OK)
self.assertEqual(response.getheader('content-length'),
str(len(self.data)))
self.assertEqual(response.getheader('content-type'),
'application/octet-stream')
def test_browser_cache(self):
"""Check that when a request to /test is sent with the request header
If-Modified-Since set to date of last modification, the server returns
status code 304, not 200
"""
headers = email.message.Message()
headers['If-Modified-Since'] = self.last_modif_header
response = self.request(self.base_url + '/test', headers=headers)
self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
# one hour after last modification : must return 304
new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
headers = email.message.Message()
headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
usegmt=True)
response = self.request(self.base_url + '/test', headers=headers)
self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
def test_browser_cache_file_changed(self):
# with If-Modified-Since earlier than Last-Modified, must return 200
dt = self.last_modif_datetime
# build datetime object : 365 days before last modification
old_dt = dt - datetime.timedelta(days=365)
headers = email.message.Message()
headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
usegmt=True)
response = self.request(self.base_url + '/test', headers=headers)
self.check_status_and_reason(response, HTTPStatus.OK)
def test_browser_cache_with_If_None_Match_header(self):
# if If-None-Match header is present, ignore If-Modified-Since
headers = email.message.Message()
headers['If-Modified-Since'] = self.last_modif_header
headers['If-None-Match'] = "*"
response = self.request(self.base_url + '/test', headers=headers)
self.check_status_and_reason(response, HTTPStatus.OK)
def test_invalid_requests(self):
response = self.request('/', method='FOO')
self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
# requests must be case sensitive,so this should fail too
response = self.request('/', method='custom')
self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
response = self.request('/', method='GETs')
self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
def test_last_modified(self):
"""Checks that the datetime returned in Last-Modified response header
is the actual datetime of last modification, rounded to the second
"""
response = self.request(self.base_url + '/test')
self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
last_modif_header = response.headers['Last-modified']
self.assertEqual(last_modif_header, self.last_modif_header)
def test_path_without_leading_slash(self):
response = self.request(self.tempdir_name + '/test')
self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
response = self.request(self.tempdir_name + '/test/')
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
response = self.request(self.tempdir_name + '/')
self.check_status_and_reason(response, HTTPStatus.OK)
response = self.request(self.tempdir_name)
self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
response = self.request(self.tempdir_name + '/?hi=2')
self.check_status_and_reason(response, HTTPStatus.OK)
response = self.request(self.tempdir_name + '?hi=1')
self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
self.assertEqual(response.getheader("Location"),
self.tempdir_name + "/?hi=1")
def test_html_escape_filename(self):
filename = '<test&>.txt'
fullpath = os.path.join(self.tempdir, filename)
try:
open(fullpath, 'w').close()
except OSError:
raise unittest.SkipTest('Can not create file %s on current file '
'system' % filename)
try:
response = self.request(self.base_url + '/')
body = self.check_status_and_reason(response, HTTPStatus.OK)
enc = response.headers.get_content_charset()
finally:
os.unlink(fullpath) # avoid affecting test_undecodable_filename
self.assertIsNotNone(enc)
html_text = '>%s<' % html.escape(filename, quote=False)
self.assertIn(html_text.encode(enc), body)
class HTTPCompressionTestCase(BaseTestCase):
class request_handler(NoLogRequestHandler, HTTPCompressionRequestHandler):
compressed_types = ["text/plain", "text/html", "text/css", "text/xml",
"text/javascript", "application/javascript", "application/json"]
compressible_ext = ["txt", "js", "html", "css"]
def setUp(self):
BaseTestCase.setUp(self)
self.cwd = os.getcwd()
basetempdir = tempfile.gettempdir()
os.chdir(basetempdir)
self.data = 10 * b'We are the knights who say Ni!'
self.tempdir = tempfile.mkdtemp(dir=basetempdir)
self.tempdir_name = os.path.basename(self.tempdir)
self.base_url = '/' + self.tempdir_name
with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
temp.write(self.data)
with open(os.path.join(self.tempdir, 'test.abc'), 'wb') as temp:
temp.write(self.data)
for ext in self.compressible_ext:
path = os.path.join(self.tempdir, 'test.{}'.format(ext))
with open(path, 'wb') as temp:
temp.write(self.data)
# create big files, size > 2 << 18
self.repeat = (2 << 19) // len(self.data)
for ext in self.compressible_ext:
path = os.path.join(self.tempdir, 'test_big.{}'.format(ext))
with open(path, 'wb') as temp:
for _ in range(self.repeat):
temp.write(self.data)
def tearDown(self):
try:
os.chdir(self.cwd)
shutil.rmtree(self.tempdir, ignore_errors=True)
finally:
BaseTestCase.tearDown(self)
@unittest.skipIf(zlib is None, 'zlib is not available')
def test_no_content_encoding_header(self):
# no Content-Encoding header, no file extension
response = self.request(self.base_url + '/test')
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
# no Content-Encoding header, uncompressible file extension
response = self.request(self.base_url + '/test.abc')
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
# no Content-Encoding header, compressible file extension
response = self.request(self.base_url + '/test.txt')
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
@unittest.skipIf(zlib is None, 'zlib is not available')
def test_header_set_unsupported_extension(self):
# no file extension
response = self.request(self.base_url + '/test',
headers={'Accept-Encoding': 'gzip'})
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
# uncompressible file extension
response = self.request(self.base_url + '/test.abc',
headers={'Accept-Encoding': 'gzip'})
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
@unittest.skipIf(zlib is None, 'zlib is not available')
def test_header_set_supported_extension(self):
# Accept-Encoding header set, compressible file extension
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'gzip'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()), self.data)
# test with encoding "deflate" instead of "gzip"
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'deflate'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(zlib.decompress(response.read()), self.data)
# alternative Accept-Encoding syntax
for ext in self.compressible_ext:
# x-gzip instead of gzip
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'x-gzip'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()), self.data)
# add quality
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'gzip; q=1'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()), self.data)
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'gzip; q=0.1'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()), self.data)
# all encodings supported
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': '*'})
self.assertIn('Content-Encoding', response.headers)
encoding = response.headers['Content-Encoding']
if encoding in ['gzip', 'x-gzip']:
self.assertEqual(gzip.decompress(response.read()), self.data)
elif encoding == 'deflate':
self.assertEqual(zlib.decompress(response.read(), wbits=15),
self.data)
# Big files
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test_big.{}'.format(ext),
headers={'Accept-Encoding': 'gzip'})
self.assertIn('Content-Encoding', response.headers)
# on HTTP/1.0 Chunked Tranfer Encoding is not supported
self.assertNotIn('Transfer-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()),
self.repeat * self.data)
@unittest.skipIf(zlib is None, 'zlib is not available')
def test_header_set_to_wrong_value_supported_extension(self):
# Content-Encoding header set to a value that doesn't include gzip,
# compressible file extension
for ext in self.compressible_ext:
# quality value set to 0 means that the value is not supported
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'gzip;q=0'})
self.assertNotIn('Content-Encoding', response.headers)
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': '*;q=0'})
self.assertNotIn('Content-Encoding', response.headers)
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'dummy'})
self.assertNotIn('Content-Encoding', response.headers)
@unittest.skipIf(bz2 is None, 'bz2 is not available')
def test_user_defined_compressions(self):
# test with encoding "bzip2" instead of "gzip"
# Write a generator for (non-standard) bzip2 compression encoding.
def _bzip2_producer(fileobj):
bufsize = 2 << 17
producer = bz2.BZ2Compressor()
with fileobj:
while True:
buf = fileobj.read(bufsize)
if not buf: # end of file
yield producer.flush()
return
yield producer.compress(buf)
# update dictionary "compressions" to support bzip2
self.request_handler.compressions.update(bzip2=_bzip2_producer)
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'bzip2'})
self.assertIn('Content-Encoding', response.headers)
self.assertEqual(bz2.decompress(response.read()), self.data)
def test_no_zlib(self):
"""Simulate the case when zlib is not supported."""
save_zlib = server.zlib
save_compressions = self.request_handler.compressions
server.zlib = None
self.request_handler.compressions = {}
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test.{}'.format(ext),
headers={'Accept-Encoding': 'gzip'})
self.assertNotIn('Content-Encoding', response.headers)
self.assertEqual(response.read(), self.data)
server.zlib = save_zlib
self.request_handler.compressions = save_compressions
class HTTPCompressionChunkedTransferTestCase(HTTPCompressionTestCase):
class request_handler(NoLogRequestHandler, HTTPCompressionRequestHandler):
protocol_version = 'HTTP/1.1'
compressed_types = ["text/plain", "text/html", "text/css", "text/xml",
"text/javascript", "application/javascript", "application/json"]
@unittest.skipIf(zlib is None, 'zlib is not available')
def test_header_set_supported_extension(self):
# with protocol set to HTTP/1.1, big files are sent with
# Chunked Tranfer Encoding
for ext in self.compressible_ext:
response = self.request(self.base_url + '/test_big.{}'.format(ext),
headers={'Accept-Encoding': 'gzip', 'Connection': 'close'})
self.assertIn('Content-Encoding', response.headers)
self.assertIn('Transfer-Encoding', response.headers)
self.assertEqual(gzip.decompress(response.read()),
self.repeat * self.data)
cgi_file1 = """\
#!%s
print("Content-type: text/html")
print()
print("Hello World")
"""
cgi_file2 = """\
#!%s
import cgi
print("Content-type: text/html")
print()
form = cgi.FieldStorage()
print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
form.getfirst("bacon")))
"""
cgi_file4 = """\
#!%s
import os
print("Content-type: text/html")
print()
print(os.environ["%s"])
"""
@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
"This test can't be run reliably as root (issue #13308).")
class CGIHTTPServerTestCase(BaseTestCase):
class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
pass
linesep = os.linesep.encode('ascii')
def setUp(self):
BaseTestCase.setUp(self)
self.cwd = os.getcwd()
self.parent_dir = tempfile.mkdtemp()
self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
os.mkdir(self.cgi_dir)
os.mkdir(self.cgi_child_dir)
self.nocgi_path = None
self.file1_path = None
self.file2_path = None
self.file3_path = None
self.file4_path = None
# The shebang line should be pure ASCII: use symlink if possible.
# See issue #7668.
if support.can_symlink():
self.pythonexe = os.path.join(self.parent_dir, 'python')
os.symlink(sys.executable, self.pythonexe)
else:
self.pythonexe = sys.executable
try:
# The python executable path is written as the first line of the
# CGI Python script. The encoding cookie cannot be used, and so the
# path should be encodable to the default script encoding (utf-8)
self.pythonexe.encode('utf-8')
except UnicodeEncodeError:
self.tearDown()
self.skipTest("Python executable path is not encodable to utf-8")
self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
with open(self.nocgi_path, 'w') as fp:
fp.write(cgi_file1 % self.pythonexe)
os.chmod(self.nocgi_path, 0o777)
self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
with open(self.file1_path, 'w', encoding='utf-8') as file1:
file1.write(cgi_file1 % self.pythonexe)
os.chmod(self.file1_path, 0o777)
self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
with open(self.file2_path, 'w', encoding='utf-8') as file2:
file2.write(cgi_file2 % self.pythonexe)
os.chmod(self.file2_path, 0o777)
self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
with open(self.file3_path, 'w', encoding='utf-8') as file3:
file3.write(cgi_file1 % self.pythonexe)
os.chmod(self.file3_path, 0o777)
self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
with open(self.file4_path, 'w', encoding='utf-8') as file4:
file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
os.chmod(self.file4_path, 0o777)
os.chdir(self.parent_dir)
def tearDown(self):
try:
os.chdir(self.cwd)
if self.pythonexe != sys.executable:
os.remove(self.pythonexe)
if self.nocgi_path:
os.remove(self.nocgi_path)
if self.file1_path:
os.remove(self.file1_path)
if self.file2_path:
os.remove(self.file2_path)
if self.file3_path:
os.remove(self.file3_path)
if self.file4_path:
os.remove(self.file4_path)
os.rmdir(self.cgi_child_dir)
os.rmdir(self.cgi_dir)
os.rmdir(self.parent_dir)
finally:
BaseTestCase.tearDown(self)
def test_url_collapse_path(self):
# verify tail is the last portion and head is the rest on proper urls
test_vectors = {
'': '//',
'..': IndexError,
'/.//..': IndexError,
'/': '//',
'//': '//',
'/\\': '//\\',
'/.//': '//',
'cgi-bin/file1.py': '/cgi-bin/file1.py',
'/cgi-bin/file1.py': '/cgi-bin/file1.py',
'a': '//a',
'/a': '//a',
'//a': '//a',
'./a': '//a',
'./C:/': '/C:/',
'/a/b': '/a/b',
'/a/b/': '/a/b/',
'/a/b/.': '/a/b/',
'/a/b/c/..': '/a/b/',
'/a/b/c/../d': '/a/b/d',
'/a/b/c/../d/e/../f': '/a/b/d/f',
'/a/b/c/../d/e/../../f': '/a/b/f',
'/a/b/c/../d/e/.././././..//f': '/a/b/f',
'../a/b/c/../d/e/.././././..//f': IndexError,
'/a/b/c/../d/e/../../../f': '/a/f',
'/a/b/c/../d/e/../../../../f': '//f',
'/a/b/c/../d/e/../../../../../f': IndexError,
'/a/b/c/../d/e/../../../../f/..': '//',
'/a/b/c/../d/e/../../../../f/../.': '//',
}
for path, expected in test_vectors.items():
if isinstance(expected, type) and issubclass(expected, Exception):
self.assertRaises(expected,
server._url_collapse_path, path)
else:
actual = server._url_collapse_path(path)
self.assertEqual(expected, actual,
msg='path = %r\nGot: %r\nWanted: %r' %
(path, actual, expected))
def test_headers_and_content(self):
res = self.request('/cgi-bin/file1.py')
self.assertEqual(
(res.read(), res.getheader('Content-type'), res.status),
(b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
def test_issue19435(self):
res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
def test_post(self):
params = urllib.parse.urlencode(
{'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
headers = {'Content-type' : 'application/x-www-form-urlencoded'}
res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
def test_invaliduri(self):
res = self.request('/cgi-bin/invalid')
res.read()
self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
def test_authorization(self):
headers = {b'Authorization' : b'Basic ' +
base64.b64encode(b'username:pass')}
res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
self.assertEqual(
(b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
(res.read(), res.getheader('Content-type'), res.status))
def test_no_leading_slash(self):
# http://bugs.python.org/issue2254
res = self.request('cgi-bin/file1.py')
self.assertEqual(
(b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
(res.read(), res.getheader('Content-type'), res.status))
def test_os_environ_is_not_altered(self):
signature = "Test CGI Server"
os.environ['SERVER_SOFTWARE'] = signature
res = self.request('/cgi-bin/file1.py')
self.assertEqual(
(b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
(res.read(), res.getheader('Content-type'), res.status))
self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
def test_urlquote_decoding_in_cgi_check(self):
res = self.request('/cgi-bin%2ffile1.py')
self.assertEqual(
(b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
(res.read(), res.getheader('Content-type'), res.status))
def test_nested_cgi_path_issue21323(self):
res = self.request('/cgi-bin/child-dir/file3.py')