blob: 97d9e8f789cd31ab792050b6eba79771d5f480a0 [file] [log] [blame]
Facundo Batista5a3b5242007-07-13 10:43:44 +00001import base64
Fred Drakeba613c32005-02-10 18:33:30 +00002import datetime
Skip Montanaro3e7bba92001-10-19 16:06:52 +00003import sys
Facundo Batista5a3b5242007-07-13 10:43:44 +00004import time
Skip Montanaro419abda2001-10-01 17:47:44 +00005import unittest
6import xmlrpclib
Facundo Batistaa53872b2007-08-14 13:35:00 +00007import SimpleXMLRPCServer
Facundo Batista7f686fc2007-08-17 19:16:44 +00008import mimetools
Georg Brandl5d1b4d42007-12-07 09:07:10 +00009import httplib
10import socket
Jeremy Hylton89420112008-11-24 22:00:29 +000011import StringIO
Georg Brandl5d1b4d42007-12-07 09:07:10 +000012import os
Senthil Kumaran20d114c2009-04-01 20:26:33 +000013import re
Barry Warsaw04f357c2002-07-23 19:04:11 +000014from test import test_support
Skip Montanaro419abda2001-10-01 17:47:44 +000015
Fred Drake22c07062005-02-11 17:59:08 +000016try:
Victor Stinnera44b5a32010-04-27 23:14:58 +000017 import threading
18except ImportError:
19 threading = None
20
21try:
Zachary Ware1f702212013-12-10 14:09:20 -060022 import gzip
23except ImportError:
24 gzip = None
25
Skip Montanaro419abda2001-10-01 17:47:44 +000026alist = [{'astring': 'foo@bar.baz.spam',
27 'afloat': 7283.43,
Skip Montanaro3e7bba92001-10-19 16:06:52 +000028 'anint': 2**20,
29 'ashortlong': 2L,
Skip Montanaro419abda2001-10-01 17:47:44 +000030 'anotherlist': ['.zyx.41'],
31 'abase64': xmlrpclib.Binary("my dog has fleas"),
32 'boolean': xmlrpclib.False,
Fred Drakeba613c32005-02-10 18:33:30 +000033 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
34 'datetime2': xmlrpclib.DateTime(
35 (2005, 02, 10, 11, 41, 23, 0, 1, -1)),
36 'datetime3': xmlrpclib.DateTime(
37 datetime.datetime(2005, 02, 10, 11, 41, 23)),
Skip Montanaro419abda2001-10-01 17:47:44 +000038 }]
39
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +020040if test_support.have_unicode:
41 alist[0].update({
42 'unicode': test_support.u(r'\u4000\u6000\u8000'),
43 test_support.u(r'ukey\u4000'): 'regular value',
44 })
45
Skip Montanaro419abda2001-10-01 17:47:44 +000046class XMLRPCTestCase(unittest.TestCase):
47
48 def test_dump_load(self):
Ezio Melotti2623a372010-11-21 13:34:58 +000049 self.assertEqual(alist,
50 xmlrpclib.loads(xmlrpclib.dumps((alist,)))[0][0])
Skip Montanaro419abda2001-10-01 17:47:44 +000051
Fred Drakeba613c32005-02-10 18:33:30 +000052 def test_dump_bare_datetime(self):
Skip Montanaro174dd222005-05-14 20:54:16 +000053 # This checks that an unwrapped datetime.date object can be handled
54 # by the marshalling code. This can't be done via test_dump_load()
55 # since with use_datetime set to 1 the unmarshaller would create
56 # datetime objects for the 'datetime[123]' keys as well
Fred Drakeba613c32005-02-10 18:33:30 +000057 dt = datetime.datetime(2005, 02, 10, 11, 41, 23)
58 s = xmlrpclib.dumps((dt,))
Skip Montanaro174dd222005-05-14 20:54:16 +000059 (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
Ezio Melotti2623a372010-11-21 13:34:58 +000060 self.assertEqual(newdt, dt)
61 self.assertEqual(m, None)
Fred Drakeba613c32005-02-10 18:33:30 +000062
Skip Montanaro174dd222005-05-14 20:54:16 +000063 (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
Ezio Melotti2623a372010-11-21 13:34:58 +000064 self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
Skip Montanaro174dd222005-05-14 20:54:16 +000065
Skip Montanarob131f042008-04-18 20:35:46 +000066 def test_datetime_before_1900(self):
Andrew M. Kuchlinga5489d42008-04-21 01:45:57 +000067 # same as before but with a date before 1900
Skip Montanarob131f042008-04-18 20:35:46 +000068 dt = datetime.datetime(1, 02, 10, 11, 41, 23)
69 s = xmlrpclib.dumps((dt,))
70 (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
Ezio Melotti2623a372010-11-21 13:34:58 +000071 self.assertEqual(newdt, dt)
72 self.assertEqual(m, None)
Skip Montanarob131f042008-04-18 20:35:46 +000073
74 (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
Ezio Melotti2623a372010-11-21 13:34:58 +000075 self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23'))
Skip Montanarob131f042008-04-18 20:35:46 +000076
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000077 def test_cmp_datetime_DateTime(self):
78 now = datetime.datetime.now()
79 dt = xmlrpclib.DateTime(now.timetuple())
Benjamin Peterson5c8da862009-06-30 22:57:08 +000080 self.assertTrue(dt == now)
81 self.assertTrue(now == dt)
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000082 then = now + datetime.timedelta(seconds=4)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(then >= dt)
84 self.assertTrue(dt < then)
Skip Montanaro174dd222005-05-14 20:54:16 +000085
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000086 def test_bug_1164912 (self):
87 d = xmlrpclib.DateTime()
Tim Peters536cf992005-12-25 23:18:31 +000088 ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000089 methodresponse=True))
Ezio Melottib0f5adc2010-01-24 16:58:36 +000090 self.assertIsInstance(new_d.value, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000091
92 # Check that the output of dumps() is still an 8-bit string
93 s = xmlrpclib.dumps((new_d,), methodresponse=True)
Ezio Melottib0f5adc2010-01-24 16:58:36 +000094 self.assertIsInstance(s, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000095
Martin v. Löwis07529352006-11-19 18:51:54 +000096 def test_newstyle_class(self):
97 class T(object):
98 pass
99 t = T()
100 t.x = 100
101 t.y = "Hello"
102 ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
Ezio Melotti2623a372010-11-21 13:34:58 +0000103 self.assertEqual(t2, t.__dict__)
Martin v. Löwis07529352006-11-19 18:51:54 +0000104
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000105 def test_dump_big_long(self):
106 self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,))
107
108 def test_dump_bad_dict(self):
109 self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))
110
Facundo Batista5a3b5242007-07-13 10:43:44 +0000111 def test_dump_recursive_seq(self):
112 l = [1,2,3]
113 t = [3,4,5,l]
114 l.append(t)
115 self.assertRaises(TypeError, xmlrpclib.dumps, (l,))
116
117 def test_dump_recursive_dict(self):
118 d = {'1':1, '2':1}
119 t = {'3':3, 'd':d}
120 d['t'] = t
121 self.assertRaises(TypeError, xmlrpclib.dumps, (d,))
122
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000123 def test_dump_big_int(self):
124 if sys.maxint > 2L**31-1:
125 self.assertRaises(OverflowError, xmlrpclib.dumps,
126 (int(2L**34),))
127
Facundo Batista5a3b5242007-07-13 10:43:44 +0000128 xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
129 self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,))
130 self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,))
131
132 def dummy_write(s):
133 pass
134
135 m = xmlrpclib.Marshaller()
136 m.dump_int(xmlrpclib.MAXINT, dummy_write)
137 m.dump_int(xmlrpclib.MININT, dummy_write)
138 self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write)
139 self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write)
140
141
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000142 def test_dump_none(self):
143 value = alist + [None]
144 arg1 = (alist + [None],)
145 strg = xmlrpclib.dumps(arg1, allow_none=True)
Ezio Melotti2623a372010-11-21 13:34:58 +0000146 self.assertEqual(value,
147 xmlrpclib.loads(strg)[0][0])
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000148 self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
149
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200150 @test_support.requires_unicode
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200151 def test_dump_encoding(self):
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200152 value = {test_support.u(r'key\u20ac\xa4'):
153 test_support.u(r'value\u20ac\xa4')}
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200154 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15')
155 strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg
156 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
157
158 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
159 methodresponse=True)
160 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
161
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200162 methodname = test_support.u(r'method\u20ac\xa4')
163 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
164 methodname=methodname)
165 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
166 self.assertEqual(xmlrpclib.loads(strg)[1], methodname)
167
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200168 @test_support.requires_unicode
Fred Drake22c07062005-02-11 17:59:08 +0000169 def test_default_encoding_issues(self):
170 # SF bug #1115989: wrong decoding in '_stringify'
171 utf8 = """<?xml version='1.0' encoding='iso-8859-1'?>
172 <params>
173 <param><value>
174 <string>abc \x95</string>
175 </value></param>
176 <param><value>
177 <struct>
178 <member>
179 <name>def \x96</name>
180 <value><string>ghi \x97</string></value>
181 </member>
182 </struct>
183 </value></param>
184 </params>
185 """
Tim Petersf754f5f2005-04-08 18:00:59 +0000186
187 # sys.setdefaultencoding() normally doesn't exist after site.py is
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000188 # loaded. Import a temporary fresh copy to get access to it
189 # but then restore the original copy to avoid messing with
190 # other potentially modified sys module attributes
Fred Drake22c07062005-02-11 17:59:08 +0000191 old_encoding = sys.getdefaultencoding()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000192 with test_support.CleanImport('sys'):
193 import sys as temp_sys
194 temp_sys.setdefaultencoding("iso-8859-1")
195 try:
196 (s, d), m = xmlrpclib.loads(utf8)
197 finally:
198 temp_sys.setdefaultencoding(old_encoding)
Tim Petersf754f5f2005-04-08 18:00:59 +0000199
Fred Drake22c07062005-02-11 17:59:08 +0000200 items = d.items()
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200201 if test_support.have_unicode:
Ezio Melotti2623a372010-11-21 13:34:58 +0000202 self.assertEqual(s, u"abc \x95")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000203 self.assertIsInstance(s, unicode)
Ezio Melotti2623a372010-11-21 13:34:58 +0000204 self.assertEqual(items, [(u"def \x96", u"ghi \x97")])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000205 self.assertIsInstance(items[0][0], unicode)
206 self.assertIsInstance(items[0][1], unicode)
Fred Drake22c07062005-02-11 17:59:08 +0000207 else:
Ezio Melotti2623a372010-11-21 13:34:58 +0000208 self.assertEqual(s, "abc \xc2\x95")
209 self.assertEqual(items, [("def \xc2\x96", "ghi \xc2\x97")])
Fred Drake22c07062005-02-11 17:59:08 +0000210
Serhiy Storchaka073418a2016-05-04 11:28:09 +0300211 def test_loads_unsupported(self):
212 ResponseError = xmlrpclib.ResponseError
213 data = '<params><param><value><spam/></value></param></params>'
214 self.assertRaises(ResponseError, xmlrpclib.loads, data)
215 data = ('<params><param><value><array>'
216 '<value><spam/></value>'
217 '</array></value></param></params>')
218 self.assertRaises(ResponseError, xmlrpclib.loads, data)
219 data = ('<params><param><value><struct>'
220 '<member><name>a</name><value><spam/></value></member>'
221 '<member><name>b</name><value><spam/></value></member>'
222 '</struct></value></param></params>')
223 self.assertRaises(ResponseError, xmlrpclib.loads, data)
224
Facundo Batista5a3b5242007-07-13 10:43:44 +0000225
226class HelperTestCase(unittest.TestCase):
227 def test_escape(self):
228 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
229 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
230 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
231
232class FaultTestCase(unittest.TestCase):
233 def test_repr(self):
234 f = xmlrpclib.Fault(42, 'Test Fault')
235 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
236 self.assertEqual(repr(f), str(f))
237
238 def test_dump_fault(self):
239 f = xmlrpclib.Fault(42, 'Test Fault')
240 s = xmlrpclib.dumps((f,))
241 (newf,), m = xmlrpclib.loads(s)
Ezio Melotti2623a372010-11-21 13:34:58 +0000242 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
243 self.assertEqual(m, None)
Facundo Batista5a3b5242007-07-13 10:43:44 +0000244
245 s = xmlrpclib.Marshaller().dumps(f)
246 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
247
248
249class DateTimeTestCase(unittest.TestCase):
250 def test_default(self):
251 t = xmlrpclib.DateTime()
252
253 def test_time(self):
254 d = 1181399930.036952
255 t = xmlrpclib.DateTime(d)
256 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
257
258 def test_time_tuple(self):
259 d = (2007,6,9,10,38,50,5,160,0)
260 t = xmlrpclib.DateTime(d)
261 self.assertEqual(str(t), '20070609T10:38:50')
262
263 def test_time_struct(self):
264 d = time.localtime(1181399930.036952)
265 t = xmlrpclib.DateTime(d)
266 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
267
268 def test_datetime_datetime(self):
269 d = datetime.datetime(2007,1,2,3,4,5)
270 t = xmlrpclib.DateTime(d)
271 self.assertEqual(str(t), '20070102T03:04:05')
272
Facundo Batista5a3b5242007-07-13 10:43:44 +0000273 def test_repr(self):
274 d = datetime.datetime(2007,1,2,3,4,5)
275 t = xmlrpclib.DateTime(d)
276 val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
277 self.assertEqual(repr(t), val)
278
279 def test_decode(self):
280 d = ' 20070908T07:11:13 '
281 t1 = xmlrpclib.DateTime()
282 t1.decode(d)
283 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
284 self.assertEqual(t1, tref)
285
286 t2 = xmlrpclib._datetime(d)
287 self.assertEqual(t1, tref)
288
289class BinaryTestCase(unittest.TestCase):
290 def test_default(self):
291 t = xmlrpclib.Binary()
292 self.assertEqual(str(t), '')
293
294 def test_string(self):
295 d = '\x01\x02\x03abc123\xff\xfe'
296 t = xmlrpclib.Binary(d)
297 self.assertEqual(str(t), d)
298
299 def test_decode(self):
300 d = '\x01\x02\x03abc123\xff\xfe'
301 de = base64.encodestring(d)
302 t1 = xmlrpclib.Binary()
303 t1.decode(de)
304 self.assertEqual(str(t1), d)
305
306 t2 = xmlrpclib._binary(de)
307 self.assertEqual(str(t2), d)
308
309
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000310ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000311
Neal Norwitz653272f2008-01-26 07:26:12 +0000312# The evt is set twice. First when the server is ready to serve.
313# Second when the server has been shutdown. The user must clear
314# the event after it has been set the first time to catch the second set.
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200315def http_server(evt, numrequests, requestHandler=None, encoding=None):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000316 class TestInstanceClass:
317 def div(self, x, y):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000318 return x // y
319
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000320 def _methodHelp(self, name):
321 if name == 'div':
322 return 'This is the div function'
323
324 def my_function():
325 '''This is my function'''
326 return True
327
Neal Norwitz70cea582008-03-28 06:34:03 +0000328 class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
329 def get_request(self):
330 # Ensure the socket is always non-blocking. On Linux, socket
331 # attributes are not inherited like they are on *BSD and Windows.
332 s, port = self.socket.accept()
333 s.setblocking(True)
334 return s, port
335
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000336 if not requestHandler:
337 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
338 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200339 encoding=encoding,
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000340 logRequests=False, bind_and_activate=False)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000341 try:
342 serv.socket.settimeout(3)
343 serv.server_bind()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000344 global ADDR, PORT, URL
345 ADDR, PORT = serv.socket.getsockname()
346 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300347 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000348 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
349 #on AF_INET only.
350 URL = "http://%s:%d"%(ADDR, PORT)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000351 serv.server_activate()
352 serv.register_introspection_functions()
353 serv.register_multicall_functions()
354 serv.register_function(pow)
355 serv.register_function(lambda x,y: x+y, 'add')
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200356 serv.register_function(lambda x: x, test_support.u(r't\xea\u0161t'))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000357 serv.register_function(my_function)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000358 serv.register_instance(TestInstanceClass())
Neal Norwitz653272f2008-01-26 07:26:12 +0000359 evt.set()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000360
361 # handle up to 'numrequests' requests
362 while numrequests > 0:
363 serv.handle_request()
364 numrequests -= 1
365
366 except socket.timeout:
367 pass
368 finally:
369 serv.socket.close()
370 PORT = None
371 evt.set()
372
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000373def http_multi_server(evt, numrequests, requestHandler=None):
374 class TestInstanceClass:
375 def div(self, x, y):
376 return x // y
377
378 def _methodHelp(self, name):
379 if name == 'div':
380 return 'This is the div function'
381
382 def my_function():
383 '''This is my function'''
384 return True
385
386 class MyXMLRPCServer(SimpleXMLRPCServer.MultiPathXMLRPCServer):
387 def get_request(self):
388 # Ensure the socket is always non-blocking. On Linux, socket
389 # attributes are not inherited like they are on *BSD and Windows.
390 s, port = self.socket.accept()
391 s.setblocking(True)
392 return s, port
393
394 if not requestHandler:
395 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
396 class MyRequestHandler(requestHandler):
397 rpc_paths = []
398
399 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
400 logRequests=False, bind_and_activate=False)
401 serv.socket.settimeout(3)
402 serv.server_bind()
403 try:
404 global ADDR, PORT, URL
405 ADDR, PORT = serv.socket.getsockname()
406 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300407 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000408 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
409 #on AF_INET only.
410 URL = "http://%s:%d"%(ADDR, PORT)
411 serv.server_activate()
412 paths = ["/foo", "/foo/bar"]
413 for path in paths:
414 d = serv.add_dispatcher(path, SimpleXMLRPCServer.SimpleXMLRPCDispatcher())
415 d.register_introspection_functions()
416 d.register_multicall_functions()
417 serv.get_dispatcher(paths[0]).register_function(pow)
418 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
419 evt.set()
420
421 # handle up to 'numrequests' requests
422 while numrequests > 0:
423 serv.handle_request()
424 numrequests -= 1
425
426 except socket.timeout:
427 pass
428 finally:
429 serv.socket.close()
430 PORT = None
431 evt.set()
432
Neal Norwitz08b50eb2008-01-26 08:26:00 +0000433# This function prevents errors like:
434# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000435def is_unavailable_exception(e):
436 '''Returns True if the given ProtocolError is the product of a server-side
437 exception caused by the 'temporarily unavailable' response sometimes
438 given by operations on non-blocking sockets.'''
Neal Norwitz653272f2008-01-26 07:26:12 +0000439
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000440 # sometimes we get a -1 error code and/or empty headers
Neal Norwitzed444e52008-01-27 18:19:04 +0000441 try:
442 if e.errcode == -1 or e.headers is None:
443 return True
444 exc_mess = e.headers.get('X-exception')
445 except AttributeError:
446 # Ignore socket.errors here.
447 exc_mess = str(e)
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000448
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000449 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
450 return True
451
452 return False
453
Victor Stinnera44b5a32010-04-27 23:14:58 +0000454@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000455class BaseServerTestCase(unittest.TestCase):
456 requestHandler = None
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000457 request_count = 1
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000458 threadFunc = staticmethod(http_server)
Victor Stinnera44b5a32010-04-27 23:14:58 +0000459
Facundo Batistaa53872b2007-08-14 13:35:00 +0000460 def setUp(self):
Facundo Batista7f686fc2007-08-17 19:16:44 +0000461 # enable traceback reporting
462 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
463
Facundo Batistaa53872b2007-08-14 13:35:00 +0000464 self.evt = threading.Event()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000465 # start server thread to handle requests
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000466 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000467 threading.Thread(target=self.threadFunc, args=serv_args).start()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000468
Neal Norwitz653272f2008-01-26 07:26:12 +0000469 # wait for the server to be ready
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000470 self.evt.wait(10)
Neal Norwitz653272f2008-01-26 07:26:12 +0000471 self.evt.clear()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000472
473 def tearDown(self):
474 # wait on the server thread to terminate
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000475 self.evt.wait(10)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000476
Facundo Batista7f686fc2007-08-17 19:16:44 +0000477 # disable traceback reporting
478 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
479
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000480# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
481# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
482# condition occurs infrequently on some platforms, frequently on others, and
483# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket
484# If the server class is updated at some point in the future to handle this
485# situation more gracefully, these tests should be modified appropriately.
486
487class SimpleServerTestCase(BaseServerTestCase):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000488 def test_simple1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000489 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000490 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000491 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000492 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000493 # ignore failures due to non-blocking socket 'unavailable' errors
494 if not is_unavailable_exception(e):
495 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000496 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000497
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200498 @test_support.requires_unicode
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000499 def test_nonascii(self):
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200500 start_string = test_support.u(r'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t')
501 end_string = test_support.u(r'h\N{LATIN SMALL LETTER O WITH HORN}n')
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000502
503 try:
504 p = xmlrpclib.ServerProxy(URL)
505 self.assertEqual(p.add(start_string, end_string),
506 start_string + end_string)
507 except (xmlrpclib.ProtocolError, socket.error) as e:
508 # ignore failures due to non-blocking socket unavailable errors.
509 if not is_unavailable_exception(e):
510 # protocol error; provide additional information in test output
511 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
512
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200513 @test_support.requires_unicode
Victor Stinner51b71982011-09-23 01:15:32 +0200514 def test_unicode_host(self):
515 server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
516 self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000517
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200518 @test_support.requires_unicode
519 def test_client_encoding(self):
520 start_string = unichr(0x20ac)
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200521 end_string = unichr(0xa4)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200522
523 try:
524 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
525 self.assertEqual(p.add(start_string, end_string),
526 start_string + end_string)
527 except (xmlrpclib.ProtocolError, socket.error) as e:
528 # ignore failures due to non-blocking socket unavailable errors.
529 if not is_unavailable_exception(e):
530 # protocol error; provide additional information in test output
531 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
532
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200533 @test_support.requires_unicode
534 def test_nonascii_methodname(self):
535 try:
536 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
537 m = getattr(p, 't\xea\xa8t')
538 self.assertEqual(m(42), 42)
539 except (xmlrpclib.ProtocolError, socket.error) as e:
540 # ignore failures due to non-blocking socket unavailable errors.
541 if not is_unavailable_exception(e):
542 # protocol error; provide additional information in test output
543 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
544
Christian Heimes6c29be52008-01-19 16:39:27 +0000545 # [ch] The test 404 is causing lots of false alarms.
546 def XXXtest_404(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000547 # send POST with httplib, it should return 404 header and
548 # 'Not Found' message.
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000549 conn = httplib.HTTPConnection(ADDR, PORT)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000550 conn.request('POST', '/this-is-not-valid')
551 response = conn.getresponse()
552 conn.close()
553
554 self.assertEqual(response.status, 404)
555 self.assertEqual(response.reason, 'Not Found')
556
Facundo Batistaa53872b2007-08-14 13:35:00 +0000557 def test_introspection1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000558 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000559 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000560 meth = p.system.listMethods()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000561 expected_methods = set(['pow', 'div', 'my_function', 'add',
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200562 test_support.u(r't\xea\u0161t'),
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000563 'system.listMethods', 'system.methodHelp',
564 'system.methodSignature', 'system.multicall'])
Facundo Batistac65a5f12007-08-21 00:16:21 +0000565 self.assertEqual(set(meth), expected_methods)
Neal Norwitz183c5342008-01-27 17:11:11 +0000566 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000567 # ignore failures due to non-blocking socket 'unavailable' errors
568 if not is_unavailable_exception(e):
569 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000570 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000571
572 def test_introspection2(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000573 try:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000574 # test _methodHelp()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000575 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000576 divhelp = p.system.methodHelp('div')
577 self.assertEqual(divhelp, 'This is the div function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000578 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000579 # ignore failures due to non-blocking socket 'unavailable' errors
580 if not is_unavailable_exception(e):
581 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000582 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000583
R. David Murrayf28fd242010-02-23 00:24:49 +0000584 @unittest.skipIf(sys.flags.optimize >= 2,
585 "Docstrings are omitted with -O2 and above")
Facundo Batistaa53872b2007-08-14 13:35:00 +0000586 def test_introspection3(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000587 try:
588 # test native doc
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000589 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000590 myfunction = p.system.methodHelp('my_function')
591 self.assertEqual(myfunction, 'This is my function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000592 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000593 # ignore failures due to non-blocking socket 'unavailable' errors
594 if not is_unavailable_exception(e):
595 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000596 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000597
598 def test_introspection4(self):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000599 # the SimpleXMLRPCServer doesn't support signatures, but
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000600 # at least check that we can try making the call
Facundo Batistac65a5f12007-08-21 00:16:21 +0000601 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000602 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000603 divsig = p.system.methodSignature('div')
604 self.assertEqual(divsig, 'signatures not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000605 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000606 # ignore failures due to non-blocking socket 'unavailable' errors
607 if not is_unavailable_exception(e):
608 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000609 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000610
611 def test_multicall(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000612 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000613 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000614 multicall = xmlrpclib.MultiCall(p)
615 multicall.add(2,3)
616 multicall.pow(6,8)
617 multicall.div(127,42)
618 add_result, pow_result, div_result = multicall()
619 self.assertEqual(add_result, 2+3)
620 self.assertEqual(pow_result, 6**8)
621 self.assertEqual(div_result, 127//42)
Neal Norwitz183c5342008-01-27 17:11:11 +0000622 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000623 # ignore failures due to non-blocking socket 'unavailable' errors
624 if not is_unavailable_exception(e):
625 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000626 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000627
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000628 def test_non_existing_multicall(self):
629 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000630 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000631 multicall = xmlrpclib.MultiCall(p)
632 multicall.this_is_not_exists()
633 result = multicall()
634
635 # result.results contains;
636 # [{'faultCode': 1, 'faultString': '<type \'exceptions.Exception\'>:'
637 # 'method "this_is_not_exists" is not supported'>}]
638
639 self.assertEqual(result.results[0]['faultCode'], 1)
640 self.assertEqual(result.results[0]['faultString'],
641 '<type \'exceptions.Exception\'>:method "this_is_not_exists" '
642 'is not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000643 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000644 # ignore failures due to non-blocking socket 'unavailable' errors
645 if not is_unavailable_exception(e):
646 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000647 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000648
649 def test_dotted_attribute(self):
Neal Norwitz162d7192008-03-23 04:08:30 +0000650 # Raises an AttributeError because private methods are not allowed.
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000651 self.assertRaises(AttributeError,
652 SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')
653
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000654 self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
Neal Norwitz162d7192008-03-23 04:08:30 +0000655 # Get the test to run faster by sending a request with test_simple1.
656 # This avoids waiting for the socket timeout.
657 self.test_simple1()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000658
Charles-François Natalie0624662012-02-18 14:30:34 +0100659 def test_partial_post(self):
660 # Check that a partial POST doesn't make the server loop: issue #14001.
661 conn = httplib.HTTPConnection(ADDR, PORT)
662 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
663 conn.close()
664
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200665class SimpleServerEncodingTestCase(BaseServerTestCase):
666 @staticmethod
667 def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
668 http_server(evt, numrequests, requestHandler, 'iso-8859-15')
669
670 @test_support.requires_unicode
671 def test_server_encoding(self):
672 start_string = unichr(0x20ac)
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200673 end_string = unichr(0xa4)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200674
675 try:
676 p = xmlrpclib.ServerProxy(URL)
677 self.assertEqual(p.add(start_string, end_string),
678 start_string + end_string)
679 except (xmlrpclib.ProtocolError, socket.error) as e:
680 # ignore failures due to non-blocking socket unavailable errors.
681 if not is_unavailable_exception(e):
682 # protocol error; provide additional information in test output
683 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
684
685
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000686class MultiPathServerTestCase(BaseServerTestCase):
687 threadFunc = staticmethod(http_multi_server)
688 request_count = 2
689 def test_path1(self):
690 p = xmlrpclib.ServerProxy(URL+"/foo")
691 self.assertEqual(p.pow(6,8), 6**8)
692 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
693 def test_path2(self):
694 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
695 self.assertEqual(p.add(6,8), 6+8)
696 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
697
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000698#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
699#does indeed serve subsequent requests on the same connection
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000700class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000701 #a request handler that supports keep-alive and logs requests into a
702 #class variable
703 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
704 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
705 protocol_version = 'HTTP/1.1'
706 myRequests = []
707 def handle(self):
708 self.myRequests.append([])
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000709 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000710 return self.parentClass.handle(self)
711 def handle_one_request(self):
712 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000713 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000714 return result
715
716 requestHandler = RequestHandler
717 def setUp(self):
718 #clear request log
719 self.RequestHandler.myRequests = []
720 return BaseServerTestCase.setUp(self)
721
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000722#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
723#does indeed serve subsequent requests on the same connection
724class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000725 def test_two(self):
726 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000727 #do three requests.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000728 self.assertEqual(p.pow(6,8), 6**8)
729 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000730 self.assertEqual(p.pow(6,8), 6**8)
731
732 #they should have all been handled by a single request handler
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000733 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000734
735 #check that we did at least two (the third may be pending append
736 #due to thread scheduling)
737 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000738
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000739#test special attribute access on the serverproxy, through the __call__
740#function.
741class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
742 #ask for two keepalive requests to be handled.
743 request_count=2
744
745 def test_close(self):
746 p = xmlrpclib.ServerProxy(URL)
747 #do some requests with close.
748 self.assertEqual(p.pow(6,8), 6**8)
749 self.assertEqual(p.pow(6,8), 6**8)
750 self.assertEqual(p.pow(6,8), 6**8)
751 p("close")() #this should trigger a new keep-alive request
752 self.assertEqual(p.pow(6,8), 6**8)
753 self.assertEqual(p.pow(6,8), 6**8)
754 self.assertEqual(p.pow(6,8), 6**8)
755
756 #they should have all been two request handlers, each having logged at least
757 #two complete requests
758 self.assertEqual(len(self.RequestHandler.myRequests), 2)
759 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
760 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
761
762 def test_transport(self):
763 p = xmlrpclib.ServerProxy(URL)
764 #do some requests with close.
765 self.assertEqual(p.pow(6,8), 6**8)
766 p("transport").close() #same as above, really.
767 self.assertEqual(p.pow(6,8), 6**8)
768 self.assertEqual(len(self.RequestHandler.myRequests), 2)
769
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000770#A test case that verifies that gzip encoding works in both directions
771#(for a request and the response)
Zachary Ware1f702212013-12-10 14:09:20 -0600772@unittest.skipUnless(gzip, 'gzip not available')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000773class GzipServerTestCase(BaseServerTestCase):
774 #a request handler that supports keep-alive and logs requests into a
775 #class variable
776 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
777 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
778 protocol_version = 'HTTP/1.1'
779
780 def do_POST(self):
781 #store content of last request in class
782 self.__class__.content_length = int(self.headers["content-length"])
783 return self.parentClass.do_POST(self)
784 requestHandler = RequestHandler
785
786 class Transport(xmlrpclib.Transport):
787 #custom transport, stores the response length for our perusal
788 fake_gzip = False
789 def parse_response(self, response):
790 self.response_length=int(response.getheader("content-length", 0))
791 return xmlrpclib.Transport.parse_response(self, response)
792
793 def send_content(self, connection, body):
794 if self.fake_gzip:
795 #add a lone gzip header to induce decode error remotely
796 connection.putheader("Content-Encoding", "gzip")
797 return xmlrpclib.Transport.send_content(self, connection, body)
798
Victor Stinnera44b5a32010-04-27 23:14:58 +0000799 def setUp(self):
800 BaseServerTestCase.setUp(self)
801
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000802 def test_gzip_request(self):
803 t = self.Transport()
804 t.encode_threshold = None
805 p = xmlrpclib.ServerProxy(URL, transport=t)
806 self.assertEqual(p.pow(6,8), 6**8)
807 a = self.RequestHandler.content_length
808 t.encode_threshold = 0 #turn on request encoding
809 self.assertEqual(p.pow(6,8), 6**8)
810 b = self.RequestHandler.content_length
811 self.assertTrue(a>b)
812
813 def test_bad_gzip_request(self):
814 t = self.Transport()
815 t.encode_threshold = None
816 t.fake_gzip = True
817 p = xmlrpclib.ServerProxy(URL, transport=t)
818 cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
819 re.compile(r"\b400\b"))
820 with cm:
821 p.pow(6, 8)
822
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500823 def test_gzip_response(self):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000824 t = self.Transport()
825 p = xmlrpclib.ServerProxy(URL, transport=t)
826 old = self.requestHandler.encode_threshold
827 self.requestHandler.encode_threshold = None #no encoding
828 self.assertEqual(p.pow(6,8), 6**8)
829 a = t.response_length
830 self.requestHandler.encode_threshold = 0 #always encode
831 self.assertEqual(p.pow(6,8), 6**8)
832 b = t.response_length
833 self.requestHandler.encode_threshold = old
834 self.assertTrue(a>b)
835
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500836 def test_gzip_decode_limit(self):
837 max_gzip_decode = 20 * 1024 * 1024
838 data = '\0' * max_gzip_decode
839 encoded = xmlrpclib.gzip_encode(data)
840 decoded = xmlrpclib.gzip_decode(encoded)
841 self.assertEqual(len(decoded), max_gzip_decode)
842
843 data = '\0' * (max_gzip_decode + 1)
844 encoded = xmlrpclib.gzip_encode(data)
845
846 with self.assertRaisesRegexp(ValueError,
847 "max gzipped payload length exceeded"):
848 xmlrpclib.gzip_decode(encoded)
849
850 xmlrpclib.gzip_decode(encoded, max_decode=-1)
851
852
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000853#Test special attributes of the ServerProxy object
854class ServerProxyTestCase(unittest.TestCase):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000855 def setUp(self):
856 unittest.TestCase.setUp(self)
857 if threading:
858 self.url = URL
859 else:
860 # Without threading, http_server() and http_multi_server() will not
861 # be executed and URL is still equal to None. 'http://' is a just
862 # enough to choose the scheme (HTTP)
863 self.url = 'http://'
864
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000865 def test_close(self):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000866 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000867 self.assertEqual(p('close')(), None)
868
869 def test_transport(self):
870 t = xmlrpclib.Transport()
Victor Stinnera44b5a32010-04-27 23:14:58 +0000871 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000872 self.assertEqual(p('transport'), t)
873
Facundo Batista7f686fc2007-08-17 19:16:44 +0000874# This is a contrived way to make a failure occur on the server side
875# in order to test the _send_traceback_header flag on the server
876class FailingMessageClass(mimetools.Message):
877 def __getitem__(self, key):
878 key = key.lower()
879 if key == 'content-length':
880 return 'I am broken'
881 return mimetools.Message.__getitem__(self, key)
882
883
Victor Stinnera44b5a32010-04-27 23:14:58 +0000884@unittest.skipUnless(threading, 'Threading required for this test.')
Facundo Batista7f686fc2007-08-17 19:16:44 +0000885class FailingServerTestCase(unittest.TestCase):
886 def setUp(self):
887 self.evt = threading.Event()
888 # start server thread to handle requests
Neal Norwitz162d7192008-03-23 04:08:30 +0000889 serv_args = (self.evt, 1)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000890 threading.Thread(target=http_server, args=serv_args).start()
891
Neal Norwitz653272f2008-01-26 07:26:12 +0000892 # wait for the server to be ready
893 self.evt.wait()
894 self.evt.clear()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000895
896 def tearDown(self):
897 # wait on the server thread to terminate
898 self.evt.wait()
899 # reset flag
900 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
901 # reset message class
902 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message
903
904 def test_basic(self):
905 # check that flag is false by default
906 flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
907 self.assertEqual(flagval, False)
908
Facundo Batistac65a5f12007-08-21 00:16:21 +0000909 # enable traceback reporting
910 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
911
912 # test a call that shouldn't fail just as a smoke test
913 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000914 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000915 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000916 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000917 # ignore failures due to non-blocking socket 'unavailable' errors
918 if not is_unavailable_exception(e):
919 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000920 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batista7f686fc2007-08-17 19:16:44 +0000921
922 def test_fail_no_info(self):
923 # use the broken message class
924 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
925
926 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000927 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000928 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000929 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000930 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000931 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000932 # The two server-side error headers shouldn't be sent back in this case
933 self.assertTrue(e.headers.get("X-exception") is None)
934 self.assertTrue(e.headers.get("X-traceback") is None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000935 else:
936 self.fail('ProtocolError not raised')
937
938 def test_fail_with_info(self):
939 # use the broken message class
940 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
941
942 # Check that errors in the server send back exception/traceback
943 # info when flag is set
944 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
945
946 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000947 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000948 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000949 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000950 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000951 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000952 # We should get error info in the response
953 expected_err = "invalid literal for int() with base 10: 'I am broken'"
954 self.assertEqual(e.headers.get("x-exception"), expected_err)
955 self.assertTrue(e.headers.get("x-traceback") is not None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000956 else:
957 self.fail('ProtocolError not raised')
958
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000959class CGIHandlerTestCase(unittest.TestCase):
960 def setUp(self):
961 self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
962
963 def tearDown(self):
964 self.cgi = None
965
966 def test_cgi_get(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000967 with test_support.EnvironmentVarGuard() as env:
Walter Dörwald6733bed2009-05-01 17:35:37 +0000968 env['REQUEST_METHOD'] = 'GET'
Walter Dörwald4b965f62009-04-26 20:51:44 +0000969 # if the method is GET and no request_text is given, it runs handle_get
970 # get sysout output
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000971 with test_support.captured_stdout() as data_out:
972 self.cgi.handle_request()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000973
Walter Dörwald4b965f62009-04-26 20:51:44 +0000974 # parse Status header
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000975 data_out.seek(0)
976 handle = data_out.read()
Walter Dörwald4b965f62009-04-26 20:51:44 +0000977 status = handle.split()[1]
978 message = ' '.join(handle.split()[2:4])
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000979
Walter Dörwald4b965f62009-04-26 20:51:44 +0000980 self.assertEqual(status, '400')
981 self.assertEqual(message, 'Bad Request')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000982
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000983
984 def test_cgi_xmlrpc_response(self):
985 data = """<?xml version='1.0'?>
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000986 <methodCall>
987 <methodName>test_method</methodName>
988 <params>
989 <param>
990 <value><string>foo</string></value>
991 </param>
992 <param>
993 <value><string>bar</string></value>
994 </param>
995 </params>
996 </methodCall>
997 """
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000998
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000999 with test_support.EnvironmentVarGuard() as env, \
1000 test_support.captured_stdout() as data_out, \
1001 test_support.captured_stdin() as data_in:
1002 data_in.write(data)
1003 data_in.seek(0)
Walter Dörwald6733bed2009-05-01 17:35:37 +00001004 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandl61fce382009-04-01 15:23:43 +00001005 self.cgi.handle_request()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +00001006 data_out.seek(0)
Georg Brandl5d1b4d42007-12-07 09:07:10 +00001007
1008 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +00001009 handle = data_out.read()
Georg Brandl5d1b4d42007-12-07 09:07:10 +00001010
1011 # start with 44th char so as not to get http header, we just need only xml
1012 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
1013
Senthil Kumaran20d114c2009-04-01 20:26:33 +00001014 # Also test the content-length returned by handle_request
1015 # Using the same test method inorder to avoid all the datapassing
1016 # boilerplate code.
1017 # Test for bug: http://bugs.python.org/issue5040
1018
1019 content = handle[handle.find("<?xml"):]
1020
Ezio Melotti2623a372010-11-21 13:34:58 +00001021 self.assertEqual(
Senthil Kumaran20d114c2009-04-01 20:26:33 +00001022 int(re.search('Content-Length: (\d+)', handle).group(1)),
1023 len(content))
1024
1025
Jeremy Hylton89420112008-11-24 22:00:29 +00001026class FakeSocket:
1027
1028 def __init__(self):
1029 self.data = StringIO.StringIO()
1030
1031 def send(self, buf):
1032 self.data.write(buf)
1033 return len(buf)
1034
1035 def sendall(self, buf):
1036 self.data.write(buf)
1037
1038 def getvalue(self):
1039 return self.data.getvalue()
1040
Kristján Valur Jónsson3c43fcb2009-01-11 16:23:37 +00001041 def makefile(self, x='r', y=-1):
Jeremy Hylton89420112008-11-24 22:00:29 +00001042 raise RuntimeError
1043
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001044 def close(self):
1045 pass
1046
Jeremy Hylton89420112008-11-24 22:00:29 +00001047class FakeTransport(xmlrpclib.Transport):
1048 """A Transport instance that records instead of sending a request.
1049
1050 This class replaces the actual socket used by httplib with a
1051 FakeSocket object that records the request. It doesn't provide a
1052 response.
1053 """
1054
1055 def make_connection(self, host):
1056 conn = xmlrpclib.Transport.make_connection(self, host)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001057 conn.sock = self.fake_socket = FakeSocket()
Jeremy Hylton89420112008-11-24 22:00:29 +00001058 return conn
1059
1060class TransportSubclassTestCase(unittest.TestCase):
1061
1062 def issue_request(self, transport_class):
1063 """Return an HTTP request made via transport_class."""
1064 transport = transport_class()
1065 proxy = xmlrpclib.ServerProxy("http://example.com/",
1066 transport=transport)
1067 try:
1068 proxy.pow(6, 8)
1069 except RuntimeError:
1070 return transport.fake_socket.getvalue()
1071 return None
1072
1073 def test_custom_user_agent(self):
1074 class TestTransport(FakeTransport):
1075
1076 def send_user_agent(self, conn):
1077 xmlrpclib.Transport.send_user_agent(self, conn)
1078 conn.putheader("X-Test", "test_custom_user_agent")
1079
1080 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001081 self.assertIn("X-Test: test_custom_user_agent\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001082
1083 def test_send_host(self):
1084 class TestTransport(FakeTransport):
1085
1086 def send_host(self, conn, host):
1087 xmlrpclib.Transport.send_host(self, conn, host)
1088 conn.putheader("X-Test", "test_send_host")
1089
1090 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001091 self.assertIn("X-Test: test_send_host\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001092
1093 def test_send_request(self):
1094 class TestTransport(FakeTransport):
1095
1096 def send_request(self, conn, url, body):
1097 xmlrpclib.Transport.send_request(self, conn, url, body)
1098 conn.putheader("X-Test", "test_send_request")
1099
1100 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001101 self.assertIn("X-Test: test_send_request\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001102
1103 def test_send_content(self):
1104 class TestTransport(FakeTransport):
1105
1106 def send_content(self, conn, body):
1107 conn.putheader("X-Test", "test_send_content")
1108 xmlrpclib.Transport.send_content(self, conn, body)
1109
1110 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001111 self.assertIn("X-Test: test_send_content\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001112
Antoine Pitrou3c968582009-10-30 17:56:00 +00001113@test_support.reap_threads
Facundo Batistaa53872b2007-08-14 13:35:00 +00001114def test_main():
1115 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
Jeremy Hylton89420112008-11-24 22:00:29 +00001116 BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001117 xmlrpc_tests.append(SimpleServerTestCase)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +02001118 xmlrpc_tests.append(SimpleServerEncodingTestCase)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +00001119 xmlrpc_tests.append(KeepaliveServerTestCase1)
1120 xmlrpc_tests.append(KeepaliveServerTestCase2)
Zachary Ware1f702212013-12-10 14:09:20 -06001121 xmlrpc_tests.append(GzipServerTestCase)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +00001122 xmlrpc_tests.append(MultiPathServerTestCase)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001123 xmlrpc_tests.append(ServerProxyTestCase)
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001124 xmlrpc_tests.append(FailingServerTestCase)
1125 xmlrpc_tests.append(CGIHandlerTestCase)
Facundo Batistaa53872b2007-08-14 13:35:00 +00001126
1127 test_support.run_unittest(*xmlrpc_tests)
Skip Montanaro419abda2001-10-01 17:47:44 +00001128
1129if __name__ == "__main__":
1130 test_main()