-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathtest.py
More file actions
3155 lines (2490 loc) · 118 KB
/
test.py
File metadata and controls
3155 lines (2490 loc) · 118 KB
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
#
# Copyright (C) 2000, 2001, 2013 Gregory Trubetskoy
# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
#
"""
Writing Tests
Writing mod_python tests can be a tricky task. This module
attempts to lay out a framework for making the testing process
consistent and quick to implement.
All tests are based on Python Unit Test framework, it's a good
idea to study the docs for the unittest module before going any
further.
To write a test, first decide in which of the 3 following categories
it falls:
o Simple tests that do not require any special server configuration
and can be conducted along with other similar tests all in one
request.
o Per-Request tests. These tests require a whole separate request
(or several requests) for a complete test.
o Per-Instance tests. These require restarting the instance of
http and running it in a particular way, perhaps with a special
config to complete the test. An example might be load testing, or
checking for memory leaks.
There are two modules involved in testing - the one you're looking at
now (test.py), which is responsible for setting up the http config
running it and initiating requests, AND htdocs/tests.py (sorry for
boring names), which is where all mod_python handlers reside.
To write a Simple test:
o Look at tests.SimpleTestCase class and the test methods in it,
then write your own following the example.
o Look at the tests.make_suite function, and make sure your test
is added to the suite in there.
o Keep in mind that the only way for Simple tests to communicate
with the outside world is via the error log, do not be shy about
writing to it.
To write a Per-Request test:
Most, if not all per-request tests require special server configuration
as part of the fixture. To avoid having to restart the server with a
different config (which would, btw, effectively turn this into a per-
instance test), we separate configs by placing them in separate virtual
hosts. This will become clearer if you follow the code.
o Look at test.PerRequestCase class.
o Note that for every test there are two methods defined: the test
method itself, plus a method with the same name ending with
"_conf". The _conf methods are supposed to return the virtual
host config necessary for this test. As tests are instantiated,
the configs are appended to a class variable (meaning its shared
across all instances) appendConfig, then before the suite is run,
the httpd config is built and httpd started. Each test will
know to query its own virtual host. This way all tests can be
conducted using a single instance of httpd.
o Note how the _config methods generate the config - they use the
httpdconf module to generate an object whose string representation
is the config part, simlar to the way HTMLgen produces html. You
do not have to do it this way, but it makes for cleaner code.
o Every Per-Request test must also have a corresponding handler in
the tests module. The convention is name everything based on the
subject of the test, e.g. the test of req.document_root() will have
a test method in PerRequestCase class called test_req_documet_root,
a config method PerRequestCase.test_req_document_root_conf, the
VirtualHost name will be test_req_document_root, and the handler
in tests.py will be called req_document_root.
o Note that you cannot use urllib if you have to specify a custom
host: header, which is required for this whole thing to work.
There is a convenience method, vhost_get, which takes the host
name as the first argument, and optionally path as the second
(though that is almost never needed). If vhost_get does not
suffice, use httplib. Note the very useful skip_host=1 argument.
o Remember to have your test added to the suite in
PerInstanceTestCase.testPerRequestTests
To write a Per-Instance test:
o Look at test.PerInstanceTestCase class.
o You have to start httpd in your test, but no need to stop it,
it will be stopped for you in tearDown()
o Add the test to the suite in test.suite() method
"""
from __future__ import print_function
import sys
import os
PY2 = sys.version[0] == '2'
try:
import mod_python.version
except:
print (
"Cannot import mod_python.version. Either you didn't "
"run the ./configure script, or you're running this script "
"in a Win32 environment, in which case you have to make it by hand."
)
sys.exit()
else:
def testpath(variable,isfile):
value = getattr(mod_python.version,variable,'<undefined>')
if isfile:
if os.path.isfile(value):
return True
else:
if os.path.isdir(value):
return True
print('Bad value for mod_python.version.%s : %s'%(
variable,
value
))
return False
good = testpath('HTTPD',True)
good = testpath('TESTHOME',False) and good
good = testpath('LIBEXECDIR',False) and good
good = testpath('TEST_MOD_PYTHON_SO',True) and good
if not good:
print("Please check your mod_python/version.py file")
sys.exit()
del testpath
del good
from mod_python.httpdconf import *
import unittest
if PY2:
from commands import getoutput
import urllib2
import httplib
from httplib import UNAUTHORIZED
import md5
from cStringIO import StringIO
from urllib2 import urlopen
from urllib import urlencode
else:
from subprocess import getoutput
import urllib.request, urllib.error
import http.client
from http.client import UNAUTHORIZED
from hashlib import md5
from io import StringIO, BytesIO, TextIOWrapper
from urllib.request import urlopen
from urllib.parse import urlencode
import shutil
import time
import socket
import tempfile
import base64
import random
try:
import threading
THREADS = True
except:
THREADS = False
HTTPD = mod_python.version.HTTPD
TESTHOME = mod_python.version.TESTHOME
MOD_PYTHON_SO = mod_python.version.TEST_MOD_PYTHON_SO
LIBEXECDIR = mod_python.version.LIBEXECDIR
SERVER_ROOT = TESTHOME
CONFIG = os.path.join(TESTHOME, "conf", "test.conf")
DOCUMENT_ROOT = os.path.join(TESTHOME, "htdocs")
TMP_DIR = os.path.join(TESTHOME, "tmp")
PORT = 0 # this is set in fundUnusedPort()
# readBlockSize is required for the test_fileupload_* tests.
# We can't import mod_python.util.readBlockSize from a cmd line
# interpreter, so we'll hard code it here.
# If util.readBlockSize changes, it MUST be changed here as well.
# Maybe we should set up a separate test to query the server to
# get the correct readBlockSize?
#
readBlockSize = 65368
def findUnusedPort():
# bind to port 0 which makes the OS find the next
# unused port.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def http_connection(conn_str):
if PY2:
return httplib.HTTPConnection(conn_str)
else:
return http.client.HTTPConnection(conn_str)
def md5_hash(s):
if PY2:
return md5.new(s).hexdigest()
else:
if isinstance(s, str):
s = s.encode('latin1')
return md5(s).hexdigest().encode('latin1')
def get_ab_path():
""" Find the location of the ab (apache benchmark) program """
for name in ['ab', 'ab2', 'ab.exe', 'ab2.exe']:
path = os.path.join(os.path.split(HTTPD)[0], name)
if os.path.exists(path):
return quote_if_space(path)
return None
def get_apache_version():
print("Checking Apache version....")
httpd = quote_if_space(HTTPD)
stdout = getoutput('%s -v' % (httpd))
version_str = None
for line in stdout.splitlines():
if line.startswith('Server version'):
version_str = line.strip()
break
if version_str:
version_str = version_str.split('/')[1]
major,minor,patch = version_str.split('.',3)
version = '%s.%s' % (major,minor)
else:
print("Can't determine Apache version. Assuming 2.0")
version = '2.0'
print(version)
return version
APACHE_VERSION = get_apache_version()
if not mod_python.version.HTTPD_VERSION.startswith(APACHE_VERSION):
print("ERROR: Build version %s does not match version reported by %s: %s, re-run ./configure?" % \
(mod_python.version.HTTPD_VERSION, HTTPD, APACHE_VERSION))
sys.exit()
class HttpdCtrl:
# a mixin providing ways to control httpd
def checkFiles(self):
modules = os.path.join(SERVER_ROOT, "modules")
if not os.path.exists(modules):
os.mkdir(modules)
logs = os.path.join(SERVER_ROOT, "logs")
if os.path.exists(logs):
shutil.rmtree(logs)
os.mkdir(logs)
# place
if os.path.exists(TMP_DIR):
shutil.rmtree(TMP_DIR)
os.mkdir(TMP_DIR)
def makeConfig(self, append=Container()):
# create config files, etc
print(" Creating config....")
self.checkFiles()
global PORT
PORT = findUnusedPort()
print(" listen port:", PORT)
# where other modules might be
modpath = LIBEXECDIR
s = Container(
IfModule("!prefork.c",
IfModule("!worker.c",
IfModule("!perchild.c",
IfModule("!mpm_winnt.c",
LoadModule("mpm_prefork_module modules/mod_mpm_prefork.so"),
)))),
IfModule("prefork.c",
StartServers("3"),
MaxSpareServers("1")),
IfModule("worker.c",
StartServers("2"),
MaxClients("6"),
MinSpareThreads("1"),
MaxSpareThreads("1"),
ThreadsPerChild("3"),
MaxRequestsPerChild("0")),
IfModule("perchild.c",
NumServers("2"),
StartThreads("2"),
MaxSpareThreads("1"),
MaxThreadsPerChild("2")),
IfModule("mpm_winnt.c",
ThreadsPerChild("5"),
MaxRequestsPerChild("0")),
IfModule("!mod_mime.c",
LoadModule("mime_module %s" %
quote_if_space(os.path.join(modpath, "mod_mime.so")))),
IfModule("!mod_log_config.c",
LoadModule("log_config_module %s" %
quote_if_space(os.path.join(modpath, "mod_log_config.so")))),
IfModule("!mod_dir.c",
LoadModule("dir_module %s" %
quote_if_space(os.path.join(modpath, "mod_dir.so")))),
IfModule("!mod_include.c",
LoadModule("include_module %s" %
quote_if_space(os.path.join(modpath, "mod_include.so")))),
ServerRoot(SERVER_ROOT),
ErrorLog("logs/error_log"),
LogLevel("debug"),
LogFormat(r'"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined'),
CustomLog("logs/access_log combined"),
TypesConfig("conf/mime.types"),
PidFile("logs/httpd.pid"),
ServerName("127.0.0.1"),
Listen(PORT),
Timeout(60),
PythonOption('mod_python.mutex_directory %s' % TMP_DIR),
PythonOption('PythonOptionTest sample_value'),
DocumentRoot(DOCUMENT_ROOT),
LoadModule("python_module %s" % quote_if_space(MOD_PYTHON_SO)))
if APACHE_VERSION == '2.4':
s.append(Mutex("file:logs"))
else:
s.append(LockFile("logs/accept.lock"))
if APACHE_VERSION == '2.4':
s.append(IfModule("!mod_unixd.c",
LoadModule("unixd_module %s" %
quote_if_space(os.path.join(modpath, "mod_unixd.so")))))
s.append(IfModule("!mod_authn_core.c",
LoadModule("authn_core_module %s" %
quote_if_space(os.path.join(modpath, "mod_authn_core.so")))))
s.append(IfModule("!mod_authz_core.c",
LoadModule("authz_core_module %s" %
quote_if_space(os.path.join(modpath, "mod_authz_core.so")))))
s.append(IfModule("!mod_authn_file.c",
LoadModule("authn_file_module %s" %
quote_if_space(os.path.join(modpath, "mod_authn_file.so")))))
s.append(IfModule("!mod_authz_user.c",
LoadModule("authz_user_module %s" %
quote_if_space(os.path.join(modpath, "mod_authz_user.so")))))
if APACHE_VERSION in ['2.2', '2.4']:
# mod_auth has been split into mod_auth_basic and some other modules
s.append(IfModule("!mod_auth_basic.c",
LoadModule("auth_basic_module %s" %
quote_if_space(os.path.join(modpath, "mod_auth_basic.so")))))
# Default KeepAliveTimeout is 5 for apache 2.2, but 15 in apache 2.0
# Explicitly set the value so it's the same as 2.0
s.append(KeepAliveTimeout("15"))
else:
s.append(IfModule("!mod_auth.c",
LoadModule("auth_module %s" %
quote_if_space(os.path.join(modpath, "mod_auth.so")))))
s.append(Comment(" --APPENDED--"))
s.append(append)
f = open(CONFIG, "w")
f.write(str(s))
f.close()
def startHttpd(self,extra=''):
print(" Starting Apache....")
httpd = quote_if_space(HTTPD)
config = quote_if_space(CONFIG)
cmd = '%s %s -k start -f %s' % (httpd, extra, config)
print(" ", cmd)
os.system(cmd)
time.sleep(1)
self.httpd_running = 1
def stopHttpd(self):
print(" Stopping Apache...")
httpd = quote_if_space(HTTPD)
config = quote_if_space(CONFIG)
cmd = '%s -k stop -f %s' % (httpd, config)
print(" ", cmd)
os.system(cmd)
time.sleep(1)
# Wait for apache to stop by checking for the existence of pid the
# file. If pid file still exists after 20 seconds raise an error.
# This check is here to facilitate testing on the qemu emulator.
# Qemu will run about 1/10 the native speed, so 1 second may
# not be long enough for apache to shut down.
count = 0
pid_file = os.path.join(os.getcwd(), 'logs/httpd.pid')
while os.path.exists(pid_file):
time.sleep(1)
count += 1
if count > 20:
# give up - apache refuses to die - or died a horrible
# death and never removed the pid_file.
raise RuntimeError(" Trouble stopping apache")
self.httpd_running = 0
class PerRequestTestCase(unittest.TestCase):
appendConfig = APACHE_VERSION < '2.4' and Container(NameVirtualHost('*')) or Container()
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
# add to config
try:
confMeth = getattr(self, methodName+"_conf")
self.__class__.appendConfig.append(confMeth())
except AttributeError:
pass
def vhost_get(self, vhost, path="/tests.py"):
# this is so that tests could easily be staged with curl
curl = "curl --verbose --header 'Host: %s' http://127.0.0.1:%s%s" % (vhost, PORT, path)
print(" $ %s" % curl)
# allows to specify a custom host: header
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", path, skip_host=1)
conn.putheader("Host", "%s:%s" % (vhost, PORT))
conn.endheaders()
response = conn.getresponse()
if PY2:
rsp = response.read()
else:
rsp = response.read().decode('latin1')
conn.close()
return rsp
def vhost_post_multipart_form_data(self, vhost, path="/tests.py",variables={}, files={}):
# variables is a { name : value } dict
# files is a { name : (filename, content) } dict
# build the POST entity
if PY2:
entity = StringIO()
boundary = "============="+''.join( [ random.choice('0123456789') for x in range(10) ] )+'=='
else:
bio = BytesIO()
entity = TextIOWrapper(bio, encoding='latin1')
boundary = "============="+''.join( [ random.choice('0123456789') for x in range(10) ] )+'=='
# A part for each variable
for name, value in variables.items():
entity.write('--')
entity.write(boundary)
entity.write('\r\n')
entity.write('Content-Type: text/plain\r\n')
entity.write('Content-Disposition: form-data;\r\n name="%s"\r\n' % name)
entity.write('\r\n')
entity.write(str(value))
entity.write('\r\n')
# A part for each file
for name, filespec in files.items():
filename, content = filespec
# if content is readable, read it
try:
content = content.read()
except:
pass
if not isinstance(content, str): # always false on 2.x
content = content.decode('latin1')
entity.write('--')
entity.write(boundary)
entity.write('\r\n')
entity.write('Content-Type: application/octet-stream\r\n')
entity.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (name, filename))
entity.write('\r\n')
entity.write(content)
entity.write('\r\n')
# The final boundary
entity.write('--')
entity.write(boundary)
entity.write('--\r\n')
entity.flush()
if PY2:
entity = entity.getvalue()
else:
entity = bio.getvalue()
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("POST", path, skip_host=1)
conn.putheader("Host", "%s:%s" % (vhost, PORT))
conn.putheader("Content-Type", 'multipart/form-data; boundary="%s"' % boundary)
conn.putheader("Content-Length", '%s'%(len(entity)))
conn.endheaders()
start = time.time()
conn.send(entity)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(' --> Send + process + receive took %.3f s'%(time.time()-start))
return rsp
### Tests begin here
def test_req_document_root_conf(self):
c = VirtualHost("*",
ServerName("test_req_document_root"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_document_root"),
PythonDebug("On")))
return c
def test_req_document_root(self):
print("\n * Testing req.document_root()")
rsp = self.vhost_get("test_req_document_root")
if rsp.upper() != DOCUMENT_ROOT.replace("\\", "/").upper():
self.fail(repr(rsp))
def test_req_add_handler_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_handler"),
PythonDebug("On")))
return c
def test_req_add_handler(self):
print("\n * Testing req.add_handler()")
rsp = self.vhost_get("test_req_add_handler")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_add_bad_handler_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_bad_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_bad_handler"),
PythonDebug("On")))
return c
def test_req_add_bad_handler(self):
# adding a non-existent handler with req.add_handler should raise
# an exception.
print("""\n * Testing req.add_handler("PythonHandler", "bad_handler")""")
rsp = self.vhost_get("test_req_add_bad_handler")
# look for evidence of the exception in the error log
time.sleep(1)
f = open(os.path.join(SERVER_ROOT, "logs/error_log"))
log = f.read()
f.close()
if log.find("contains no 'bad_handler'") == -1:
self.fail("""Could not find "contains no 'bad_handler'" in error_log""")
def test_req_add_empty_handler_string_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_empty_handler_string"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_empty_handler_string"),
PythonDebug("On")))
return c
def test_req_add_empty_handler_string(self):
# Adding an empty string as the handler in req.add_handler
# should raise an exception
print("""\n * Testing req.add_handler("PythonHandler","")""")
rsp = self.vhost_get("test_req_add_empty_handler_string")
if (rsp == "no exception"):
self.fail("Expected an exception")
def test_req_add_handler_empty_phase_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler_empty_phase"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonInterpPerDirective("On"),
PythonFixupHandler("tests::req_add_handler_empty_phase"),
PythonDebug("On")))
return c
def test_req_add_handler_empty_phase(self):
# Adding handler to content phase when no handler already
# exists for that phase.
print("""\n * Testing req.add_handler() for empty phase""")
rsp = self.vhost_get("test_req_add_handler_empty_phase")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_add_handler_directory_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler_directory"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonInterpPerDirective("On"),
PythonFixupHandler("tests::test_req_add_handler_directory"),
PythonDebug("On")))
return c
def test_req_add_handler_directory(self):
# Checking that directory is canonicalized and trailing
# slash is added.
print("""\n * Testing req.add_handler() directory""")
rsp = self.vhost_get("test_req_add_handler_directory")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_accesshandler_add_handler_to_empty_hl_conf(self):
# Note that there is no PythonHandler specified in the the VirtualHost
# config. We want to see if req.add_handler will work when the
# handler list is empty.
#PythonHandler("tests::req_add_empty_handler_string"),
c = VirtualHost("*",
ServerName("test_accesshandler_add_handler_to_empty_hl"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonAccessHandler("tests::accesshandler_add_handler_to_empty_hl"),
PythonDebug("On")))
return c
def test_accesshandler_add_handler_to_empty_hl(self):
print("""\n * Testing req.add_handler() when handler list is empty""")
rsp = self.vhost_get("test_accesshandler_add_handler_to_empty_hl")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_allow_methods_conf(self):
c = VirtualHost("*",
ServerName("test_req_allow_methods"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_allow_methods"),
PythonDebug("On")))
return c
def test_req_allow_methods(self):
print("\n * Testing req.allow_methods()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_allow_methods", PORT))
conn.endheaders()
response = conn.getresponse()
server_hdr = response.getheader("Allow", "")
conn.close()
self.failUnless(server_hdr.find("PYTHONIZE") > -1, "req.allow_methods() didn't work")
def test_req_unauthorized_conf(self):
if APACHE_VERSION == '2.4':
c = VirtualHost("*",
ServerName("test_req_unauthorized"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
Require("all granted"),
PythonHandler("tests::req_unauthorized"),
PythonDebug("On")))
else:
c = VirtualHost("*",
ServerName("test_req_unauthorized"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
PythonHandler("tests::req_unauthorized"),
PythonDebug("On")))
return c
def test_req_unauthorized(self):
print("\n * Testing whether returning HTTP_UNAUTHORIZED works")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_unauthorized", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_unauthorized", PORT))
auth = base64.encodestring(b"spam:BAD PASSWD").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if response.status != UNAUTHORIZED:
self.fail("req.status is not httplib.UNAUTHORIZED, but: %s" % repr(response.status))
if rsp == b"test ok":
self.fail("We were supposed to get HTTP_UNAUTHORIZED")
def test_req_get_basic_auth_pw_conf(self):
if APACHE_VERSION == '2.4':
c = VirtualHost("*",
ServerName("test_req_get_basic_auth_pw"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
Require("all granted"),
PythonHandler("tests::req_get_basic_auth_pw"),
PythonDebug("On")))
else:
c = VirtualHost("*",
ServerName("test_req_get_basic_auth_pw"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
PythonHandler("tests::req_get_basic_auth_pw"),
PythonDebug("On")))
return c
def test_req_get_basic_auth_pw(self):
print("\n * Testing req.get_basic_auth_pw()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_get_basic_auth_pw", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_get_basic_auth_pw_latin1_conf(self):
return self.test_req_get_basic_auth_pw_conf()
def test_req_get_basic_auth_pw_latin1(self):
print("\n * Testing req.get_basic_auth_pw_latin1()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_get_basic_auth_pw", PORT))
auth = base64.encodestring(b'sp\xe1m:\xe9ggs').strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_auth_type_conf(self):
c = VirtualHost("*",
ServerName("test_req_auth_type"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("dummy"),
Require("valid-user"),
PythonAuthenHandler("tests::req_auth_type"),
PythonAuthzHandler("tests::req_auth_type"),
PythonHandler("tests::req_auth_type"),
PythonDebug("On")))
return c
def test_req_auth_type(self):
print("\n * Testing req.auth_type()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_auth_type", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_requires_conf(self):
c = VirtualHost("*",
ServerName("test_req_requires"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("dummy"),
Require("valid-user"),
PythonAuthenHandler("tests::req_requires"),
PythonDebug("On")))
return c
def test_req_requires(self):
print("\n * Testing req.requires()")
rsp = self.vhost_get("test_req_requires")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_requires", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_internal_redirect_conf(self):
c = VirtualHost("*",
ServerName("test_req_internal_redirect"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_internal_redirect | .py"),
PythonHandler("tests::req_internal_redirect_int | .int"),
PythonDebug("On")))
return c
def test_req_internal_redirect(self):
print("\n * Testing req.internal_redirect()")
rsp = self.vhost_get("test_req_internal_redirect")
if rsp != "test ok":
self.fail("internal_redirect")
def test_req_construct_url_conf(self):
c = VirtualHost("*",
ServerName("test_req_construct_url"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_construct_url"),
PythonDebug("On")))
return c
def test_req_construct_url(self):
print("\n * Testing req.construct_url()")
rsp = self.vhost_get("test_req_construct_url")
if rsp != "test ok":
self.fail("construct_url")
def test_req_read_conf(self):
c = Container(Timeout("5"),
VirtualHost("*",
ServerName("test_req_read"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_read"),
PythonDebug("On"))))
return c
def test_req_read(self):
print("\n * Testing req.read()")
params = b'1234567890'*10000
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_read:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()