summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Howitz <mh@gocept.com>2021-05-28 16:35:48 +0200
committerMichael Howitz <mh@gocept.com>2021-05-31 08:19:50 +0200
commitda66b3938b93ee24eb5aa9d22939afe7bea93b65 (patch)
tree4af0a24b34461d7f8661f8fd8286b92ca14f70b9
parent6b2bdc4d5835e16276ee709fef3f1fb58df1550c (diff)
downloadzope-configuration-da66b3938b93ee24eb5aa9d22939afe7bea93b65.tar.gz
Lint the code.
Add support for Python 3.9.
-rw-r--r--CHANGES.rst2
-rw-r--r--setup.py5
-rw-r--r--src/zope/__init__.py2
-rw-r--r--src/zope/configuration/__init__.py4
-rw-r--r--src/zope/configuration/_compat.py12
-rw-r--r--src/zope/configuration/config.py88
-rw-r--r--src/zope/configuration/docutils.py5
-rw-r--r--src/zope/configuration/exceptions.py4
-rw-r--r--src/zope/configuration/fields.py21
-rw-r--r--src/zope/configuration/interfaces.py6
-rw-r--r--src/zope/configuration/name.py4
-rw-r--r--src/zope/configuration/tests/conditions.py2
-rw-r--r--src/zope/configuration/tests/directives.py12
-rw-r--r--src/zope/configuration/tests/nested.py23
-rw-r--r--src/zope/configuration/tests/samplepackage/foo.py3
-rw-r--r--src/zope/configuration/tests/simple.py4
-rw-r--r--src/zope/configuration/tests/test_config.py263
-rw-r--r--src/zope/configuration/tests/test_docs.py1
-rw-r--r--src/zope/configuration/tests/test_docutils.py31
-rw-r--r--src/zope/configuration/tests/test_fields.py16
-rw-r--r--src/zope/configuration/tests/test_name.py1
-rw-r--r--src/zope/configuration/tests/test_xmlconfig.py81
-rw-r--r--src/zope/configuration/tests/victim.py2
-rw-r--r--src/zope/configuration/xmlconfig.py50
-rw-r--r--src/zope/configuration/zopeconfigure.py1
25 files changed, 447 insertions, 196 deletions
diff --git a/CHANGES.rst b/CHANGES.rst
index b75a207..8cd46ef 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -7,6 +7,8 @@ Changes
- Avoid creating reference cycles through tracebacks in ``reraise`` (change
imported from ``six``).
+- Add support for Python 3.9.
+
4.4.0 (2020-03-22)
------------------
diff --git a/setup.py b/setup.py
index c99d28c..9c0fbec 100644
--- a/setup.py
+++ b/setup.py
@@ -20,10 +20,12 @@
import os
from setuptools import setup, find_packages
+
def read(*rnames):
with open(os.path.join(os.path.dirname(__file__), *rnames)) as f:
return f.read()
+
TESTS_REQUIRE = [
'manuel',
# We test the specific exceptions raised, which
@@ -58,6 +60,7 @@ setup(name='zope.configuration',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Natural Language :: English',
@@ -82,4 +85,4 @@ setup(name='zope.configuration',
include_package_data=True,
zip_safe=False,
tests_require=TESTS_REQUIRE,
-)
+ )
diff --git a/src/zope/__init__.py b/src/zope/__init__.py
index 2cdb0e4..656dc0f 100644
--- a/src/zope/__init__.py
+++ b/src/zope/__init__.py
@@ -1 +1 @@
-__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
+__import__('pkg_resources').declare_namespace(__name__) # pragma: no cover
diff --git a/src/zope/configuration/__init__.py b/src/zope/configuration/__init__.py
index 958fcee..5ff3d37 100644
--- a/src/zope/configuration/__init__.py
+++ b/src/zope/configuration/__init__.py
@@ -17,6 +17,6 @@ Software that wants to provide new config directives calls
zope.configuration.meta.register.
"""
-def namespace(suffix):
- return 'http://namespaces.zope.org/'+suffix
+def namespace(suffix):
+ return 'http://namespaces.zope.org/' + suffix
diff --git a/src/zope/configuration/_compat.py b/src/zope/configuration/_compat.py
index 6a1eebc..a5fb4a1 100644
--- a/src/zope/configuration/_compat.py
+++ b/src/zope/configuration/_compat.py
@@ -15,7 +15,7 @@ import sys
PY3 = sys.version_info[0] >= 3
-if PY3: # pragma: no cover
+if PY3: # pragma: PY3
import builtins
@@ -24,7 +24,7 @@ if PY3: # pragma: no cover
# borrowed from 'six'
def reraise(tp, value, tb=None):
- try:
+ try: # pragma: no cover
if value is None:
value = tp
if value.__traceback__ is not tb:
@@ -34,12 +34,12 @@ if PY3: # pragma: no cover
value = None
tb = None
-else: # pragma: no cover
+else: # pragma: PY2
- import __builtin__ as builtins
+ import __builtin__ as builtins # noqa: F401 imported but unused
- text_type = unicode
- string_types = (basestring,)
+ text_type = unicode # noqa: F821 undefined name
+ string_types = (basestring,) # noqa: F821 undefined name
# borrowed from 'six'
exec("""\
diff --git a/src/zope/configuration/config.py b/src/zope/configuration/config.py
index 30a7566..2d99b36 100644
--- a/src/zope/configuration/config.py
+++ b/src/zope/configuration/config.py
@@ -140,7 +140,6 @@ class ConfigurationContext(object):
Examples:
>>> from zope.configuration.config import ConfigurationContext
- >>> from zope.configuration.config import ConfigurationError
>>> c = ConfigurationContext()
>>> import zope, zope.interface
>>> c.resolve('zope') is zope
@@ -167,7 +166,7 @@ class ConfigurationContext(object):
True
>>> c.resolve('str') is str
True
- """
+ """ # noqa: E501 line too long
name = dottedname.strip()
if not name:
@@ -236,7 +235,6 @@ class ConfigurationContext(object):
# see not mname case above
return mod
-
try:
obj = getattr(mod, oname)
return obj
@@ -278,8 +276,7 @@ class ConfigurationContext(object):
True
>>> c.path("y/../z") == d + os.path.normpath("/z")
True
-
- """
+ """ # noqa: E501 line too long
filename, needs_processing = PathProcessor.expand(filename)
if not needs_processing:
@@ -509,8 +506,8 @@ class ConfigurationContext(object):
includepath=includepath,
info=info,
order=order,
- )
)
+ )
self.actions.append(action)
@@ -555,7 +552,6 @@ class ConfigurationAdapterRegistry(object):
>>> from zope.configuration.interfaces import IConfigurationContext
>>> from zope.configuration.config import ConfigurationAdapterRegistry
- >>> from zope.configuration.config import ConfigurationError
>>> from zope.configuration.config import ConfigurationMachine
>>> r = ConfigurationAdapterRegistry()
>>> c = ConfigurationMachine()
@@ -566,7 +562,8 @@ class ConfigurationAdapterRegistry(object):
>>> def f():
... pass
- >>> r.register(IConfigurationContext, ('http://www.zope.com', 'xxx'), f)
+ >>> r.register(
+ ... IConfigurationContext, ('http://www.zope.com', 'xxx'), f)
>>> r.factory(c, ('http://www.zope.com', 'xxx')) is f
True
>>> r.factory(c, ('http://www.zope.com', 'yyy')) is f
@@ -636,6 +633,7 @@ class ConfigurationAdapterRegistry(object):
"The directive %s cannot be used in this context" % (name, ))
return f
+
@implementer(IConfigurationContext)
class ConfigurationMachine(ConfigurationAdapterRegistry, ConfigurationContext):
"""
@@ -674,12 +672,13 @@ class ConfigurationMachine(ConfigurationAdapterRegistry, ConfigurationContext):
includepath = ()
info = ''
- #: These `Exception` subclasses are allowed to be raised from `execute_actions`
- #: without being re-wrapped into a `~.ConfigurationError`. (`BaseException`
- #: and other `~.ConfigurationError` instances are never wrapped.)
+ #: These `Exception` subclasses are allowed to be raised from
+ #: `execute_actions` without being re-wrapped into a
+ #: `~.ConfigurationError`. (`BaseException` and other
+ #: `~.ConfigurationError` instances are never wrapped.)
#:
- #: Users of instances of this class may modify this before calling `execute_actions`
- #: if they need to propagate specific exceptions.
+ #: Users of instances of this class may modify this before calling
+ #: `execute_actions` if they need to propagate specific exceptions.
#:
#: .. versionadded:: 4.2.0
pass_through_exceptions = ()
@@ -797,12 +796,14 @@ class ConfigurationMachine(ConfigurationAdapterRegistry, ConfigurationContext):
raise
except Exception:
# Wrap it up and raise.
- reraise(ConfigurationExecutionError(info, sys.exc_info()[1]),
- None, sys.exc_info()[2])
+ reraise(
+ ConfigurationExecutionError(info, sys.exc_info()[1]),
+ None, sys.exc_info()[2])
finally:
if clear:
del self.actions[:]
+
class ConfigurationExecutionError(ConfigurationWrapperError):
"""
An error occurred during execution of a configuration action
@@ -811,6 +812,7 @@ class ConfigurationExecutionError(ConfigurationWrapperError):
##############################################################################
# Stack items
+
class IStackItem(Interface):
"""
Configuration machine stack items
@@ -836,6 +838,7 @@ class IStackItem(Interface):
"""Finish processing a directive
"""
+
@implementer(IStackItem)
class SimpleStackItem(object):
"""
@@ -848,7 +851,8 @@ class SimpleStackItem(object):
It also defers any computation until the end of the directive
has been reached.
"""
- #XXX why this *argdata hack instead of schema, data?
+ # XXX why this *argdata hack instead of schema, data?
+
def __init__(self, context, handler, info, *argdata):
newcontext = GroupingContextDecorator(context)
newcontext.info = info
@@ -871,9 +875,10 @@ class SimpleStackItem(object):
# we allow the handler to return nothing
for action in actions:
if not isinstance(action, dict):
- action = expand_action(*action) # b/c
+ action = expand_action(*action) # b/c
context.action(**action)
+
@implementer(IStackItem)
class RootStackItem(object):
"""
@@ -898,6 +903,7 @@ class RootStackItem(object):
def finish(self):
pass
+
@implementer_if_needed(IStackItem)
class GroupingStackItem(RootStackItem):
"""
@@ -1079,6 +1085,7 @@ class GroupingStackItem(RootStackItem):
action = expand_action(*action)
self.context.action(**action)
+
def noop():
pass
@@ -1139,8 +1146,8 @@ class ComplexStackItem(object):
ready to use a stack item.
>>> from zope.configuration.config import ComplexStackItem
- >>> item = ComplexStackItem(definition, context, {'x': u'xv', 'y': u'yv'},
- ... 'foo')
+ >>> item = ComplexStackItem(
+ ... definition, context, {'x': u'xv', 'y': u'yv'}, 'foo')
When we created the definition, the handler (factory) was called.
@@ -1215,6 +1222,7 @@ class ComplexStackItem(object):
'kw': {},
'order': 0}]
"""
+
def __init__(self, meta, context, data, info):
newcontext = GroupingContextDecorator(context)
newcontext.info = info
@@ -1233,7 +1241,7 @@ class ComplexStackItem(object):
schema = self.meta.get(name)
if schema is None:
raise ConfigurationError("Invalid directive", name)
- schema = schema[0] # strip off info
+ schema = schema[0] # strip off info
handler = getattr(self.handler, name)
return SimpleStackItem(self.context, handler, info, schema, data)
@@ -1245,10 +1253,10 @@ class ComplexStackItem(object):
actions = self.handler()
except AttributeError as v:
if v.args[0] == '__call__':
- return # noncallable
+ return # noncallable
raise
except TypeError:
- return # non callable
+ return # non callable
if actions:
# we allow the handler to return nothing
@@ -1288,10 +1296,12 @@ class GroupingContextDecorator(ConfigurationContext):
##############################################################################
# Directive-definition
+
class DirectiveSchema(GlobalInterface):
"""A field that contains a global variable value that must be a schema
"""
+
class IDirectivesInfo(Interface):
"""Schema for the ``directives`` directive
"""
@@ -1357,6 +1367,7 @@ class IStandaloneDirectiveInfo(IDirectivesInfo, IFullInfo):
"""Info for full directives defined outside a directives directives
"""
+
def defineSimpleDirective(context, name, schema, handler,
namespace='', usedIn=IConfigurationContext):
"""
@@ -1414,7 +1425,7 @@ def defineSimpleDirective(context, name, schema, handler,
'info': None,
'kw': {},
'order': 0}]
- """
+ """ # noqa: E501 line too long
namespace = namespace or context.namespace
if namespace != '*':
name = namespace, name
@@ -1426,6 +1437,7 @@ def defineSimpleDirective(context, name, schema, handler,
context.register(usedIn, name, factory)
context.document(name, schema, usedIn, handler, context.info)
+
def defineGroupingDirective(context, name, schema, handler,
namespace='', usedIn=IConfigurationContext):
"""
@@ -1442,7 +1454,6 @@ def defineGroupingDirective(context, name, schema, handler,
>>> context = ConfigurationMachine()
>>> from zope.interface import Interface
>>> from zope.schema import TextLine
- >>> from zope.configuration.tests.directives import f
>>> class Ixy(Interface):
... x = TextLine()
... y = TextLine()
@@ -1476,7 +1487,7 @@ def defineGroupingDirective(context, name, schema, handler,
'vx'
>>> context.stack[-1].context.y
'vy'
- """
+ """ # noqa: E501 line too long
namespace = namespace or context.namespace
if namespace != '*':
name = namespace, name
@@ -1502,6 +1513,7 @@ class ComplexDirectiveDefinition(GroupingContextDecorator, dict):
See the description and tests for ComplexStackItem.
"""
+
def before(self):
def factory(context, data, info):
@@ -1512,6 +1524,7 @@ class ComplexDirectiveDefinition(GroupingContextDecorator, dict):
self.document((self.namespace, self.name), self.schema, self.usedIn,
self.handler, self.info)
+
def subdirective(context, name, schema):
context.document((context.namespace, name), schema, context.usedIn,
getattr(context.handler, name, context.handler),
@@ -1521,6 +1534,7 @@ def subdirective(context, name, schema):
##############################################################################
# Features
+
class IProvidesDirectiveInfo(Interface):
"""Information for a <meta:provides> directive"""
@@ -1532,6 +1546,7 @@ class IProvidesDirectiveInfo(Interface):
""",
)
+
def provides(context, feature):
"""
Declare that a feature is provided in context.
@@ -1686,16 +1701,20 @@ def toargs(context, schema, data):
try:
args[str(name)] = field.fromUnicode(s)
except ValidationError as v:
- reraise(ConfigurationError("Invalid value for %r" % (n)).add_details(v),
- None, sys.exc_info()[2])
+ reraise(
+ ConfigurationError(
+ "Invalid value for %r" % (n)).add_details(v),
+ None, sys.exc_info()[2])
elif field.required:
# if the default is valid, we can use that:
default = field.default
try:
field.validate(default)
except ValidationError as v:
- reraise(ConfigurationError("Missing parameter: %r" % (n,)).add_details(v),
- None, sys.exc_info()[2])
+ reraise(
+ ConfigurationError(
+ "Missing parameter: %r" % (n,)).add_details(v),
+ None, sys.exc_info()[2])
args[str(name)] = default
if data:
@@ -1715,6 +1734,7 @@ def toargs(context, schema, data):
##############################################################################
# Conflict resolution
+
def expand_action(discriminator, callable=None, args=(), kw=None,
includepath=(), info=None, order=0, **extra):
if kw is None:
@@ -1729,10 +1749,11 @@ def expand_action(discriminator, callable=None, args=(), kw=None,
includepath=includepath,
info=info,
order=order,
- )
)
+ )
return action
+
def resolveConflicts(actions):
"""
Resolve conflicting actions.
@@ -1802,8 +1823,8 @@ def resolveConflicts(actions):
for _, _, action in rest:
includepath = action['includepath']
# Test whether path is a prefix of opath
- if (includepath[:len(basepath)] != basepath # not a prefix
- or includepath == basepath):
+ if (includepath[:len(basepath)] != basepath # not a prefix
+ or includepath == basepath):
L = conflicts.setdefault(discriminator, [baseinfo])
L.append(action['info'])
@@ -1829,7 +1850,8 @@ class ConfigurationConflictError(ConfigurationError):
r.append(u" " + line)
opening = "\n".join(r)
- return super(ConfigurationConflictError, self)._with_details(opening, detail_formatter)
+ return super(ConfigurationConflictError, self)._with_details(
+ opening, detail_formatter)
##############################################################################
diff --git a/src/zope/configuration/docutils.py b/src/zope/configuration/docutils.py
index 37b0060..f64f9f6 100644
--- a/src/zope/configuration/docutils.py
+++ b/src/zope/configuration/docutils.py
@@ -25,6 +25,7 @@ __all__ = [
para_sep = re.compile('\n{2,}')
whitespace = re.compile('[ \t\n\r]+')
+
def wrap(text, width=78, indent=0):
"""
Makes sure that we keep a line length of a certain width.
@@ -59,11 +60,11 @@ def wrap(text, width=78, indent=0):
line.append(word)
length += len(word) + 1
else:
- lines.append(' '*indent + ' '.join(line))
+ lines.append(' ' * indent + ' '.join(line))
line = [word]
length = len(word) + 1 + indent
- lines.append(' '*indent + ' '.join(line))
+ lines.append(' ' * indent + ' '.join(line))
new_paras.append('\n'.join(lines))
diff --git a/src/zope/configuration/exceptions.py b/src/zope/configuration/exceptions.py
index abac17a..296ff73 100644
--- a/src/zope/configuration/exceptions.py
+++ b/src/zope/configuration/exceptions.py
@@ -20,6 +20,7 @@ __all__ = [
'ConfigurationError',
]
+
class ConfigurationError(Exception):
"""There was an error in a configuration
"""
@@ -60,7 +61,8 @@ class ConfigurationWrapperError(ConfigurationError):
USE_INFO_REPR = False
def __init__(self, info, exception):
- super(ConfigurationWrapperError, self).__init__(repr(info) if self.USE_INFO_REPR else info)
+ super(ConfigurationWrapperError, self).__init__(
+ repr(info) if self.USE_INFO_REPR else info)
self.add_details(exception)
# This stuff is undocumented and not used but we store
diff --git a/src/zope/configuration/fields.py b/src/zope/configuration/fields.py
index 4a83103..37c9797 100644
--- a/src/zope/configuration/fields.py
+++ b/src/zope/configuration/fields.py
@@ -68,7 +68,8 @@ class PythonIdentifier(schema_PythonIdentifier):
Now let's see whether validation works alright
- >>> for value in (u'foo', u'foo3', u'foo_', u'_foo3', u'foo_3', u'foo3_'):
+ >>> values = (u'foo', u'foo3', u'foo_', u'_foo3', u'foo_3', u'foo3_')
+ >>> for value in values:
... _ = field.fromUnicode(value)
>>> from zope.schema import ValidationError
>>> for value in (u'3foo', u'foo:', u'\\', u''):
@@ -212,6 +213,7 @@ class GlobalInterface(GlobalObject):
NotAnInterface: (<class 'Foo'>, ...
"""
+
def __init__(self, **kw):
super(GlobalInterface, self).__init__(InterfaceField(), **kw)
@@ -268,7 +270,9 @@ class Tokens(List):
try:
v = vt.fromUnicode(s)
except ValidationError as ex:
- raise InvalidToken("%s in %r" % (ex, value)).with_field_and_value(self, s)
+ raise InvalidToken(
+ "%s in %r" % (ex, value)).with_field_and_value(
+ self, s)
else:
values.append(v)
else:
@@ -278,6 +282,7 @@ class Tokens(List):
return values
+
class PathProcessor(object):
# Internal helper for manipulations on paths
@@ -428,7 +433,6 @@ class Bool(schema_Bool):
raise InvalidValue().with_field_and_value(self, value)
-
@implementer_if_needed(IFromUnicode)
class MessageID(Text):
"""
@@ -506,7 +510,8 @@ class MessageID(Text):
('file location', 8)]}}
>>> from zope.i18nmessageid import Message
- >>> isinstance(list(context.i18n_strings['testing'].keys())[0], Message)
+ >>> isinstance(list(context.i18n_strings['testing'].keys())[0],
+ ... Message)
True
Explicit Message IDs
@@ -523,15 +528,15 @@ class MessageID(Text):
>>> i.default is None
True
- """
+ """ # noqa: E501 line too long
context = self.context
domain = getattr(context, 'i18n_domain', '')
if not domain:
domain = 'untranslated'
warnings.warn(
- "You did not specify an i18n translation domain for the "\
+ "You did not specify an i18n translation domain for the "
"'%s' field in %s" % (self.getName(), context.info.file)
- )
+ )
if not isinstance(domain, str):
# IZopeConfigure specifies i18n_domain as a BytesLine, but that's
# wrong on Python 3, where the filesystem uses str, and hence
@@ -548,7 +553,7 @@ class MessageID(Text):
v = v[2:].lstrip()
elif v.startswith('['):
end = v.find(']')
- default = v[end+2:]
+ default = v[end + 2:]
v = v[1:end]
# Convert to a message id, importing the factory, if necessary
diff --git a/src/zope/configuration/interfaces.py b/src/zope/configuration/interfaces.py
index a8dbc9d..e6342d7 100644
--- a/src/zope/configuration/interfaces.py
+++ b/src/zope/configuration/interfaces.py
@@ -23,9 +23,11 @@ __all__ = [
'IGroupingContext',
]
+
class InvalidToken(ValidationError):
"""Invalid token in list."""
+
class IConfigurationContext(Interface):
"""Configuration Context
@@ -110,8 +112,8 @@ class IConfigurationContext(Interface):
with the value `None`. An action with a discriminator of `None`
never conflicts with other actions.
- :keyword int order: This is possible to add an order argument to crudely control
- the order of execution.
+ :keyword int order: This is possible to add an order argument to
+ crudely control the order of execution.
:keyword str info: Optional source line information
diff --git a/src/zope/configuration/name.py b/src/zope/configuration/name.py
index 97b7d76..5df88a5 100644
--- a/src/zope/configuration/name.py
+++ b/src/zope/configuration/name.py
@@ -27,6 +27,7 @@ __all__ = [
'path',
]
+
def resolve(name, package='zopeproducts', _silly=('__doc__',), _globals={}):
name = name.strip()
@@ -46,7 +47,7 @@ def resolve(name, package='zopeproducts', _silly=('__doc__',), _globals={}):
if not mod:
return __import__(name, _globals, _globals, _silly)
- while 1:
+ while True:
m = __import__(mod, _globals, _globals, _silly)
try:
a = getattr(m, last)
@@ -79,6 +80,7 @@ def getNormalizedName(name, package):
name += "+"
return name
+
def path(file='', package='zopeproducts', _silly=('__doc__',), _globals={}):
# XXX WTF? why not look for abspath before importing?
try:
diff --git a/src/zope/configuration/tests/conditions.py b/src/zope/configuration/tests/conditions.py
index b79fdce..8068e48 100644
--- a/src/zope/configuration/tests/conditions.py
+++ b/src/zope/configuration/tests/conditions.py
@@ -26,8 +26,10 @@ class IRegister(Interface):
required=True,
)
+
registry = []
+
def register(context, id):
context.action(discriminator=('Register', id),
callable=registry.append,
diff --git a/src/zope/configuration/tests/directives.py b/src/zope/configuration/tests/directives.py
index 4cba067..0a17f89 100644
--- a/src/zope/configuration/tests/directives.py
+++ b/src/zope/configuration/tests/directives.py
@@ -26,20 +26,25 @@ from zope.configuration.fields import GlobalObject
class F(object):
def __repr__(self):
return 'f'
+
def __call__(self, *a, **k):
raise NotImplementedError
+
f = F()
+
class ISimple(Interface):
a = Text()
b = Text(required=False)
c = NativeStringLine()
+
def simple(context, a=None, c=None, b=u"xxx"):
return [(('simple', a, b, c), f, (a, b, c))]
+
def newsimple(context, a, c, b=u"xxx"):
context.action(('newsimple', a, b, c), f, (a, b, c))
@@ -62,8 +67,10 @@ class IFactory(Interface):
factory = GlobalObject()
+
def factory(context, factory):
- context.action(('factory', 1,2), factory)
+ context.action(('factory', 1, 2), factory)
+
class Complex(object):
@@ -75,7 +82,7 @@ class Complex(object):
return [(('Complex.factory', 1, 2), factory, (self.a, ))]
def __call__(self):
- return [(('Complex', 1,2), f, (self.b, self.c))]
+ return [(('Complex', 1, 2), f, (self.b, self.c))]
class Ik(Interface):
@@ -83,5 +90,6 @@ class Ik(Interface):
class_ = NativeStringLine()
x = NativeStringLine()
+
def k(context, for_, class_, x):
context.action(('k', for_), f, (for_, class_, x))
diff --git a/src/zope/configuration/tests/nested.py b/src/zope/configuration/tests/nested.py
index 3a108aa..f804f13 100644
--- a/src/zope/configuration/tests/nested.py
+++ b/src/zope/configuration/tests/nested.py
@@ -23,13 +23,12 @@ from zope.schema import Int
from zope.schema import Text
from zope.schema import TextLine
from zope.configuration.config import GroupingContextDecorator
-from zope.configuration.config import IConfigurationContext
from zope.configuration.fields import Bool
-
schema_registry = {}
+
class ISchemaInfo(Interface):
"""Parameter schema for the schema directive
"""
@@ -37,10 +36,11 @@ class ISchemaInfo(Interface):
name = TextLine(
title=u"The schema name",
description=u"This is a descriptive name for the schema.",
- )
+ )
id = Id(title=u"The unique id for the schema")
+
class ISchema(Interface):
"""Interface that distinguishes the schema directive
"""
@@ -53,7 +53,6 @@ class Schema(GroupingContextDecorator):
"""Handle schema directives
"""
-
def __init__(self, context, name, id):
self.context, self.name, self.id = context, name, id
self.fields = {}
@@ -63,13 +62,13 @@ class Schema(GroupingContextDecorator):
self.name,
(Interface, ),
self.fields
- )
+ )
schema.__doc__ = self.info.text.strip()
self.action(
discriminator=('schema', self.id),
callable=schema_registry.__setitem__,
args=(self.id, schema),
- )
+ )
class IFieldInfo(Interface):
@@ -96,6 +95,7 @@ class IFieldInfo(Interface):
required=False,
default=False)
+
class ITextInfo(IFieldInfo):
min_length = Int(
@@ -106,7 +106,7 @@ class ITextInfo(IFieldInfo):
u"no minimum."
),
required=False,
- min=0, # needs to be a positive number
+ min=0, # needs to be a positive number
default=0)
max_length = Int(
@@ -117,9 +117,10 @@ class ITextInfo(IFieldInfo):
u"None, there is no maximum."
),
required=False,
- min=0, # needs to be a positive number
+ min=0, # needs to be a positive number
default=None)
+
def field(context, constructor, name, **kw):
# Compute the field
@@ -135,19 +136,21 @@ def field(context, constructor, name, **kw):
def textField(context, **kw):
field(context, Text, **kw)
+
class IIntInfo(IFieldInfo):
min = Int(
title=u"Start of the range",
required=False,
default=None
- )
+ )
max = Int(
title=u"End of the range (excluding the value itself)",
required=False,
default=None
- )
+ )
+
def intField(context, **kw):
field(context, Int, **kw)
diff --git a/src/zope/configuration/tests/samplepackage/foo.py b/src/zope/configuration/tests/samplepackage/foo.py
index f6da18d..f1060c1 100644
--- a/src/zope/configuration/tests/samplepackage/foo.py
+++ b/src/zope/configuration/tests/samplepackage/foo.py
@@ -18,15 +18,18 @@ from zope import schema
data = []
+
class S1(Interface):
x = schema.BytesLine()
y = schema.Int()
+
class stuff(object):
def __init__(self, args, info, basepath, package, includepath):
(self.args, self.info, self.basepath, self.package, self.includepath
) = args, info, basepath, package, includepath
+
def handler(_context, **kw):
args = sorted(kw.items())
args = tuple(args)
diff --git a/src/zope/configuration/tests/simple.py b/src/zope/configuration/tests/simple.py
index 60c95ff..17aa7d7 100644
--- a/src/zope/configuration/tests/simple.py
+++ b/src/zope/configuration/tests/simple.py
@@ -19,6 +19,7 @@ from zope.schema import Text
from zope.configuration.fields import Path
+
class IRegisterFile(Interface):
path = Path(
@@ -32,14 +33,17 @@ class IRegisterFile(Interface):
required=False
)
+
class FileInfo(object):
def __init__(self, path, title, description, info):
(self.path, self.title, self.description, self.info
) = path, title, description, info
+
file_registry = []
+
def registerFile(context, path, title=u""):
info = context.info
description = info.text.strip()
diff --git a/src/zope/configuration/tests/test_config.py b/src/zope/configuration/tests/test_config.py
index ab21589..714e7e2 100644
--- a/src/zope/configuration/tests/test_config.py
+++ b/src/zope/configuration/tests/test_config.py
@@ -19,6 +19,7 @@ import sys
# pylint:disable=inherit-non-class,protected-access
# pylint:disable=attribute-defined-outside-init, arguments-differ
+
class ConfigurationContextTests(unittest.TestCase):
def _getTargetClass(self):
@@ -51,7 +52,7 @@ class ConfigurationContextTests(unittest.TestCase):
self.assertTrue(c.resolve('.') is package)
def test_resolve_trailing_dot_in_resolve(self):
- #Dotted names are no longer allowed to end in dots
+ # Dotted names are no longer allowed to end in dots
c = self._makeOne()
with self.assertRaises(ValueError):
c.resolve('zope.')
@@ -99,15 +100,15 @@ class ConfigurationContextTests(unittest.TestCase):
self.assertIn('ImportError', str(exc.exception))
def test_resolve_bad_sub_last_import(self):
- #Import error caused by a bad sub import inside the referenced
- #dotted name. Here we keep the standard traceback.
+ # Import error caused by a bad sub import inside the referenced
+ # dotted name. Here we keep the standard traceback.
c = self._makeOne()
with self.assertRaises(ImportError):
c.resolve('zope.configuration.tests.victim')
def test_resolve_bad_sub_import(self):
- #Import error caused by a bad sub import inside part of the referenced
- #dotted name. Here we keep the standard traceback.
+ # Import error caused by a bad sub import inside part of the referenced
+ # dotted name. Here we keep the standard traceback.
c = self._makeOne()
with self.assertRaises(ImportError):
c.resolve('zope.configuration.tests.victim.nosuch')
@@ -144,8 +145,9 @@ class ConfigurationContextTests(unittest.TestCase):
os.path.join(os.getcwd(), 'somewhere'))
def test_path_wo_basepath_w_package_having_file(self):
- #Path must always return an absolute path.
+ # Path must always return an absolute path.
import os
+
class stub:
__file__ = os.path.join('relative', 'path')
c = self._makeOne()
@@ -153,10 +155,11 @@ class ConfigurationContextTests(unittest.TestCase):
self.assertTrue(os.path.isabs(c.path('y/z')))
def test_path_wo_basepath_w_package_having_no_file_but_path(self):
- #Determine package path using __path__ if __file__ isn't available.
+ # Determine package path using __path__ if __file__ isn't available.
# (i.e. namespace package installed with
- #--single-version-externally-managed)
+ # --single-version-externally-managed)
import os
+
class stub:
__path__ = [os.path.join('relative', 'path')]
c = self._makeOne()
@@ -182,7 +185,7 @@ class ConfigurationContextTests(unittest.TestCase):
try:
path = c.path('~')
self.assertEqual(path, os.path.join(os.sep, 'HOME'))
- finally: # pragma: no cover
+ finally: # pragma: no cover
if old_home:
os.environ['HOME'] = old_home
else:
@@ -191,7 +194,7 @@ class ConfigurationContextTests(unittest.TestCase):
def test_checkDuplicate_miss(self):
import os
c = self._makeOne()
- c.checkDuplicate('/path') # doesn't raise
+ c.checkDuplicate('/path') # doesn't raise
self.assertEqual(list(c._seen_files), [os.path.normpath('/path')])
def test_checkDuplicate_hit(self):
@@ -219,7 +222,7 @@ class ConfigurationContextTests(unittest.TestCase):
def test_action_defaults_no_info_no_includepath(self):
DISCRIMINATOR = ('a', ('b',), 0)
c = self._makeOne()
- c.actions = [] # normally provided by subclass
+ c.actions = [] # normally provided by subclass
c.action(DISCRIMINATOR)
self.assertEqual(len(c.actions), 1)
info = c.actions[0]
@@ -234,9 +237,9 @@ class ConfigurationContextTests(unittest.TestCase):
def test_action_defaults_w_info_w_includepath(self):
DISCRIMINATOR = ('a', ('b',), 0)
c = self._makeOne()
- c.actions = [] # normally provided by subclass
- c.info = 'INFO' # normally provided by subclass
- c.includepath = ('a', 'b') # normally provided by subclass
+ c.actions = [] # normally provided by subclass
+ c.info = 'INFO' # normally provided by subclass
+ c.includepath = ('a', 'b') # normally provided by subclass
c.action(DISCRIMINATOR)
self.assertEqual(len(c.actions), 1)
info = c.actions[0]
@@ -254,10 +257,11 @@ class ConfigurationContextTests(unittest.TestCase):
KW = {'one': 1}
INCLUDE_PATH = ('p', 'q/r')
INFO = 'INFO'
+
def _callable():
raise AssertionError("should not be called")
c = self._makeOne()
- c.actions = [] # normally provided by subclass
+ c.actions = [] # normally provided by subclass
c.action(DISCRIMINATOR,
_callable,
ARGS,
@@ -265,7 +269,7 @@ class ConfigurationContextTests(unittest.TestCase):
42,
INCLUDE_PATH,
INFO,
- )
+ )
self.assertEqual(len(c.actions), 1)
info = c.actions[0]
self.assertEqual(info['discriminator'], DISCRIMINATOR)
@@ -282,10 +286,11 @@ class ConfigurationContextTests(unittest.TestCase):
KW = {'one': 1}
INCLUDE_PATH = ('p', 'q/r')
INFO = 'INFO'
+
def _callable():
raise AssertionError("should not be called")
c = self._makeOne()
- c.actions = [] # normally provided by subclass
+ c.actions = [] # normally provided by subclass
c.action(DISCRIMINATOR,
_callable,
ARGS,
@@ -295,7 +300,7 @@ class ConfigurationContextTests(unittest.TestCase):
INFO,
foo='bar',
baz=17,
- )
+ )
self.assertEqual(len(c.actions), 1)
info = c.actions[0]
self.assertEqual(info['discriminator'], DISCRIMINATOR)
@@ -339,10 +344,12 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_register(self):
from zope.interface import Interface
+
class IFoo(Interface):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
+
def _factory():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -354,12 +361,15 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_register_replacement(self):
from zope.interface import Interface
+
class IFoo(Interface):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
+
def _factory():
raise AssertionError("should not be called")
+
def _rival():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -372,13 +382,16 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_register_new_name(self):
from zope.interface import Interface
+
class IFoo(Interface):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
NAME2 = 'other'
+
def _factory():
raise AssertionError("should not be called")
+
def _rival():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -393,8 +406,10 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_document_non_string_name(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/'
@@ -415,8 +430,10 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_document_w_string_name(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
NAME = 'testing'
@@ -446,14 +463,17 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_factory_hit_on_fqn(self):
from zope.interface import Interface
from zope.interface import implementer
+
class IFoo(Interface):
pass
+
@implementer(IFoo)
class Context(object):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
context = Context()
+
def _factory():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -463,14 +483,17 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_factory_miss_on_fqn_hit_on_bare_name(self):
from zope.interface import Interface
from zope.interface import implementer
+
class IFoo(Interface):
pass
+
@implementer(IFoo)
class Context(object):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
context = Context()
+
def _factory():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -480,11 +503,13 @@ class ConfigurationAdapterRegistryTests(unittest.TestCase):
def test_factory_hit_on_fqn_lookup_fails(self):
from zope.interface import Interface
from zope.configuration.exceptions import ConfigurationError
+
class IFoo(Interface):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
- context = object() # doesn't provide IFoo
+ context = object() # doesn't provide IFoo
+
def _factory():
raise AssertionError("should not be called")
reg = self._makeOne()
@@ -514,7 +539,7 @@ class _ConformsToIConfigurationContext(object):
class ConfigurationMachineTests(_ConformsToIConfigurationContext,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import ConfigurationMachine
@@ -549,6 +574,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
from zope.configuration.config import IConfigurationContext
NS = 'http://namespace.example.com/'
NAME = 'testing'
+
def _factory(context, data, info):
raise AssertionError("should not be called")
cm = self._makeOne()
@@ -560,16 +586,20 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
from zope.interface import Interface
from zope.configuration.config import IConfigurationContext
from zope.configuration.config import RootStackItem
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
+
def _handler(*args, **kw):
raise AssertionError("should not be called")
NS = 'http://namespace.example.com/'
NAME = 'testing'
_called_with = []
item = object()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return item
@@ -598,16 +628,20 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
from zope.interface import Interface
from zope.configuration.config import IConfigurationContext
from zope.configuration.config import RootStackItem
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
+
def _handler(*args, **kw):
raise AssertionError("should not be called")
NS = 'http://namespace.example.com/'
NAME = 'testing'
_called_with = []
item = object()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return item
@@ -635,8 +669,10 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def test_end(self):
from zope.configuration.config import RootStackItem
+
class FauxItem(object):
_finished = False
+
def finish(self):
self._finished = True
cm = self._makeOne()
@@ -652,20 +688,26 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
from zope.interface import Interface
from zope.configuration.config import IConfigurationContext
from zope.configuration.config import RootStackItem
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
+
class FauxItem(object):
_finished = False
+
def finish(self):
self._finished = True
+
def _handler(*args, **kw):
raise AssertionError("should not be called")
NS = 'http://namespace.example.com/'
NAME = 'testing'
_called_with = []
item = FauxItem()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return item
@@ -702,6 +744,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def test_getInfo_w_item(self):
class FauxItem(object):
info = 'FAUX'
+
def __init__(self):
self.context = self
cm = self._makeOne()
@@ -716,6 +759,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def test_setInfo_w_item(self):
class FauxItem(object):
info = 'FAUX'
+
def __init__(self):
self.context = self
cm = self._makeOne()
@@ -726,16 +770,18 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def test_execute_actions_empty(self):
cm = self._makeOne()
- cm.execute_actions() # noop
+ cm.execute_actions() # noop
def test_execute_actions_wo_errors(self):
_called_with = {}
+
def _a1(*args, **kw):
_called_with.setdefault('_a1', []).append((args, kw))
+
def _a2(*args, **kw):
_called_with.setdefault('_a2', []).append((args, kw))
cm = self._makeOne()
- cm.action(None, None) # will be skipped
+ cm.action(None, None) # will be skipped
cm.action(None, _a1, ('a', 0), {'foo': 'bar'}, 4)
cm.action(None, _a2, ('a', 1), {'foo': 'baz'}, 3)
cm.action(None, _a1, ('b', 2), {'foo': 'qux'}, 2)
@@ -743,10 +789,10 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
self.assertEqual(_called_with['_a1'],
[(('b', 2), {'foo': 'qux'}),
(('a', 0), {'foo': 'bar'}),
- ])
+ ])
self.assertEqual(_called_with['_a2'],
[(('a', 1), {'foo': 'baz'}),
- ])
+ ])
def test_execute_actions_w_errors_w_testing(self):
def _err(*args, **kw):
@@ -759,6 +805,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def test_execute_actions_w_errors_wo_testing(self):
from zope.configuration.config import ConfigurationExecutionError
+
def _err(*args, **kw):
raise ValueError('XXX')
cm = self._makeOne()
@@ -772,6 +819,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
def _check_execute_actions_w_errors_wo_testing(self, ex_kind, cm=None):
ex = ex_kind('XXX')
+
def _err(*args, **kw):
raise ex
cm = cm if cm is not None else self._makeOne()
@@ -811,7 +859,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
machine = self._makeOne()
ns = "http://www.zope.org/testing"
- #Register some test directives, starting with a grouping directive
+ # Register some test directives, starting with a grouping directive
# that sets a package:
machine(
@@ -827,7 +875,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
package="zope.configuration.tests.directives",
)
- #Which makes it easier to define the other directives:
+ # Which makes it easier to define the other directives:
machine((metans, "directive"),
namespace=ns, name="k",
schema=".Ik", handler=".k")
@@ -844,7 +892,7 @@ class ConfigurationMachineTests(_ConformsToIConfigurationContext,
'info': 'yee ha',
'kw': {},
'order': 0,
- })
+ })
class _ConformsToIStackItem(object):
@@ -868,7 +916,7 @@ class _ConformsToIStackItem(object):
class SimpleStackItemTests(_ConformsToIStackItem,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import SimpleStackItem
@@ -894,9 +942,11 @@ class SimpleStackItemTests(_ConformsToIStackItem,
def test_ctor(self):
from zope.interface import Interface
from zope.configuration.config import GroupingContextDecorator
+
class ISchema(Interface):
pass
context = FauxContext()
+
def _handler():
raise AssertionError("should not be called")
_data = {}
@@ -916,24 +966,29 @@ class SimpleStackItemTests(_ConformsToIStackItem,
def test_finish_handler_returns_no_actions(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
name = Text(required=True)
context = FauxContext()
+
def _handler(context, **kw):
return ()
_data = {'name': 'NAME'}
ssi = self._makeOne(context, _handler, 'INFO', ISchema, _data)
- ssi.finish() # noraise
+ ssi.finish() # noraise
self.assertEqual(context.actions, [])
def test_finish_handler_returns_oldstyle_actions(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
name = Text(required=True)
context = FauxContext()
+
def _action(context, **kw):
raise AssertionError("should not be called")
+
def _handler(context, **kw):
return [(None, _action)]
_data = {'name': 'NAME'}
@@ -947,16 +1002,19 @@ class SimpleStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': 'INFO',
'order': 0,
- }])
+ }])
def test_finish_handler_returns_newstyle_actions(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
name = Text(required=True)
context = FauxContext()
+
def _action(context, **kw):
raise AssertionError("should not be called")
+
def _handler(context, **kw):
return [{'discriminator': None, 'callable': _action}]
_data = {'name': 'NAME'}
@@ -970,13 +1028,12 @@ class SimpleStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': 'INFO',
'order': 0,
- }])
-
+ }])
class RootStackItemTests(_ConformsToIStackItem,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import RootStackItem
@@ -989,6 +1046,7 @@ class RootStackItemTests(_ConformsToIStackItem,
def test_contained_context_factory_fails(self):
from zope.configuration.exceptions import ConfigurationError
+
class _Context(object):
def factory(self, context, name):
"does nothing"
@@ -999,9 +1057,11 @@ class RootStackItemTests(_ConformsToIStackItem,
def test_contained_context_factory_normal(self):
_called_with = []
_adapter = object()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return _adapter
+
class _Context(object):
def factory(self, context, name):
return _factory
@@ -1013,12 +1073,12 @@ class RootStackItemTests(_ConformsToIStackItem,
def test_finish(self):
rsi = self._makeOne()
- rsi.finish() #noraise
+ rsi.finish() # noraise
class GroupingStackItemTests(_ConformsToIStackItem,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import GroupingStackItem
@@ -1032,16 +1092,21 @@ class GroupingStackItemTests(_ConformsToIStackItem,
def test_contained_context_before_returns_oldstyle_actions(self):
_called_with = []
_adapter = object()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return _adapter
+
def _action(*args, **kw):
raise AssertionError("should not be called")
+
class _Context(FauxContext):
def factory(self, context, name):
return _factory
+
def before(self):
return [(None, _action)]
+
def after(self):
return ()
context = _Context()
@@ -1058,25 +1123,31 @@ class GroupingStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': None,
'order': 0,
- })
- rsi.finish() # doesn't re-do the 'before' dance
+ })
+ rsi.finish() # doesn't re-do the 'before' dance
self.assertEqual(len(context.actions), 1)
def test_contained_context_before_returns_newstyle_actions(self):
_called_with = []
_adapter = object()
+
def _factory(context, data, info):
_called_with.append((context, data, info))
return _adapter
+
def _before(*args, **kw):
raise AssertionError("should not be called")
+
def _after(*args, **kw):
raise AssertionError("should not be called")
+
class _Context(FauxContext):
def factory(self, context, name):
return _factory
+
def before(self):
return [{'discriminator': None, 'callable': _before}]
+
def after(self):
return [{'discriminator': None, 'callable': _after}]
context = _Context()
@@ -1085,32 +1156,35 @@ class GroupingStackItemTests(_ConformsToIStackItem,
self.assertTrue(adapter is _adapter)
self.assertEqual(_called_with, [(context, {'a': 'b'}, 'INFO')])
self.assertEqual(len(context.actions), 1)
- self.assertEqual(context.actions[0], # no GSI to add extras
+ self.assertEqual(context.actions[0], # no GSI to add extras
{'discriminator': None,
'callable': _before,
- })
- rsi.finish() # doesn't re-do the 'before' dance
+ })
+ rsi.finish() # doesn't re-do the 'before' dance
self.assertEqual(len(context.actions), 2)
self.assertEqual(context.actions[1],
{'discriminator': None,
'callable': _after,
- })
+ })
def test_finish_calls_before_if_not_already_called(self):
def _before(*args, **kw):
raise AssertionError("should not be called")
+
def _after(*args, **kw):
raise AssertionError("should not be called")
+
class _Context(FauxContext):
def before(self):
return [(None, _before)]
+
def after(self):
return [(None, _after)]
context = _Context()
rsi = self._makeOne(context)
rsi.finish()
self.assertEqual(len(context.actions), 2)
- self.assertEqual(context.actions[0], # no GSI to add extras
+ self.assertEqual(context.actions[0], # no GSI to add extras
{'discriminator': None,
'callable': _before,
'args': (),
@@ -1118,7 +1192,7 @@ class GroupingStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': None,
'order': 0,
- })
+ })
self.assertEqual(context.actions[1],
{'discriminator': None,
'callable': _after,
@@ -1127,12 +1201,12 @@ class GroupingStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': None,
'order': 0,
- })
+ })
class ComplexStackItemTests(_ConformsToIStackItem,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import ComplexStackItem
@@ -1152,12 +1226,15 @@ class ComplexStackItemTests(_ConformsToIStackItem,
def _makeMeta(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
name = Text()
+
class FauxMeta(dict):
schema = ISchema
_handler_args = None
_handler = object()
+
def handler(self, newcontext, **kw):
self._handler_kwargs = kw
return self._handler
@@ -1189,8 +1266,10 @@ class ComplexStackItemTests(_ConformsToIStackItem,
from zope.configuration.config import SimpleStackItem
NS = 'http://namespace.example.com/'
NAME = 'testing'
+
class ISubSchema(Interface):
pass
+
class WithName(object):
def testing(self, *args):
raise AssertionError("should not be called")
@@ -1213,7 +1292,7 @@ class ComplexStackItemTests(_ConformsToIStackItem,
context = FauxContext()
_data = {'name': 'NAME'}
csi = self._makeOne(meta, context, _data, 'INFO')
- csi.finish() #noraise
+ csi.finish() # noraise
self.assertEqual(len(context.actions), 0)
def test_finish_handler_raises_AE_for___call__(self):
@@ -1224,7 +1303,7 @@ class ComplexStackItemTests(_ConformsToIStackItem,
context = FauxContext()
_data = {'name': 'NAME'}
csi = self._makeOne(meta, context, _data, 'INFO')
- csi.finish() #noraise
+ csi.finish() # noraise
self.assertEqual(len(context.actions), 0)
def test_finish_handler_raises_AE_for_other(self):
@@ -1241,6 +1320,7 @@ class ComplexStackItemTests(_ConformsToIStackItem,
def test_finish_handler_returns_oldstyle_actions(self):
def _action():
raise AssertionError("should not be called")
+
def _handler():
return [(None, _action)]
meta = self._makeMeta()
@@ -1258,11 +1338,12 @@ class ComplexStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': 'INFO',
'order': 0,
- })
+ })
def test_finish_handler_returns_newstyle_actions(self):
def _action():
raise AssertionError("should not be called")
+
def _handler():
return [{'discriminator': None, 'callable': _action}]
meta = self._makeMeta()
@@ -1280,7 +1361,7 @@ class ComplexStackItemTests(_ConformsToIStackItem,
'includepath': (),
'info': 'INFO',
'order': 0,
- })
+ })
class _ConformsToIGroupingContext(object):
@@ -1305,7 +1386,7 @@ class _ConformsToIGroupingContext(object):
class GroupingContextDecoratorTests(_ConformsToIConfigurationContext,
_ConformsToIGroupingContext,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import GroupingContextDecorator
@@ -1314,7 +1395,7 @@ class GroupingContextDecoratorTests(_ConformsToIConfigurationContext,
def _makeOne(self, context=None, **kw):
if context is None:
context = FauxContext()
- context.package = None #appease IConfigurationContext
+ context.package = None # appease IConfigurationContext
instance = self._getTargetClass()(context, **kw)
return instance
@@ -1339,11 +1420,11 @@ class GroupingContextDecoratorTests(_ConformsToIConfigurationContext,
def test_before(self):
gcd = self._makeOne()
- gcd.before() #noraise
+ gcd.before() # noraise
def test_after(self):
gcd = self._makeOne()
- gcd.after() #noraise
+ gcd.after() # noraise
class _ConformsToIDirectivesContext(object):
@@ -1367,17 +1448,16 @@ class _ConformsToIDirectivesContext(object):
class DirectivesHandlerTests(_ConformsToIDirectivesContext,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import DirectivesHandler
return DirectivesHandler
- def _makeOne(self, context=None):
- if context is None:
- context = FauxContext()
- context.package = None #appease IConfigurationContext
- context.namespace = None #appease IDirectivesInfo
+ def _makeOne(self):
+ context = FauxContext()
+ context.package = None # appease IConfigurationContext
+ context.namespace = None # appease IDirectivesInfo
instance = self._getTargetClass()(context)
return instance
@@ -1394,8 +1474,10 @@ class Test_defineSimpleDirective(unittest.TestCase):
FauxContext.__init__(self)
self._registered = []
self._documented = []
+
def register(self, usedIn, name, factory):
self._registered.append((usedIn, name, factory))
+
def document(self, name, schema, usedIn, handler, info):
self._documented.append((name, schema, usedIn, handler, info))
return _Context()
@@ -1403,6 +1485,7 @@ class Test_defineSimpleDirective(unittest.TestCase):
def test_defaults(self):
from zope.interface import Interface
from zope.configuration.interfaces import IConfigurationContext as ICC
+
class ISchema(Interface):
pass
NS = 'http://namespace.example.com/'
@@ -1410,6 +1493,7 @@ class Test_defineSimpleDirective(unittest.TestCase):
context = self._makeContext()
context.namespace = NS
context.info = 'INFO'
+
def _handler():
raise AssertionError("should not be called")
@@ -1431,8 +1515,10 @@ class Test_defineSimpleDirective(unittest.TestCase):
def test_explicit_w_star_namespace(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/'
@@ -1440,6 +1526,7 @@ class Test_defineSimpleDirective(unittest.TestCase):
context = self._makeContext()
context.namespace = NS
context.info = 'INFO'
+
def _handler():
raise AssertionError("should not be called")
@@ -1473,8 +1560,10 @@ class Test_defineGroupingDirective(unittest.TestCase):
FauxContext.__init__(self)
self._registered = []
self._documented = []
+
def register(self, usedIn, name, factory):
self._registered.append((usedIn, name, factory))
+
def document(self, name, schema, usedIn, handler, info):
self._documented.append((name, schema, usedIn, handler, info))
return _Context()
@@ -1483,6 +1572,7 @@ class Test_defineGroupingDirective(unittest.TestCase):
from zope.interface import Interface
from zope.schema import Text
from zope.configuration.interfaces import IConfigurationContext as ICC
+
class ISchema(Interface):
arg = Text()
NS = 'http://namespace.example.com/'
@@ -1492,6 +1582,7 @@ class Test_defineGroupingDirective(unittest.TestCase):
context.info = 'INFO'
newcontext = FauxContext()
_called_with = []
+
def _handler(context, **kw):
_called_with.append((context, kw))
return newcontext
@@ -1515,8 +1606,10 @@ class Test_defineGroupingDirective(unittest.TestCase):
def test_explicit_w_star_namespace(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
arg = Text()
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/'
@@ -1526,6 +1619,7 @@ class Test_defineGroupingDirective(unittest.TestCase):
context.info = 'INFO'
newcontext = FauxContext()
_called_with = []
+
def _handler(context, **kw):
_called_with.append((context, kw))
return newcontext
@@ -1569,7 +1663,7 @@ class _ConformsToIComplexDirectiveContext(object):
class ComplexDirectiveDefinitionTests(_ConformsToIComplexDirectiveContext,
unittest.TestCase,
- ):
+ ):
def _getTargetClass(self):
from zope.configuration.config import ComplexDirectiveDefinition
@@ -1595,14 +1689,17 @@ class ComplexDirectiveDefinitionTests(_ConformsToIComplexDirectiveContext,
def test_before(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
arg = Text()
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/'
NAME = 'testing'
_handled = []
_csi_handler = object()
+
def _handler(context, **kw):
_handled.append((context, kw))
return _csi_handler
@@ -1610,10 +1707,12 @@ class ComplexDirectiveDefinitionTests(_ConformsToIComplexDirectiveContext,
handler=_handler, usedIn=IUsedIn)
context.info = 'INFO'
_registered = []
+
def _register(*args):
_registered.append(args)
context.register = _register
_documented = []
+
def _document(*args):
_documented.append(args)
context.document = _document
@@ -1649,6 +1748,7 @@ class Test_subdirective(unittest.TestCase):
def __init__(self):
self.context = {}
self._documented = []
+
def document(self, *args):
self._documented.append(args)
context = _Context()
@@ -1663,10 +1763,13 @@ class Test_subdirective(unittest.TestCase):
def test_wo_handler_attribute(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISubSchema(Interface):
arg = Text()
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/'
@@ -1690,12 +1793,16 @@ class Test_subdirective(unittest.TestCase):
def test_w_handler_attribute(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISubSchema(Interface):
arg = Text()
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
+
class Handler(object):
sub = object()
NS = 'http://namespace.example.com/'
@@ -1729,6 +1836,7 @@ class Test_provides(unittest.TestCase):
def test_w_single(self):
_provided = []
+
def _provideFeature(feature):
_provided.append(feature)
context = FauxContext()
@@ -1745,6 +1853,7 @@ class Test_toargs(unittest.TestCase):
def test_w_empty_schema_no_data(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
context = FauxContext()
@@ -1753,6 +1862,7 @@ class Test_toargs(unittest.TestCase):
def test_w_empty_schema_w_data_no_kwargs_allowed(self):
from zope.configuration.exceptions import ConfigurationError
from zope.interface import Interface
+
class ISchema(Interface):
pass
context = FauxContext()
@@ -1763,6 +1873,7 @@ class Test_toargs(unittest.TestCase):
def test_w_empty_schema_w_data_w_kwargs_allowed(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
ISchema.setTaggedValue('keyword_arguments', True)
@@ -1773,6 +1884,7 @@ class Test_toargs(unittest.TestCase):
def test_w_keyword_sub(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
for_ = Text()
context = FauxContext()
@@ -1783,6 +1895,7 @@ class Test_toargs(unittest.TestCase):
from zope.interface import Interface
from zope.schema import Text
from zope.configuration.exceptions import ConfigurationError
+
class ISchema(Interface):
no_default = Text()
context = FauxContext()
@@ -1805,6 +1918,7 @@ class Test_toargs(unittest.TestCase):
def test_w_field_missing_but_default(self):
from zope.interface import Interface
from zope.schema import Text
+
class ISchema(Interface):
w_default = Text(default=u'default')
context = FauxContext()
@@ -1815,6 +1929,7 @@ class Test_toargs(unittest.TestCase):
from zope.interface import Interface
from zope.schema import Int
from zope.configuration.exceptions import ConfigurationError
+
class ISchema(Interface):
count = Int(min=0)
context = FauxContext()
@@ -1832,6 +1947,7 @@ class Test_toargs(unittest.TestCase):
"TooSmall: (-1, 0)",
exception_str)
+
class Test_expand_action(unittest.TestCase):
def _callFUT(self, *args, **kw):
@@ -1847,7 +1963,7 @@ class Test_expand_action(unittest.TestCase):
'includepath': (),
'info': None,
'order': 0,
- })
+ })
def test_explicit_no_extra(self):
def _callable():
@@ -1855,7 +1971,7 @@ class Test_expand_action(unittest.TestCase):
self.assertEqual(self._callFUT(('a', 1, None),
_callable, ('b', 2), {'c': None},
('p', 'q/r'), 'INFO', 42,
- ),
+ ),
{'discriminator': ('a', 1, None),
'callable': _callable,
'args': ('b', 2),
@@ -1863,7 +1979,7 @@ class Test_expand_action(unittest.TestCase):
'includepath': ('p', 'q/r'),
'info': 'INFO',
'order': 42,
- })
+ })
def test_explicit_w_extra(self):
def _callable():
@@ -1872,7 +1988,7 @@ class Test_expand_action(unittest.TestCase):
_callable, ('b', 2), {'c': None},
('p', 'q/r'), 'INFO', 42,
foo='bar', baz=None,
- ),
+ ),
{'discriminator': ('a', 1, None),
'callable': _callable,
'args': ('b', 2),
@@ -1882,7 +1998,7 @@ class Test_expand_action(unittest.TestCase):
'order': 42,
'foo': 'bar',
'baz': None,
- })
+ })
class Test_resolveConflicts(unittest.TestCase):
@@ -1914,12 +2030,16 @@ class Test_resolveConflicts(unittest.TestCase):
def test_wo_discriminator_clash(self):
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
+
def _c():
raise AssertionError("should not be called")
+
def _d():
raise AssertionError("should not be called")
actions = [
@@ -1933,8 +2053,10 @@ class Test_resolveConflicts(unittest.TestCase):
def test_w_resolvable_discriminator_clash(self):
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
actions = [
@@ -1947,8 +2069,10 @@ class Test_resolveConflicts(unittest.TestCase):
def test_w_non_resolvable_discriminator_clash_different_paths(self):
from zope.configuration.config import ConfigurationConflictError
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
actions = [
@@ -1962,8 +2086,10 @@ class Test_resolveConflicts(unittest.TestCase):
def test_w_non_resolvable_discriminator_clash_same_path(self):
from zope.configuration.config import ConfigurationConflictError
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
actions = [
@@ -1977,8 +2103,10 @@ class Test_resolveConflicts(unittest.TestCase):
def test_configuration_conflict_error_has_readable_exception(self):
from zope.configuration.config import ConfigurationConflictError
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
actions = [
@@ -2003,12 +2131,16 @@ class Test_resolveConflicts(unittest.TestCase):
def test_wo_discriminators_final_sorting_order(self):
from zope.configuration.config import expand_action
+
def _a():
raise AssertionError("should not be called")
+
def _b():
raise AssertionError("should not be called")
+
def _c():
raise AssertionError("should not be called")
+
def _d():
raise AssertionError("should not be called")
actions = [
@@ -2024,5 +2156,6 @@ class Test_resolveConflicts(unittest.TestCase):
class FauxContext(object):
def __init__(self):
self.actions = []
+
def action(self, **kw):
self.actions.append(kw)
diff --git a/src/zope/configuration/tests/test_docs.py b/src/zope/configuration/tests/test_docs.py
index 4d10540..4cb8727 100644
--- a/src/zope/configuration/tests/test_docs.py
+++ b/src/zope/configuration/tests/test_docs.py
@@ -47,6 +47,7 @@ optionflags = (
| doctest.IGNORE_EXCEPTION_DETAIL
)
+
def test_suite():
# zope.testrunner
suite = unittest.TestSuite()
diff --git a/src/zope/configuration/tests/test_docutils.py b/src/zope/configuration/tests/test_docutils.py
index 7583369..22fb36d 100644
--- a/src/zope/configuration/tests/test_docutils.py
+++ b/src/zope/configuration/tests/test_docutils.py
@@ -30,13 +30,13 @@ class Test_wrap(unittest.TestCase):
def test_single_paragraphs(self):
self.assertEqual(
- self._callFUT('abcde fghij klmno pqrst uvwxy', 10, 3),
- ' abcde\n fghij\n klmno\n pqrst\n uvwxy\n\n')
+ self._callFUT('abcde fghij klmno pqrst uvwxy', 10, 3),
+ ' abcde\n fghij\n klmno\n pqrst\n uvwxy\n\n')
def test_multiple_paragraphs(self):
self.assertEqual(
- self._callFUT('abcde fghij klmno\n\npqrst uvwxy', 10, 3),
- ' abcde\n fghij\n klmno\n\n pqrst\n uvwxy\n\n')
+ self._callFUT('abcde fghij klmno\n\npqrst uvwxy', 10, 3),
+ ' abcde\n fghij\n klmno\n\n pqrst\n uvwxy\n\n')
class Test_makeDocStructures(unittest.TestCase):
@@ -59,25 +59,30 @@ class Test_makeDocStructures(unittest.TestCase):
def test_wo_parents(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
NS = 'http://namespace.example.com/main'
NS2 = 'http://namespace.example.com/other'
+
def _one():
raise AssertionError("should not be called")
+
def _two():
raise AssertionError("should not be called")
+
def _three():
raise AssertionError("should not be called")
context = self._makeContext()
context._docRegistry.append(
- ((NS, 'one'), ISchema, IUsedIn, _one, 'ONE', None))
+ ((NS, 'one'), ISchema, IUsedIn, _one, 'ONE', None))
context._docRegistry.append(
- ((NS2, 'two'), ISchema, IUsedIn, _two, 'TWO', None))
+ ((NS2, 'two'), ISchema, IUsedIn, _two, 'TWO', None))
context._docRegistry.append(
- ((NS, 'three'), ISchema, IUsedIn, _three, 'THREE', None))
+ ((NS, 'three'), ISchema, IUsedIn, _three, 'THREE', None))
namespaces, subdirs = self._callFUT(context)
self.assertEqual(len(namespaces), 2)
self.assertEqual(namespaces[NS], {'one': (ISchema, _one, 'ONE'),
@@ -87,19 +92,25 @@ class Test_makeDocStructures(unittest.TestCase):
def test_w_parents(self):
from zope.interface import Interface
+
class ISchema(Interface):
pass
+
class IUsedIn(Interface):
pass
PNS = 'http://namespace.example.com/parent'
NS = 'http://namespace.example.com/main'
NS2 = 'http://namespace.example.com/other'
+
def _one():
raise AssertionError("should not be called")
+
def _two():
raise AssertionError("should not be called")
+
def _three():
raise AssertionError("should not be called")
+
class Parent(object):
namespace = PNS
name = 'parent'
@@ -108,11 +119,11 @@ class Test_makeDocStructures(unittest.TestCase):
parent2.name = 'parent2'
context = self._makeContext()
context._docRegistry.append(
- ((NS, 'one'), ISchema, IUsedIn, _one, 'ONE', parent1))
+ ((NS, 'one'), ISchema, IUsedIn, _one, 'ONE', parent1))
context._docRegistry.append(
- ((NS2, 'two'), ISchema, IUsedIn, _two, 'TWO', parent2))
+ ((NS2, 'two'), ISchema, IUsedIn, _two, 'TWO', parent2))
context._docRegistry.append(
- ((NS, 'three'), ISchema, IUsedIn, _three, 'THREE', parent1))
+ ((NS, 'three'), ISchema, IUsedIn, _three, 'THREE', parent1))
namespaces, subdirs = self._callFUT(context)
self.assertEqual(len(namespaces), 0)
self.assertEqual(len(subdirs), 2)
diff --git a/src/zope/configuration/tests/test_fields.py b/src/zope/configuration/tests/test_fields.py
index bbcc7f0..8242211 100644
--- a/src/zope/configuration/tests/test_fields.py
+++ b/src/zope/configuration/tests/test_fields.py
@@ -17,6 +17,7 @@ import unittest
# pylint:disable=protected-access
+
class _ConformsToIFromUnicode(object):
def _getTargetClass(self):
@@ -48,7 +49,7 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
def test__validate_wo_value_type(self):
go = self._makeOne(value_type=None)
for value in [0, 0.0, (), [], set(), frozenset(), u'', b'']:
- go._validate(value) #noraise
+ go._validate(value) # noraise
def test__validate_w_value_type(self):
from zope.schema import Text
@@ -66,8 +67,10 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
def test_fromUnicode_w_resolve_fails(self):
from zope.schema import ValidationError
from zope.configuration.config import ConfigurationError
+
class Context(object):
_resolved = None
+
def resolve(self, name):
self._resolved = name
raise ConfigurationError()
@@ -83,8 +86,10 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
def test_fromUnicode_w_resolve_success(self):
_target = object()
+
class Context(object):
_resolved = None
+
def resolve(self, name):
self._resolved = name
return _target
@@ -97,8 +102,10 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
def test_fromUnicode_w_resolve_dots(self):
_target = object()
+
class Context(object):
_resolved = None
+
def resolve(self, name):
self._resolved = name
return _target
@@ -120,8 +127,10 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
from zope.schema import Text
from zope.schema import ValidationError
_target = object()
+
class Context(object):
_resolved = None
+
def resolve(self, name):
self._resolved = name
return _target
@@ -134,7 +143,6 @@ class GlobalObjectTests(unittest.TestCase, _ConformsToIFromUnicode):
def test_fromUnicode_rejects_slash(self):
from zope.schema import ValidationError
- _target = object()
field = self._makeOne()
with self.assertRaises(ValidationError) as exc:
field.fromUnicode('foo/bar')
@@ -157,6 +165,7 @@ class GlobalInterfaceTests(unittest.TestCase, _ConformsToIFromUnicode):
gi = self._makeOne()
self.assertIsInstance(gi.value_type, InterfaceField)
+
class TokensTests(unittest.TestCase, _ConformsToIFromUnicode):
def _getTargetClass(self):
@@ -205,6 +214,7 @@ class PathTests(unittest.TestCase, _ConformsToIFromUnicode):
def test_fromUnicode_relative(self):
class Context(object):
_pathed = None
+
def path(self, value):
self._pathed = value
return '/hard/coded'
@@ -261,8 +271,10 @@ class MessageIDTests(unittest.TestCase, _ConformsToIFromUnicode):
class Info(object):
file = 'test_file'
line = 42
+
class Context(object):
i18n_domain = domain
+
def __init__(self):
self.i18n_strings = {}
self.info = Info()
diff --git a/src/zope/configuration/tests/test_name.py b/src/zope/configuration/tests/test_name.py
index d41b2d7..6fd1b99 100644
--- a/src/zope/configuration/tests/test_name.py
+++ b/src/zope/configuration/tests/test_name.py
@@ -65,6 +65,7 @@ class Test_resolve(unittest.TestCase):
'zope.configuration.tests.samplepackage.NamedForClass.'),
NamedForClass)
+
class Test_getNormalizedName(unittest.TestCase):
def _callFUT(self, *args, **kw):
diff --git a/src/zope/configuration/tests/test_xmlconfig.py b/src/zope/configuration/tests/test_xmlconfig.py
index 3cb1270..6d180b8 100644
--- a/src/zope/configuration/tests/test_xmlconfig.py
+++ b/src/zope/configuration/tests/test_xmlconfig.py
@@ -28,6 +28,7 @@ BVALUE = u'bvalue'
# pylint:disable=protected-access
+
class ZopeXMLConfigurationErrorTests(unittest.TestCase):
maxDiff = None
@@ -46,7 +47,6 @@ class ZopeXMLConfigurationErrorTests(unittest.TestCase):
)
-
class ZopeSAXParseExceptionTests(unittest.TestCase):
maxDiff = None
@@ -150,7 +150,7 @@ class ConfigurationHandlerTests(unittest.TestCase):
{ZCML_CONDITION: 'have nonesuch',
(None, A): AVALUE,
(None, B): BVALUE,
- })
+ })
self.assertEqual(handler.ignore_depth, 1)
def test_startElementNS_w_ignore_depth_already_set(self):
@@ -163,7 +163,7 @@ class ConfigurationHandlerTests(unittest.TestCase):
{(XXX, SPLAT): SPLATV,
(None, A): AVALUE,
(None, B): BVALUE,
- })
+ })
self.assertEqual(handler.ignore_depth, 2)
def _check_elementNS_context_raises(self, raises, catches,
@@ -174,8 +174,10 @@ class ConfigurationHandlerTests(unittest.TestCase):
def end(self, *args):
raise raises("xxx")
begin = end
+
class Info(object):
_line = _col = None
+
def end(self, line, col):
self._line, self._col = line, col
context = ErrorContext()
@@ -190,7 +192,8 @@ class ConfigurationHandlerTests(unittest.TestCase):
meth(*meth_args)
return exc.exception, info
- def _check_startElementNS_context_begin_raises(self, raises, catches, testing=False):
+ def _check_startElementNS_context_begin_raises(
+ self, raises, catches, testing=False):
return self._check_elementNS_context_raises(
raises, catches, testing,
meth='startElementNS',
@@ -199,13 +202,13 @@ class ConfigurationHandlerTests(unittest.TestCase):
{(XXX, SPLAT): SPLATV,
(None, A): AVALUE,
(None, B): BVALUE,
- })
+ })
)
def test_startElementNS_context_begin_raises_wo_testing(self):
from zope.configuration.xmlconfig import ZopeXMLConfigurationError
- raised, _ = self._check_startElementNS_context_begin_raises(AttributeError,
- ZopeXMLConfigurationError)
+ raised, _ = self._check_startElementNS_context_begin_raises(
+ AttributeError, ZopeXMLConfigurationError)
info = raised.info
self.assertEqual(info.file, 'tests//sample.zcml')
self.assertEqual(info.line, 7)
@@ -222,7 +225,6 @@ class ConfigurationHandlerTests(unittest.TestCase):
self._check_startElementNS_context_begin_raises(Bex,
Bex)
-
def test_startElementNS_normal(self):
# Integration test of startElementNS / endElementNS pair.
context = FauxContext()
@@ -234,7 +236,7 @@ class ConfigurationHandlerTests(unittest.TestCase):
{(XXX, SPLAT): SPLATV,
(None, A): AVALUE,
(None, B): BVALUE,
- })
+ })
self.assertEqual(context.info.file, 'tests//sample.zcml')
self.assertEqual(context.info.line, 1)
self.assertEqual(context.info.column, 1)
@@ -252,14 +254,15 @@ class ConfigurationHandlerTests(unittest.TestCase):
handler.endElementNS((NS, FOO), FOO)
self.assertEqual(handler.ignore_depth, 0)
- def _check_endElementNS_context_end_raises(self, raises, catches, testing=False):
+ def _check_endElementNS_context_end_raises(
+ self, raises, catches, testing=False):
return self._check_elementNS_context_raises(raises, catches, testing)
def test_endElementNS_context_end_raises_wo_testing(self):
from zope.configuration.xmlconfig import ZopeXMLConfigurationError
- raised, info = self._check_endElementNS_context_end_raises(AttributeError,
- ZopeXMLConfigurationError)
+ raised, info = self._check_endElementNS_context_end_raises(
+ AttributeError, ZopeXMLConfigurationError)
self.assertIs(raised.info, info)
self.assertEqual(raised.info._line, 7)
@@ -365,6 +368,7 @@ class ConfigurationHandlerTests(unittest.TestCase):
def test_endElementNS_normal(self):
class Info(object):
_line = _col = None
+
def end(self, line, col):
self._line, self._col = line, col
context = FauxContext()
@@ -413,11 +417,13 @@ class Test_processxmlfile(unittest.TestCase):
context.execute_actions()
data = foo.data.pop()
self.assertEqual(data.args, (('x', (b'blah')), ('y', 0)))
- self.assertEqual(clean_info_path(repr(data.info)),
- 'File "tests/samplepackage/configure.zcml", line 12.2-12.29')
- self.assertEqual(clean_info_path(str(data.info)),
- 'File "tests/samplepackage/configure.zcml", line 12.2-12.29\n'
- + ' <test:foo x="blah" y="0" />')
+ self.assertEqual(
+ clean_info_path(repr(data.info)),
+ 'File "tests/samplepackage/configure.zcml", line 12.2-12.29')
+ self.assertEqual(
+ clean_info_path(str(data.info)),
+ 'File "tests/samplepackage/configure.zcml", line 12.2-12.29\n'
+ ' <test:foo x="blah" y="0" />')
self.assertEqual(data.package, None)
self.assertEqual(data.basepath, None)
@@ -476,7 +482,7 @@ class Test_include(unittest.TestCase):
context._seen_files.add(fqn)
logger = LoggerStub()
with _Monkey(xmlconfig, logger=logger):
- self._callFUT(context) #skips
+ self._callFUT(context) # skips
self.assertEqual(len(logger.debugs), 0)
self.assertEqual(len(context.actions), 0)
@@ -662,11 +668,12 @@ class Test_includeOverrides(unittest.TestCase):
context.package = tests
# dummy action, path from "previous" include
context.includepath = (fqp,)
+
def _callable():
raise AssertionError("should not be called")
context.actions.append({'discriminator': None,
'callable': _callable,
- })
+ })
fqn = _packageFile(tests, 'simple.zcml')
logger = LoggerStub()
with _Monkey(xmlconfig, logger=logger):
@@ -873,7 +880,7 @@ class XMLConfigTests(unittest.TestCase):
xc = self._makeOne(path)
self.assertEqual(len(logger.debugs), 1)
self.assertEqual(logger.debugs[0], ('include %s', (path,), {}))
- self.assertEqual(len(foo.data), 0) # no execut_actions
+ self.assertEqual(len(foo.data), 0) # no execut_actions
self.assertEqual(len(xc.context.actions), 1)
action = xc.context.actions[0]
self.assertEqual(action['discriminator'],
@@ -890,7 +897,7 @@ class XMLConfigTests(unittest.TestCase):
xc = self._makeOne(fqn)
self.assertEqual(len(logger.debugs), 1)
self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {}))
- self.assertEqual(len(foo.data), 0) # no execut_actions
+ self.assertEqual(len(foo.data), 0) # no execut_actions
self.assertEqual(len(xc.context.actions), 1)
action = xc.context.actions[0]
self.assertEqual(action['discriminator'],
@@ -907,7 +914,7 @@ class XMLConfigTests(unittest.TestCase):
xc = self._makeOne("configure.zcml", samplepackage)
self.assertEqual(len(logger.debugs), 1)
self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {}))
- self.assertEqual(len(foo.data), 0) # no execut_actions
+ self.assertEqual(len(foo.data), 0) # no execut_actions
self.assertEqual(len(xc.context.actions), 1)
action = xc.context.actions[0]
self.assertEqual(action['discriminator'],
@@ -926,7 +933,7 @@ class XMLConfigTests(unittest.TestCase):
self.assertEqual(len(logger.debugs), 1)
self.assertEqual(logger.debugs[0], ('include %s', (fqn,), {}))
self.assertEqual(len(foo.data), 0)
- xc() # call to process the actions
+ xc() # call to process the actions
self.assertEqual(len(foo.data), 1)
data = foo.data.pop(0)
self.assertEqual(data.args, (('x', (b'blah')), ('y', 0)))
@@ -939,7 +946,6 @@ class XMLConfigTests(unittest.TestCase):
self.assertEqual(data.info.ecolumn, 29)
-
class Test_xmlconfig(unittest.TestCase):
def setUp(self):
@@ -963,6 +969,7 @@ class Test_xmlconfig(unittest.TestCase):
from zope.configuration import xmlconfig
from zope.configuration.tests import samplepackage
from zope.configuration.tests.samplepackage import foo
+
def _assertTestingFalse(func):
def _wrapper(*args, **kw):
assert not kw['testing']
@@ -991,6 +998,7 @@ class Test_xmlconfig(unittest.TestCase):
from zope.configuration import xmlconfig
from zope.configuration.tests import samplepackage
from zope.configuration.tests.samplepackage import foo
+
def _assertTestingTrue(func):
def _wrapper(*args, **kw):
assert kw['testing']
@@ -1038,6 +1046,7 @@ class Test_testxmlconfig(unittest.TestCase):
from zope.configuration import xmlconfig
from zope.configuration.tests import samplepackage
from zope.configuration.tests.samplepackage import foo
+
def _assertTestingTrue(func):
def _wrapper(*args, **kw):
assert kw['testing']
@@ -1062,14 +1071,16 @@ class Test_testxmlconfig(unittest.TestCase):
self.assertEqual(data.info.ecolumn, 29)
-
class FauxLocator(object):
def __init__(self, file, line, column):
self.file, self.line, self.column = file, line, column
+
def getSystemId(self):
return self.file
+
def getLineNumber(self):
return self.line
+
def getColumnNumber(self):
return self.column
@@ -1078,15 +1089,20 @@ class FauxContext(object):
includepath = ()
_features = ()
_end_called = False
+
def setInfo(self, info):
self.info = info
+
def getInfo(self):
return self.info
+
def begin(self, name, data, info):
self.begin_args = name, data
self.info = info
+
def end(self):
self._end_called = 1
+
def hasFeature(self, feature):
return feature in self._features
@@ -1095,6 +1111,7 @@ def path(*p):
import os
return os.path.join(os.path.dirname(__file__), *p)
+
def clean_info_path(s):
import os
part1 = s[:6]
@@ -1102,7 +1119,8 @@ def clean_info_path(s):
part2 = part2[part2.rfind("tests"):]
part2 = part2.replace(os.sep, '/')
part3 = s[s.find('"', 6):].rstrip()
- return part1+part2+part3
+ return part1 + part2 + part3
+
def clean_path(s):
import os
@@ -1110,6 +1128,7 @@ def clean_path(s):
s = s.replace(os.sep, '/')
return s
+
def clean_actions(actions):
return [
{
@@ -1120,15 +1139,16 @@ def clean_actions(actions):
for action in actions
]
+
def clean_text_w_paths(error):
r = []
for line in str(error).split("\n"):
line = line.rstrip()
if not line:
continue
- l = line.find('File "')
- if l >= 0:
- line = line[:l] + clean_info_path(line[l:])
+ l_ = line.find('File "')
+ if l_ >= 0:
+ line = line[:l_] + clean_info_path(line[l_:])
r.append(line)
return '\n'.join(r)
@@ -1137,6 +1157,7 @@ def _packageFile(package, filename):
import os
return os.path.join(os.path.dirname(package.__file__), filename)
+
class _Monkey(object):
def __init__(self, module, **replacements):
@@ -1155,7 +1176,7 @@ class _Monkey(object):
for k in self.replacements:
if k in self.orig:
setattr(self.module, k, self.orig[k])
- else: # pragma: no cover
+ else: # pragma: no cover
delattr(self.module, k)
diff --git a/src/zope/configuration/tests/victim.py b/src/zope/configuration/tests/victim.py
index fe67828..5f33d5a 100644
--- a/src/zope/configuration/tests/victim.py
+++ b/src/zope/configuration/tests/victim.py
@@ -1,2 +1,2 @@
from __future__ import absolute_import
-from zope.configuration.tests import bad # pylint:disable=unused-import
+from zope.configuration.tests import bad # pylint:disable=unused-import
diff --git a/src/zope/configuration/xmlconfig.py b/src/zope/configuration/xmlconfig.py
index 4fc0d0d..5a8c586 100644
--- a/src/zope/configuration/xmlconfig.py
+++ b/src/zope/configuration/xmlconfig.py
@@ -95,7 +95,8 @@ class ZopeSAXParseException(ConfigurationWrapperError):
Example
>>> from zope.configuration.xmlconfig import ZopeSAXParseException
- >>> v = ZopeSAXParseException("info", Exception("foo.xml:12:3:Not well formed"))
+ >>> v = ZopeSAXParseException(
+ ... "info", Exception("foo.xml:12:3:Not well formed"))
>>> print(v)
info
Exception: foo.xml:12:3:Not well formed
@@ -168,34 +169,35 @@ class ParserInfo(object):
try:
with open(file) as f:
- lines = f.readlines()[self.line-1:self.eline]
+ lines = f.readlines()[self.line - 1:self.eline]
except IOError:
src = " Could not read source."
else:
ecolumn = self.ecolumn
- if lines[-1][ecolumn:ecolumn+2] == '</': # pragma: no cover
+ if lines[-1][ecolumn:ecolumn + 2] == '</': # pragma: no cover
# We're pointing to the start of an end tag. Try to find
# the end
- l = lines[-1].find('>', ecolumn)
- if l >= 0:
- lines[-1] = lines[-1][:l+1]
- else: # pragma: no cover
- lines[-1] = lines[-1][:ecolumn+1]
+ l_ = lines[-1].find('>', ecolumn)
+ if l_ >= 0:
+ lines[-1] = lines[-1][:l_ + 1]
+ else: # pragma: no cover
+ lines[-1] = lines[-1][:ecolumn + 1]
column = self.column
- if lines[0][:column].strip(): # pragma: no cover
+ if lines[0][:column].strip(): # pragma: no cover
# Remove text before start if it's noy whitespace
lines[0] = lines[0][self.column:]
pad = u' '
blank = u''
try:
- src = blank.join([pad + l for l in lines])
- except UnicodeDecodeError: # pragma: no cover
+ src = blank.join([pad + line for line in lines])
+ except UnicodeDecodeError: # pragma: no cover
# XXX:
# I hope so most internation zcml will use UTF-8 as encoding
# otherwise this code must be made more clever
- src = blank.join([pad + l.decode('utf-8') for l in lines])
+ src = blank.join([pad + line.decode('utf-8')
+ for line in lines])
# unicode won't be printable, at least on my console
src = src.encode('ascii', 'replace')
@@ -260,7 +262,7 @@ class ConfigurationHandler(ContentHandler):
self.locator.getSystemId(),
self.locator.getLineNumber(),
self.locator.getColumnNumber(),
- )
+ )
try:
self.context.begin(name, data, info)
@@ -385,7 +387,7 @@ class ConfigurationHandler(ContentHandler):
info.end(
self.locator.getLineNumber(),
self.locator.getColumnNumber(),
- )
+ )
try:
self.context.end()
@@ -432,7 +434,8 @@ def openInOrPlain(filename):
>>> from zope.configuration.xmlconfig import __file__
>>> from zope.configuration.xmlconfig import openInOrPlain
>>> here = os.path.dirname(__file__)
- >>> path = os.path.join(here, 'tests', 'samplepackage', 'configure.zcml')
+ >>> path = os.path.join(
+ ... here, 'tests', 'samplepackage', 'configure.zcml')
>>> f = openInOrPlain(path)
>>> f.name[-14:]
'configure.zcml'
@@ -558,6 +561,7 @@ def include(_context, file=None, package=None, files=None):
assert _context.stack[-1].context is context
_context.stack.pop()
+
def exclude(_context, file=None, package=None, files=None):
"""Exclude a zcml file
@@ -571,7 +575,6 @@ def exclude(_context, file=None, package=None, files=None):
elif not file:
file = 'configure.zcml'
-
context = GroupingContextDecorator(_context)
if package is not None:
context.package = package
@@ -591,6 +594,7 @@ def exclude(_context, file=None, package=None, files=None):
# processed in the future
context.processFile(path)
+
def includeOverrides(_context, file=None, package=None, files=None):
"""Include zcml file containing overrides.
@@ -624,6 +628,7 @@ def includeOverrides(_context, file=None, package=None, files=None):
_context.actions[nactions:] = newactions
+
def registerCommonDirectives(context):
# We have to use the direct definition functions to define
# a directive for all namespaces.
@@ -643,7 +648,8 @@ def registerCommonDirectives(context):
namespace="*",
schema=IZopeConfigure,
handler=ZopeConfigure,
- )
+ )
+
def file(name, package=None, context=None, execute=True):
"""Execute a zcml file
@@ -660,6 +666,7 @@ def file(name, package=None, context=None, execute=True):
return context
+
def string(s, context=None, name="<string>", execute=True):
"""Execute a zcml string
"""
@@ -682,24 +689,28 @@ def string(s, context=None, name="<string>", execute=True):
_context = None
+
+
def _clearContext():
global _context
_context = ConfigurationMachine()
registerCommonDirectives(_context)
+
def _getContext():
global _context
if _context is None:
_clearContext()
try:
from zope.testing.cleanup import addCleanUp
- except ImportError: # pragma: no cover
+ except ImportError: # pragma: no cover
pass
- else: # pragma: no cover
+ else: # pragma: no cover
addCleanUp(_clearContext)
del addCleanUp
return _context
+
class XMLConfig(object):
"""Provide high-level handling of configuration files.
@@ -714,6 +725,7 @@ class XMLConfig(object):
def __call__(self):
self.context.execute_actions()
+
def xmlconfig(file, testing=False):
context = _getContext()
processxmlfile(file, context, testing=testing)
diff --git a/src/zope/configuration/zopeconfigure.py b/src/zope/configuration/zopeconfigure.py
index 266fd46..26c3b74 100644
--- a/src/zope/configuration/zopeconfigure.py
+++ b/src/zope/configuration/zopeconfigure.py
@@ -113,6 +113,7 @@ __all__ = [
'ZopeConfigure',
]
+
class IZopeConfigure(Interface):
"""The ``zope:configure`` Directive