blob: 2bb3978b844f4febbf4e013d094de94b4255f35b [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
26try:
Fred Drake22c07062005-02-11 17:59:08 +000027 unicode
28except NameError:
29 have_unicode = False
30else:
31 have_unicode = True
32
Skip Montanaro419abda2001-10-01 17:47:44 +000033alist = [{'astring': 'foo@bar.baz.spam',
34 'afloat': 7283.43,
Skip Montanaro3e7bba92001-10-19 16:06:52 +000035 'anint': 2**20,
36 'ashortlong': 2L,
Skip Montanaro419abda2001-10-01 17:47:44 +000037 'anotherlist': ['.zyx.41'],
38 'abase64': xmlrpclib.Binary("my dog has fleas"),
39 'boolean': xmlrpclib.False,
Andrew M. Kuchlingb12d97c2004-06-05 12:33:27 +000040 'unicode': u'\u4000\u6000\u8000',
41 u'ukey\u4000': 'regular value',
Fred Drakeba613c32005-02-10 18:33:30 +000042 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
43 'datetime2': xmlrpclib.DateTime(
44 (2005, 02, 10, 11, 41, 23, 0, 1, -1)),
45 'datetime3': xmlrpclib.DateTime(
46 datetime.datetime(2005, 02, 10, 11, 41, 23)),
Skip Montanaro419abda2001-10-01 17:47:44 +000047 }]
48
49class XMLRPCTestCase(unittest.TestCase):
50
51 def test_dump_load(self):
Ezio Melotti2623a372010-11-21 13:34:58 +000052 self.assertEqual(alist,
53 xmlrpclib.loads(xmlrpclib.dumps((alist,)))[0][0])
Skip Montanaro419abda2001-10-01 17:47:44 +000054
Fred Drakeba613c32005-02-10 18:33:30 +000055 def test_dump_bare_datetime(self):
Skip Montanaro174dd222005-05-14 20:54:16 +000056 # This checks that an unwrapped datetime.date object can be handled
57 # by the marshalling code. This can't be done via test_dump_load()
58 # since with use_datetime set to 1 the unmarshaller would create
59 # datetime objects for the 'datetime[123]' keys as well
Fred Drakeba613c32005-02-10 18:33:30 +000060 dt = datetime.datetime(2005, 02, 10, 11, 41, 23)
61 s = xmlrpclib.dumps((dt,))
Skip Montanaro174dd222005-05-14 20:54:16 +000062 (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
Ezio Melotti2623a372010-11-21 13:34:58 +000063 self.assertEqual(newdt, dt)
64 self.assertEqual(m, None)
Fred Drakeba613c32005-02-10 18:33:30 +000065
Skip Montanaro174dd222005-05-14 20:54:16 +000066 (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
Ezio Melotti2623a372010-11-21 13:34:58 +000067 self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
Skip Montanaro174dd222005-05-14 20:54:16 +000068
Skip Montanarob131f042008-04-18 20:35:46 +000069 def test_datetime_before_1900(self):
Andrew M. Kuchlinga5489d42008-04-21 01:45:57 +000070 # same as before but with a date before 1900
Skip Montanarob131f042008-04-18 20:35:46 +000071 dt = datetime.datetime(1, 02, 10, 11, 41, 23)
72 s = xmlrpclib.dumps((dt,))
73 (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
Ezio Melotti2623a372010-11-21 13:34:58 +000074 self.assertEqual(newdt, dt)
75 self.assertEqual(m, None)
Skip Montanarob131f042008-04-18 20:35:46 +000076
77 (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
Ezio Melotti2623a372010-11-21 13:34:58 +000078 self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23'))
Skip Montanarob131f042008-04-18 20:35:46 +000079
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000080 def test_cmp_datetime_DateTime(self):
81 now = datetime.datetime.now()
82 dt = xmlrpclib.DateTime(now.timetuple())
Benjamin Peterson5c8da862009-06-30 22:57:08 +000083 self.assertTrue(dt == now)
84 self.assertTrue(now == dt)
Andrew M. Kuchling085f75a2008-02-23 16:23:05 +000085 then = now + datetime.timedelta(seconds=4)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000086 self.assertTrue(then >= dt)
87 self.assertTrue(dt < then)
Skip Montanaro174dd222005-05-14 20:54:16 +000088
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000089 def test_bug_1164912 (self):
90 d = xmlrpclib.DateTime()
Tim Peters536cf992005-12-25 23:18:31 +000091 ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000092 methodresponse=True))
Ezio Melottib0f5adc2010-01-24 16:58:36 +000093 self.assertIsInstance(new_d.value, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000094
95 # Check that the output of dumps() is still an 8-bit string
96 s = xmlrpclib.dumps((new_d,), methodresponse=True)
Ezio Melottib0f5adc2010-01-24 16:58:36 +000097 self.assertIsInstance(s, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +000098
Martin v. Löwis07529352006-11-19 18:51:54 +000099 def test_newstyle_class(self):
100 class T(object):
101 pass
102 t = T()
103 t.x = 100
104 t.y = "Hello"
105 ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
Ezio Melotti2623a372010-11-21 13:34:58 +0000106 self.assertEqual(t2, t.__dict__)
Martin v. Löwis07529352006-11-19 18:51:54 +0000107
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000108 def test_dump_big_long(self):
109 self.assertRaises(OverflowError, xmlrpclib.dumps, (2L**99,))
110
111 def test_dump_bad_dict(self):
112 self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))
113
Facundo Batista5a3b5242007-07-13 10:43:44 +0000114 def test_dump_recursive_seq(self):
115 l = [1,2,3]
116 t = [3,4,5,l]
117 l.append(t)
118 self.assertRaises(TypeError, xmlrpclib.dumps, (l,))
119
120 def test_dump_recursive_dict(self):
121 d = {'1':1, '2':1}
122 t = {'3':3, 'd':d}
123 d['t'] = t
124 self.assertRaises(TypeError, xmlrpclib.dumps, (d,))
125
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000126 def test_dump_big_int(self):
127 if sys.maxint > 2L**31-1:
128 self.assertRaises(OverflowError, xmlrpclib.dumps,
129 (int(2L**34),))
130
Facundo Batista5a3b5242007-07-13 10:43:44 +0000131 xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
132 self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,))
133 self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,))
134
135 def dummy_write(s):
136 pass
137
138 m = xmlrpclib.Marshaller()
139 m.dump_int(xmlrpclib.MAXINT, dummy_write)
140 m.dump_int(xmlrpclib.MININT, dummy_write)
141 self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write)
142 self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write)
143
144
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000145 def test_dump_none(self):
146 value = alist + [None]
147 arg1 = (alist + [None],)
148 strg = xmlrpclib.dumps(arg1, allow_none=True)
Ezio Melotti2623a372010-11-21 13:34:58 +0000149 self.assertEqual(value,
150 xmlrpclib.loads(strg)[0][0])
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000151 self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
152
Fred Drake22c07062005-02-11 17:59:08 +0000153 def test_default_encoding_issues(self):
154 # SF bug #1115989: wrong decoding in '_stringify'
155 utf8 = """<?xml version='1.0' encoding='iso-8859-1'?>
156 <params>
157 <param><value>
158 <string>abc \x95</string>
159 </value></param>
160 <param><value>
161 <struct>
162 <member>
163 <name>def \x96</name>
164 <value><string>ghi \x97</string></value>
165 </member>
166 </struct>
167 </value></param>
168 </params>
169 """
Tim Petersf754f5f2005-04-08 18:00:59 +0000170
171 # sys.setdefaultencoding() normally doesn't exist after site.py is
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000172 # loaded. Import a temporary fresh copy to get access to it
173 # but then restore the original copy to avoid messing with
174 # other potentially modified sys module attributes
Fred Drake22c07062005-02-11 17:59:08 +0000175 old_encoding = sys.getdefaultencoding()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000176 with test_support.CleanImport('sys'):
177 import sys as temp_sys
178 temp_sys.setdefaultencoding("iso-8859-1")
179 try:
180 (s, d), m = xmlrpclib.loads(utf8)
181 finally:
182 temp_sys.setdefaultencoding(old_encoding)
Tim Petersf754f5f2005-04-08 18:00:59 +0000183
Fred Drake22c07062005-02-11 17:59:08 +0000184 items = d.items()
185 if have_unicode:
Ezio Melotti2623a372010-11-21 13:34:58 +0000186 self.assertEqual(s, u"abc \x95")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000187 self.assertIsInstance(s, unicode)
Ezio Melotti2623a372010-11-21 13:34:58 +0000188 self.assertEqual(items, [(u"def \x96", u"ghi \x97")])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000189 self.assertIsInstance(items[0][0], unicode)
190 self.assertIsInstance(items[0][1], unicode)
Fred Drake22c07062005-02-11 17:59:08 +0000191 else:
Ezio Melotti2623a372010-11-21 13:34:58 +0000192 self.assertEqual(s, "abc \xc2\x95")
193 self.assertEqual(items, [("def \xc2\x96", "ghi \xc2\x97")])
Fred Drake22c07062005-02-11 17:59:08 +0000194
Facundo Batista5a3b5242007-07-13 10:43:44 +0000195
196class HelperTestCase(unittest.TestCase):
197 def test_escape(self):
198 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
199 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
200 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
201
202class FaultTestCase(unittest.TestCase):
203 def test_repr(self):
204 f = xmlrpclib.Fault(42, 'Test Fault')
205 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
206 self.assertEqual(repr(f), str(f))
207
208 def test_dump_fault(self):
209 f = xmlrpclib.Fault(42, 'Test Fault')
210 s = xmlrpclib.dumps((f,))
211 (newf,), m = xmlrpclib.loads(s)
Ezio Melotti2623a372010-11-21 13:34:58 +0000212 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
213 self.assertEqual(m, None)
Facundo Batista5a3b5242007-07-13 10:43:44 +0000214
215 s = xmlrpclib.Marshaller().dumps(f)
216 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
217
218
219class DateTimeTestCase(unittest.TestCase):
220 def test_default(self):
221 t = xmlrpclib.DateTime()
222
223 def test_time(self):
224 d = 1181399930.036952
225 t = xmlrpclib.DateTime(d)
226 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
227
228 def test_time_tuple(self):
229 d = (2007,6,9,10,38,50,5,160,0)
230 t = xmlrpclib.DateTime(d)
231 self.assertEqual(str(t), '20070609T10:38:50')
232
233 def test_time_struct(self):
234 d = time.localtime(1181399930.036952)
235 t = xmlrpclib.DateTime(d)
236 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
237
238 def test_datetime_datetime(self):
239 d = datetime.datetime(2007,1,2,3,4,5)
240 t = xmlrpclib.DateTime(d)
241 self.assertEqual(str(t), '20070102T03:04:05')
242
Facundo Batista5a3b5242007-07-13 10:43:44 +0000243 def test_repr(self):
244 d = datetime.datetime(2007,1,2,3,4,5)
245 t = xmlrpclib.DateTime(d)
246 val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
247 self.assertEqual(repr(t), val)
248
249 def test_decode(self):
250 d = ' 20070908T07:11:13 '
251 t1 = xmlrpclib.DateTime()
252 t1.decode(d)
253 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
254 self.assertEqual(t1, tref)
255
256 t2 = xmlrpclib._datetime(d)
257 self.assertEqual(t1, tref)
258
259class BinaryTestCase(unittest.TestCase):
260 def test_default(self):
261 t = xmlrpclib.Binary()
262 self.assertEqual(str(t), '')
263
264 def test_string(self):
265 d = '\x01\x02\x03abc123\xff\xfe'
266 t = xmlrpclib.Binary(d)
267 self.assertEqual(str(t), d)
268
269 def test_decode(self):
270 d = '\x01\x02\x03abc123\xff\xfe'
271 de = base64.encodestring(d)
272 t1 = xmlrpclib.Binary()
273 t1.decode(de)
274 self.assertEqual(str(t1), d)
275
276 t2 = xmlrpclib._binary(de)
277 self.assertEqual(str(t2), d)
278
279
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000280ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000281
Neal Norwitz653272f2008-01-26 07:26:12 +0000282# The evt is set twice. First when the server is ready to serve.
283# Second when the server has been shutdown. The user must clear
284# the event after it has been set the first time to catch the second set.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000285def http_server(evt, numrequests, requestHandler=None):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000286 class TestInstanceClass:
287 def div(self, x, y):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000288 return x // y
289
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000290 def _methodHelp(self, name):
291 if name == 'div':
292 return 'This is the div function'
293
294 def my_function():
295 '''This is my function'''
296 return True
297
Neal Norwitz70cea582008-03-28 06:34:03 +0000298 class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
299 def get_request(self):
300 # Ensure the socket is always non-blocking. On Linux, socket
301 # attributes are not inherited like they are on *BSD and Windows.
302 s, port = self.socket.accept()
303 s.setblocking(True)
304 return s, port
305
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000306 if not requestHandler:
307 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
308 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000309 logRequests=False, bind_and_activate=False)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000310 try:
311 serv.socket.settimeout(3)
312 serv.server_bind()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000313 global ADDR, PORT, URL
314 ADDR, PORT = serv.socket.getsockname()
315 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300316 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000317 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
318 #on AF_INET only.
319 URL = "http://%s:%d"%(ADDR, PORT)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000320 serv.server_activate()
321 serv.register_introspection_functions()
322 serv.register_multicall_functions()
323 serv.register_function(pow)
324 serv.register_function(lambda x,y: x+y, 'add')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000325 serv.register_function(my_function)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000326 serv.register_instance(TestInstanceClass())
Neal Norwitz653272f2008-01-26 07:26:12 +0000327 evt.set()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000328
329 # handle up to 'numrequests' requests
330 while numrequests > 0:
331 serv.handle_request()
332 numrequests -= 1
333
334 except socket.timeout:
335 pass
336 finally:
337 serv.socket.close()
338 PORT = None
339 evt.set()
340
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000341def http_multi_server(evt, numrequests, requestHandler=None):
342 class TestInstanceClass:
343 def div(self, x, y):
344 return x // y
345
346 def _methodHelp(self, name):
347 if name == 'div':
348 return 'This is the div function'
349
350 def my_function():
351 '''This is my function'''
352 return True
353
354 class MyXMLRPCServer(SimpleXMLRPCServer.MultiPathXMLRPCServer):
355 def get_request(self):
356 # Ensure the socket is always non-blocking. On Linux, socket
357 # attributes are not inherited like they are on *BSD and Windows.
358 s, port = self.socket.accept()
359 s.setblocking(True)
360 return s, port
361
362 if not requestHandler:
363 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
364 class MyRequestHandler(requestHandler):
365 rpc_paths = []
366
367 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
368 logRequests=False, bind_and_activate=False)
369 serv.socket.settimeout(3)
370 serv.server_bind()
371 try:
372 global ADDR, PORT, URL
373 ADDR, PORT = serv.socket.getsockname()
374 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300375 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000376 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
377 #on AF_INET only.
378 URL = "http://%s:%d"%(ADDR, PORT)
379 serv.server_activate()
380 paths = ["/foo", "/foo/bar"]
381 for path in paths:
382 d = serv.add_dispatcher(path, SimpleXMLRPCServer.SimpleXMLRPCDispatcher())
383 d.register_introspection_functions()
384 d.register_multicall_functions()
385 serv.get_dispatcher(paths[0]).register_function(pow)
386 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
387 evt.set()
388
389 # handle up to 'numrequests' requests
390 while numrequests > 0:
391 serv.handle_request()
392 numrequests -= 1
393
394 except socket.timeout:
395 pass
396 finally:
397 serv.socket.close()
398 PORT = None
399 evt.set()
400
Neal Norwitz08b50eb2008-01-26 08:26:00 +0000401# This function prevents errors like:
402# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000403def is_unavailable_exception(e):
404 '''Returns True if the given ProtocolError is the product of a server-side
405 exception caused by the 'temporarily unavailable' response sometimes
406 given by operations on non-blocking sockets.'''
Neal Norwitz653272f2008-01-26 07:26:12 +0000407
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000408 # sometimes we get a -1 error code and/or empty headers
Neal Norwitzed444e52008-01-27 18:19:04 +0000409 try:
410 if e.errcode == -1 or e.headers is None:
411 return True
412 exc_mess = e.headers.get('X-exception')
413 except AttributeError:
414 # Ignore socket.errors here.
415 exc_mess = str(e)
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000416
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000417 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
418 return True
419
420 return False
421
Victor Stinnera44b5a32010-04-27 23:14:58 +0000422@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000423class BaseServerTestCase(unittest.TestCase):
424 requestHandler = None
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000425 request_count = 1
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000426 threadFunc = staticmethod(http_server)
Victor Stinnera44b5a32010-04-27 23:14:58 +0000427
Facundo Batistaa53872b2007-08-14 13:35:00 +0000428 def setUp(self):
Facundo Batista7f686fc2007-08-17 19:16:44 +0000429 # enable traceback reporting
430 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
431
Facundo Batistaa53872b2007-08-14 13:35:00 +0000432 self.evt = threading.Event()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000433 # start server thread to handle requests
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000434 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000435 threading.Thread(target=self.threadFunc, args=serv_args).start()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000436
Neal Norwitz653272f2008-01-26 07:26:12 +0000437 # wait for the server to be ready
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000438 self.evt.wait(10)
Neal Norwitz653272f2008-01-26 07:26:12 +0000439 self.evt.clear()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000440
441 def tearDown(self):
442 # wait on the server thread to terminate
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000443 self.evt.wait(10)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000444
Facundo Batista7f686fc2007-08-17 19:16:44 +0000445 # disable traceback reporting
446 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
447
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000448# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
449# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
450# condition occurs infrequently on some platforms, frequently on others, and
451# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket
452# If the server class is updated at some point in the future to handle this
453# situation more gracefully, these tests should be modified appropriately.
454
455class SimpleServerTestCase(BaseServerTestCase):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000456 def test_simple1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000457 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000458 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000459 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000460 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000461 # ignore failures due to non-blocking socket 'unavailable' errors
462 if not is_unavailable_exception(e):
463 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000464 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000465
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000466 def test_nonascii(self):
467 start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
468 end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
469
470 try:
471 p = xmlrpclib.ServerProxy(URL)
472 self.assertEqual(p.add(start_string, end_string),
473 start_string + end_string)
474 except (xmlrpclib.ProtocolError, socket.error) as e:
475 # ignore failures due to non-blocking socket unavailable errors.
476 if not is_unavailable_exception(e):
477 # protocol error; provide additional information in test output
478 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
479
Victor Stinner51b71982011-09-23 01:15:32 +0200480 def test_unicode_host(self):
481 server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
482 self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000483
Christian Heimes6c29be52008-01-19 16:39:27 +0000484 # [ch] The test 404 is causing lots of false alarms.
485 def XXXtest_404(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000486 # send POST with httplib, it should return 404 header and
487 # 'Not Found' message.
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000488 conn = httplib.HTTPConnection(ADDR, PORT)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000489 conn.request('POST', '/this-is-not-valid')
490 response = conn.getresponse()
491 conn.close()
492
493 self.assertEqual(response.status, 404)
494 self.assertEqual(response.reason, 'Not Found')
495
Facundo Batistaa53872b2007-08-14 13:35:00 +0000496 def test_introspection1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000497 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000498 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000499 meth = p.system.listMethods()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000500 expected_methods = set(['pow', 'div', 'my_function', 'add',
501 'system.listMethods', 'system.methodHelp',
502 'system.methodSignature', 'system.multicall'])
Facundo Batistac65a5f12007-08-21 00:16:21 +0000503 self.assertEqual(set(meth), expected_methods)
Neal Norwitz183c5342008-01-27 17:11:11 +0000504 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000505 # ignore failures due to non-blocking socket 'unavailable' errors
506 if not is_unavailable_exception(e):
507 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000508 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000509
510 def test_introspection2(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000511 try:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000512 # test _methodHelp()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000513 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000514 divhelp = p.system.methodHelp('div')
515 self.assertEqual(divhelp, 'This is the div function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000516 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000517 # ignore failures due to non-blocking socket 'unavailable' errors
518 if not is_unavailable_exception(e):
519 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000520 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000521
R. David Murrayf28fd242010-02-23 00:24:49 +0000522 @unittest.skipIf(sys.flags.optimize >= 2,
523 "Docstrings are omitted with -O2 and above")
Facundo Batistaa53872b2007-08-14 13:35:00 +0000524 def test_introspection3(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000525 try:
526 # test native doc
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000527 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000528 myfunction = p.system.methodHelp('my_function')
529 self.assertEqual(myfunction, 'This is my function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000530 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000531 # ignore failures due to non-blocking socket 'unavailable' errors
532 if not is_unavailable_exception(e):
533 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000534 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000535
536 def test_introspection4(self):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000537 # the SimpleXMLRPCServer doesn't support signatures, but
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000538 # at least check that we can try making the call
Facundo Batistac65a5f12007-08-21 00:16:21 +0000539 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000540 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000541 divsig = p.system.methodSignature('div')
542 self.assertEqual(divsig, 'signatures not supported')
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
549 def test_multicall(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000550 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000551 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000552 multicall = xmlrpclib.MultiCall(p)
553 multicall.add(2,3)
554 multicall.pow(6,8)
555 multicall.div(127,42)
556 add_result, pow_result, div_result = multicall()
557 self.assertEqual(add_result, 2+3)
558 self.assertEqual(pow_result, 6**8)
559 self.assertEqual(div_result, 127//42)
Neal Norwitz183c5342008-01-27 17:11:11 +0000560 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000561 # ignore failures due to non-blocking socket 'unavailable' errors
562 if not is_unavailable_exception(e):
563 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000564 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000565
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000566 def test_non_existing_multicall(self):
567 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000568 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000569 multicall = xmlrpclib.MultiCall(p)
570 multicall.this_is_not_exists()
571 result = multicall()
572
573 # result.results contains;
574 # [{'faultCode': 1, 'faultString': '<type \'exceptions.Exception\'>:'
575 # 'method "this_is_not_exists" is not supported'>}]
576
577 self.assertEqual(result.results[0]['faultCode'], 1)
578 self.assertEqual(result.results[0]['faultString'],
579 '<type \'exceptions.Exception\'>:method "this_is_not_exists" '
580 'is not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000581 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000582 # ignore failures due to non-blocking socket 'unavailable' errors
583 if not is_unavailable_exception(e):
584 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000585 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000586
587 def test_dotted_attribute(self):
Neal Norwitz162d7192008-03-23 04:08:30 +0000588 # Raises an AttributeError because private methods are not allowed.
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000589 self.assertRaises(AttributeError,
590 SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')
591
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000592 self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
Neal Norwitz162d7192008-03-23 04:08:30 +0000593 # Get the test to run faster by sending a request with test_simple1.
594 # This avoids waiting for the socket timeout.
595 self.test_simple1()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000596
Charles-François Natalie0624662012-02-18 14:30:34 +0100597 def test_partial_post(self):
598 # Check that a partial POST doesn't make the server loop: issue #14001.
599 conn = httplib.HTTPConnection(ADDR, PORT)
600 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
601 conn.close()
602
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000603class MultiPathServerTestCase(BaseServerTestCase):
604 threadFunc = staticmethod(http_multi_server)
605 request_count = 2
606 def test_path1(self):
607 p = xmlrpclib.ServerProxy(URL+"/foo")
608 self.assertEqual(p.pow(6,8), 6**8)
609 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
610 def test_path2(self):
611 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
612 self.assertEqual(p.add(6,8), 6+8)
613 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
614
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000615#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
616#does indeed serve subsequent requests on the same connection
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000617class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000618 #a request handler that supports keep-alive and logs requests into a
619 #class variable
620 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
621 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
622 protocol_version = 'HTTP/1.1'
623 myRequests = []
624 def handle(self):
625 self.myRequests.append([])
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000626 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000627 return self.parentClass.handle(self)
628 def handle_one_request(self):
629 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000630 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000631 return result
632
633 requestHandler = RequestHandler
634 def setUp(self):
635 #clear request log
636 self.RequestHandler.myRequests = []
637 return BaseServerTestCase.setUp(self)
638
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000639#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
640#does indeed serve subsequent requests on the same connection
641class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000642 def test_two(self):
643 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000644 #do three requests.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000645 self.assertEqual(p.pow(6,8), 6**8)
646 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000647 self.assertEqual(p.pow(6,8), 6**8)
648
649 #they should have all been handled by a single request handler
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000650 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000651
652 #check that we did at least two (the third may be pending append
653 #due to thread scheduling)
654 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000655
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000656#test special attribute access on the serverproxy, through the __call__
657#function.
658class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
659 #ask for two keepalive requests to be handled.
660 request_count=2
661
662 def test_close(self):
663 p = xmlrpclib.ServerProxy(URL)
664 #do some requests with close.
665 self.assertEqual(p.pow(6,8), 6**8)
666 self.assertEqual(p.pow(6,8), 6**8)
667 self.assertEqual(p.pow(6,8), 6**8)
668 p("close")() #this should trigger a new keep-alive request
669 self.assertEqual(p.pow(6,8), 6**8)
670 self.assertEqual(p.pow(6,8), 6**8)
671 self.assertEqual(p.pow(6,8), 6**8)
672
673 #they should have all been two request handlers, each having logged at least
674 #two complete requests
675 self.assertEqual(len(self.RequestHandler.myRequests), 2)
676 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
677 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
678
679 def test_transport(self):
680 p = xmlrpclib.ServerProxy(URL)
681 #do some requests with close.
682 self.assertEqual(p.pow(6,8), 6**8)
683 p("transport").close() #same as above, really.
684 self.assertEqual(p.pow(6,8), 6**8)
685 self.assertEqual(len(self.RequestHandler.myRequests), 2)
686
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000687#A test case that verifies that gzip encoding works in both directions
688#(for a request and the response)
Zachary Ware1f702212013-12-10 14:09:20 -0600689@unittest.skipUnless(gzip, 'gzip not available')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000690class GzipServerTestCase(BaseServerTestCase):
691 #a request handler that supports keep-alive and logs requests into a
692 #class variable
693 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
694 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
695 protocol_version = 'HTTP/1.1'
696
697 def do_POST(self):
698 #store content of last request in class
699 self.__class__.content_length = int(self.headers["content-length"])
700 return self.parentClass.do_POST(self)
701 requestHandler = RequestHandler
702
703 class Transport(xmlrpclib.Transport):
704 #custom transport, stores the response length for our perusal
705 fake_gzip = False
706 def parse_response(self, response):
707 self.response_length=int(response.getheader("content-length", 0))
708 return xmlrpclib.Transport.parse_response(self, response)
709
710 def send_content(self, connection, body):
711 if self.fake_gzip:
712 #add a lone gzip header to induce decode error remotely
713 connection.putheader("Content-Encoding", "gzip")
714 return xmlrpclib.Transport.send_content(self, connection, body)
715
Victor Stinnera44b5a32010-04-27 23:14:58 +0000716 def setUp(self):
717 BaseServerTestCase.setUp(self)
718
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000719 def test_gzip_request(self):
720 t = self.Transport()
721 t.encode_threshold = None
722 p = xmlrpclib.ServerProxy(URL, transport=t)
723 self.assertEqual(p.pow(6,8), 6**8)
724 a = self.RequestHandler.content_length
725 t.encode_threshold = 0 #turn on request encoding
726 self.assertEqual(p.pow(6,8), 6**8)
727 b = self.RequestHandler.content_length
728 self.assertTrue(a>b)
729
730 def test_bad_gzip_request(self):
731 t = self.Transport()
732 t.encode_threshold = None
733 t.fake_gzip = True
734 p = xmlrpclib.ServerProxy(URL, transport=t)
735 cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
736 re.compile(r"\b400\b"))
737 with cm:
738 p.pow(6, 8)
739
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500740 def test_gzip_response(self):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000741 t = self.Transport()
742 p = xmlrpclib.ServerProxy(URL, transport=t)
743 old = self.requestHandler.encode_threshold
744 self.requestHandler.encode_threshold = None #no encoding
745 self.assertEqual(p.pow(6,8), 6**8)
746 a = t.response_length
747 self.requestHandler.encode_threshold = 0 #always encode
748 self.assertEqual(p.pow(6,8), 6**8)
749 b = t.response_length
750 self.requestHandler.encode_threshold = old
751 self.assertTrue(a>b)
752
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500753 def test_gzip_decode_limit(self):
754 max_gzip_decode = 20 * 1024 * 1024
755 data = '\0' * max_gzip_decode
756 encoded = xmlrpclib.gzip_encode(data)
757 decoded = xmlrpclib.gzip_decode(encoded)
758 self.assertEqual(len(decoded), max_gzip_decode)
759
760 data = '\0' * (max_gzip_decode + 1)
761 encoded = xmlrpclib.gzip_encode(data)
762
763 with self.assertRaisesRegexp(ValueError,
764 "max gzipped payload length exceeded"):
765 xmlrpclib.gzip_decode(encoded)
766
767 xmlrpclib.gzip_decode(encoded, max_decode=-1)
768
769
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000770#Test special attributes of the ServerProxy object
771class ServerProxyTestCase(unittest.TestCase):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000772 def setUp(self):
773 unittest.TestCase.setUp(self)
774 if threading:
775 self.url = URL
776 else:
777 # Without threading, http_server() and http_multi_server() will not
778 # be executed and URL is still equal to None. 'http://' is a just
779 # enough to choose the scheme (HTTP)
780 self.url = 'http://'
781
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000782 def test_close(self):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000783 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000784 self.assertEqual(p('close')(), None)
785
786 def test_transport(self):
787 t = xmlrpclib.Transport()
Victor Stinnera44b5a32010-04-27 23:14:58 +0000788 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000789 self.assertEqual(p('transport'), t)
790
Facundo Batista7f686fc2007-08-17 19:16:44 +0000791# This is a contrived way to make a failure occur on the server side
792# in order to test the _send_traceback_header flag on the server
793class FailingMessageClass(mimetools.Message):
794 def __getitem__(self, key):
795 key = key.lower()
796 if key == 'content-length':
797 return 'I am broken'
798 return mimetools.Message.__getitem__(self, key)
799
800
Victor Stinnera44b5a32010-04-27 23:14:58 +0000801@unittest.skipUnless(threading, 'Threading required for this test.')
Facundo Batista7f686fc2007-08-17 19:16:44 +0000802class FailingServerTestCase(unittest.TestCase):
803 def setUp(self):
804 self.evt = threading.Event()
805 # start server thread to handle requests
Neal Norwitz162d7192008-03-23 04:08:30 +0000806 serv_args = (self.evt, 1)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000807 threading.Thread(target=http_server, args=serv_args).start()
808
Neal Norwitz653272f2008-01-26 07:26:12 +0000809 # wait for the server to be ready
810 self.evt.wait()
811 self.evt.clear()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000812
813 def tearDown(self):
814 # wait on the server thread to terminate
815 self.evt.wait()
816 # reset flag
817 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
818 # reset message class
819 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message
820
821 def test_basic(self):
822 # check that flag is false by default
823 flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
824 self.assertEqual(flagval, False)
825
Facundo Batistac65a5f12007-08-21 00:16:21 +0000826 # enable traceback reporting
827 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
828
829 # test a call that shouldn't fail just as a smoke test
830 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000831 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000832 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000833 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000834 # ignore failures due to non-blocking socket 'unavailable' errors
835 if not is_unavailable_exception(e):
836 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000837 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batista7f686fc2007-08-17 19:16:44 +0000838
839 def test_fail_no_info(self):
840 # use the broken message class
841 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
842
843 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000844 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000845 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000846 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000847 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000848 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000849 # The two server-side error headers shouldn't be sent back in this case
850 self.assertTrue(e.headers.get("X-exception") is None)
851 self.assertTrue(e.headers.get("X-traceback") is None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000852 else:
853 self.fail('ProtocolError not raised')
854
855 def test_fail_with_info(self):
856 # use the broken message class
857 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
858
859 # Check that errors in the server send back exception/traceback
860 # info when flag is set
861 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
862
863 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000864 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000865 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000866 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000867 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000868 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000869 # We should get error info in the response
870 expected_err = "invalid literal for int() with base 10: 'I am broken'"
871 self.assertEqual(e.headers.get("x-exception"), expected_err)
872 self.assertTrue(e.headers.get("x-traceback") is not None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000873 else:
874 self.fail('ProtocolError not raised')
875
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000876class CGIHandlerTestCase(unittest.TestCase):
877 def setUp(self):
878 self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
879
880 def tearDown(self):
881 self.cgi = None
882
883 def test_cgi_get(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000884 with test_support.EnvironmentVarGuard() as env:
Walter Dörwald6733bed2009-05-01 17:35:37 +0000885 env['REQUEST_METHOD'] = 'GET'
Walter Dörwald4b965f62009-04-26 20:51:44 +0000886 # if the method is GET and no request_text is given, it runs handle_get
887 # get sysout output
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000888 with test_support.captured_stdout() as data_out:
889 self.cgi.handle_request()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000890
Walter Dörwald4b965f62009-04-26 20:51:44 +0000891 # parse Status header
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000892 data_out.seek(0)
893 handle = data_out.read()
Walter Dörwald4b965f62009-04-26 20:51:44 +0000894 status = handle.split()[1]
895 message = ' '.join(handle.split()[2:4])
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000896
Walter Dörwald4b965f62009-04-26 20:51:44 +0000897 self.assertEqual(status, '400')
898 self.assertEqual(message, 'Bad Request')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000899
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000900
901 def test_cgi_xmlrpc_response(self):
902 data = """<?xml version='1.0'?>
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000903 <methodCall>
904 <methodName>test_method</methodName>
905 <params>
906 <param>
907 <value><string>foo</string></value>
908 </param>
909 <param>
910 <value><string>bar</string></value>
911 </param>
912 </params>
913 </methodCall>
914 """
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000915
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000916 with test_support.EnvironmentVarGuard() as env, \
917 test_support.captured_stdout() as data_out, \
918 test_support.captured_stdin() as data_in:
919 data_in.write(data)
920 data_in.seek(0)
Walter Dörwald6733bed2009-05-01 17:35:37 +0000921 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandl61fce382009-04-01 15:23:43 +0000922 self.cgi.handle_request()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000923 data_out.seek(0)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000924
925 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000926 handle = data_out.read()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000927
928 # start with 44th char so as not to get http header, we just need only xml
929 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
930
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000931 # Also test the content-length returned by handle_request
932 # Using the same test method inorder to avoid all the datapassing
933 # boilerplate code.
934 # Test for bug: http://bugs.python.org/issue5040
935
936 content = handle[handle.find("<?xml"):]
937
Ezio Melotti2623a372010-11-21 13:34:58 +0000938 self.assertEqual(
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000939 int(re.search('Content-Length: (\d+)', handle).group(1)),
940 len(content))
941
942
Jeremy Hylton89420112008-11-24 22:00:29 +0000943class FakeSocket:
944
945 def __init__(self):
946 self.data = StringIO.StringIO()
947
948 def send(self, buf):
949 self.data.write(buf)
950 return len(buf)
951
952 def sendall(self, buf):
953 self.data.write(buf)
954
955 def getvalue(self):
956 return self.data.getvalue()
957
Kristján Valur Jónsson3c43fcb2009-01-11 16:23:37 +0000958 def makefile(self, x='r', y=-1):
Jeremy Hylton89420112008-11-24 22:00:29 +0000959 raise RuntimeError
960
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000961 def close(self):
962 pass
963
Jeremy Hylton89420112008-11-24 22:00:29 +0000964class FakeTransport(xmlrpclib.Transport):
965 """A Transport instance that records instead of sending a request.
966
967 This class replaces the actual socket used by httplib with a
968 FakeSocket object that records the request. It doesn't provide a
969 response.
970 """
971
972 def make_connection(self, host):
973 conn = xmlrpclib.Transport.make_connection(self, host)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000974 conn.sock = self.fake_socket = FakeSocket()
Jeremy Hylton89420112008-11-24 22:00:29 +0000975 return conn
976
977class TransportSubclassTestCase(unittest.TestCase):
978
979 def issue_request(self, transport_class):
980 """Return an HTTP request made via transport_class."""
981 transport = transport_class()
982 proxy = xmlrpclib.ServerProxy("http://example.com/",
983 transport=transport)
984 try:
985 proxy.pow(6, 8)
986 except RuntimeError:
987 return transport.fake_socket.getvalue()
988 return None
989
990 def test_custom_user_agent(self):
991 class TestTransport(FakeTransport):
992
993 def send_user_agent(self, conn):
994 xmlrpclib.Transport.send_user_agent(self, conn)
995 conn.putheader("X-Test", "test_custom_user_agent")
996
997 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +0000998 self.assertIn("X-Test: test_custom_user_agent\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +0000999
1000 def test_send_host(self):
1001 class TestTransport(FakeTransport):
1002
1003 def send_host(self, conn, host):
1004 xmlrpclib.Transport.send_host(self, conn, host)
1005 conn.putheader("X-Test", "test_send_host")
1006
1007 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001008 self.assertIn("X-Test: test_send_host\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001009
1010 def test_send_request(self):
1011 class TestTransport(FakeTransport):
1012
1013 def send_request(self, conn, url, body):
1014 xmlrpclib.Transport.send_request(self, conn, url, body)
1015 conn.putheader("X-Test", "test_send_request")
1016
1017 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001018 self.assertIn("X-Test: test_send_request\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001019
1020 def test_send_content(self):
1021 class TestTransport(FakeTransport):
1022
1023 def send_content(self, conn, body):
1024 conn.putheader("X-Test", "test_send_content")
1025 xmlrpclib.Transport.send_content(self, conn, body)
1026
1027 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001028 self.assertIn("X-Test: test_send_content\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001029
Antoine Pitrou3c968582009-10-30 17:56:00 +00001030@test_support.reap_threads
Facundo Batistaa53872b2007-08-14 13:35:00 +00001031def test_main():
1032 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
Jeremy Hylton89420112008-11-24 22:00:29 +00001033 BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001034 xmlrpc_tests.append(SimpleServerTestCase)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +00001035 xmlrpc_tests.append(KeepaliveServerTestCase1)
1036 xmlrpc_tests.append(KeepaliveServerTestCase2)
Zachary Ware1f702212013-12-10 14:09:20 -06001037 xmlrpc_tests.append(GzipServerTestCase)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +00001038 xmlrpc_tests.append(MultiPathServerTestCase)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001039 xmlrpc_tests.append(ServerProxyTestCase)
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001040 xmlrpc_tests.append(FailingServerTestCase)
1041 xmlrpc_tests.append(CGIHandlerTestCase)
Facundo Batistaa53872b2007-08-14 13:35:00 +00001042
1043 test_support.run_unittest(*xmlrpc_tests)
Skip Montanaro419abda2001-10-01 17:47:44 +00001044
1045if __name__ == "__main__":
1046 test_main()