Source

trac-rpc-mq / t5437 / t5437-protocol_api_v2-r7194.diff

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
RPC Protocol API version 2

diff -r b5e897b63dc2 trunk/setup.py
--- a/trunk/setup.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/setup.py	Thu Mar 18 14:13:28 2010 -0500
@@ -28,7 +28,7 @@
     url='http://trac-hacks.org/wiki/XmlRpcPlugin',
     description='RPC interface to Trac',
     zip_safe=True,
-    test_suite = 'tracrpc.tests.suite',
+    test_suite = 'tracrpc.tests.test_suite',
     tests_require = test_deps,
     packages=find_packages(exclude=['*.tests']),
     package_data={
diff -r b5e897b63dc2 trunk/tracrpc/api.py
--- a/trunk/tracrpc/api.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/api.py	Thu Mar 18 14:13:28 2010 -0500
@@ -21,13 +21,34 @@
     """ RPC Binary type. Currently == xmlrpclib.Binary. """
     pass
 
+#----------------------------------------------------------------
+# RPC Exception classes
+#----------------------------------------------------------------
 class RPCError(TracError):
     """ Error class for general RPC-related errors. """
-    pass
 
 class MethodNotFound(RPCError):
     """ Error to raise when requested method is not found. """
-    pass
+
+class _CompositeRpcError(RPCError):
+    def __init__(self, details, title=None, show_traceback=False):
+        if isinstance(details, Exception):
+          self._exc = details
+          message = unicode(details)
+        else :
+          self._exc = None
+          message = details
+        RPCError.__init__(self, message, title, show_traceback)
+    def __unicode__(self):
+        return u"%s details : %s" % (self.__class__.__name__, self.message)
+
+class ProtocolException(_CompositeRpcError):
+    """Protocol could not handle RPC request. Usually this means 
+    that the request has some sort of syntactic error, a library 
+    needed to parse the RPC call is not available, or similar errors."""
+
+class ServiceException(_CompositeRpcError):
+    """The called method threw an exception. Helpful to identify bugs ;o)"""
 
 RPC_TYPES = {int: 'int', bool: 'boolean', str: 'string', float: 'double',
              datetime: 'dateTime.iso8601', Binary: 'base64',
@@ -63,8 +84,57 @@
                    (/login)?/<path_item>. Answer to 'rpc' only if possible.
         content_type: Starts-with check of 'Content-Type' request header. """
 
-    def rpc_process(req, content_type):
-        """ Process the RPC request and finalize response. """
+    def parse_rpc_request(req, content_type):
+        """ Parse RPC requests. 
+        
+        req          :        HTTP request object
+        content_type :        Input MIME type
+        
+        Return a dictionary with the following keys set. All the other 
+        values included in this mapping will be ignored by the core 
+        RPC subsystem, will be protocol-specific, and SHOULD NOT be 
+        needed in order to invoke a given method.
+        (TODO: reuse `req` ?)
+        
+        method  (MANDATORY): target method name (e.g. 'ticket.get')
+        params  (OPTIONAL) : a tuple containing input positional arguments
+        headers (OPTIONAL) : if the protocol supports custom headers set 
+                              by the client, then this value SHOULD be a 
+                              dictionary binding `header name` to `value`. 
+                              However, protocol handlers as well as target 
+                              RPC methods *MUST (SHOULD ?) NOT* rely on 
+                              specific values assigned to a particular 
+                              header in order to send a response back 
+                              to the client.
+        mimetype           : request MIME-type. This value will be set 
+                              by core RPC components after calling 
+                              this method so, please, ignore
+        
+        If the request cannot be parsed this method *MUST* raise 
+        an instance of `ProtocolException` wrapping another exception 
+        containing details about the failure.
+        """
+
+    def send_rpc_result(req, rpcreq, result):
+        """Serialize the result of the RPC call and send it back to 
+        the client.
+        
+        rpcreq  : The same object returned by `parse_rpc_request` 
+                  (see above).
+        result  : The value returned by the target RPC method
+        """
+
+    def send_rpc_error(req, rpcreq, e):
+        """Send a fault message back to the caller. Exception type 
+        and message are used for this purpose. This message *SHOULD* 
+        handle `RPCError`, `PermissionError`, and `ResourceNotFound` 
+        and subclasses. This method is called from within an exception 
+        handler.
+        
+        rpcreq  : The same object returned by `parse_rpc_request` 
+                  (see above).
+        e       : exception object describing the failure
+        """
 
 class IXMLRPCHandler(Interface):
 
diff -r b5e897b63dc2 trunk/tracrpc/json_rpc.py
--- a/trunk/tracrpc/json_rpc.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/json_rpc.py	Thu Mar 18 14:13:28 2010 -0500
@@ -5,8 +5,9 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
+import datetime
+from itertools import izip
 import re
-import datetime
 from types import GeneratorType
 
 from trac.core import *
@@ -16,7 +17,7 @@
 from trac.util.text import to_unicode
 
 from tracrpc.api import IRPCProtocol, XMLRPCSystem, Binary, \
-        RPCError, MethodNotFound
+        RPCError, MethodNotFound, ProtocolException
 from tracrpc.util import exception_to_unicode, empty, prepare_docs
 
 __all__ = ['JsonRpcProtocol']
@@ -92,6 +93,12 @@
         obj = json.JSONDecoder.decode(self, obj, *args, **kwargs)
         return self._normalize(obj)
 
+class JsonProtocolException(ProtocolException):
+    """Impossible to handle JSON-RPC request."""
+    def __init__(self, details, code=-32603, title=None, show_traceback=False):
+        ProtocolException.__init__(self, details, title, show_traceback)
+        self.code = code
+
 class JsonRpcProtocol(Component):
     r"""
     Example `POST` request using `curl` with `Content-Type` header
@@ -126,34 +133,41 @@
         # Legacy path - provided for backwards compatibility:
         yield ('jsonrpc', 'application/json')
 
-    def rpc_process(self, req, content_type):
-        """ Handles JSON-RPC requests """
+    def parse_rpc_request(self, req, content_type):
+        """ Parse JSON-RPC requests"""
         if not json:
-            raise RPCError("RPC(json) error. JSON not available.")
+            self.log.debug("RPC(json) call ignored (not available).")
+            # TODO: Specify correponding error code
+            raise JsonProtocolException("Error: JSON-RPC not available.\n")
         try:
             data = json.load(req, cls=TracRpcJSONDecoder)
+            if data.get('method') == 'system.multicall':
+                # Prepare for multicall
+                for signature in data.itervalues() :
+                    signature['methodName'] = signature.get('method', '')
+            self.log.info("RPC(json) JSON-RPC request ID : %s.", data.get('id'))
+            return data
         except Exception, e:
             # Abort with exception - no data can be read
-            self.log.error("RPC(json) decode error %s" % \
-                    exception_to_unicode(e, traceback=True))
-            response = json.dumps(self._json_error(e, -32700),
-                                    cls=TracRpcJSONEncoder)
-            self._send_response(req, response + '\n', content_type)
-            return
-        self.log.debug("RPC(json) call by '%s': %s" % (req.authname, data))
-        args = data.get('params') or []
-        r_id = data.get('id', None)
-        method = data.get('method', '')
+            self.log.error("RPC(json) decode error %s", 
+                              exception_to_unicode(e, traceback=True))
+            raise JsonProtocolException(e, -32700)
+
+    def send_rpc_result(self, req, rpcreq, result):
+        """Send JSON-RPC response back to the caller."""
+        r_id = rpcreq.get('id')
         try:
-            req.perm.require('XML_RPC') # Need at least XML_RPC
-            if method == 'system.multicall': # Custom multicall
-                results = []
-                for mc in args:
-                    results.append(self._json_call(req, mc.get('method', ''),
-                        mc.get('params') or [], mc.get('id') or r_id))
-                response = {'result': results, 'error': None, 'id': r_id}
+            if rpcreq.get('method') == 'system.multicall': 
+                # Custom multicall
+                args = rpcreq.get('params') or []
+                mcresults = [self._json_result(value, sig.get('id') or r_id) \
+                              for sig, value in izip(args, result)]
+                
+                # TODO: Which one is better ?
+                # response = self._json_result(req, mcresults, r_id)
+                response = {'result': mcresults, 'error': None, 'id': r_id}
             else:
-                response = self._json_call(req, method, args, r_id)
+                response = self._json_result(result, r_id)
             try: # JSON encoding
                 self.log.debug("RPC(json) result: %s" % repr(response))
                 response = json.dumps(response, cls=TracRpcJSONEncoder)
@@ -166,7 +180,13 @@
             response = json.dumps(self._json_error(e, r_id=r_id),
                             cls=TracRpcJSONEncoder)
         self.log.debug("RPC(json) encoded result: %s" % response)
-        self._send_response(req, response + '\n', content_type)
+        self._send_response(req, response + '\n', rpcreq['mimetype'])
+
+    def send_rpc_error(self, req, rpcreq, e):
+        """Send a JSON-RPC fault message back to the caller. """
+        # TODO : Check error codes and RPC exceptions
+        response = json.dumps(self._json_error(e), cls=TracRpcJSONEncoder)
+        self._send_response(req, response + '\n', rpcreq['mimetype'])
 
     # Internal methods
 
@@ -178,14 +198,11 @@
         req.end_headers()
         req.write(response)
 
-    def _json_call(self, req, method, args, r_id=None):
-        """ Call method and create response dictionary. """
-        try:
-            result = (XMLRPCSystem(self.env).get_method(method)(req, args))[0]
-            if isinstance(result, GeneratorType):
-                result = list(result)
+    def _json_result(self, result, r_id=None):
+        """ Create JSON-RPC response dictionary. """
+        if not isinstance(result, Exception):
             return {'result': result, 'error': None, 'id': r_id}
-        except Exception, e:
+        else :
             return self._json_error(e, r_id=r_id)
 
     def _json_error(self, e, c=None, r_id=None):
diff -r b5e897b63dc2 trunk/tracrpc/tests/__init__.py
--- a/trunk/tracrpc/tests/__init__.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/__init__.py	Thu Mar 18 14:13:28 2010 -0500
@@ -35,6 +35,7 @@
             print "Enabling RPC plugin and permissions..."
             env.config.set('components', 'tracrpc.*', 'enabled')
             env.config.save()
+            self.getLogger = lambda : env.log
             self._tracadmin('permission', 'add', 'anonymous', 'XML_RPC')
             print "Created test environment: %s" % self.dirname
             parts = urllib2.urlparse.urlsplit(self.url)
@@ -66,22 +67,55 @@
                 os.path.realpath(__file__), '..', '..', '..', 'rpctestenv')),
                 '8765', 'http://127.0.0.1')
 
