test_xmlrpc.py 23 KB
Newer Older
1
import base64
2
import datetime
3
import sys
4
import time
5 6
import unittest
import xmlrpclib
7 8
import SimpleXMLRPCServer
import threading
9
import mimetools
10 11 12
import httplib
import socket
import os
13
from test import test_support
14 15 16

alist = [{'astring': 'foo@bar.baz.spam',
          'afloat': 7283.43,
17
          'anint': 2**20,
18
          'ashortlong': 2,
19
          'anotherlist': ['.zyx.41'],
20
          'abase64': xmlrpclib.Binary(b"my dog has fleas"),
21
          'boolean': False,
22 23
          'unicode': '\u4000\u6000\u8000',
          'ukey\u4000': 'regular value',
24 25
          'datetime1': xmlrpclib.DateTime('20050210T11:41:23'),
          'datetime2': xmlrpclib.DateTime(
26
                        (2005, 2, 10, 11, 41, 23, 0, 1, -1)),
27
          'datetime3': xmlrpclib.DateTime(
28
                        datetime.datetime(2005, 2, 10, 11, 41, 23)),
29 30 31 32 33
          }]

class XMLRPCTestCase(unittest.TestCase):

    def test_dump_load(self):
34 35 36
        dump = xmlrpclib.dumps((alist,))
        load = xmlrpclib.loads(dump)
        self.assertEquals(alist, load[0][0])
37

38
    def test_dump_bare_datetime(self):
39 40 41 42
        # This checks that an unwrapped datetime.date object can be handled
        # by the marshalling code.  This can't be done via test_dump_load()
        # since with use_datetime set to 1 the unmarshaller would create
        # datetime objects for the 'datetime[123]' keys as well
43
        dt = datetime.datetime(2005, 2, 10, 11, 41, 23)
44
        s = xmlrpclib.dumps((dt,))
45 46
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEquals(newdt, dt)
47 48
        self.assertEquals(m, None)

49 50 51
        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEquals(newdt, xmlrpclib.DateTime('20050210T11:41:23'))

Christian Heimes's avatar
Christian Heimes committed
52
    def test_datetime_before_1900(self):
Christian Heimes's avatar
Christian Heimes committed
53
        # same as before but with a date before 1900
Christian Heimes's avatar
Christian Heimes committed
54 55 56 57 58 59 60 61 62
        dt = datetime.datetime(1,  2, 10, 11, 41, 23)
        s = xmlrpclib.dumps((dt,))
        (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
        self.assertEquals(newdt, dt)
        self.assertEquals(m, None)

        (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
        self.assertEquals(newdt, xmlrpclib.DateTime('00010210T11:41:23'))

63 64 65 66 67 68 69 70
    def test_cmp_datetime_DateTime(self):
        now = datetime.datetime.now()
        dt = xmlrpclib.DateTime(now.timetuple())
        self.assert_(dt == now)
        self.assert_(now == dt)
        then = now + datetime.timedelta(seconds=4)
        self.assert_(then >= dt)
        self.assert_(dt < then)
71

72 73
    def test_bug_1164912 (self):
        d = xmlrpclib.DateTime()
Tim Peters's avatar
Tim Peters committed
74
        ((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
75 76 77 78 79 80 81
                                            methodresponse=True))
        self.assert_(isinstance(new_d.value, str))

        # Check that the output of dumps() is still an 8-bit string
        s = xmlrpclib.dumps((new_d,), methodresponse=True)
        self.assert_(isinstance(s, str))

82 83 84 85 86 87 88 89 90
    def test_newstyle_class(self):
        class T(object):
            pass
        t = T()
        t.x = 100
        t.y = "Hello"
        ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
        self.assertEquals(t2, t.__dict__)

91
    def test_dump_big_long(self):
92
        self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,))
93 94 95 96

    def test_dump_bad_dict(self):
        self.assertRaises(TypeError, xmlrpclib.dumps, ({(1,2,3): 1},))

97 98 99 100 101 102 103 104 105 106 107 108
    def test_dump_recursive_seq(self):
        l = [1,2,3]
        t = [3,4,5,l]
        l.append(t)
        self.assertRaises(TypeError, xmlrpclib.dumps, (l,))

    def test_dump_recursive_dict(self):
        d = {'1':1, '2':1}
        t = {'3':3, 'd':d}
        d['t'] = t
        self.assertRaises(TypeError, xmlrpclib.dumps, (d,))

