blob: 2c199411a7ab98b256208308eb0375cc1611b7a8 [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):
152 value = unichr(0x20ac)
153 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15')
154 strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg
155 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
156
157 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
158 methodresponse=True)
159 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
160
161 @test_support.requires_unicode
Fred Drake22c07062005-02-11 17:59:08 +0000162 def test_default_encoding_issues(self):
163 # SF bug #1115989: wrong decoding in '_stringify'
164 utf8 = """<?xml version='1.0' encoding='iso-8859-1'?>
165 <params>
166 <param><value>
167 <string>abc \x95</string>
168 </value></param>
169 <param><value>
170 <struct>
171 <member>
172 <name>def \x96</name>
173 <value><string>ghi \x97</string></value>
174 </member>
175 </struct>
176 </value></param>
177 </params>
178 """
Tim Petersf754f5f2005-04-08 18:00:59 +0000179
180 # sys.setdefaultencoding() normally doesn't exist after site.py is
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000181 # loaded. Import a temporary fresh copy to get access to it
182 # but then restore the original copy to avoid messing with
183 # other potentially modified sys module attributes
Fred Drake22c07062005-02-11 17:59:08 +0000184 old_encoding = sys.getdefaultencoding()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000185 with test_support.CleanImport('sys'):
186 import sys as temp_sys
187 temp_sys.setdefaultencoding("iso-8859-1")
188 try:
189 (s, d), m = xmlrpclib.loads(utf8)
190 finally:
191 temp_sys.setdefaultencoding(old_encoding)
Tim Petersf754f5f2005-04-08 18:00:59 +0000192
Fred Drake22c07062005-02-11 17:59:08 +0000193 items = d.items()
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200194 if test_support.have_unicode:
Ezio Melotti2623a372010-11-21 13:34:58 +0000195 self.assertEqual(s, u"abc \x95")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000196 self.assertIsInstance(s, unicode)
Ezio Melotti2623a372010-11-21 13:34:58 +0000197 self.assertEqual(items, [(u"def \x96", u"ghi \x97")])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000198 self.assertIsInstance(items[0][0], unicode)
199 self.assertIsInstance(items[0][1], unicode)
Fred Drake22c07062005-02-11 17:59:08 +0000200 else:
Ezio Melotti2623a372010-11-21 13:34:58 +0000201 self.assertEqual(s, "abc \xc2\x95")
202 self.assertEqual(items, [("def \xc2\x96", "ghi \xc2\x97")])
Fred Drake22c07062005-02-11 17:59:08 +0000203
Facundo Batista5a3b5242007-07-13 10:43:44 +0000204
205class HelperTestCase(unittest.TestCase):
206 def test_escape(self):
207 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
208 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
209 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
210
211class FaultTestCase(unittest.TestCase):
212 def test_repr(self):
213 f = xmlrpclib.Fault(42, 'Test Fault')
214 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
215 self.assertEqual(repr(f), str(f))
216
217 def test_dump_fault(self):
218 f = xmlrpclib.Fault(42, 'Test Fault')
219 s = xmlrpclib.dumps((f,))
220 (newf,), m = xmlrpclib.loads(s)
Ezio Melotti2623a372010-11-21 13:34:58 +0000221 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
222 self.assertEqual(m, None)
Facundo Batista5a3b5242007-07-13 10:43:44 +0000223
224 s = xmlrpclib.Marshaller().dumps(f)
225 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
226
227
228class DateTimeTestCase(unittest.TestCase):
229 def test_default(self):
230 t = xmlrpclib.DateTime()
231
232 def test_time(self):
233 d = 1181399930.036952
234 t = xmlrpclib.DateTime(d)
235 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
236
237 def test_time_tuple(self):
238 d = (2007,6,9,10,38,50,5,160,0)
239 t = xmlrpclib.DateTime(d)
240 self.assertEqual(str(t), '20070609T10:38:50')
241
242 def test_time_struct(self):
243 d = time.localtime(1181399930.036952)
244 t = xmlrpclib.DateTime(d)
245 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
246
247 def test_datetime_datetime(self):
248 d = datetime.datetime(2007,1,2,3,4,5)
249 t = xmlrpclib.DateTime(d)
250 self.assertEqual(str(t), '20070102T03:04:05')
251
Facundo Batista5a3b5242007-07-13 10:43:44 +0000252 def test_repr(self):
253 d = datetime.datetime(2007,1,2,3,4,5)
254 t = xmlrpclib.DateTime(d)
255 val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
256 self.assertEqual(repr(t), val)
257
258 def test_decode(self):
259 d = ' 20070908T07:11:13 '
260 t1 = xmlrpclib.DateTime()
261 t1.decode(d)
262 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
263 self.assertEqual(t1, tref)
264
265 t2 = xmlrpclib._datetime(d)
266 self.assertEqual(t1, tref)
267
268class BinaryTestCase(unittest.TestCase):
269 def test_default(self):
270 t = xmlrpclib.Binary()
271 self.assertEqual(str(t), '')
272
273 def test_string(self):
274 d = '\x01\x02\x03abc123\xff\xfe'
275 t = xmlrpclib.Binary(d)
276 self.assertEqual(str(t), d)
277
278 def test_decode(self):
279 d = '\x01\x02\x03abc123\xff\xfe'
280 de = base64.encodestring(d)
281 t1 = xmlrpclib.Binary()
282 t1.decode(de)
283 self.assertEqual(str(t1), d)
284
285 t2 = xmlrpclib._binary(de)
286 self.assertEqual(str(t2), d)
287
288
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000289ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000290
Neal Norwitz653272f2008-01-26 07:26:12 +0000291# The evt is set twice. First when the server is ready to serve.
292# Second when the server has been shutdown. The user must clear
293# the event after it has been set the first time to catch the second set.
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200294def http_server(evt, numrequests, requestHandler=None, encoding=None):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000295 class TestInstanceClass:
296 def div(self, x, y):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000297 return x // y
298
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000299 def _methodHelp(self, name):
300 if name == 'div':
301 return 'This is the div function'
302
303 def my_function():
304 '''This is my function'''
305 return True
306
Neal Norwitz70cea582008-03-28 06:34:03 +0000307 class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
308 def get_request(self):
309 # Ensure the socket is always non-blocking. On Linux, socket
310 # attributes are not inherited like they are on *BSD and Windows.
311 s, port = self.socket.accept()
312 s.setblocking(True)
313 return s, port
314
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000315 if not requestHandler:
316 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
317 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200318 encoding=encoding,
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000319 logRequests=False, bind_and_activate=False)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000320 try:
321 serv.socket.settimeout(3)
322 serv.server_bind()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000323 global ADDR, PORT, URL
324 ADDR, PORT = serv.socket.getsockname()
325 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300326 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000327 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
328 #on AF_INET only.
329 URL = "http://%s:%d"%(ADDR, PORT)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000330 serv.server_activate()
331 serv.register_introspection_functions()
332 serv.register_multicall_functions()
333 serv.register_function(pow)
334 serv.register_function(lambda x,y: x+y, 'add')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000335 serv.register_function(my_function)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000336 serv.register_instance(TestInstanceClass())
Neal Norwitz653272f2008-01-26 07:26:12 +0000337 evt.set()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000338
339 # handle up to 'numrequests' requests
340 while numrequests > 0:
341 serv.handle_request()
342 numrequests -= 1
343
344 except socket.timeout:
345 pass
346 finally:
347 serv.socket.close()
348 PORT = None
349 evt.set()
350
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000351def http_multi_server(evt, numrequests, requestHandler=None):
352 class TestInstanceClass:
353 def div(self, x, y):
354 return x // y
355
356 def _methodHelp(self, name):
357 if name == 'div':
358 return 'This is the div function'
359
360 def my_function():
361 '''This is my function'''
362 return True
363
364 class MyXMLRPCServer(SimpleXMLRPCServer.MultiPathXMLRPCServer):
365 def get_request(self):
366 # Ensure the socket is always non-blocking. On Linux, socket
367 # attributes are not inherited like they are on *BSD and Windows.
368 s, port = self.socket.accept()
369 s.setblocking(True)
370 return s, port
371
372 if not requestHandler:
373 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
374 class MyRequestHandler(requestHandler):
375 rpc_paths = []
376
377 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
378 logRequests=False, bind_and_activate=False)
379 serv.socket.settimeout(3)
380 serv.server_bind()
381 try:
382 global ADDR, PORT, URL
383 ADDR, PORT = serv.socket.getsockname()
384 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300385 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000386 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
387 #on AF_INET only.
388 URL = "http://%s:%d"%(ADDR, PORT)
389 serv.server_activate()
390 paths = ["/foo", "/foo/bar"]
391 for path in paths:
392 d = serv.add_dispatcher(path, SimpleXMLRPCServer.SimpleXMLRPCDispatcher())
393 d.register_introspection_functions()
394 d.register_multicall_functions()
395 serv.get_dispatcher(paths[0]).register_function(pow)
396 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
397 evt.set()
398
399 # handle up to 'numrequests' requests
400 while numrequests > 0:
401 serv.handle_request()
402 numrequests -= 1
403
404 except socket.timeout:
405 pass
406 finally:
407 serv.socket.close()
408 PORT = None
409 evt.set()
410
Neal Norwitz08b50eb2008-01-26 08:26:00 +0000411# This function prevents errors like:
412# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000413def is_unavailable_exception(e):
414 '''Returns True if the given ProtocolError is the product of a server-side
415 exception caused by the 'temporarily unavailable' response sometimes
416 given by operations on non-blocking sockets.'''
Neal Norwitz653272f2008-01-26 07:26:12 +0000417
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000418 # sometimes we get a -1 error code and/or empty headers
Neal Norwitzed444e52008-01-27 18:19:04 +0000419 try:
420 if e.errcode == -1 or e.headers is None:
421 return True
422 exc_mess = e.headers.get('X-exception')
423 except AttributeError:
424 # Ignore socket.errors here.
425 exc_mess = str(e)
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000426
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000427 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
428 return True
429
430 return False
431
Victor Stinnera44b5a32010-04-27 23:14:58 +0000432@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000433class BaseServerTestCase(unittest.TestCase):
434 requestHandler = None
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000435 request_count = 1
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000436 threadFunc = staticmethod(http_server)
Victor Stinnera44b5a32010-04-27 23:14:58 +0000437
Facundo Batistaa53872b2007-08-14 13:35:00 +0000438 def setUp(self):
Facundo Batista7f686fc2007-08-17 19:16:44 +0000439 # enable traceback reporting
440 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
441
Facundo Batistaa53872b2007-08-14 13:35:00 +0000442 self.evt = threading.Event()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000443 # start server thread to handle requests
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000444 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000445 threading.Thread(target=self.threadFunc, args=serv_args).start()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000446
Neal Norwitz653272f2008-01-26 07:26:12 +0000447 # wait for the server to be ready
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000448 self.evt.wait(10)
Neal Norwitz653272f2008-01-26 07:26:12 +0000449 self.evt.clear()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000450
451 def tearDown(self):
452 # wait on the server thread to terminate
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000453 self.evt.wait(10)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000454
Facundo Batista7f686fc2007-08-17 19:16:44 +0000455 # disable traceback reporting
456 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
457
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000458# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
459# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
460# condition occurs infrequently on some platforms, frequently on others, and
461# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket
462# If the server class is updated at some point in the future to handle this
463# situation more gracefully, these tests should be modified appropriately.
464
465class SimpleServerTestCase(BaseServerTestCase):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000466 def test_simple1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000467 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000468 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000469 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000470 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000471 # ignore failures due to non-blocking socket 'unavailable' errors
472 if not is_unavailable_exception(e):
473 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000474 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000475
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200476 @test_support.requires_unicode
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000477 def test_nonascii(self):
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200478 start_string = test_support.u(r'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t')
479 end_string = test_support.u(r'h\N{LATIN SMALL LETTER O WITH HORN}n')
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000480
481 try:
482 p = xmlrpclib.ServerProxy(URL)
483 self.assertEqual(p.add(start_string, end_string),
484 start_string + end_string)
485 except (xmlrpclib.ProtocolError, socket.error) as e:
486 # ignore failures due to non-blocking socket unavailable errors.
487 if not is_unavailable_exception(e):
488 # protocol error; provide additional information in test output
489 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
490
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200491 @test_support.requires_unicode
Victor Stinner51b71982011-09-23 01:15:32 +0200492 def test_unicode_host(self):
493 server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
494 self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000495
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200496 @test_support.requires_unicode
497 def test_client_encoding(self):
498 start_string = unichr(0x20ac)
499 end_string = unichr(0xa3)
500
501 try:
502 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
503 self.assertEqual(p.add(start_string, end_string),
504 start_string + end_string)
505 except (xmlrpclib.ProtocolError, socket.error) as e:
506 # ignore failures due to non-blocking socket unavailable errors.
507 if not is_unavailable_exception(e):
508 # protocol error; provide additional information in test output
509 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
510
Christian Heimes6c29be52008-01-19 16:39:27 +0000511 # [ch] The test 404 is causing lots of false alarms.
512 def XXXtest_404(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000513 # send POST with httplib, it should return 404 header and
514 # 'Not Found' message.
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000515 conn = httplib.HTTPConnection(ADDR, PORT)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000516 conn.request('POST', '/this-is-not-valid')
517 response = conn.getresponse()
518 conn.close()
519
520 self.assertEqual(response.status, 404)
521 self.assertEqual(response.reason, 'Not Found')
522
Facundo Batistaa53872b2007-08-14 13:35:00 +0000523 def test_introspection1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000524 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000525 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000526 meth = p.system.listMethods()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000527 expected_methods = set(['pow', 'div', 'my_function', 'add',
528 'system.listMethods', 'system.methodHelp',
529 'system.methodSignature', 'system.multicall'])
Facundo Batistac65a5f12007-08-21 00:16:21 +0000530 self.assertEqual(set(meth), expected_methods)
Neal Norwitz183c5342008-01-27 17:11:11 +0000531 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000532 # ignore failures due to non-blocking socket 'unavailable' errors
533 if not is_unavailable_exception(e):
534 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000535 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000536
537 def test_introspection2(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000538 try:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000539 # test _methodHelp()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000540 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000541 divhelp = p.system.methodHelp('div')
542 self.assertEqual(divhelp, 'This is the div function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000543 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000544 # ignore failures due to non-blocking socket 'unavailable' errors
545 if not is_unavailable_exception(e):
546 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000547 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000548
R. David Murrayf28fd242010-02-23 00:24:49 +0000549 @unittest.skipIf(sys.flags.optimize >= 2,
550 "Docstrings are omitted with -O2 and above")
Facundo Batistaa53872b2007-08-14 13:35:00 +0000551 def test_introspection3(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000552 try:
553 # test native doc
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000554 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000555 myfunction = p.system.methodHelp('my_function')
556 self.assertEqual(myfunction, 'This is my function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000557 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000558 # ignore failures due to non-blocking socket 'unavailable' errors
559 if not is_unavailable_exception(e):
560 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000561 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000562
563 def test_introspection4(self):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000564 # the SimpleXMLRPCServer doesn't support signatures, but
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000565 # at least check that we can try making the call
Facundo Batistac65a5f12007-08-21 00:16:21 +0000566 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000567 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000568 divsig = p.system.methodSignature('div')
569 self.assertEqual(divsig, 'signatures not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000570 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000571 # ignore failures due to non-blocking socket 'unavailable' errors
572 if not is_unavailable_exception(e):
573 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000574 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000575
576 def test_multicall(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000577 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000578 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000579 multicall = xmlrpclib.MultiCall(p)
580 multicall.add(2,3)
581 multicall.pow(6,8)
582 multicall.div(127,42)
583 add_result, pow_result, div_result = multicall()
584 self.assertEqual(add_result, 2+3)
585 self.assertEqual(pow_result, 6**8)
586 self.assertEqual(div_result, 127//42)
Neal Norwitz183c5342008-01-27 17:11:11 +0000587 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000588 # ignore failures due to non-blocking socket 'unavailable' errors
589 if not is_unavailable_exception(e):
590 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000591 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000592
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000593 def test_non_existing_multicall(self):
594 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000595 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000596 multicall = xmlrpclib.MultiCall(p)
597 multicall.this_is_not_exists()
598 result = multicall()
599
600 # result.results contains;
601 # [{'faultCode': 1, 'faultString': '<type \'exceptions.Exception\'>:'
602 # 'method "this_is_not_exists" is not supported'>}]
603
604 self.assertEqual(result.results[0]['faultCode'], 1)
605 self.assertEqual(result.results[0]['faultString'],
606 '<type \'exceptions.Exception\'>:method "this_is_not_exists" '
607 'is not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000608 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +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", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000613
614 def test_dotted_attribute(self):
Neal Norwitz162d7192008-03-23 04:08:30 +0000615 # Raises an AttributeError because private methods are not allowed.
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000616 self.assertRaises(AttributeError,
617 SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')
618
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000619 self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
Neal Norwitz162d7192008-03-23 04:08:30 +0000620 # Get the test to run faster by sending a request with test_simple1.
621 # This avoids waiting for the socket timeout.
622 self.test_simple1()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000623
Charles-François Natalie0624662012-02-18 14:30:34 +0100624 def test_partial_post(self):
625 # Check that a partial POST doesn't make the server loop: issue #14001.
626 conn = httplib.HTTPConnection(ADDR, PORT)
627 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
628 conn.close()
629
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +0200630class SimpleServerEncodingTestCase(BaseServerTestCase):
631 @staticmethod
632 def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
633 http_server(evt, numrequests, requestHandler, 'iso-8859-15')
634
635 @test_support.requires_unicode
636 def test_server_encoding(self):
637 start_string = unichr(0x20ac)
638 end_string = unichr(0xa3)
639
640 try:
641 p = xmlrpclib.ServerProxy(URL)
642 self.assertEqual(p.add(start_string, end_string),
643 start_string + end_string)
644 except (xmlrpclib.ProtocolError, socket.error) as e:
645 # ignore failures due to non-blocking socket unavailable errors.
646 if not is_unavailable_exception(e):
647 # protocol error; provide additional information in test output
648 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
649
650
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000651class MultiPathServerTestCase(BaseServerTestCase):
652 threadFunc = staticmethod(http_multi_server)
653 request_count = 2
654 def test_path1(self):
655 p = xmlrpclib.ServerProxy(URL+"/foo")
656 self.assertEqual(p.pow(6,8), 6**8)
657 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
658 def test_path2(self):
659 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
660 self.assertEqual(p.add(6,8), 6+8)
661 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
662
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000663#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
664#does indeed serve subsequent requests on the same connection
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000665class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000666 #a request handler that supports keep-alive and logs requests into a
667 #class variable
668 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
669 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
670 protocol_version = 'HTTP/1.1'
671 myRequests = []
672 def handle(self):
673 self.myRequests.append([])
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000674 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000675 return self.parentClass.handle(self)
676 def handle_one_request(self):
677 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000678 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000679 return result
680
681 requestHandler = RequestHandler
682 def setUp(self):
683 #clear request log
684 self.RequestHandler.myRequests = []
685 return BaseServerTestCase.setUp(self)
686
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000687#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
688#does indeed serve subsequent requests on the same connection
689class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000690 def test_two(self):
691 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000692 #do three requests.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000693 self.assertEqual(p.pow(6,8), 6**8)
694 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000695 self.assertEqual(p.pow(6,8), 6**8)
696
697 #they should have all been handled by a single request handler
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000698 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000699
700 #check that we did at least two (the third may be pending append
701 #due to thread scheduling)
702 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000703
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000704#test special attribute access on the serverproxy, through the __call__
705#function.
706class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
707 #ask for two keepalive requests to be handled.
708 request_count=2
709
710 def test_close(self):
711 p = xmlrpclib.ServerProxy(URL)
712 #do some requests with close.
713 self.assertEqual(p.pow(6,8), 6**8)
714 self.assertEqual(p.pow(6,8), 6**8)
715 self.assertEqual(p.pow(6,8), 6**8)
716 p("close")() #this should trigger a new keep-alive request
717 self.assertEqual(p.pow(6,8), 6**8)
718 self.assertEqual(p.pow(6,8), 6**8)
719 self.assertEqual(p.pow(6,8), 6**8)
720
721 #they should have all been two request handlers, each having logged at least
722 #two complete requests
723 self.assertEqual(len(self.RequestHandler.myRequests), 2)
724 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
725 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
726
727 def test_transport(self):
728 p = xmlrpclib.ServerProxy(URL)
729 #do some requests with close.
730 self.assertEqual(p.pow(6,8), 6**8)
731 p("transport").close() #same as above, really.
732 self.assertEqual(p.pow(6,8), 6**8)
733 self.assertEqual(len(self.RequestHandler.myRequests), 2)
734
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000735#A test case that verifies that gzip encoding works in both directions
736#(for a request and the response)
Zachary Ware1f702212013-12-10 14:09:20 -0600737@unittest.skipUnless(gzip, 'gzip not available')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000738class GzipServerTestCase(BaseServerTestCase):
739 #a request handler that supports keep-alive and logs requests into a
740 #class variable
741 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
742 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
743 protocol_version = 'HTTP/1.1'
744
745 def do_POST(self):
746 #store content of last request in class
747 self.__class__.content_length = int(self.headers["content-length"])
748 return self.parentClass.do_POST(self)
749 requestHandler = RequestHandler
750
751 class Transport(xmlrpclib.Transport):
752 #custom transport, stores the response length for our perusal
753 fake_gzip = False
754 def parse_response(self, response):
755 self.response_length=int(response.getheader("content-length", 0))
756 return xmlrpclib.Transport.parse_response(self, response)
757
758 def send_content(self, connection, body):
759 if self.fake_gzip:
760 #add a lone gzip header to induce decode error remotely
761 connection.putheader("Content-Encoding", "gzip")
762 return xmlrpclib.Transport.send_content(self, connection, body)
763
Victor Stinnera44b5a32010-04-27 23:14:58 +0000764 def setUp(self):
765 BaseServerTestCase.setUp(self)
766
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000767 def test_gzip_request(self):
768 t = self.Transport()
769 t.encode_threshold = None
770 p = xmlrpclib.ServerProxy(URL, transport=t)
771 self.assertEqual(p.pow(6,8), 6**8)
772 a = self.RequestHandler.content_length
773 t.encode_threshold = 0 #turn on request encoding
774 self.assertEqual(p.pow(6,8), 6**8)
775 b = self.RequestHandler.content_length
776 self.assertTrue(a>b)
777
778 def test_bad_gzip_request(self):
779 t = self.Transport()
780 t.encode_threshold = None
781 t.fake_gzip = True
782 p = xmlrpclib.ServerProxy(URL, transport=t)
783 cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
784 re.compile(r"\b400\b"))
785 with cm:
786 p.pow(6, 8)
787
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500788 def test_gzip_response(self):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000789 t = self.Transport()
790 p = xmlrpclib.ServerProxy(URL, transport=t)
791 old = self.requestHandler.encode_threshold
792 self.requestHandler.encode_threshold = None #no encoding
793 self.assertEqual(p.pow(6,8), 6**8)
794 a = t.response_length
795 self.requestHandler.encode_threshold = 0 #always encode
796 self.assertEqual(p.pow(6,8), 6**8)
797 b = t.response_length
798 self.requestHandler.encode_threshold = old
799 self.assertTrue(a>b)
800
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500801 def test_gzip_decode_limit(self):
802 max_gzip_decode = 20 * 1024 * 1024
803 data = '\0' * max_gzip_decode
804 encoded = xmlrpclib.gzip_encode(data)
805 decoded = xmlrpclib.gzip_decode(encoded)
806 self.assertEqual(len(decoded), max_gzip_decode)
807
808 data = '\0' * (max_gzip_decode + 1)
809 encoded = xmlrpclib.gzip_encode(data)
810
811 with self.assertRaisesRegexp(ValueError,
812 "max gzipped payload length exceeded"):
813 xmlrpclib.gzip_decode(encoded)
814
815 xmlrpclib.gzip_decode(encoded, max_decode=-1)
816
817
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000818#Test special attributes of the ServerProxy object
819class ServerProxyTestCase(unittest.TestCase):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000820 def setUp(self):
821 unittest.TestCase.setUp(self)
822 if threading:
823 self.url = URL
824 else:
825 # Without threading, http_server() and http_multi_server() will not
826 # be executed and URL is still equal to None. 'http://' is a just
827 # enough to choose the scheme (HTTP)
828 self.url = 'http://'
829
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000830 def test_close(self):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000831 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000832 self.assertEqual(p('close')(), None)
833
834 def test_transport(self):
835 t = xmlrpclib.Transport()
Victor Stinnera44b5a32010-04-27 23:14:58 +0000836 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000837 self.assertEqual(p('transport'), t)
838
Facundo Batista7f686fc2007-08-17 19:16:44 +0000839# This is a contrived way to make a failure occur on the server side
840# in order to test the _send_traceback_header flag on the server
841class FailingMessageClass(mimetools.Message):
842 def __getitem__(self, key):
843 key = key.lower()
844 if key == 'content-length':
845 return 'I am broken'
846 return mimetools.Message.__getitem__(self, key)
847
848
Victor Stinnera44b5a32010-04-27 23:14:58 +0000849@unittest.skipUnless(threading, 'Threading required for this test.')
Facundo Batista7f686fc2007-08-17 19:16:44 +0000850class FailingServerTestCase(unittest.TestCase):
851 def setUp(self):
852 self.evt = threading.Event()
853 # start server thread to handle requests
Neal Norwitz162d7192008-03-23 04:08:30 +0000854 serv_args = (self.evt, 1)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000855 threading.Thread(target=http_server, args=serv_args).start()
856
Neal Norwitz653272f2008-01-26 07:26:12 +0000857 # wait for the server to be ready
858 self.evt.wait()
859 self.evt.clear()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000860
861 def tearDown(self):
862 # wait on the server thread to terminate
863 self.evt.wait()
864 # reset flag
865 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
866 # reset message class
867 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message
868
869 def test_basic(self):
870 # check that flag is false by default
871 flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
872 self.assertEqual(flagval, False)
873
Facundo Batistac65a5f12007-08-21 00:16:21 +0000874 # enable traceback reporting
875 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
876
877 # test a call that shouldn't fail just as a smoke test
878 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000879 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000880 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000881 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000882 # ignore failures due to non-blocking socket 'unavailable' errors
883 if not is_unavailable_exception(e):
884 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000885 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batista7f686fc2007-08-17 19:16:44 +0000886
887 def test_fail_no_info(self):
888 # use the broken message class
889 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
890
891 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000892 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000893 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000894 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000895 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000896 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000897 # The two server-side error headers shouldn't be sent back in this case
898 self.assertTrue(e.headers.get("X-exception") is None)
899 self.assertTrue(e.headers.get("X-traceback") is None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000900 else:
901 self.fail('ProtocolError not raised')
902
903 def test_fail_with_info(self):
904 # use the broken message class
905 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
906
907 # Check that errors in the server send back exception/traceback
908 # info when flag is set
909 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
910
911 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000912 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000913 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000914 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000915 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000916 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000917 # We should get error info in the response
918 expected_err = "invalid literal for int() with base 10: 'I am broken'"
919 self.assertEqual(e.headers.get("x-exception"), expected_err)
920 self.assertTrue(e.headers.get("x-traceback") is not None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000921 else:
922 self.fail('ProtocolError not raised')
923
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000924class CGIHandlerTestCase(unittest.TestCase):
925 def setUp(self):
926 self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
927
928 def tearDown(self):
929 self.cgi = None
930
931 def test_cgi_get(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000932 with test_support.EnvironmentVarGuard() as env:
Walter Dörwald6733bed2009-05-01 17:35:37 +0000933 env['REQUEST_METHOD'] = 'GET'
Walter Dörwald4b965f62009-04-26 20:51:44 +0000934 # if the method is GET and no request_text is given, it runs handle_get
935 # get sysout output
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000936 with test_support.captured_stdout() as data_out:
937 self.cgi.handle_request()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000938
Walter Dörwald4b965f62009-04-26 20:51:44 +0000939 # parse Status header
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000940 data_out.seek(0)
941 handle = data_out.read()
Walter Dörwald4b965f62009-04-26 20:51:44 +0000942 status = handle.split()[1]
943 message = ' '.join(handle.split()[2:4])
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000944
Walter Dörwald4b965f62009-04-26 20:51:44 +0000945 self.assertEqual(status, '400')
946 self.assertEqual(message, 'Bad Request')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000947
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000948
949 def test_cgi_xmlrpc_response(self):
950 data = """<?xml version='1.0'?>
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000951 <methodCall>
952 <methodName>test_method</methodName>
953 <params>
954 <param>
955 <value><string>foo</string></value>
956 </param>
957 <param>
958 <value><string>bar</string></value>
959 </param>
960 </params>
961 </methodCall>
962 """
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000963
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000964 with test_support.EnvironmentVarGuard() as env, \
965 test_support.captured_stdout() as data_out, \
966 test_support.captured_stdin() as data_in:
967 data_in.write(data)
968 data_in.seek(0)
Walter Dörwald6733bed2009-05-01 17:35:37 +0000969 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandl61fce382009-04-01 15:23:43 +0000970 self.cgi.handle_request()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000971 data_out.seek(0)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000972
973 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000974 handle = data_out.read()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000975
976 # start with 44th char so as not to get http header, we just need only xml
977 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
978
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000979 # Also test the content-length returned by handle_request
980 # Using the same test method inorder to avoid all the datapassing
981 # boilerplate code.
982 # Test for bug: http://bugs.python.org/issue5040
983
984 content = handle[handle.find("<?xml"):]
985
Ezio Melotti2623a372010-11-21 13:34:58 +0000986 self.assertEqual(
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000987 int(re.search('Content-Length: (\d+)', handle).group(1)),
988 len(content))
989
990
Jeremy Hylton89420112008-11-24 22:00:29 +0000991class FakeSocket:
992
993 def __init__(self):
994 self.data = StringIO.StringIO()
995
996 def send(self, buf):
997 self.data.write(buf)
998 return len(buf)
999
1000 def sendall(self, buf):
1001 self.data.write(buf)
1002
1003 def getvalue(self):
1004 return self.data.getvalue()
1005
Kristján Valur Jónsson3c43fcb2009-01-11 16:23:37 +00001006 def makefile(self, x='r', y=-1):
Jeremy Hylton89420112008-11-24 22:00:29 +00001007 raise RuntimeError
1008
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001009 def close(self):
1010 pass
1011
Jeremy Hylton89420112008-11-24 22:00:29 +00001012class FakeTransport(xmlrpclib.Transport):
1013 """A Transport instance that records instead of sending a request.
1014
1015 This class replaces the actual socket used by httplib with a
1016 FakeSocket object that records the request. It doesn't provide a
1017 response.
1018 """
1019
1020 def make_connection(self, host):
1021 conn = xmlrpclib.Transport.make_connection(self, host)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001022 conn.sock = self.fake_socket = FakeSocket()
Jeremy Hylton89420112008-11-24 22:00:29 +00001023 return conn
1024
1025class TransportSubclassTestCase(unittest.TestCase):
1026
1027 def issue_request(self, transport_class):
1028 """Return an HTTP request made via transport_class."""
1029 transport = transport_class()
1030 proxy = xmlrpclib.ServerProxy("http://example.com/",
1031 transport=transport)
1032 try:
1033 proxy.pow(6, 8)
1034 except RuntimeError:
1035 return transport.fake_socket.getvalue()
1036 return None
1037
1038 def test_custom_user_agent(self):
1039 class TestTransport(FakeTransport):
1040
1041 def send_user_agent(self, conn):
1042 xmlrpclib.Transport.send_user_agent(self, conn)
1043 conn.putheader("X-Test", "test_custom_user_agent")
1044
1045 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001046 self.assertIn("X-Test: test_custom_user_agent\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001047
1048 def test_send_host(self):
1049 class TestTransport(FakeTransport):
1050
1051 def send_host(self, conn, host):
1052 xmlrpclib.Transport.send_host(self, conn, host)
1053 conn.putheader("X-Test", "test_send_host")
1054
1055 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001056 self.assertIn("X-Test: test_send_host\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001057
1058 def test_send_request(self):
1059 class TestTransport(FakeTransport):
1060
1061 def send_request(self, conn, url, body):
1062 xmlrpclib.Transport.send_request(self, conn, url, body)
1063 conn.putheader("X-Test", "test_send_request")
1064
1065 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001066 self.assertIn("X-Test: test_send_request\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001067
1068 def test_send_content(self):
1069 class TestTransport(FakeTransport):
1070
1071 def send_content(self, conn, body):
1072 conn.putheader("X-Test", "test_send_content")
1073 xmlrpclib.Transport.send_content(self, conn, body)
1074
1075 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001076 self.assertIn("X-Test: test_send_content\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001077
Antoine Pitrou3c968582009-10-30 17:56:00 +00001078@test_support.reap_threads
Facundo Batistaa53872b2007-08-14 13:35:00 +00001079def test_main():
1080 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
Jeremy Hylton89420112008-11-24 22:00:29 +00001081 BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001082 xmlrpc_tests.append(SimpleServerTestCase)
Serhiy Storchaka27d9c3d2016-01-18 19:38:53 +02001083 xmlrpc_tests.append(SimpleServerEncodingTestCase)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +00001084 xmlrpc_tests.append(KeepaliveServerTestCase1)
1085 xmlrpc_tests.append(KeepaliveServerTestCase2)
Zachary Ware1f702212013-12-10 14:09:20 -06001086 xmlrpc_tests.append(GzipServerTestCase)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +00001087 xmlrpc_tests.append(MultiPathServerTestCase)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001088 xmlrpc_tests.append(ServerProxyTestCase)
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001089 xmlrpc_tests.append(FailingServerTestCase)
1090 xmlrpc_tests.append(CGIHandlerTestCase)
Facundo Batistaa53872b2007-08-14 13:35:00 +00001091
1092 test_support.run_unittest(*xmlrpc_tests)
Skip Montanaro419abda2001-10-01 17:47:44 +00001093
1094if __name__ == "__main__":
1095 test_main()