-    def suite():
+    def test_suite():
         suite = unittest.TestSuite()
         import tracrpc.tests.api
-        suite.addTest(tracrpc.tests.api.suite())
+        suite.addTest(tracrpc.tests.api.test_suite())
         import tracrpc.tests.xml_rpc
-        suite.addTest(tracrpc.tests.xml_rpc.suite())
+        suite.addTest(tracrpc.tests.xml_rpc.test_suite())
         import tracrpc.tests.json_rpc
-        suite.addTest(tracrpc.tests.json_rpc.suite())
+        suite.addTest(tracrpc.tests.json_rpc.test_suite())
         import tracrpc.tests.ticket
-        suite.addTest(tracrpc.tests.ticket.suite())
+        suite.addTest(tracrpc.tests.ticket.test_suite())
         import tracrpc.tests.wiki
-        suite.addTest(tracrpc.tests.wiki.suite())
+        suite.addTest(tracrpc.tests.wiki.test_suite())
         return suite
 
 except Exception, e:
     print e
     print "Trac test infrastructure not available."
     print "Install Trac as 'python setup.py develop' (run Trac from source).\n"
-    suite = unittest.TestSuite() # return empty suite
+    test_suite = unittest.TestSuite() # return empty suite
+    
+    TracRpcTestCase = unittest.TestCase
+else :
+    class TracRpcTestCase(unittest.TestCase):
+        def setUp(self):
+            log = rpc_testenv.getLogger()
+            log.info('=' * 70)
+            log.info('(TEST) Starting %s', self._testMethodName)
+            log.info('=' * 70)
+
+        def failUnlessRaises(self, excClass, callableObj, *args, **kwargs):
+            """Enhanced assertions to detect exceptions."""
+            try:
+                callableObj(*args, **kwargs)
+            except excClass, e:
+                return e
+            except self.failureException :
+                raise
+            except Exception, e :
+                if hasattr(excClass, '__name__'): excName = excClass.__name__
+                else: excName = str(excClass)
+
+                if hasattr(e, '__name__'): excMsg = e.__name__
+                else: excMsg = str(e)
+
+                raise self.failureException("\n\nExpected %s\n\nGot %s : %s" % (
+                                        excName, e.__class__.__name__, excMsg))
+            else:
+                if hasattr(excClass,'__name__'): excName = excClass.__name__
+                else: excName = str(excClass)
+                raise self.failureException, "Expected %s\n\nNothing raised" % excName
+
+        assertRaises = failUnlessRaises
diff -r b5e897b63dc2 trunk/tracrpc/tests/api.py
--- a/trunk/tracrpc/tests/api.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/api.py	Thu Mar 18 14:13:28 2010 -0500
@@ -9,14 +9,14 @@
 import unittest
 import urllib2
 