109
    def test_dump_big_int(self):
110
        if sys.maxsize > 2**31-1:
111
            self.assertRaises(OverflowError, xmlrpclib.dumps,
112
                              (int(2**34),))
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127
        xmlrpclib.dumps((xmlrpclib.MAXINT, xmlrpclib.MININT))
        self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MAXINT+1,))
        self.assertRaises(OverflowError, xmlrpclib.dumps, (xmlrpclib.MININT-1,))

        def dummy_write(s):
            pass

        m = xmlrpclib.Marshaller()
        m.dump_int(xmlrpclib.MAXINT, dummy_write)
        m.dump_int(xmlrpclib.MININT, dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MAXINT+1, dummy_write)
        self.assertRaises(OverflowError, m.dump_int, xmlrpclib.MININT-1, dummy_write)


128 129 130 131 132 133 134 135
    def test_dump_none(self):
        value = alist + [None]
        arg1 = (alist + [None],)
        strg = xmlrpclib.dumps(arg1, allow_none=True)
        self.assertEquals(value,
                          xmlrpclib.loads(strg)[0][0])
        self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158

class HelperTestCase(unittest.TestCase):
    def test_escape(self):
        self.assertEqual(xmlrpclib.escape("a&b"), "a&amp;b")
        self.assertEqual(xmlrpclib.escape("a<b"), "a&lt;b")
        self.assertEqual(xmlrpclib.escape("a>b"), "a&gt;b")

class FaultTestCase(unittest.TestCase):
    def test_repr(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        self.assertEqual(repr(f), "<Fault 42: 'Test Fault'>")
        self.assertEqual(repr(f), str(f))

    def test_dump_fault(self):
        f = xmlrpclib.Fault(42, 'Test Fault')
        s = xmlrpclib.dumps((f,))
        (newf,), m = xmlrpclib.loads(s)
        self.assertEquals(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
        self.assertEquals(m, None)

        s = xmlrpclib.Marshaller().dumps(f)
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)

159 160 161 162 163 164 165
    def test_dotted_attribute(self):
        # this will raise AttirebuteError because code don't want us to use
        # private methods
        self.assertRaises(AttributeError,
                          SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')

        self.assert_(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

class DateTimeTestCase(unittest.TestCase):
    def test_default(self):
        t = xmlrpclib.DateTime()

    def test_time(self):
        d = 1181399930.036952
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), time.strftime("%Y%m%dT%H:%M:%S", time.localtime(d)))

    def test_time_tuple(self):
        d = (2007,6,9,10,38,50,5,160,0)
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), '20070609T10:38:50')

    def test_time_struct(self):
        d = time.localtime(1181399930.036952)
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t),  time.strftime("%Y%m%dT%H:%M:%S", d))

    def test_datetime_datetime(self):
        d = datetime.datetime(2007,1,2,3,4,5)
        t = xmlrpclib.DateTime(d)
        self.assertEqual(str(t), '20070102T03:04:05')

    def test_repr(self):
        d = datetime.datetime(2007,1,2,3,4,5)
        t = xmlrpclib.DateTime(d)
        val ="<DateTime '20070102T03:04:05' at %x>" % id(t)
        self.assertEqual(repr(t), val)

    def test_decode(self):
        d = ' 20070908T07:11:13  '
        t1 = xmlrpclib.DateTime()
        t1.decode(d)
        tref = xmlrpclib.DateTime(datetime.datetime(2007,9,8,7,11,13))
        self.assertEqual(t1, tref)

        t2 = xmlrpclib._datetime(d)
        self.assertEqual(t1, tref)

class BinaryTestCase(unittest.TestCase):
208 209 210 211 212 213

    # XXX What should str(Binary(b"\xff")) return?  I'm chosing "\xff"
    # for now (i.e. interpreting the binary data as Latin-1-encoded
    # text).  But this feels very unsatisfactory.  Perhaps we should
    # only define repr(), and return r"Binary(b'\xff')" instead?

214 215 216 217 218
    def test_default(self):
        t = xmlrpclib.Binary()
        self.assertEqual(str(t), '')

    def test_string(self):
219
        d = b'\x01\x02\x03abc123\xff\xfe'
220
        t = xmlrpclib.Binary(d)
