Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(257338)

Delta Between Two Patch Sets: Lib/test/test_xmlrpc.py

Issue 16510: Using appropriate checks in tests
Left Patch Set: Created 6 years, 9 months ago
Right Patch Set: Created 5 years, 6 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/test_xdrlib.py ('k') | Lib/test/test_zlib.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 import base64 1 import base64
2 import datetime 2 import datetime
3 import sys 3 import sys
4 import time 4 import time
5 import unittest 5 import unittest
6 from unittest import mock
6 import xmlrpc.client as xmlrpclib 7 import xmlrpc.client as xmlrpclib
7 import xmlrpc.server 8 import xmlrpc.server
8 import http.client 9 import http.client
9 import socket 10 import socket
10 import os 11 import os
11 import re 12 import re
12 import io 13 import io
13 import contextlib 14 import contextlib
14 from test import support 15 from test import support
15 16
17 try:
18 import gzip
19 except ImportError:
20 gzip = None
16 try: 21 try:
17 import threading 22 import threading
18 except ImportError: 23 except ImportError:
19 threading = None 24 threading = None
20 25
21 alist = [{'astring': 'foo@bar.baz.spam', 26 alist = [{'astring': 'foo@bar.baz.spam',
22 'afloat': 7283.43, 27 'afloat': 7283.43,
23 'anint': 2**20, 28 'anint': 2**20,
24 'ashortlong': 2, 29 'ashortlong': 2,
25 'anotherlist': ['.zyx.41'], 30 'anotherlist': ['.zyx.41'],
(...skipping 182 matching lines...) Expand 10 before | Expand all | Expand 10 after
208 try: 213 try:
209 import ssl 214 import ssl
210 except ImportError: 215 except ImportError:
211 has_ssl = False 216 has_ssl = False
212 else: 217 else:
213 has_ssl = True 218 has_ssl = True
214 try: 219 try:
215 xmlrpc.client.ServerProxy('https://localhost:9999').bad_function() 220 xmlrpc.client.ServerProxy('https://localhost:9999').bad_function()
216 except NotImplementedError: 221 except NotImplementedError:
217 self.assertFalse(has_ssl, "xmlrpc client's error with SSL support") 222 self.assertFalse(has_ssl, "xmlrpc client's error with SSL support")
218 except socket.error: 223 except OSError:
219 self.assertTrue(has_ssl) 224 self.assertTrue(has_ssl)
220 225
221 class HelperTestCase(unittest.TestCase): 226 class HelperTestCase(unittest.TestCase):
222 def test_escape(self): 227 def test_escape(self):
223 self.assertEqual(xmlrpclib.escape("a&b"), "a&b") 228 self.assertEqual(xmlrpclib.escape("a&b"), "a&b")
224 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b") 229 self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
225 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b") 230 self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")
226 231
227 class FaultTestCase(unittest.TestCase): 232 class FaultTestCase(unittest.TestCase):
228 def test_repr(self): 233 def test_repr(self):
(...skipping 13 matching lines...) Expand all
242 247
243 def test_dotted_attribute(self): 248 def test_dotted_attribute(self):
244 # this will raise AttributeError because code don't want us to use 249 # this will raise AttributeError because code don't want us to use
245 # private methods 250 # private methods
246 self.assertRaises(AttributeError, 251 self.assertRaises(AttributeError,
247 xmlrpc.server.resolve_dotted_attribute, str, '__add') 252 xmlrpc.server.resolve_dotted_attribute, str, '__add')
248 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) 253 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
249 254
250 class DateTimeTestCase(unittest.TestCase): 255 class DateTimeTestCase(unittest.TestCase):
251 def test_default(self): 256 def test_default(self):
252 t = xmlrpclib.DateTime() 257 with mock.patch('time.localtime') as localtime_mock:
258 time_struct = time.struct_time(
259 [2013, 7, 15, 0, 24, 49, 0, 196, 0])
260 localtime_mock.return_value = time_struct
261 localtime = time.localtime()
262 t = xmlrpclib.DateTime()
263 self.assertEqual(str(t),
264 time.strftime("%Y%m%dT%H:%M:%S", localtime))
253 265
254 def test_time(self): 266 def test_time(self):
255 d = 1181399930.036952 267 d = 1181399930.036952
256 t = xmlrpclib.DateTime(d) 268 t = xmlrpclib.DateTime(d)
257 self.assertEqual(str(t), 269 self.assertEqual(str(t),
258 time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d))) 270 time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))
259 271
260 def test_time_tuple(self): 272 def test_time_tuple(self):
261 d = (2007,6,9,10,38,50,5,160,0) 273 d = (2007,6,9,10,38,50,5,160,0)
262 t = xmlrpclib.DateTime(d) 274 t = xmlrpclib.DateTime(d)
(...skipping 16 matching lines...) Expand all
279 self.assertEqual(repr(t), val) 291 self.assertEqual(repr(t), val)
280 292
281 def test_decode(self): 293 def test_decode(self):
282 d = ' 20070908T07:11:13 ' 294 d = ' 20070908T07:11:13 '
283 t1 = xmlrpclib.DateTime() 295 t1 = xmlrpclib.DateTime()
284 t1.decode(d) 296 t1.decode(d)
285 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13)) 297 tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
286 self.assertEqual(t1, tref) 298 self.assertEqual(t1, tref)
287 299
288 t2 = xmlrpclib._datetime(d) 300 t2 = xmlrpclib._datetime(d)
289 self.assertEqual(t1, tref) 301 self.assertEqual(t2, tref)
290 302
291 def test_comparison(self): 303 def test_comparison(self):
292 now = datetime.datetime.now() 304 now = datetime.datetime.now()
293 dtime = xmlrpclib.DateTime(now.timetuple()) 305 dtime = xmlrpclib.DateTime(now.timetuple())
294 306
295 # datetime vs. DateTime 307 # datetime vs. DateTime
296 self.assertTrue(dtime == now) 308 self.assertTrue(dtime == now)
297 self.assertTrue(now == dtime) 309 self.assertTrue(now == dtime)
298 then = now + datetime.timedelta(seconds=4) 310 then = now + datetime.timedelta(seconds=4)
299 self.assertTrue(then >= dtime) 311 self.assertTrue(then >= dtime)
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after
361 # the event after it has been set the first time to catch the second set. 373 # the event after it has been set the first time to catch the second set.
362 def http_server(evt, numrequests, requestHandler=None): 374 def http_server(evt, numrequests, requestHandler=None):
363 class TestInstanceClass: 375 class TestInstanceClass:
364 def div(self, x, y): 376 def div(self, x, y):
365 return x // y 377 return x // y
366 378
367 def _methodHelp(self, name): 379 def _methodHelp(self, name):
368 if name == 'div': 380 if name == 'div':
369 return 'This is the div function' 381 return 'This is the div function'
370 382
383 class Fixture:
384 @staticmethod
385 def getData():
386 return '42'
387
371 def my_function(): 388 def my_function():
372 '''This is my function''' 389 '''This is my function'''
373 return True 390 return True
374 391
375 class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer): 392 class MyXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer):
376 def get_request(self): 393 def get_request(self):
377 # Ensure the socket is always non-blocking. On Linux, socket 394 # Ensure the socket is always non-blocking. On Linux, socket
378 # attributes are not inherited like they are on *BSD and Windows. 395 # attributes are not inherited like they are on *BSD and Windows.
379 s, port = self.socket.accept() 396 s, port = self.socket.accept()
380 s.setblocking(True) 397 s.setblocking(True)
(...skipping 11 matching lines...) Expand all
392 #trying to connect to "localhost" using all address families, which 409 #trying to connect to "localhost" using all address families, which
393 #causes slowdown e.g. on vista which supports AF_INET6. The server list ens 410 #causes slowdown e.g. on vista which supports AF_INET6. The server list ens
394 #on AF_INET only. 411 #on AF_INET only.
395 URL = "http://%s:%d"%(ADDR, PORT) 412 URL = "http://%s:%d"%(ADDR, PORT)
396 serv.server_activate() 413 serv.server_activate()
397 serv.register_introspection_functions() 414 serv.register_introspection_functions()
398 serv.register_multicall_functions() 415 serv.register_multicall_functions()
399 serv.register_function(pow) 416 serv.register_function(pow)
400 serv.register_function(lambda x,y: x+y, 'add') 417 serv.register_function(lambda x,y: x+y, 'add')
401 serv.register_function(my_function) 418 serv.register_function(my_function)
402 serv.register_instance(TestInstanceClass()) 419 testInstance = TestInstanceClass()
420 serv.register_instance(testInstance, allow_dotted_names=True)
403 evt.set() 421 evt.set()
404 422
405 # handle up to 'numrequests' requests 423 # handle up to 'numrequests' requests
406 while numrequests > 0: 424 while numrequests > 0:
407 serv.handle_request() 425 serv.handle_request()
408 numrequests -= 1 426 numrequests -= 1
409 427
410 except socket.timeout: 428 except socket.timeout:
411 pass 429 pass
412 finally: 430 finally:
(...skipping 72 matching lines...) Expand 10 before | Expand all | Expand 10 after
485 '''Returns True if the given ProtocolError is the product of a server-side 503 '''Returns True if the given ProtocolError is the product of a server-side
486 exception caused by the 'temporarily unavailable' response sometimes 504 exception caused by the 'temporarily unavailable' response sometimes
487 given by operations on non-blocking sockets.''' 505 given by operations on non-blocking sockets.'''
488 506
489 # sometimes we get a -1 error code and/or empty headers 507 # sometimes we get a -1 error code and/or empty headers
490 try: 508 try:
491 if e.errcode == -1 or e.headers is None: 509 if e.errcode == -1 or e.headers is None:
492 return True 510 return True
493 exc_mess = e.headers.get('X-exception') 511 exc_mess = e.headers.get('X-exception')
494 except AttributeError: 512 except AttributeError:
495 # Ignore socket.errors here. 513 # Ignore OSErrors here.
496 exc_mess = str(e) 514 exc_mess = str(e)
497 515
498 if exc_mess and 'temporarily unavailable' in exc_mess.lower(): 516 if exc_mess and 'temporarily unavailable' in exc_mess.lower():
499 return True 517 return True
500 518
501 def make_request_and_skipIf(condition, reason): 519 def make_request_and_skipIf(condition, reason):
502 # If we skip the test, we have to make a request because the 520 # If we skip the test, we have to make a request because the
503 # the server created in setUp blocks expecting one to come in. 521 # the server created in setUp blocks expecting one to come in.
504 if not condition: 522 if not condition:
505 return lambda func: func 523 return lambda func: func
506 def decorator(func): 524 def decorator(func):
507 def make_request_and_skip(self): 525 def make_request_and_skip(self):
508 try: 526 try:
509 xmlrpclib.ServerProxy(URL).my_function() 527 xmlrpclib.ServerProxy(URL).my_function()
510 except (xmlrpclib.ProtocolError, socket.error) as e: 528 except (xmlrpclib.ProtocolError, OSError) as e:
511 if not is_unavailable_exception(e): 529 if not is_unavailable_exception(e):
512 raise 530 raise
513 raise unittest.SkipTest(reason) 531 raise unittest.SkipTest(reason)
514 return make_request_and_skip 532 return make_request_and_skip
515 return decorator 533 return decorator
516 534
517 @unittest.skipUnless(threading, 'Threading required for this test.') 535 @unittest.skipUnless(threading, 'Threading required for this test.')
518 class BaseServerTestCase(unittest.TestCase): 536 class BaseServerTestCase(unittest.TestCase):
519 requestHandler = None 537 requestHandler = None
520 request_count = 1 538 request_count = 1
(...skipping 17 matching lines...) Expand all
538 self.evt.wait() 556 self.evt.wait()
539 557
540 # disable traceback reporting 558 # disable traceback reporting
541 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False 559 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = False
542 560
543 class SimpleServerTestCase(BaseServerTestCase): 561 class SimpleServerTestCase(BaseServerTestCase):
544 def test_simple1(self): 562 def test_simple1(self):
545 try: 563 try:
546 p = xmlrpclib.ServerProxy(URL) 564 p = xmlrpclib.ServerProxy(URL)
547 self.assertEqual(p.pow(6,8), 6**8) 565 self.assertEqual(p.pow(6,8), 6**8)
548 except (xmlrpclib.ProtocolError, socket.error) as e: 566 except (xmlrpclib.ProtocolError, OSError) as e:
549 # ignore failures due to non-blocking socket 'unavailable' errors 567 # ignore failures due to non-blocking socket 'unavailable' errors
550 if not is_unavailable_exception(e): 568 if not is_unavailable_exception(e):
551 # protocol error; provide additional information in test output 569 # protocol error; provide additional information in test output
552 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 570 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
553 571
554 def test_nonascii(self): 572 def test_nonascii(self):
555 start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t' 573 start_string = 'P\N{LATIN SMALL LETTER Y WITH CIRCUMFLEX}t'
556 end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n' 574 end_string = 'h\N{LATIN SMALL LETTER O WITH HORN}n'
557 try: 575 try:
558 p = xmlrpclib.ServerProxy(URL) 576 p = xmlrpclib.ServerProxy(URL)
559 self.assertEqual(p.add(start_string, end_string), 577 self.assertEqual(p.add(start_string, end_string),
560 start_string + end_string) 578 start_string + end_string)
561 except (xmlrpclib.ProtocolError, socket.error) as e: 579 except (xmlrpclib.ProtocolError, OSError) as e:
562 # ignore failures due to non-blocking socket 'unavailable' errors 580 # ignore failures due to non-blocking socket 'unavailable' errors
563 if not is_unavailable_exception(e): 581 if not is_unavailable_exception(e):
564 # protocol error; provide additional information in test output 582 # protocol error; provide additional information in test output
565 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 583 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
566 584
567 # [ch] The test 404 is causing lots of false alarms. 585 # [ch] The test 404 is causing lots of false alarms.
568 def XXXtest_404(self): 586 def XXXtest_404(self):
569 # send POST with http.client, it should return 404 header and 587 # send POST with http.client, it should return 404 header and
570 # 'Not Found' message. 588 # 'Not Found' message.
571 conn = httplib.client.HTTPConnection(ADDR, PORT) 589 conn = httplib.client.HTTPConnection(ADDR, PORT)
572 conn.request('POST', '/this-is-not-valid') 590 conn.request('POST', '/this-is-not-valid')
573 response = conn.getresponse() 591 response = conn.getresponse()
574 conn.close() 592 conn.close()
575 593
576 self.assertEqual(response.status, 404) 594 self.assertEqual(response.status, 404)
577 self.assertEqual(response.reason, 'Not Found') 595 self.assertEqual(response.reason, 'Not Found')
578 596
579 def test_introspection1(self): 597 def test_introspection1(self):
580 expected_methods = set(['pow', 'div', 'my_function', 'add', 598 expected_methods = set(['pow', 'div', 'my_function', 'add',
581 'system.listMethods', 'system.methodHelp', 599 'system.listMethods', 'system.methodHelp',
582 'system.methodSignature', 'system.multicall']) 600 'system.methodSignature', 'system.multicall',
601 'Fixture'])
583 try: 602 try:
584 p = xmlrpclib.ServerProxy(URL) 603 p = xmlrpclib.ServerProxy(URL)
585 meth = p.system.listMethods() 604 meth = p.system.listMethods()
586 self.assertEqual(set(meth), expected_methods) 605 self.assertEqual(set(meth), expected_methods)
587 except (xmlrpclib.ProtocolError, socket.error) as e: 606 except (xmlrpclib.ProtocolError, OSError) as e:
588 # ignore failures due to non-blocking socket 'unavailable' errors 607 # ignore failures due to non-blocking socket 'unavailable' errors
589 if not is_unavailable_exception(e): 608 if not is_unavailable_exception(e):
590 # protocol error; provide additional information in test output 609 # protocol error; provide additional information in test output
591 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 610 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
592 611
593 612
594 def test_introspection2(self): 613 def test_introspection2(self):
595 try: 614 try:
596 # test _methodHelp() 615 # test _methodHelp()
597 p = xmlrpclib.ServerProxy(URL) 616 p = xmlrpclib.ServerProxy(URL)
598 divhelp = p.system.methodHelp('div') 617 divhelp = p.system.methodHelp('div')
599 self.assertEqual(divhelp, 'This is the div function') 618 self.assertEqual(divhelp, 'This is the div function')
600 except (xmlrpclib.ProtocolError, socket.error) as e: 619 except (xmlrpclib.ProtocolError, OSError) as e:
601 # ignore failures due to non-blocking socket 'unavailable' errors 620 # ignore failures due to non-blocking socket 'unavailable' errors
602 if not is_unavailable_exception(e): 621 if not is_unavailable_exception(e):
603 # protocol error; provide additional information in test output 622 # protocol error; provide additional information in test output
604 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 623 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
605 624
606 @make_request_and_skipIf(sys.flags.optimize >= 2, 625 @make_request_and_skipIf(sys.flags.optimize >= 2,
607 "Docstrings are omitted with -O2 and above") 626 "Docstrings are omitted with -O2 and above")
608 def test_introspection3(self): 627 def test_introspection3(self):
609 try: 628 try:
610 # test native doc 629 # test native doc
611 p = xmlrpclib.ServerProxy(URL) 630 p = xmlrpclib.ServerProxy(URL)
612 myfunction = p.system.methodHelp('my_function') 631 myfunction = p.system.methodHelp('my_function')
613 self.assertEqual(myfunction, 'This is my function') 632 self.assertEqual(myfunction, 'This is my function')
614 except (xmlrpclib.ProtocolError, socket.error) as e: 633 except (xmlrpclib.ProtocolError, OSError) as e:
615 # ignore failures due to non-blocking socket 'unavailable' errors 634 # ignore failures due to non-blocking socket 'unavailable' errors
616 if not is_unavailable_exception(e): 635 if not is_unavailable_exception(e):
617 # protocol error; provide additional information in test output 636 # protocol error; provide additional information in test output
618 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 637 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
619 638
620 def test_introspection4(self): 639 def test_introspection4(self):
621 # the SimpleXMLRPCServer doesn't support signatures, but 640 # the SimpleXMLRPCServer doesn't support signatures, but
622 # at least check that we can try making the call 641 # at least check that we can try making the call
623 try: 642 try:
624 p = xmlrpclib.ServerProxy(URL) 643 p = xmlrpclib.ServerProxy(URL)
625 divsig = p.system.methodSignature('div') 644 divsig = p.system.methodSignature('div')
626 self.assertEqual(divsig, 'signatures not supported') 645 self.assertEqual(divsig, 'signatures not supported')
627 except (xmlrpclib.ProtocolError, socket.error) as e: 646 except (xmlrpclib.ProtocolError, OSError) as e:
628 # ignore failures due to non-blocking socket 'unavailable' errors 647 # ignore failures due to non-blocking socket 'unavailable' errors
629 if not is_unavailable_exception(e): 648 if not is_unavailable_exception(e):
630 # protocol error; provide additional information in test output 649 # protocol error; provide additional information in test output
631 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 650 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
632 651
633 def test_multicall(self): 652 def test_multicall(self):
634 try: 653 try:
635 p = xmlrpclib.ServerProxy(URL) 654 p = xmlrpclib.ServerProxy(URL)
636 multicall = xmlrpclib.MultiCall(p) 655 multicall = xmlrpclib.MultiCall(p)
637 multicall.add(2,3) 656 multicall.add(2,3)
638 multicall.pow(6,8) 657 multicall.pow(6,8)
639 multicall.div(127,42) 658 multicall.div(127,42)
640 add_result, pow_result, div_result = multicall() 659 add_result, pow_result, div_result = multicall()
641 self.assertEqual(add_result, 2+3) 660 self.assertEqual(add_result, 2+3)
642 self.assertEqual(pow_result, 6**8) 661 self.assertEqual(pow_result, 6**8)
643 self.assertEqual(div_result, 127//42) 662 self.assertEqual(div_result, 127//42)
644 except (xmlrpclib.ProtocolError, socket.error) as e: 663 except (xmlrpclib.ProtocolError, OSError) as e:
645 # ignore failures due to non-blocking socket 'unavailable' errors 664 # ignore failures due to non-blocking socket 'unavailable' errors
646 if not is_unavailable_exception(e): 665 if not is_unavailable_exception(e):
647 # protocol error; provide additional information in test output 666 # protocol error; provide additional information in test output
648 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 667 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
649 668
650 def test_non_existing_multicall(self): 669 def test_non_existing_multicall(self):
651 try: 670 try:
652 p = xmlrpclib.ServerProxy(URL) 671 p = xmlrpclib.ServerProxy(URL)
653 multicall = xmlrpclib.MultiCall(p) 672 multicall = xmlrpclib.MultiCall(p)
654 multicall.this_is_not_exists() 673 multicall.this_is_not_exists()
655 result = multicall() 674 result = multicall()
656 675
657 # result.results contains; 676 # result.results contains;
658 # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'> :' 677 # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'> :'
659 # 'method "this_is_not_exists" is not supported'>}] 678 # 'method "this_is_not_exists" is not supported'>}]
660 679
661 self.assertEqual(result.results[0]['faultCode'], 1) 680 self.assertEqual(result.results[0]['faultCode'], 1)
662 self.assertEqual(result.results[0]['faultString'], 681 self.assertEqual(result.results[0]['faultString'],
663 '<class \'Exception\'>:method "this_is_not_exists" ' 682 '<class \'Exception\'>:method "this_is_not_exists" '
664 'is not supported') 683 'is not supported')
665 except (xmlrpclib.ProtocolError, socket.error) as e: 684 except (xmlrpclib.ProtocolError, OSError) as e:
666 # ignore failures due to non-blocking socket 'unavailable' errors 685 # ignore failures due to non-blocking socket 'unavailable' errors
667 if not is_unavailable_exception(e): 686 if not is_unavailable_exception(e):
668 # protocol error; provide additional information in test output 687 # protocol error; provide additional information in test output
669 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 688 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
670 689
671 def test_dotted_attribute(self): 690 def test_dotted_attribute(self):
672 # Raises an AttributeError because private methods are not allowed. 691 # Raises an AttributeError because private methods are not allowed.
673 self.assertRaises(AttributeError, 692 self.assertRaises(AttributeError,
674 xmlrpc.server.resolve_dotted_attribute, str, '__add') 693 xmlrpc.server.resolve_dotted_attribute, str, '__add')
675 694
676 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title')) 695 self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
677 # Get the test to run faster by sending a request with test_simple1. 696 # Get the test to run faster by sending a request with test_simple1.
678 # This avoids waiting for the socket timeout. 697 # This avoids waiting for the socket timeout.
679 self.test_simple1() 698 self.test_simple1()
699
700 def test_allow_dotted_names_true(self):
701 # XXX also need allow_dotted_names_false test.
702 server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
703 data = server.Fixture.getData()
704 self.assertEqual(data, '42')
680 705
681 def test_unicode_host(self): 706 def test_unicode_host(self):
682 server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT)) 707 server = xmlrpclib.ServerProxy("http://%s:%d/RPC2" % (ADDR, PORT))
683 self.assertEqual(server.add("a", "\xe9"), "a\xe9") 708 self.assertEqual(server.add("a", "\xe9"), "a\xe9")
684 709
685 def test_partial_post(self): 710 def test_partial_post(self):
686 # Check that a partial POST doesn't make the server loop: issue #14001. 711 # Check that a partial POST doesn't make the server loop: issue #14001.
687 conn = http.client.HTTPConnection(ADDR, PORT) 712 conn = http.client.HTTPConnection(ADDR, PORT)
688 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye') 713 conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
689 conn.close() 714 conn.close()
(...skipping 88 matching lines...) Expand 10 before | Expand all | Expand 10 after
778 p = xmlrpclib.ServerProxy(URL) 803 p = xmlrpclib.ServerProxy(URL)
779 #do some requests with close. 804 #do some requests with close.
780 self.assertEqual(p.pow(6,8), 6**8) 805 self.assertEqual(p.pow(6,8), 6**8)
781 p("transport").close() #same as above, really. 806 p("transport").close() #same as above, really.
782 self.assertEqual(p.pow(6,8), 6**8) 807 self.assertEqual(p.pow(6,8), 6**8)
783 p("close")() 808 p("close")()
784 self.assertEqual(len(self.RequestHandler.myRequests), 2) 809 self.assertEqual(len(self.RequestHandler.myRequests), 2)
785 810
786 #A test case that verifies that gzip encoding works in both directions 811 #A test case that verifies that gzip encoding works in both directions
787 #(for a request and the response) 812 #(for a request and the response)
813 @unittest.skipIf(gzip is None, 'requires gzip')
788 class GzipServerTestCase(BaseServerTestCase): 814 class GzipServerTestCase(BaseServerTestCase):
789 #a request handler that supports keep-alive and logs requests into a 815 #a request handler that supports keep-alive and logs requests into a
790 #class variable 816 #class variable
791 class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): 817 class RequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler):
792 parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler 818 parentClass = xmlrpc.server.SimpleXMLRPCRequestHandler
793 protocol_version = 'HTTP/1.1' 819 protocol_version = 'HTTP/1.1'
794 820
795 def do_POST(self): 821 def do_POST(self):
796 #store content of last request in class 822 #store content of last request in class
797 self.__class__.content_length = int(self.headers["content-length"]) 823 self.__class__.content_length = int(self.headers["content-length"])
(...skipping 110 matching lines...) Expand 10 before | Expand all | Expand 10 after
908 flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header 934 flagval = xmlrpc.server.SimpleXMLRPCServer._send_traceback_header
909 self.assertEqual(flagval, False) 935 self.assertEqual(flagval, False)
910 936
911 # enable traceback reporting 937 # enable traceback reporting
912 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True 938 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
913 939
914 # test a call that shouldn't fail just as a smoke test 940 # test a call that shouldn't fail just as a smoke test
915 try: 941 try:
916 p = xmlrpclib.ServerProxy(URL) 942 p = xmlrpclib.ServerProxy(URL)
917 self.assertEqual(p.pow(6,8), 6**8) 943 self.assertEqual(p.pow(6,8), 6**8)
918 except (xmlrpclib.ProtocolError, socket.error) as e: 944 except (xmlrpclib.ProtocolError, OSError) as e:
919 # ignore failures due to non-blocking socket 'unavailable' errors 945 # ignore failures due to non-blocking socket 'unavailable' errors
920 if not is_unavailable_exception(e): 946 if not is_unavailable_exception(e):
921 # protocol error; provide additional information in test output 947 # protocol error; provide additional information in test output
922 self.fail("%s\n%s" % (e, getattr(e, "headers", ""))) 948 self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
923 949
924 def test_fail_no_info(self): 950 def test_fail_no_info(self):
925 # use the broken message class 951 # use the broken message class
926 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageCl ass 952 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageCl ass
927 953
928 try: 954 try:
929 p = xmlrpclib.ServerProxy(URL) 955 p = xmlrpclib.ServerProxy(URL)
930 p.pow(6,8) 956 p.pow(6,8)
931 except (xmlrpclib.ProtocolError, socket.error) as e: 957 except (xmlrpclib.ProtocolError, OSError) as e:
932 # ignore failures due to non-blocking socket 'unavailable' errors 958 # ignore failures due to non-blocking socket 'unavailable' errors
933 if not is_unavailable_exception(e) and hasattr(e, "headers"): 959 if not is_unavailable_exception(e) and hasattr(e, "headers"):
934 # The two server-side error headers shouldn't be sent back in th is case 960 # The two server-side error headers shouldn't be sent back in th is case
935 self.assertIsNone(e.headers.get("X-exception")) 961 self.assertIsNone(e.headers.get("X-exception"))
936 self.assertIsNone(e.headers.get("X-traceback")) 962 self.assertIsNone(e.headers.get("X-traceback"))
937 else: 963 else:
938 self.fail('ProtocolError not raised') 964 self.fail('ProtocolError not raised')
939 965
940 def test_fail_with_info(self): 966 def test_fail_with_info(self):
941 # use the broken message class 967 # use the broken message class
942 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageCl ass 968 xmlrpc.server.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageCl ass
943 969
944 # Check that errors in the server send back exception/traceback 970 # Check that errors in the server send back exception/traceback
945 # info when flag is set 971 # info when flag is set
946 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True 972 xmlrpc.server.SimpleXMLRPCServer._send_traceback_header = True
947 973
948 try: 974 try:
949 p = xmlrpclib.ServerProxy(URL) 975 p = xmlrpclib.ServerProxy(URL)
950 p.pow(6,8) 976 p.pow(6,8)
951 except (xmlrpclib.ProtocolError, socket.error) as e: 977 except (xmlrpclib.ProtocolError, OSError) as e:
952 # ignore failures due to non-blocking socket 'unavailable' errors 978 # ignore failures due to non-blocking socket 'unavailable' errors
953 if not is_unavailable_exception(e) and hasattr(e, "headers"): 979 if not is_unavailable_exception(e) and hasattr(e, "headers"):
954 # We should get error info in the response 980 # We should get error info in the response
955 expected_err = "invalid literal for int() with base 10: 'I am br oken'" 981 expected_err = "invalid literal for int() with base 10: 'I am br oken'"
956 self.assertEqual(e.headers.get("X-exception"), expected_err) 982 self.assertEqual(e.headers.get("X-exception"), expected_err)
957 self.assertIsNotNone(e.headers.get("X-traceback")) 983 self.assertIsNotNone(e.headers.get("X-traceback"))
958 else: 984 else:
959 self.fail('ProtocolError not raised') 985 self.fail('ProtocolError not raised')
960 986
961 987
(...skipping 107 matching lines...) Expand 10 before | Expand all | Expand 10 after
1069 1095
1070 def test_xmlrpcserver_has_use_builtin_types_flag(self): 1096 def test_xmlrpcserver_has_use_builtin_types_flag(self):
1071 server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0), 1097 server = xmlrpc.server.SimpleXMLRPCServer(("localhost", 0),
1072 use_builtin_types=True) 1098 use_builtin_types=True)
1073 server.server_close() 1099 server.server_close()
1074 self.assertTrue(server.use_builtin_types) 1100 self.assertTrue(server.use_builtin_types)
1075 1101
1076 1102
1077 @support.reap_threads 1103 @support.reap_threads
1078 def test_main(): 1104 def test_main():
1079 xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase, 1105 support.run_unittest(XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
1080 BinaryTestCase, FaultTestCase] 1106 BinaryTestCase, FaultTestCase, UseBuiltinTypesTestCase,
1081 xmlrpc_tests.append(UseBuiltinTypesTestCase) 1107 SimpleServerTestCase, KeepaliveServerTestCase1,
1082 xmlrpc_tests.append(SimpleServerTestCase) 1108 KeepaliveServerTestCase2, GzipServerTestCase,
1083 xmlrpc_tests.append(KeepaliveServerTestCase1) 1109 MultiPathServerTestCase, ServerProxyTestCase, FailingServerTestCase,
1084 xmlrpc_tests.append(KeepaliveServerTestCase2) 1110 CGIHandlerTestCase)
1085 try: 1111
1086 import gzip
1087 xmlrpc_tests.append(GzipServerTestCase)
1088 except ImportError:
1089 pass #gzip not supported in this build
1090 xmlrpc_tests.append(MultiPathServerTestCase)
1091 xmlrpc_tests.append(ServerProxyTestCase)
1092 xmlrpc_tests.append(FailingServerTestCase)
1093 xmlrpc_tests.append(CGIHandlerTestCase)
1094
1095 support.run_unittest(*xmlrpc_tests)
1096 1112
1097 if __name__ == "__main__": 1113 if __name__ == "__main__":
1098 test_main() 1114 test_main()
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+