-from tracrpc.tests import rpc_testenv
+from tracrpc.tests import rpc_testenv, TracRpcTestCase
 
 from tracrpc.api import IRPCProtocol
 
 from trac.core import *
 from trac.test import Mock
 
-class ProtocolProviderTestCase(unittest.TestCase):
+class ProtocolProviderTestCase(TracRpcTestCase):
 
     def test_invalid_content_type(self):
         req = urllib2.Request(rpc_testenv.url_anon,
@@ -47,16 +47,18 @@
             "class DummyProvider(Component):\n"
             "    implements(IRPCProtocol)\n"
             "    def rpc_info(self):\n"
-            "        yield ('TEST-RPC', 'No Docs!')\n"
+            "        return ('TEST-RPC', 'No Docs!')\n"
             "    def rpc_match(self):\n"
             "        yield ('rpc', 'application/x-tracrpc-test')\n"
-            "    def rpc_process(self, req, content_type):\n"
+            "    def parse_rpc_request(self, req, content_type):\n"
+            "        return {'method' : 'system.getAPIVersion'}\n"
+            "    def send_rpc_error(self, req, rpcreq, e):\n"
+            "        req.send_error(None, template='', content_type=rpcreq['mimetype'],\n"
+            "                       status=500, env=None, data='Test failure ')\n"
+            "    def send_rpc_result(self, req, rpcreq, result):\n"
+            "        # raise KeyError('Here')\n"
             "        response = 'Got a result!'\n"
-            "        req.send_response(200)\n"
-            "        req.send_header('Content-Type', content_type)\n"
-            "        req.send_header('Content-Length', len(response))\n"
-            "        req.end_headers()\n"
-            "        req.write(response)\n")
+            "        req.send(response, rpcreq['mimetype'], 200)\n")
         rpc_testenv.restart()
         try:
             req = urllib2.Request(rpc_testenv.url_anon,
@@ -65,7 +67,7 @@
             self.assertEquals(200, resp.code)
             self.assertEquals("Got a result!", resp.read())
             self.assertEquals(resp.headers['Content-Type'],
-                                                'application/x-tracrpc-test')
+                                                'application/x-tracrpc-test;charset=utf-8')
         finally:
             # Clean up so that provider don't affect further tests
             os.unlink(provider)
