blob: 727193af519afcc22a7e2edf884a7c920f62744f [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
Fred Drake22c07062005-02-11 17:59:08 +0000151 def test_default_encoding_issues(self):
152 # SF bug #1115989: wrong decoding in '_stringify'
153 utf8 = """<?xml version='1.0' encoding='iso-8859-1'?>
154 <params>
155 <param><value>
156 <string>abc \x95</string>
157 </value></param>
158 <param><value>
159 <struct>
160 <member>
161 <name>def \x96</name>
162 <value><string>ghi \x97</string></value>
163 </member>
164 </struct>
165 </value></param>
166 </params>
167 """
Tim Petersf754f5f2005-04-08 18:00:59 +0000168
169 # sys.setdefaultencoding() normally doesn't exist after site.py is
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000170 # loaded. Import a temporary fresh copy to get access to it
171 # but then restore the original copy to avoid messing with
172 # other potentially modified sys module attributes
Fred Drake22c07062005-02-11 17:59:08 +0000173 old_encoding = sys.getdefaultencoding()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000174 with test_support.CleanImport('sys'):
175 import sys as temp_sys
176 temp_sys.setdefaultencoding("iso-8859-1")
177 try:
178 (s, d), m = xmlrpclib.loads(utf8)
179 finally:
180 temp_sys.setdefaultencoding(old_encoding)
Tim Petersf754f5f2005-04-08 18:00:59 +0000181
Fred Drake22c07062005-02-11 17:59:08 +0000182 items = d.items()
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200183 if test_support.have_unicode:
Ezio Melotti2623a372010-11-21 13:34:58 +0000184 self.assertEqual(s, u"abc \x95")
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000185 self.assertIsInstance(s, unicode)
Ezio Melotti2623a372010-11-21 13:34:58 +0000186 self.assertEqual(items, [(u"def \x96", u"ghi \x97")])
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000187 self.assertIsInstance(items[0][0], unicode)
188 self.assertIsInstance(items[0][1], unicode)
Fred Drake22c07062005-02-11 17:59:08 +0000189 else:
Ezio Melotti2623a372010-11-21 13:34:58 +0000190 self.assertEqual(s, "abc \xc2\x95")
191 self.assertEqual(items, [("def \xc2\x96", "ghi \xc2\x97")])
Fred Drake22c07062005-02-11 17:59:08 +0000192
Facundo Batista5a3b5242007-07-13 10:43:44 +0000193
194class HelperTestCase(unittest.TestCase):
195 def test_escape(self):
196 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
197 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
198 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
199
200class FaultTestCase(unittest.TestCase):
201 def test_repr(self):
202 f = xmlrpclib.Fault(42, 'Test Fault')
203 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
204 self.assertEqual(repr(f), str(f))
205
206 def test_dump_fault(self):
207 f = xmlrpclib.Fault(42, 'Test Fault')
208 s = xmlrpclib.dumps((f,))
209 (newf,), m = xmlrpclib.loads(s)
Ezio Melotti2623a372010-11-21 13:34:58 +0000210 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
211 self.assertEqual(m, None)
Facundo Batista5a3b5242007-07-13 10:43:44 +0000212
213 s = xmlrpclib.Marshaller().dumps(f)
214 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
215
216
217class DateTimeTestCase(unittest.TestCase):
218 def test_default(self):
219 t = xmlrpclib.DateTime()
220
221 def test_time(self):
222 d = 1181399930.036952
223 t = xmlrpclib.DateTime(d)
224 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
225
226 def test_time_tuple(self):
227 d = (2007,6,9,10,38,50,5,160,0)
228 t = xmlrpclib.DateTime(d)
229 self.assertEqual(str(t), '20070609T10:38:50')
230
231 def test_time_struct(self):
232 d = time.localtime(1181399930.036952)
233 t = xmlrpclib.DateTime(d)
234 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
235
236 def test_datetime_datetime(self):
237 d = datetime.datetime(2007,1,2,3,4,5)
238 t = xmlrpclib.DateTime(d)
239 self.assertEqual(str(t), '20070102T03:04:05')
240
Facundo Batista5a3b5242007-07-13 10:43:44 +0000241 def test_repr(self):
242 d = datetime.datetime(2007,1,2,3,4,5)
243 t = xmlrpclib.DateTime(d)
244 val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
245 self.assertEqual(repr(t), val)
246
247 def test_decode(self):
248 d = ' 20070908T07:11:13 '
249 t1 = xmlrpclib.DateTime()
250 t1.decode(d)
251 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
252 self.assertEqual(t1, tref)
253
254 t2 = xmlrpclib._datetime(d)
255 self.assertEqual(t1, tref)
256
257class BinaryTestCase(unittest.TestCase):
258 def test_default(self):
259 t = xmlrpclib.Binary()
260 self.assertEqual(str(t), '')
261
262 def test_string(self):
263 d = '\x01\x02\x03abc123\xff\xfe'
264 t = xmlrpclib.Binary(d)
265 self.assertEqual(str(t), d)
266
267 def test_decode(self):
268 d = '\x01\x02\x03abc123\xff\xfe'
269 de = base64.encodestring(d)
270 t1 = xmlrpclib.Binary()
271 t1.decode(de)
272 self.assertEqual(str(t1), d)
273
274 t2 = xmlrpclib._binary(de)
275 self.assertEqual(str(t2), d)
276
277
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000278ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000279
Neal Norwitz653272f2008-01-26 07:26:12 +0000280# The evt is set twice. First when the server is ready to serve.
281# Second when the server has been shutdown. The user must clear
282# 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 +0000283def http_server(evt, numrequests, requestHandler=None):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000284 class TestInstanceClass:
285 def div(self, x, y):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000286 return x // y
287
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000288 def _methodHelp(self, name):
289 if name == 'div':
290 return 'This is the div function'
291
292 def my_function():
293 '''This is my function'''
294 return True
295
Neal Norwitz70cea582008-03-28 06:34:03 +0000296 class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
297 def get_request(self):
298 # Ensure the socket is always non-blocking. On Linux, socket
299 # attributes are not inherited like they are on *BSD and Windows.
300 s, port = self.socket.accept()
301 s.setblocking(True)
302 return s, port
303
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000304 if not requestHandler:
305 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
306 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000307 logRequests=False, bind_and_activate=False)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000308 try:
309 serv.socket.settimeout(3)
310 serv.server_bind()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000311 global ADDR, PORT, URL
312 ADDR, PORT = serv.socket.getsockname()
313 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300314 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000315 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
316 #on AF_INET only.
317 URL = "http://%s:%d"%(ADDR, PORT)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000318 serv.server_activate()
319 serv.register_introspection_functions()
320 serv.register_multicall_functions()
321 serv.register_function(pow)
322 serv.register_function(lambda x,y: x+y, 'add')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000323 serv.register_function(my_function)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000324 serv.register_instance(TestInstanceClass())
Neal Norwitz653272f2008-01-26 07:26:12 +0000325 evt.set()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000326
327 # handle up to 'numrequests' requests
328 while numrequests > 0:
329 serv.handle_request()
330 numrequests -= 1
331
332 except socket.timeout:
333 pass
334 finally:
335 serv.socket.close()
336 PORT = None
337 evt.set()
338
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000339def http_multi_server(evt, numrequests, requestHandler=None):
340 class TestInstanceClass:
341 def div(self, x, y):
342 return x // y
343
344 def _methodHelp(self, name):
345 if name == 'div':
346 return 'This is the div function'
347
348 def my_function():
349 '''This is my function'''
350 return True
351
352 class MyXMLRPCServer(SimpleXMLRPCServer.MultiPathXMLRPCServer):
353 def get_request(self):
354 # Ensure the socket is always non-blocking. On Linux, socket
355 # attributes are not inherited like they are on *BSD and Windows.
356 s, port = self.socket.accept()
357 s.setblocking(True)
358 return s, port
359
360 if not requestHandler:
361 requestHandler = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
362 class MyRequestHandler(requestHandler):
363 rpc_paths = []
364
365 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
366 logRequests=False, bind_and_activate=False)
367 serv.socket.settimeout(3)
368 serv.server_bind()
369 try:
370 global ADDR, PORT, URL
371 ADDR, PORT = serv.socket.getsockname()
372 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melotti1e87da12011-10-19 10:39:35 +0300373 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000374 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
375 #on AF_INET only.
376 URL = "http://%s:%d"%(ADDR, PORT)
377 serv.server_activate()
378 paths = ["/foo", "/foo/bar"]
379 for path in paths:
380 d = serv.add_dispatcher(path, SimpleXMLRPCServer.SimpleXMLRPCDispatcher())
381 d.register_introspection_functions()
382 d.register_multicall_functions()
383 serv.get_dispatcher(paths[0]).register_function(pow)
384 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
385 evt.set()
386
387 # handle up to 'numrequests' requests
388 while numrequests > 0:
389 serv.handle_request()
390 numrequests -= 1
391
392 except socket.timeout:
393 pass
394 finally:
395 serv.socket.close()
396 PORT = None
397 evt.set()
398
Neal Norwitz08b50eb2008-01-26 08:26:00 +0000399# This function prevents errors like:
400# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000401def is_unavailable_exception(e):
402 '''Returns True if the given ProtocolError is the product of a server-side
403 exception caused by the 'temporarily unavailable' response sometimes
404 given by operations on non-blocking sockets.'''
Neal Norwitz653272f2008-01-26 07:26:12 +0000405
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000406 # sometimes we get a -1 error code and/or empty headers
Neal Norwitzed444e52008-01-27 18:19:04 +0000407 try:
408 if e.errcode == -1 or e.headers is None:
409 return True
410 exc_mess = e.headers.get('X-exception')
411 except AttributeError:
412 # Ignore socket.errors here.
413 exc_mess = str(e)
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000414
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000415 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
416 return True
417
418 return False
419
Victor Stinnera44b5a32010-04-27 23:14:58 +0000420@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000421class BaseServerTestCase(unittest.TestCase):
422 requestHandler = None
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000423 request_count = 1
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000424 threadFunc = staticmethod(http_server)
Victor Stinnera44b5a32010-04-27 23:14:58 +0000425
Facundo Batistaa53872b2007-08-14 13:35:00 +0000426 def setUp(self):
Facundo Batista7f686fc2007-08-17 19:16:44 +0000427 # enable traceback reporting
428 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
429
Facundo Batistaa53872b2007-08-14 13:35:00 +0000430 self.evt = threading.Event()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000431 # start server thread to handle requests
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000432 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000433 threading.Thread(target=self.threadFunc, args=serv_args).start()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000434
Neal Norwitz653272f2008-01-26 07:26:12 +0000435 # wait for the server to be ready
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000436 self.evt.wait(10)
Neal Norwitz653272f2008-01-26 07:26:12 +0000437 self.evt.clear()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000438
439 def tearDown(self):
440 # wait on the server thread to terminate
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000441 self.evt.wait(10)
Facundo Batistaa53872b2007-08-14 13:35:00 +0000442
Facundo Batista7f686fc2007-08-17 19:16:44 +0000443 # disable traceback reporting
444 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
445
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000446# NOTE: The tests in SimpleServerTestCase will ignore failures caused by
447# "temporarily unavailable" exceptions raised in SimpleXMLRPCServer. This
448# condition occurs infrequently on some platforms, frequently on others, and
449# is apparently caused by using SimpleXMLRPCServer with a non-blocking socket
450# If the server class is updated at some point in the future to handle this
451# situation more gracefully, these tests should be modified appropriately.
452
453class SimpleServerTestCase(BaseServerTestCase):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000454 def test_simple1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000455 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000456 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000457 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000458 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000459 # ignore failures due to non-blocking socket 'unavailable' errors
460 if not is_unavailable_exception(e):
461 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000462 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000463
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000464 def test_nonascii(self):
465 start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
466 end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
467
468 try:
469 p = xmlrpclib.ServerProxy(URL)
470 self.assertEqual(p.add(start_string, end_string),
471 start_string + end_string)
472 except (xmlrpclib.ProtocolError, socket.error) as e:
473 # ignore failures due to non-blocking socket unavailable errors.
474 if not is_unavailable_exception(e):
475 # protocol error; provide additional information in test output
476 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
477
Serhiy Storchaka2f173fe2016-01-18 19:35:23 +0200478 @test_support.requires_unicode
Victor Stinner51b71982011-09-23 01:15:32 +0200479 def test_unicode_host(self):
480 server = xmlrpclib.ServerProxy(u"http://%s:%d/RPC2"%(ADDR, PORT))
481 self.assertEqual(server.add("a", u"\xe9"), u"a\xe9")
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000482
Christian Heimes6c29be52008-01-19 16:39:27 +0000483 # [ch] The test 404 is causing lots of false alarms.
484 def XXXtest_404(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000485 # send POST with httplib, it should return 404 header and
486 # 'Not Found' message.
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000487 conn = httplib.HTTPConnection(ADDR, PORT)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000488 conn.request('POST', '/this-is-not-valid')
489 response = conn.getresponse()
490 conn.close()
491
492 self.assertEqual(response.status, 404)
493 self.assertEqual(response.reason, 'Not Found')
494
Facundo Batistaa53872b2007-08-14 13:35:00 +0000495 def test_introspection1(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000496 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000497 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000498 meth = p.system.listMethods()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000499 expected_methods = set(['pow', 'div', 'my_function', 'add',
500 'system.listMethods', 'system.methodHelp',
501 'system.methodSignature', 'system.multicall'])
Facundo Batistac65a5f12007-08-21 00:16:21 +0000502 self.assertEqual(set(meth), expected_methods)
Neal Norwitz183c5342008-01-27 17:11:11 +0000503 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000504 # ignore failures due to non-blocking socket 'unavailable' errors
505 if not is_unavailable_exception(e):
506 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000507 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000508
509 def test_introspection2(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000510 try:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000511 # test _methodHelp()
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000512 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000513 divhelp = p.system.methodHelp('div')
514 self.assertEqual(divhelp, 'This is the div function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000515 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000516 # ignore failures due to non-blocking socket 'unavailable' errors
517 if not is_unavailable_exception(e):
518 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000519 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000520
R. David Murrayf28fd242010-02-23 00:24:49 +0000521 @unittest.skipIf(sys.flags.optimize >= 2,
522 "Docstrings are omitted with -O2 and above")
Facundo Batistaa53872b2007-08-14 13:35:00 +0000523 def test_introspection3(self):
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000524 try:
525 # test native doc
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000526 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000527 myfunction = p.system.methodHelp('my_function')
528 self.assertEqual(myfunction, 'This is my function')
Neal Norwitz183c5342008-01-27 17:11:11 +0000529 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000530 # ignore failures due to non-blocking socket 'unavailable' errors
531 if not is_unavailable_exception(e):
532 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000533 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000534
535 def test_introspection4(self):
Facundo Batistaa53872b2007-08-14 13:35:00 +0000536 # the SimpleXMLRPCServer doesn't support signatures, but
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000537 # at least check that we can try making the call
Facundo Batistac65a5f12007-08-21 00:16:21 +0000538 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000539 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000540 divsig = p.system.methodSignature('div')
541 self.assertEqual(divsig, 'signatures not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000542 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000543 # ignore failures due to non-blocking socket 'unavailable' errors
544 if not is_unavailable_exception(e):
545 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000546 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000547
548 def test_multicall(self):
Facundo Batistac65a5f12007-08-21 00:16:21 +0000549 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000550 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000551 multicall = xmlrpclib.MultiCall(p)
552 multicall.add(2,3)
553 multicall.pow(6,8)
554 multicall.div(127,42)
555 add_result, pow_result, div_result = multicall()
556 self.assertEqual(add_result, 2+3)
557 self.assertEqual(pow_result, 6**8)
558 self.assertEqual(div_result, 127//42)
Neal Norwitz183c5342008-01-27 17:11:11 +0000559 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batistaf91ad6a2007-08-27 01:15:34 +0000560 # ignore failures due to non-blocking socket 'unavailable' errors
561 if not is_unavailable_exception(e):
562 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000563 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batistaa53872b2007-08-14 13:35:00 +0000564
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000565 def test_non_existing_multicall(self):
566 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000567 p = xmlrpclib.ServerProxy(URL)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000568 multicall = xmlrpclib.MultiCall(p)
569 multicall.this_is_not_exists()
570 result = multicall()
571
572 # result.results contains;
573 # [{'faultCode': 1, 'faultString': '<type \'exceptions.Exception\'>:'
574 # 'method "this_is_not_exists" is not supported'>}]
575
576 self.assertEqual(result.results[0]['faultCode'], 1)
577 self.assertEqual(result.results[0]['faultString'],
578 '<type \'exceptions.Exception\'>:method "this_is_not_exists" '
579 'is not supported')
Neal Norwitz183c5342008-01-27 17:11:11 +0000580 except (xmlrpclib.ProtocolError, socket.error), e:
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000581 # ignore failures due to non-blocking socket 'unavailable' errors
582 if not is_unavailable_exception(e):
583 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000584 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000585
586 def test_dotted_attribute(self):
Neal Norwitz162d7192008-03-23 04:08:30 +0000587 # Raises an AttributeError because private methods are not allowed.
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000588 self.assertRaises(AttributeError,
589 SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')
590
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000591 self.assertTrue(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
Neal Norwitz162d7192008-03-23 04:08:30 +0000592 # Get the test to run faster by sending a request with test_simple1.
593 # This avoids waiting for the socket timeout.
594 self.test_simple1()
Facundo Batistaa53872b2007-08-14 13:35:00 +0000595
Charles-François Natalie0624662012-02-18 14:30:34 +0100596 def test_partial_post(self):
597 # Check that a partial POST doesn't make the server loop: issue #14001.
598 conn = httplib.HTTPConnection(ADDR, PORT)
599 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
600 conn.close()
601
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +0000602class MultiPathServerTestCase(BaseServerTestCase):
603 threadFunc = staticmethod(http_multi_server)
604 request_count = 2
605 def test_path1(self):
606 p = xmlrpclib.ServerProxy(URL+"/foo")
607 self.assertEqual(p.pow(6,8), 6**8)
608 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
609 def test_path2(self):
610 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
611 self.assertEqual(p.add(6,8), 6+8)
612 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
613
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000614#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
615#does indeed serve subsequent requests on the same connection
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000616class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000617 #a request handler that supports keep-alive and logs requests into a
618 #class variable
619 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
620 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
621 protocol_version = 'HTTP/1.1'
622 myRequests = []
623 def handle(self):
624 self.myRequests.append([])
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000625 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000626 return self.parentClass.handle(self)
627 def handle_one_request(self):
628 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000629 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000630 return result
631
632 requestHandler = RequestHandler
633 def setUp(self):
634 #clear request log
635 self.RequestHandler.myRequests = []
636 return BaseServerTestCase.setUp(self)
637
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000638#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
639#does indeed serve subsequent requests on the same connection
640class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000641 def test_two(self):
642 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000643 #do three requests.
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000644 self.assertEqual(p.pow(6,8), 6**8)
645 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000646 self.assertEqual(p.pow(6,8), 6**8)
647
648 #they should have all been handled by a single request handler
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000649 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónssonef6007c2009-07-11 08:44:43 +0000650
651 #check that we did at least two (the third may be pending append
652 #due to thread scheduling)
653 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000654
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +0000655#test special attribute access on the serverproxy, through the __call__
656#function.
657class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
658 #ask for two keepalive requests to be handled.
659 request_count=2
660
661 def test_close(self):
662 p = xmlrpclib.ServerProxy(URL)
663 #do some requests with close.
664 self.assertEqual(p.pow(6,8), 6**8)
665 self.assertEqual(p.pow(6,8), 6**8)
666 self.assertEqual(p.pow(6,8), 6**8)
667 p("close")() #this should trigger a new keep-alive request
668 self.assertEqual(p.pow(6,8), 6**8)
669 self.assertEqual(p.pow(6,8), 6**8)
670 self.assertEqual(p.pow(6,8), 6**8)
671
672 #they should have all been two request handlers, each having logged at least
673 #two complete requests
674 self.assertEqual(len(self.RequestHandler.myRequests), 2)
675 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
676 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
677
678 def test_transport(self):
679 p = xmlrpclib.ServerProxy(URL)
680 #do some requests with close.
681 self.assertEqual(p.pow(6,8), 6**8)
682 p("transport").close() #same as above, really.
683 self.assertEqual(p.pow(6,8), 6**8)
684 self.assertEqual(len(self.RequestHandler.myRequests), 2)
685
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000686#A test case that verifies that gzip encoding works in both directions
687#(for a request and the response)
Zachary Ware1f702212013-12-10 14:09:20 -0600688@unittest.skipUnless(gzip, 'gzip not available')
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000689class GzipServerTestCase(BaseServerTestCase):
690 #a request handler that supports keep-alive and logs requests into a
691 #class variable
692 class RequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler):
693 parentClass = SimpleXMLRPCServer.SimpleXMLRPCRequestHandler
694 protocol_version = 'HTTP/1.1'
695
696 def do_POST(self):
697 #store content of last request in class
698 self.__class__.content_length = int(self.headers["content-length"])
699 return self.parentClass.do_POST(self)
700 requestHandler = RequestHandler
701
702 class Transport(xmlrpclib.Transport):
703 #custom transport, stores the response length for our perusal
704 fake_gzip = False
705 def parse_response(self, response):
706 self.response_length=int(response.getheader("content-length", 0))
707 return xmlrpclib.Transport.parse_response(self, response)
708
709 def send_content(self, connection, body):
710 if self.fake_gzip:
711 #add a lone gzip header to induce decode error remotely
712 connection.putheader("Content-Encoding", "gzip")
713 return xmlrpclib.Transport.send_content(self, connection, body)
714
Victor Stinnera44b5a32010-04-27 23:14:58 +0000715 def setUp(self):
716 BaseServerTestCase.setUp(self)
717
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000718 def test_gzip_request(self):
719 t = self.Transport()
720 t.encode_threshold = None
721 p = xmlrpclib.ServerProxy(URL, transport=t)
722 self.assertEqual(p.pow(6,8), 6**8)
723 a = self.RequestHandler.content_length
724 t.encode_threshold = 0 #turn on request encoding
725 self.assertEqual(p.pow(6,8), 6**8)
726 b = self.RequestHandler.content_length
727 self.assertTrue(a>b)
728
729 def test_bad_gzip_request(self):
730 t = self.Transport()
731 t.encode_threshold = None
732 t.fake_gzip = True
733 p = xmlrpclib.ServerProxy(URL, transport=t)
734 cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
735 re.compile(r"\b400\b"))
736 with cm:
737 p.pow(6, 8)
738
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500739 def test_gzip_response(self):
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000740 t = self.Transport()
741 p = xmlrpclib.ServerProxy(URL, transport=t)
742 old = self.requestHandler.encode_threshold
743 self.requestHandler.encode_threshold = None #no encoding
744 self.assertEqual(p.pow(6,8), 6**8)
745 a = t.response_length
746 self.requestHandler.encode_threshold = 0 #always encode
747 self.assertEqual(p.pow(6,8), 6**8)
748 b = t.response_length
749 self.requestHandler.encode_threshold = old
750 self.assertTrue(a>b)
751
Benjamin Peterson9e8f5232014-12-05 20:15:15 -0500752 def test_gzip_decode_limit(self):
753 max_gzip_decode = 20 * 1024 * 1024
754 data = '\0' * max_gzip_decode
755 encoded = xmlrpclib.gzip_encode(data)
756 decoded = xmlrpclib.gzip_decode(encoded)
757 self.assertEqual(len(decoded), max_gzip_decode)
758
759 data = '\0' * (max_gzip_decode + 1)
760 encoded = xmlrpclib.gzip_encode(data)
761
762 with self.assertRaisesRegexp(ValueError,
763 "max gzipped payload length exceeded"):
764 xmlrpclib.gzip_decode(encoded)
765
766 xmlrpclib.gzip_decode(encoded, max_decode=-1)
767
768
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000769#Test special attributes of the ServerProxy object
770class ServerProxyTestCase(unittest.TestCase):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000771 def setUp(self):
772 unittest.TestCase.setUp(self)
773 if threading:
774 self.url = URL
775 else:
776 # Without threading, http_server() and http_multi_server() will not
777 # be executed and URL is still equal to None. 'http://' is a just
778 # enough to choose the scheme (HTTP)
779 self.url = 'http://'
780
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000781 def test_close(self):
Victor Stinnera44b5a32010-04-27 23:14:58 +0000782 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000783 self.assertEqual(p('close')(), None)
784
785 def test_transport(self):
786 t = xmlrpclib.Transport()
Victor Stinnera44b5a32010-04-27 23:14:58 +0000787 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000788 self.assertEqual(p('transport'), t)
789
Facundo Batista7f686fc2007-08-17 19:16:44 +0000790# This is a contrived way to make a failure occur on the server side
791# in order to test the _send_traceback_header flag on the server
792class FailingMessageClass(mimetools.Message):
793 def __getitem__(self, key):
794 key = key.lower()
795 if key == 'content-length':
796 return 'I am broken'
797 return mimetools.Message.__getitem__(self, key)
798
799
Victor Stinnera44b5a32010-04-27 23:14:58 +0000800@unittest.skipUnless(threading, 'Threading required for this test.')
Facundo Batista7f686fc2007-08-17 19:16:44 +0000801class FailingServerTestCase(unittest.TestCase):
802 def setUp(self):
803 self.evt = threading.Event()
804 # start server thread to handle requests
Neal Norwitz162d7192008-03-23 04:08:30 +0000805 serv_args = (self.evt, 1)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000806 threading.Thread(target=http_server, args=serv_args).start()
807
Neal Norwitz653272f2008-01-26 07:26:12 +0000808 # wait for the server to be ready
809 self.evt.wait()
810 self.evt.clear()
Facundo Batista7f686fc2007-08-17 19:16:44 +0000811
812 def tearDown(self):
813 # wait on the server thread to terminate
814 self.evt.wait()
815 # reset flag
816 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
817 # reset message class
818 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message
819
820 def test_basic(self):
821 # check that flag is false by default
822 flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
823 self.assertEqual(flagval, False)
824
Facundo Batistac65a5f12007-08-21 00:16:21 +0000825 # enable traceback reporting
826 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
827
828 # test a call that shouldn't fail just as a smoke test
829 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000830 p = xmlrpclib.ServerProxy(URL)
Facundo Batistac65a5f12007-08-21 00:16:21 +0000831 self.assertEqual(p.pow(6,8), 6**8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000832 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000833 # ignore failures due to non-blocking socket 'unavailable' errors
834 if not is_unavailable_exception(e):
835 # protocol error; provide additional information in test output
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000836 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Facundo Batista7f686fc2007-08-17 19:16:44 +0000837
838 def test_fail_no_info(self):
839 # use the broken message class
840 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
841
842 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000843 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000844 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000845 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000846 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000847 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000848 # The two server-side error headers shouldn't be sent back in this case
849 self.assertTrue(e.headers.get("X-exception") is None)
850 self.assertTrue(e.headers.get("X-traceback") is None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000851 else:
852 self.fail('ProtocolError not raised')
853
854 def test_fail_with_info(self):
855 # use the broken message class
856 SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
857
858 # Check that errors in the server send back exception/traceback
859 # info when flag is set
860 SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True
861
862 try:
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +0000863 p = xmlrpclib.ServerProxy(URL)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000864 p.pow(6,8)
Neal Norwitz183c5342008-01-27 17:11:11 +0000865 except (xmlrpclib.ProtocolError, socket.error), e:
Facundo Batista492e5922007-08-29 10:28:28 +0000866 # ignore failures due to non-blocking socket 'unavailable' errors
Neal Norwitzcf25eb12008-01-27 20:03:13 +0000867 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Facundo Batista492e5922007-08-29 10:28:28 +0000868 # We should get error info in the response
869 expected_err = "invalid literal for int() with base 10: 'I am broken'"
870 self.assertEqual(e.headers.get("x-exception"), expected_err)
871 self.assertTrue(e.headers.get("x-traceback") is not None)
Facundo Batista7f686fc2007-08-17 19:16:44 +0000872 else:
873 self.fail('ProtocolError not raised')
874
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000875class CGIHandlerTestCase(unittest.TestCase):
876 def setUp(self):
877 self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()
878
879 def tearDown(self):
880 self.cgi = None
881
882 def test_cgi_get(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000883 with test_support.EnvironmentVarGuard() as env:
Walter Dörwald6733bed2009-05-01 17:35:37 +0000884 env['REQUEST_METHOD'] = 'GET'
Walter Dörwald4b965f62009-04-26 20:51:44 +0000885 # if the method is GET and no request_text is given, it runs handle_get
886 # get sysout output
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000887 with test_support.captured_stdout() as data_out:
888 self.cgi.handle_request()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000889
Walter Dörwald4b965f62009-04-26 20:51:44 +0000890 # parse Status header
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000891 data_out.seek(0)
892 handle = data_out.read()
Walter Dörwald4b965f62009-04-26 20:51:44 +0000893 status = handle.split()[1]
894 message = ' '.join(handle.split()[2:4])
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000895
Walter Dörwald4b965f62009-04-26 20:51:44 +0000896 self.assertEqual(status, '400')
897 self.assertEqual(message, 'Bad Request')
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000898
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000899
900 def test_cgi_xmlrpc_response(self):
901 data = """<?xml version='1.0'?>
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000902 <methodCall>
903 <methodName>test_method</methodName>
904 <params>
905 <param>
906 <value><string>foo</string></value>
907 </param>
908 <param>
909 <value><string>bar</string></value>
910 </param>
911 </params>
912 </methodCall>
913 """
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000914
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000915 with test_support.EnvironmentVarGuard() as env, \
916 test_support.captured_stdout() as data_out, \
917 test_support.captured_stdin() as data_in:
918 data_in.write(data)
919 data_in.seek(0)
Walter Dörwald6733bed2009-05-01 17:35:37 +0000920 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandl61fce382009-04-01 15:23:43 +0000921 self.cgi.handle_request()
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000922 data_out.seek(0)
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000923
924 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan8c1ffeb2009-10-17 15:09:41 +0000925 handle = data_out.read()
Georg Brandl5d1b4d42007-12-07 09:07:10 +0000926
927 # start with 44th char so as not to get http header, we just need only xml
928 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
929
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000930 # Also test the content-length returned by handle_request
931 # Using the same test method inorder to avoid all the datapassing
932 # boilerplate code.
933 # Test for bug: http://bugs.python.org/issue5040
934
935 content = handle[handle.find("<?xml"):]
936
Ezio Melotti2623a372010-11-21 13:34:58 +0000937 self.assertEqual(
Senthil Kumaran20d114c2009-04-01 20:26:33 +0000938 int(re.search('Content-Length: (\d+)', handle).group(1)),
939 len(content))
940
941
Jeremy Hylton89420112008-11-24 22:00:29 +0000942class FakeSocket:
943
944 def __init__(self):
945 self.data = StringIO.StringIO()
946
947 def send(self, buf):
948 self.data.write(buf)
949 return len(buf)
950
951 def sendall(self, buf):
952 self.data.write(buf)
953
954 def getvalue(self):
955 return self.data.getvalue()
956
Kristján Valur Jónsson3c43fcb2009-01-11 16:23:37 +0000957 def makefile(self, x='r', y=-1):
Jeremy Hylton89420112008-11-24 22:00:29 +0000958 raise RuntimeError
959
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000960 def close(self):
961 pass
962
Jeremy Hylton89420112008-11-24 22:00:29 +0000963class FakeTransport(xmlrpclib.Transport):
964 """A Transport instance that records instead of sending a request.
965
966 This class replaces the actual socket used by httplib with a
967 FakeSocket object that records the request. It doesn't provide a
968 response.
969 """
970
971 def make_connection(self, host):
972 conn = xmlrpclib.Transport.make_connection(self, host)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +0000973 conn.sock = self.fake_socket = FakeSocket()
Jeremy Hylton89420112008-11-24 22:00:29 +0000974 return conn
975
976class TransportSubclassTestCase(unittest.TestCase):
977
978 def issue_request(self, transport_class):
979 """Return an HTTP request made via transport_class."""
980 transport = transport_class()
981 proxy = xmlrpclib.ServerProxy("http://example.com/",
982 transport=transport)
983 try:
984 proxy.pow(6, 8)
985 except RuntimeError:
986 return transport.fake_socket.getvalue()
987 return None
988
989 def test_custom_user_agent(self):
990 class TestTransport(FakeTransport):
991
992 def send_user_agent(self, conn):
993 xmlrpclib.Transport.send_user_agent(self, conn)
994 conn.putheader("X-Test", "test_custom_user_agent")
995
996 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +0000997 self.assertIn("X-Test: test_custom_user_agent\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +0000998
999 def test_send_host(self):
1000 class TestTransport(FakeTransport):
1001
1002 def send_host(self, conn, host):
1003 xmlrpclib.Transport.send_host(self, conn, host)
1004 conn.putheader("X-Test", "test_send_host")
1005
1006 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001007 self.assertIn("X-Test: test_send_host\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001008
1009 def test_send_request(self):
1010 class TestTransport(FakeTransport):
1011
1012 def send_request(self, conn, url, body):
1013 xmlrpclib.Transport.send_request(self, conn, url, body)
1014 conn.putheader("X-Test", "test_send_request")
1015
1016 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001017 self.assertIn("X-Test: test_send_request\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001018
1019 def test_send_content(self):
1020 class TestTransport(FakeTransport):
1021
1022 def send_content(self, conn, body):
1023 conn.putheader("X-Test", "test_send_content")
1024 xmlrpclib.Transport.send_content(self, conn, body)
1025
1026 req = self.issue_request(TestTransport)
Ezio Melottiaa980582010-01-23 23:04:36 +00001027 self.assertIn("X-Test: test_send_content\r\n", req)
Jeremy Hylton89420112008-11-24 22:00:29 +00001028
Antoine Pitrou3c968582009-10-30 17:56:00 +00001029@test_support.reap_threads
Facundo Batistaa53872b2007-08-14 13:35:00 +00001030def test_main():
1031 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
Jeremy Hylton89420112008-11-24 22:00:29 +00001032 BinaryTestCase, FaultTestCase, TransportSubclassTestCase]
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001033 xmlrpc_tests.append(SimpleServerTestCase)
Kristján Valur Jónsson0369ba22009-07-12 22:42:08 +00001034 xmlrpc_tests.append(KeepaliveServerTestCase1)
1035 xmlrpc_tests.append(KeepaliveServerTestCase2)
Zachary Ware1f702212013-12-10 14:09:20 -06001036 xmlrpc_tests.append(GzipServerTestCase)
Kristján Valur Jónsson429677e2009-08-27 23:13:18 +00001037 xmlrpc_tests.append(MultiPathServerTestCase)
Kristján Valur Jónssone0078602009-06-28 21:04:17 +00001038 xmlrpc_tests.append(ServerProxyTestCase)
Kristján Valur Jónsson018760e2009-01-14 10:50:57 +00001039 xmlrpc_tests.append(FailingServerTestCase)
1040 xmlrpc_tests.append(CGIHandlerTestCase)
Facundo Batistaa53872b2007-08-14 13:35:00 +00001041
1042 test_support.run_unittest(*xmlrpc_tests)
Skip Montanaro419abda2001-10-01 17:47:44 +00001043
1044if __name__ == "__main__":
1045 test_main()