Skip to content
This repository
Browse code

Merge branch 'cdman/use-logging-module'

fixes #42
  • Loading branch information...
commit 7d65da59879e392678b75f14756a14cba87fde53 2 parents fab30b0 + 95aa2a9
Will Norris authored August 24, 2012
57  openid/consumer/consumer.py
@@ -189,6 +189,7 @@
189 189
 
190 190
 import cgi
191 191
 import copy
  192
+import logging
192 193
 from urlparse import urlparse, urldefrag
193 194
 
194 195
 from openid import fetchers
@@ -662,7 +663,7 @@ def _checkReturnTo(self, message, return_to):
662 663
         try:
663 664
             self._verifyReturnToArgs(message.toPostArgs())
664 665
         except ProtocolError, why:
665  
-            oidutil.log("Verifying return_to arguments: %s" % (why[0],))
  666
+            logging.exception("Verifying return_to arguments: %s" % (why[0],))
666 667
             return False
667 668
 
668 669
         # Check the return_to base URL against the one in the message.
@@ -728,7 +729,7 @@ def _doIdRes(self, message, endpoint, return_to):
728 729
 
729 730
         # Verify discovery information:
730 731
         endpoint = self._verifyDiscoveryResults(message, endpoint)
731  
-        oidutil.log("Received id_res response from %s using association %s" %
  732
+        logging.info("Received id_res response from %s using association %s" %
732 733
                     (endpoint.server_url,
733 734
                      message.getArg(OPENID_NS, 'assoc_handle')))
734 735
 
@@ -922,7 +923,7 @@ def _verifyDiscoveryResultsOpenID2(self, resp_msg, endpoint):
922 923
         # endpoints and responses that didn't match the original
923 924
         # request.
924 925
         if not endpoint:
925  
-            oidutil.log('No pre-discovered information supplied.')
  926
+            logging.info('No pre-discovered information supplied.')
926 927
             endpoint = self._discoverAndVerify(to_match.claimed_id, [to_match])
927 928
         else:
928 929
             # The claimed ID matches, so we use the endpoint that we
@@ -931,10 +932,10 @@ def _verifyDiscoveryResultsOpenID2(self, resp_msg, endpoint):
931 932
             try:
932 933
                 self._verifyDiscoverySingle(endpoint, to_match)
933 934
             except ProtocolError, e:
934  
-                oidutil.log(
  935
+                logging.exception(
935 936
                     "Error attempting to use stored discovery information: " +
936 937
                     str(e))
937  
-                oidutil.log("Attempting discovery to verify endpoint")
  938
+                logging.info("Attempting discovery to verify endpoint")
938 939
                 endpoint = self._discoverAndVerify(
939 940
                     to_match.claimed_id, [to_match])
940 941
 
@@ -976,9 +977,9 @@ def _verifyDiscoveryResultsOpenID1(self, resp_msg, endpoint):
976 977
                 except TypeURIMismatch:
977 978
                     self._verifyDiscoverySingle(endpoint, to_match_1_0)
978 979
             except ProtocolError, e:
979  
-                oidutil.log("Error attempting to use stored discovery information: " +
  980
+                logging.exception("Error attempting to use stored discovery information: " +
980 981
                             str(e))
981  
-                oidutil.log("Attempting discovery to verify endpoint")
  982
+                logging.info("Attempting discovery to verify endpoint")
982 983
             else:
983 984
                 return endpoint
984 985
 
@@ -1048,7 +1049,7 @@ def _discoverAndVerify(self, claimed_id, to_match_endpoints):
1048 1049
 
1049 1050
         @raises DiscoveryFailure: when discovery fails.
1050 1051
         """
1051  
-        oidutil.log('Performing discovery on %s' % (claimed_id,))
  1052
+        logging.info('Performing discovery on %s' % (claimed_id,))
1052 1053
         _, services = self._discover(claimed_id)
1053 1054
         if not services:
1054 1055
             raise DiscoveryFailure('No OpenID information found at %s' %
@@ -1075,10 +1076,10 @@ def _verifyDiscoveredServices(self, claimed_id, services, to_match_endpoints):
1075 1076
                     # succeeded. Return this endpoint.
1076 1077
                     return endpoint
1077 1078
         else:
1078  
-            oidutil.log('Discovery verification failure for %s' %
  1079
+            logging.error('Discovery verification failure for %s' %
1079 1080
                         (claimed_id,))
1080 1081
             for failure_message in failure_messages:
1081  
-                oidutil.log(' * Endpoint mismatch: ' + failure_message)
  1082
+                logging.error(' * Endpoint mismatch: ' + failure_message)
1082 1083
 
1083 1084
             raise DiscoveryFailure(
1084 1085
                 'No matching endpoint found after discovering %s'
@@ -1090,14 +1091,14 @@ def _checkAuth(self, message, server_url):
1090 1091
         @returns: True if the request is valid.
1091 1092
         @rtype: bool
1092 1093
         """
1093  
-        oidutil.log('Using OpenID check_authentication')
  1094
+        logging.info('Using OpenID check_authentication')
1094 1095
         request = self._createCheckAuthRequest(message)
1095 1096
         if request is None:
1096 1097
             return False
1097 1098
         try:
1098 1099
             response = self._makeKVPost(request, server_url)
1099 1100
         except (fetchers.HTTPFetchingError, ServerError), e:
1100  
-            oidutil.log('check_authentication failed: %s' % (e[0],))
  1101
+            logging.exception('check_authentication failed: %s' % (e[0],))
1101 1102
             return False
1102 1103
         else:
1103 1104
             return self._processCheckAuthResponse(response, server_url)
@@ -1109,12 +1110,12 @@ def _createCheckAuthRequest(self, message):
1109 1110
         signed = message.getArg(OPENID_NS, 'signed')
1110 1111
         if signed:
1111 1112
             for k in signed.split(','):
1112  
-                oidutil.log(k)
  1113
+                logging.info(k)
1113 1114
                 val = message.getAliasedArg(k)
1114 1115
 
1115 1116
                 # Signed value is missing
1116 1117
                 if val is None:
1117  
-                    oidutil.log('Missing signed field %r' % (k,))
  1118
+                    logging.info('Missing signed field %r' % (k,))
1118 1119
                     return None
1119 1120
 
1120 1121
         check_auth_message = message.copy()
@@ -1129,10 +1130,10 @@ def _processCheckAuthResponse(self, response, server_url):
1129 1130
 
1130 1131
         invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle')
1131 1132
         if invalidate_handle is not None:
1132  
-            oidutil.log(
  1133
+            logging.info(
1133 1134
                 'Received "invalidate_handle" from server %s' % (server_url,))
1134 1135
             if self.store is None:
1135  
-                oidutil.log('Unexpectedly got invalidate_handle without '
  1136
+                logging.error('Unexpectedly got invalidate_handle without '
1136 1137
                             'a store!')
1137 1138
             else:
1138 1139
                 self.store.removeAssociation(server_url, invalidate_handle)
@@ -1140,7 +1141,7 @@ def _processCheckAuthResponse(self, response, server_url):
1140 1141
         if is_valid == 'true':
1141 1142
             return True
1142 1143
         else:
1143  
-            oidutil.log('Server responds that checkAuth call is not valid')
  1144
+            logging.error('Server responds that checkAuth call is not valid')
1144 1145
             return False
1145 1146
 
1146 1147
     def _getAssociation(self, endpoint):
@@ -1193,7 +1194,7 @@ def _negotiateAssociation(self, endpoint):
1193 1194
                 except ServerError, why:
1194 1195
                     # Do not keep trying, since it rejected the
1195 1196
                     # association type that it told us to use.
1196  
-                    oidutil.log('Server %s refused its suggested association '
  1197
+                    logging.error('Server %s refused its suggested association '
1197 1198
                                 'type: session_type=%s, assoc_type=%s'
1198 1199
                                 % (endpoint.server_url, session_type,
1199 1200
                                    assoc_type))
@@ -1216,7 +1217,7 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
1216 1217
         # should be considered a total failure.
1217 1218
         if server_error.error_code != 'unsupported-type' or \
1218 1219
                server_error.message.isOpenID1():
1219  
-            oidutil.log(
  1220
+            logging.error(
1220 1221
                 'Server error when requesting an association from %r: %s'
1221 1222
                 % (endpoint.server_url, server_error.error_text))
1222 1223
             return None
@@ -1224,7 +1225,7 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
1224 1225
         # The server didn't like the association/session type
1225 1226
         # that we sent, and it sent us back a message that
1226 1227
         # might tell us how to handle it.
1227  
-        oidutil.log(
  1228
+        logging.error(
1228 1229
             'Unsupported association type %s: %s' % (assoc_type,
1229 1230
                                                      server_error.error_text,))
1230 1231
 
@@ -1234,13 +1235,13 @@ def _extractSupportedAssociationType(self, server_error, endpoint,
1234 1235
         session_type = server_error.message.getArg(OPENID_NS, 'session_type')
1235 1236
 
1236 1237
         if assoc_type is None or session_type is None:
1237  
-            oidutil.log('Server responded with unsupported association '
  1238
+            logging.error('Server responded with unsupported association '
1238 1239
                         'session but did not supply a fallback.')
1239 1240
             return None
1240 1241
         elif not self.negotiator.isAllowed(assoc_type, session_type):
1241 1242
             fmt = ('Server sent unsupported session/association type: '
1242 1243
                    'session_type=%s, assoc_type=%s')
1243  
-            oidutil.log(fmt % (session_type, assoc_type))
  1244
+            logging.error(fmt % (session_type, assoc_type))
1244 1245
             return None
1245 1246
         else:
1246 1247
             return assoc_type, session_type
@@ -1261,17 +1262,17 @@ def _requestAssociation(self, endpoint, assoc_type, session_type):
1261 1262
         try:
1262 1263
             response = self._makeKVPost(args, endpoint.server_url)
1263 1264
         except fetchers.HTTPFetchingError, why:
1264  
-            oidutil.log('openid.associate request failed: %s' % (why[0],))
  1265
+            logging.exception('openid.associate request failed: %s' % (why[0],))
1265 1266
             return None
1266 1267
 
1267 1268
         try:
1268 1269
             assoc = self._extractAssociation(response, assoc_session)
1269 1270
         except KeyError, why:
1270  
-            oidutil.log('Missing required parameter in response from %s: %s'
  1271
+            logging.exception('Missing required parameter in response from %s: %s'
1271 1272
                         % (endpoint.server_url, why[0]))
1272 1273
             return None
1273 1274
         except ProtocolError, why:
1274  
-            oidutil.log('Protocol error parsing response from %s: %s' % (
  1275
+            logging.exception('Protocol error parsing response from %s: %s' % (
1275 1276
                 endpoint.server_url, why[0]))
1276 1277
             return None
1277 1278
         else:
@@ -1348,7 +1349,7 @@ def _getOpenID1SessionType(self, assoc_response):
1348 1349
         # OpenID 1, but we'll accept it anyway, while issuing a
1349 1350
         # warning.
1350 1351
         if session_type == 'no-encryption':
1351  
-            oidutil.log('WARNING: OpenID server sent "no-encryption"'
  1352
+            logging.warn('OpenID server sent "no-encryption"'
1352 1353
                         'for OpenID 1.X')
1353 1354
 
1354 1355
         # Missing or empty session type is the way to flag a
@@ -1599,7 +1600,7 @@ def getMessage(self, realm, return_to=None, immediate=False):
1599 1600
         else:
1600 1601
             assoc_log_msg = 'using stateless mode.'
1601 1602
 
1602  
-        oidutil.log("Generated %s request to %s %s" %
  1603
+        logging.info("Generated %s request to %s %s" %
1603 1604
                     (mode, self.endpoint.server_url, assoc_log_msg))
1604 1605
 
1605 1606
         return message
@@ -1779,7 +1780,7 @@ def getSignedNS(self, ns_uri):
1779 1780
 
1780 1781
         for key in msg_args.iterkeys():
1781 1782
             if not self.isSigned(ns_uri, key):
1782  
-                oidutil.log("SuccessResponse.getSignedNS: (%s, %s) not signed."
  1783
+                logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed."
1783 1784
                             % (ns_uri, key))
1784 1785
                 return None
1785 1786
 
5  openid/consumer/discover.py
@@ -14,8 +14,9 @@
14 14
     ]
15 15
 
16 16
 import urlparse
  17
+import logging
17 18
 
18  
-from openid import oidutil, fetchers, urinorm
  19
+from openid import fetchers, urinorm
19 20
 
20 21
 from openid import yadis
21 22
 from openid.yadis.etxrd import nsTag, XRDSError, XRD_NS_2_0
@@ -425,7 +426,7 @@ def discoverXRI(iname):
425 426
         for service_element in services:
426 427
             endpoints.extend(flt.getServiceEndpoints(iname, service_element))
427 428
     except XRDSError:
428  
-        oidutil.log('xrds error on ' + iname)
  429
+        logging.exception('xrds error on ' + iname)
429 430
 
430 431
     for endpoint in endpoints:
431 432
         # Is there a way to pass this through the filter to the endpoint
4  openid/extensions/sreg.py
@@ -38,7 +38,7 @@
38 38
 from openid.message import registerNamespaceAlias, \
39 39
      NamespaceAliasRegistrationError
40 40
 from openid.extension import Extension
41  
-from openid import oidutil
  41
+import logging
42 42
 
43 43
 try:
44 44
     basestring #pylint:disable-msg=W0104
@@ -95,7 +95,7 @@ def checkFieldName(field_name):
95 95
 try:
96 96
     registerNamespaceAlias(ns_uri_1_1, 'sreg')
97 97
 except NamespaceAliasRegistrationError, e:
98  
-    oidutil.log('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri_1_1,
  98
+    logging.exception('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri_1_1,
99 99
                                                                'sreg', str(e),))
100 100
 
101 101
 def supportsSReg(endpoint):
7  openid/kvform.py
... ...
@@ -1,8 +1,7 @@
1 1
 __all__ = ['seqToKV', 'kvToSeq', 'dictToKV', 'kvToDict']
2 2
 
3  
-from openid import oidutil
4  
-
5 3
 import types
  4
+import logging
6 5
 
7 6
 class KVFormError(ValueError):
8 7
     pass
@@ -22,7 +21,7 @@ def err(msg):
22 21
         if strict:
23 22
             raise KVFormError(formatted)
24 23
         else:
25  
-            oidutil.log(formatted)
  24
+            logging.warn(formatted)
26 25
 
27 26
     lines = []
28 27
     for k, v in seq:
@@ -73,7 +72,7 @@ def err(msg):
73 72
         if strict:
74 73
             raise KVFormError(formatted)
75 74
         else:
76  
-            oidutil.log(formatted)
  75
+            logging.warn(formatted)
77 76
 
78 77
     lines = data.split('\n')
79 78
     if lines[-1]:
26  openid/oidutil.py
@@ -10,6 +10,7 @@
10 10
 import binascii
11 11
 import sys
12 12
 import urlparse
  13
+import logging
13 14
 
14 15
 from urllib import urlencode
15 16
 
@@ -77,9 +78,8 @@ def importElementTree(module_names=None):
77 78
             except (SystemExit, MemoryError, AssertionError):
78 79
                 raise
79 80
             except:
80  
-                why = sys.exc_info()[1]
81  
-                log('Not using ElementTree library %r because it failed to '
82  
-                    'parse a trivial document: %s' % (mod_name, why))
  81
+                logging.exception('Not using ElementTree library %r because it failed to '
  82
+                    'parse a trivial document: %s' % mod_name)
83 83
             else:
84 84
                 return ElementTree
85 85
     else:
@@ -91,20 +91,8 @@ def importElementTree(module_names=None):
91 91
 def log(message, level=0):
92 92
     """Handle a log message from the OpenID library.
93 93
 
94  
-    This implementation writes the string it to C{sys.stderr},
95  
-    followed by a newline.
96  
-
97  
-    Currently, the library does not use the second parameter to this
98  
-    function, but that may change in the future.
99  
-
100  
-    To install your own logging hook::
101  
-
102  
-      from openid import oidutil
103  
-
104  
-      def myLoggingFunction(message, level):
105  
-          ...
106  
-
107  
-      oidutil.log = myLoggingFunction
  94
+    This is a legacy function which redirects to logging.error.
  95
+    The logging module should be used instead of this
108 96
 
109 97
     @param message: A string containing a debugging message from the
110 98
         OpenID library
@@ -118,8 +106,8 @@ def myLoggingFunction(message, level):
118 106
     @returns: Nothing.
119 107
     """
120 108
 
121  
-    sys.stderr.write(message)
122  
-    sys.stderr.write('\n')
  109
+    logging.error("This is a legacy log message, please use the "
  110
+      "logging module. Message: %s", message)
123 111
 
124 112
 def appendArgs(url, args):
125 113
     """Append query arguments to a HTTP(s) URL. If the URL already has
9  openid/server/server.py
@@ -117,6 +117,7 @@
117 117
 """
118 118
 
119 119
 import time, warnings
  120
+import logging
120 121
 from copy import deepcopy
121 122
 
122 123
 from openid import cryptutil
@@ -420,7 +421,7 @@ def fromMessage(klass, message, op_endpoint=UNUSED):
420 421
         if message.isOpenID1():
421 422
             session_type = message.getArg(OPENID_NS, 'session_type')
422 423
             if session_type == 'no-encryption':
423  
-                oidutil.log('Received OpenID 1 request with a no-encryption '
  424
+                logging.warn('Received OpenID 1 request with a no-encryption '
424 425
                             'assocaition session type. Continuing anyway.')
425 426
             elif not session_type:
426 427
                 session_type = 'no-encryption'
@@ -1170,7 +1171,7 @@ def verify(self, assoc_handle, message):
1170 1171
         """
1171 1172
         assoc = self.getAssociation(assoc_handle, dumb=True)
1172 1173
         if not assoc:
1173  
-            oidutil.log("failed to get assoc with handle %r to verify "
  1174
+            logging.error("failed to get assoc with handle %r to verify "
1174 1175
                         "message %r"
1175 1176
                         % (assoc_handle, message))
1176 1177
             return False
@@ -1178,7 +1179,7 @@ def verify(self, assoc_handle, message):
1178 1179
         try:
1179 1180
             valid = assoc.checkMessageSignature(message)
1180 1181
         except ValueError, ex:
1181  
-            oidutil.log("Error in verifying %s with %s: %s" % (message,
  1182
+            logging.exception("Error in verifying %s with %s: %s" % (message,
1182 1183
                                                                assoc,
1183 1184
                                                                ex))
1184 1185
             return False
@@ -1285,7 +1286,7 @@ def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
1285 1286
             key = self._normal_key
1286 1287
         assoc = self.store.getAssociation(key, assoc_handle)
1287 1288
         if assoc is not None and assoc.expiresIn <= 0:
1288  
-            oidutil.log("requested %sdumb key %r is expired (by %s seconds)" %
  1289
+            logging.info("requested %sdumb key %r is expired (by %s seconds)" %
1289 1290
                         ((not dumb) and 'not-' or '',
1290 1291
                          assoc_handle, assoc.expiresIn))
1291 1292
             if checkExpiration:
6  openid/server/trustroot.py
@@ -17,12 +17,12 @@
17 17
     'verifyReturnTo',
18 18
     ]
19 19
 
20  
-from openid import oidutil
21 20
 from openid import urinorm
22 21
 from openid.yadis import services
23 22
 
24 23
 from urlparse import urlparse, urlunparse
25 24
 import re
  25
+import logging
26 26
 
27 27
 ############################################
28 28
 _protocols = ['http', 'https']
@@ -443,12 +443,12 @@ def verifyReturnTo(realm_str, return_to, _vrfy=getAllowedReturnURLs):
443 443
     try:
444 444
         allowable_urls = _vrfy(realm.buildDiscoveryURL())
445 445
     except RealmVerificationRedirected, err:
446  
-        oidutil.log(str(err))
  446
+        logging.exception(str(err))
447 447
         return False
448 448
 
449 449
     if returnToMatches(allowable_urls, return_to):
450 450
         return True
451 451
     else:
452  
-        oidutil.log("Failed to validate return_to %r for realm %r, was not "
  452
+        logging.error("Failed to validate return_to %r for realm %r, was not "
453 453
                     "in %s" % (return_to, realm_str, allowable_urls))
454 454
         return False
3  openid/store/filestore.py
@@ -7,6 +7,7 @@
7 7
 import os
8 8
 import os.path
9 9
 import time
  10
+import logging
10 11
 
11 12
 from errno import EEXIST, ENOENT
12 13
 
@@ -371,7 +372,7 @@ def _allAssocs(self):
371 372
                 association_file = file(association_filename, 'rb')
372 373
             except IOError, why:
373 374
                 if why.errno == ENOENT:
374  
-                    oidutil.log("%s disappeared during %s._allAssocs" % (
  375
+                    logging.exception("%s disappeared during %s._allAssocs" % (
375 376
                         association_filename, self.__class__.__name__))
376 377
                 else:
377 378
                     raise
22  openid/test/kvform.py
... ...
@@ -1,26 +1,19 @@
1 1
 from openid import kvform
2  
-from openid import oidutil
  2
+from openid.test.support import CatchLogs
3 3
 import unittest
4 4
 
5  
-class KVBaseTest(unittest.TestCase):
  5
+class KVBaseTest(unittest.TestCase, CatchLogs):
6 6
     def shortDescription(self):
7 7
         return '%s test for %r' % (self.__class__.__name__, self.kvform)
8 8
 
9  
-    def log(self, message, unused_priority=None):
10  
-        self.warnings.append(message)
11  
-
12 9
     def checkWarnings(self, num_warnings):
13  
-        self.failUnlessEqual(num_warnings, len(self.warnings), repr(self.warnings))
  10
+        self.failUnlessEqual(num_warnings, len(self.messages), repr(self.messages))
14 11
 
15 12
     def setUp(self):
16  
-        self.warnings = []
17  
-        self.old_log = oidutil.log
18  
-        self.log_func = oidutil.log = self.log
19  
-        self.failUnless(self.log_func is oidutil.log,
20  
-                        (oidutil.log, self.log_func))
  13
+        CatchLogs.setUp(self)
21 14
 
22 15
     def tearDown(self):
23  
-        oidutil.log = self.old_log
  16
+        CatchLogs.tearDown(self)
24 17
 
25 18
 class KVDictTest(KVBaseTest):
26 19
     def __init__(self, kv, dct, warnings):
@@ -172,3 +165,8 @@ def pyUnitTests():
172 165
     tests.extend([KVExcTest(case) for case in kvexc_cases])
173 166
     tests.append(unittest.defaultTestLoader.loadTestsFromTestCase(GeneralTest))
174 167
     return unittest.TestSuite(tests)
  168
+
  169
+if __name__ == '__main__':
  170
+    suite = pyUnitTests()
  171
+    runner = unittest.TextTestRunner()
  172
+    runner.run(suite)
40  openid/test/support.py
... ...
@@ -1,5 +1,17 @@
1 1
 from openid import message
2  
-from openid import oidutil
  2
+from logging.handlers import BufferingHandler
  3
+import logging
  4
+
  5
+class TestHandler(BufferingHandler):
  6
+    def __init__(self, messages):
  7
+        BufferingHandler.__init__(self, 0)
  8
+	self.messages = messages
  9
+
  10
+    def shouldFlush(self):
  11
+        return False
  12
+
  13
+    def emit(self, record):
  14
+        self.messages.append(record.__dict__)
3 15
 
4 16
 class OpenIDTestMixin(object):
5 17
     def failUnlessOpenIDValueEquals(self, msg, key, expected, ns=None):
@@ -21,15 +33,20 @@ def failIfOpenIDKeyExists(self, msg, key, ns=None):
21 33
 
22 34
 class CatchLogs(object):
23 35
     def setUp(self):
24  
-        self.old_logger = oidutil.log
25  
-        oidutil.log = self.gotLogMessage
26  
-        self.messages = []
  36
+	self.messages = []
  37
+	root_logger = logging.getLogger()
  38
+	self.old_log_level = root_logger.getEffectiveLevel()
  39
+	root_logger.setLevel(logging.DEBUG)
27 40
 
28  
-    def gotLogMessage(self, message):
29  
-        self.messages.append(message)
  41
+	self.handler = TestHandler(self.messages)
  42
+	formatter = logging.Formatter("%(message)s [%(asctime)s - %(name)s - %(levelname)s]")
  43
+	self.handler.setFormatter(formatter)
  44
+	root_logger.addHandler(self.handler)
30 45
 
31 46
     def tearDown(self):
32  
-        oidutil.log = self.old_logger
  47
+        root_logger = logging.getLogger()
  48
+	root_logger.removeHandler(self.handler)
  49
+	root_logger.setLevel(self.old_log_level)
33 50
 
34 51
     def failUnlessLogMatches(self, *prefixes):
35 52
         """
@@ -38,14 +55,15 @@ def failUnlessLogMatches(self, *prefixes):
38 55
         number of prefixes is different than the number of log
39 56
         messages.
40 57
         """
41  
-        assert len(prefixes) == len(self.messages), \
  58
+	messages = [r['msg'] for r in self.messages]
  59
+	assert len(prefixes) == len(messages), \
42 60
                "Expected log prefixes %r, got %r" % (prefixes,
43  
-                                                     self.messages)
  61
+                                                     messages)
44 62
 
45  
-        for prefix, message in zip(prefixes, self.messages):
  63
+        for prefix, message in zip(prefixes, messages):
46 64
             assert message.startswith(prefix), \
47 65
                    "Expected log prefixes %r, got %r" % (prefixes,
48  
-                                                         self.messages)
  66
+                                                         messages)
49 67
 
50 68
     def failUnlessLogEmpty(self):
51 69
         self.failUnlessLogMatches()
4  openid/test/test_negotiation.py
@@ -163,8 +163,8 @@ class TestOpenID1SessionNegotiation(unittest.TestCase, CatchLogs):
163 163
     Tests for the OpenID 1 consumer association session behavior.  See
164 164
     the docs for TestOpenID2SessionNegotiation.  Notice that this
165 165
     class is not a subclass of the OpenID 2 tests.  Instead, it uses
166  
-    many of the same inputs but inspects the log messages logged with
167  
-    oidutil.log.  See the calls to self.failUnlessLogMatches.  Some of
  166
+    many of the same inputs but inspects the log messages.
  167
+    See the calls to self.failUnlessLogMatches.  Some of
168 168
     these tests pass openid2-style messages to the openid 1
169 169
     association processing logic to be sure it ignores the extra data.
170 170
     """
17  openid/test/test_server.py
@@ -5,6 +5,7 @@
5 5
 from openid.message import Message, OPENID_NS, OPENID2_NS, OPENID1_NS, \
6 6
      IDENTIFIER_SELECT, no_default, OPENID1_URL_LIMIT
7 7
 from openid.store import memstore
  8
+from openid.test.support import CatchLogs
8 9
 import cgi
9 10
 
10 11
 import unittest
@@ -21,18 +22,6 @@
21 22
 ALT_MODULUS = 0xCAADDDEC1667FC68B5FA15D53C4E1532DD24561A1A2D47A12C01ABEA1E00731F6921AAC40742311FDF9E634BB7131BEE1AF240261554389A910425E044E88C8359B010F5AD2B80E29CB1A5B027B19D9E01A6F63A6F45E5D7ED2FF6A2A0085050A7D0CF307C3DB51D2490355907B4427C23A98DF1EB8ABEF2BA209BB7AFFE86A7
22 23
 ALT_GEN = 5
23 24
 
24  
-class CatchLogs(object):
25  
-    def setUp(self):
26  
-        self.old_logger = oidutil.log
27  
-        oidutil.log = self.gotLogMessage
28  
-        self.messages = []
29  
-
30  
-    def gotLogMessage(self, message):
31  
-        self.messages.append(message)
32  
-
33  
-    def tearDown(self):
34  
-        oidutil.log = self.old_logger
35  
-
36 25
 class TestProtocolError(unittest.TestCase):
37 26
     def test_browserWithReturnTo(self):
38 27
         return_to = "http://rp.unittest/consumer"
@@ -1999,10 +1988,10 @@ def test_getAssoc(self):
1999 1988
         self.failIf(self.messages, self.messages)
2000 1989
 
2001 1990
     def test_getAssocExpired(self):
2002  
-        assoc_handle = self.makeAssoc(dumb=True, lifetime=-10)
  1991
+	assoc_handle = self.makeAssoc(dumb=True, lifetime=-10)
2003 1992
         assoc = self.signatory.getAssociation(assoc_handle, True)
2004 1993
         self.failIf(assoc, assoc)
2005  
-        self.failUnless(self.messages)
  1994
+	self.failUnless(self.messages)
2006 1995
 
2007 1996
     def test_getAssocInvalid(self):
2008 1997
         ah = 'no-such-handle'

0 notes on commit 7d65da5

Please sign in to comment.
Something went wrong with that request. Please try again.