@@ -80,10 +82,21 @@
             "class DummyProvider(Component):\n"
             "    implements(IRPCProtocol)\n"
             "    def rpc_info(self):\n"
-            "        yield ('TEST-RPC', 'No Docs!')\n"
+            "        return ('TEST-RPC', 'No Docs!')\n"
             "    def rpc_match(self):\n"
             "        yield ('rpc', 'application/x-tracrpc-test')\n"
-            "    def rpc_process(self, req, content_type):\n"
+            "    def parse_rpc_request(self, req, content_type):\n"
+            "        return {'method' : 'system.getAPIVersion'}\n"
+            "    def send_rpc_error(self, req, rpcreq, e):\n"
+            "        if isinstance(e, RPCError) :\n"
+            "            req.send_error(None, template='', \n"
+            "                       content_type='text/plain',\n"
+            "                       status=500, env=None, data=e.message)\n"
+            "        else :\n"
+            "            req.send_error(None, template='', \n"
+            "                       content_type='text/plain',\n"
+            "                       status=500, env=None, data='Test failure')\n"
+            "    def send_rpc_result(self, req, rpcreq, result):\n"
             "        raise RPCError('No good.')")
         rpc_testenv.restart()
         # Make the request
@@ -100,8 +113,8 @@
             os.unlink(provider)
             rpc_testenv.restart()
 
