[Checkins] SVN: zope.error/trunk/ Prepare zope.error
Roger Ineichen
roger at projekt01.ch
Mon Sep 24 16:42:40 EDT 2007
Log message for revision 79905:
Prepare zope.error
Changed:
_U zope.error/trunk/
A zope.error/trunk/CHANGES.txt
A zope.error/trunk/README.txt
A zope.error/trunk/bootstrap.py
A zope.error/trunk/buildout.cfg
A zope.error/trunk/setup.py
A zope.error/trunk/src/
A zope.error/trunk/src/zope/
A zope.error/trunk/src/zope/__init__.py
A zope.error/trunk/src/zope/error/
A zope.error/trunk/src/zope/error/SETUP.cfg
A zope.error/trunk/src/zope/error/__init__.py
A zope.error/trunk/src/zope/error/bootstrap.py
A zope.error/trunk/src/zope/error/configure.zcml
A zope.error/trunk/src/zope/error/error.py
A zope.error/trunk/src/zope/error/interfaces.py
A zope.error/trunk/src/zope/error/tests.py
A zope.error/trunk/src/zope/error/zope.error-configure.zcml
-=-
Property changes on: zope.error/trunk
___________________________________________________________________
Name: svn:ignore
+ bin
.installed.cfg
develop-eggs
parts
Added: zope.error/trunk/CHANGES.txt
===================================================================
--- zope.error/trunk/CHANGES.txt (rev 0)
+++ zope.error/trunk/CHANGES.txt 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,14 @@
+=======
+CHANGES
+=======
+
+Version 3.5.0
+-------------
+
+- Move core components to ``zope.error``
+
+
+Version 3.4.0 (2007/9/24)
+-------------------------
+
+- Initial documented release
Property changes on: zope.error/trunk/CHANGES.txt
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/README.txt
===================================================================
--- zope.error/trunk/README.txt (rev 0)
+++ zope.error/trunk/README.txt 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1 @@
+This package provides an error reporting utility which is able to store errors.
Property changes on: zope.error/trunk/README.txt
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/bootstrap.py
===================================================================
--- zope.error/trunk/bootstrap.py (rev 0)
+++ zope.error/trunk/bootstrap.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,52 @@
+##############################################################################
+#
+# Copyright (c) 2006 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Bootstrap a buildout-based project
+
+Simply run this script in a directory containing a buildout.cfg.
+The script accepts buildout command-line options, so you can
+use the -c option to specify an alternate configuration file.
+
+$Id: bootstrap.py 73543 2007-03-25 08:43:44Z dobe $
+"""
+
+import os, shutil, sys, tempfile, urllib2
+
+tmpeggs = tempfile.mkdtemp()
+
+ez = {}
+exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py'
+ ).read() in ez
+ez['use_setuptools'](to_dir=tmpeggs, download_delay=0)
+
+import pkg_resources
+
+cmd = 'from setuptools.command.easy_install import main; main()'
+if sys.platform == 'win32':
+ cmd = '"%s"' % cmd # work around spawn lamosity on windows
+
+ws = pkg_resources.working_set
+assert os.spawnle(
+ os.P_WAIT, sys.executable, sys.executable,
+ '-c', cmd, '-mqNxd', tmpeggs, 'zc.buildout',
+ dict(os.environ,
+ PYTHONPATH=
+ ws.find(pkg_resources.Requirement.parse('setuptools')).location
+ ),
+ ) == 0
+
+ws.add_entry(tmpeggs)
+ws.require('zc.buildout')
+import zc.buildout.buildout
+zc.buildout.buildout.main(sys.argv[1:] + ['bootstrap'])
+shutil.rmtree(tmpeggs)
Property changes on: zope.error/trunk/bootstrap.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/buildout.cfg
===================================================================
--- zope.error/trunk/buildout.cfg (rev 0)
+++ zope.error/trunk/buildout.cfg 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,8 @@
+[buildout]
+develop = .
+parts = test
+find-links = http://download.zope.org/distribution/
+
+[test]
+recipe = zc.recipe.testrunner
+eggs = zope.error [test]
Added: zope.error/trunk/setup.py
===================================================================
--- zope.error/trunk/setup.py (rev 0)
+++ zope.error/trunk/setup.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,63 @@
+##############################################################################
+#
+# Copyright (c) 2006 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Setup for zope.error package
+
+$Id: setup.py 79889 2007-09-24 16:35:25Z rogerineichen $
+"""
+
+import os
+
+from setuptools import setup, find_packages
+
+def read(*rnames):
+ return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
+
+setup(name='zope.error',
+ version = '3.5.0',
+ author='Zope Corporation and Contributors',
+ author_email='zope3-dev at zope.org',
+ description = "An error reporting utility for Zope3",
+ long_description=(
+ read('README.txt')
+ + '\n\n' +
+ read('CHANGES.txt')
+ ),
+ license='ZPL 2.1',
+ keywords = "zope3 error",
+ classifiers = [
+ 'Development Status :: 5 - Production/Stable',
+ 'Environment :: Web Environment',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: Zope Public License',
+ 'Programming Language :: Python',
+ 'Natural Language :: English',
+ 'Operating System :: OS Independent',
+ 'Topic :: Internet :: WWW/HTTP',
+ 'Framework :: Zope3'],
+ url='http://cheeseshop.python.org/pypi/zope.error',
+ packages=find_packages('src'),
+ package_dir = {'': 'src'},
+ extras_require=dict(
+ test=['zope.app.testing']),
+ namespace_packages=['zope',],
+ install_requires=['setuptools',
+ 'zope.exceptions',
+ 'zope.app.appsetup',
+ 'zope.publisher',
+ 'zope.app.container',
+ ],
+ include_package_data = True,
+
+ zip_safe = False,
+ )
Property changes on: zope.error/trunk/setup.py
___________________________________________________________________
Name: svn:eol-style
+ native
Property changes on: zope.error/trunk/src
___________________________________________________________________
Name: svn:ignore
+ zope.error.egg-info
Added: zope.error/trunk/src/zope/__init__.py
===================================================================
--- zope.error/trunk/src/zope/__init__.py (rev 0)
+++ zope.error/trunk/src/zope/__init__.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,8 @@
+# this is a namespace package
+try:
+ import pkg_resources
+ pkg_resources.declare_namespace(__name__)
+except ImportError:
+ import pkgutil
+ __path__ = pkgutil.extend_path(__path__, __name__)
+
Property changes on: zope.error/trunk/src/zope/__init__.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/SETUP.cfg
===================================================================
--- zope.error/trunk/src/zope/error/SETUP.cfg (rev 0)
+++ zope.error/trunk/src/zope/error/SETUP.cfg 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,5 @@
+# Tell zpkg how to install the ZCML slugs.
+
+<data-files zopeskel/etc/package-includes>
+ zope.error-*.zcml
+</data-files>
Added: zope.error/trunk/src/zope/error/__init__.py
===================================================================
--- zope.error/trunk/src/zope/error/__init__.py (rev 0)
+++ zope.error/trunk/src/zope/error/__init__.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1 @@
+# import this
Property changes on: zope.error/trunk/src/zope/error/__init__.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/bootstrap.py
===================================================================
--- zope.error/trunk/src/zope/error/bootstrap.py (rev 0)
+++ zope.error/trunk/src/zope/error/bootstrap.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,38 @@
+##############################################################################
+#
+# Copyright (c) 2002, 2004 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Bootstrap code for error reporting utility.
+
+$Id: bootstrap.py 70794 2006-10-19 04:29:42Z baijum $
+"""
+
+import transaction
+
+from zope.app.appsetup.bootstrap import ensureUtility, getInformationFromEvent
+
+from zope.error.error import RootErrorReportingUtility
+from zope.error.interfaces import IErrorReportingUtility
+
+def bootStrapSubscriber(event):
+ """Subscriber to the IDataBaseOpenedEvent
+
+ Create utility at that time if not yet present
+ """
+
+ db, connection, root, root_folder = getInformationFromEvent(event)
+
+ ensureUtility(root_folder, IErrorReportingUtility, '',
+ RootErrorReportingUtility, copy_to_zlog=False, asObject=True)
+
+ transaction.commit()
+ connection.close()
Property changes on: zope.error/trunk/src/zope/error/bootstrap.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/configure.zcml
===================================================================
--- zope.error/trunk/src/zope/error/configure.zcml (rev 0)
+++ zope.error/trunk/src/zope/error/configure.zcml 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,42 @@
+<configure
+ xmlns="http://namespaces.zope.org/zope">
+
+ <class class=".error.ErrorReportingUtility">
+ <factory
+ id="zope.app.ErrorLogging"
+ />
+ <implements
+ interface="zope.annotation.interfaces.IAttributeAnnotatable"
+ />
+ <require
+ permission="zope.Public"
+ interface=".interfaces.IErrorReportingUtility"
+ />
+ <require
+ permission="zope.ManageServices"
+ interface=".interfaces.ILocalErrorReportingUtility"
+ />
+ </class>
+
+ <class class=".error.RootErrorReportingUtility">
+ <require
+ permission="zope.Public"
+ interface=".interfaces.IErrorReportingUtility"
+ />
+ <require
+ permission="zope.ManageServices"
+ interface=".interfaces.ILocalErrorReportingUtility"
+ />
+ </class>
+
+ <utility
+ provides=".interfaces.IErrorReportingUtility"
+ component=".error.globalErrorReportingUtility"
+ />
+
+ <subscriber
+ for="zope.app.appsetup.IDatabaseOpenedEvent"
+ handler=".bootstrap.bootStrapSubscriber"
+ />
+
+</configure>
Property changes on: zope.error/trunk/src/zope/error/configure.zcml
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/error.py
===================================================================
--- zope.error/trunk/src/zope/error/error.py (rev 0)
+++ zope.error/trunk/src/zope/error/error.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,286 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Error Reporting Utility
+
+This is a port of the Zope 2 error reporting object
+
+$Id: error.py 70794 2006-10-19 04:29:42Z baijum $
+"""
+__docformat__ = 'restructuredtext'
+
+import time
+import logging
+import codecs
+
+from persistent import Persistent
+from random import random
+from threading import Lock
+
+from zope.exceptions.exceptionformatter import format_exception
+from zope.interface import implements
+
+from zope.app.container.contained import Contained
+from zope.error.interfaces import IErrorReportingUtility
+from zope.error.interfaces import ILocalErrorReportingUtility
+
+
+#Restrict the rate at which errors are sent to the Event Log
+_rate_restrict_pool = {}
+
+# The number of seconds that must elapse on average between sending two
+# exceptions of the same name into the the Event Log. one per minute.
+_rate_restrict_period = 60
+
+# The number of exceptions to allow in a burst before the above limit
+# kicks in. We allow five exceptions, before limiting them to one per
+# minute.
+_rate_restrict_burst = 5
+
+# _temp_logs holds the logs.
+_temp_logs = {} # { oid -> [ traceback string ] }
+
+cleanup_lock = Lock()
+
+logger = logging.getLogger('SiteError')
+
+def printedreplace(error):
+ symbols = (ur"\x%02x" % ord(s)
+ for s in error.object[error.start:error.end])
+ return u"".join(symbols), error.end
+
+codecs.register_error("zope.app.error.printedreplace", printedreplace)
+
+def getPrintable(value):
+ if not isinstance(value, unicode):
+ if not isinstance(value, str):
+ # A call to str(obj) could raise anything at all.
+ # We'll ignore these errors, and print something
+ # useful instead, but also log the error.
+ try:
+ value = str(value)
+ except:
+ logger.exception(
+ "Error in ErrorReportingUtility while getting a str"
+ " representation of an object")
+ return u"<unprintable %s object>" % type(value).__name__
+ value = unicode(value, errors="zope.app.error.printedreplace")
+ return value
+
+def getFormattedException(info, as_html=False):
+ lines = []
+ for line in format_exception(as_html=as_html, *info):
+ line = getPrintable(line)
+ if not line.endswith("\n"):
+ if not as_html:
+ line += "\n"
+ else:
+ line += "<br />\n"
+ lines.append(line)
+ return u"".join(lines)
+
+class ErrorReportingUtility(Persistent, Contained):
+ """Error Reporting Utility"""
+ implements(IErrorReportingUtility, ILocalErrorReportingUtility)
+
+ keep_entries = 20
+ copy_to_zlog = 0
+ _ignored_exceptions = ('Unauthorized',)
+
+
+ def _getLog(self):
+ """Returns the log for this object.
+ Careful, the log is shared between threads.
+ """
+ log = _temp_logs.get(self._p_oid, None)
+ if log is None:
+ log = []
+ _temp_logs[self._p_oid] = log
+ return log
+
+ def _getUsername(self, request):
+ username = None
+
+ principal = getattr(request, "principal", None)
+ if principal is None:
+ return username
+
+ # UnauthenticatedPrincipal does not have getLogin()
+ getLogin = getattr(principal, "getLogin", None)
+ if getLogin is None:
+ login = "unauthenticated"
+ else:
+ try:
+ login = getLogin()
+ except:
+ logger.exception("Error in ErrorReportingUtility while"
+ " getting login of the principal")
+ login = u"<error getting login>"
+
+ parts = []
+ for part in [
+ login,
+ getattr(principal, "id",
+ u"<error getting 'principal.id'>"),
+ getattr(principal, "title",
+ u"<error getting 'principal.title'>"),
+ getattr(principal, "description",
+ u"<error getting 'principal.description'>")
+ ]:
+ part = getPrintable(part)
+ parts.append(part)
+ username = u", ".join(parts)
+ return username
+
+ def _getRequestAsHTML(self, request):
+ lines = []
+ for key, value in request.items():
+ lines.append(u"%s: %s<br />\n" % (
+ getPrintable(key), getPrintable(value)))
+ return u"".join(lines)
+
+ # Exceptions that happen all the time, so we dont need
+ # to log them. Eventually this should be configured
+ # through-the-web.
+ def raising(self, info, request=None):
+ """Log an exception.
+ Called by ZopePublication.handleException method.
+ """
+ now = time.time()
+ try:
+ strtype = unicode(getattr(info[0], '__name__', info[0]))
+ if strtype in self._ignored_exceptions:
+ return
+
+ tb_text = None
+ tb_html = None
+ if not isinstance(info[2], basestring):
+ tb_text = getFormattedException(info)
+ tb_html = getFormattedException(info, True)
+ else:
+ tb_text = getPrintable(info[2])
+
+ url = None
+ username = None
+ req_html = None
+ if request:
+ # TODO: Temporary fix, which Steve should undo. URL is
+ # just too HTTPRequest-specific.
+ if hasattr(request, 'URL'):
+ url = request.URL
+ username = self._getUsername(request)
+ req_html = self._getRequestAsHTML(request)
+
+ strv = getPrintable(info[1])
+
+ log = self._getLog()
+ entry_id = str(now) + str(random()) # Low chance of collision
+
+ log.append({
+ 'type': strtype,
+ 'value': strv,
+ 'time': time.ctime(now),
+ 'id': entry_id,
+ 'tb_text': tb_text,
+ 'tb_html': tb_html,
+ 'username': username,
+ 'url': url,
+ 'req_html': req_html,
+ })
+ cleanup_lock.acquire()
+ try:
+ if len(log) >= self.keep_entries:
+ del log[:-self.keep_entries]
+ finally:
+ cleanup_lock.release()
+
+ if self.copy_to_zlog:
+ self._do_copy_to_zlog(now, strtype, str(url), info)
+ finally:
+ info = None
+
+ def _do_copy_to_zlog(self, now, strtype, url, info):
+ # info is unused; logging.exception() will call sys.exc_info()
+ # work around this with an evil hack
+ when = _rate_restrict_pool.get(strtype,0)
+ if now > when:
+ next_when = max(when,
+ now - _rate_restrict_burst * _rate_restrict_period)
+ next_when += _rate_restrict_period
+ _rate_restrict_pool[strtype] = next_when
+ try:
+ raise info[0], info[1], info[2]
+ except:
+ logger.exception(str(url))
+
+ def getProperties(self):
+ return {
+ 'keep_entries': self.keep_entries,
+ 'copy_to_zlog': self.copy_to_zlog,
+ 'ignored_exceptions': self._ignored_exceptions,
+ }
+
+ def setProperties(self, keep_entries, copy_to_zlog=0,
+ ignored_exceptions=()):
+ """Sets the properties of this site error log.
+ """
+ self.keep_entries = int(keep_entries)
+ self.copy_to_zlog = bool(copy_to_zlog)
+ self._ignored_exceptions = tuple(
+ [unicode(e) for e in ignored_exceptions if e]
+ )
+
+ def getLogEntries(self):
+ """Returns the entries in the log, most recent first.
+
+ Makes a copy to prevent changes.
+ """
+ res = [entry.copy() for entry in self._getLog()]
+ res.reverse()
+ return res
+
+ def getLogEntryById(self, id):
+ """Returns the specified log entry.
+ Makes a copy to prevent changes. Returns None if not found.
+ """
+ for entry in self._getLog():
+ if entry['id'] == id:
+ return entry.copy()
+ return None
+
+class RootErrorReportingUtility(ErrorReportingUtility):
+ rootId = 'root'
+
+ def _getLog(self):
+ """Returns the log for this object.
+
+ Careful, the log is shared between threads.
+ """
+ log = _temp_logs.get(self.rootId, None)
+ if log is None:
+ log = []
+ _temp_logs[self.rootId] = log
+ return log
+
+
+globalErrorReportingUtility = RootErrorReportingUtility()
+
+def _cleanup_temp_log():
+ _temp_logs.clear()
+
+_clear = _cleanup_temp_log
+
+# Register our cleanup with Testing.CleanUp to make writing unit tests simpler.
+from zope.testing.cleanup import addCleanUp
+addCleanUp(_clear)
+del addCleanUp
Property changes on: zope.error/trunk/src/zope/error/error.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/interfaces.py
===================================================================
--- zope.error/trunk/src/zope/error/interfaces.py (rev 0)
+++ zope.error/trunk/src/zope/error/interfaces.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,52 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Error Reporting Utility interfaces
+
+$Id: interfaces.py 70211 2006-09-17 14:45:07Z flox $
+"""
+__docformat__ = 'restructuredtext'
+
+from zope.interface import Interface
+
+class IErrorReportingUtility(Interface):
+ """Error Reporting Utility"""
+
+ def raising(info, request=None):
+ """Logs an exception."""
+
+
+class ILocalErrorReportingUtility(Interface):
+ """Local Error Reporting Utility
+
+ This interface contains additional management functions.
+ """
+
+ def getProperties():
+ """Gets the properties as dictionary.
+
+ keep_entries, copy_to_logfile, ignored_exceptions
+ """
+
+ def setProperties(keep_entries, copy_to_zlog=0, ignored_exceptions=(),
+ RESPONSE=None):
+ """Sets the properties
+
+ keep_entries, copy_to_logfile, ignored_exceptions
+ """
+
+ def getLogEntries():
+ """Returns the entries in the log, most recent first."""
+
+ def getLogEntryById(id):
+ """Return LogEntry by ID"""
Property changes on: zope.error/trunk/src/zope/error/interfaces.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/tests.py
===================================================================
--- zope.error/trunk/src/zope/error/tests.py (rev 0)
+++ zope.error/trunk/src/zope/error/tests.py 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1,137 @@
+##############################################################################
+#
+# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
+# All Rights Reserved.
+#
+# This software is subject to the provisions of the Zope Public License,
+# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
+# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
+# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
+# FOR A PARTICULAR PURPOSE.
+#
+##############################################################################
+"""Error Reporting Utility Tests
+
+$Id: tests.py 41724 2006-02-21 13:27:44Z hdima $
+"""
+import sys
+import unittest
+
+from zope.exceptions.exceptionformatter import format_exception
+from zope.publisher.tests.httprequest import TestRequest
+from zope.app.testing.placelesssetup import PlacelessSetup
+
+from zope.error.error import ErrorReportingUtility, getFormattedException
+
+class Error(Exception):
+
+ def __init__(self, value):
+ self.value = value
+
+ def __str__(self):
+ return self.value
+
+def getAnErrorInfo(value=""):
+ try:
+ raise Error(value)
+ except:
+ return sys.exc_info()
+
+class ErrorReportingUtilityTests(PlacelessSetup, unittest.TestCase):
+
+ def test_checkForEmpryLog(self):
+ # Test Check Empty Log
+ errUtility = ErrorReportingUtility()
+ getProp = errUtility.getLogEntries()
+ self.failIf(getProp)
+
+ def test_checkProperties(self):
+ # Test Properties test
+ errUtility = ErrorReportingUtility()
+ setProp = {
+ 'keep_entries':10,
+ 'copy_to_zlog':1,
+ 'ignored_exceptions':()
+ }
+ errUtility.setProperties(**setProp)
+ getProp = errUtility.getProperties()
+ self.assertEqual(setProp, getProp)
+
+ def test_ErrorLog(self):
+ # Test for Logging Error. Create one error and check whether its
+ # logged or not.
+ errUtility = ErrorReportingUtility()
+ exc_info = getAnErrorInfo()
+ errUtility.raising(exc_info)
+ getErrLog = errUtility.getLogEntries()
+ self.assertEquals(1, len(getErrLog))
+
+ tb_text = ''.join(format_exception(as_html=0, *exc_info))
+
+ err_id = getErrLog[0]['id']
+ self.assertEquals(tb_text,
+ errUtility.getLogEntryById(err_id)['tb_text'])
+
+ def test_ErrorLog_unicode(self):
+ # Emulate a unicode url, it gets encoded to utf-8 before it's passed
+ # to the request. Also add some unicode field to the request's
+ # environment and make the principal's title unicode.
+ request = TestRequest(environ={'PATH_INFO': '/\xd1\x82',
+ 'SOME_UNICODE': u'\u0441'})
+ class PrincipalStub(object):
+ id = u'\u0441'
+ title = u'\u0441'
+ description = u'\u0441'
+ request.setPrincipal(PrincipalStub())
+
+ errUtility = ErrorReportingUtility()
+ exc_info = getAnErrorInfo(u"Error (\u0441)")
+ errUtility.raising(exc_info, request=request)
+ getErrLog = errUtility.getLogEntries()
+ self.assertEquals(1, len(getErrLog))
+
+ tb_text = ''.join(format_exception(as_html=0, *exc_info))
+
+ err_id = getErrLog[0]['id']
+ self.assertEquals(tb_text,
+ errUtility.getLogEntryById(err_id)['tb_text'])
+
+ username = getErrLog[0]['username']
+ self.assertEquals(username, u'unauthenticated, \u0441, \u0441, \u0441')
+
+ def test_ErrorLog_nonascii(self):
+ # Emulate a unicode url, it gets encoded to utf-8 before it's passed
+ # to the request. Also add some unicode field to the request's
+ # environment and make the principal's title unicode.
+ request = TestRequest(environ={'PATH_INFO': '/\xd1\x82',
+ 'SOME_NONASCII': '\xe1'})
+ class PrincipalStub(object):
+ id = '\xe1'
+ title = '\xe1'
+ description = '\xe1'
+ request.setPrincipal(PrincipalStub())
+
+ errUtility = ErrorReportingUtility()
+ exc_info = getAnErrorInfo("Error (\xe1)")
+ errUtility.raising(exc_info, request=request)
+ getErrLog = errUtility.getLogEntries()
+ self.assertEquals(1, len(getErrLog))
+
+ tb_text = getFormattedException(exc_info)
+
+ err_id = getErrLog[0]['id']
+ self.assertEquals(tb_text,
+ errUtility.getLogEntryById(err_id)['tb_text'])
+
+ username = getErrLog[0]['username']
+ self.assertEquals(username, r"unauthenticated, \xe1, \xe1, \xe1")
+
+
+def test_suite():
+ return unittest.TestSuite((
+ unittest.makeSuite(ErrorReportingUtilityTests),
+ ))
+
+if __name__ == '__main__':
+ unittest.main(defaultTest='test_suite')
Property changes on: zope.error/trunk/src/zope/error/tests.py
___________________________________________________________________
Name: svn:eol-style
+ native
Added: zope.error/trunk/src/zope/error/zope.error-configure.zcml
===================================================================
--- zope.error/trunk/src/zope/error/zope.error-configure.zcml (rev 0)
+++ zope.error/trunk/src/zope/error/zope.error-configure.zcml 2007-09-24 20:42:39 UTC (rev 79905)
@@ -0,0 +1 @@
+<include package="zope.error"/>
Property changes on: zope.error/trunk/src/zope/error/zope.error-configure.zcml
___________________________________________________________________
Name: svn:eol-style
+ native
More information about the Checkins
mailing list