Last set of CW Pro 5 projects (probably)
[python/dscho.git] / Lib / test / test_cgi.py
blob29eb5a6c1850cd295524043f061c7501c9d5aa4f
1 import cgi
2 import os
3 import sys
5 class HackedSysModule:
6 # The regression test will have real values in sys.argv, which
7 # will completely confuse the test of the cgi module
8 argv = []
9 stdin = sys.stdin
11 cgi.sys = HackedSysModule()
13 try:
14 from cStringIO import StringIO
15 except ImportError:
16 from StringIO import StringIO
18 class ComparableException:
19 def __init__(self, err):
20 self.err = err
22 def __str__(self):
23 return str(self.err)
25 def __cmp__(self, anExc):
26 if not isinstance(anExc, Exception):
27 return -1
28 x = cmp(self.err.__class__, anExc.__class__)
29 if x != 0:
30 return x
31 return cmp(self.err.args, anExc.args)
33 def __getattr__(self, attr):
34 return getattr(self, self.err)
36 def do_test(buf, method):
37 env = {}
38 if method == "GET":
39 fp = None
40 env['REQUEST_METHOD'] = 'GET'
41 env['QUERY_STRING'] = buf
42 elif method == "POST":
43 fp = StringIO(buf)
44 env['REQUEST_METHOD'] = 'POST'
45 env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
46 env['CONTENT_LENGTH'] = str(len(buf))
47 else:
48 raise ValueError, "unknown method: %s" % method
49 try:
50 return cgi.parse(fp, env, strict_parsing=1)
51 except StandardError, err:
52 return ComparableException(err)
54 # A list of test cases. Each test case is a a two-tuple that contains
55 # a string with the query and a dictionary with the expected result.
57 parse_test_cases = [
58 ("", ValueError("bad query field: ''")),
59 ("&", ValueError("bad query field: ''")),
60 ("&&", ValueError("bad query field: ''")),
61 # Should the next few really be valid?
62 ("=", {}),
63 ("=&=", {}),
64 # This rest seem to make sense
65 ("=a", {'': ['a']}),
66 ("&=a", ValueError("bad query field: ''")),
67 ("=a&", ValueError("bad query field: ''")),
68 ("=&a", ValueError("bad query field: 'a'")),
69 ("b=a", {'b': ['a']}),
70 ("b+=a", {'b ': ['a']}),
71 ("a=b=a", {'a': ['b=a']}),
72 ("a=+b=a", {'a': [' b=a']}),
73 ("&b=a", ValueError("bad query field: ''")),
74 ("b&=a", ValueError("bad query field: 'b'")),
75 ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}),
76 ("a=a+b&a=b+a", {'a': ['a b', 'b a']}),
77 ("x=1&y=2.0&z=2-3.%2b0", {'x': ['1'], 'y': ['2.0'], 'z': ['2-3.+0']}),
78 ("Hbc5161168c542333633315dee1182227:key_store_seqid=400006&cuyer=r&view=bustomer&order_id=0bb2e248638833d48cb7fed300000f1b&expire=964546263&lobale=en-US&kid=130003.300038&ss=env",
79 {'Hbc5161168c542333633315dee1182227:key_store_seqid': ['400006'],
80 'cuyer': ['r'],
81 'expire': ['964546263'],
82 'kid': ['130003.300038'],
83 'lobale': ['en-US'],
84 'order_id': ['0bb2e248638833d48cb7fed300000f1b'],
85 'ss': ['env'],
86 'view': ['bustomer'],
87 }),
89 ("group_id=5470&set=custom&_assigned_to=31392&_status=1&_category=100&SUBMIT=Browse",
90 {'SUBMIT': ['Browse'],
91 '_assigned_to': ['31392'],
92 '_category': ['100'],
93 '_status': ['1'],
94 'group_id': ['5470'],
95 'set': ['custom'],
99 def norm(list):
100 if type(list) == type([]):
101 list.sort()
102 return list
104 def first_elts(list):
105 return map(lambda x:x[0], list)
107 def first_second_elts(list):
108 return map(lambda p:(p[0], p[1][0]), list)
110 def main():
111 for orig, expect in parse_test_cases:
112 # Test basic parsing
113 print repr(orig)
114 d = do_test(orig, "GET")
115 assert d == expect, "Error parsing %s" % repr(orig)
116 d = do_test(orig, "POST")
117 assert d == expect, "Error parsing %s" % repr(orig)
119 env = {'QUERY_STRING': orig}
120 fcd = cgi.FormContentDict(env)
121 sd = cgi.SvFormContentDict(env)
122 fs = cgi.FieldStorage(environ=env)
123 if type(expect) == type({}):
124 # test dict interface
125 assert len(expect) == len(fcd)
126 assert norm(expect.keys()) == norm(fcd.keys())
127 assert norm(expect.values()) == norm(fcd.values())
128 assert norm(expect.items()) == norm(fcd.items())
129 assert fcd.get("nonexistent field", "default") == "default"
130 assert len(sd) == len(fs)
131 assert norm(sd.keys()) == norm(fs.keys())
132 assert fs.getvalue("nonexistent field", "default") == "default"
133 # test individual fields
134 for key in expect.keys():
135 expect_val = expect[key]
136 assert fcd.has_key(key)
137 assert norm(fcd[key]) == norm(expect[key])
138 assert fcd.get(key, "default") == fcd[key]
139 assert fs.has_key(key)
140 if len(expect_val) > 1:
141 single_value = 0
142 else:
143 single_value = 1
144 try:
145 val = sd[key]
146 except IndexError:
147 assert not single_value
148 assert fs.getvalue(key) == expect_val
149 else:
150 assert single_value
151 assert val == expect_val[0]
152 assert fs.getvalue(key) == expect_val[0]
153 assert norm(sd.getlist(key)) == norm(expect_val)
154 if single_value:
155 assert norm(sd.values()) == \
156 first_elts(norm(expect.values()))
157 assert norm(sd.items()) == \
158 first_second_elts(norm(expect.items()))
160 # Test the weird FormContentDict classes
161 env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"}
162 expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'}
163 d = cgi.InterpFormContentDict(env)
164 for k, v in expect.items():
165 assert d[k] == v
166 for k, v in d.items():
167 assert expect[k] == v
168 assert norm(expect.values()) == norm(d.values())
170 print "Testing log"
171 cgi.initlog()
172 cgi.log("Testing")
173 cgi.logfp = sys.stdout
174 cgi.initlog("%s", "Testing initlog 1")
175 cgi.log("%s", "Testing log 2")
176 if os.path.exists("/dev/null"):
177 cgi.logfp = None
178 cgi.logfile = "/dev/null"
179 cgi.initlog("%s", "Testing log 3")
180 cgi.log("Testing log 4")
182 main()