-def suite():
+def test_suite():
     return unittest.makeSuite(ProtocolProviderTestCase)
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    unittest.main(defaultTest='test_suite')
diff -r b5e897b63dc2 trunk/tracrpc/tests/json_rpc.py
--- a/trunk/tracrpc/tests/json_rpc.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/json_rpc.py	Thu Mar 18 14:13:28 2010 -0500
@@ -14,10 +14,10 @@
 from tracrpc.util import StringIO
 
 if json:
-    from tracrpc.tests import rpc_testenv
+    from tracrpc.tests import rpc_testenv, TracRpcTestCase
 
-    class JsonTestCase(unittest.TestCase):
-        
+    class JsonTestCase(TracRpcTestCase):
+
         def _anon_req(self, data):
             req = urllib2.Request(rpc_testenv.url_anon,
                         headers={'Content-Type': 'application/json'})
@@ -167,11 +167,11 @@
             self.assertEquals(result['error']['message'],
                      'Wiki page "Test" does not exist at version 10')
 
-    def suite():
+    def test_suite():
         return unittest.makeSuite(JsonTestCase)
 else:
     print "SKIP: json not available. Cannot run tests."
-    suite = unittest.TestSuite()
+    test_suite = unittest.TestSuite()
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    unittest.main(defaultTest='test_suite')
diff -r b5e897b63dc2 trunk/tracrpc/tests/ticket.py
--- a/trunk/tracrpc/tests/ticket.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/ticket.py	Thu Mar 18 14:13:28 2010 -0500
@@ -12,9 +12,9 @@
 import shutil
 import time
 
-from tracrpc.tests import rpc_testenv
+from tracrpc.tests import rpc_testenv, TracRpcTestCase
 
-class RpcTicketTestCase(unittest.TestCase):
+class RpcTicketTestCase(TracRpcTestCase):
     
     def setUp(self):
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
@@ -124,8 +124,8 @@
             self.admin.ticket.delete(tid1)
             self.admin.ticket.delete(tid2)
 
-def suite():
+def test_suite():
     return unittest.makeSuite(RpcTicketTestCase)
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    unittest.main(defaultTest='test_suite')
diff -r b5e897b63dc2 trunk/tracrpc/tests/wiki.py
--- a/trunk/tracrpc/tests/wiki.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/wiki.py	Thu Mar 18 14:13:28 2010 -0500
@@ -13,10 +13,10 @@
 
 from trac.util.compat import sorted
 
