Source

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

   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
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
RPC Protocol API version 2

diff --git a/trunk/MANIFEST.in b/trunk/MANIFEST.in
new file mode 100644
--- /dev/null
+++ b/trunk/MANIFEST.in
@@ -0,0 +1,4 @@
+include README.wiki
+include tracrpc/htdocs/css/*.css
+include tracrpc/htdocs/js/*.js
+include tracrpc/templates/*.html
diff --git a/trunk/setup.py b/trunk/setup.py
--- a/trunk/setup.py
+++ b/trunk/setup.py
@@ -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 --git a/trunk/tracrpc/api.py b/trunk/tracrpc/api.py
--- a/trunk/tracrpc/api.py
+++ b/trunk/tracrpc/api.py
@@ -15,19 +15,41 @@
 from trac.perm import IPermissionRequestor
 
 __all__ = ['expose_rpc', 'IRPCProtocol', 'IXMLRPCHandler', 'AbstractRPCHandler',
-            'Method', 'XMLRPCSystem', 'Binary', 'RPCError']
+            'Method', 'XMLRPCSystem', 'Binary', 'RPCError', 'MethodNotFound', 
+            'ProtocolException', 'ServiceException']
 
 class Binary(xmlrpclib.Binary):
     """ 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 +85,58 @@
                    (/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.
+
+        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` optionally wrapping another 
+        exception containing details about the failure.
+        """
+
+    def send_rpc_result(req, result):
+        """Serialize the result of the RPC call and send it back to 
+        the client.
+        
+        req     : Request object. The same mapping returned by 
+                  `parse_rpc_request` can be accessed through 
+                  `req.rpc` (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 method *SHOULD* 
+        handle `RPCError`, `PermissionError`, `ResourceNotFound` and 
+        their subclasses. This method is *ALWAYS* called from within 
+        an exception handler.
+        
+        req     : Request object. The same mapping returned by 
+                  `parse_rpc_request` can be accessed through 
+                  `req.rpc` (see above).
+        e       : exception object describing the failure
+        """
 
 class IXMLRPCHandler(Interface):
 
diff --git a/trunk/tracrpc/json_rpc.py b/trunk/tracrpc/json_rpc.py
--- a/trunk/tracrpc/json_rpc.py
+++ b/trunk/tracrpc/json_rpc.py
@@ -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 *
@@ -14,9 +15,10 @@
 from trac.resource import ResourceNotFound
 from trac.util.datefmt import utc
 from trac.util.text import to_unicode
+from trac.web.api import RequestDone
 
 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 +94,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 +134,46 @@
         # 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)
+            self.log.info("RPC(json) JSON-RPC request ID : %s.", data.get('id'))
+            if data.get('method') == 'system.multicall':
+                # Prepare for multicall
+                self.log.debug("RPC(json) Multicall request %s", data)
+                params = data.get('params', [])
+                for signature in params :
+                    signature['methodName'] = signature.get('method', '')
+                data['params'] = [params]
+            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, result):
+        """Send JSON-RPC response back to the caller."""
+        rpcreq = req.rpc
+        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 [[]])[0]
+                mcresults = [self._json_result(
+                                        isinstance(value, Exception) and \
+                                                    value or value[0], \
+                                        sig.get('id') or r_id) \
+                              for sig, value in izip(args, result)]
+                
+                response = self._json_result(mcresults, 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)
@@ -165,28 +185,35 @@
                                                     traceback=True))
             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, e):
+        """Send a JSON-RPC fault message back to the caller. """
+        # TODO : Check error codes and RPC exceptions
+        rpcreq = req.rpc
+        r_id = rpcreq.get('id')
+        response = json.dumps(self._json_error(e, r_id=r_id), \
+                                  cls=TracRpcJSONEncoder)
+        self._send_response(req, response + '\n', rpcreq['mimetype'])
 
     # Internal methods
 
     def _send_response(self, req, response, content_type='application/json'):
+        self.log.debug("RPC(json) encoded response: %s" % response)
         response = to_unicode(response).encode("utf-8")
         req.send_response(200)
         req.send_header('Content-Type', content_type)
         req.send_header('Content-Length', len(response))
         req.end_headers()
         req.write(response)
+        raise RequestDone()
 
-    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:
-            return self._json_error(e, r_id=r_id)
+        else :
+            return self._json_error(result, r_id=r_id)
 
     def _json_error(self, e, c=None, r_id=None):
         """ Makes a response dictionary that is an error. """
diff --git a/trunk/tracrpc/tests/__init__.py b/trunk/tracrpc/tests/__init__.py
--- a/trunk/tracrpc/tests/__init__.py
+++ b/trunk/tracrpc/tests/__init__.py
@@ -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,60 @@
                 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())
+        import tracrpc.tests.web_ui
+        suite.addTest(tracrpc.tests.web_ui.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 :
+    __unittest = 1          # Do not show this module in tracebacks
+    class TracRpcTestCase(unittest.TestCase):
+        def setUp(self):
+            log = rpc_testenv.get_trac_environment().log
+            log.info('=' * 70)
+            log.info('(TEST) Starting %s.%s',
+                            self.__class__.__name__,
+                            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 --git a/trunk/tracrpc/tests/api.py b/trunk/tracrpc/tests/api.py
--- a/trunk/tracrpc/tests/api.py
+++ b/trunk/tracrpc/tests/api.py
@@ -9,14 +9,20 @@
 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 setUp(self):
+        TracRpcTestCase.setUp(self)
+
+    def tearDown(self):
+        TracRpcTestCase.tearDown(self)
 
     def test_invalid_content_type(self):
         req = urllib2.Request(rpc_testenv.url_anon,
@@ -47,16 +53,20 @@
             "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, e):\n"
+            "        rpcreq = req.rpc\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, result):\n"
+            "        rpcreq = req.rpc\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 +75,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 +90,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, 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, result):\n"
             "        raise RPCError('No good.')")
         rpc_testenv.restart()
         # Make the request
@@ -100,8 +121,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 --git a/trunk/tracrpc/tests/json_rpc.py b/trunk/tracrpc/tests/json_rpc.py
--- a/trunk/tracrpc/tests/json_rpc.py
+++ b/trunk/tracrpc/tests/json_rpc.py
@@ -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'})
@@ -39,10 +39,10 @@
             return json.loads(resp.read())
 
         def setUp(self):
-            pass
+            TracRpcTestCase.setUp(self)
 
         def tearDown(self):
-            pass
+            TracRpcTestCase.tearDown(self)
 
         def test_call(self):
             result = self._anon_req(
@@ -59,6 +59,7 @@
                     {'method': 'nonexisting', 'params': []}
                 ], 'id': 233}
             result = self._anon_req(data)
+            self.assertEquals(None, result['error'])
             self.assertEquals(4, len(result['result']))
             items = result['result']
             self.assertEquals(1, items[0]['id'])
@@ -167,11 +168,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 --git a/trunk/tracrpc/tests/ticket.py b/trunk/tracrpc/tests/ticket.py
--- a/trunk/tracrpc/tests/ticket.py
+++ b/trunk/tracrpc/tests/ticket.py
@@ -12,15 +12,19 @@
 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):
+        TracRpcTestCase.setUp(self)
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
         self.user = xmlrpclib.ServerProxy(rpc_testenv.url_user)
         self.admin = xmlrpclib.ServerProxy(rpc_testenv.url_admin)
 
+    def tearDown(self):
+        TracRpcTestCase.tearDown(self)
+
     def test_getActions(self):
         tid = self.admin.ticket.create("ticket_getActions", "kjsald", {})
         actions = self.admin.ticket.getActions(tid)
@@ -124,8 +128,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 --git a/trunk/tracrpc/tests/web_ui.py b/trunk/tracrpc/tests/web_ui.py
new file mode 100644
--- /dev/null
+++ b/trunk/tracrpc/tests/web_ui.py
@@ -0,0 +1,39 @@
+# -*- coding: utf-8 -*-
+"""
+License: BSD
+
+(c) 2009      ::: www.CodeResort.com - BV Network AS (simon-code@bvnetwork.no)
+"""
+
+import unittest
+import urllib2
+
+from tracrpc.tests import rpc_testenv, TracRpcTestCase
+
+class DocumentationTestCase(TracRpcTestCase):
+
+    def setUp(self):
+        TracRpcTestCase.setUp(self)
+
+    def tearDown(self):
+        TracRpcTestCase.tearDown(self)
+
+    def test_documentation_render(self):
+        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
+        handler = urllib2.HTTPBasicAuthHandler(password_mgr)
+        password_mgr.add_password(realm=None,
+                      uri=rpc_testenv.url_auth,
+                      user='user', passwd='user')
+        req = urllib2.Request(rpc_testenv.url_auth,
+                    headers={'Content-Type': 'text/html'})
+        resp = urllib2.build_opener(handler).open(req)
+        self.assertEquals(200, resp.code)
+        body = resp.read()
+        self.assertTrue('<h3 id="XML-RPC">XML-RPC</h3>' in body)
+        self.assertTrue('<h3 id="xmlrpc.ticket.status">' in body)
+
+def test_suite():
+    return unittest.makeSuite(DocumentationTestCase)
+
+if __name__ == '__main__':
+    unittest.main(defaultTest='test_suite')
diff --git a/trunk/tracrpc/tests/wiki.py b/trunk/tracrpc/tests/wiki.py
--- a/trunk/tracrpc/tests/wiki.py
+++ b/trunk/tracrpc/tests/wiki.py
@@ -13,16 +13,20 @@
 
 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):
+        TracRpcTestCase.setUp(self)
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
         self.user = xmlrpclib.ServerProxy(rpc_testenv.url_user)
         self.admin = xmlrpclib.ServerProxy(rpc_testenv.url_admin)
 
+    def tearDown(self):
+        TracRpcTestCase.tearDown(self)
+
     def test_attachments(self):
         # Note: Quite similar to the tracrpc.tests.json.JsonTestCase.test_binary
         image_url = os.path.join(rpc_testenv.trac_src, 'trac',
@@ -60,8 +64,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 --git a/trunk/tracrpc/tests/xml_rpc.py b/trunk/tracrpc/tests/xml_rpc.py
--- a/trunk/tracrpc/tests/xml_rpc.py
+++ b/trunk/tracrpc/tests/xml_rpc.py
@@ -9,57 +9,62 @@
 
 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):
+        TracRpcTestCase.setUp(self)
         self.anon = xmlrpclib.ServerProxy(rpc_testenv.url_anon)
         self.user = xmlrpclib.ServerProxy(rpc_testenv.url_user)
         self.admin = xmlrpclib.ServerProxy(rpc_testenv.url_admin)
 
+    def tearDown(self):
+        TracRpcTestCase.tearDown(self)
+
     def test_xmlrpc_permission(self):
         # Test returned response if not XML_RPC permission
         rpc_testenv._tracadmin('permission', 'remove', 'anonymous',
                                 'XML_RPC')
-        try:
+        def local_test():
             self.anon.system.listMethods()
             rpc_testenv._tracadmin('permission', 'add', 'anonymous',
                                         'XML_RPC')
             self.fail("Revoked permissions not taken effect???")
-        except xmlrpclib.Fault, e:
-            self.assertEquals(403, e.faultCode)
-            self.assertTrue('XML_RPC' in e.faultString)
-            rpc_testenv._tracadmin('permission', 'add', 'anonymous',
+
+        e = self.assertRaises(xmlrpclib.Fault, local_test)
+        self.assertEquals(403, e.faultCode)
+        self.assertTrue('XML_RPC' in e.faultString)
+        rpc_testenv._tracadmin('permission', 'add', 'anonymous',
                                         'XML_RPC')
 
     def test_method_not_found(self):
-        try:
+        def local_test():
             self.admin.system.doesNotExist()
             self.fail("What? Method exists???")
-        except xmlrpclib.Fault, e:
-            self.assertEquals(-32601, e.faultCode)
-            self.assertTrue("not found" in e.faultString)
+        e = self.assertRaises(xmlrpclib.Fault, local_test)
+        self.assertEquals(-32601, e.faultCode)
+        self.assertTrue("not found" in e.faultString)
 
     def test_wrong_argspec(self):
-        try:
+        def local_test():
             self.admin.system.listMethods("hello")
             self.fail("Oops. Wrong argspec accepted???")
-        except xmlrpclib.Fault, e:
-            self.assertEquals(1, e.faultCode)
-            self.assertTrue("listMethods() takes exactly 2 arguments" \
+        e = self.assertRaises(xmlrpclib.Fault, local_test)
+        self.assertEquals(1, e.faultCode)
+        self.assertTrue("listMethods() takes exactly 2 arguments" \
                                     in e.faultString)
 
     def test_content_encoding(self):
         test_string = "øæåØÆÅàéüoö"
         # No encoding / encoding error
-        try:
+        def local_test():
             t_id = self.admin.ticket.create(test_string, test_string[::-1], {})
             self.admin.ticket.delete(t_id)
             self.fail("Expected ticket create to fail...")
-        except Exception, e:
-            self.assertTrue(isinstance(e, xmlrpclib.Fault))
-            self.assertEquals(-32700, e.faultCode)
+        e = self.assertRaises(xmlrpclib.Fault, local_test)
+        self.assertTrue(isinstance(e, xmlrpclib.Fault))
+        self.assertEquals(-32700, e.faultCode)
         # Unicode version (encodable)
         from trac.util.text import to_unicode
         test_string = to_unicode(test_string)
@@ -81,7 +86,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")
@@ -90,22 +95,18 @@
 
     def test_resource_not_found(self):
         # A Ticket resource
-        try:
-            self.admin.ticket.get(2147483647)
-        except Exception, e:
-            self.assertEquals(e.faultCode, 404)
-            self.assertEquals(e.faultString, 
-                    'Ticket 2147483647 does not exist.')
+        e = self.assertRaises(xmlrpclib.Fault, self.admin.ticket.get, 2147483647)
+        self.assertEquals(e.faultCode, 404)
+        self.assertEquals(e.faultString, 
+                'Ticket 2147483647 does not exist.')
         # A Wiki resource
-        try:
-            self.admin.wiki.getPage("Test", 10)
-        except Exception, e:
-            self.assertEquals(e.faultCode, 404)
-            self.assertEquals(e.faultString,
-                    'Wiki page "Test" does not exist at version 10')
+        e = self.assertRaises(xmlrpclib.Fault, self.admin.wiki.getPage, "Test", 10)
+        self.assertEquals(e.faultCode, 404)
+        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 --git a/trunk/tracrpc/util.py b/trunk/tracrpc/util.py
--- a/trunk/tracrpc/util.py
+++ b/trunk/tracrpc/util.py
@@ -33,12 +33,6 @@
 except ImportError:
     empty = None
 
-def accepts_mimetype(req, mimetype):
-    if isinstance(mimetype, basestring):
-      mimetype = (mimetype,)
-    accept = (req.get_header('Accept') or '').split(',')
-    return any(x.strip().startswith(y) for x in accept for y in mimetype)
-
 def prepare_docs(text, indent=4):
     r"""Remove leading whitespace"""
     return ''.join(l[indent:] for l in text.splitlines(True))
diff --git a/trunk/tracrpc/web_ui.py b/trunk/tracrpc/web_ui.py
--- a/trunk/tracrpc/web_ui.py
+++ b/trunk/tracrpc/web_ui.py
@@ -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,16 +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.util import accepts_mimetype
+from tracrpc.api import XMLRPCSystem, IRPCProtocol, ProtocolException, \
+                          RPCError, ServiceException
 
 __all__ = ['RPCWeb']
 
@@ -59,14 +66,8 @@
             # 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))
-        elif accepts_mimetype(req, 'text/html'):
+            self._rpc_process(req, protocol, content_type)
+        elif req.method == 'GET' and content_type.startswith('text/html'):
             return self._dump_docs(req)
         else:
             # Attempt at API call gone wrong. Raise a plain-text 415 error
@@ -76,6 +77,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 +131,66 @@
             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 = req.rpc = {'mimetype': content_type}
+        try :
+            self.log.debug("RPC(%s) call by '%s'", proto_id, req.authname)
+            rpcreq = req.rpc = protocol.parse_rpc_request(req, content_type)
+            rpcreq['mimetype'] = content_type
+
+            # Important ! Check after parsing RPC request to add 
+            #             protocol-specific fields in response 
+            #             (e.g. JSON-RPC response `id`)
+            req.perm.require('XML_RPC') # Need at least XML_RPC
+
+            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, result)
+        except RequestDone :
+            raise
+        except (RPCError, PermissionError, ResourceNotFound), e:
+            self.log.exception("RPC(%s) Error", proto_id)
+            try :
+                protocol.send_rpc_error(req, e)
+            except RequestDone :
+                raise
+            except Exception, e :
+                self.log.exception("RPC(%s) Unhandled protocol error", proto_id)
+                self._send_unknown_error(req, e)
+        except Exception, e :
+            self.log.exception("RPC(%s) Unhandled protocol error", proto_id)
+            self._send_unknown_error(req, e)
+
+    def _send_unknown_error(self, req, 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 = req.rpc and req.rpc.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 --git a/trunk/tracrpc/xml_rpc.py b/trunk/tracrpc/xml_rpc.py
--- a/trunk/tracrpc/xml_rpc.py
+++ b/trunk/tracrpc/xml_rpc.py
@@ -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']
@@ -82,41 +82,48 @@
         yield ('rpc', 'text/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, result):
+        """Send the result of the XML-RPC call back to the client."""
+        rpcreq = req.rpc
+        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, e):
+        """Send an XML-RPC fault message back to the caller"""
+        rpcreq = req.rpc
+        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
@@ -124,6 +131,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,