221
        self.assertEqual(str(t), str(d, "latin-1"))
222 223

    def test_decode(self):
224
        d = b'\x01\x02\x03abc123\xff\xfe'
225 226 227
        de = base64.encodestring(d)
        t1 = xmlrpclib.Binary()
        t1.decode(de)
228
        self.assertEqual(str(t1), str(d, "latin-1"))
229 230

        t2 = xmlrpclib._binary(de)
231
        self.assertEqual(str(t2), str(d, "latin-1"))
232 233


234 235
PORT = None

236 237 238
# The evt is set twice.  First when the server is ready to serve.
# Second when the server has been shutdown.  The user must clear
# the event after it has been set the first time to catch the second set.
239 240 241 242 243
def http_server(evt, numrequests):
    class TestInstanceClass:
        def div(self, x, y):
            return x // y

244 245 246 247 248 249 250 251
        def _methodHelp(self, name):
            if name == 'div':
                return 'This is the div function'

    def my_function():
        '''This is my function'''
        return True

252 253 254 255 256 257 258 259
    class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
        def get_request(self):
            # Ensure the socket is always non-blocking.  On Linux, socket
            # attributes are not inherited like they are on *BSD and Windows.
            s, port = self.socket.accept()
            s.setblocking(True)
            return s, port

260
    try:
261 262
        serv = MyXMLRPCServer(("localhost", 0),
                              logRequests=False, bind_and_activate=False)
263 264 265 266 267 268 269 270
        serv.server_bind()
        global PORT
        PORT = serv.socket.getsockname()[1]
        serv.server_activate()
        serv.register_introspection_functions()
        serv.register_multicall_functions()
        serv.register_function(pow)
        serv.register_function(lambda x,y: x+y, 'add')
271
        serv.register_function(my_function)
272
        serv.register_instance(TestInstanceClass())
273
        evt.set()
274 275 276 277 278 279 280 281 282 283 284 285 286

        # handle up to 'numrequests' requests
        while numrequests > 0:
            serv.handle_request()
            numrequests -= 1

    except socket.timeout:
        pass
    finally:
        serv.socket.close()
        PORT = None
        evt.set()

287 288 289 290 291 292 293 294
# This function prevents errors like:
#    <ProtocolError for localhost:57527/RPC2: 500 Internal Server Error>
def is_unavailable_exception(e):
    '''Returns True if the given ProtocolError is the product of a server-side
       exception caused by the 'temporarily unavailable' response sometimes
       given by operations on non-blocking sockets.'''

    # sometimes we get a -1 error code and/or empty headers
295 296 297 298 299 300 301 302 303
    try:
        if e.errcode == -1 or e.headers is None:
            return True
        exc_mess = e.headers.get('X-exception')
    except AttributeError:
        # Ignore socket.errors here.
        exc_mess = str(e)

    if exc_mess and 'temporarily unavailable' in exc_mess.lower():
304
        return True
305

306
class SimpleServerTestCase(unittest.TestCase):
307
    def setUp(self):
308 309 310
        # enable traceback reporting
        SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True

311
        self.evt = threading.Event()
312
        # start server thread to handle requests
313
        serv_args = (self.evt, 1)
314
        threading.Thread(target=http_server, args=serv_args).start()
315

316 317 318
        # wait for the server to be ready
        self.evt.wait()
        self.evt.clear()
319 320 321

    def tearDown(self):
        # wait on the server thread to terminate
322 323 324 325 326
        self.evt.wait(4.0)
        if not self.evt.isSet():
            self.evt.set()
            stop_serving()
            raise RuntimeError("timeout reached, test has failed")
327

328 329 330
        # disable traceback reporting
        SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False

331
    def test_simple1(self):
332 333 334
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            self.assertEqual(p.pow(6,8), 6**8)
335 336 337 338
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
339
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
340

341 342
    # [ch] The test 404 is causing lots of false alarms.
    def XXXtest_404(self):
343 344 345
        # send POST with httplib, it should return 404 header and
        # 'Not Found' message.
        conn = httplib.HTTPConnection('localhost', PORT)
346
        conn.request('POST', '/this-is-not-valid')
347 348 349 350 351 352
        response = conn.getresponse()
        conn.close()

        self.assertEqual(response.status, 404)
        self.assertEqual(response.reason, 'Not Found')

353
    def test_introspection1(self):
