From 7d0bd4b8951ef7894668ad3c63607769e208c9d0 Mon Sep 17 00:00:00 2001 From: Pavel Zuna Date: Thu, 23 Apr 2009 14:51:59 +0200 Subject: Rename errors2.py to errors.py. Modify all affected files. --- install/tools/ipa-compat-manage | 6 +- ipalib/__init__.py | 2 +- ipalib/backend.py | 2 +- ipalib/cli.py | 2 +- ipalib/errors.py | 1077 ++++++++++++++++++++++++++++ ipalib/errors2.py | 1077 ---------------------------- ipalib/frontend.py | 4 +- ipalib/parameters.py | 2 +- ipalib/plugable.py | 20 +- ipalib/plugins/aci.py | 28 +- ipalib/plugins/automount.py | 12 +- ipalib/plugins/basegroup.py | 4 +- ipalib/plugins/group.py | 4 +- ipalib/plugins/host.py | 6 +- ipalib/plugins/join.py | 8 +- ipalib/plugins/passwd.py | 4 +- ipalib/plugins/service.py | 10 +- ipalib/plugins/user.py | 6 +- ipalib/plugins/user2.py | 14 +- ipalib/rpc.py | 18 +- ipalib/util.py | 4 +- ipaserver/install/krbinstance.py | 4 +- ipaserver/install/ldapupdate.py | 14 +- ipaserver/install/replication.py | 10 +- ipaserver/ipaldap.py | 28 +- ipaserver/plugins/ldap2.py | 50 +- ipaserver/plugins/ldapapi.py | 10 +- ipaserver/plugins/ra.py | 2 +- ipaserver/rpcserver.py | 2 +- ipaserver/servercore.py | 32 +- tests/test_ipalib/test_backend.py | 10 +- tests/test_ipalib/test_error2.py | 371 ---------- tests/test_ipalib/test_errors.py | 371 ++++++++++ tests/test_ipalib/test_frontend.py | 14 +- tests/test_ipalib/test_parameters.py | 20 +- tests/test_ipalib/test_plugable.py | 12 +- tests/test_ipalib/test_rpc.py | 6 +- tests/test_ipaserver/test_rpcserver.py | 2 +- tests/test_xmlrpc/test_automount_plugin.py | 18 +- tests/test_xmlrpc/test_group_plugin.py | 10 +- tests/test_xmlrpc/test_host_plugin.py | 4 +- tests/test_xmlrpc/test_hostgroup_plugin.py | 6 +- tests/test_xmlrpc/test_netgroup_plugin.py | 12 +- tests/test_xmlrpc/test_rolegroup_plugin.py | 6 +- tests/test_xmlrpc/test_service_plugin.py | 10 +- tests/test_xmlrpc/test_taskgroup_plugin.py | 8 +- tests/test_xmlrpc/test_user_plugin.py | 6 +- tests/test_xmlrpc/xmlrpc_test.py | 6 +- 48 files changed, 1677 insertions(+), 1677 deletions(-) create mode 100644 ipalib/errors.py delete mode 100644 ipalib/errors2.py delete mode 100644 tests/test_ipalib/test_error2.py create mode 100644 tests/test_ipalib/test_errors.py diff --git a/install/tools/ipa-compat-manage b/install/tools/ipa-compat-manage index 8c707e5b0..15ff88fac 100755 --- a/install/tools/ipa-compat-manage +++ b/install/tools/ipa-compat-manage @@ -26,7 +26,7 @@ try: from ipapython import entity, ipautil, config from ipaserver.install import installutils from ipaserver.install.ldapupdate import LDAPUpdate, BadSyntax, UPDATES_DIR - from ipalib import errors2 + from ipalib import errors import ldap import logging import re @@ -110,7 +110,7 @@ def main(): ldap.SCOPE_BASE, "(objectclass=*)") print "Plugin already Enabled" retval = 2 - except errors2.NotFound: + except errors.NotFound: print "Enabling plugin" except ldap.LDAPError, e: print "An error occurred while talking to the server." @@ -132,7 +132,7 @@ def main(): conn.deleteEntry("cn=groups,cn=Schema Compatibility,cn=plugins,cn=config") conn.deleteEntry("cn=users,cn=Schema Compatibility,cn=plugins,cn=config") conn.deleteEntry("cn=Schema Compatibility,cn=plugins,cn=config") - except errors2.NotFound: + except errors.NotFound: print "Plugin is already disabled" retval = 2 except ldap.LDAPError, e: diff --git a/ipalib/__init__.py b/ipalib/__init__.py index b2fc1f857..a657ea974 100644 --- a/ipalib/__init__.py +++ b/ipalib/__init__.py @@ -878,7 +878,7 @@ from frontend import Object, Method, Property from crud import Create, Retrieve, Update, Delete, Search from parameters import DefaultFrom, Bool, Flag, Int, Float, Bytes, Str, Password,List from parameters import BytesEnum, StrEnum -from errors2 import SkipPluginModule +from errors import SkipPluginModule try: import uuid diff --git a/ipalib/backend.py b/ipalib/backend.py index 7bd9a29f8..03dae1ced 100644 --- a/ipalib/backend.py +++ b/ipalib/backend.py @@ -23,7 +23,7 @@ Base classes for all backed-end plugins. import threading import plugable -from errors2 import PublicError, InternalError, CommandError +from errors import PublicError, InternalError, CommandError from request import context, Connection, destroy_context diff --git a/ipalib/cli.py b/ipalib/cli.py index 6a1a6d0ff..4949a9b9f 100644 --- a/ipalib/cli.py +++ b/ipalib/cli.py @@ -36,7 +36,7 @@ import frontend import backend import plugable import util -from errors2 import PublicError, CommandError, HelpError, InternalError, NoSuchNamespaceError, ValidationError +from errors import PublicError, CommandError, HelpError, InternalError, NoSuchNamespaceError, ValidationError from constants import CLI_TAB from parameters import Password, Bytes from request import ugettext as _ diff --git a/ipalib/errors.py b/ipalib/errors.py new file mode 100644 index 000000000..f626f359d --- /dev/null +++ b/ipalib/errors.py @@ -0,0 +1,1077 @@ +# Authors: +# Jason Gerard DeRose +# +# Copyright (C) 2008 Red Hat +# see file 'COPYING' for use and warranty inmsgion +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; version 2 only +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +""" +Custom exception classes (some which are RPC transparent). + +`PrivateError` and its subclasses are custom IPA excetions that will *never* be +forwarded in a Remote Procedure Call (RPC) response. + +On the other hand, `PublicError` and its subclasses can be forwarded in an RPC +response. These public errors each carry a unique integer error code as well as +a gettext translated error message (translated at the time the exception is +raised). The purpose of the public errors is to relay information about +*expected* user errors, service availability errors, and so on. They should +*never* be used for *unexpected* programmatic or run-time errors. + +For security reasons it is *extremely* important that arbitrary exceptions *not* +be forwarded in an RPC response. Unexpected exceptions can easily contain +compromising information in their error messages. Any time the server catches +any exception that isn't a `PublicError` subclass, it should raise an +`InternalError`, which itself always has the same, static error message (and +therefore cannot be populated with information about the true exception). + +The public errors are arranging into five main blocks of error code ranges: + + ============= ======================================== + Error codes Exceptions + ============= ======================================== + 1000 - 1999 `AuthenticationError` and its subclasses + 2000 - 2999 `AuthorizationError` and its subclasses + 3000 - 3999 `InvocationError` and its subclasses + 4000 - 4999 `ExecutionError` and its subclasses + 5000 - 5999 `GenericError` and its subclasses + ============= ======================================== + +Within these five blocks some sub-ranges are already allocated for certain types +of error messages, while others are reserved for future use. Here are the +current block assignments: + + - **900-5999** `PublicError` and its subclasses + + - **901 - 907** Assigned to special top-level public errors + + - **908 - 999** *Reserved for future use* + + - **1000 - 1999** `AuthenticationError` and its subclasses + + - **1001 - 1099** Open for general authentication errors + + - **1100 - 1199** `KerberosError` and its subclasses + + - **1200 - 1999** *Reserved for future use* + + - **2000 - 2999** `AuthorizationError` and its subclasses + + - **2001 - 2099** Open for general authorization errors + + - **2100 - 2199** `ACIError` and its subclasses + + - **2200 - 2999** *Reserved for future use* + + - **3000 - 3999** `InvocationError` and its subclasses + + - **3001 - 3099** Open for general invocation errors + + - **3100 - 3199** *Reserved for future use* + + - **4000 - 4999** `ExecutionError` and its subclasses + + - **4001 - 4099** Open for general execution errors + + - **4100 - 4199** `BuiltinError` and its subclasses + + - **4200 - 4299** `LDAPError` and its subclasses + + - **4300 - 4999** *Reserved for future use* + + - **5000 - 5999** `GenericError` and its subclasses + + - **5001 - 5099** Open for generic errors + + - **5100 - 5999** *Reserved for future use* +""" + +from inspect import isclass +from request import ugettext, ungettext +from constants import TYPE_ERROR + + +class PrivateError(StandardError): + """ + Base class for exceptions that are *never* forwarded in an RPC response. + """ + + format = '' + + def __init__(self, **kw): + self.message = self.format % kw + for (key, value) in kw.iteritems(): + assert not hasattr(self, key), 'conflicting kwarg %s.%s = %r' % ( + self.__class__.__name__, key, value, + ) + setattr(self, key, value) + StandardError.__init__(self, self.message) + + +class SubprocessError(PrivateError): + """ + Raised when ``subprocess.call()`` returns a non-zero exit status. + + This custom exception is needed because Python 2.4 doesn't have the + ``subprocess.CalledProcessError`` exception (which was added in Python 2.5). + + For example: + + >>> raise SubprocessError(returncode=2, argv=('ls', '-lh', '/no-foo/')) + Traceback (most recent call last): + ... + SubprocessError: return code 2 from ('ls', '-lh', '/no-foo/') + + The exit code of the sub-process is available via the ``returncode`` + instance attribute. For example: + + >>> e = SubprocessError(returncode=1, argv=('/bin/false',)) + >>> e.returncode + 1 + >>> e.argv # argv is also available + ('/bin/false',) + """ + + format = 'return code %(returncode)d from %(argv)r' + + +class PluginSubclassError(PrivateError): + """ + Raised when a plugin doesn't subclass from an allowed base. + + For example: + + >>> raise PluginSubclassError(plugin='bad', bases=('base1', 'base2')) + Traceback (most recent call last): + ... + PluginSubclassError: 'bad' not subclass of any base in ('base1', 'base2') + + """ + + format = '%(plugin)r not subclass of any base in %(bases)r' + + +class PluginDuplicateError(PrivateError): + """ + Raised when the same plugin class is registered more than once. + + For example: + + >>> raise PluginDuplicateError(plugin='my_plugin') + Traceback (most recent call last): + ... + PluginDuplicateError: 'my_plugin' was already registered + """ + + format = '%(plugin)r was already registered' + + +class PluginOverrideError(PrivateError): + """ + Raised when a plugin overrides another without using ``override=True``. + + For example: + + >>> raise PluginOverrideError(base='Command', name='env', plugin='my_env') + Traceback (most recent call last): + ... + PluginOverrideError: unexpected override of Command.env with 'my_env' + """ + + format = 'unexpected override of %(base)s.%(name)s with %(plugin)r' + + +class PluginMissingOverrideError(PrivateError): + """ + Raised when a plugin overrides another that has not been registered. + + For example: + + >>> raise PluginMissingOverrideError(base='Command', name='env', plugin='my_env') + Traceback (most recent call last): + ... + PluginMissingOverrideError: Command.env not registered, cannot override with 'my_env' + """ + + format = '%(base)s.%(name)s not registered, cannot override with %(plugin)r' + + +class SkipPluginModule(PrivateError): + """ + Raised to abort the loading of a plugin module. + """ + + format = '%(reason)s' + + +class PluginsPackageError(PrivateError): + """ + Raised when ``package.plugins`` is a module instead of a sub-package. + """ + + format = '%(name)s must be sub-package, not module: %(file)r' + + +############################################################################## +# Public errors: + +__messages = [] + +def _(message): + __messages.append(message) + return message + + +class PublicError(StandardError): + """ + **900** Base class for exceptions that can be forwarded in an RPC response. + """ + + errno = 900 + format = None + + def __init__(self, format=None, message=None, **kw): + name = self.__class__.__name__ + if self.format is not None and format is not None: + raise ValueError( + 'non-generic %r needs format=None; got format=%r' % ( + name, format) + ) + if message is None: + if self.format is None: + if format is None: + raise ValueError( + '%s.format is None yet format=None, message=None' % name + ) + self.format = format + self.forwarded = False + self.message = self.format % kw + self.strerror = ugettext(self.format) % kw + else: + if type(message) is not unicode: + raise TypeError( + TYPE_ERROR % ('message', unicode, message, type(message)) + ) + self.forwarded = True + self.message = message + self.strerror = message + for (key, value) in kw.iteritems(): + assert not hasattr(self, key), 'conflicting kwarg %s.%s = %r' % ( + name, key, value, + ) + setattr(self, key, value) + StandardError.__init__(self, self.message) + + +class VersionError(PublicError): + """ + **901** Raised when client and server versions are incompatible. + + For example: + + >>> raise VersionError(cver='2.0', sver='2.1', server='https://localhost') + Traceback (most recent call last): + ... + VersionError: 2.0 client incompatible with 2.1 server at 'https://localhost' + + """ + + errno = 901 + format = _('%(cver)s client incompatible with %(sver)s server at %(server)r') + + +class UnknownError(PublicError): + """ + **902** Raised when client does not know error it caught from server. + + For example: + + >>> raise UnknownError(code=57, server='localhost', error=u'a new error') + ... + Traceback (most recent call last): + ... + UnknownError: unknown error 57 from localhost: a new error + + """ + + errno = 902 + format = _('unknown error %(code)d from %(server)s: %(error)s') + + +class InternalError(PublicError): + """ + **903** Raised to conceal a non-public exception. + + For example: + + >>> raise InternalError() + Traceback (most recent call last): + ... + InternalError: an internal error has occured + """ + + errno = 903 + format = _('an internal error has occured') + + def __init__(self, message=None): + """ + Security issue: ignore any information given to constructor. + """ + PublicError.__init__(self) + + +class ServerInternalError(PublicError): + """ + **904** Raised when client catches an `InternalError` from server. + + For example: + + >>> raise ServerInternalError(server='https://localhost') + Traceback (most recent call last): + ... + ServerInternalError: an internal error has occured on server at 'https://localhost' + """ + + errno = 904 + format = _('an internal error has occured on server at %(server)r') + + +class CommandError(PublicError): + """ + **905** Raised when an unknown command is called. + + For example: + + >>> raise CommandError(name='foobar') + Traceback (most recent call last): + ... + CommandError: unknown command 'foobar' + """ + + errno = 905 + format = _('unknown command %(name)r') + + +class ServerCommandError(PublicError): + """ + **906** Raised when client catches a `CommandError` from server. + + For example: + + >>> e = CommandError(name='foobar') + >>> raise ServerCommandError(error=e.message, server='https://localhost') + Traceback (most recent call last): + ... + ServerCommandError: error on server 'https://localhost': unknown command 'foobar' + """ + + errno = 906 + format = _('error on server %(server)r: %(error)s') + + +class NetworkError(PublicError): + """ + **907** Raised when a network connection cannot be created. + + For example: + + >>> raise NetworkError(uri='ldap://localhost:389', error='Connection refused') + Traceback (most recent call last): + ... + NetworkError: cannot connect to 'ldap://localhost:389': Connection refused + """ + + errno = 907 + format = _('cannot connect to %(uri)r: %(error)s') + + +class ServerNetworkError(PublicError): + """ + **908** Raised when client catches a `NetworkError` from server. + """ + + errno = 908 + format = _('error on server %(server)r: %(error)s') + + + +############################################################################## +# 1000 - 1999: Authentication errors +class AuthenticationError(PublicError): + """ + **1000** Base class for authentication errors (*1000 - 1999*). + """ + + errno = 1000 + + +class KerberosError(AuthenticationError): + """ + **1100** Base class for Kerberos authentication errors (*1100 - 1199*). + """ + + errno = 1100 + + +class CCacheError(KerberosError): + """ + **1101** Raised when sever does not recieve Kerberose credentials. + + For example: + + >>> raise CCacheError() + Traceback (most recent call last): + ... + CCacheError: did not receive Kerberos credentials + + """ + + errno = 1101 + format = _('did not receive Kerberos credentials') + + +class ServiceError(KerberosError): + """ + **1102** Raised when service is not found in Kerberos DB. + + For example: + + >>> raise ServiceError(service='HTTP@localhost') + Traceback (most recent call last): + ... + ServiceError: Service 'HTTP@localhost' not found in Kerberos database + """ + + errno = 1102 + format = _('Service %(service)r not found in Kerberos database') + + +class NoCCacheError(KerberosError): + """ + **1103** Raised when a client attempts to use Kerberos without a ccache. + + For example: + + >>> raise NoCCacheError() + Traceback (most recent call last): + ... + NoCCacheError: No credentials cache found + """ + + errno = 1103 + format = _('No credentials cache found') + + +class TicketExpired(KerberosError): + """ + **1104** Raised when a client attempts to use an expired ticket + + For example: + + >>> raise TicketExpired() + Traceback (most recent call last): + ... + TicketExpired: Ticket expired + """ + + errno = 1104 + format = _('Ticket expired') + + +class BadCCachePerms(KerberosError): + """ + **1105** Raised when a client has bad permissions on their ccache + + For example: + + >>> raise BadCCachePerms() + Traceback (most recent call last): + ... + BadCCachePerms: Credentials cache permissions incorrect + """ + + errno = 1105 + format = _('Credentials cache permissions incorrect') + + +class BadCCacheFormat(KerberosError): + """ + **1106** Raised when a client has a misformated ccache + + For example: + + >>> raise BadCCacheFormat() + Traceback (most recent call last): + ... + BadCCacheFormat: Bad format in credentials cache + """ + + errno = 1106 + format = _('Bad format in credentials cache') + + +class CannotResolveKDC(KerberosError): + """ + **1107** Raised when the KDC can't be resolved + + For example: + + >>> raise CannotResolveKDC() + Traceback (most recent call last): + ... + CannotResolveKDC: Cannot resolve KDC for requested realm + """ + + errno = 1107 + format = _('Cannot resolve KDC for requested realm') + + +############################################################################## +# 2000 - 2999: Authorization errors +class AuthorizationError(PublicError): + """ + **2000** Base class for authorization errors (*2000 - 2999*). + """ + + errno = 2000 + + +class ACIError(AuthorizationError): + """ + **2100** Base class for ACI authorization errors (*2100 - 2199*). + """ + + errno = 2100 + format = _('Insufficient access: %(info)r') + + + +############################################################################## +# 3000 - 3999: Invocation errors + +class InvocationError(PublicError): + """ + **3000** Base class for command invocation errors (*3000 - 3999*). + """ + + errno = 3000 + + +class EncodingError(InvocationError): + """ + **3001** Raised when received text is incorrectly encoded. + """ + + errno = 3001 + + +class BinaryEncodingError(InvocationError): + """ + **3002** Raised when received binary data is incorrectly encoded. + """ + + errno = 3002 + + +class ZeroArgumentError(InvocationError): + """ + **3003** Raised when a command is called with arguments but takes none. + + For example: + + >>> raise ZeroArgumentError(name='ping') + Traceback (most recent call last): + ... + ZeroArgumentError: command 'ping' takes no arguments + """ + + errno = 3003 + format = _('command %(name)r takes no arguments') + + +class MaxArgumentError(InvocationError): + """ + **3004** Raised when a command is called with too many arguments. + + For example: + + >>> raise MaxArgumentError(name='user_add', count=2) + Traceback (most recent call last): + ... + MaxArgumentError: command 'user_add' takes at most 2 arguments + """ + + errno = 3004 + + def __init__(self, message=None, **kw): + if message is None: + format = ungettext( + 'command %(name)r takes at most %(count)d argument', + 'command %(name)r takes at most %(count)d arguments', + kw['count'] + ) + else: + format = None + InvocationError.__init__(self, format, message, **kw) + + +class OptionError(InvocationError): + """ + **3005** Raised when a command is called with unknown options. + """ + + errno = 3005 + + +class OverlapError(InvocationError): + """ + **3006** Raised when arguments and options overlap. + + For example: + + >>> raise OverlapError(names=['givenname', 'login']) + Traceback (most recent call last): + ... + OverlapError: overlapping arguments and options: ['givenname', 'login'] + """ + + errno = 3006 + format = _('overlapping arguments and options: %(names)r') + + +class RequirementError(InvocationError): + """ + **3007** Raised when a required parameter is not provided. + + For example: + + >>> raise RequirementError(name='givenname') + Traceback (most recent call last): + ... + RequirementError: 'givenname' is required + """ + + errno = 3007 + format = _('%(name)r is required') + + +class ConversionError(InvocationError): + """ + **3008** Raised when parameter value can't be converted to correct type. + + For example: + + >>> raise ConversionError(name='age', error='must be an integer') + Traceback (most recent call last): + ... + ConversionError: invalid 'age': must be an integer + """ + + errno = 3008 + format = _('invalid %(name)r: %(error)s') + + +class ValidationError(InvocationError): + """ + **3009** Raised when a parameter value fails a validation rule. + + For example: + + >>> raise ValidationError(name='sn', error='can be at most 128 characters') + Traceback (most recent call last): + ... + ValidationError: invalid 'sn': can be at most 128 characters + """ + + errno = 3009 + format = _('invalid %(name)r: %(error)s') + + +class NoSuchNamespaceError(InvocationError): + """ + **3010** Raised when an unknown namespace is requested. + + For example: + + >>> raise NoSuchNamespaceError(name='Plugins') + Traceback (most recent call last): + ... + NoSuchNamespaceError: api has no such namespace: Plugins + """ + + errno = 3010 + format = _('api has no such namespace: %(name)r') + + +############################################################################## +# 4000 - 4999: Execution errors + +class ExecutionError(PublicError): + """ + **4000** Base class for execution errors (*4000 - 4999*). + """ + + errno = 4000 + +class NotFound(ExecutionError): + """ + **4001** Raised when an entry is not found. + + For example: + + >>> raise NotFound() + Traceback (most recent call last): + ... + NotFound: entry not found + + """ + + errno = 4001 + format = _('entry not found') + +class DuplicateEntry(ExecutionError): + """ + **4002** Raised when an entry already exists. + + For example: + + >>> raise DuplicateEntry + Traceback (most recent call last): + ... + DuplicateEntry: This entry already exists + + """ + + errno = 4002 + format = _('This entry already exists') + +class HostService(ExecutionError): + """ + **4003** Raised when a host service principal is requested + + For example: + + >>> raise HostService + Traceback (most recent call last): + ... + HostService: You must enroll a host in order to create a host service + + """ + + errno = 4003 + format = _('You must enroll a host in order to create a host service') + +class MalformedServicePrincipal(ExecutionError): + """ + **4004** Raised when a service principal is not of the form: service/fully-qualified host name + + For example: + + >>> raise MalformedServicePrincipal + Traceback (most recent call last): + ... + MalformedServicePrincipal: Service principal is not of the form: service/fully-qualified host name + + """ + + errno = 4004 + format = _('Service principal is not of the form: service/fully-qualified host name') + +class RealmMismatch(ExecutionError): + """ + **4005** Raised when the requested realm does not match the IPA realm + + For example: + + >>> raise RealmMismatch + Traceback (most recent call last): + ... + RealmMismatch: The realm for the principal does not match the realm for this IPA server + + """ + + errno = 4005 + format = _('The realm for the principal does not match the realm for this IPA server') + +class RequiresRoot(ExecutionError): + """ + **4006** Raised when a command requires the unix super-user to run + + For example: + + >>> raise RequiresRoot + Traceback (most recent call last): + ... + RequiresRoot: This command requires root access + + """ + + errno = 4006 + format = _('This command requires root access') + +class AlreadyPosixGroup(ExecutionError): + """ + **4007** Raised when a group is already a posix group + + For example: + + >>> raise AlreadyPosixGroup + Traceback (most recent call last): + ... + AlreadyPosixGroup: This is already a posix group + + """ + + errno = 4007 + format = _('This is already a posix group') + +class MalformedUserPrincipal(ExecutionError): + """ + **4008** Raised when a user principal is not of the form: user@REALM + + For example: + + >>> raise MalformedUserPrincipal(principal=jsmith@@EXAMPLE.COM) + Traceback (most recent call last): + ... + MalformedUserPrincipal: Principal is not of the form user@REALM: jsmith@@EXAMPLE.COM + + """ + + errno = 4008 + format = _('Principal is not of the form user@REALM: %(principal)r') + +class AlreadyActive(ExecutionError): + """ + **4009** Raised when an entry is made active that is already active + + For example: + + >>> raise AlreadyActive() + Traceback (most recent call last): + ... + AlreadyActive: This entry is already unlocked + + """ + + errno = 4009 + format = _('This entry is already unlocked') + +class AlreadyInactive(ExecutionError): + """ + **4010** Raised when an entry is made inactive that is already inactive + + For example: + + >>> raise AlreadyInactive() + Traceback (most recent call last): + ... + AlreadyInactive: This entry is already locked + + """ + + errno = 4010 + format = _('This entry is already locked') + +class HasNSAccountLock(ExecutionError): + """ + **4011** Raised when an entry has the nsAccountLock attribute set + + For example: + + >>> raise HasNSAccountLock() + Traceback (most recent call last): + ... + HasNSAccountLock: This entry has nsAccountLock set, it cannot be locked or unlocked + + """ + + errno = 4011 + format = _('This entry has nsAccountLock set, it cannot be locked or unlocked') + +class NotGroupMember(ExecutionError): + """ + **4012** Raised when a non-member is attempted to be removed from a group + + For example: + + >>> raise NotGroupMember() + Traceback (most recent call last): + ... + NotGroupMember: This entry is not a member of the group + + """ + + errno = 4012 + format = _('This entry is not a member of the group') + +class RecursiveGroup(ExecutionError): + """ + **4013** Raised when a group is added as a member of itself + + For example: + + >>> raise RecursiveGroup() + Traceback (most recent call last): + ... + RecursiveGroup: A group may not be a member of itself + + """ + + errno = 4013 + format = _('A group may not be a member of itself') + +class AlreadyGroupMember(ExecutionError): + """ + **4014** Raised when a member is attempted to be re-added to a group + + For example: + + >>> raise AlreadyGroupMember() + Traceback (most recent call last): + ... + AlreadyGroupMember: This entry is already a member of the group + + """ + + errno = 4014 + format = _('This entry is already a member of the group') + +class BuiltinError(ExecutionError): + """ + **4100** Base class for builtin execution errors (*4100 - 4199*). + """ + + errno = 4100 + + +class HelpError(BuiltinError): + """ + **4101** Raised when requesting help for an unknown topic. + + For example: + + >>> raise HelpError(topic='newfeature') + Traceback (most recent call last): + ... + HelpError: no command nor help topic 'newfeature' + """ + + errno = 4101 + format = _('no command nor help topic %(topic)r') + + +class LDAPError(ExecutionError): + """ + **4200** Base class for LDAP execution errors (*4200 - 4299*). + """ + + errno = 4200 + + +class MidairCollision(ExecutionError): + """ + **4201** Raised when a change collides with another change + + For example: + + >>> raise MidairCollision() + Traceback (most recent call last): + ... + MidairCollision: change collided with another change + """ + + errno = 4201 + format = _('change collided with another change') + + +class EmptyModlist(ExecutionError): + """ + **4202** Raised when an LDAP update makes no changes + + For example: + + >>> raise EmptyModlist() + Traceback (most recent call last): + ... + EmptyModlist: no modifications to be performed + """ + + errno = 4202 + format = _('no modifications to be performed') + + +class DatabaseError(ExecutionError): + """ + **4203** Raised when an LDAP error is not otherwise handled + + For example: + + >>> raise DatabaseError(desc="Can't contact LDAP server", info="") + Traceback (most recent call last): + ... + DatabaseError: Can't contact LDAP server: + """ + + errno = 4203 + format = _('%(desc)r:%(info)r') + + +class LimitsExceeded(ExecutionError): + """ + **4204** Raised when search limits are exceeded. + + For example: + + >>> raise LimitsExceeded() + Traceback (most recent call last): + ... + LimitsExceeded: limits exceeded for this query + """ + + errno = 4204 + format = _('limits exceeded for this query') + + +############################################################################## +# 5000 - 5999: Generic errors + +class GenericError(PublicError): + """ + **5000** Base class for errors that don't fit elsewhere (*5000 - 5999*). + """ + + errno = 5000 + + + +def __errors_iter(): + """ + Iterate through all the `PublicError` subclasses. + """ + for (key, value) in globals().items(): + if key.startswith('_') or not isclass(value): + continue + if issubclass(value, PublicError): + yield value + +public_errors = tuple( + sorted(__errors_iter(), key=lambda E: E.errno) +) + +if __name__ == '__main__': + for klass in public_errors: + print '%d\t%s' % (klass.code, klass.__name__) + print '(%d public errors)' % len(public_errors) diff --git a/ipalib/errors2.py b/ipalib/errors2.py deleted file mode 100644 index f626f359d..000000000 --- a/ipalib/errors2.py +++ /dev/null @@ -1,1077 +0,0 @@ -# Authors: -# Jason Gerard DeRose -# -# Copyright (C) 2008 Red Hat -# see file 'COPYING' for use and warranty inmsgion -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as -# published by the Free Software Foundation; version 2 only -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -""" -Custom exception classes (some which are RPC transparent). - -`PrivateError` and its subclasses are custom IPA excetions that will *never* be -forwarded in a Remote Procedure Call (RPC) response. - -On the other hand, `PublicError` and its subclasses can be forwarded in an RPC -response. These public errors each carry a unique integer error code as well as -a gettext translated error message (translated at the time the exception is -raised). The purpose of the public errors is to relay information about -*expected* user errors, service availability errors, and so on. They should -*never* be used for *unexpected* programmatic or run-time errors. - -For security reasons it is *extremely* important that arbitrary exceptions *not* -be forwarded in an RPC response. Unexpected exceptions can easily contain -compromising information in their error messages. Any time the server catches -any exception that isn't a `PublicError` subclass, it should raise an -`InternalError`, which itself always has the same, static error message (and -therefore cannot be populated with information about the true exception). - -The public errors are arranging into five main blocks of error code ranges: - - ============= ======================================== - Error codes Exceptions - ============= ======================================== - 1000 - 1999 `AuthenticationError` and its subclasses - 2000 - 2999 `AuthorizationError` and its subclasses - 3000 - 3999 `InvocationError` and its subclasses - 4000 - 4999 `ExecutionError` and its subclasses - 5000 - 5999 `GenericError` and its subclasses - ============= ======================================== - -Within these five blocks some sub-ranges are already allocated for certain types -of error messages, while others are reserved for future use. Here are the -current block assignments: - - - **900-5999** `PublicError` and its subclasses - - - **901 - 907** Assigned to special top-level public errors - - - **908 - 999** *Reserved for future use* - - - **1000 - 1999** `AuthenticationError` and its subclasses - - - **1001 - 1099** Open for general authentication errors - - - **1100 - 1199** `KerberosError` and its subclasses - - - **1200 - 1999** *Reserved for future use* - - - **2000 - 2999** `AuthorizationError` and its subclasses - - - **2001 - 2099** Open for general authorization errors - - - **2100 - 2199** `ACIError` and its subclasses - - - **2200 - 2999** *Reserved for future use* - - - **3000 - 3999** `InvocationError` and its subclasses - - - **3001 - 3099** Open for general invocation errors - - - **3100 - 3199** *Reserved for future use* - - - **4000 - 4999** `ExecutionError` and its subclasses - - - **4001 - 4099** Open for general execution errors - - - **4100 - 4199** `BuiltinError` and its subclasses - - - **4200 - 4299** `LDAPError` and its subclasses - - - **4300 - 4999** *Reserved for future use* - - - **5000 - 5999** `GenericError` and its subclasses - - - **5001 - 5099** Open for generic errors - - - **5100 - 5999** *Reserved for future use* -""" - -from inspect import isclass -from request import ugettext, ungettext -from constants import TYPE_ERROR - - -class PrivateError(StandardError): - """ - Base class for exceptions that are *never* forwarded in an RPC response. - """ - - format = '' - - def __init__(self, **kw): - self.message = self.format % kw - for (key, value) in kw.iteritems(): - assert not hasattr(self, key), 'conflicting kwarg %s.%s = %r' % ( - self.__class__.__name__, key, value, - ) - setattr(self, key, value) - StandardError.__init__(self, self.message) - - -class SubprocessError(PrivateError): - """ - Raised when ``subprocess.call()`` returns a non-zero exit status. - - This custom exception is needed because Python 2.4 doesn't have the - ``subprocess.CalledProcessError`` exception (which was added in Python 2.5). - - For example: - - >>> raise SubprocessError(returncode=2, argv=('ls', '-lh', '/no-foo/')) - Traceback (most recent call last): - ... - SubprocessError: return code 2 from ('ls', '-lh', '/no-foo/') - - The exit code of the sub-process is available via the ``returncode`` - instance attribute. For example: - - >>> e = SubprocessError(returncode=1, argv=('/bin/false',)) - >>> e.returncode - 1 - >>> e.argv # argv is also available - ('/bin/false',) - """ - - format = 'return code %(returncode)d from %(argv)r' - - -class PluginSubclassError(PrivateError): - """ - Raised when a plugin doesn't subclass from an allowed base. - - For example: - - >>> raise PluginSubclassError(plugin='bad', bases=('base1', 'base2')) - Traceback (most recent call last): - ... - PluginSubclassError: 'bad' not subclass of any base in ('base1', 'base2') - - """ - - format = '%(plugin)r not subclass of any base in %(bases)r' - - -class PluginDuplicateError(PrivateError): - """ - Raised when the same plugin class is registered more than once. - - For example: - - >>> raise PluginDuplicateError(plugin='my_plugin') - Traceback (most recent call last): - ... - PluginDuplicateError: 'my_plugin' was already registered - """ - - format = '%(plugin)r was already registered' - - -class PluginOverrideError(PrivateError): - """ - Raised when a plugin overrides another without using ``override=True``. - - For example: - - >>> raise PluginOverrideError(base='Command', name='env', plugin='my_env') - Traceback (most recent call last): - ... - PluginOverrideError: unexpected override of Command.env with 'my_env' - """ - - format = 'unexpected override of %(base)s.%(name)s with %(plugin)r' - - -class PluginMissingOverrideError(PrivateError): - """ - Raised when a plugin overrides another that has not been registered. - - For example: - - >>> raise PluginMissingOverrideError(base='Command', name='env', plugin='my_env') - Traceback (most recent call last): - ... - PluginMissingOverrideError: Command.env not registered, cannot override with 'my_env' - """ - - format = '%(base)s.%(name)s not registered, cannot override with %(plugin)r' - - -class SkipPluginModule(PrivateError): - """ - Raised to abort the loading of a plugin module. - """ - - format = '%(reason)s' - - -class PluginsPackageError(PrivateError): - """ - Raised when ``package.plugins`` is a module instead of a sub-package. - """ - - format = '%(name)s must be sub-package, not module: %(file)r' - - -############################################################################## -# Public errors: - -__messages = [] - -def _(message): - __messages.append(message) - return message - - -class PublicError(StandardError): - """ - **900** Base class for exceptions that can be forwarded in an RPC response. - """ - - errno = 900 - format = None - - def __init__(self, format=None, message=None, **kw): - name = self.__class__.__name__ - if self.format is not None and format is not None: - raise ValueError( - 'non-generic %r needs format=None; got format=%r' % ( - name, format) - ) - if message is None: - if self.format is None: - if format is None: - raise ValueError( - '%s.format is None yet format=None, message=None' % name - ) - self.format = format - self.forwarded = False - self.message = self.format % kw - self.strerror = ugettext(self.format) % kw - else: - if type(message) is not unicode: - raise TypeError( - TYPE_ERROR % ('message', unicode, message, type(message)) - ) - self.forwarded = True - self.message = message - self.strerror = message - for (key, value) in kw.iteritems(): - assert not hasattr(self, key), 'conflicting kwarg %s.%s = %r' % ( - name, key, value, - ) - setattr(self, key, value) - StandardError.__init__(self, self.message) - - -class VersionError(PublicError): - """ - **901** Raised when client and server versions are incompatible. - - For example: - - >>> raise VersionError(cver='2.0', sver='2.1', server='https://localhost') - Traceback (most recent call last): - ... - VersionError: 2.0 client incompatible with 2.1 server at 'https://localhost' - - """ - - errno = 901 - format = _('%(cver)s client incompatible with %(sver)s server at %(server)r') - - -class UnknownError(PublicError): - """ - **902** Raised when client does not know error it caught from server. - - For example: - - >>> raise UnknownError(code=57, server='localhost', error=u'a new error') - ... - Traceback (most recent call last): - ... - UnknownError: unknown error 57 from localhost: a new error - - """ - - errno = 902 - format = _('unknown error %(code)d from %(server)s: %(error)s') - - -class InternalError(PublicError): - """ - **903** Raised to conceal a non-public exception. - - For example: - - >>> raise InternalError() - Traceback (most recent call last): - ... - InternalError: an internal error has occured - """ - - errno = 903 - format = _('an internal error has occured') - - def __init__(self, message=None): - """ - Security issue: ignore any information given to constructor. - """ - PublicError.__init__(self) - - -class ServerInternalError(PublicError): - """ - **904** Raised when client catches an `InternalError` from server. - - For example: - - >>> raise ServerInternalError(server='https://localhost') - Traceback (most recent call last): - ... - ServerInternalError: an internal error has occured on server at 'https://localhost' - """ - - errno = 904 - format = _('an internal error has occured on server at %(server)r') - - -class CommandError(PublicError): - """ - **905** Raised when an unknown command is called. - - For example: - - >>> raise CommandError(name='foobar') - Traceback (most recent call last): - ... - CommandError: unknown command 'foobar' - """ - - errno = 905 - format = _('unknown command %(name)r') - - -class ServerCommandError(PublicError): - """ - **906** Raised when client catches a `CommandError` from server. - - For example: - - >>> e = CommandError(name='foobar') - >>> raise ServerCommandError(error=e.message, server='https://localhost') - Traceback (most recent call last): - ... - ServerCommandError: error on server 'https://localhost': unknown command 'foobar' - """ - - errno = 906 - format = _('error on server %(server)r: %(error)s') - - -class NetworkError(PublicError): - """ - **907** Raised when a network connection cannot be created. - - For example: - - >>> raise NetworkError(uri='ldap://localhost:389', error='Connection refused') - Traceback (most recent call last): - ... - NetworkError: cannot connect to 'ldap://localhost:389': Connection refused - """ - - errno = 907 - format = _('cannot connect to %(uri)r: %(error)s') - - -class ServerNetworkError(PublicError): - """ - **908** Raised when client catches a `NetworkError` from server. - """ - - errno = 908 - format = _('error on server %(server)r: %(error)s') - - - -############################################################################## -# 1000 - 1999: Authentication errors -class AuthenticationError(PublicError): - """ - **1000** Base class for authentication errors (*1000 - 1999*). - """ - - errno = 1000 - - -class KerberosError(AuthenticationError): - """ - **1100** Base class for Kerberos authentication errors (*1100 - 1199*). - """ - - errno = 1100 - - -class CCacheError(KerberosError): - """ - **1101** Raised when sever does not recieve Kerberose credentials. - - For example: - - >>> raise CCacheError() - Traceback (most recent call last): - ... - CCacheError: did not receive Kerberos credentials - - """ - - errno = 1101 - format = _('did not receive Kerberos credentials') - - -class ServiceError(KerberosError): - """ - **1102** Raised when service is not found in Kerberos DB. - - For example: - - >>> raise ServiceError(service='HTTP@localhost') - Traceback (most recent call last): - ... - ServiceError: Service 'HTTP@localhost' not found in Kerberos database - """ - - errno = 1102 - format = _('Service %(service)r not found in Kerberos database') - - -class NoCCacheError(KerberosError): - """ - **1103** Raised when a client attempts to use Kerberos without a ccache. - - For example: - - >>> raise NoCCacheError() - Traceback (most recent call last): - ... - NoCCacheError: No credentials cache found - """ - - errno = 1103 - format = _('No credentials cache found') - - -class TicketExpired(KerberosError): - """ - **1104** Raised when a client attempts to use an expired ticket - - For example: - - >>> raise TicketExpired() - Traceback (most recent call last): - ... - TicketExpired: Ticket expired - """ - - errno = 1104 - format = _('Ticket expired') - - -class BadCCachePerms(KerberosError): - """ - **1105** Raised when a client has bad permissions on their ccache - - For example: - - >>> raise BadCCachePerms() - Traceback (most recent call last): - ... - BadCCachePerms: Credentials cache permissions incorrect - """ - - errno = 1105 - format = _('Credentials cache permissions incorrect') - - -class BadCCacheFormat(KerberosError): - """ - **1106** Raised when a client has a misformated ccache - - For example: - - >>> raise BadCCacheFormat() - Traceback (most recent call last): - ... - BadCCacheFormat: Bad format in credentials cache - """ - - errno = 1106 - format = _('Bad format in credentials cache') - - -class CannotResolveKDC(KerberosError): - """ - **1107** Raised when the KDC can't be resolved - - For example: - - >>> raise CannotResolveKDC() - Traceback (most recent call last): - ... - CannotResolveKDC: Cannot resolve KDC for requested realm - """ - - errno = 1107 - format = _('Cannot resolve KDC for requested realm') - - -############################################################################## -# 2000 - 2999: Authorization errors -class AuthorizationError(PublicError): - """ - **2000** Base class for authorization errors (*2000 - 2999*). - """ - - errno = 2000 - - -class ACIError(AuthorizationError): - """ - **2100** Base class for ACI authorization errors (*2100 - 2199*). - """ - - errno = 2100 - format = _('Insufficient access: %(info)r') - - - -############################################################################## -# 3000 - 3999: Invocation errors - -class InvocationError(PublicError): - """ - **3000** Base class for command invocation errors (*3000 - 3999*). - """ - - errno = 3000 - - -class EncodingError(InvocationError): - """ - **3001** Raised when received text is incorrectly encoded. - """ - - errno = 3001 - - -class BinaryEncodingError(InvocationError): - """ - **3002** Raised when received binary data is incorrectly encoded. - """ - - errno = 3002 - - -class ZeroArgumentError(InvocationError): - """ - **3003** Raised when a command is called with arguments but takes none. - - For example: - - >>> raise ZeroArgumentError(name='ping') - Traceback (most recent call last): - ... - ZeroArgumentError: command 'ping' takes no arguments - """ - - errno = 3003 - format = _('command %(name)r takes no arguments') - - -class MaxArgumentError(InvocationError): - """ - **3004** Raised when a command is called with too many arguments. - - For example: - - >>> raise MaxArgumentError(name='user_add', count=2) - Traceback (most recent call last): - ... - MaxArgumentError: command 'user_add' takes at most 2 arguments - """ - - errno = 3004 - - def __init__(self, message=None, **kw): - if message is None: - format = ungettext( - 'command %(name)r takes at most %(count)d argument', - 'command %(name)r takes at most %(count)d arguments', - kw['count'] - ) - else: - format = None - InvocationError.__init__(self, format, message, **kw) - - -class OptionError(InvocationError): - """ - **3005** Raised when a command is called with unknown options. - """ - - errno = 3005 - - -class OverlapError(InvocationError): - """ - **3006** Raised when arguments and options overlap. - - For example: - - >>> raise OverlapError(names=['givenname', 'login']) - Traceback (most recent call last): - ... - OverlapError: overlapping arguments and options: ['givenname', 'login'] - """ - - errno = 3006 - format = _('overlapping arguments and options: %(names)r') - - -class RequirementError(InvocationError): - """ - **3007** Raised when a required parameter is not provided. - - For example: - - >>> raise RequirementError(name='givenname') - Traceback (most recent call last): - ... - RequirementError: 'givenname' is required - """ - - errno = 3007 - format = _('%(name)r is required') - - -class ConversionError(InvocationError): - """ - **3008** Raised when parameter value can't be converted to correct type. - - For example: - - >>> raise ConversionError(name='age', error='must be an integer') - Traceback (most recent call last): - ... - ConversionError: invalid 'age': must be an integer - """ - - errno = 3008 - format = _('invalid %(name)r: %(error)s') - - -class ValidationError(InvocationError): - """ - **3009** Raised when a parameter value fails a validation rule. - - For example: - - >>> raise ValidationError(name='sn', error='can be at most 128 characters') - Traceback (most recent call last): - ... - ValidationError: invalid 'sn': can be at most 128 characters - """ - - errno = 3009 - format = _('invalid %(name)r: %(error)s') - - -class NoSuchNamespaceError(InvocationError): - """ - **3010** Raised when an unknown namespace is requested. - - For example: - - >>> raise NoSuchNamespaceError(name='Plugins') - Traceback (most recent call last): - ... - NoSuchNamespaceError: api has no such namespace: Plugins - """ - - errno = 3010 - format = _('api has no such namespace: %(name)r') - - -############################################################################## -# 4000 - 4999: Execution errors - -class ExecutionError(PublicError): - """ - **4000** Base class for execution errors (*4000 - 4999*). - """ - - errno = 4000 - -class NotFound(ExecutionError): - """ - **4001** Raised when an entry is not found. - - For example: - - >>> raise NotFound() - Traceback (most recent call last): - ... - NotFound: entry not found - - """ - - errno = 4001 - format = _('entry not found') - -class DuplicateEntry(ExecutionError): - """ - **4002** Raised when an entry already exists. - - For example: - - >>> raise DuplicateEntry - Traceback (most recent call last): - ... - DuplicateEntry: This entry already exists - - """ - - errno = 4002 - format = _('This entry already exists') - -class HostService(ExecutionError): - """ - **4003** Raised when a host service principal is requested - - For example: - - >>> raise HostService - Traceback (most recent call last): - ... - HostService: You must enroll a host in order to create a host service - - """ - - errno = 4003 - format = _('You must enroll a host in order to create a host service') - -class MalformedServicePrincipal(ExecutionError): - """ - **4004** Raised when a service principal is not of the form: service/fully-qualified host name - - For example: - - >>> raise MalformedServicePrincipal - Traceback (most recent call last): - ... - MalformedServicePrincipal: Service principal is not of the form: service/fully-qualified host name - - """ - - errno = 4004 - format = _('Service principal is not of the form: service/fully-qualified host name') - -class RealmMismatch(ExecutionError): - """ - **4005** Raised when the requested realm does not match the IPA realm - - For example: - - >>> raise RealmMismatch - Traceback (most recent call last): - ... - RealmMismatch: The realm for the principal does not match the realm for this IPA server - - """ - - errno = 4005 - format = _('The realm for the principal does not match the realm for this IPA server') - -class RequiresRoot(ExecutionError): - """ - **4006** Raised when a command requires the unix super-user to run - - For example: - - >>> raise RequiresRoot - Traceback (most recent call last): - ... - RequiresRoot: This command requires root access - - """ - - errno = 4006 - format = _('This command requires root access') - -class AlreadyPosixGroup(ExecutionError): - """ - **4007** Raised when a group is already a posix group - - For example: - - >>> raise AlreadyPosixGroup - Traceback (most recent call last): - ... - AlreadyPosixGroup: This is already a posix group - - """ - - errno = 4007 - format = _('This is already a posix group') - -class MalformedUserPrincipal(ExecutionError): - """ - **4008** Raised when a user principal is not of the form: user@REALM - - For example: - - >>> raise MalformedUserPrincipal(principal=jsmith@@EXAMPLE.COM) - Traceback (most recent call last): - ... - MalformedUserPrincipal: Principal is not of the form user@REALM: jsmith@@EXAMPLE.COM - - """ - - errno = 4008 - format = _('Principal is not of the form user@REALM: %(principal)r') - -class AlreadyActive(ExecutionError): - """ - **4009** Raised when an entry is made active that is already active - - For example: - - >>> raise AlreadyActive() - Traceback (most recent call last): - ... - AlreadyActive: This entry is already unlocked - - """ - - errno = 4009 - format = _('This entry is already unlocked') - -class AlreadyInactive(ExecutionError): - """ - **4010** Raised when an entry is made inactive that is already inactive - - For example: - - >>> raise AlreadyInactive() - Traceback (most recent call last): - ... - AlreadyInactive: This entry is already locked - - """ - - errno = 4010 - format = _('This entry is already locked') - -class HasNSAccountLock(ExecutionError): - """ - **4011** Raised when an entry has the nsAccountLock attribute set - - For example: - - >>> raise HasNSAccountLock() - Traceback (most recent call last): - ... - HasNSAccountLock: This entry has nsAccountLock set, it cannot be locked or unlocked - - """ - - errno = 4011 - format = _('This entry has nsAccountLock set, it cannot be locked or unlocked') - -class NotGroupMember(ExecutionError): - """ - **4012** Raised when a non-member is attempted to be removed from a group - - For example: - - >>> raise NotGroupMember() - Traceback (most recent call last): - ... - NotGroupMember: This entry is not a member of the group - - """ - - errno = 4012 - format = _('This entry is not a member of the group') - -class RecursiveGroup(ExecutionError): - """ - **4013** Raised when a group is added as a member of itself - - For example: - - >>> raise RecursiveGroup() - Traceback (most recent call last): - ... - RecursiveGroup: A group may not be a member of itself - - """ - - errno = 4013 - format = _('A group may not be a member of itself') - -class AlreadyGroupMember(ExecutionError): - """ - **4014** Raised when a member is attempted to be re-added to a group - - For example: - - >>> raise AlreadyGroupMember() - Traceback (most recent call last): - ... - AlreadyGroupMember: This entry is already a member of the group - - """ - - errno = 4014 - format = _('This entry is already a member of the group') - -class BuiltinError(ExecutionError): - """ - **4100** Base class for builtin execution errors (*4100 - 4199*). - """ - - errno = 4100 - - -class HelpError(BuiltinError): - """ - **4101** Raised when requesting help for an unknown topic. - - For example: - - >>> raise HelpError(topic='newfeature') - Traceback (most recent call last): - ... - HelpError: no command nor help topic 'newfeature' - """ - - errno = 4101 - format = _('no command nor help topic %(topic)r') - - -class LDAPError(ExecutionError): - """ - **4200** Base class for LDAP execution errors (*4200 - 4299*). - """ - - errno = 4200 - - -class MidairCollision(ExecutionError): - """ - **4201** Raised when a change collides with another change - - For example: - - >>> raise MidairCollision() - Traceback (most recent call last): - ... - MidairCollision: change collided with another change - """ - - errno = 4201 - format = _('change collided with another change') - - -class EmptyModlist(ExecutionError): - """ - **4202** Raised when an LDAP update makes no changes - - For example: - - >>> raise EmptyModlist() - Traceback (most recent call last): - ... - EmptyModlist: no modifications to be performed - """ - - errno = 4202 - format = _('no modifications to be performed') - - -class DatabaseError(ExecutionError): - """ - **4203** Raised when an LDAP error is not otherwise handled - - For example: - - >>> raise DatabaseError(desc="Can't contact LDAP server", info="") - Traceback (most recent call last): - ... - DatabaseError: Can't contact LDAP server: - """ - - errno = 4203 - format = _('%(desc)r:%(info)r') - - -class LimitsExceeded(ExecutionError): - """ - **4204** Raised when search limits are exceeded. - - For example: - - >>> raise LimitsExceeded() - Traceback (most recent call last): - ... - LimitsExceeded: limits exceeded for this query - """ - - errno = 4204 - format = _('limits exceeded for this query') - - -############################################################################## -# 5000 - 5999: Generic errors - -class GenericError(PublicError): - """ - **5000** Base class for errors that don't fit elsewhere (*5000 - 5999*). - """ - - errno = 5000 - - - -def __errors_iter(): - """ - Iterate through all the `PublicError` subclasses. - """ - for (key, value) in globals().items(): - if key.startswith('_') or not isclass(value): - continue - if issubclass(value, PublicError): - yield value - -public_errors = tuple( - sorted(__errors_iter(), key=lambda E: E.errno) -) - -if __name__ == '__main__': - for klass in public_errors: - print '%d\t%s' % (klass.code, klass.__name__) - print '(%d public errors)' % len(public_errors) diff --git a/ipalib/frontend.py b/ipalib/frontend.py index c2f68d471..aeae24ca0 100644 --- a/ipalib/frontend.py +++ b/ipalib/frontend.py @@ -28,7 +28,7 @@ from plugable import lock, check_name from parameters import create_param, Param, Str, Flag, Password from util import make_repr -from errors2 import ZeroArgumentError, MaxArgumentError, OverlapError +from errors import ZeroArgumentError, MaxArgumentError, OverlapError from constants import TYPE_ERROR @@ -294,7 +294,7 @@ class Command(plugable.Plugin): """ Validate all values. - If any value fails the validation, `ipalib.errors2.ValidationError` + If any value fails the validation, `ipalib.errors.ValidationError` (or a subclass thereof) will be raised. """ for param in self.params(): diff --git a/ipalib/parameters.py b/ipalib/parameters.py index e5f4e8ef1..13fd50b59 100644 --- a/ipalib/parameters.py +++ b/ipalib/parameters.py @@ -34,7 +34,7 @@ from types import NoneType from util import make_repr from request import ugettext from plugable import ReadOnly, lock, check_name -from errors2 import ConversionError, RequirementError, ValidationError +from errors import ConversionError, RequirementError, ValidationError from constants import NULLS, TYPE_ERROR, CALLABLE_ERROR import csv diff --git a/ipalib/plugable.py b/ipalib/plugable.py index 213b59783..c0a4c3567 100644 --- a/ipalib/plugable.py +++ b/ipalib/plugable.py @@ -34,7 +34,7 @@ import os from os import path import subprocess import optparse -import errors2 +import errors from config import Env import util from base import ReadOnly, NameSpace, lock, islocked, check_name @@ -283,7 +283,7 @@ class Plugin(ReadOnly): Call ``executable`` with ``args`` using subprocess.call(). If the call exits with a non-zero exit status, - `ipalib.errors2.SubprocessError` is raised, from which you can retrieve + `ipalib.errors.SubprocessError` is raised, from which you can retrieve the exit code by checking the SubprocessError.returncode attribute. This method does *not* return what ``executable`` sent to stdout... for @@ -293,7 +293,7 @@ class Plugin(ReadOnly): self.debug('Calling %r', argv) code = subprocess.call(argv) if code != 0: - raise errors2.SubprocessError(returncode=code, argv=argv) + raise errors.SubprocessError(returncode=code, argv=argv) def __repr__(self): """ @@ -450,7 +450,7 @@ class Registrar(DictProxy): """ Iterates through allowed bases that ``klass`` is a subclass of. - Raises `errors2.PluginSubclassError` if ``klass`` is not a subclass of + Raises `errors.PluginSubclassError` if ``klass`` is not a subclass of any allowed base. :param klass: The plugin class to find bases for. @@ -462,7 +462,7 @@ class Registrar(DictProxy): found = True yield (base, sub_d) if not found: - raise errors2.PluginSubclassError( + raise errors.PluginSubclassError( plugin=klass, bases=self.__allowed.keys() ) @@ -478,7 +478,7 @@ class Registrar(DictProxy): # Raise DuplicateError if this exact class was already registered: if klass in self.__registered: - raise errors2.PluginDuplicateError(plugin=klass) + raise errors.PluginDuplicateError(plugin=klass) # Find the base class or raise SubclassError: for (base, sub_d) in self.__findbases(klass): @@ -486,7 +486,7 @@ class Registrar(DictProxy): if klass.__name__ in sub_d: if not override: # Must use override=True to override: - raise errors2.PluginOverrideError( + raise errors.PluginOverrideError( base=base.__name__, name=klass.__name__, plugin=klass, @@ -494,7 +494,7 @@ class Registrar(DictProxy): else: if override: # There was nothing already registered to override: - raise errors2.PluginMissingOverrideError( + raise errors.PluginMissingOverrideError( base=base.__name__, name=klass.__name__, plugin=klass, @@ -667,7 +667,7 @@ class API(DictProxy): parent_dir = path.dirname(path.abspath(parent.__file__)) plugins_dir = path.dirname(path.abspath(plugins.__file__)) if parent_dir == plugins_dir: - raise errors2.PluginsPackageError( + raise errors.PluginsPackageError( name=subpackage, file=plugins.__file__ ) self.log.debug('importing all plugin modules in %r...', plugins_dir) @@ -676,7 +676,7 @@ class API(DictProxy): self.log.debug('importing plugin module %r', pyfile) try: __import__(fullname) - except errors2.SkipPluginModule, e: + except errors.SkipPluginModule, e: self.log.info( 'skipping plugin module %s: %s', fullname, e.reason ) diff --git a/ipalib/plugins/aci.py b/ipalib/plugins/aci.py index 6a2a1c2d7..8587e2ae9 100644 --- a/ipalib/plugins/aci.py +++ b/ipalib/plugins/aci.py @@ -21,7 +21,7 @@ Frontend plugins for managing DS ACIs """ -from ipalib import api, crud, errors2 +from ipalib import api, crud, errors from ipalib import Object, Command # Plugin base classes from ipalib import Str, Flag, Int, StrEnum # Parameter types from ipalib.aci import ACI @@ -35,7 +35,7 @@ type_map = { def make_aci(current, aciname, kw): try: taskgroup = api.Command['taskgroup_show'](kw['taskgroup']) - except errors2.NotFound: + except errors.NotFound: # The task group doesn't exist, let's be helpful and add it tgkw = {'description':aciname} taskgroup = api.Command['taskgroup_add'](kw['taskgroup'], **tgkw) @@ -81,7 +81,7 @@ def search_by_name(acis, aciname): # FIXME: need to log syntax errors, ignore for now pass - raise errors2.NotFound() + raise errors.NotFound() def search_by_attr(acis, attrlist): """ @@ -105,7 +105,7 @@ def search_by_attr(acis, attrlist): if results: return results - raise errors2.NotFound() + raise errors.NotFound() def search_by_taskgroup(acis, tgdn): """ @@ -126,7 +126,7 @@ def search_by_taskgroup(acis, tgdn): if results: return results - raise errors2.NotFound() + raise errors.NotFound() def search_by_perm(acis, permlist): """ @@ -148,7 +148,7 @@ def search_by_perm(acis, permlist): if results: return results - raise errors2.NotFound() + raise errors.NotFound() def search_by_memberof(acis, memberoffilter): """ @@ -174,7 +174,7 @@ def search_by_memberof(acis, memberoffilter): if results: return results - raise errors2.NotFound() + raise errors.NotFound() class aci(Object): """ @@ -241,7 +241,7 @@ class aci_add(crud.Create): try: b = ACI(a) if newaci.isequal(b): - raise errors2.DuplicateEntry() + raise errors.DuplicateEntry() except SyntaxError: pass acilist.append(str(newaci)) @@ -318,7 +318,7 @@ class aci_find(crud.Search): results = [a] if kw.get('and'): currentaci = results - except errors2.NotFound: + except errors.NotFound: if kw.get('and'): results = [] currentaci = [] @@ -335,7 +335,7 @@ class aci_find(crud.Search): currentaci = results else: results = results + a - except errors2.NotFound: + except errors.NotFound: if kw.get('and'): results = [] currentaci = [] @@ -345,7 +345,7 @@ class aci_find(crud.Search): if kw.get('taskgroup'): try: tg = api.Command['taskgroup_show'](kw.get('taskgroup')) - except errors2.NotFound: + except errors.NotFound: # FIXME, need more precise error raise try: @@ -355,7 +355,7 @@ class aci_find(crud.Search): currentaci = results else: results = results + a - except errors2.NotFound: + except errors.NotFound: if kw.get('and'): results = [] currentaci = [] @@ -372,7 +372,7 @@ class aci_find(crud.Search): currentaci = results else: results = results + a - except errors2.NotFound: + except errors.NotFound: if kw.get('and'): results = [] currentaci = [] @@ -387,7 +387,7 @@ class aci_find(crud.Search): results = results + a if kw.get('and'): currentaci = results - except errors2.NotFound: + except errors.NotFound: if kw.get('and'): results = [] currentaci = [] diff --git a/ipalib/plugins/automount.py b/ipalib/plugins/automount.py index b4b696d10..6378a1385 100644 --- a/ipalib/plugins/automount.py +++ b/ipalib/plugins/automount.py @@ -86,7 +86,7 @@ automountInformation: -ro,soft,rsize=8192,wsize=8192 nfs.example.com:/vol/arch """ from ldap import explode_dn -from ipalib import crud, errors2 +from ipalib import crud, errors from ipalib import api, Str, Flag, Object, Command map_attributes = ['automountMapName', 'description', ] @@ -251,7 +251,7 @@ class automount_delmap(crud.Del): try: infodn = ldap.find_entry_dn("automountinformation", mapname, "automount", api.env.container_automount) ldap.delete(infodn) - except errors2.NotFound: + except errors.NotFound: # direct maps may not have this pass @@ -291,7 +291,7 @@ class automount_delkey(crud.Del): keydn = k.get('dn') break if not keydn: - raise errors2.NotFound(msg='Entry not found') + raise errors.NotFound(msg='Entry not found') return ldap.delete(keydn) def output_for_cli(self, textui, result, *args, **options): """ @@ -369,7 +369,7 @@ class automount_modkey(crud.Mod): keydn = k.get('dn') break if not keydn: - raise errors2.NotFound(msg='Entry not found') + raise errors.NotFound(msg='Entry not found') return ldap.update(keydn, **kw) def output_for_cli(self, textui, result, *args, **options): @@ -517,7 +517,7 @@ class automount_showkey(crud.Get): keydn = k.get('dn') break if not keydn: - raise errors2.NotFound(msg='Entry not found') + raise errors.NotFound(msg='Entry not found') # FIXME: should kw contain the list of attributes to display? if kw.get('all', False): return ldap.retrieve(keydn) @@ -558,7 +558,7 @@ class automount_getkeys(Command): dn = ldap.find_entry_dn("automountmapname", mapname, "automountmap", api.env.container_automount) try: keys = ldap.get_one_entry(dn, 'objectclass=*', ['*']) - except errors2.NotFound: + except errors.NotFound: keys = [] return keys diff --git a/ipalib/plugins/basegroup.py b/ipalib/plugins/basegroup.py index b93fdc8d9..733a6c384 100644 --- a/ipalib/plugins/basegroup.py +++ b/ipalib/plugins/basegroup.py @@ -21,7 +21,7 @@ Base plugin for groups. """ -from ipalib import api, crud, errors2 +from ipalib import api, crud, errors from ipalib import Object, Command # Plugin base classes from ipalib import Str, Int, Flag, List # Parameter types from ldap.dn import escape_dn_chars @@ -50,7 +50,7 @@ def find_members(ldap, failed, members, attribute, filter=None, base=None): try: member_dn = ldap.find_entry_dn(attribute, m, filter, base) found.append(member_dn) - except errors2.NotFound: + except errors.NotFound: failed.append(m) return found, failed diff --git a/ipalib/plugins/group.py b/ipalib/plugins/group.py index 3bf5221fe..766d1679f 100644 --- a/ipalib/plugins/group.py +++ b/ipalib/plugins/group.py @@ -119,7 +119,7 @@ class group_del(basegroup_del): default_group = ldap.find_entry_dn("cn", config.get('ipadefaultprimarygroup'), self.filter_class) if dn == default_group: raise errors.DefaultGroup - except errors2.NotFound: + except errors.NotFound: pass return super(group_del, self).execute(cn, **kw) @@ -160,7 +160,7 @@ class group_mod(basegroup_mod): groupkw = {'all': True} oldgroup = api.Command['group_show'](cn, **groupkw) if oldgroup.get('gidnumber'): - raise errors2.AlreadyPosixGroup + raise errors.AlreadyPosixGroup else: oldgroup['objectclass'].append('posixgroup') kw['objectclass'] = oldgroup['objectclass'] diff --git a/ipalib/plugins/host.py b/ipalib/plugins/host.py index 13a0254e3..87180733f 100644 --- a/ipalib/plugins/host.py +++ b/ipalib/plugins/host.py @@ -21,7 +21,7 @@ Frontend plugins for host/machine Identity. """ -from ipalib import api, crud, errors2, util +from ipalib import api, crud, errors, util from ipalib import Object # Plugin base class from ipalib import Str, Flag # Parameter types import sys, os, platform @@ -39,7 +39,7 @@ def get_host(hostname): hostname = hostname[:-1] try: dn = ldap.find_entry_dn("cn", hostname, "ipaHost") - except errors2.NotFound: + except errors.NotFound: dn = ldap.find_entry_dn("serverhostname", hostname, "ipaHost") return dn @@ -138,7 +138,7 @@ class host_add(crud.Add): current = util.get_current_principal() if not current: - raise errors2.NotFound('Unable to determine current user') + raise errors.NotFound('Unable to determine current user') kw['enrolledby'] = ldap.find_entry_dn("krbPrincipalName", current, "posixAccount") # Get our configuration diff --git a/ipalib/plugins/join.py b/ipalib/plugins/join.py index 1230d5bcc..d75043fdd 100644 --- a/ipalib/plugins/join.py +++ b/ipalib/plugins/join.py @@ -23,7 +23,7 @@ Machine join from ipalib import api, util from ipalib import Command, Str, Int -from ipalib import errors2 +from ipalib import errors import krbV import os, subprocess @@ -74,10 +74,10 @@ class join(Command): try: host = api.Command['host_show'](hostname) - except errors2.NotFound: + except errors.NotFound: pass else: - raise errors2.DuplicateEntry + raise errors.DuplicateEntry return api.Command['host_add'](hostname) @@ -91,7 +91,7 @@ class join(Command): """ if not self.env.in_server: # if os.getegid() != 0: -# raise errors2.RequiresRoot +# raise errors.RequiresRoot result = self.forward(*args, **options) else: return self.execute(*args, **options) diff --git a/ipalib/plugins/passwd.py b/ipalib/plugins/passwd.py index cc7ab5861..bb6e637a9 100644 --- a/ipalib/plugins/passwd.py +++ b/ipalib/plugins/passwd.py @@ -21,7 +21,7 @@ Frontend plugins for password changes. """ -from ipalib import api, errors2, util +from ipalib import api, errors, util from ipalib import Command # Plugin base classes from ipalib import Str, Password # Parameter types @@ -54,7 +54,7 @@ class passwd(Command): if principal.find('@') > 0: u = principal.split('@') if len(u) > 2: - raise errors2.MalformedUserPrincipal(principal=principal) + raise errors.MalformedUserPrincipal(principal=principal) else: principal = principal+"@"+self.api.env.realm dn = self.Backend.ldap.find_entry_dn( diff --git a/ipalib/plugins/service.py b/ipalib/plugins/service.py index 4c6f5bd80..c9f00deb2 100644 --- a/ipalib/plugins/service.py +++ b/ipalib/plugins/service.py @@ -22,7 +22,7 @@ Frontend plugins for service (Identity). """ -from ipalib import api, crud, errors2 +from ipalib import api, crud, errors from ipalib import Object # Plugin base classes from ipalib import Str, Flag # Parameter types @@ -73,11 +73,11 @@ class service_add(crud.Add): # may not include the realm. sp = principal.split('/') if len(sp) != 2: - raise errors2.MalformedServicePrincipal + raise errors.MalformedServicePrincipal service = sp[0] if service.lower() == "host": - raise errors2.HostService + raise errors.HostService sr = sp[1].split('@') if len(sr) == 1: @@ -87,7 +87,7 @@ class service_add(crud.Add): hostname = sr[0].lower() realm = sr[1] else: - raise errors2.MalformedServicePrincipal + raise errors.MalformedServicePrincipal """ FIXME once DNS client is done @@ -103,7 +103,7 @@ class service_add(crud.Add): # At some point we'll support multiple realms if (realm != self.api.env.realm): - raise errors2.RealmMismatch + raise errors.RealmMismatch # Put the principal back together again princ_name = service + "/" + hostname + "@" + realm diff --git a/ipalib/plugins/user.py b/ipalib/plugins/user.py index e4e1cdaf1..be70e7bee 100644 --- a/ipalib/plugins/user.py +++ b/ipalib/plugins/user.py @@ -21,7 +21,7 @@ Frontend plugins for user (Identity). """ -from ipalib import api, crud, errors2 +from ipalib import api, crud, errors from ipalib import Object, Command # Plugin base classes from ipalib import Str, Password, Flag, Int # Parameter types @@ -158,9 +158,9 @@ class user_add(crud.Create): default_group = ldap.retrieve(group_dn, ['cn', 'dn','gidNumber']) if default_group: kw['gidnumber'] = default_group.get('gidnumber') - except errors2.NotFound: + except errors.NotFound: # Fake an LDAP error so we can return something useful to the kw - raise errors2.NotFound("The default group for new users, '%s', cannot be found." % config.get('ipadefaultprimarygroup')) + raise errors.NotFound("The default group for new users, '%s', cannot be found." % config.get('ipadefaultprimarygroup')) except Exception, e: # catch everything else raise e diff --git a/ipalib/plugins/user2.py b/ipalib/plugins/user2.py index 13bd37f5a..b322aa87d 100644 --- a/ipalib/plugins/user2.py +++ b/ipalib/plugins/user2.py @@ -21,7 +21,7 @@ Users (Identity) """ -from ipalib import api, crud, errors2 +from ipalib import api, crud, errors from ipalib import Command, Object from ipalib import Flag, Int, Password, Str @@ -146,9 +146,9 @@ class user2_create(crud.Create): # try to retrieve the group's gidNumber try: (group_dn, group_attrs) = ldap.get_entry(group_dn, ['gidNumber']) - except errors2.NotFound: + except errors.NotFound: error_msg = 'Default group for new users not found.' - raise errors2.NotFound(error_msg) + raise errors.NotFound(error_msg) # fill default group's gidNumber entry_attrs['gidnumber'] = group_attrs['gidNumber'] @@ -184,7 +184,7 @@ class user2_delete(crud.Delete): if uid == 'admin': # FIXME: add a specific exception for this? - raise errors2.ExecutionError('Cannot delete user "admin".') + raise errors.ExecutionError('Cannot delete user "admin".') # build entry DN rdn = ldap.make_rdn_from_attr('uid', uid) @@ -276,7 +276,7 @@ class user2_find(crud.Search): entries = ldap.find_entries( filter, attrs_list, _container_dn, ldap.SCOPE_ONELEVEL ) - except errors2.NotFound: + except errors.NotFound: entries = tuple() return entries @@ -355,7 +355,7 @@ class user2_lock(Command): # lock! try: ldap.deactivate_entry(dn) - except errors2.AlreadyInactive: + except errors.AlreadyInactive: pass # return something positive @@ -391,7 +391,7 @@ class user2_unlock(Command): # unlock! try: ldap.activate_entry(dn) - except errors2.AlreadyActive: + except errors.AlreadyActive: pass # return something positive diff --git a/ipalib/rpc.py b/ipalib/rpc.py index b0b55ce59..48ac16b5a 100644 --- a/ipalib/rpc.py +++ b/ipalib/rpc.py @@ -38,8 +38,8 @@ import errno from xmlrpclib import Binary, Fault, dumps, loads, ServerProxy, Transport import kerberos from ipalib.backend import Connectible -from ipalib.errors2 import public_errors, PublicError, UnknownError, NetworkError -from ipalib import errors2 +from ipalib.errors import public_errors, PublicError, UnknownError, NetworkError +from ipalib import errors from ipalib.request import context from ipapython import ipautil from OpenSSL import SSL @@ -316,19 +316,19 @@ class KerbTransport(SSLTransport): def _handle_exception(self, e, service=None): (major, minor) = ipautil.get_gsserror(e) if minor[1] == KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN: - raise errors2.ServiceError(service=service) + raise errors.ServiceError(service=service) elif minor[1] == KRB5_FCC_NOFILE: - raise errors2.NoCCacheError() + raise errors.NoCCacheError() elif minor[1] == KRB5KRB_AP_ERR_TKT_EXPIRED: - raise errors2.TicketExpired() + raise errors.TicketExpired() elif minor[1] == KRB5_FCC_PERM: - raise errors2.BadCCachePerms() + raise errors.BadCCachePerms() elif minor[1] == KRB5_CC_FORMAT: - raise errors2.BadCCacheFormat() + raise errors.BadCCacheFormat() elif minor[1] == KRB5_REALM_CANT_RESOLVE: - raise errors2.CannotResolveKDC() + raise errors.CannotResolveKDC() else: - raise errors2.KerberosError(major=major, minor=minor) + raise errors.KerberosError(major=major, minor=minor) def get_host_info(self, host): (host, extra_headers, x509) = SSLTransport.get_host_info(self, host) diff --git a/ipalib/util.py b/ipalib/util.py index 54529b14c..5ea13dc8c 100644 --- a/ipalib/util.py +++ b/ipalib/util.py @@ -28,7 +28,7 @@ import logging import time import krbV import socket -from ipalib import errors2 +from ipalib import errors def get_current_principal(): @@ -36,7 +36,7 @@ def get_current_principal(): return unicode(krbV.default_context().default_ccache().principal().name) except krbV.Krb5Error: #TODO: do a kinit? - raise errors2.CCacheError() + raise errors.CCacheError() def get_fqdn(): fqdn = "" diff --git a/ipaserver/install/krbinstance.py b/ipaserver/install/krbinstance.py index 50df2968c..6a45d3456 100644 --- a/ipaserver/install/krbinstance.py +++ b/ipaserver/install/krbinstance.py @@ -35,7 +35,7 @@ import installutils from ipapython import sysrestore from ipapython import ipautil from ipalib import util -from ipalib import errors2 +from ipalib import errors from ipaserver import ipaldap @@ -322,7 +322,7 @@ class KrbInstance(service.Service): def __write_stash_from_ds(self): try: entry = self.conn.getEntry("cn=%s, cn=kerberos, %s" % (self.realm, self.suffix), ldap.SCOPE_SUBTREE) - except errors2.NotFound: + except errors.NotFound: logging.critical("Could not find master key in DS") raise e diff --git a/ipaserver/install/ldapupdate.py b/ipaserver/install/ldapupdate.py index 17b519b32..ce12607e7 100644 --- a/ipaserver/install/ldapupdate.py +++ b/ipaserver/install/ldapupdate.py @@ -29,7 +29,7 @@ from ipaserver.install import installutils from ipaserver import ipaldap from ipapython import entity, ipautil from ipalib import util -from ipalib import errors2 +from ipalib import errors import ldap import logging import krbV @@ -310,10 +310,10 @@ class LDAPUpdate: while True: try: entry = self.conn.getEntry(dn, ldap.SCOPE_BASE, "(objectclass=*)", attrlist) - except errors2.NotFound, e: + except errors.NotFound, e: logging.error("Task not found: %s", dn) return - except errors2.DatabaseError, e: + except errors.DatabaseError, e: logging.error("Task lookup failure %s", e) return @@ -480,11 +480,11 @@ class LDAPUpdate: entry = self.__entry_to_entity(e[0]) found = True logging.info("Updating existing entry: %s", entry.dn) - except errors2.NotFound: + except errors.NotFound: # Doesn't exist, start with the default entry entry = new_entry logging.info("New entry: %s", entry.dn) - except errors2.DatabaseError: + except errors.DatabaseError: # Doesn't exist, start with the default entry entry = new_entry logging.info("New entry, using default value: %s", entry.dn) @@ -521,10 +521,10 @@ class LDAPUpdate: if self.live_run and updated: self.conn.updateEntry(entry.dn, entry.origDataDict(), entry.toDict()) logging.info("Done") - except errors2.EmptyModlist: + except errors.EmptyModlist: logging.info("Entry already up-to-date") updated = False - except errors2.DatabaseError, e: + except errors.DatabaseError, e: logging.error("Update failed: %s", e) updated = False diff --git a/ipaserver/install/replication.py b/ipaserver/install/replication.py index 12db0eb0c..653ec3c4e 100644 --- a/ipaserver/install/replication.py +++ b/ipaserver/install/replication.py @@ -24,7 +24,7 @@ from ipaserver.install import dsinstance from ipaserver import ipaldap from ldap import modlist from ipalib import util -from ipalib import errors2 +from ipalib import errors DIRMAN_CN = "cn=directory manager" CACERT="/usr/share/ipa/html/ca.crt" @@ -148,7 +148,7 @@ class ReplicationManager: conn.getEntry(dn, ldap.SCOPE_BASE) # replication is already configured return - except errors2.NotFound: + except errors.NotFound: pass replica_type = self.get_replica_type() @@ -220,7 +220,7 @@ class ReplicationManager: try: entry = self.conn.getEntry("cn=mapping tree,cn=config", ldap.SCOPE_ONELEVEL, "(cn=\"%s\")" % (self.suffix)) - except errors2.NotFound, e: + except errors.NotFound, e: logging.debug("failed to find mappting tree entry for %s" % self.suffix) raise e @@ -256,7 +256,7 @@ class ReplicationManager: conn.getEntry(pass_dn, ldap.SCOPE_BASE) print "Windows PassSync entry exists, not resetting password" return - except errors2.NotFound: + except errors.NotFound: pass # The user doesn't exist, add it @@ -315,7 +315,7 @@ class ReplicationManager: try: a.getEntry(dn, ldap.SCOPE_BASE) return - except errors2.NotFound: + except errors.NotFound: pass iswinsync = kargs.get("winsync", False) diff --git a/ipaserver/ipaldap.py b/ipaserver/ipaldap.py index e63fe55b9..7d194aa95 100644 --- a/ipaserver/ipaldap.py +++ b/ipaserver/ipaldap.py @@ -32,7 +32,7 @@ import ldap.sasl from ldap.controls import LDAPControl,DecodeControlTuples,EncodeControlTuples from ldap.ldapobject import SimpleLDAPObject from ipaserver import ipautil -from ipalib import errors2 +from ipalib import errors # Global variable to define SASL auth sasl_auth = ldap.sasl.sasl({},'GSSAPI') @@ -283,30 +283,30 @@ class IPAdmin(SimpleLDAPObject): raise e except ldap.NO_SUCH_OBJECT, e: args = kw.get('args', '') - raise errors2.NotFound(msg=notfound(args)) + raise errors.NotFound(msg=notfound(args)) except ldap.ALREADY_EXISTS, e: - raise errors2.DuplicateEntry() + raise errors.DuplicateEntry() except ldap.CONSTRAINT_VIOLATION, e: # This error gets thrown by the uniqueness plugin if info == 'Another entry with the same attribute value already exists': - raise errors2.DuplicateEntry() + raise errors.DuplicateEntry() else: - raise errors2.DatabaseError(desc=desc,info=info) + raise errors.DatabaseError(desc=desc,info=info) except ldap.INSUFFICIENT_ACCESS, e: - raise errors2.ACIError(info=info) + raise errors.ACIError(info=info) except ldap.NO_SUCH_ATTRIBUTE: # this is raised when a 'delete' attribute isn't found. # it indicates the previous attribute was removed by another # update, making the oldentry stale. - raise errors2.MidairCollision() + raise errors.MidairCollision() except ldap.ADMINLIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except ldap.SIZELIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except ldap.TIMELIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except ldap.LDAPError, e: - raise errors2.DatabaseError(desc=desc,info=info) + raise errors.DatabaseError(desc=desc,info=info) def toLDAPURL(self): return "ldap://%s:%d/" % (self.host,self.port) @@ -345,7 +345,7 @@ class IPAdmin(SimpleLDAPObject): self.__handle_errors(e, **kw) if not obj: - raise errors2.NotFound(msg=notfound(args)) + raise errors.NotFound(msg=notfound(args)) elif isinstance(obj,Entry): return obj @@ -367,7 +367,7 @@ class IPAdmin(SimpleLDAPObject): self.__handle_errors(e, **kw) if not obj: - raise errors2.NotFound(msg=notfound(args)) + raise errors.NotFound(msg=notfound(args)) entries = [] for s in obj: @@ -405,7 +405,7 @@ class IPAdmin(SimpleLDAPObject): self.__handle_errors(e, **kw) if not entries: - raise errors2.NotFound(msg=notfound(args)) + raise errors.NotFound(msg=notfound(args)) if partial == 1: counter = -1 diff --git a/ipaserver/plugins/ldap2.py b/ipaserver/plugins/ldap2.py index c31460856..8b5983aed 100644 --- a/ipaserver/plugins/ldap2.py +++ b/ipaserver/plugins/ldap2.py @@ -45,7 +45,7 @@ from ldap.controls import LDAPControl from ldap.ldapobject import SimpleLDAPObject from ipalib import api -from ipalib import errors2 +from ipalib import errors from ipalib.crud import CrudBackend # attribute syntax to python type mapping, 'SYNTAX OID': type @@ -93,31 +93,31 @@ def _handle_errors(self, e, **kw): raise e except _ldap.NO_SUCH_OBJECT, e: # args = kw.get('args', '') - # raise errors2.NotFound(msg=notfound(args)) - raise errors2.NotFound() + # raise errors.NotFound(msg=notfound(args)) + raise errors.NotFound() except _ldap.ALREADY_EXISTS, e: - raise errors2.DuplicateEntry() + raise errors.DuplicateEntry() except _ldap.CONSTRAINT_VIOLATION, e: # This error gets thrown by the uniqueness plugin if info == 'Another entry with the same attribute value already exists': - raise errors2.DuplicateEntry() + raise errors.DuplicateEntry() else: - raise errors2.DatabaseError(desc=desc, info=info) + raise errors.DatabaseError(desc=desc, info=info) except _ldap.INSUFFICIENT_ACCESS, e: - raise errors2.ACIError(info=info) + raise errors.ACIError(info=info) except _ldap.NO_SUCH_ATTRIBUTE: # this is raised when a 'delete' attribute isn't found. # it indicates the previous attribute was removed by another # update, making the oldentry stale. - raise errors2.MidairCollision() + raise errors.MidairCollision() except _ldap.ADMINLIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except _ldap.SIZELIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except _ldap.TIMELIMIT_EXCEEDED, e: - raise errors2.LimitsExceeded() + raise errors.LimitsExceeded() except _ldap.LDAPError, e: - raise errors2.DatabaseError(desc=desc, info=info) + raise errors.DatabaseError(desc=desc, info=info) # utility function, builds LDAP URL string def _get_url(host, port, using_cacert=False): @@ -458,7 +458,7 @@ class ldap2(CrudBackend): except _ldap.LDAPError, e: _handle_errors(e, **{}) if not res: - raise errors2.NotFound() + raise errors.NotFound() # decode results for i in xrange(len(res)): @@ -553,7 +553,7 @@ class ldap2(CrudBackend): # generate modlist modlist = self._generate_modlist(dn, entry_attrs_copy) if not modlist: - raise errors2.EmptyModlist() + raise errors.EmptyModlist() # pass arguments to python-ldap try: @@ -594,7 +594,7 @@ class ldap2(CrudBackend): group_dn = self.normalize_dn(group_dn) # check if we're not trying to add group into itself if dn == group_dn: - raise errors2.SameGroupError() + raise errors.SameGroupError() # check if the entry exists (dn, entry_attrs) = self.get_entry(dn, ['objectClass']) @@ -609,8 +609,8 @@ class ldap2(CrudBackend): # update group entry try: self.update_entry(group_dn, group_entry_attrs) - except errors2.EmptyModlist: - raise errors2.AlreadyGroupMember() + except errors.EmptyModlist: + raise errors.AlreadyGroupMember() def remove_entry_from_group(self, dn, group_dn, member_attr='member'): """Remove entry from group.""" @@ -625,7 +625,7 @@ class ldap2(CrudBackend): try: members.remove(dn) except ValueError: - raise errors2.NotGroupMember() + raise errors.NotGroupMember() group_entry_attrs[member_attr] = members # update group entry @@ -642,10 +642,10 @@ class ldap2(CrudBackend): account_lock_attr = account_lock_attr[0].lower() if active: if account_lock_attr == 'false': - raise errors2.AlreadyActive() + raise errors.AlreadyActive() else: if account_lock_attr == 'true': - raise errors2.AlreadyInactive() + raise errors.AlreadyInactive() # check if nsAccountLock attribute is in the entry itself is_member = False @@ -655,7 +655,7 @@ class ldap2(CrudBackend): is_member = True break if not is_member and entry_attrs.has_key('nsAccountLock'): - raise errors2.HasNSAccountLock() + raise errors.HasNSAccountLock() activated_filter = '(cn=activated)' inactivated_filter = '(cn=inactivated)' @@ -669,7 +669,7 @@ class ldap2(CrudBackend): (group_dn, group_entry_attrs) = entries[0] try: self.remove_entry_from_group(dn, group_dn) - except errors2.NotGroupMember: + except errors.NotGroupMember: pass # add the entry to the activated/inactivated group if necessary @@ -688,11 +688,11 @@ class ldap2(CrudBackend): (group_dn, group_entry_attrs) = entries[0] try: self.add_entry_to_group(dn, group_dn) - except errors2.EmptyModlist: + except errors.EmptyModlist: if active: - raise errors2.AlreadyActive() + raise errors.AlreadyActive() else: - raise errors2.AlreadyInactive() + raise errors.AlreadyInactive() def activate_entry(self, dn): """Mark entry active.""" diff --git a/ipaserver/plugins/ldapapi.py b/ipaserver/plugins/ldapapi.py index 9eea3eaae..995abe381 100644 --- a/ipaserver/plugins/ldapapi.py +++ b/ipaserver/plugins/ldapapi.py @@ -27,7 +27,7 @@ This wraps the python-ldap bindings. import ldap as _ldap import ldap.dn from ipalib import api -from ipalib import errors2 +from ipalib import errors from ipalib.crud import CrudBackend from ipaserver import servercore, ipaldap import krbV @@ -44,7 +44,7 @@ class ldap(CrudBackend): def create_connection(self, ccache): if ccache is None: - raise errors2.CCacheError() + raise errors.CCacheError() conn = ipaldap.IPAdmin(self.env.ldap_host, self.env.ldap_port) principle = krbV.CCache( name=ccache, context=krbV.default_context() @@ -326,7 +326,7 @@ class ldap(CrudBackend): def create(self, **kw): if servercore.entry_exists(kw['dn']): - raise errors2.DuplicateEntry + raise errors.DuplicateEntry kw = dict(self.strip_none(kw)) entry = ipaldap.Entry(kw['dn']) @@ -409,14 +409,14 @@ class ldap(CrudBackend): try: exact_results = servercore.search(search_base, exact_match_filter, attributes, scope=search_scope) - except errors2.NotFound: + except errors.NotFound: exact_results = [0] if not exactonly: try: partial_results = servercore.search(search_base, partial_match_filter, attributes, scope=search_scope) - except errors2.NotFound: + except errors.NotFound: partial_results = [0] else: partial_results = [0] diff --git a/ipaserver/plugins/ra.py b/ipaserver/plugins/ra.py index 71f7a97c9..de14cbd3a 100644 --- a/ipaserver/plugins/ra.py +++ b/ipaserver/plugins/ra.py @@ -45,7 +45,7 @@ from urllib import urlencode, quote from socket import gethostname import socket from ipalib import Backend -from ipalib.errors2 import NetworkError +from ipalib.errors import NetworkError from ipaserver import servercore from ipaserver import ipaldap from ipalib.constants import TYPE_ERROR diff --git a/ipaserver/rpcserver.py b/ipaserver/rpcserver.py index 2ad233dc1..68d8215f9 100644 --- a/ipaserver/rpcserver.py +++ b/ipaserver/rpcserver.py @@ -25,7 +25,7 @@ Also see the `ipalib.rpc` module. from xmlrpclib import Fault from ipalib.backend import Executioner -from ipalib.errors2 import PublicError, InternalError, CommandError +from ipalib.errors import PublicError, InternalError, CommandError from ipalib.rpc import xml_dumps, xml_loads from ipalib.util import make_repr diff --git a/ipaserver/servercore.py b/ipaserver/servercore.py index ee0e518d2..1e0972d7b 100644 --- a/ipaserver/servercore.py +++ b/ipaserver/servercore.py @@ -23,7 +23,7 @@ import re from ipalib.request import context from ipaserver import ipaldap import ipautil -from ipalib import errors2 +from ipalib import errors from ipalib import api def convert_entry(ent): @@ -186,7 +186,7 @@ def entry_exists(dn): try: get_base_entry(dn, "objectclass=*", ['dn','objectclass']) return True - except errors2.NotFound: + except errors.NotFound: return False def get_user_by_uid (uid, sattrs): @@ -270,7 +270,7 @@ def search(base, filter, attributes, timelimit=1, sizelimit=3000, scope=ldap.SCO results = context.ldap.conn.getListAsync(base, scope, filter, attributes, 0, None, None, timelimit, sizelimit) except ldap.NO_SUCH_OBJECT: - raise errors2.NotFound() + raise errors.NotFound() counter = results[0] entries = [counter] @@ -317,7 +317,7 @@ def get_ipa_config(): config = get_sub_entry("cn=etc," + api.env.basedn, searchfilter) except ldap.NO_SUCH_OBJECT, e: # FIXME - raise errors2.NotFound() + raise errors.NotFound() return config @@ -341,16 +341,16 @@ def mark_entry_active (dn): if entry.get('nsaccountlock', 'false').lower() == "false": api.log.debug("IPA: already active") - raise errors2.AlreadyActive() + raise errors.AlreadyActive() if has_nsaccountlock(dn): api.log.debug("IPA: appears to have the nsaccountlock attribute") - raise errors2.HasNSAccountLock() + raise errors.HasNSAccountLock() group = get_entry_by_cn("inactivated", None) try: remove_member_from_group(entry.get('dn'), group.get('dn')) - except errors2.NotGroupMember: + except errors.NotGroupMember: # Perhaps the user is there as a result of group membership pass @@ -377,18 +377,18 @@ def mark_entry_inactive (dn): if entry.get('nsaccountlock', 'false').lower() == "true": api.log.debug("IPA: already marked as inactive") - raise errors2.AlreadyInactive() + raise errors.AlreadyInactive() if has_nsaccountlock(dn): api.log.debug("IPA: appears to have the nsaccountlock attribute") - raise errors2.HasNSAccountLock() + raise errors.HasNSAccountLock() # First see if they are in the activated group as this will override # the our inactivation. group = get_entry_by_cn("activated", None) try: remove_member_from_group(dn, group.get('dn')) - except errors2.NotGroupMember: + except errors.NotGroupMember: # this is fine, they may not be explicitly in this group pass @@ -405,16 +405,16 @@ def add_member_to_group(member_dn, group_dn, memberattr='member'): api.log.info("IPA: add_member_to_group '%s' to '%s'" % (member_dn, group_dn)) if member_dn.lower() == group_dn.lower(): # You can't add a group to itself - raise errors2.RecursiveGroup() + raise errors.RecursiveGroup() group = get_entry_by_dn(group_dn, None) if group is None: - raise errors2.NotFound() + raise errors.NotFound() # check to make sure member_dn exists member_entry = get_base_entry(member_dn, "(objectClass=*)", ['dn','objectclass']) if not member_entry: - raise errors2.NotFound() + raise errors.NotFound() # Add the new member to the group member attribute members = group.get(memberattr, []) @@ -430,7 +430,7 @@ def remove_member_from_group(member_dn, group_dn, memberattr='member'): group = get_entry_by_dn(group_dn, None) if group is None: - raise errors2.NotFound() + raise errors.NotFound() """ if group.get('cn') == "admins": member = get_entry_by_dn(member_dn, ['dn','uid']) @@ -441,7 +441,7 @@ def remove_member_from_group(member_dn, group_dn, memberattr='member'): members = group.get(memberattr, False) if not members: - raise errors2.NotGroupMember() + raise errors.NotGroupMember() if isinstance(members,basestring): members = [members] @@ -450,7 +450,7 @@ def remove_member_from_group(member_dn, group_dn, memberattr='member'): try: members.remove(member_dn) except ValueError: - raise errors2.NotGroupMember() + raise errors.NotGroupMember() except Exception, e: raise e diff --git a/tests/test_ipalib/test_backend.py b/tests/test_ipalib/test_backend.py index 798e93de8..a7c80f5cb 100644 --- a/tests/test_ipalib/test_backend.py +++ b/tests/test_ipalib/test_backend.py @@ -26,7 +26,7 @@ from tests.util import ClassChecker, raises, create_test_api from tests.data import unicode_str from ipalib.request import context, Connection from ipalib.frontend import Command -from ipalib import backend, plugable, errors2, base +from ipalib import backend, plugable, errors, base @@ -181,7 +181,7 @@ class test_Executioner(ClassChecker): class good(Command): def execute(self): - raise errors2.ValidationError( + raise errors.ValidationError( name='nurse', error=u'Not naughty!', ) @@ -209,7 +209,7 @@ class test_Executioner(ClassChecker): # Test that CommandError is raised: conn = Connection('The connection.', Disconnect()) context.someconn = conn - e = raises(errors2.CommandError, o.execute, 'nope') + e = raises(errors.CommandError, o.execute, 'nope') assert e.name == 'nope' assert conn.disconnect.called is True # Make sure destroy_context() was called assert context.__dict__.keys() == [] @@ -235,7 +235,7 @@ class test_Executioner(ClassChecker): # Test with good command: conn = Connection('The connection.', Disconnect()) context.someconn = conn - e = raises(errors2.ValidationError, o.execute, 'good') + e = raises(errors.ValidationError, o.execute, 'good') assert e.name == 'nurse' assert e.error == u'Not naughty!' assert conn.disconnect.called is True # Make sure destroy_context() was called @@ -244,7 +244,7 @@ class test_Executioner(ClassChecker): # Test with bad command: conn = Connection('The connection.', Disconnect()) context.someconn = conn - e = raises(errors2.InternalError, o.execute, 'bad') + e = raises(errors.InternalError, o.execute, 'bad') assert conn.disconnect.called is True # Make sure destroy_context() was called assert context.__dict__.keys() == [] diff --git a/tests/test_ipalib/test_error2.py b/tests/test_ipalib/test_error2.py deleted file mode 100644 index cd13ba775..000000000 --- a/tests/test_ipalib/test_error2.py +++ /dev/null @@ -1,371 +0,0 @@ -# Authors: -# Jason Gerard DeRose -# -# Copyright (C) 2008 Red Hat -# see file 'COPYING' for use and warranty information -# -# This program is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License as -# published by the Free Software Foundation; version 2 only -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -""" -Test the `ipalib.error2` module. -""" - -import re -import inspect -from tests.util import assert_equal, raises, dummy_ugettext -from ipalib import errors2, request -from ipalib.constants import TYPE_ERROR - - -class PrivateExceptionTester(object): - _klass = None - __klass = None - - def __get_klass(self): - if self.__klass is None: - self.__klass = self._klass - assert issubclass(self.__klass, StandardError) - assert issubclass(self.__klass, errors2.PrivateError) - assert not issubclass(self.__klass, errors2.PublicError) - return self.__klass - klass = property(__get_klass) - - def new(self, **kw): - for (key, value) in kw.iteritems(): - assert not hasattr(self.klass, key), key - inst = self.klass(**kw) - assert isinstance(inst, StandardError) - assert isinstance(inst, errors2.PrivateError) - assert isinstance(inst, self.klass) - assert not isinstance(inst, errors2.PublicError) - for (key, value) in kw.iteritems(): - assert getattr(inst, key) is value - assert str(inst) == self.klass.format % kw - assert inst.message == str(inst) - return inst - - -class test_PrivateError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.PrivateError` exception. - """ - _klass = errors2.PrivateError - - def test_init(self): - """ - Test the `ipalib.errors2.PrivateError.__init__` method. - """ - inst = self.klass(key1='Value 1', key2='Value 2') - assert inst.key1 == 'Value 1' - assert inst.key2 == 'Value 2' - assert str(inst) == '' - - # Test subclass and use of format: - class subclass(self.klass): - format = '%(true)r %(text)r %(number)r' - - kw = dict(true=True, text='Hello!', number=18) - inst = subclass(**kw) - assert inst.true is True - assert inst.text is kw['text'] - assert inst.number is kw['number'] - assert str(inst) == subclass.format % kw - - # Test via PrivateExceptionTester.new() - inst = self.new(**kw) - assert isinstance(inst, self.klass) - assert inst.true is True - assert inst.text is kw['text'] - assert inst.number is kw['number'] - - -class test_SubprocessError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.SubprocessError` exception. - """ - - _klass = errors2.SubprocessError - - def test_init(self): - """ - Test the `ipalib.errors2.SubprocessError.__init__` method. - """ - inst = self.new(returncode=1, argv=('/bin/false',)) - assert inst.returncode == 1 - assert inst.argv == ('/bin/false',) - assert str(inst) == "return code 1 from ('/bin/false',)" - assert inst.message == str(inst) - - -class test_PluginSubclassError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.PluginSubclassError` exception. - """ - - _klass = errors2.PluginSubclassError - - def test_init(self): - """ - Test the `ipalib.errors2.PluginSubclassError.__init__` method. - """ - inst = self.new(plugin='bad', bases=('base1', 'base2')) - assert inst.plugin == 'bad' - assert inst.bases == ('base1', 'base2') - assert str(inst) == \ - "'bad' not subclass of any base in ('base1', 'base2')" - assert inst.message == str(inst) - - -class test_PluginDuplicateError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.PluginDuplicateError` exception. - """ - - _klass = errors2.PluginDuplicateError - - def test_init(self): - """ - Test the `ipalib.errors2.PluginDuplicateError.__init__` method. - """ - inst = self.new(plugin='my_plugin') - assert inst.plugin == 'my_plugin' - assert str(inst) == "'my_plugin' was already registered" - assert inst.message == str(inst) - - -class test_PluginOverrideError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.PluginOverrideError` exception. - """ - - _klass = errors2.PluginOverrideError - - def test_init(self): - """ - Test the `ipalib.errors2.PluginOverrideError.__init__` method. - """ - inst = self.new(base='Base', name='cmd', plugin='my_cmd') - assert inst.base == 'Base' - assert inst.name == 'cmd' - assert inst.plugin == 'my_cmd' - assert str(inst) == "unexpected override of Base.cmd with 'my_cmd'" - assert inst.message == str(inst) - - -class test_PluginMissingOverrideError(PrivateExceptionTester): - """ - Test the `ipalib.errors2.PluginMissingOverrideError` exception. - """ - - _klass = errors2.PluginMissingOverrideError - - def test_init(self): - """ - Test the `ipalib.errors2.PluginMissingOverrideError.__init__` method. - """ - inst = self.new(base='Base', name='cmd', plugin='my_cmd') - assert inst.base == 'Base' - assert inst.name == 'cmd' - assert inst.plugin == 'my_cmd' - assert str(inst) == "Base.cmd not registered, cannot override with 'my_cmd'" - assert inst.message == str(inst) - - - -############################################################################## -# Unit tests for public errors: - -class PublicExceptionTester(object): - _klass = None - __klass = None - - def __get_klass(self): - if self.__klass is None: - self.__klass = self._klass - assert issubclass(self.__klass, StandardError) - assert issubclass(self.__klass, errors2.PublicError) - assert not issubclass(self.__klass, errors2.PrivateError) - assert type(self.__klass.errno) is int - assert 900 <= self.__klass.errno <= 5999 - return self.__klass - klass = property(__get_klass) - - def new(self, format=None, message=None, **kw): - # Test that TypeError is raised if message isn't unicode: - e = raises(TypeError, self.klass, message='The message') - assert str(e) == TYPE_ERROR % ('message', unicode, 'The message', str) - - # Test the instance: - for (key, value) in kw.iteritems(): - assert not hasattr(self.klass, key), key - inst = self.klass(format=format, message=message, **kw) - assert isinstance(inst, StandardError) - assert isinstance(inst, errors2.PublicError) - assert isinstance(inst, self.klass) - assert not isinstance(inst, errors2.PrivateError) - for (key, value) in kw.iteritems(): - assert getattr(inst, key) is value - return inst - - -class test_PublicError(PublicExceptionTester): - """ - Test the `ipalib.errors2.PublicError` exception. - """ - _klass = errors2.PublicError - - def test_init(self): - """ - Test the `ipalib.errors2.PublicError.__init__` method. - """ - context = request.context - message = u'The translated, interpolated message' - format = 'key=%(key1)r and key2=%(key2)r' - uformat = u'Translated key=%(key1)r and key2=%(key2)r' - val1 = 'Value 1' - val2 = 'Value 2' - kw = dict(key1=val1, key2=val2) - - assert not hasattr(context, 'ugettext') - - # Test with format=str, message=None - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - inst = self.klass(format, **kw) - assert dummy.message is format # Means ugettext() called - assert inst.format is format - assert_equal(inst.message, format % kw) - assert_equal(inst.strerror, uformat % kw) - assert inst.forwarded is False - assert inst.key1 is val1 - assert inst.key2 is val2 - - # Test with format=None, message=unicode - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - inst = self.klass(message=message, **kw) - assert not hasattr(dummy, 'message') # Means ugettext() not called - assert inst.format is None - assert inst.message is message - assert inst.strerror is message - assert inst.forwarded is True - assert inst.key1 is val1 - assert inst.key2 is val2 - - # Test with format=None, message=str - e = raises(TypeError, self.klass, message='the message', **kw) - assert str(e) == TYPE_ERROR % ('message', unicode, 'the message', str) - - # Test with format=None, message=None - e = raises(ValueError, self.klass, **kw) - assert str(e) == \ - 'PublicError.format is None yet format=None, message=None' - - - ###################################### - # Test via PublicExceptionTester.new() - - # Test with format=str, message=None - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - inst = self.new(format, **kw) - assert isinstance(inst, self.klass) - assert dummy.message is format # Means ugettext() called - assert inst.format is format - assert_equal(inst.message, format % kw) - assert_equal(inst.strerror, uformat % kw) - assert inst.forwarded is False - assert inst.key1 is val1 - assert inst.key2 is val2 - - # Test with format=None, message=unicode - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - inst = self.new(message=message, **kw) - assert isinstance(inst, self.klass) - assert not hasattr(dummy, 'message') # Means ugettext() not called - assert inst.format is None - assert inst.message is message - assert inst.strerror is message - assert inst.forwarded is True - assert inst.key1 is val1 - assert inst.key2 is val2 - - - ################## - # Test a subclass: - class subclass(self.klass): - format = '%(true)r %(text)r %(number)r' - - uformat = u'Translated %(true)r %(text)r %(number)r' - kw = dict(true=True, text='Hello!', number=18) - - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - - # Test with format=str, message=None - e = raises(ValueError, subclass, format, **kw) - assert str(e) == 'non-generic %r needs format=None; got format=%r' % ( - 'subclass', format) - - # Test with format=None, message=None: - inst = subclass(**kw) - assert dummy.message is subclass.format # Means ugettext() called - assert inst.format is subclass.format - assert_equal(inst.message, subclass.format % kw) - assert_equal(inst.strerror, uformat % kw) - assert inst.forwarded is False - assert inst.true is True - assert inst.text is kw['text'] - assert inst.number is kw['number'] - - # Test with format=None, message=unicode: - dummy = dummy_ugettext(uformat) - context.ugettext = dummy - inst = subclass(message=message, **kw) - assert not hasattr(dummy, 'message') # Means ugettext() not called - assert inst.format is subclass.format - assert inst.message is message - assert inst.strerror is message - assert inst.forwarded is True - assert inst.true is True - assert inst.text is kw['text'] - assert inst.number is kw['number'] - del context.ugettext - - -def test_public_errors(): - """ - Test the `ipalib.errors2.public_errors` module variable. - """ - i = 0 - for klass in errors2.public_errors: - assert issubclass(klass, StandardError) - assert issubclass(klass, errors2.PublicError) - assert not issubclass(klass, errors2.PrivateError) - assert type(klass.errno) is int - assert 900 <= klass.errno <= 5999 - doc = inspect.getdoc(klass) - assert doc is not None, 'need class docstring for %s' % klass.__name__ - m = re.match(r'^\*{2}(\d+)\*{2} ', doc) - assert m is not None, "need '**ERRNO**' in %s docstring" % klass.__name__ - errno = int(m.group(1)) - assert errno == klass.errno, ( - 'docstring=%r but errno=%r in %s' % (errno, klass.errno, klass.__name__) - ) - - # Test format - if klass.format is not None: - assert klass.format is errors2.__messages[i] - i += 1 diff --git a/tests/test_ipalib/test_errors.py b/tests/test_ipalib/test_errors.py new file mode 100644 index 000000000..2e2ed3e7a --- /dev/null +++ b/tests/test_ipalib/test_errors.py @@ -0,0 +1,371 @@ +# Authors: +# Jason Gerard DeRose +# +# Copyright (C) 2008 Red Hat +# see file 'COPYING' for use and warranty information +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License as +# published by the Free Software Foundation; version 2 only +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +""" +Test the `ipalib.errors` module. +""" + +import re +import inspect +from tests.util import assert_equal, raises, dummy_ugettext +from ipalib import errors, request +from ipalib.constants import TYPE_ERROR + + +class PrivateExceptionTester(object): + _klass = None + __klass = None + + def __get_klass(self): + if self.__klass is None: + self.__klass = self._klass + assert issubclass(self.__klass, StandardError) + assert issubclass(self.__klass, errors.PrivateError) + assert not issubclass(self.__klass, errors.PublicError) + return self.__klass + klass = property(__get_klass) + + def new(self, **kw): + for (key, value) in kw.iteritems(): + assert not hasattr(self.klass, key), key + inst = self.klass(**kw) + assert isinstance(inst, StandardError) + assert isinstance(inst, errors.PrivateError) + assert isinstance(inst, self.klass) + assert not isinstance(inst, errors.PublicError) + for (key, value) in kw.iteritems(): + assert getattr(inst, key) is value + assert str(inst) == self.klass.format % kw + assert inst.message == str(inst) + return inst + + +class test_PrivateError(PrivateExceptionTester): + """ + Test the `ipalib.errors.PrivateError` exception. + """ + _klass = errors.PrivateError + + def test_init(self): + """ + Test the `ipalib.errors.PrivateError.__init__` method. + """ + inst = self.klass(key1='Value 1', key2='Value 2') + assert inst.key1 == 'Value 1' + assert inst.key2 == 'Value 2' + assert str(inst) == '' + + # Test subclass and use of format: + class subclass(self.klass): + format = '%(true)r %(text)r %(number)r' + + kw = dict(true=True, text='Hello!', number=18) + inst = subclass(**kw) + assert inst.true is True + assert inst.text is kw['text'] + assert inst.number is kw['number'] + assert str(inst) == subclass.format % kw + + # Test via PrivateExceptionTester.new() + inst = self.new(**kw) + assert isinstance(inst, self.klass) + assert inst.true is True + assert inst.text is kw['text'] + assert inst.number is kw['number'] + + +class test_SubprocessError(PrivateExceptionTester): + """ + Test the `ipalib.errors.SubprocessError` exception. + """ + + _klass = errors.SubprocessError + + def test_init(self): + """ + Test the `ipalib.errors.SubprocessError.__init__` method. + """ + inst = self.new(returncode=1, argv=('/bin/false',)) + assert inst.returncode == 1 + assert inst.argv == ('/bin/false',) + assert str(inst) == "return code 1 from ('/bin/false',)" + assert inst.message == str(inst) + + +class test_PluginSubclassError(PrivateExceptionTester): + """ + Test the `ipalib.errors.PluginSubclassError` exception. + """ + + _klass = errors.PluginSubclassError + + def test_init(self): + """ + Test the `ipalib.errors.PluginSubclassError.__init__` method. + """ + inst = self.new(plugin='bad', bases=('base1', 'base2')) + assert inst.plugin == 'bad' + assert inst.bases == ('base1', 'base2') + assert str(inst) == \ + "'bad' not subclass of any base in ('base1', 'base2')" + assert inst.message == str(inst) + + +class test_PluginDuplicateError(PrivateExceptionTester): + """ + Test the `ipalib.errors.PluginDuplicateError` exception. + """ + + _klass = errors.PluginDuplicateError + + def test_init(self): + """ + Test the `ipalib.errors.PluginDuplicateError.__init__` method. + """ + inst = self.new(plugin='my_plugin') + assert inst.plugin == 'my_plugin' + assert str(inst) == "'my_plugin' was already registered" + assert inst.message == str(inst) + + +class test_PluginOverrideError(PrivateExceptionTester): + """ + Test the `ipalib.errors.PluginOverrideError` exception. + """ + + _klass = errors.PluginOverrideError + + def test_init(self): + """ + Test the `ipalib.errors.PluginOverrideError.__init__` method. + """ + inst = self.new(base='Base', name='cmd', plugin='my_cmd') + assert inst.base == 'Base' + assert inst.name == 'cmd' + assert inst.plugin == 'my_cmd' + assert str(inst) == "unexpected override of Base.cmd with 'my_cmd'" + assert inst.message == str(inst) + + +class test_PluginMissingOverrideError(PrivateExceptionTester): + """ + Test the `ipalib.errors.PluginMissingOverrideError` exception. + """ + + _klass = errors.PluginMissingOverrideError + + def test_init(self): + """ + Test the `ipalib.errors.PluginMissingOverrideError.__init__` method. + """ + inst = self.new(base='Base', name='cmd', plugin='my_cmd') + assert inst.base == 'Base' + assert inst.name == 'cmd' + assert inst.plugin == 'my_cmd' + assert str(inst) == "Base.cmd not registered, cannot override with 'my_cmd'" + assert inst.message == str(inst) + + + +############################################################################## +# Unit tests for public errors: + +class PublicExceptionTester(object): + _klass = None + __klass = None + + def __get_klass(self): + if self.__klass is None: + self.__klass = self._klass + assert issubclass(self.__klass, StandardError) + assert issubclass(self.__klass, errors.PublicError) + assert not issubclass(self.__klass, errors.PrivateError) + assert type(self.__klass.errno) is int + assert 900 <= self.__klass.errno <= 5999 + return self.__klass + klass = property(__get_klass) + + def new(self, format=None, message=None, **kw): + # Test that TypeError is raised if message isn't unicode: + e = raises(TypeError, self.klass, message='The message') + assert str(e) == TYPE_ERROR % ('message', unicode, 'The message', str) + + # Test the instance: + for (key, value) in kw.iteritems(): + assert not hasattr(self.klass, key), key + inst = self.klass(format=format, message=message, **kw) + assert isinstance(inst, StandardError) + assert isinstance(inst, errors.PublicError) + assert isinstance(inst, self.klass) + assert not isinstance(inst, errors.PrivateError) + for (key, value) in kw.iteritems(): + assert getattr(inst, key) is value + return inst + + +class test_PublicError(PublicExceptionTester): + """ + Test the `ipalib.errors.PublicError` exception. + """ + _klass = errors.PublicError + + def test_init(self): + """ + Test the `ipalib.errors.PublicError.__init__` method. + """ + context = request.context + message = u'The translated, interpolated message' + format = 'key=%(key1)r and key2=%(key2)r' + uformat = u'Translated key=%(key1)r and key2=%(key2)r' + val1 = 'Value 1' + val2 = 'Value 2' + kw = dict(key1=val1, key2=val2) + + assert not hasattr(context, 'ugettext') + + # Test with format=str, message=None + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + inst = self.klass(format, **kw) + assert dummy.message is format # Means ugettext() called + assert inst.format is format + assert_equal(inst.message, format % kw) + assert_equal(inst.strerror, uformat % kw) + assert inst.forwarded is False + assert inst.key1 is val1 + assert inst.key2 is val2 + + # Test with format=None, message=unicode + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + inst = self.klass(message=message, **kw) + assert not hasattr(dummy, 'message') # Means ugettext() not called + assert inst.format is None + assert inst.message is message + assert inst.strerror is message + assert inst.forwarded is True + assert inst.key1 is val1 + assert inst.key2 is val2 + + # Test with format=None, message=str + e = raises(TypeError, self.klass, message='the message', **kw) + assert str(e) == TYPE_ERROR % ('message', unicode, 'the message', str) + + # Test with format=None, message=None + e = raises(ValueError, self.klass, **kw) + assert str(e) == \ + 'PublicError.format is None yet format=None, message=None' + + + ###################################### + # Test via PublicExceptionTester.new() + + # Test with format=str, message=None + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + inst = self.new(format, **kw) + assert isinstance(inst, self.klass) + assert dummy.message is format # Means ugettext() called + assert inst.format is format + assert_equal(inst.message, format % kw) + assert_equal(inst.strerror, uformat % kw) + assert inst.forwarded is False + assert inst.key1 is val1 + assert inst.key2 is val2 + + # Test with format=None, message=unicode + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + inst = self.new(message=message, **kw) + assert isinstance(inst, self.klass) + assert not hasattr(dummy, 'message') # Means ugettext() not called + assert inst.format is None + assert inst.message is message + assert inst.strerror is message + assert inst.forwarded is True + assert inst.key1 is val1 + assert inst.key2 is val2 + + + ################## + # Test a subclass: + class subclass(self.klass): + format = '%(true)r %(text)r %(number)r' + + uformat = u'Translated %(true)r %(text)r %(number)r' + kw = dict(true=True, text='Hello!', number=18) + + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + + # Test with format=str, message=None + e = raises(ValueError, subclass, format, **kw) + assert str(e) == 'non-generic %r needs format=None; got format=%r' % ( + 'subclass', format) + + # Test with format=None, message=None: + inst = subclass(**kw) + assert dummy.message is subclass.format # Means ugettext() called + assert inst.format is subclass.format + assert_equal(inst.message, subclass.format % kw) + assert_equal(inst.strerror, uformat % kw) + assert inst.forwarded is False + assert inst.true is True + assert inst.text is kw['text'] + assert inst.number is kw['number'] + + # Test with format=None, message=unicode: + dummy = dummy_ugettext(uformat) + context.ugettext = dummy + inst = subclass(message=message, **kw) + assert not hasattr(dummy, 'message') # Means ugettext() not called + assert inst.format is subclass.format + assert inst.message is message + assert inst.strerror is message + assert inst.forwarded is True + assert inst.true is True + assert inst.text is kw['text'] + assert inst.number is kw['number'] + del context.ugettext + + +def test_public_errors(): + """ + Test the `ipalib.errors.public_errors` module variable. + """ + i = 0 + for klass in errors.public_errors: + assert issubclass(klass, StandardError) + assert issubclass(klass, errors.PublicError) + assert not issubclass(klass, errors.PrivateError) + assert type(klass.errno) is int + assert 900 <= klass.errno <= 5999 + doc = inspect.getdoc(klass) + assert doc is not None, 'need class docstring for %s' % klass.__name__ + m = re.match(r'^\*{2}(\d+)\*{2} ', doc) + assert m is not None, "need '**ERRNO**' in %s docstring" % klass.__name__ + errno = int(m.group(1)) + assert errno == klass.errno, ( + 'docstring=%r but errno=%r in %s' % (errno, klass.errno, klass.__name__) + ) + + # Test format + if klass.format is not None: + assert klass.format is errors.__messages[i] + i += 1 diff --git a/tests/test_ipalib/test_frontend.py b/tests/test_ipalib/test_frontend.py index 744370415..414803954 100644 --- a/tests/test_ipalib/test_frontend.py +++ b/tests/test_ipalib/test_frontend.py @@ -26,7 +26,7 @@ from tests.util import check_TypeError, ClassChecker, create_test_api from tests.util import assert_equal from ipalib.constants import TYPE_ERROR from ipalib.base import NameSpace -from ipalib import frontend, backend, plugable, errors2, parameters, config +from ipalib import frontend, backend, plugable, errors, parameters, config def test_RULE_FLAG(): assert frontend.RULE_FLAG == 'validation_rule' @@ -274,7 +274,7 @@ class test_Command(ClassChecker): # Check with an invalid value fail = dict(okay) fail['option0'] = u'whatever' - e = raises(errors2.ValidationError, sub.validate, **fail) + e = raises(errors.ValidationError, sub.validate, **fail) assert_equal(e.name, 'option0') assert_equal(e.value, u'whatever') assert_equal(e.error, u"must equal 'option0'") @@ -284,7 +284,7 @@ class test_Command(ClassChecker): # Check with a missing required arg fail = dict(okay) fail.pop('option1') - e = raises(errors2.RequirementError, sub.validate, **fail) + e = raises(errors.RequirementError, sub.validate, **fail) assert e.name == 'option1' def test_execute(self): @@ -304,26 +304,26 @@ class test_Command(ClassChecker): # Test that ZeroArgumentError is raised: o = self.get_instance() - e = raises(errors2.ZeroArgumentError, o.args_options_2_params, 1) + e = raises(errors.ZeroArgumentError, o.args_options_2_params, 1) assert e.name == 'example' # Test that MaxArgumentError is raised (count=1) o = self.get_instance(args=('one?',)) - e = raises(errors2.MaxArgumentError, o.args_options_2_params, 1, 2) + e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2) assert e.name == 'example' assert e.count == 1 assert str(e) == "command 'example' takes at most 1 argument" # Test that MaxArgumentError is raised (count=2) o = self.get_instance(args=('one', 'two?')) - e = raises(errors2.MaxArgumentError, o.args_options_2_params, 1, 2, 3) + e = raises(errors.MaxArgumentError, o.args_options_2_params, 1, 2, 3) assert e.name == 'example' assert e.count == 2 assert str(e) == "command 'example' takes at most 2 arguments" # Test that OverlapError is raised: o = self.get_instance(args=('one', 'two'), options=('three', 'four')) - e = raises(errors2.OverlapError, o.args_options_2_params, + e = raises(errors.OverlapError, o.args_options_2_params, 1, 2, three=3, two=2, four=4, one=1) assert e.names == ['one', 'two'] diff --git a/tests/test_ipalib/test_parameters.py b/tests/test_ipalib/test_parameters.py index 82f39a32d..ea098a95a 100644 --- a/tests/test_ipalib/test_parameters.py +++ b/tests/test_ipalib/test_parameters.py @@ -27,7 +27,7 @@ from inspect import isclass from tests.util import raises, ClassChecker, read_only from tests.util import dummy_ugettext, assert_equal from tests.data import binary_bytes, utf8_bytes, unicode_str -from ipalib import parameters, request, errors2 +from ipalib import parameters, request, errors from ipalib.constants import TYPE_ERROR, CALLABLE_ERROR, NULLS @@ -379,7 +379,7 @@ class test_Param(ClassChecker): assert o._convert_scalar(None) is None assert dummy.called() is False # Test with incorrect type - e = raises(errors2.ConversionError, o._convert_scalar, 'hello', index=17) + e = raises(errors.ConversionError, o._convert_scalar, 'hello', index=17) def test_validate(self): """ @@ -388,7 +388,7 @@ class test_Param(ClassChecker): # Test in default state (with no rules, no kwarg): o = self.cls('my_param') - e = raises(errors2.RequirementError, o.validate, None) + e = raises(errors.RequirementError, o.validate, None) assert e.name == 'my_param' # Test with required=False @@ -399,7 +399,7 @@ class test_Param(ClassChecker): # Test with query=True: o = self.cls('my_param', query=True) assert o.query is True - e = raises(errors2.RequirementError, o.validate, None) + e = raises(errors.RequirementError, o.validate, None) assert_equal(e.name, 'my_param') # Test with multivalue=True: @@ -431,7 +431,7 @@ class test_Param(ClassChecker): pass1.reset() pass2.reset() o = Example('example', pass1, pass2, fail) - e = raises(errors2.ValidationError, o.validate, 42) + e = raises(errors.ValidationError, o.validate, 42) assert e.name == 'example' assert e.error == u'no good' assert e.index is None @@ -458,7 +458,7 @@ class test_Param(ClassChecker): pass2.reset() o = Example('multi_example', pass1, pass2, fail, multivalue=True) assert o.multivalue is True - e = raises(errors2.ValidationError, o.validate, (3, 9)) + e = raises(errors.ValidationError, o.validate, (3, 9)) assert e.name == 'multi_example' assert e.error == u'this one is not good' assert e.index == 0 @@ -495,11 +495,11 @@ class test_Param(ClassChecker): okay = DummyRule() fail = DummyRule(u'this describes the error') o = MyParam('my_param', okay, fail) - e = raises(errors2.ValidationError, o._validate_scalar, True) + e = raises(errors.ValidationError, o._validate_scalar, True) assert e.name == 'my_param' assert e.error == u'this describes the error' assert e.index is None - e = raises(errors2.ValidationError, o._validate_scalar, False, index=2) + e = raises(errors.ValidationError, o._validate_scalar, False, index=2) assert e.name == 'my_param' assert e.error == u'this describes the error' assert e.index == 2 @@ -868,11 +868,11 @@ class test_Str(ClassChecker): assert mthd(value) == unicode(value) bad = [True, 'Hello', (u'Hello',), [42.3], dict(one=1), utf8_bytes] for value in bad: - e = raises(errors2.ConversionError, mthd, value) + e = raises(errors.ConversionError, mthd, value) assert e.name == 'my_str' assert e.index is None assert_equal(e.error, u'must be Unicode text') - e = raises(errors2.ConversionError, mthd, value, index=18) + e = raises(errors.ConversionError, mthd, value, index=18) assert e.name == 'my_str' assert e.index == 18 assert_equal(e.error, u'must be Unicode text') diff --git a/tests/test_ipalib/test_plugable.py b/tests/test_ipalib/test_plugable.py index 4f54d3f7e..6f0cc297d 100644 --- a/tests/test_ipalib/test_plugable.py +++ b/tests/test_ipalib/test_plugable.py @@ -25,7 +25,7 @@ import inspect from tests.util import raises, no_set, no_del, read_only from tests.util import getitem, setitem, delitem from tests.util import ClassChecker, create_test_api -from ipalib import plugable, errors2 +from ipalib import plugable, errors class test_SetProxy(ClassChecker): @@ -372,7 +372,7 @@ class test_Plugin(ClassChecker): """ o = self.cls() o.call('/bin/true') is None - e = raises(errors2.SubprocessError, o.call, '/bin/false') + e = raises(errors.SubprocessError, o.call, '/bin/false') assert e.returncode == 1 assert e.argv == ('/bin/false',) @@ -539,7 +539,7 @@ def test_Registrar(): # Check that SubclassError is raised trying to register a class that is # not a subclass of an allowed base: - e = raises(errors2.PluginSubclassError, r, plugin3) + e = raises(errors.PluginSubclassError, r, plugin3) assert e.plugin is plugin3 # Check that registration works @@ -550,7 +550,7 @@ def test_Registrar(): # Check that DuplicateError is raised trying to register exact class # again: - e = raises(errors2.PluginDuplicateError, r, plugin1) + e = raises(errors.PluginDuplicateError, r, plugin1) assert e.plugin is plugin1 # Check that OverrideError is raised trying to register class with same @@ -560,7 +560,7 @@ def test_Registrar(): pass class plugin1(base1_extended): pass - e = raises(errors2.PluginOverrideError, r, plugin1) + e = raises(errors.PluginOverrideError, r, plugin1) assert e.base == 'Base1' assert e.name == 'plugin1' assert e.plugin is plugin1 @@ -573,7 +573,7 @@ def test_Registrar(): # Check that MissingOverrideError is raised trying to override a name # not yet registerd: - e = raises(errors2.PluginMissingOverrideError, r, plugin2, override=True) + e = raises(errors.PluginMissingOverrideError, r, plugin2, override=True) assert e.base == 'Base2' assert e.name == 'plugin2' assert e.plugin is plugin2 diff --git a/tests/test_ipalib/test_rpc.py b/tests/test_ipalib/test_rpc.py index 826f481e9..d5dd38cdc 100644 --- a/tests/test_ipalib/test_rpc.py +++ b/tests/test_ipalib/test_rpc.py @@ -27,7 +27,7 @@ from tests.util import raises, assert_equal, PluginTester, DummyClass from tests.data import binary_bytes, utf8_bytes, unicode_str from ipalib.frontend import Command from ipalib.request import context, Connection -from ipalib import rpc, errors2 +from ipalib import rpc, errors std_compound = (binary_bytes, utf8_bytes, unicode_str) @@ -233,11 +233,11 @@ class test_xmlclient(PluginTester): assert o.forward('user_add', *args, **kw) == result # Test with an errno the client knows: - e = raises(errors2.RequirementError, o.forward, 'user_add', *args, **kw) + e = raises(errors.RequirementError, o.forward, 'user_add', *args, **kw) assert_equal(e.message, u"'four' is required") # Test with an errno the client doesn't know - e = raises(errors2.UnknownError, o.forward, 'user_add', *args, **kw) + e = raises(errors.UnknownError, o.forward, 'user_add', *args, **kw) assert_equal(e.code, 700) assert_equal(e.error, u'no such error') diff --git a/tests/test_ipaserver/test_rpcserver.py b/tests/test_ipaserver/test_rpcserver.py index bb0cba684..c8cf7e05d 100644 --- a/tests/test_ipaserver/test_rpcserver.py +++ b/tests/test_ipaserver/test_rpcserver.py @@ -23,7 +23,7 @@ Test the `ipaserver.rpc` module. from tests.util import create_test_api, raises, PluginTester from tests.data import unicode_str -from ipalib import errors2, Command +from ipalib import errors, Command from ipaserver import rpcserver diff --git a/tests/test_xmlrpc/test_automount_plugin.py b/tests/test_xmlrpc/test_automount_plugin.py index e2a3bd6f6..e81375211 100644 --- a/tests/test_xmlrpc/test_automount_plugin.py +++ b/tests/test_xmlrpc/test_automount_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_automount' module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Service(XMLRPC_test): @@ -70,7 +70,7 @@ class test_Service(XMLRPC_test): """ try: res = api.Command['automount_addkey'](**self.key_kw) - except errors2.DuplicateEntry: + except errors.DuplicateEntry: pass else: assert False @@ -145,7 +145,7 @@ class test_Service(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showkey'](**delkey_kw) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -160,7 +160,7 @@ class test_Service(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showmap'](self.mapname) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -173,7 +173,7 @@ class test_Service(XMLRPC_test): key_kw={'automountmapname': self.mapname, 'automountkey': self.keyname2} try: res = api.Command['automount_showkey'](**key_kw) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -216,7 +216,7 @@ class test_Indirect(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showkey'](**delkey_kw) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -231,7 +231,7 @@ class test_Indirect(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showmap'](self.mapname) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -274,7 +274,7 @@ class test_IndirectNoParent(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showkey'](**delkey_kw) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -289,7 +289,7 @@ class test_IndirectNoParent(XMLRPC_test): # Verify that it is gone try: res = api.Command['automount_showmap'](self.mapname) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_group_plugin.py b/tests/test_xmlrpc/test_group_plugin.py index c40f4c9d3..a3e854799 100644 --- a/tests/test_xmlrpc/test_group_plugin.py +++ b/tests/test_xmlrpc/test_group_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_group` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Group(XMLRPC_test): @@ -52,7 +52,7 @@ class test_Group(XMLRPC_test): """ try: res = api.Command['group_add'](**self.kw) - except errors2.DuplicateEntry: + except errors.DuplicateEntry: pass def test_add3(self): @@ -195,7 +195,7 @@ class test_Group(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -210,7 +210,7 @@ class test_Group(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.cn2) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -225,7 +225,7 @@ class test_Group(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.cnposix) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_host_plugin.py b/tests/test_xmlrpc/test_host_plugin.py index 2529868c5..11676d08a 100644 --- a/tests/test_xmlrpc/test_host_plugin.py +++ b/tests/test_xmlrpc/test_host_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_host` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Host(XMLRPC_test): @@ -117,7 +117,7 @@ class test_Host(XMLRPC_test): # Verify that it is gone try: res = api.Command['host_show'](self.cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_hostgroup_plugin.py b/tests/test_xmlrpc/test_hostgroup_plugin.py index 4b0d65925..34aea6724 100644 --- a/tests/test_xmlrpc/test_hostgroup_plugin.py +++ b/tests/test_xmlrpc/test_hostgroup_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_hostgroup` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Host(XMLRPC_test): @@ -123,7 +123,7 @@ class test_Host(XMLRPC_test): # Verify that it is gone try: res = api.Command['hostgroup_show'](self.cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -138,7 +138,7 @@ class test_Host(XMLRPC_test): # Verify that it is gone try: res = api.Command['host_show'](self.host_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_netgroup_plugin.py b/tests/test_xmlrpc/test_netgroup_plugin.py index 33c7b419a..90db4633c 100644 --- a/tests/test_xmlrpc/test_netgroup_plugin.py +++ b/tests/test_xmlrpc/test_netgroup_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_netgroup` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors def is_member_of(members, candidate): @@ -259,7 +259,7 @@ class test_Netgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['netgroup_show'](self.ng_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -275,7 +275,7 @@ class test_Netgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['host_show'](self.host_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -287,7 +287,7 @@ class test_Netgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['hostgroup_show'](self.hg_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -299,7 +299,7 @@ class test_Netgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['user_show'](self.user_uid) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -311,7 +311,7 @@ class test_Netgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.group_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_rolegroup_plugin.py b/tests/test_xmlrpc/test_rolegroup_plugin.py index 0912736cb..37135b2e2 100644 --- a/tests/test_xmlrpc/test_rolegroup_plugin.py +++ b/tests/test_xmlrpc/test_rolegroup_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/rolegroup` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Rolegroup(XMLRPC_test): @@ -122,7 +122,7 @@ class test_Rolegroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['rolegroup_show'](self.cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -137,7 +137,7 @@ class test_Rolegroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.rolegroup_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_service_plugin.py b/tests/test_xmlrpc/test_service_plugin.py index 2a3c90ba9..d1b348ee2 100644 --- a/tests/test_xmlrpc/test_service_plugin.py +++ b/tests/test_xmlrpc/test_service_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_service` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Service(XMLRPC_test): @@ -51,7 +51,7 @@ class test_Service(XMLRPC_test): kw={'principal':self.hostprincipal} try: res = api.Command['service_add'](**kw) - except errors2.HostService: + except errors.HostService: pass else: assert False @@ -63,7 +63,7 @@ class test_Service(XMLRPC_test): kw={'principal': u'foo'} try: res = api.Command['service_add'](**kw) - except errors2.MalformedServicePrincipal: + except errors.MalformedServicePrincipal: pass else: assert False @@ -75,7 +75,7 @@ class test_Service(XMLRPC_test): kw={'principal': u'HTTP/foo@FOO.NET'} try: res = api.Command['service_add'](**kw) - except errors2.RealmMismatch: + except errors.RealmMismatch: pass else: assert False @@ -107,7 +107,7 @@ class test_Service(XMLRPC_test): # Verify that it is gone try: res = api.Command['service_show'](self.principal) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_taskgroup_plugin.py b/tests/test_xmlrpc/test_taskgroup_plugin.py index ee4a5bbac..4dc7228f1 100644 --- a/tests/test_xmlrpc/test_taskgroup_plugin.py +++ b/tests/test_xmlrpc/test_taskgroup_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/taskgroup` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_Taskgroup(XMLRPC_test): @@ -152,7 +152,7 @@ class test_Taskgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['taskgroup_show'](self.cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -167,7 +167,7 @@ class test_Taskgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['group_show'](self.taskgroup_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False @@ -182,7 +182,7 @@ class test_Taskgroup(XMLRPC_test): # Verify that it is gone try: res = api.Command['rolegroup_show'](self.rolegroup_cn) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/test_user_plugin.py b/tests/test_xmlrpc/test_user_plugin.py index 200511401..87334045b 100644 --- a/tests/test_xmlrpc/test_user_plugin.py +++ b/tests/test_xmlrpc/test_user_plugin.py @@ -24,7 +24,7 @@ Test the `ipalib/plugins/f_user` module. import sys from xmlrpc_test import XMLRPC_test from ipalib import api -from ipalib import errors2 +from ipalib import errors class test_User(XMLRPC_test): @@ -55,7 +55,7 @@ class test_User(XMLRPC_test): """ try: res = api.Command['user_add'](**self.kw) - except errors2.DuplicateEntry: + except errors.DuplicateEntry: pass def test_doshow(self): @@ -140,7 +140,7 @@ class test_User(XMLRPC_test): # Verify that it is gone try: res = api.Command['user_show'](self.uid) - except errors2.NotFound: + except errors.NotFound: pass else: assert False diff --git a/tests/test_xmlrpc/xmlrpc_test.py b/tests/test_xmlrpc/xmlrpc_test.py index 7ff43c745..83ee7b5d9 100644 --- a/tests/test_xmlrpc/xmlrpc_test.py +++ b/tests/test_xmlrpc/xmlrpc_test.py @@ -25,7 +25,7 @@ import sys import socket import nose from ipalib import api, request -from ipalib import errors2 +from ipalib import errors # Initialize the API. We do this here so that one can run the tests # individually instead of at the top-level. If API.bootstrap() @@ -50,9 +50,9 @@ class XMLRPC_test(object): if not api.Backend.xmlclient.isconnected(): api.Backend.xmlclient.connect() res = api.Command['user_show'](u'notfound') - except errors2.NetworkError: + except errors.NetworkError: raise nose.SkipTest() - except errors2.NotFound: + except errors.NotFound: pass def tearDown(self): -- cgit