blob: 02d9f5c650c6f3b5d47c2a21fa208365f4a0c5ea [file] [log] [blame]
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001import base64
Fred Drakeba613c32005-02-10 18:33:30 +00002import datetime
Skip Montanaro3e7bba92001-10-19 16:06:52 +00003import sys
Guido van Rossumb5a755e2007-07-18 18:15:48 +00004import time
Skip Montanaro419abda2001-10-01 17:47:44 +00005import unittest
Ezio Melotti31916322013-08-10 18:37:05 +03006from unittest import mock
Georg Brandl38eceaa2008-05-26 11:14:17 +00007import xmlrpc.client as xmlrpclib
8import xmlrpc.server
Georg Brandl24420152008-05-26 16:32:26 +00009import http.client
Martin Pantereae33362016-02-25 11:53:40 +000010import http, http.server
Christian Heimes255f53b2007-12-08 15:33:56 +000011import socket
12import os
Senthil Kumaranb3af08f2009-04-01 20:20:43 +000013import re
R. David Murray0548ce02009-10-26 08:24:14 +000014import io
15import contextlib
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Skip Montanaro419abda2001-10-01 17:47:44 +000017
Victor Stinner45df8202010-04-28 22:31:17 +000018try:
Brett Cannon603dcf22013-06-12 20:04:19 -040019 import gzip
Brett Cannon260fbe82013-07-04 18:16:15 -040020except ImportError:
Brett Cannon603dcf22013-06-12 20:04:19 -040021 gzip = None
22try:
Victor Stinner45df8202010-04-28 22:31:17 +000023 import threading
Brett Cannon260fbe82013-07-04 18:16:15 -040024except ImportError:
Victor Stinner45df8202010-04-28 22:31:17 +000025 threading = None
26
Skip Montanaro419abda2001-10-01 17:47:44 +000027alist = [{'astring': 'foo@bar.baz.spam',
28 'afloat': 7283.43,
Skip Montanaro3e7bba92001-10-19 16:06:52 +000029 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +000030 'ashortlong': 2,
Skip Montanaro419abda2001-10-01 17:47:44 +000031 'anotherlist': ['.zyx.41'],
Guido van Rossum54a40cb2007-08-27 22:27:41 +000032 'abase64': xmlrpclib.Binary(b"my dog has fleas"),
Florent Xicluna61665192011-11-15 20:53:25 +010033 'b64bytes': b"my dog has fleas",
34 'b64bytearray': bytearray(b"my dog has fleas"),
Guido van Rossume7ba4952007-06-06 23:52:48 +000035 'boolean': False,
Guido van Rossumef87d6e2007-05-02 19:09:54 +000036 'unicode': '\u4000\u6000\u8000',
37 'ukey\u4000': 'regular value',
Fred Drakeba613c32005-02-10 18:33:30 +000038 'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
39 'datetime2': xmlrpclib.DateTime(
Guido van Rossumcd16bf62007-06-13 18:07:49 +000040 (2005, 2, 10, 11, 41, 23, 0, 1, -1)),
Fred Drakeba613c32005-02-10 18:33:30 +000041 'datetime3': xmlrpclib.DateTime(
Guido van Rossumcd16bf62007-06-13 18:07:49 +000042 datetime.datetime(2005, 2, 10, 11, 41, 23)),
Skip Montanaro419abda2001-10-01 17:47:44 +000043 }]
44
45class XMLRPCTestCase(unittest.TestCase):
46
47 def test_dump_load(self):
Guido van Rossum54a40cb2007-08-27 22:27:41 +000048 dump = xmlrpclib.dumps((alist,))
49 load = xmlrpclib.loads(dump)
Ezio Melottib3aedd42010-11-20 19:04:17 +000050 self.assertEqual(alist, load[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()
Florent Xicluna61665192011-11-15 20:53:25 +010055 # since with use_builtin_types set to 1 the unmarshaller would create
Skip Montanaro174dd222005-05-14 20:54:16 +000056 # datetime objects for the 'datetime[123]' keys as well
Guido van Rossumcd16bf62007-06-13 18:07:49 +000057 dt = datetime.datetime(2005, 2, 10, 11, 41, 23)
Florent Xicluna61665192011-11-15 20:53:25 +010058 self.assertEqual(dt, xmlrpclib.DateTime('20050210T11:41:23'))
Fred Drakeba613c32005-02-10 18:33:30 +000059 s = xmlrpclib.dumps((dt,))
Fred Drakeba613c32005-02-10 18:33:30 +000060
Florent Xicluna61665192011-11-15 20:53:25 +010061 result, m = xmlrpclib.loads(s, use_builtin_types=True)
62 (newdt,) = result
63 self.assertEqual(newdt, dt)
64 self.assertIs(type(newdt), datetime.datetime)
65 self.assertIsNone(m)
66
67 result, m = xmlrpclib.loads(s, use_builtin_types=False)
68 (newdt,) = result
69 self.assertEqual(newdt, dt)
70 self.assertIs(type(newdt), xmlrpclib.DateTime)
71 self.assertIsNone(m)
72
73 result, m = xmlrpclib.loads(s, use_datetime=True)
74 (newdt,) = result
75 self.assertEqual(newdt, dt)
76 self.assertIs(type(newdt), datetime.datetime)
77 self.assertIsNone(m)
78
79 result, m = xmlrpclib.loads(s, use_datetime=False)
80 (newdt,) = result
81 self.assertEqual(newdt, dt)
82 self.assertIs(type(newdt), xmlrpclib.DateTime)
83 self.assertIsNone(m)
84
Skip Montanaro174dd222005-05-14 20:54:16 +000085
Christian Heimesdae2a892008-04-19 00:55:37 +000086 def test_datetime_before_1900(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +000087 # same as before but with a date before 1900
Christian Heimesdae2a892008-04-19 00:55:37 +000088 dt = datetime.datetime(1, 2, 10, 11, 41, 23)
Florent Xicluna61665192011-11-15 20:53:25 +010089 self.assertEqual(dt, xmlrpclib.DateTime('00010210T11:41:23'))
Christian Heimesdae2a892008-04-19 00:55:37 +000090 s = xmlrpclib.dumps((dt,))
Christian Heimesdae2a892008-04-19 00:55:37 +000091
Florent Xicluna61665192011-11-15 20:53:25 +010092 result, m = xmlrpclib.loads(s, use_builtin_types=True)
93 (newdt,) = result
94 self.assertEqual(newdt, dt)
95 self.assertIs(type(newdt), datetime.datetime)
96 self.assertIsNone(m)
97
98 result, m = xmlrpclib.loads(s, use_builtin_types=False)
99 (newdt,) = result
100 self.assertEqual(newdt, dt)
101 self.assertIs(type(newdt), xmlrpclib.DateTime)
102 self.assertIsNone(m)
Christian Heimesdae2a892008-04-19 00:55:37 +0000103
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +0000104 def test_bug_1164912 (self):
105 d = xmlrpclib.DateTime()
Tim Peters536cf992005-12-25 23:18:31 +0000106 ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +0000107 methodresponse=True))
Ezio Melottie9615932010-01-24 19:26:24 +0000108 self.assertIsInstance(new_d.value, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +0000109
110 # Check that the output of dumps() is still an 8-bit string
111 s = xmlrpclib.dumps((new_d,), methodresponse=True)
Ezio Melottie9615932010-01-24 19:26:24 +0000112 self.assertIsInstance(s, str)
Andrew M. Kuchlingbdb39012005-12-04 19:11:17 +0000113
Thomas Wouters89f507f2006-12-13 04:49:30 +0000114 def test_newstyle_class(self):
115 class T(object):
116 pass
117 t = T()
118 t.x = 100
119 t.y = "Hello"
120 ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000121 self.assertEqual(t2, t.__dict__)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000122
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000123 def test_dump_big_long(self):
Guido van Rossume2a383d2007-01-15 16:59:06 +0000124 self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,))
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000125
126 def test_dump_bad_dict(self):
127 self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))
128
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000129 def test_dump_recursive_seq(self):
130 l = [1,2,3]
131 t = [3,4,5,l]
132 l.append(t)
133 self.assertRaises(TypeError, xmlrpclib.dumps, (l,))
134
135 def test_dump_recursive_dict(self):
136 d = {'1':1, '2':1}
137 t = {'3':3, 'd':d}
138 d['t'] = t
139 self.assertRaises(TypeError, xmlrpclib.dumps, (d,))
140
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000141 def test_dump_big_int(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +0000142 if sys.maxsize > 2**31-1:
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000143 self.assertRaises(OverflowError, xmlrpclib.dumps,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000144 (int(2**34),))
Skip Montanaro3e7bba92001-10-19 16:06:52 +0000145
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000146 xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000147 self.assertRaises(OverflowError, xmlrpclib.dumps,
148 (xmlrpclib.MAXINT+1,))
149 self.assertRaises(OverflowError, xmlrpclib.dumps,
150 (xmlrpclib.MININT-1,))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000151
152 def dummy_write(s):
153 pass
154
155 m = xmlrpclib.Marshaller()
156 m.dump_int(xmlrpclib.MAXINT, dummy_write)
157 m.dump_int(xmlrpclib.MININT, dummy_write)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000158 self.assertRaises(OverflowError, m.dump_int,
159 xmlrpclib.MAXINT+1, dummy_write)
160 self.assertRaises(OverflowError, m.dump_int,
161 xmlrpclib.MININT-1, dummy_write)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000162
Florent Xicluna1917ea92012-07-07 17:03:25 +0200163 def test_dump_double(self):
164 xmlrpclib.dumps((float(2 ** 34),))
165 xmlrpclib.dumps((float(xmlrpclib.MAXINT),
166 float(xmlrpclib.MININT)))
167 xmlrpclib.dumps((float(xmlrpclib.MAXINT + 42),
168 float(xmlrpclib.MININT - 42)))
169
170 def dummy_write(s):
171 pass
172
173 m = xmlrpclib.Marshaller()
174 m.dump_double(xmlrpclib.MAXINT, dummy_write)
175 m.dump_double(xmlrpclib.MININT, dummy_write)
176 m.dump_double(xmlrpclib.MAXINT + 42, dummy_write)
177 m.dump_double(xmlrpclib.MININT - 42, dummy_write)
178
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000179 def test_dump_none(self):
180 value = alist + [None]
181 arg1 = (alist + [None],)
182 strg = xmlrpclib.dumps(arg1, allow_none=True)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertEqual(value,
Andrew M. Kuchling0b852032003-04-25 00:27:24 +0000184 xmlrpclib.loads(strg)[0][0])
185 self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
186
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200187 def test_dump_encoding(self):
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200188 value = {'key\u20ac\xa4':
189 'value\u20ac\xa4'}
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200190 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15')
191 strg = "<?xml version='1.0' encoding='iso-8859-15'?>" + strg
192 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200193 strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200194 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
195
196 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
197 methodresponse=True)
198 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200199 strg = strg.encode('iso-8859-15', 'xmlcharrefreplace')
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200200 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
201
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200202 methodname = 'method\u20ac\xa4'
203 strg = xmlrpclib.dumps((value,), encoding='iso-8859-15',
204 methodname=methodname)
205 self.assertEqual(xmlrpclib.loads(strg)[0][0], value)
206 self.assertEqual(xmlrpclib.loads(strg)[1], methodname)
207
Florent Xicluna61665192011-11-15 20:53:25 +0100208 def test_dump_bytes(self):
209 sample = b"my dog has fleas"
210 self.assertEqual(sample, xmlrpclib.Binary(sample))
211 for type_ in bytes, bytearray, xmlrpclib.Binary:
212 value = type_(sample)
213 s = xmlrpclib.dumps((value,))
214
215 result, m = xmlrpclib.loads(s, use_builtin_types=True)
216 (newvalue,) = result
217 self.assertEqual(newvalue, sample)
218 self.assertIs(type(newvalue), bytes)
219 self.assertIsNone(m)
220
221 result, m = xmlrpclib.loads(s, use_builtin_types=False)
222 (newvalue,) = result
223 self.assertEqual(newvalue, sample)
224 self.assertIs(type(newvalue), xmlrpclib.Binary)
225 self.assertIsNone(m)
226
Serhiy Storchaka290fed42016-05-04 11:26:42 +0300227 def test_loads_unsupported(self):
228 ResponseError = xmlrpclib.ResponseError
229 data = '<params><param><value><spam/></value></param></params>'
230 self.assertRaises(ResponseError, xmlrpclib.loads, data)
231 data = ('<params><param><value><array>'
232 '<value><spam/></value>'
233 '</array></value></param></params>')
234 self.assertRaises(ResponseError, xmlrpclib.loads, data)
235 data = ('<params><param><value><struct>'
236 '<member><name>a</name><value><spam/></value></member>'
237 '<member><name>b</name><value><spam/></value></member>'
238 '</struct></value></param></params>')
239 self.assertRaises(ResponseError, xmlrpclib.loads, data)
240
Georg Brandlc8dcfb62009-02-13 10:50:01 +0000241 def test_get_host_info(self):
242 # see bug #3613, this raised a TypeError
243 transp = xmlrpc.client.Transport()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000244 self.assertEqual(transp.get_host_info("user@host.tld"),
Georg Brandlc8dcfb62009-02-13 10:50:01 +0000245 ('host.tld',
246 [('Authorization', 'Basic dXNlcg==')], {}))
247
Senthil Kumaran8ce1f1f2010-11-18 15:00:53 +0000248 def test_ssl_presence(self):
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +0000249 try:
250 import ssl
Antoine Pitrou98b644f2010-11-19 20:07:52 +0000251 except ImportError:
252 has_ssl = False
Senthil Kumaran8ce1f1f2010-11-18 15:00:53 +0000253 else:
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +0000254 has_ssl = True
Senthil Kumaran8ce1f1f2010-11-18 15:00:53 +0000255 try:
256 xmlrpc.client.ServerProxy('https://localhost:9999').bad_function()
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +0000257 except NotImplementedError:
258 self.assertFalse(has_ssl, "xmlrpc client's error with SSL support")
Andrew Svetlov0832af62012-12-18 23:10:48 +0200259 except OSError:
Senthil Kumaran6a0b5c42010-11-18 17:08:48 +0000260 self.assertTrue(has_ssl)
Ezio Melottie9615932010-01-24 19:26:24 +0000261
Martin Pantereae33362016-02-25 11:53:40 +0000262 @unittest.skipUnless(threading, "Threading required for this test.")
263 def test_keepalive_disconnect(self):
264 class RequestHandler(http.server.BaseHTTPRequestHandler):
265 protocol_version = "HTTP/1.1"
266 handled = False
267
268 def do_POST(self):
269 length = int(self.headers.get("Content-Length"))
270 self.rfile.read(length)
271 if self.handled:
272 self.close_connection = True
273 return
274 response = xmlrpclib.dumps((5,), methodresponse=True)
275 response = response.encode()
276 self.send_response(http.HTTPStatus.OK)
277 self.send_header("Content-Length", len(response))
278 self.end_headers()
279 self.wfile.write(response)
280 self.handled = True
281 self.close_connection = False
282
283 def run_server():
284 server.socket.settimeout(float(1)) # Don't hang if client fails
285 server.handle_request() # First request and attempt at second
286 server.handle_request() # Retried second request
287
288 server = http.server.HTTPServer((support.HOST, 0), RequestHandler)
289 self.addCleanup(server.server_close)
290 thread = threading.Thread(target=run_server)
291 thread.start()
292 self.addCleanup(thread.join)
293 url = "http://{}:{}/".format(*server.server_address)
294 with xmlrpclib.ServerProxy(url) as p:
295 self.assertEqual(p.method(), 5)
296 self.assertEqual(p.method(), 5)
297
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000298class HelperTestCase(unittest.TestCase):
299 def test_escape(self):
300 self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
301 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
302 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
303
304class FaultTestCase(unittest.TestCase):
305 def test_repr(self):
306 f = xmlrpclib.Fault(42, 'Test Fault')
307 self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
308 self.assertEqual(repr(f), str(f))
309
310 def test_dump_fault(self):
311 f = xmlrpclib.Fault(42, 'Test Fault')
312 s = xmlrpclib.dumps((f,))
313 (newf,), m = xmlrpclib.loads(s)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000314 self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
315 self.assertEqual(m, None)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000316
317 s = xmlrpclib.Marshaller().dumps(f)
318 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
319
Christian Heimeseda9e2b2007-12-08 22:32:47 +0000320 def test_dotted_attribute(self):
Florent Xiclunac4fec932011-10-30 20:19:32 +0100321 # this will raise AttributeError because code don't want us to use
Christian Heimeseda9e2b2007-12-08 22:32:47 +0000322 # private methods
323 self.assertRaises(AttributeError,
Georg Brandl38eceaa2008-05-26 11:14:17 +0000324 xmlrpc.server.resolve_dotted_attribute, str, '__add')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000325 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000326
327class DateTimeTestCase(unittest.TestCase):
328 def test_default(self):
Ezio Melotti31916322013-08-10 18:37:05 +0300329 with mock.patch('time.localtime') as localtime_mock:
330 time_struct = time.struct_time(
331 [2013, 7, 15, 0, 24, 49, 0, 196, 0])
332 localtime_mock.return_value = time_struct
333 localtime = time.localtime()
334 t = xmlrpclib.DateTime()
335 self.assertEqual(str(t),
336 time.strftime("%Y%m%dT%H:%M:%S", localtime))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000337
338 def test_time(self):
339 d = 1181399930.036952
340 t = xmlrpclib.DateTime(d)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000341 self.assertEqual(str(t),
342 time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000343
344 def test_time_tuple(self):
345 d = (2007,6,9,10,38,50,5,160,0)
346 t = xmlrpclib.DateTime(d)
347 self.assertEqual(str(t), '20070609T10:38:50')
348
349 def test_time_struct(self):
350 d = time.localtime(1181399930.036952)
351 t = xmlrpclib.DateTime(d)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000352 self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", d))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000353
354 def test_datetime_datetime(self):
355 d = datetime.datetime(2007,1,2,3,4,5)
356 t = xmlrpclib.DateTime(d)
357 self.assertEqual(str(t), '20070102T03:04:05')
358
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000359 def test_repr(self):
360 d = datetime.datetime(2007,1,2,3,4,5)
361 t = xmlrpclib.DateTime(d)
Serhiy Storchaka0c937b32014-07-22 12:14:52 +0300362 val ="<DateTime '20070102T03:04:05' at %#x>" % id(t)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000363 self.assertEqual(repr(t), val)
364
365 def test_decode(self):
366 d = ' 20070908T07:11:13 '
367 t1 = xmlrpclib.DateTime()
368 t1.decode(d)
369 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
370 self.assertEqual(t1, tref)
371
372 t2 = xmlrpclib._datetime(d)
Ezio Melotti31916322013-08-10 18:37:05 +0300373 self.assertEqual(t2, tref)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000374
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100375 def test_comparison(self):
376 now = datetime.datetime.now()
377 dtime = xmlrpclib.DateTime(now.timetuple())
378
379 # datetime vs. DateTime
380 self.assertTrue(dtime == now)
381 self.assertTrue(now == dtime)
382 then = now + datetime.timedelta(seconds=4)
383 self.assertTrue(then >= dtime)
384 self.assertTrue(dtime < then)
385
386 # str vs. DateTime
387 dstr = now.strftime("%Y%m%dT%H:%M:%S")
388 self.assertTrue(dtime == dstr)
389 self.assertTrue(dstr == dtime)
390 dtime_then = xmlrpclib.DateTime(then.timetuple())
391 self.assertTrue(dtime_then >= dstr)
392 self.assertTrue(dstr < dtime_then)
393
394 # some other types
395 dbytes = dstr.encode('ascii')
396 dtuple = now.timetuple()
397 with self.assertRaises(TypeError):
398 dtime == 1970
399 with self.assertRaises(TypeError):
400 dtime != dbytes
401 with self.assertRaises(TypeError):
402 dtime == bytearray(dbytes)
403 with self.assertRaises(TypeError):
404 dtime != dtuple
405 with self.assertRaises(TypeError):
406 dtime < float(1970)
407 with self.assertRaises(TypeError):
408 dtime > dbytes
409 with self.assertRaises(TypeError):
410 dtime <= bytearray(dbytes)
411 with self.assertRaises(TypeError):
412 dtime >= dtuple
413
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000414class BinaryTestCase(unittest.TestCase):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000415
416 # XXX What should str(Binary(b"\xff")) return? I'm chosing "\xff"
417 # for now (i.e. interpreting the binary data as Latin-1-encoded
418 # text). But this feels very unsatisfactory. Perhaps we should
419 # only define repr(), and return r"Binary(b'\xff')" instead?
420
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000421 def test_default(self):
422 t = xmlrpclib.Binary()
423 self.assertEqual(str(t), '')
424
425 def test_string(self):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000426 d = b'\x01\x02\x03abc123\xff\xfe'
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000427 t = xmlrpclib.Binary(d)
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000428 self.assertEqual(str(t), str(d, "latin-1"))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000429
430 def test_decode(self):
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000431 d = b'\x01\x02\x03abc123\xff\xfe'
Georg Brandlb54d8012009-06-04 09:11:51 +0000432 de = base64.encodebytes(d)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000433 t1 = xmlrpclib.Binary()
434 t1.decode(de)
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000435 self.assertEqual(str(t1), str(d, "latin-1"))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000436
437 t2 = xmlrpclib._binary(de)
Guido van Rossum54a40cb2007-08-27 22:27:41 +0000438 self.assertEqual(str(t2), str(d, "latin-1"))
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000439
440
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000441ADDR = PORT = URL = None
Skip Montanaro419abda2001-10-01 17:47:44 +0000442
Christian Heimesaf98da12008-01-27 15:18:18 +0000443# The evt is set twice. First when the server is ready to serve.
444# Second when the server has been shutdown. The user must clear
445# the event after it has been set the first time to catch the second set.
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200446def http_server(evt, numrequests, requestHandler=None, encoding=None):
Guido van Rossumaf554a02007-08-16 23:48:43 +0000447 class TestInstanceClass:
448 def div(self, x, y):
Guido van Rossumaf554a02007-08-16 23:48:43 +0000449 return x // y
450
Christian Heimes255f53b2007-12-08 15:33:56 +0000451 def _methodHelp(self, name):
452 if name == 'div':
453 return 'This is the div function'
454
R David Murrayaaf17b32013-10-11 12:09:51 -0400455 class Fixture:
456 @staticmethod
457 def getData():
458 return '42'
459
Christian Heimes255f53b2007-12-08 15:33:56 +0000460 def my_function():
461 '''This is my function'''
462 return True
463
Georg Brandl38eceaa2008-05-26 11:14:17 +0000464 class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer):
Christian Heimesbbe741d2008-03-28 10:53:29 +0000465 def get_request(self):
466 # Ensure the socket is always non-blocking. On Linux, socket
467 # attributes are not inherited like they are on *BSD and Windows.
468 s, port = self.socket.accept()
469 s.setblocking(True)
470 return s, port
471
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000472 if not requestHandler:
473 requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler
474 serv = MyXMLRPCServer(("localhost", 0), requestHandler,
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200475 encoding=encoding,
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000476 logRequests=False, bind_and_activate=False)
Guido van Rossumaf554a02007-08-16 23:48:43 +0000477 try:
Guido van Rossumaf554a02007-08-16 23:48:43 +0000478 serv.server_bind()
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000479 global ADDR, PORT, URL
480 ADDR, PORT = serv.socket.getsockname()
481 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melottie130a522011-10-19 10:58:56 +0300482 #trying to connect to "localhost" using all address families, which
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000483 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
484 #on AF_INET only.
485 URL = "http://%s:%d"%(ADDR, PORT)
Guido van Rossumaf554a02007-08-16 23:48:43 +0000486 serv.server_activate()
487 serv.register_introspection_functions()
488 serv.register_multicall_functions()
489 serv.register_function(pow)
490 serv.register_function(lambda x,y: x+y, 'add')
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200491 serv.register_function(lambda x: x, 'têšt')
Christian Heimes255f53b2007-12-08 15:33:56 +0000492 serv.register_function(my_function)
R David Murrayaaf17b32013-10-11 12:09:51 -0400493 testInstance = TestInstanceClass()
494 serv.register_instance(testInstance, allow_dotted_names=True)
Christian Heimesaf98da12008-01-27 15:18:18 +0000495 evt.set()
Guido van Rossumaf554a02007-08-16 23:48:43 +0000496
497 # handle up to 'numrequests' requests
498 while numrequests > 0:
499 serv.handle_request()
500 numrequests -= 1
501
502 except socket.timeout:
503 pass
504 finally:
505 serv.socket.close()
506 PORT = None
507 evt.set()
508
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000509def http_multi_server(evt, numrequests, requestHandler=None):
510 class TestInstanceClass:
511 def div(self, x, y):
512 return x // y
513
514 def _methodHelp(self, name):
515 if name == 'div':
516 return 'This is the div function'
517
518 def my_function():
519 '''This is my function'''
520 return True
521
522 class MyXMLRPCServer(xmlrpc.server.MultiPathXMLRPCServer):
523 def get_request(self):
524 # Ensure the socket is always non-blocking. On Linux, socket
525 # attributes are not inherited like they are on *BSD and Windows.
526 s, port = self.socket.accept()
527 s.setblocking(True)
528 return s, port
529
530 if not requestHandler:
531 requestHandler = xmlrpc.server.SimpleXMLRPCRequestHandler
532 class MyRequestHandler(requestHandler):
533 rpc_paths = []
534
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100535 class BrokenDispatcher:
536 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
537 raise RuntimeError("broken dispatcher")
538
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000539 serv = MyXMLRPCServer(("localhost", 0), MyRequestHandler,
540 logRequests=False, bind_and_activate=False)
541 serv.socket.settimeout(3)
542 serv.server_bind()
543 try:
544 global ADDR, PORT, URL
545 ADDR, PORT = serv.socket.getsockname()
546 #connect to IP address directly. This avoids socket.create_connection()
Ezio Melottie130a522011-10-19 10:58:56 +0300547 #trying to connect to "localhost" using all address families, which
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000548 #causes slowdown e.g. on vista which supports AF_INET6. The server listens
549 #on AF_INET only.
550 URL = "http://%s:%d"%(ADDR, PORT)
551 serv.server_activate()
552 paths = ["/foo", "/foo/bar"]
553 for path in paths:
554 d = serv.add_dispatcher(path, xmlrpc.server.SimpleXMLRPCDispatcher())
555 d.register_introspection_functions()
556 d.register_multicall_functions()
557 serv.get_dispatcher(paths[0]).register_function(pow)
558 serv.get_dispatcher(paths[1]).register_function(lambda x,y: x+y, 'add')
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100559 serv.add_dispatcher("/is/broken", BrokenDispatcher())
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000560 evt.set()
561
562 # handle up to 'numrequests' requests
563 while numrequests > 0:
564 serv.handle_request()
565 numrequests -= 1
566
567 except socket.timeout:
568 pass
569 finally:
570 serv.socket.close()
571 PORT = None
572 evt.set()
573
Christian Heimesaf98da12008-01-27 15:18:18 +0000574# This function prevents errors like:
575# <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
576def is_unavailable_exception(e):
577 '''Returns True if the given ProtocolError is the product of a server-side
578 exception caused by the 'temporarily unavailable' response sometimes
579 given by operations on non-blocking sockets.'''
580
581 # sometimes we get a -1 error code and/or empty headers
Christian Heimes26855632008-01-27 23:50:43 +0000582 try:
583 if e.errcode == -1 or e.headers is None:
584 return True
585 exc_mess = e.headers.get('X-exception')
586 except AttributeError:
Andrew Svetlov0832af62012-12-18 23:10:48 +0200587 # Ignore OSErrors here.
Christian Heimes26855632008-01-27 23:50:43 +0000588 exc_mess = str(e)
Guido van Rossumaf554a02007-08-16 23:48:43 +0000589
Christian Heimes26855632008-01-27 23:50:43 +0000590 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
591 return True
Thomas Woutersed03b412007-08-28 21:37:11 +0000592
R. David Murray378c0cf2010-02-24 01:46:21 +0000593def make_request_and_skipIf(condition, reason):
Serhiy Storchaka56a6d852014-12-01 18:28:43 +0200594 # If we skip the test, we have to make a request because
R. David Murray378c0cf2010-02-24 01:46:21 +0000595 # the server created in setUp blocks expecting one to come in.
596 if not condition:
597 return lambda func: func
598 def decorator(func):
599 def make_request_and_skip(self):
600 try:
601 xmlrpclib.ServerProxy(URL).my_function()
Andrew Svetlov0832af62012-12-18 23:10:48 +0200602 except (xmlrpclib.ProtocolError, OSError) as e:
R. David Murray378c0cf2010-02-24 01:46:21 +0000603 if not is_unavailable_exception(e):
604 raise
605 raise unittest.SkipTest(reason)
606 return make_request_and_skip
607 return decorator
608
Victor Stinner45df8202010-04-28 22:31:17 +0000609@unittest.skipUnless(threading, 'Threading required for this test.')
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000610class BaseServerTestCase(unittest.TestCase):
611 requestHandler = None
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000612 request_count = 1
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000613 threadFunc = staticmethod(http_server)
Victor Stinner45df8202010-04-28 22:31:17 +0000614
Guido van Rossumaf554a02007-08-16 23:48:43 +0000615 def setUp(self):
Guido van Rossum61e21b52007-08-20 19:06:03 +0000616 # enable traceback reporting
Georg Brandl38eceaa2008-05-26 11:14:17 +0000617 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
Guido van Rossum61e21b52007-08-20 19:06:03 +0000618
Guido van Rossumaf554a02007-08-16 23:48:43 +0000619 self.evt = threading.Event()
Guido van Rossum61e21b52007-08-20 19:06:03 +0000620 # start server thread to handle requests
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000621 serv_args = (self.evt, self.request_count, self.requestHandler)
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000622 threading.Thread(target=self.threadFunc, args=serv_args).start()
Guido van Rossumaf554a02007-08-16 23:48:43 +0000623
Christian Heimesaf98da12008-01-27 15:18:18 +0000624 # wait for the server to be ready
625 self.evt.wait()
626 self.evt.clear()
Guido van Rossumaf554a02007-08-16 23:48:43 +0000627
628 def tearDown(self):
629 # wait on the server thread to terminate
Charles-François Natalicd96b4f2012-02-18 14:53:41 +0100630 self.evt.wait()
Guido van Rossumaf554a02007-08-16 23:48:43 +0000631
Guido van Rossum61e21b52007-08-20 19:06:03 +0000632 # disable traceback reporting
Georg Brandl38eceaa2008-05-26 11:14:17 +0000633 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
Guido van Rossum61e21b52007-08-20 19:06:03 +0000634
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000635class SimpleServerTestCase(BaseServerTestCase):
Guido van Rossumaf554a02007-08-16 23:48:43 +0000636 def test_simple1(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000637 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000638 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000639 self.assertEqual(p.pow(6,8), 6**8)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200640 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +0000641 # ignore failures due to non-blocking socket 'unavailable' errors
642 if not is_unavailable_exception(e):
643 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000644 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Guido van Rossumaf554a02007-08-16 23:48:43 +0000645
Senthil Kumaranb3af08f2009-04-01 20:20:43 +0000646 def test_nonascii(self):
647 start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
648 end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
649 try:
650 p = xmlrpclib.ServerProxy(URL)
651 self.assertEqual(p.add(start_string, end_string),
652 start_string + end_string)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200653 except (xmlrpclib.ProtocolError, OSError) as e:
Senthil Kumaranb3af08f2009-04-01 20:20:43 +0000654 # ignore failures due to non-blocking socket 'unavailable' errors
655 if not is_unavailable_exception(e):
656 # protocol error; provide additional information in test output
657 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
658
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200659 def test_client_encoding(self):
660 start_string = '\u20ac'
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200661 end_string = '\xa4'
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200662
663 try:
664 p = xmlrpclib.ServerProxy(URL, encoding='iso-8859-15')
665 self.assertEqual(p.add(start_string, end_string),
666 start_string + end_string)
667 except (xmlrpclib.ProtocolError, socket.error) as e:
668 # ignore failures due to non-blocking socket unavailable errors.
669 if not is_unavailable_exception(e):
670 # protocol error; provide additional information in test output
671 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
672
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200673 def test_nonascii_methodname(self):
674 try:
675 p = xmlrpclib.ServerProxy(URL, encoding='ascii')
676 self.assertEqual(p.têšt(42), 42)
677 except (xmlrpclib.ProtocolError, socket.error) as e:
678 # ignore failures due to non-blocking socket unavailable errors.
679 if not is_unavailable_exception(e):
680 # protocol error; provide additional information in test output
681 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
682
Georg Brandlfceab5a2008-01-19 20:08:23 +0000683 # [ch] The test 404 is causing lots of false alarms.
684 def XXXtest_404(self):
Georg Brandl24420152008-05-26 16:32:26 +0000685 # send POST with http.client, it should return 404 header and
Christian Heimes255f53b2007-12-08 15:33:56 +0000686 # 'Not Found' message.
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000687 conn = httplib.client.HTTPConnection(ADDR, PORT)
Christian Heimes99d73f22007-12-08 16:13:06 +0000688 conn.request('POST', '/this-is-not-valid')
Christian Heimes255f53b2007-12-08 15:33:56 +0000689 response = conn.getresponse()
690 conn.close()
691
692 self.assertEqual(response.status, 404)
693 self.assertEqual(response.reason, 'Not Found')
694
Guido van Rossumaf554a02007-08-16 23:48:43 +0000695 def test_introspection1(self):
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200696 expected_methods = set(['pow', 'div', 'my_function', 'add', 'têšt',
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000697 'system.listMethods', 'system.methodHelp',
R David Murrayaaf17b32013-10-11 12:09:51 -0400698 'system.methodSignature', 'system.multicall',
699 'Fixture'])
Guido van Rossum04110fb2007-08-24 16:32:05 +0000700 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000701 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000702 meth = p.system.listMethods()
Guido van Rossum04110fb2007-08-24 16:32:05 +0000703 self.assertEqual(set(meth), expected_methods)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200704 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +0000705 # ignore failures due to non-blocking socket 'unavailable' errors
706 if not is_unavailable_exception(e):
707 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000708 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Christian Heimes412dc9c2008-01-27 18:55:54 +0000709
Guido van Rossumaf554a02007-08-16 23:48:43 +0000710
711 def test_introspection2(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000712 try:
Christian Heimes255f53b2007-12-08 15:33:56 +0000713 # test _methodHelp()
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000714 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000715 divhelp = p.system.methodHelp('div')
716 self.assertEqual(divhelp, 'This is the div function')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200717 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +0000718 # ignore failures due to non-blocking socket 'unavailable' errors
719 if not is_unavailable_exception(e):
720 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000721 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Guido van Rossumaf554a02007-08-16 23:48:43 +0000722
R. David Murray378c0cf2010-02-24 01:46:21 +0000723 @make_request_and_skipIf(sys.flags.optimize >= 2,
724 "Docstrings are omitted with -O2 and above")
Guido van Rossumaf554a02007-08-16 23:48:43 +0000725 def test_introspection3(self):
Christian Heimes255f53b2007-12-08 15:33:56 +0000726 try:
727 # test native doc
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000728 p = xmlrpclib.ServerProxy(URL)
Christian Heimes255f53b2007-12-08 15:33:56 +0000729 myfunction = p.system.methodHelp('my_function')
730 self.assertEqual(myfunction, 'This is my function')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200731 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes255f53b2007-12-08 15:33:56 +0000732 # ignore failures due to non-blocking socket 'unavailable' errors
733 if not is_unavailable_exception(e):
734 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000735 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Christian Heimes255f53b2007-12-08 15:33:56 +0000736
737 def test_introspection4(self):
Guido van Rossumaf554a02007-08-16 23:48:43 +0000738 # the SimpleXMLRPCServer doesn't support signatures, but
Thomas Woutersed03b412007-08-28 21:37:11 +0000739 # at least check that we can try making the call
Guido van Rossum04110fb2007-08-24 16:32:05 +0000740 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000741 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000742 divsig = p.system.methodSignature('div')
743 self.assertEqual(divsig, 'signatures not supported')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200744 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +0000745 # ignore failures due to non-blocking socket 'unavailable' errors
746 if not is_unavailable_exception(e):
747 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000748 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Guido van Rossumaf554a02007-08-16 23:48:43 +0000749
750 def test_multicall(self):
Guido van Rossum04110fb2007-08-24 16:32:05 +0000751 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000752 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +0000753 multicall = xmlrpclib.MultiCall(p)
754 multicall.add(2,3)
755 multicall.pow(6,8)
756 multicall.div(127,42)
757 add_result, pow_result, div_result = multicall()
758 self.assertEqual(add_result, 2+3)
759 self.assertEqual(pow_result, 6**8)
760 self.assertEqual(div_result, 127//42)
Andrew Svetlov0832af62012-12-18 23:10:48 +0200761 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +0000762 # ignore failures due to non-blocking socket 'unavailable' errors
763 if not is_unavailable_exception(e):
764 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000765 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Guido van Rossumaf554a02007-08-16 23:48:43 +0000766
Christian Heimes255f53b2007-12-08 15:33:56 +0000767 def test_non_existing_multicall(self):
768 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +0000769 p = xmlrpclib.ServerProxy(URL)
Christian Heimes255f53b2007-12-08 15:33:56 +0000770 multicall = xmlrpclib.MultiCall(p)
771 multicall.this_is_not_exists()
772 result = multicall()
773
774 # result.results contains;
Martin v. Löwis250ad612008-04-07 05:43:42 +0000775 # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'>:'
Christian Heimes255f53b2007-12-08 15:33:56 +0000776 # 'method "this_is_not_exists" is not supported'>}]
777
778 self.assertEqual(result.results[0]['faultCode'], 1)
779 self.assertEqual(result.results[0]['faultString'],
Martin v. Löwis250ad612008-04-07 05:43:42 +0000780 '<class \'Exception\'>:method "this_is_not_exists" '
Christian Heimes255f53b2007-12-08 15:33:56 +0000781 'is not supported')
Andrew Svetlov0832af62012-12-18 23:10:48 +0200782 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes255f53b2007-12-08 15:33:56 +0000783 # ignore failures due to non-blocking socket 'unavailable' errors
784 if not is_unavailable_exception(e):
785 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +0000786 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Christian Heimes255f53b2007-12-08 15:33:56 +0000787
Christian Heimesfe337bf2008-03-23 21:54:12 +0000788 def test_dotted_attribute(self):
789 # Raises an AttributeError because private methods are not allowed.
790 self.assertRaises(AttributeError,
Georg Brandl38eceaa2008-05-26 11:14:17 +0000791 xmlrpc.server.resolve_dotted_attribute, str, '__add')
Christian Heimesfe337bf2008-03-23 21:54:12 +0000792
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000793 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
Christian Heimesfe337bf2008-03-23 21:54:12 +0000794 # Get the test to run faster by sending a request with test_simple1.
795 # This avoids waiting for the socket timeout.
796 self.test_simple1()
797
R David Murrayaaf17b32013-10-11 12:09:51 -0400798 def test_allow_dotted_names_true(self):
799 # XXX also need allow_dotted_names_false test.
800 server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
801 data = server.Fixture.getData()
802 self.assertEqual(data, '42')
803
Victor Stinnerda6eb532011-09-23 01:29:44 +0200804 def test_unicode_host(self):
805 server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
806 self.assertEqual(server.add("a", "\xe9"), "a\xe9")
807
Charles-François Natalicd96b4f2012-02-18 14:53:41 +0100808 def test_partial_post(self):
809 # Check that a partial POST doesn't make the server loop: issue #14001.
810 conn = http.client.HTTPConnection(ADDR, PORT)
811 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
812 conn.close()
813
Brett Cannon33a40002014-03-21 11:24:40 -0400814 def test_context_manager(self):
815 with xmlrpclib.ServerProxy(URL) as server:
816 server.add(2, 3)
817 self.assertNotEqual(server('transport')._connection,
818 (None, None))
819 self.assertEqual(server('transport')._connection,
820 (None, None))
821
822 def test_context_manager_method_error(self):
823 try:
824 with xmlrpclib.ServerProxy(URL) as server:
825 server.add(2, "a")
826 except xmlrpclib.Fault:
827 pass
828 self.assertEqual(server('transport')._connection,
829 (None, None))
830
Charles-François Natalicd96b4f2012-02-18 14:53:41 +0100831
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200832class SimpleServerEncodingTestCase(BaseServerTestCase):
833 @staticmethod
834 def threadFunc(evt, numrequests, requestHandler=None, encoding=None):
835 http_server(evt, numrequests, requestHandler, 'iso-8859-15')
836
837 def test_server_encoding(self):
838 start_string = '\u20ac'
Serhiy Storchakaaebb6d32016-01-20 10:34:27 +0200839 end_string = '\xa4'
Serhiy Storchaka084f7e42016-01-18 19:39:26 +0200840
841 try:
842 p = xmlrpclib.ServerProxy(URL)
843 self.assertEqual(p.add(start_string, end_string),
844 start_string + end_string)
845 except (xmlrpclib.ProtocolError, socket.error) as e:
846 # ignore failures due to non-blocking socket unavailable errors.
847 if not is_unavailable_exception(e):
848 # protocol error; provide additional information in test output
849 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
850
851
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000852class MultiPathServerTestCase(BaseServerTestCase):
853 threadFunc = staticmethod(http_multi_server)
854 request_count = 2
855 def test_path1(self):
856 p = xmlrpclib.ServerProxy(URL+"/foo")
857 self.assertEqual(p.pow(6,8), 6**8)
858 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100859
Kristján Valur Jónsson1f2a1ae2009-12-16 10:50:44 +0000860 def test_path2(self):
861 p = xmlrpclib.ServerProxy(URL+"/foo/bar")
862 self.assertEqual(p.add(6,8), 6+8)
863 self.assertRaises(xmlrpclib.Fault, p.pow, 6, 8)
864
Florent Xicluna3fa29f72011-10-30 20:18:50 +0100865 def test_path3(self):
866 p = xmlrpclib.ServerProxy(URL+"/is/broken")
867 self.assertRaises(xmlrpclib.Fault, p.add, 6, 8)
868
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000869#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
870#does indeed serve subsequent requests on the same connection
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000871class BaseKeepaliveServerTestCase(BaseServerTestCase):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000872 #a request handler that supports keep-alive and logs requests into a
873 #class variable
874 class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
875 parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler
876 protocol_version = 'HTTP/1.1'
877 myRequests = []
878 def handle(self):
879 self.myRequests.append([])
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000880 self.reqidx = len(self.myRequests)-1
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000881 return self.parentClass.handle(self)
882 def handle_one_request(self):
883 result = self.parentClass.handle_one_request(self)
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000884 self.myRequests[self.reqidx].append(self.raw_requestline)
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000885 return result
886
887 requestHandler = RequestHandler
888 def setUp(self):
889 #clear request log
890 self.RequestHandler.myRequests = []
891 return BaseServerTestCase.setUp(self)
892
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000893#A test case that verifies that a server using the HTTP/1.1 keep-alive mechanism
894#does indeed serve subsequent requests on the same connection
895class KeepaliveServerTestCase1(BaseKeepaliveServerTestCase):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000896 def test_two(self):
897 p = xmlrpclib.ServerProxy(URL)
Kristján Valur Jónsson1bbb19a2009-07-11 21:57:16 +0000898 #do three requests.
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000899 self.assertEqual(p.pow(6,8), 6**8)
900 self.assertEqual(p.pow(6,8), 6**8)
Kristján Valur Jónsson1bbb19a2009-07-11 21:57:16 +0000901 self.assertEqual(p.pow(6,8), 6**8)
Victor Stinnera935e8f2011-01-03 14:30:44 +0000902 p("close")()
Kristján Valur Jónsson1bbb19a2009-07-11 21:57:16 +0000903
904 #they should have all been handled by a single request handler
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000905 self.assertEqual(len(self.RequestHandler.myRequests), 1)
Kristján Valur Jónsson1bbb19a2009-07-11 21:57:16 +0000906
907 #check that we did at least two (the third may be pending append
908 #due to thread scheduling)
909 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000910
Victor Stinnera935e8f2011-01-03 14:30:44 +0000911
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000912#test special attribute access on the serverproxy, through the __call__
913#function.
914class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
915 #ask for two keepalive requests to be handled.
916 request_count=2
917
918 def test_close(self):
919 p = xmlrpclib.ServerProxy(URL)
920 #do some requests with close.
921 self.assertEqual(p.pow(6,8), 6**8)
922 self.assertEqual(p.pow(6,8), 6**8)
923 self.assertEqual(p.pow(6,8), 6**8)
924 p("close")() #this should trigger a new keep-alive request
925 self.assertEqual(p.pow(6,8), 6**8)
926 self.assertEqual(p.pow(6,8), 6**8)
927 self.assertEqual(p.pow(6,8), 6**8)
Victor Stinnera935e8f2011-01-03 14:30:44 +0000928 p("close")()
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000929
930 #they should have all been two request handlers, each having logged at least
931 #two complete requests
932 self.assertEqual(len(self.RequestHandler.myRequests), 2)
933 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
934 self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
935
Victor Stinnera935e8f2011-01-03 14:30:44 +0000936
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000937 def test_transport(self):
938 p = xmlrpclib.ServerProxy(URL)
939 #do some requests with close.
940 self.assertEqual(p.pow(6,8), 6**8)
941 p("transport").close() #same as above, really.
942 self.assertEqual(p.pow(6,8), 6**8)
Victor Stinnera935e8f2011-01-03 14:30:44 +0000943 p("close")()
Kristján Valur Jónssonf6087ca2009-07-12 22:45:18 +0000944 self.assertEqual(len(self.RequestHandler.myRequests), 2)
945
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000946#A test case that verifies that gzip encoding works in both directions
947#(for a request and the response)
Brett Cannon603dcf22013-06-12 20:04:19 -0400948@unittest.skipIf(gzip is None, 'requires gzip')
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000949class GzipServerTestCase(BaseServerTestCase):
950 #a request handler that supports keep-alive and logs requests into a
951 #class variable
952 class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
953 parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler
954 protocol_version = 'HTTP/1.1'
955
956 def do_POST(self):
957 #store content of last request in class
958 self.__class__.content_length = int(self.headers["content-length"])
959 return self.parentClass.do_POST(self)
960 requestHandler = RequestHandler
961
962 class Transport(xmlrpclib.Transport):
963 #custom transport, stores the response length for our perusal
964 fake_gzip = False
965 def parse_response(self, response):
966 self.response_length=int(response.getheader("content-length", 0))
967 return xmlrpclib.Transport.parse_response(self, response)
968
969 def send_content(self, connection, body):
970 if self.fake_gzip:
971 #add a lone gzip header to induce decode error remotely
972 connection.putheader("Content-Encoding", "gzip")
973 return xmlrpclib.Transport.send_content(self, connection, body)
974
Victor Stinner45df8202010-04-28 22:31:17 +0000975 def setUp(self):
976 BaseServerTestCase.setUp(self)
977
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000978 def test_gzip_request(self):
979 t = self.Transport()
980 t.encode_threshold = None
981 p = xmlrpclib.ServerProxy(URL, transport=t)
982 self.assertEqual(p.pow(6,8), 6**8)
983 a = self.RequestHandler.content_length
984 t.encode_threshold = 0 #turn on request encoding
985 self.assertEqual(p.pow(6,8), 6**8)
986 b = self.RequestHandler.content_length
987 self.assertTrue(a>b)
Victor Stinnera935e8f2011-01-03 14:30:44 +0000988 p("close")()
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000989
990 def test_bad_gzip_request(self):
991 t = self.Transport()
992 t.encode_threshold = None
993 t.fake_gzip = True
994 p = xmlrpclib.ServerProxy(URL, transport=t)
Ezio Melottied3a7d22010-12-01 02:32:32 +0000995 cm = self.assertRaisesRegex(xmlrpclib.ProtocolError,
996 re.compile(r"\b400\b"))
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +0000997 with cm:
998 p.pow(6, 8)
Victor Stinnera935e8f2011-01-03 14:30:44 +0000999 p("close")()
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001000
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001001 def test_gzip_response(self):
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001002 t = self.Transport()
1003 p = xmlrpclib.ServerProxy(URL, transport=t)
1004 old = self.requestHandler.encode_threshold
1005 self.requestHandler.encode_threshold = None #no encoding
1006 self.assertEqual(p.pow(6,8), 6**8)
1007 a = t.response_length
1008 self.requestHandler.encode_threshold = 0 #always encode
1009 self.assertEqual(p.pow(6,8), 6**8)
Victor Stinnera935e8f2011-01-03 14:30:44 +00001010 p("close")()
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001011 b = t.response_length
1012 self.requestHandler.encode_threshold = old
1013 self.assertTrue(a>b)
1014
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001015
Benjamin Petersoneca72d42014-12-05 20:34:56 -05001016@unittest.skipIf(gzip is None, 'requires gzip')
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001017class GzipUtilTestCase(unittest.TestCase):
1018
1019 def test_gzip_decode_limit(self):
1020 max_gzip_decode = 20 * 1024 * 1024
1021 data = b'\0' * max_gzip_decode
1022 encoded = xmlrpclib.gzip_encode(data)
1023 decoded = xmlrpclib.gzip_decode(encoded)
1024 self.assertEqual(len(decoded), max_gzip_decode)
1025
1026 data = b'\0' * (max_gzip_decode + 1)
1027 encoded = xmlrpclib.gzip_encode(data)
1028
Brett Cannon92716772014-12-12 12:00:02 -05001029 with self.assertRaisesRegex(ValueError,
Serhiy Storchaka93da9b52015-04-10 12:52:09 +03001030 "max gzipped payload length exceeded"):
Benjamin Peterson4e9cefa2014-12-05 20:15:15 -05001031 xmlrpclib.gzip_decode(encoded)
1032
1033 xmlrpclib.gzip_decode(encoded, max_decode=-1)
1034
1035
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001036#Test special attributes of the ServerProxy object
1037class ServerProxyTestCase(unittest.TestCase):
Victor Stinner45df8202010-04-28 22:31:17 +00001038 def setUp(self):
1039 unittest.TestCase.setUp(self)
1040 if threading:
1041 self.url = URL
1042 else:
1043 # Without threading, http_server() and http_multi_server() will not
1044 # be executed and URL is still equal to None. 'http://' is a just
1045 # enough to choose the scheme (HTTP)
1046 self.url = 'http://'
1047
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001048 def test_close(self):
Victor Stinner45df8202010-04-28 22:31:17 +00001049 p = xmlrpclib.ServerProxy(self.url)
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001050 self.assertEqual(p('close')(), None)
1051
1052 def test_transport(self):
1053 t = xmlrpclib.Transport()
Victor Stinner45df8202010-04-28 22:31:17 +00001054 p = xmlrpclib.ServerProxy(self.url, transport=t)
Kristján Valur Jónsson985fc6a2009-07-01 10:01:31 +00001055 self.assertEqual(p('transport'), t)
1056
Brett Cannon33a40002014-03-21 11:24:40 -04001057
Guido van Rossum61e21b52007-08-20 19:06:03 +00001058# This is a contrived way to make a failure occur on the server side
1059# in order to test the _send_traceback_header flag on the server
Barry Warsaw820c1202008-06-12 04:06:45 +00001060class FailingMessageClass(http.client.HTTPMessage):
1061 def get(self, key, failobj=None):
Guido van Rossum61e21b52007-08-20 19:06:03 +00001062 key = key.lower()
1063 if key == 'content-length':
1064 return 'I am broken'
Barry Warsaw820c1202008-06-12 04:06:45 +00001065 return super().get(key, failobj)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001066
1067
Victor Stinner45df8202010-04-28 22:31:17 +00001068@unittest.skipUnless(threading, 'Threading required for this test.')
Guido van Rossum61e21b52007-08-20 19:06:03 +00001069class FailingServerTestCase(unittest.TestCase):
1070 def setUp(self):
1071 self.evt = threading.Event()
1072 # start server thread to handle requests
Guido van Rossum15c97462007-11-02 16:10:06 +00001073 serv_args = (self.evt, 1)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001074 threading.Thread(target=http_server, args=serv_args).start()
1075
Christian Heimesaf98da12008-01-27 15:18:18 +00001076 # wait for the server to be ready
1077 self.evt.wait()
1078 self.evt.clear()
Guido van Rossum61e21b52007-08-20 19:06:03 +00001079
1080 def tearDown(self):
1081 # wait on the server thread to terminate
1082 self.evt.wait()
1083 # reset flag
Georg Brandl38eceaa2008-05-26 11:14:17 +00001084 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
Guido van Rossum61e21b52007-08-20 19:06:03 +00001085 # reset message class
Barry Warsaw820c1202008-06-12 04:06:45 +00001086 default_class = http.client.HTTPMessage
1087 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = default_class
Guido van Rossum61e21b52007-08-20 19:06:03 +00001088
1089 def test_basic(self):
1090 # check that flag is false by default
Georg Brandl38eceaa2008-05-26 11:14:17 +00001091 flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header
Guido van Rossum61e21b52007-08-20 19:06:03 +00001092 self.assertEqual(flagval, False)
1093
Guido van Rossum04110fb2007-08-24 16:32:05 +00001094 # enable traceback reporting
Georg Brandl38eceaa2008-05-26 11:14:17 +00001095 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
Guido van Rossum04110fb2007-08-24 16:32:05 +00001096
1097 # test a call that shouldn't fail just as a smoke test
1098 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001099 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum04110fb2007-08-24 16:32:05 +00001100 self.assertEqual(p.pow(6,8), 6**8)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001101 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +00001102 # ignore failures due to non-blocking socket 'unavailable' errors
1103 if not is_unavailable_exception(e):
1104 # protocol error; provide additional information in test output
Christian Heimes26855632008-01-27 23:50:43 +00001105 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
Guido van Rossum61e21b52007-08-20 19:06:03 +00001106
1107 def test_fail_no_info(self):
1108 # use the broken message class
Georg Brandl38eceaa2008-05-26 11:14:17 +00001109 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
Guido van Rossum61e21b52007-08-20 19:06:03 +00001110
1111 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001112 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001113 p.pow(6,8)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001114 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +00001115 # ignore failures due to non-blocking socket 'unavailable' errors
Christian Heimes26855632008-01-27 23:50:43 +00001116 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Christian Heimes412dc9c2008-01-27 18:55:54 +00001117 # The two server-side error headers shouldn't be sent back in this case
1118 self.assertTrue(e.headers.get("X-exception") is None)
1119 self.assertTrue(e.headers.get("X-traceback") is None)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001120 else:
1121 self.fail('ProtocolError not raised')
1122
1123 def test_fail_with_info(self):
1124 # use the broken message class
Georg Brandl38eceaa2008-05-26 11:14:17 +00001125 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass
Guido van Rossum61e21b52007-08-20 19:06:03 +00001126
1127 # Check that errors in the server send back exception/traceback
1128 # info when flag is set
Georg Brandl38eceaa2008-05-26 11:14:17 +00001129 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
Guido van Rossum61e21b52007-08-20 19:06:03 +00001130
1131 try:
Benjamin Petersone1cdfd72009-01-18 21:02:37 +00001132 p = xmlrpclib.ServerProxy(URL)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001133 p.pow(6,8)
Andrew Svetlov0832af62012-12-18 23:10:48 +02001134 except (xmlrpclib.ProtocolError, OSError) as e:
Christian Heimes412dc9c2008-01-27 18:55:54 +00001135 # ignore failures due to non-blocking socket 'unavailable' errors
Christian Heimes26855632008-01-27 23:50:43 +00001136 if not is_unavailable_exception(e) and hasattr(e, "headers"):
Christian Heimes412dc9c2008-01-27 18:55:54 +00001137 # We should get error info in the response
1138 expected_err = "invalid literal for int() with base 10: 'I am broken'"
Barry Warsaw820c1202008-06-12 04:06:45 +00001139 self.assertEqual(e.headers.get("X-exception"), expected_err)
1140 self.assertTrue(e.headers.get("X-traceback") is not None)
Guido van Rossum61e21b52007-08-20 19:06:03 +00001141 else:
1142 self.fail('ProtocolError not raised')
1143
R. David Murray0548ce02009-10-26 08:24:14 +00001144
1145@contextlib.contextmanager
1146def captured_stdout(encoding='utf-8'):
1147 """A variation on support.captured_stdout() which gives a text stream
1148 having a `buffer` attribute.
1149 """
1150 import io
1151 orig_stdout = sys.stdout
1152 sys.stdout = io.TextIOWrapper(io.BytesIO(), encoding=encoding)
1153 try:
1154 yield sys.stdout
1155 finally:
1156 sys.stdout = orig_stdout
1157
1158
Christian Heimes255f53b2007-12-08 15:33:56 +00001159class CGIHandlerTestCase(unittest.TestCase):
1160 def setUp(self):
Georg Brandl38eceaa2008-05-26 11:14:17 +00001161 self.cgi = xmlrpc.server.CGIXMLRPCRequestHandler()
Christian Heimes255f53b2007-12-08 15:33:56 +00001162
1163 def tearDown(self):
1164 self.cgi = None
1165
1166 def test_cgi_get(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +00001167 with support.EnvironmentVarGuard() as env:
Walter Dörwald155374d2009-05-01 19:58:58 +00001168 env['REQUEST_METHOD'] = 'GET'
Walter Dörwaldb525e182009-04-26 21:39:21 +00001169 # if the method is GET and no request_text is given, it runs handle_get
1170 # get sysout output
R. David Murray0548ce02009-10-26 08:24:14 +00001171 with captured_stdout(encoding=self.cgi.encoding) as data_out:
Nick Coghlan6ead5522009-10-18 13:19:33 +00001172 self.cgi.handle_request()
Christian Heimes255f53b2007-12-08 15:33:56 +00001173
Walter Dörwaldb525e182009-04-26 21:39:21 +00001174 # parse Status header
Nick Coghlan6ead5522009-10-18 13:19:33 +00001175 data_out.seek(0)
1176 handle = data_out.read()
Walter Dörwaldb525e182009-04-26 21:39:21 +00001177 status = handle.split()[1]
1178 message = ' '.join(handle.split()[2:4])
Christian Heimes255f53b2007-12-08 15:33:56 +00001179
Walter Dörwaldb525e182009-04-26 21:39:21 +00001180 self.assertEqual(status, '400')
1181 self.assertEqual(message, 'Bad Request')
Christian Heimes255f53b2007-12-08 15:33:56 +00001182
Christian Heimes255f53b2007-12-08 15:33:56 +00001183
1184 def test_cgi_xmlrpc_response(self):
1185 data = """<?xml version='1.0'?>
Nick Coghlan6ead5522009-10-18 13:19:33 +00001186 <methodCall>
1187 <methodName>test_method</methodName>
1188 <params>
1189 <param>
1190 <value><string>foo</string></value>
1191 </param>
1192 <param>
1193 <value><string>bar</string></value>
1194 </param>
1195 </params>
1196 </methodCall>
1197 """
Christian Heimes255f53b2007-12-08 15:33:56 +00001198
Nick Coghlan6ead5522009-10-18 13:19:33 +00001199 with support.EnvironmentVarGuard() as env, \
R. David Murray0548ce02009-10-26 08:24:14 +00001200 captured_stdout(encoding=self.cgi.encoding) as data_out, \
Nick Coghlan6ead5522009-10-18 13:19:33 +00001201 support.captured_stdin() as data_in:
1202 data_in.write(data)
1203 data_in.seek(0)
Walter Dörwald155374d2009-05-01 19:58:58 +00001204 env['CONTENT_LENGTH'] = str(len(data))
Georg Brandlc7485062009-04-01 15:53:15 +00001205 self.cgi.handle_request()
Nick Coghlan6ead5522009-10-18 13:19:33 +00001206 data_out.seek(0)
Christian Heimes255f53b2007-12-08 15:33:56 +00001207
1208 # will respond exception, if so, our goal is achieved ;)
Nick Coghlan6ead5522009-10-18 13:19:33 +00001209 handle = data_out.read()
Christian Heimes255f53b2007-12-08 15:33:56 +00001210
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001211 # start with 44th char so as not to get http header, we just
1212 # need only xml
Christian Heimes255f53b2007-12-08 15:33:56 +00001213 self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])
1214
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001215 # Also test the content-length returned by handle_request
1216 # Using the same test method inorder to avoid all the datapassing
1217 # boilerplate code.
1218 # Test for bug: http://bugs.python.org/issue5040
1219
1220 content = handle[handle.find("<?xml"):]
1221
Ezio Melottib3aedd42010-11-20 19:04:17 +00001222 self.assertEqual(
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001223 int(re.search('Content-Length: (\d+)', handle).group(1)),
1224 len(content))
1225
Senthil Kumaranb3af08f2009-04-01 20:20:43 +00001226
Florent Xicluna1b7458b2011-12-09 22:35:06 +01001227class UseBuiltinTypesTestCase(unittest.TestCase):
1228
1229 def test_use_builtin_types(self):
1230 # SimpleXMLRPCDispatcher.__init__ accepts use_builtin_types, which
1231 # makes all dispatch of binary data as bytes instances, and all
1232 # dispatch of datetime argument as datetime.datetime instances.
1233 self.log = []
1234 expected_bytes = b"my dog has fleas"
1235 expected_date = datetime.datetime(2008, 5, 26, 18, 25, 12)
1236 marshaled = xmlrpclib.dumps((expected_bytes, expected_date), 'foobar')
1237 def foobar(*args):
1238 self.log.extend(args)
1239 handler = xmlrpc.server.SimpleXMLRPCDispatcher(
1240 allow_none=True, encoding=None, use_builtin_types=True)
1241 handler.register_function(foobar)
1242 handler._marshaled_dispatch(marshaled)
1243 self.assertEqual(len(self.log), 2)
1244 mybytes, mydate = self.log
1245 self.assertEqual(self.log, [expected_bytes, expected_date])
1246 self.assertIs(type(mydate), datetime.datetime)
1247 self.assertIs(type(mybytes), bytes)
1248
1249 def test_cgihandler_has_use_builtin_types_flag(self):
1250 handler = xmlrpc.server.CGIXMLRPCRequestHandler(use_builtin_types=True)
1251 self.assertTrue(handler.use_builtin_types)
1252
1253 def test_xmlrpcserver_has_use_builtin_types_flag(self):
1254 server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0),
1255 use_builtin_types=True)
1256 server.server_close()
1257 self.assertTrue(server.use_builtin_types)
1258
1259
Brett Cannone382b582013-06-12 21:25:23 -04001260@support.reap_threads
1261def test_main():
1262 support.run_unittest(XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
1263 BinaryTestCase, FaultTestCase, UseBuiltinTypesTestCase,
Serhiy Storchaka084f7e42016-01-18 19:39:26 +02001264 SimpleServerTestCase, SimpleServerEncodingTestCase,
1265 KeepaliveServerTestCase1, KeepaliveServerTestCase2,
1266 GzipServerTestCase, GzipUtilTestCase,
Brett Cannone382b582013-06-12 21:25:23 -04001267 MultiPathServerTestCase, ServerProxyTestCase, FailingServerTestCase,
1268 CGIHandlerTestCase)
1269
1270
Skip Montanaro419abda2001-10-01 17:47:44 +00001271if __name__ == "__main__":
Brett Cannone382b582013-06-12 21:25:23 -04001272 test_main()