354 355 356
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            meth = p.system.listMethods()
357 358 359
            expected_methods = set(['pow', 'div', 'my_function', 'add',
                                    'system.listMethods', 'system.methodHelp',
                                    'system.methodSignature', 'system.multicall'])
360
            self.assertEqual(set(meth), expected_methods)
361 362 363 364
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
365
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
366

367 368

    def test_introspection2(self):
369
        try:
370
            # test _methodHelp()
371 372 373
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            divhelp = p.system.methodHelp('div')
            self.assertEqual(divhelp, 'This is the div function')
374 375 376 377
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
378
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
379 380

    def test_introspection3(self):
381 382 383 384 385
        try:
            # test native doc
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            myfunction = p.system.methodHelp('my_function')
            self.assertEqual(myfunction, 'This is my function')
386
        except (xmlrpclib.ProtocolError, socket.error) as e:
387 388 389
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
390
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
391 392

    def test_introspection4(self):
393
        # the SimpleXMLRPCServer doesn't support signatures, but
394
        # at least check that we can try making the call
395 396 397 398
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            divsig = p.system.methodSignature('div')
            self.assertEqual(divsig, 'signatures not supported')
399 400 401 402
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
403
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
404 405

    def test_multicall(self):
406 407 408 409 410 411 412 413 414 415
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            multicall = xmlrpclib.MultiCall(p)
            multicall.add(2,3)
            multicall.pow(6,8)
            multicall.div(127,42)
            add_result, pow_result, div_result = multicall()
            self.assertEqual(add_result, 2+3)
            self.assertEqual(pow_result, 6**8)
            self.assertEqual(div_result, 127//42)
416 417 418 419
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
420
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
421

422 423 424 425 426 427 428 429
    def test_non_existing_multicall(self):
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            multicall = xmlrpclib.MultiCall(p)
            multicall.this_is_not_exists()
            result = multicall()

            # result.results contains;
430
            # [{'faultCode': 1, 'faultString': '<class \'exceptions.Exception\'>:'
431 432 433 434
            #   'method "this_is_not_exists" is not supported'>}]

            self.assertEqual(result.results[0]['faultCode'], 1)
            self.assertEqual(result.results[0]['faultString'],
435
                '<class \'Exception\'>:method "this_is_not_exists" '
436
                'is not supported')
437
        except (xmlrpclib.ProtocolError, socket.error) as e:
438 439 440
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
441
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
442

Christian Heimes's avatar
Christian Heimes committed
443 444 445 446 447 448 449 450 451 452
    def test_dotted_attribute(self):
        # Raises an AttributeError because private methods are not allowed.
        self.assertRaises(AttributeError,
                          SimpleXMLRPCServer.resolve_dotted_attribute, str, '__add')

        self.assert_(SimpleXMLRPCServer.resolve_dotted_attribute(str, 'title'))
        # Get the test to run faster by sending a request with test_simple1.
        # This avoids waiting for the socket timeout.
        self.test_simple1()

453 454 455 456 457 458 459 460 461 462 463 464 465 466
# This is a contrived way to make a failure occur on the server side
# in order to test the _send_traceback_header flag on the server
class FailingMessageClass(mimetools.Message):
    def __getitem__(self, key):
        key = key.lower()
        if key == 'content-length':
            return 'I am broken'
        return mimetools.Message.__getitem__(self, key)


class FailingServerTestCase(unittest.TestCase):
    def setUp(self):
        self.evt = threading.Event()
        # start server thread to handle requests
467
        serv_args = (self.evt, 1)
468 469
        threading.Thread(target=http_server, args=serv_args).start()

470 471 472
        # wait for the server to be ready
        self.evt.wait()
        self.evt.clear()
473 474 475 476 477 478 479 480 481 482 483 484 485 486

    def tearDown(self):
        # wait on the server thread to terminate
        self.evt.wait()
        # reset flag
        SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = False
        # reset message class
        SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = mimetools.Message

    def test_basic(self):
        # check that flag is false by default
        flagval = SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header
        self.assertEqual(flagval, False)

487 488 489 490 491 492 493
        # enable traceback reporting
        SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True

        # test a call that shouldn't fail just as a smoke test
        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            self.assertEqual(p.pow(6,8), 6**8)
494 495 496 497
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
            if not is_unavailable_exception(e):
                # protocol error; provide additional information in test output
498
                self.fail("%s\n%s" % (e, getattr(e, "headers", "")))
499 500 501 502 503 504 505 506

    def test_fail_no_info(self):
        # use the broken message class
        SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass

        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            p.pow(6,8)
507 508
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
509
            if not is_unavailable_exception(e) and hasattr(e, "headers"):
510 511 512
                # The two server-side error headers shouldn't be sent back in this case
                self.assertTrue(e.headers.get("X-exception") is None)
                self.assertTrue(e.headers.get("X-traceback") is None)
513 514 515 516 517 518 519 520 521 522 523 524 525 526
        else:
            self.fail('ProtocolError not raised')

    def test_fail_with_info(self):
        # use the broken message class
        SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.MessageClass = FailingMessageClass

        # Check that errors in the server send back exception/traceback
        # info when flag is set
        SimpleXMLRPCServer.SimpleXMLRPCServer._send_traceback_header = True

        try:
            p = xmlrpclib.ServerProxy('http://localhost:%d' % PORT)
            p.pow(6,8)
527 528
        except (xmlrpclib.ProtocolError, socket.error) as e:
            # ignore failures due to non-blocking socket 'unavailable' errors
529
            if not is_unavailable_exception(e) and hasattr(e, "headers"):
530 531 532 533
                # We should get error info in the response
                expected_err = "invalid literal for int() with base 10: 'I am broken'"
                self.assertEqual(e.headers.get("x-exception"), expected_err)
                self.assertTrue(e.headers.get("x-traceback") is not None)
534 535 536
        else:
            self.fail('ProtocolError not raised')

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
class CGIHandlerTestCase(unittest.TestCase):
    def setUp(self):
        self.cgi = SimpleXMLRPCServer.CGIXMLRPCRequestHandler()

    def tearDown(self):
        self.cgi = None

    def test_cgi_get(self):
        os.environ['REQUEST_METHOD'] = 'GET'
        # if the method is GET and no request_text is given, it runs handle_get
        # get sysout output
        tmp = sys.stdout
        sys.stdout = open(test_support.TESTFN, "w")
        self.cgi.handle_request()
        sys.stdout.close()
        sys.stdout = tmp

        # parse Status header
        handle = open(test_support.TESTFN, "r").read()
        status = handle.split()[1]
        message = ' '.join(handle.split()[2:4])

        self.assertEqual(status, '400')
        self.assertEqual(message, 'Bad Request')

        os.remove(test_support.TESTFN)
        os.environ['REQUEST_METHOD'] = ''

    def test_cgi_xmlrpc_response(self):
        data = """<?xml version='1.0'?>
<methodCall>
    <methodName>test_method</methodName>
    <params>
        <param>
            <value><string>foo</string></value>
        </param>
        <param>
            <value><string>bar</string></value>
        </param>
     </params>
</methodCall>
"""
        open("xmldata.txt", "w").write(data)
        tmp1 = sys.stdin
        tmp2 = sys.stdout

        sys.stdin = open("xmldata.txt", "r")
        sys.stdout = open(test_support.TESTFN, "w")

        self.cgi.handle_request()

        sys.stdin.close()
        sys.stdout.close()
        sys.stdin = tmp1
        sys.stdout = tmp2

        # will respond exception, if so, our goal is achieved ;)
        handle = open(test_support.TESTFN, "r").read()

        # start with 44th char so as not to get http header, we just need only xml
        self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, handle[44:])

        os.remove("xmldata.txt")
        os.remove(test_support.TESTFN)
601

602
def test_main():
603 604 605 606 607 608 609 610
    xmlrpc_tests = [XMLRPCTestCase, HelperTestCase, DateTimeTestCase,
         BinaryTestCase, FaultTestCase]

    # The test cases against a SimpleXMLRPCServer raise a socket error
    # 10035 (WSAEWOULDBLOCK) in the server thread handle_request call when
    # run on Windows. This only happens on the first test to run, but it
    # fails every time and so these tests are skipped on win32 platforms.
    if sys.platform != 'win32':
611 612
        xmlrpc_tests.append(SimpleServerTestCase)
        xmlrpc_tests.append(FailingServerTestCase)
613
        xmlrpc_tests.append(CGIHandlerTestCase)
614

615
    test_support.run_unittest(*xmlrpc_tests)
616 617 618

if __name__ == "__main__":
    test_main()