blob: ca8d5d8cc03e1afc3d88eb60fe84bca3c33e1488 [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
Facundo Batista5a3b5242007-07-13 10:43:44 +0000211
212class HelperTestCase(unittest.TestCase):
213 def test_escape(self):
214 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
215 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
216 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
217
218class FaultTestCase(unittest.TestCase):
219 def test_repr(self):
220 f = xmlrpclib.Fault(42, 'Test Fault')
221 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
222 self.assertEqual(repr(f), str(f))
223
224 def test_dump_fault(self):
225 f = xmlrpclib.Fault(42, 'Test Fault')
226 s = xmlrpclib.dumps((f,))
227 (newf,), m = xmlrpclib.loads(s)
Ezio Melotti2623a372010-11-21 13:34:58 +0000228 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
229 self.assertEqual(m, None)
Facundo Batista5a3b5242007-07-13 10:43:44 +0000230
231 s = xmlrpclib.Marshaller().dumps(f)
232 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
233
234
235class DateTimeTestCase(unittest.TestCase):
236 def test_default(self):
237 t = xmlrpclib.DateTime()
238
239 def test_time(self):
240 d = 1181399930.036952
241 t = xmlrpclib.DateTime(d)
242 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
243
244 def test_time_tuple(self):
245 d = (2007,6,9,10,38,50,5,160,0)
246 t = xmlrpclib.DateTime(d)
247 self.assertEqual(str(t), '20070609T10:38:50')
248
249 def test_time_struct(self):
250 d = time.localtime(1181399930.036952)
251 t = xmlrpclib.DateTime(d)
252 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
253
254 def test_datetime_datetime(self):
255 d = datetime.datetime(2007,1,2,3,4,5)
256 t = xmlrpclib.DateTime(d)
257 self.assertEqual(str(t), '20070102T03:04:05')
258
Facundo Batista5a3b5242007-07-13 10:43:44 +0000259 def test_repr(self):
260 d = datetime.datetime(2007,1,2,3,4,5)
261 t = xmlrpclib.DateTime(d)
262 val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
263 self.assertEqual(repr(t), val)
264
265 def test_decode(self):
266 d = ' 20070908T07:11:13 '
267 t1 = xmlrpclib.DateTime()
268 t1.decode(d)
269 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
270 self.assertEqual(t1, tref)
271
272 t2 = xmlrpclib._datetime(d)
273 self.assertEqual(t1, tref)
274
275class BinaryTestCase(unittest.TestCase):
276 def test_default(self):
277 t = xmlrpclib.Binary()
278 self.assertEqual(str(t), '')
279
280 def test_string(self):
281 d = '\x01\x02\x03abc123\xff\xfe'
282 t = xmlrpclib.Binary(d)
283 self.assertEqual(str(t), d)
284
285 def test_decode(self):
286 d = '\x01\x02\x03abc123\xff\xfe'
287 de = base64.encodestring(d)
288 t1 = xmlrpclib.Binary()
289 t1.decode(de)
290 self.assertEqual(str(t1), d)
291
292 t2 = xmlrpclib._binary(de)
293 self.assertEqual(str(t2), d)
294
295
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000296ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000297
Neal Norwitz653272f2008-01-26 07:26:12 +0000298# The evt is set twice. First when the server is ready to serve.
299# Second when the server has been shutdown. The user must clear
300# the event after it has been set the first time to catch the second set.
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200301def http_server(evt, numrequests, requestHandler=None, encoding=None):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000302 class TestInstanceClass:
303 def div(self, x, y):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000304 return x // y
305
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000306 def _methodHelp(self, name):
307 if name == 'div':
308 return 'This is the div function'
309
310 def my_function():
311 '''This is my function'''
312 return True
313
Neal Norwitz70cea582008-03-28 06:34:03 +0000314 class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
315 def get_request(self):
316 # Ensure the socket is always non-blocking. On Linux, socket
317 # attributes are not inherited like they are on *BSD and Windows.
318 s, port = self.socket.accept()
319 s.setblocking(True)
320 return s, port
321
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000322 if not requestHandler:
323 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
324 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200325 encoding=encoding,
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000326 logRequests=False, bind_and_activate=False)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000327 try:
328 serv.socket.settimeout(3)
329 serv.server_bind()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000330 global ADDR, PORT, URL
331 ADDR, PORT = serv.socket.getsockname()
332 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300333 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000334 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
335 #on AF_INET only.
336 URL = "http://%s:%d"%(ADDR, PORT)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000337 serv.server_activate()
338 serv.register_introspection_functions()
339 serv.register_multicall_functions()
340 serv.register_function(pow)
341 serv.register_function(lambda x,y: x+y, 'add')
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200342 serv.register_function(lambda x: x, test_support.u(r't\xea\u0161t'))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000343 serv.register_function(my_function)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000344 serv.register_instance(TestInstanceClass())
Neal Norwitz653272f2008-01-26 07:26:12 +0000345 evt.set()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000346
347 # handle up to 'numrequests' requests
348 while numrequests > 0:
349 serv.handle_request()
350 numrequests -= 1
351
352 except socket.timeout:
353 pass
354 finally:
355 serv.socket.close()
356 PORT = None
357 evt.set()
358
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000359def http_multi_server(evt, numrequests, requestHandler=None):
360 class TestInstanceClass:
361 def div(self, x, y):
362 return x // y
363
364 def _methodHelp(self, name):
365 if name == 'div':
366 return 'This is the div function'
367
368 def my_function():
369 '''This is my function'''
370 return True
371
372 class MyXMLRPCServer(SimpleXMLRPCServer.MultiPathXMLRPCServer):
373 def get_request(self):
374 # Ensure the socket is always non-blocking. On Linux, socket
375 # attributes are not inherited like they are on *BSD and Windows.
376 s, port = self.socket.accept()
377 s.setblocking(True)
378 return s, port
379
380 if not requestHandler:
381 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
382 class MyRequestHandler(requestHandler):
383 rpc_paths = []
384
385 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
386 logRequests=False, bind_and_activate=False)
387 serv.socket.settimeout(3)
388 serv.server_bind()
389 try:
390 global ADDR, PORT, URL
391 ADDR, PORT = serv.socket.getsockname()
392 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300393 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000394 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
395 #on AF_INET only.
396 URL = "http://%s:%d"%(ADDR, PORT)
397 serv.server_activate()
398 paths = ["/foo", "/foo/bar"]
399 for path in paths:
400 d = serv.add_dispatcher(path, SimpleXMLRPCServer.SimpleXMLRPCDispatcher())
401 d.register_introspection_functions()
402 d.register_multicall_functions()
403 serv.get_dispatcher(paths[0]).register_function(pow)
404 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
405 evt.set()
406
407 # handle up to 'numrequests' requests
408 while numrequests > 0:
409 serv.handle_request()
410 numrequests -= 1
411
412 except socket.timeout:
413 pass
414 finally:
415 serv.socket.close()
416 PORT = None
417 evt.set()
418
Neal Norwitz08b50eb2008-01-26 08:26:00 +0000419# This function prevents errors like:
420# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000421def is_unavailable_exception(e):
422 '''Returns True if the given ProtocolError is the product of a server-side
423 exception caused by the 'temporarily unavailable' response sometimes
424 given by operations on non-blocking sockets.'''
Neal Norwitz653272f2008-01-26 07:26:12 +0000425
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000426 # sometimes we get a -1 error code and/or empty headers
Neal Norwitzed444e52008-01-27 18:19:04 +0000427 try:
428 if e.errcode == -1 or e.headers is None:
429 return True
430 exc_mess = e.headers.get('X-exception')
431 except AttributeError:
432 # Ignore socket.errors here.
433 exc_mess = str(e)
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000434
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000435 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
436 return True
437
438 return False
439
Victor Stinnera44b5a32010-04-27 23:14:58 +0000440@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000441class BaseServerTestCase(unittest.TestCase):
442 requestHandler = None
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000443 request_count = 1
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000444 threadFunc = staticmethod(http_server)
Victor Stinnera44b5a32010-04-27 23:14:58 +0000445
Facundo Batistaa53872b2007-08-14 13:35:00 +0000446 def setUp(self):
Facundo Batista7f686fc2007-08-17 19:16:44 +0000447 # enable traceback reporting
448 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
449
Facundo Batistaa53872b2007-08-14 13:35:00 +0000450 self.evt = threading.Event()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000451 # start server thread to handle requests
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000452 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000453 threading.Thread(target=self.threadFunc, args=serv_args).start()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000454
Neal Norwitz653272f2008-01-26 07:26:12 +0000455 # wait for the server to be ready
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000456 self.evt.wait(10)
Neal Norwitz653272f2008-01-26 07:26:12 +0000457 self.evt.clear()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000458
459 def tearDown(self):
460 # wait on the server thread to terminate
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000461 self.evt.wait(10)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000462
Facundo Batista7f686fc2007-08-17 19:16:44 +0000463 # disable traceback reporting
464 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
465
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000466# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
467# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
468# condition occurs infrequently on some platforms, frequently on others, and
469# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket
470# If the server class is updated at some point in the future to handle this
471# situation more gracefully, these tests should be modified appropriately.
472
473class SimpleServerTestCase(BaseServerTestCase):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000474 def test_simple1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000475 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000476 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000477 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000478 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000479 # ignore failures due to non-blocking socket 'unavailable' errors
480 if not is_unavailable_exception(e):
481 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000482 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000483
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200484 @test_support.requires_unicode
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000485 def test_nonascii(self):
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200486 start_string = test_support.u(r'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t')
487 end_string = test_support.u(r'h\N{LATIN SMALL LETTER O WITH HORN}n')
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000488
489 try:
490 p = xmlrpclib.ServerProxy(URL)
491 self.assertEqual(p.add(start_string, end_string),
492 start_string + end_string)
493 except (xmlrpclib.ProtocolError, socket.error) as e:
494 # ignore failures due to non-blocking socket unavailable errors.
495 if not is_unavailable_exception(e):
496 # protocol error; provide additional information in test output
497 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
498
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200499 @test_support.requires_unicode
Victor Stinner51b71982011-09-23 01:15:32 +0200500 def test_unicode_host(self):
501 server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
502 self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000503
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200504 @test_support.requires_unicode
505 def test_client_encoding(self):
506 start_string = unichr(0x20ac)
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200507 end_string = unichr(0xa4)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200508
509 try:
510 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
511 self.assertEqual(p.add(start_string, end_string),
512 start_string + end_string)
513 except (xmlrpclib.ProtocolError, socket.error) as e:
514 # ignore failures due to non-blocking socket unavailable errors.
515 if not is_unavailable_exception(e):
516 # protocol error; provide additional information in test output
517 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
518
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200519 @test_support.requires_unicode
520 def test_nonascii_methodname(self):
521 try:
522 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
523 m = getattr(p, 't\xea\xa8t')
524 self.assertEqual(m(42), 42)
525 except (xmlrpclib.ProtocolError, socket.error) as e:
526 # ignore failures due to non-blocking socket unavailable errors.
527 if not is_unavailable_exception(e):
528 # protocol error; provide additional information in test output
529 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
530
Christian Heimes6c29be52008-01-19 16:39:27 +0000531 # [ch] The test 404 is causing lots of false alarms.
532 def XXXtest_404(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000533 # send POST with httplib, it should return 404 header and
534 # 'Not Found' message.
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000535 conn = httplib.HTTPConnection(ADDR, PORT)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000536 conn.request('POST', '/this-is-not-valid')
537 response = conn.getresponse()
538 conn.close()
539
540 self.assertEqual(response.status, 404)
541 self.assertEqual(response.reason, 'Not Found')
542
Facundo Batistaa53872b2007-08-14 13:35:00 +0000543 def test_introspection1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000544 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000545 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000546 meth = p.system.listMethods()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000547 expected_methods = set(['pow', 'div', 'my_function', 'add',
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200548 test_support.u(r't\xea\u0161t'),
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000549 'system.listMethods', 'system.methodHelp',
550 'system.methodSignature', 'system.multicall'])
Facundo Batistac65a5f12007-08-21 00:16:21 +0000551 self.assertEqual(set(meth), expected_methods)
Neal Norwitz183c5342008-01-27 17:11:11 +0000552 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000553 # ignore failures due to non-blocking socket 'unavailable' errors
554 if not is_unavailable_exception(e):
555 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000556 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000557
558 def test_introspection2(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000559 try:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000560 # test _methodHelp()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000561 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000562 divhelp = p.system.methodHelp('div')
563 self.assertEqual(divhelp, 'This is the div function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000564 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000565 # ignore failures due to non-blocking socket 'unavailable' errors
566 if not is_unavailable_exception(e):
567 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000568 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000569
R. David Murrayf28fd242010-02-23 00:24:49 +0000570 @unittest.skipIf(sys.flags.optimize >= 2,
571 "Docstrings are omitted with -O2 and above")
Facundo Batistaa53872b2007-08-14 13:35:00 +0000572 def test_introspection3(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000573 try:
574 # test native doc
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000575 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000576 myfunction = p.system.methodHelp('my_function')
577 self.assertEqual(myfunction, 'This is my function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000578 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +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", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000583
584 def test_introspection4(self):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000585 # the SimpleXMLRPCServer doesn't support signatures, but
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000586 # at least check that we can try making the call
Facundo Batistac65a5f12007-08-21 00:16:21 +0000587 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000588 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000589 divsig = p.system.methodSignature('div')
590 self.assertEqual(divsig, 'signatures not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000591 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000592 # ignore failures due to non-blocking socket 'unavailable' errors
593 if not is_unavailable_exception(e):
594 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000595 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000596
597 def test_multicall(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000598 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000599 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000600 multicall = xmlrpclib.MultiCall(p)
601 multicall.add(2,3)
602 multicall.pow(6,8)
603 multicall.div(127,42)
604 add_result, pow_result, div_result = multicall()
605 self.assertEqual(add_result, 2+3)
606 self.assertEqual(pow_result, 6**8)
607 self.assertEqual(div_result, 127//42)
Neal Norwitz183c5342008-01-27 17:11:11 +0000608 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000609 # ignore failures due to non-blocking socket 'unavailable' errors
610 if not is_unavailable_exception(e):
611 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000612 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000613
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000614 def test_non_existing_multicall(self):
615 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000616 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000617 multicall = xmlrpclib.MultiCall(p)
618 multicall.this_is_not_exists()
619 result = multicall()
620
621 # result.results contains;
622 # [{'faultCode': 1, 'faultString': '<type \'exceptions.Exception\'>:'
623 # 'method "this_is_not_exists" is not supported'>}]
624
625 self.assertEqual(result.results[0]['faultCode'], 1)
626 self.assertEqual(result.results[0]['faultString'],
627 '<type \'exceptions.Exception\'>:method "this_is_not_exists" '
628 'is not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000629 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000630 # ignore failures due to non-blocking socket 'unavailable' errors
631 if not is_unavailable_exception(e):
632 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000633 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000634
635 def test_dotted_attribute(self):
Neal Norwitz162d7192008-03-23 04:08:30 +0000636 # Raises an AttributeError because private methods are not allowed.
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000637 self.assertRaises(AttributeError,
638 SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')
639
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000640 self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
Neal Norwitz162d7192008-03-23 04:08:30 +0000641 # Get the test to run faster by sending a request with test_simple1.
642 # This avoids waiting for the socket timeout.
643 self.test_simple1()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000644
Charles-François Natalie0624662012-02-18 14:30:34 +0100645 def test_partial_post(self):
646 # Check that a partial POST doesn't make the server loop: issue #14001.
647 conn = httplib.HTTPConnection(ADDR, PORT)
648 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
649 conn.close()
650
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200651class SimpleServerEncodingTestCase(BaseServerTestCase):
652 @staticmethod
653 def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
654 http_server(evt, numrequests, requestHandler, 'iso-8859-15')
655
656 @test_support.requires_unicode
657 def test_server_encoding(self):
658 start_string = unichr(0x20ac)
Serhiy Storchaka9b5177c2016-01-20 10:33:51 +0200659 end_string = unichr(0xa4)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200660
661 try:
662 p = xmlrpclib.ServerProxy(URL)
663 self.assertEqual(p.add(start_string, end_string),
664 start_string + end_string)
665 except (xmlrpclib.ProtocolError, socket.error) as e:
666 # ignore failures due to non-blocking socket unavailable errors.
667 if not is_unavailable_exception(e):
668 # protocol error; provide additional information in test output
669 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
670
671
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000672class MultiPathServerTestCase(BaseServerTestCase):
673 threadFunc = staticmethod(http_multi_server)
674 request_count = 2
675 def test_path1(self):
676 p = xmlrpclib.ServerProxy(URL+"/foo")
677 self.assertEqual(p.pow(6,8), 6**8)
678 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
679 def test_path2(self):
680 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
681 self.assertEqual(p.add(6,8), 6+8)
682 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
683
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000684#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
685#does indeed serve subsequent requests on the same connection
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000686class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000687 #a request handler that supports keep-alive and logs requests into a
688 #class variable
689 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
690 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
691 protocol_version = 'HTTP/1.1'
692 myRequests = []
693 def handle(self):
694 self.myRequests.append([])
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000695 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000696 return self.parentClass.handle(self)
697 def handle_one_request(self):
698 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000699 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000700 return result
701
702 requestHandler = RequestHandler
703 def setUp(self):
704 #clear request log
705 self.RequestHandler.myRequests = []
706 return BaseServerTestCase.setUp(self)
707
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000708#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
709#does indeed serve subsequent requests on the same connection
710class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000711 def test_two(self):
712 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000713 #do three requests.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000714 self.assertEqual(p.pow(6,8), 6**8)
715 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000716 self.assertEqual(p.pow(6,8), 6**8)
717
718 #they should have all been handled by a single request handler
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000719 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000720
721 #check that we did at least two (the third may be pending append
722 #due to thread scheduling)
723 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000724
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000725#test special attribute access on the serverproxy, through the __call__
726#function.
727class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
728 #ask for two keepalive requests to be handled.
729 request_count=2
730
731 def test_close(self):
732 p = xmlrpclib.ServerProxy(URL)
733 #do some requests with close.
734 self.assertEqual(p.pow(6,8), 6**8)
735 self.assertEqual(p.pow(6,8), 6**8)
736 self.assertEqual(p.pow(6,8), 6**8)
737 p("close")() #this should trigger a new keep-alive request
738 self.assertEqual(p.pow(6,8), 6**8)
739 self.assertEqual(p.pow(6,8), 6**8)
740 self.assertEqual(p.pow(6,8), 6**8)
741
742 #they should have all been two request handlers, each having logged at least
743 #two complete requests
744 self.assertEqual(len(self.RequestHandler.myRequests), 2)
745 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
746 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
747
748 def test_transport(self):
749 p = xmlrpclib.ServerProxy(URL)
750 #do some requests with close.
751 self.assertEqual(p.pow(6,8), 6**8)
752 p("transport").close() #same as above, really.
753 self.assertEqual(p.pow(6,8), 6**8)
754 self.assertEqual(len(self.RequestHandler.myRequests), 2)
755
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000756#A test case that verifies that gzip encoding works in both directions
757#(for a request and the response)
Zachary Ware1f702212013-12-10 14:09:20 -0600758@unittest.skipUnless(gzip, 'gzip not available')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000759class GzipServerTestCase(BaseServerTestCase):
760 #a request handler that supports keep-alive and logs requests into a
761 #class variable
762 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
763 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
764 protocol_version = 'HTTP/1.1'
765
766 def do_POST(self):
767 #store content of last request in class
768 self.__class__.content_length = int(self.headers["content-length"])
769 return self.parentClass.do_POST(self)
770 requestHandler = RequestHandler
771
772 class Transport(xmlrpclib.Transport):
773 #custom transport, stores the response length for our perusal
774 fake_gzip = False
775 def parse_response(self, response):
776 self.response_length=int(response.getheader("content-length", 0))
777 return xmlrpclib.Transport.parse_response(self, response)
778
779 def send_content(self, connection, body):
780 if self.fake_gzip:
781 #add a lone gzip header to induce decode error remotely
782 connection.putheader("Content-Encoding", "gzip")
783 return xmlrpclib.Transport.send_content(self, connection, body)
784
Victor Stinnera44b5a32010-04-27 23:14:58 +0000785 def setUp(self):
786 BaseServerTestCase.setUp(self)
787
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000788 def test_gzip_request(self):
789 t = self.Transport()
790 t.encode_threshold = None
791 p = xmlrpclib.ServerProxy(URL, transport=t)
792 self.assertEqual(p.pow(6,8), 6**8)
793 a = self.RequestHandler.content_length
794 t.encode_threshold = 0 #turn on request encoding
795 self.assertEqual(p.pow(6,8), 6**8)
796 b = self.RequestHandler.content_length
797 self.assertTrue(a>b)
798
799 def test_bad_gzip_request(self):
800 t = self.Transport()
801 t.encode_threshold = None
802 t.fake_gzip = True
803 p = xmlrpclib.ServerProxy(URL, transport=t)
804 cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
805 re.compile(r"\b400\b"))
806 with cm:
807 p.pow(6, 8)
808
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500809 def test_gzip_response(self):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000810 t = self.Transport()
811 p = xmlrpclib.ServerProxy(URL, transport=t)
812 old = self.requestHandler.encode_threshold
813 self.requestHandler.encode_threshold = None #no encoding
814 self.assertEqual(p.pow(6,8), 6**8)
815 a = t.response_length
816 self.requestHandler.encode_threshold = 0 #always encode
817 self.assertEqual(p.pow(6,8), 6**8)
818 b = t.response_length
819 self.requestHandler.encode_threshold = old
820 self.assertTrue(a>b)
821
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500822 def test_gzip_decode_limit(self):
823 max_gzip_decode = 20 * 1024 * 1024
824 data = '\0' * max_gzip_decode
825 encoded = xmlrpclib.gzip_encode(data)
826 decoded = xmlrpclib.gzip_decode(encoded)
827 self.assertEqual(len(decoded), max_gzip_decode)
828
829 data = '\0' * (max_gzip_decode + 1)
830 encoded = xmlrpclib.gzip_encode(data)
831
832 with self.assertRaisesRegexp(ValueError,
833 "max gzipped payload length exceeded"):
834 xmlrpclib.gzip_decode(encoded)
835
836 xmlrpclib.gzip_decode(encoded, max_decode=-1)
837
838
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000839#Test special attributes of the ServerProxy object
840class ServerProxyTestCase(unittest.TestCase):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000841 def setUp(self):
842 unittest.TestCase.setUp(self)
843 if threading:
844 self.url = URL
845 else:
846 # Without threading, http_server() and http_multi_server() will not
847 # be executed and URL is still equal to None. 'http://' is a just
848 # enough to choose the scheme (HTTP)
849 self.url = 'http://'
850
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000851 def test_close(self):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000852 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000853 self.assertEqual(p('close')(), None)
854
855 def test_transport(self):
856 t = xmlrpclib.Transport()
Victor Stinnera44b5a32010-04-27 23:14:58 +0000857 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000858 self.assertEqual(p('transport'), t)
859
Facundo Batista7f686fc2007-08-17 19:16:44 +0000860# This is a contrived way to make a failure occur on the server side
861# in order to test the _send_traceback_header flag on the server
862class FailingMessageClass(mimetools.Message):
863 def __getitem__(self, key):
864 key = key.lower()
865 if key == 'content-length':
866 return 'I am broken'
867 return mimetools.Message.__getitem__(self, key)
868
869
Victor Stinnera44b5a32010-04-27 23:14:58 +0000870@unittest.skipUnless(threading, 'Threading required for this test.')
Facundo Batista7f686fc2007-08-17 19:16:44 +0000871class FailingServerTestCase(unittest.TestCase):
872 def setUp(self):
873 self.evt = threading.Event()
874 # start server thread to handle requests
Neal Norwitz162d7192008-03-23 04:08:30 +0000875 serv_args = (self.evt, 1)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000876 threading.Thread(target=http_server, args=serv_args).start()
877
Neal Norwitz653272f2008-01-26 07:26:12 +0000878 # wait for the server to be ready
879 self.evt.wait()
880 self.evt.clear()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000881
882 def tearDown(self):
883 # wait on the server thread to terminate
884 self.evt.wait()
885 # reset flag
886 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
887 # reset message class
888 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message
889
890 def test_basic(self):
891 # check that flag is false by default
892 flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
893 self.assertEqual(flagval, False)
894
Facundo Batistac65a5f12007-08-21 00:16:21 +0000895 # enable traceback reporting
896 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
897
898 # test a call that shouldn't fail just as a smoke test
899 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000900 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000901 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000902 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000903 # ignore failures due to non-blocking socket 'unavailable' errors
904 if not is_unavailable_exception(e):
905 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000906 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batista7f686fc2007-08-17 19:16:44 +0000907
908 def test_fail_no_info(self):
909 # use the broken message class
910 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
911
912 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000913 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000914 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000915 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000916 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000917 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000918 # The two server-side error headers shouldn't be sent back in this case
919 self.assertTrue(e.headers.get("X-exception") is None)
920 self.assertTrue(e.headers.get("X-traceback") is None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000921 else:
922 self.fail('ProtocolError not raised')
923
924 def test_fail_with_info(self):
925 # use the broken message class
926 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
927
928 # Check that errors in the server send back exception/traceback
929 # info when flag is set
930 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
931
932 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000933 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000934 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000935 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000936 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000937 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000938 # We should get error info in the response
939 expected_err = "invalid literal for int() with base 10: 'I am broken'"
940 self.assertEqual(e.headers.get("x-exception"), expected_err)
941 self.assertTrue(e.headers.get("x-traceback") is not None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000942 else:
943 self.fail('ProtocolError not raised')
944
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000945class CGIHandlerTestCase(unittest.TestCase):
946 def setUp(self):
947 self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
948
949 def tearDown(self):
950 self.cgi = None
951
952 def test_cgi_get(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000953 with test_support.EnvironmentVarGuard() as env:
Walter Dörwald6733bed2009-05-01 17:35:37 +0000954 env['REQUEST_METHOD'] = 'GET'
Walter Dörwald4b965f62009-04-26 20:51:44 +0000955 # if the method is GET and no request_text is given, it runs handle_get
956 # get sysout output
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000957 with test_support.captured_stdout() as data_out:
958 self.cgi.handle_request()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000959
Walter Dörwald4b965f62009-04-26 20:51:44 +0000960 # parse Status header
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000961 data_out.seek(0)
962 handle = data_out.read()
Walter Dörwald4b965f62009-04-26 20:51:44 +0000963 status = handle.split()[1]
964 message = ' '.join(handle.split()[2:4])
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000965
Walter Dörwald4b965f62009-04-26 20:51:44 +0000966 self.assertEqual(status, '400')
967 self.assertEqual(message, 'Bad Request')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000968
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000969
970 def test_cgi_xmlrpc_response(self):
971 data = """<?xml version='1.0'?>
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000972 <methodCall>
973 <methodName>test_method</methodName>
974 <params>
975 <param>
976 <value><string>foo</string></value>
977 </param>
978 <param>
979 <value><string>bar</string></value>
980 </param>
981 </params>
982 </methodCall>
983 """
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000984
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000985 with test_support.EnvironmentVarGuard() as env, \
986 test_support.captured_stdout() as data_out, \
987 test_support.captured_stdin() as data_in:
988 data_in.write(data)
989 data_in.seek(0)
Walter Dörwald6733bed2009-05-01 17:35:37 +0000990 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandl61fce382009-04-01 15:23:43 +0000991 self.cgi.handle_request()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000992 data_out.seek(0)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000993
994 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000995 handle = data_out.read()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000996
997 # start with 44th char so as not to get http header, we just need only xml
998 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
999
Senthil Kumaran20d114c2009-04-01 20:26:33 +00001000 # Also test the content-length returned by handle_request
1001 # Using the same test method inorder to avoid all the datapassing
1002 # boilerplate code.
1003 # Test for bug: http://bugs.python.org/issue5040
1004
1005 content = handle[handle.find("<?xml"):]
1006
Ezio Melotti2623a372010-11-21 13:34:58 +00001007 self.assertEqual(
Senthil Kumaran20d114c2009-04-01 20:26:33 +00001008 int(re.search('Content-Length: (\d+)', handle).group(1)),
1009 len(content))
1010
1011
Jeremy Hylton89420112008-11-24 22:00:29 +00001012class FakeSocket:
1013
1014 def __init__(self):
1015 self.data = StringIO.StringIO()
1016
1017 def send(self, buf):
1018 self.data.write(buf)
1019 return len(buf)
1020
1021 def sendall(self, buf):
1022 self.data.write(buf)
1023
1024 def getvalue(self):
1025 return self.data.getvalue()
1026
Kristján Valur Jónsson3c43fcb2009-01-11 16:23:37 +00001027 def makefile(self, x='r', y=-1):
Jeremy Hylton89420112008-11-24 22:00:29 +00001028 raise RuntimeError
1029
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001030 def close(self):
1031 pass
1032
Jeremy Hylton89420112008-11-24 22:00:29 +00001033class FakeTransport(xmlrpclib.Transport):
1034 """A Transport instance that records instead of sending a request.
1035
1036 This class replaces the actual socket used by httplib with a
1037 FakeSocket object that records the request. It doesn't provide a
1038 response.
1039 """
1040
1041 def make_connection(self, host):
1042 conn = xmlrpclib.Transport.make_connection(self, host)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001043 conn.sock = self.fake_socket = FakeSocket()
Jeremy Hylton89420112008-11-24 22:00:29 +00001044 return conn
1045
1046class TransportSubclassTestCase(unittest.TestCase):
1047
1048 def issue_request(self, transport_class):
1049 """Return an HTTP request made via transport_class."""
1050 transport = transport_class()
1051 proxy = xmlrpclib.ServerProxy("http://example.com/",
1052 transport=transport)
1053 try:
1054 proxy.pow(6, 8)
1055 except RuntimeError:
1056 return transport.fake_socket.getvalue()
1057 return None
1058
1059 def test_custom_user_agent(self):
1060 class TestTransport(FakeTransport):
1061
1062 def send_user_agent(self, conn):
1063 xmlrpclib.Transport.send_user_agent(self, conn)
1064 conn.putheader("X-Test", "test_custom_user_agent")
1065
1066 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001067 self.assertIn("X-Test: test_custom_user_agent\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001068
1069 def test_send_host(self):
1070 class TestTransport(FakeTransport):
1071
1072 def send_host(self, conn, host):
1073 xmlrpclib.Transport.send_host(self, conn, host)
1074 conn.putheader("X-Test", "test_send_host")
1075
1076 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001077 self.assertIn("X-Test: test_send_host\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001078
1079 def test_send_request(self):
1080 class TestTransport(FakeTransport):
1081
1082 def send_request(self, conn, url, body):
1083 xmlrpclib.Transport.send_request(self, conn, url, body)
1084 conn.putheader("X-Test", "test_send_request")
1085
1086 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001087 self.assertIn("X-Test: test_send_request\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001088
1089 def test_send_content(self):
1090 class TestTransport(FakeTransport):
1091
1092 def send_content(self, conn, body):
1093 conn.putheader("X-Test", "test_send_content")
1094 xmlrpclib.Transport.send_content(self, conn, body)
1095
1096 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001097 self.assertIn("X-Test: test_send_content\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001098
Antoine Pitrou3c968582009-10-30 17:56:00 +00001099@test_support.reap_threads
Facundo Batistaa53872b2007-08-14 13:35:00 +00001100def test_main():
1101 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
Jeremy Hylton89420112008-11-24 22:00:29 +00001102 BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001103 xmlrpc_tests.append(SimpleServerTestCase)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +02001104 xmlrpc_tests.append(SimpleServerEncodingTestCase)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +00001105 xmlrpc_tests.append(KeepaliveServerTestCase1)
1106 xmlrpc_tests.append(KeepaliveServerTestCase2)
Zachary Ware1f702212013-12-10 14:09:20 -06001107 xmlrpc_tests.append(GzipServerTestCase)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +00001108 xmlrpc_tests.append(MultiPathServerTestCase)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001109 xmlrpc_tests.append(ServerProxyTestCase)
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001110 xmlrpc_tests.append(FailingServerTestCase)
1111 xmlrpc_tests.append(CGIHandlerTestCase)
Facundo Batistaa53872b2007-08-14 13:35:00 +00001112
1113 test_support.run_unittest(*xmlrpc_tests)
Skip Montanaro419abda2001-10-01 17:47:44 +00001114
1115if __name__ == "__main__":
1116 test_main()