-from tracrpc.tests import rpc_testenv
+from tracrpc.tests import rpc_testenv, TracRpcTestCase
 from tracrpc.util import StringIO
 
-class RpcWikiTestCase(unittest.TestCase):
+class RpcWikiTestCase(TracRpcTestCase):
     
     def setUp(self):
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
@@ -60,8 +60,8 @@
         self.admin.wiki.deletePage('WikiOne')
         self.admin.wiki.deletePage('WikiTwo')
 
-def suite():
+def test_suite():
     return unittest.makeSuite(RpcWikiTestCase)
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    unittest.main(defaultTest='test_suite')
diff -r b5e897b63dc2 trunk/tracrpc/tests/xml_rpc.py
--- a/trunk/tracrpc/tests/xml_rpc.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/tests/xml_rpc.py	Thu Mar 18 14:13:28 2010 -0500
@@ -9,9 +9,9 @@
 
 import xmlrpclib
 
-from tracrpc.tests import rpc_testenv
+from tracrpc.tests import rpc_testenv, TracRpcTestCase
 
-class RpcXmlTestCase(unittest.TestCase):
+class RpcXmlTestCase(TracRpcTestCase):
     
     def setUp(self):
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
@@ -81,7 +81,7 @@
         xmlrpc_now = to_xmlrpc_datetime(now)
         self.assertTrue(isinstance(xmlrpc_now, xmlrpclib.DateTime),
                 "Expected xmlprc_now to be an xmlrpclib.DateTime")
-        self.assertEquals(xmlrpc_now.timetuple()[:6], now_timetuple)
+        self.assertEquals(str(xmlrpc_now), now.strftime("%Y%m%dT%H:%M:%S"))
         now_from_xmlrpc = from_xmlrpc_datetime(xmlrpc_now)
         self.assertTrue(isinstance(now_from_xmlrpc, datetime),
                 "Expected now_from_xmlrpc to be a datetime")
@@ -104,8 +104,8 @@
             self.assertEquals(e.faultString,
                     'Wiki page "Test" does not exist at version 10')
 
-def suite():
+def test_suite():
     return unittest.makeSuite(RpcXmlTestCase)
 
 if __name__ == '__main__':
-    unittest.main(defaultTest='suite')
+    unittest.main(defaultTest='test_suite')
diff -r b5e897b63dc2 trunk/tracrpc/web_ui.py
--- a/trunk/tracrpc/web_ui.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/web_ui.py	Thu Mar 18 14:13:28 2010 -0500
@@ -6,6 +6,10 @@
 (c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
 """
 
+import sys
+from traceback import format_exc
+from types import GeneratorType
+
 from pkg_resources import resource_filename
 
 from genshi.builder import tag
@@ -13,15 +17,19 @@
 from genshi.template.text import TextTemplate
 
 from trac.core import *
+from trac.perm import PermissionError
+from trac.resource import ResourceNotFound
 from trac.util.text import to_unicode
 from trac.util.translation import _
-from trac.web.api import RequestDone, HTTPUnsupportedMediaType
+from trac.web.api import RequestDone, HTTPUnsupportedMediaType, \
+                          HTTPInternalError
 from trac.web.main import IRequestHandler
 from trac.web.chrome import ITemplateProvider, INavigationContributor, \
                             add_stylesheet, add_script, add_ctxtnav
 from trac.wiki.formatter import wiki_to_oneliner
 
-from tracrpc.api import XMLRPCSystem, IRPCProtocol
+from tracrpc.api import XMLRPCSystem, IRPCProtocol, ProtocolException, \
+                          RPCError, ServiceException
 from tracrpc.util import accepts_mimetype
 
 __all__ = ['RPCWeb']
@@ -59,13 +67,7 @@
             # Perform the method call
             self.log.debug("RPC incoming request of content type '%s' " \
                     "dispatched to %s" % (content_type, repr(protocol)))
-            try:
-                protocol.rpc_process(req, content_type)
-            except Exception, e:
-                # Unhandled protocol exception
-                self.log.error("Unhandled protocol error: %s" % to_unicode(e))
-                req.send_error(None, template='', content_type='text/plain',
-                        status=500, env=None, data=to_unicode(e))
+            self._rpc_process(req, protocol, content_type)
         elif accepts_mimetype(req, 'text/html'):
             return self._dump_docs(req)
         else:
@@ -76,6 +78,8 @@
             req.send_error(None, template='', content_type='text/plain',
                     status=HTTPUnsupportedMediaType.code, env=None, data=body)
 
+    # Internal methods
+
     def _dump_docs(self, req):
         # Dump RPC documentation
         req.perm.require('XML_RPC') # Need at least XML_RPC
@@ -128,6 +132,57 @@
             return "Error rendering protocol documentation. " \
                        "Contact your '''Trac''' administrator for details"
 
+    def _rpc_process(self, req, protocol, content_type):
+        """Process incoming RPC request and finalize response."""
+        proto_id = protocol.rpc_info()[0]
+        rpcreq = {'mimetype': content_type}
+        try :
+            self.log.debug("RPC(%s) call by '%s'", proto_id, req.authname)
+            req.perm.require('XML_RPC') # Need at least XML_RPC
+            rpcreq = protocol.parse_rpc_request(req, content_type)
+            rpcreq['mimetype'] = content_type
+            method_name = rpcreq.get('method')
+            if method_name is None :
+                raise ProtocolException('Missing method name')
+            args = rpcreq.get('params') or []
+            self.log.debug("RPC(%s) call by '%s' %s", proto_id, \
+                                              req.authname, method_name)
+            try :
+                result = (XMLRPCSystem(self.env).get_method(method_name)(req, args))[0]
+                if isinstance(result, GeneratorType):
+                    result = list(result)
+            except (RPCError, PermissionError, ResourceNotFound), e:
+                raise
+            except Exception:
+                e, tb = sys.exc_info()[-2:]
+                raise ServiceException(e), None, tb
+            else :
+                protocol.send_rpc_result(req, rpcreq, result)
+        except (RPCError, PermissionError, ResourceNotFound), e:
+            self.log.exception("RPC(%s) Error", proto_id)
+            try :
+                protocol.send_rpc_error(req, rpcreq, e)
+            except Exception, e :
+                self.log.exception("RPC(%s) Unhandled protocol error", proto_id)
+                self._send_unknown_error(req, rpcreq, e)
+        except Exception, e :
+            self.log.exception("RPC(%s) Unhandled protocol error", proto_id)
+            self._send_unknown_error(req, rpcreq, e)
+
+    def _send_unknown_error(self, req, rpcreq, e):
+        """Last recourse if protocol cannot handle the RPC request | error"""
+
+        # TODO: This is the previous implementation. Please review.
+#        self.log.error("Unhandled protocol error: %s" % to_unicode(e))
+#        req.send_error(None, template='', content_type='text/plain',
+#                status=500, env=None, data=to_unicode(e))
+
+        stackTrace = format_exc()
+        method_name = rpcreq and rpcreq.get('method') or '(undefined)'
+        body = "Unhandled protocol error calling '%s'\n\n%s" % (method_name, stackTrace)
+        req.send_error(None, template='', content_type='text/plain',
+                            env=None, data=body, status=HTTPInternalError.code)
+
     # ITemplateProvider methods
 
     def get_htdocs_dirs(self):
diff -r b5e897b63dc2 trunk/tracrpc/xml_rpc.py
--- a/trunk/tracrpc/xml_rpc.py	Thu Mar 18 12:50:57 2010 -0500
+++ b/trunk/tracrpc/xml_rpc.py	Thu Mar 18 14:13:28 2010 -0500
@@ -19,7 +19,7 @@
 from trac.util.text import to_unicode
 
 from tracrpc.api import XMLRPCSystem, IRPCProtocol, Binary, \
-        RPCError, MethodNotFound
+        RPCError, MethodNotFound, ProtocolException, ServiceException
 from tracrpc.util import empty, prepare_docs
 
 __all__ = ['XmlRpcProtocol']
@@ -81,41 +81,46 @@
         yield ('xmlrpc', 'application/xml')
         yield ('xmlrpc', 'text/xml')
 
-    def rpc_process(self, req, content_type):
-        """ Handles XML-RPC requests """
+    def parse_rpc_request(self, req, content_type):
+        """ Parse XML-RPC requests."""
         try:
             args, method = xmlrpclib.loads(
                         req.read(int(req.get_header('Content-Length'))))
         except Exception, e:
             self.log.debug("RPC(xml) parse error: %s", to_unicode(e))
-            self._send_response(req,
-                    xmlrpclib.dumps(
-                        xmlrpclib.Fault(-32700, to_unicode(e))), content_type)
-            return
-        self.log.debug("RPC(xml) call by '%s', method '%s' with args: %s" \
-                                    % (req.authname, method, repr(args)))
-        args = self._normalize_xml_input(args)
-        try:
-            req.perm.require('XML_RPC') # Need at least XML_RPC
-            result = XMLRPCSystem(self.env).get_method(method)(req, args)
-            self.env.log.debug("RPC(xml) '%s' result: %s" % (
-                                                        method, repr(result)))
-            result = tuple(self._normalize_xml_output(result))
-            self._send_response(req,
-                    xmlrpclib.dumps(result, methodresponse=True), content_type)
-        except MethodNotFound, e:
-            self._send_response(req,
-                    xmlrpclib.dumps(
-                        xmlrpclib.Fault(-32601, to_unicode(e))), content_type)
-        except PermissionError, e:
-            self._send_response(req,
-                    xmlrpclib.dumps(
-                        xmlrpclib.Fault(403, to_unicode(e))), content_type)
-        except ResourceNotFound, e:
-            self._send_response(req,
-                    xmlrpclib.dumps(
-                        xmlrpclib.Fault(404, to_unicode(e))), content_type)
-        except Exception, e:
+            raise ProtocolException(xmlrpclib.Fault(-32700, to_unicode(e)))
+        else :
+            self.log.debug("RPC(xml) call by '%s', method '%s' with args: %s" \
+                                        % (req.authname, method, repr(args)))
+            args = self._normalize_xml_input(args)
+            return {'method' : method, 'params' : args}
+
+    def send_rpc_result(self, req, rpcreq, result):
+        """Send the result of the XML-RPC call back to the client."""
+        method = rpcreq.get('method')
+        self.log.debug("RPC(xml) '%s' result: %s" % (
+                                                    method, repr(result)))
+        result = tuple(self._normalize_xml_output([result]))
+        self._send_response(req,
+                xmlrpclib.dumps(result, methodresponse=True), rpcreq['mimetype'])
+
+    def send_rpc_error(self, req, rpcreq, e):
+        """Send an XML-RPC fault message back to the caller"""
+        fault = None
+        if isinstance(e, ProtocolException):
+            fault = e._exc
+        elif isinstance(e, ServiceException):
+            e = e._exc
+        elif isinstance(e, MethodNotFound):
+            fault = xmlrpclib.Fault(-32601, to_unicode(e))
+        elif isinstance(e, PermissionError):
+            fault = xmlrpclib.Fault(403, to_unicode(e))
+        elif isinstance(e, ResourceNotFound):
+            fault = xmlrpclib.Fault(404, to_unicode(e))
+
+        if fault is not None :
+            self._send_response(req, xmlrpclib.dumps(fault), rpcreq['mimetype'])
+        else :
             self.log.error(e)
             import traceback
             from tracrpc.util import StringIO
@@ -123,6 +128,7 @@
             traceback.print_exc(file = out)
             self.log.error(out.getvalue())
             err_code = hasattr(e, 'code') and e.code or 1
+            method = rpcreq.get('method')
             self._send_response(req,
                     xmlrpclib.dumps(
                         xmlrpclib.Fault(err_code,