Commit 7bcfe9ca authored by Tres Seaver's avatar Tres Seaver

Zope2 Interfaces package delenda est\!

parents d47802e4 316abb73
...@@ -28,7 +28,6 @@ from HelpSys.HelpSys import ProductHelp ...@@ -28,7 +28,6 @@ from HelpSys.HelpSys import ProductHelp
from FactoryDispatcher import FactoryDispatcher from FactoryDispatcher import FactoryDispatcher
from DateTime import DateTime from DateTime import DateTime
from Interface.Implements import instancesOfObjectImplements
from zope.interface import implementedBy from zope.interface import implementedBy
import ZClasses # to enable 'PC.registerBaseClass()' import ZClasses # to enable 'PC.registerBaseClass()'
...@@ -183,8 +182,6 @@ class ProductContext: ...@@ -183,8 +182,6 @@ class ProductContext:
interfaces = () interfaces = ()
else: else:
interfaces = tuple(implementedBy(instance_class)) interfaces = tuple(implementedBy(instance_class))
# BBB: Will be removed in Zope 2.11.
interfaces += tuple(instancesOfObjectImplements(instance_class))
Products.meta_types=Products.meta_types+( Products.meta_types=Products.meta_types+(
{ 'name': meta_type or instance_class.meta_type, { 'name': meta_type or instance_class.meta_type,
......
...@@ -26,13 +26,6 @@ import HelpTopic ...@@ -26,13 +26,6 @@ import HelpTopic
_ignore_objects = {} _ignore_objects = {}
try:
import Interface
_ignore_objects.update(Interface.__dict__)
except ImportError:
pass
class APIHelpTopic(HelpTopic.HelpTopic): class APIHelpTopic(HelpTopic.HelpTopic):
""" Provides API documentation. """ Provides API documentation.
""" """
......
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from _Element import Element
class Attribute(Element):
"""Attribute descriptions
"""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IAttribute
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from Interface import Interface
class IReadMapping(Interface):
"""Basic mapping interface
"""
def __getitem__(key):
"""Get a value for a key
A KeyError is raised if there is no value for the key.
"""
def get(key, default=None):
"""Get a value for a key
The default is returned if there is no value for the key.
"""
def has_key(key):
"""Tell if a key exists in the mapping
"""
class IEnumerableMapping(IReadMapping):
"""Mapping objects whose items can be enumerated
"""
def keys():
"""Return the keys of the mapping object
"""
def values():
"""Return the values of the mapping object
"""
def items():
"""Return the items of the mapping object
"""
def __len__():
"""Return the number of items
"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from operator import __getitem__
def testIReadMapping(self, inst, state, absent):
for key in state:
self.assertEqual(inst[key], state[key])
self.assertEqual(inst.get(key, None), state[key])
self.failUnless(inst.has_key(key))
for key in absent:
self.assertEqual(inst.get(key, None), None)
self.assertEqual(inst.get(key), None)
self.assertEqual(inst.get(key, self), self)
self.assertRaises(KeyError, __getitem__, inst, key)
def test_keys(self, inst, state):
"""Return the keys of the mapping object
"""
inst_keys = list(inst.keys()); inst_keys.sort()
state_keys = list(state.keys()) ; state_keys.sort()
self.assertEqual(inst_keys, state_keys)
def test_values(self, inst, state):
"""Return the values of the mapping object
"""
inst_values = list(inst.values()); inst_values.sort()
state_values = list(state.values()) ; state_values.sort()
self.assertEqual(inst_values, state_values)
def test_items(self, inst, state):
"""Return the items of the mapping object
"""
inst_items = list(inst.items()); inst_items.sort()
state_items = list(state.items()) ; state_items.sort()
self.assertEqual(inst_items, state_items)
def test___len__(self, inst, state):
"""Return the number of items
"""
self.assertEqual(len(inst), len(state))
def testIEnumerableMapping(self, inst, state):
test_keys(self, inst, state)
test_items(self, inst, state)
test_values(self, inst, state)
test___len__(self, inst, state)
class BaseTestIReadMapping:
def testIReadMapping(self):
inst = self._IReadMapping__sample()
state = self._IReadMapping__stateDict()
absent = self._IReadMapping__absentKeys()
testIReadMapping(self, inst, state, absent)
class BaseTestIEnumerableMapping(BaseTestIReadMapping):
"""Mapping objects whose items can be enumerated
"""
def test_keys(self):
"""Return the keys of the mapping object
"""
inst = self._IEnumerableMapping__sample()
state = self._IEnumerableMapping__stateDict()
test_keys(self, inst, state)
def test_values(self):
"""Return the values of the mapping object
"""
inst = self._IEnumerableMapping__sample()
state = self._IEnumerableMapping__stateDict()
test_values(self, inst, state)
def test_items(self):
"""Return the items of the mapping object
"""
inst = self._IEnumerableMapping__sample()
state = self._IEnumerableMapping__stateDict()
test_items(self, inst, state)
def test___len__(self):
"""Return the number of items
"""
inst = self._IEnumerableMapping__sample()
state = self._IEnumerableMapping__stateDict()
test___len__(self, inst, state)
def _IReadMapping__stateDict(self):
return self._IEnumerableMapping__stateDict()
def _IReadMapping__sample(self):
return self._IEnumerableMapping__sample()
def _IReadMapping__absentKeys(self):
return self._IEnumerableMapping__absentKeys()
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Pretty-Print an Interface object as structured text (Yum)
This module provides a function, asStructuredText, for rendering an
interface as structured text.
Revision information:
$Id$
"""
from string import maketrans
def asStructuredText(I, munge=0):
""" Output structured text format. Note, this will wack any existing
'structured' format of the text. """
r = ["%s\n\n" % I.getName()]
outp = r.append
level = 1
if I.getDoc():
outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level)+ "\n\n")
if I.getBases():
outp((" " * level) + "This interface extends:\n\n")
level = level + 1
for b in I.getBases():
item = "o %s" % b.getName()
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
level = level - 1
namesAndDescriptions = list(I.namesAndDescriptions())
namesAndDescriptions.sort()
outp(_justify_and_indent("Attributes:", level, munge)+'\n\n')
level = level + 1
for name, desc in namesAndDescriptions:
if not hasattr(desc, 'getSignatureString'): # ugh...
item = "%s -- %s" % (desc.getName(),
desc.getDoc() or 'no documentation')
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
level = level - 1
outp(_justify_and_indent("Methods:", level, munge)+'\n\n')
level = level + 1
for name, desc in namesAndDescriptions:
if hasattr(desc, 'getSignatureString'): # ugh...
item = "%s%s -- %s" % (desc.getName(),
desc.getSignatureString(),
desc.getDoc() or 'no documentation')
outp(_justify_and_indent(_trim_doc_string(item), level, munge)
+ "\n\n")
return "".join(r)
def _trim_doc_string(text):
"""
Trims a doc string to make it format
correctly with structured text.
"""
text = text.strip().replace('\r\n', '\n')
lines = text.split('\n')
nlines = [lines[0]]
if len(lines) > 1:
min_indent=None
for line in lines[1:]:
indent=len(line) - len(line.lstrip())
if indent < min_indent or min_indent is None:
min_indent=indent
for line in lines[1:]:
nlines.append(line[min_indent:])
return '\n'.join(nlines)
_trans = maketrans("\r\n", " ")
def _justify_and_indent(text, level, munge=0, width=72):
""" indent and justify text, rejustify (munge) if specified """
lines = []
if munge:
line = " " * level
text = text.translate(text, _trans).strip().split()
for word in text:
line = ' '.join([line, word])
if len(line) > width:
lines.append(line)
line = " " * level
else:
lines.append(line)
return "\n".join(lines)
else:
text = text.replace("\r\n", "\n").split("\n")
for line in text:
lines.append( (" " * level) + line)
return '\n'.join(lines)
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
class DoesNotImplement(Exception):
""" This object does not implement """
def __init__(self, interface):
self.interface = interface
def __str__(self):
return """An object does not implement interface %(interface)s
""" % self.__dict__
class BrokenImplementation(Exception):
"""An attribute is not completely implemented.
"""
def __init__(self, interface, name):
self.interface=interface
self.name=name
def __str__(self):
return """An object has failed to implement interface %(interface)s
The %(name)s attribute was not provided.
""" % self.__dict__
class BrokenMethodImplementation(Exception):
"""An method is not completely implemented.
"""
def __init__(self, method, mess):
self.method=method
self.mess=mess
def __str__(self):
return """The implementation of %(method)s violates its contract
because %(mess)s.
""" % self.__dict__
class InvalidInterface(Exception):
"""The interface has invalid contents
"""
class BadImplements(TypeError):
"""An implementation assertion is invalid
because it doesn't contain an interface or a sequence of valid
implementation assertions.
"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from IElement import IElement
class IAttribute(IElement):
"""Attribute descriptors"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from _Interface import Interface
from Attribute import Attribute
class IElement(Interface):
"""Objects that have basic documentation and tagged values.
"""
__name__ = Attribute('__name__', 'The object name')
__doc__ = Attribute('__doc__', 'The object doc string')
def getName():
"""Returns the name of the object."""
def getDoc():
"""Returns the documentation for the object."""
def getTaggedValue(tag):
"""Returns the value associated with 'tag'."""
def getTaggedValueTags():
"""Returns a list of all tags."""
def setTaggedValue(tag, value):
"""Associates 'value' with 'key'."""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from IElement import IElement
class IInterface(IElement):
"""Interface objects
Interface objects describe the behavior of an object by containing
useful information about the object. This information includes:
o Prose documentation about the object. In Python terms, this
is called the "doc string" of the interface. In this element,
you describe how the object works in prose language and any
other useful information about the object.
o Descriptions of attributes. Attribute descriptions include
the name of the attribute and prose documentation describing
the attributes usage.
o Descriptions of methods. Method descriptions can include:
o Prose "doc string" documentation about the method and its
usage.
o A description of the methods arguments; how many arguments
are expected, optional arguments and their default values,
the position or arguments in the signature, whether the
method accepts arbitrary arguments and whether the method
accepts arbitrary keyword arguments.
o Optional tagged data. Interface objects (and their attributes and
methods) can have optional, application specific tagged data
associated with them. Examples uses for this are examples,
security assertions, pre/post conditions, and other possible
information you may want to associate with an Interface or its
attributes.
Not all of this information is mandatory. For example, you may
only want the methods of your interface to have prose
documentation and not describe the arguments of the method in
exact detail. Interface objects are flexible and let you give or
take any of these components.
Interfaces are created with the Python class statement using
either Interface.Interface or another interface, as in::
from Interface import Interface
class IMyInterface(Interface):
'''Interface documentation
'''
def meth(arg1, arg2):
'''Documentation for meth
'''
# Note that there is no self argument
class IMySubInterface(IMyInterface):
'''Interface documentation
'''
def meth2():
'''Documentation for meth2
'''
You use interfaces in two ways:
o You assert that your object implement the interfaces.
There are several ways that you can assert that an object
implements an interface::
1. Include an '__implements__' attribute in the object's class
definition. The value of the '__implements__' attribute must
be an implementation specification. An implementation
specification is either an interface or a tuple of
implementation specifications.
2. Incluse an '__implements__' attribute in the object.
Because Python classes don't have their own attributes, to
assert that a class implements interfaces, you must provide a
'__class_implements__' attribute in the class definition.
**Important**: A class usually doesn't implement the
interfaces that it's instances implement. The class and
it's instances are separate objects with their own
interfaces.
3. Call 'Interface.Implements.implements' to assert that instances
of a class implement an interface.
For example::
from Interface.Implements import implements
implements(some_class, some_interface)
This is approach is useful when it is not an option to modify
the class source. Note that this doesn't affect what the
class itself implements, but only what it's instances
implement.
4. For types that can't be modified, you can assert that
instances of the type implement an interface using
'Interface.Implements.assertTypeImplements'.
For example::
from Interface.Implements import assertTypeImplements
assertTypeImplements(some_type, some_interface)
o You query interface meta-data. See the IInterface methods and
attributes for details.
"""
def getBases():
"""Return a sequence of the base interfaces
"""
def extends(other, strict=1):
"""Test whether the interface extends another interface
A true value is returned in the interface extends the other
interface, and false otherwise.
Normally, an interface doesn't extend itself. If a false value
is passed as the second argument, or via the 'strict' keyword
argument, then a true value will be returned if the interface
and the other interface are the same.
"""
def isImplementedBy(object):
"""Test whether the interface is implemented by the object.
Return true of the object asserts that it implements the
interface, including asseting that it implements an extended
interface.
"""
def isImplementedByInstancesOf(class_):
"""Test whether the interface is implemented by instances of the class
Return true of the class asserts that it's instances implement the
interface, including asseting that they implement an extended
interface.
"""
def names(all=0):
"""Get the interface attribute names.
Return a sequence of the names of the attributes, including
methods, included in the interface definition.
Normally, only directly defined attributes are included. If
a true positional or keyword argument is given, then
attributes defined by nase classes will be included.
"""
def namesAndDescriptions(all=0):
"""Get the interface attribute names and descriptions.
Return a sequence of the names and descriptions of the
attributes, including methods, as name-value pairs, included
in the interface definition.
Normally, only directly defined attributes are included. If
a true positional or keyword argument is given, then
attributes defined by nase classes will be included.
"""
def getDescriptionFor(name):
"""Get the description for a name
If the named attribute does not exist, a KeyError is raised.
"""
def queryDescriptionFor(name, default=None):
"""Get the description for a name
Return the default if no description exists.
"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from IAttribute import IAttribute
class IMethod(IAttribute):
"""Method attributes
"""
# XXX What the heck should methods provide? Grrrr
def getSignatureString():
"""Return a signature string suitable for inclusion in documentation.
"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Implemantation assertion facilities.
Revision information:
$Id$
"""
import Exceptions
from types import ClassType
from Verify import verifyClass
from _InterfaceClass import Interface as InterfaceClass
from types import TupleType, ClassType, StringType
# Special value indicating the object supports
# what its class supports.
CLASS_INTERFACES = 1
from _object import ClassTypes, isInstance
_typeImplements={}
def getImplements(object):
t = type(object)
if t in ClassTypes:
if hasattr(object, '__class_implements__'):
return object.__class_implements__
elif hasattr(object, '__implements__'):
return object.__implements__
return _typeImplements.get(t, None)
def getImplementsOfInstances(klass, tiget=_typeImplements.get):
if type(klass) in ClassTypes:
if hasattr(klass, '__implements__'):
return klass.__implements__
else:
return None
else:
return tiget(klass, None)
def visitImplements(implements, object, visitor, getInterface=None):
"""
Visits the interfaces described by an __implements__ attribute,
invoking the visitor for each interface object.
If the visitor returns anything true, the loop stops.
This does not, and should not, visit superinterfaces.
"""
# this allows us to work with proxy wrappers in Python 2.2,
# yet remain compatible with earlier versions of python.
implements_class = getattr(implements, '__class__', None)
if implements_class == InterfaceClass or \
isInstance(implements, InterfaceClass):
return visitor(implements)
elif implements == CLASS_INTERFACES:
klass = getattr(object, '__class__', None)
if klass is not None:
i = getImplementsOfInstances(klass)
if i:
return visitImplements(i, object, visitor, getInterface)
elif implements_class == StringType or type(implements) is StringType:
if getInterface is not None:
# Look up a named interface.
i = getInterface(object, implements)
if i is not None:
return visitImplements(i, object, visitor, getInterface)
elif implements_class == TupleType or type(implements) is TupleType:
for i in implements:
r = visitImplements(i, object, visitor, getInterface)
if r:
# If the visitor returns anything true, stop.
return r
else:
if implements_class is not None and \
type(implements) != implements_class:
raise Exceptions.BadImplements(
"""__implements__ should be an interface or tuple,
not a %s pretending to be a %s"""
% (type(implements).__name__, implements_class.__name__)
)
raise Exceptions.BadImplements(
"""__implements__ should be an interface or tuple,
not a %s""" % type(implements).__name__)
return 0
def assertTypeImplements(type, interfaces):
"""Assign a set of interfaces to a Python type such as int, str, tuple,
list and dict.
"""
_typeImplements[type]=interfaces
def objectImplements(object, getInterface=None):
r = []
implements = getImplements(object)
if not implements:
return r
visitImplements(implements, object, r.append, getInterface)
return r
def instancesOfObjectImplements(klass, getInterface=None):
r = []
implements = getImplementsOfInstances(klass)
if not implements:
return r
visitImplements(implements, klass, r.append, getInterface)
return r
def _flatten(i, append):
append(i)
bases = i.getBases()
if bases:
for b in bases:
_flatten(b, append)
def _detuplize(interface, append):
if type(interface) is TupleType:
for subinterface in interface:
_detuplize(subinterface, append)
else:
append(interface)
def flattenInterfaces(interfaces, remove_duplicates=1):
detupledInterfaces = []
for interface in interfaces:
_detuplize(interface, detupledInterfaces.append)
res = []
for i in detupledInterfaces:
_flatten(i, res.append)
if remove_duplicates:
# Remove duplicates in reverse.
# Similar to Python 2.2's method resolution order.
seen = {}
index = len(res) - 1
while index >= 0:
i = res[index]
if seen.has_key(i):
del res[index]
else:
seen[i] = 1
index = index - 1
return res
def implements(klass, interface, check=1):
if check:
verifyClass(interface, klass, tentative=1)
old=getattr(klass, '__implements__', None)
if old is None:
klass.__implements__ = interface
else:
klass.__implements__ = old, interface
import Basic, Util
class Mapping(Basic.Base):
"anything supporting __getitem__"
def __getitem__(key):
"""Get the value for the given key
Raise a key error if the key if not in the collection.
"""
class QueryMapping(Mapping):
def has_key(key):
"""Check whether the object has an item with the given key"""
def get(key, default=None):
"""Get the value for the given key
Return the default if the key is not in the collection.
"""
class Sized(Basic.Base):
"anything supporting __len"
def __len__():
"""Return the number of items in the container"""
class MutableMapping(Basic.Mutable):
"Has __setitem__ and __delitem__"
def __setitem__(key, value):
"""Set the value for the given key"""
def __delitem__(key):
"""delete the value for the given key
Raise a key error if the key if not in the collection."""
class EnumerableMapping(Mapping):
def keys():
"""Return an Sequence containing the keys in the collection
The type of the IReadSequence is not specified. It could be a
list or a tuple or some other type.
"""
class MinimalDictionary(QueryMapping, Sized, MutableMapping,
EnumerableMapping):
"""Provide minimal dictionary-like behavior
"""
def values():
"""Return a IReadSequence containing the values in the collection
The type of the IReadSequence is not specified. It could be a
list or a tuple or some other type.
"""
def items():
"""Return a IReadSequence containing the items in the collection
An item is a key-value tuple.
The type of the IReadSequence is not specified. It could be a
list or a tuple or some other type.
"""
class Sequence(Mapping):
"Keys must be integers in a sequence starting at 0."
class Sequential(Sequence):
"Keys must be used in order"
Util.assertTypeImplements(type(()), (Sequence, Sized, Basic.HashKey))
Util.assertTypeImplements(type([]), (Sequence, Sized, MutableMapping))
Util.assertTypeImplements(type({}), (Mapping, Sized, MutableMapping))
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Method interfaces
Revision information:
$Id$
"""
import Exceptions
from Attribute import Attribute
sig_traits = ['positional', 'required', 'optional', 'varargs', 'kwargs']
CO_VARARGS = 4
CO_VARKEYWORDS = 8
class Method(Attribute):
"""Method interfaces
The idea here is that you have objects that describe methods.
This provides an opportunity for rich meta-data.
"""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IMethod
interface=''
def __call__(self, *args, **kw):
raise Exceptions.BrokenImplementation(self.interface, self.__name__)
def getSignatureInfo(self):
info = {}
for t in sig_traits:
info[t] = getattr(self, t)
return info
def getSignatureString(self):
sig = "("
for v in self.positional:
sig = sig + v
if v in self.optional.keys():
sig = sig + "=%s" % `self.optional[v]`
sig = sig + ", "
if self.varargs:
sig = sig + ("*%s, " % self.varargs)
if self.kwargs:
sig = sig + ("**%s, " % self.kwargs)
# slice off the last comma and space
if self.positional or self.varargs or self.kwargs:
sig = sig[:-2]
sig = sig + ")"
return sig
def fromFunction(func, interface='', imlevel=0):
m=Method(func.__name__, func.__doc__)
defaults=func.func_defaults or ()
c=func.func_code
na=c.co_argcount-imlevel
names=c.co_varnames[imlevel:]
d={}
nr=na-len(defaults)
if nr < 0:
defaults=defaults[-nr:]
nr=0
for i in range(len(defaults)):
d[names[i+nr]]=defaults[i]
m.positional=names[:na]
m.required=names[:nr]
m.optional=d
argno = na
if c.co_flags & CO_VARARGS:
m.varargs = names[argno]
argno = argno + 1
else:
m.varargs = None
if c.co_flags & CO_VARKEYWORDS:
m.kwargs = names[argno]
else:
m.kwargs = None
m.interface=interface
return m
def fromMethod(meth, interface=''):
func = meth.im_func
return fromFunction(func, interface, imlevel=1)
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from Exceptions import BrokenImplementation, DoesNotImplement
from Exceptions import BrokenMethodImplementation
from types import FunctionType
from Method import fromMethod, fromFunction
from _object import MethodTypes
def _verify(iface, candidate, tentative=0, vtype=None):
"""
Verify that 'candidate' might correctly implements 'iface'.
This involves:
o Making sure the candidate defines all the necessary methods
o Making sure the methods have the correct signature
o Making sure the candidate asserts that it implements the interface
Note that this isn't the same as verifying that the class does
implement the interface.
If optional tentative is true, suppress the "is implemented by" test.
"""
if vtype is 'c':
tester = iface.isImplementedByInstancesOf
else:
tester = iface.isImplementedBy
if not tentative and not tester( candidate ):
raise DoesNotImplement(iface)
for n, d in iface.namesAndDescriptions(1):
if not hasattr(candidate, n):
raise BrokenImplementation(iface, n)
attr = getattr(candidate, n)
if type(attr) is FunctionType:
# should never get here
meth = fromFunction(attr, n)
elif type(attr) in MethodTypes:
meth = fromMethod(attr, n)
else:
continue # must be an attribute...
d=d.getSignatureInfo()
meth = meth.getSignatureInfo()
mess = _incompat(d, meth)
if mess:
raise BrokenMethodImplementation(n, mess)
return 1
def verifyClass(iface, candidate, tentative=0):
return _verify(iface, candidate, tentative, vtype='c')
def verifyObject(iface, candidate, tentative=0):
return _verify(iface, candidate, tentative, vtype='o')
def _incompat(required, implemented):
#if (required['positional'] !=
# implemented['positional'][:len(required['positional'])]
# and implemented['kwargs'] is None):
# return 'imlementation has different argument names'
if len(implemented['required']) > len(required['required']):
return 'implementation requires too many arguments'
if ((len(implemented['positional']) < len(required['positional']))
and not implemented['varargs']):
return "implementation doesn't allow enough arguments"
if required['kwargs'] and not implemented['kwargs']:
return "implementation doesn't support keyword arguments"
if required['varargs'] and not implemented['varargs']:
return "implementation doesn't support variable arguments"
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from _object import object
class Element(object):
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IElement
def __init__(self, __name__=None, __doc__=''):
"""Create an 'attribute' description
"""
if not __doc__ and __name__ and __name__.find(' ') >= 0:
__doc__ = __name__
__name__ = None
self.__name__=__name__
self.__doc__=__doc__
self.__tagged_values = {}
def getName(self):
""" Returns the name of the object. """
return self.__name__
def getDoc(self):
""" Returns the documentation for the object. """
return self.__doc__
def getTaggedValue(self, tag):
""" Returns the value associated with 'tag'. """
return self.__tagged_values[tag]
def getTaggedValueTags(self):
""" Returns a list of all tags. """
return self.__tagged_values.keys()
def setTaggedValue(self, tag, value):
""" Associates 'value' with 'key'. """
self.__tagged_values[tag] = value
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interface object implementation
Revision information:
$Id$
"""
from _InterfaceClass import Interface as InterfaceClass
Interface = InterfaceClass("Interface")
# Now we can create the interesting interfaces and wire them up:
def wire():
from Implements import implements
from Attribute import Attribute
from IAttribute import IAttribute
implements(Attribute, IAttribute)
from Method import Method
from IMethod import IMethod
implements(Method, IMethod)
from IInterface import IInterface
implements(InterfaceClass, IInterface)
wire()
del wire
del InterfaceClass
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interface object implementation
Revision information:
$Id$
"""
from inspect import currentframe
import sys
from Method import Method, fromFunction
from Attribute import Attribute
from types import FunctionType
import Exceptions
from _Element import Element
from _object import isInstance
class Interface(Element):
"""Prototype (scarecrow) Interfaces Implementation
"""
# We can't say this yet because we don't have enough
# infrastructure in place.
#
#__implements__ = IInterface
def __init__(self, name, bases=(), attrs=None, __doc__=None,
__module__=None):
if __module__ is None:
if attrs is not None and attrs.has_key('__module__'):
__module__ = attrs['__module__']
del attrs['__module__']
else:
try:
# Figure out what module defined the interface.
# This is how cPython figures out the module of
# a class, but of course it does it in C. :-/
__module__ = currentframe().f_back.f_globals['__name__']
except (AttributeError, KeyError):
pass
self.__module__ = __module__
for b in bases:
if not isInstance(b, Interface):
raise TypeError, 'Expected base interfaces'
self.__bases__=bases
if attrs is None: attrs={}
if attrs.has_key('__doc__'):
if __doc__ is None: __doc__=attrs['__doc__']
del attrs['__doc__']
if __doc__ is not None:
self.__doc__=__doc__
else:
self.__doc__ = ""
Element.__init__(self, name, __doc__)
for k, v in attrs.items():
if isInstance(v, Attribute):
v.interface=name
if not v.__name__:
v.__name__ = k
elif isinstance(v, FunctionType):
attrs[k]=fromFunction(v, name)
else:
raise Exceptions.InvalidInterface(
"Concrete attribute, %s" % k)
self.__attrs = attrs
def getBases(self):
return self.__bases__
def extends(self, other, strict=1):
"""Does an interface extend another?
"""
if not strict and self is other:
return 1
for b in self.__bases__:
if b == other: return 1
if b.extends(other): return 1
return 0
def isEqualOrExtendedBy(self, other):
"""Same interface or extends?
"""
if self == other:
return 1
return other.extends(self)
def isImplementedBy(self, object):
"""Does the given object implement the interface?
"""
i = getImplements(object)
if i is not None:
return visitImplements(
i, object, self.isEqualOrExtendedBy, self._getInterface)
return 0
def isImplementedByInstancesOf(self, klass):
"""Do instances of the given class implement the interface?
"""
i = getImplementsOfInstances(klass)
if i is not None:
return visitImplements(
i, klass, self.isEqualOrExtendedBy, self._getInterface)
return 0
def names(self, all=0):
"""Return the attribute names defined by the interface
"""
if not all:
return self.__attrs.keys()
r = {}
for name in self.__attrs.keys():
r[name] = 1
for base in self.__bases__:
for name in base.names(all):
r[name] = 1
return r.keys()
def namesAndDescriptions(self, all=0):
"""Return the attribute names and descriptions defined by the interface
"""
if not all:
return self.__attrs.items()
r = {}
for name, d in self.__attrs.items():
r[name] = d
for base in self.__bases__:
for name, d in base.namesAndDescriptions(all):
if not r.has_key(name):
r[name] = d
return r.items()
def getDescriptionFor(self, name):
"""Return the attribute description for the given name
"""
r = self.queryDescriptionFor(name)
if r is not None:
return r
raise KeyError, name
def queryDescriptionFor(self, name, default=None):
"""Return the attribute description for the given name
"""
r = self.__attrs.get(name, self)
if r is not self:
return r
for base in self.__bases__:
r = base.queryDescriptionFor(name, self)
if r is not self:
return r
return default
def deferred(self):
"""Return a defered class corresponding to the interface
"""
if hasattr(self, "_deferred"): return self._deferred
klass={}
exec "class %s: pass" % self.__name__ in klass
klass=klass[self.__name__]
self.__d(klass.__dict__)
self._deferred=klass
return klass
def _getInterface(self, ob, name):
'''
Retrieve a named interface.
'''
return None
def __d(self, dict):
for k, v in self.__attrs.items():
if isInstance(v, Method) and not dict.has_key(k):
dict[k]=v
for b in self.__bases__: b.__d(dict)
def __repr__(self):
name = self.__name__
m = self.__module__
if m:
name = '%s.%s' % (m, name)
return "<%s %s at %x>" % (self.__class__.__name__, name, id(self))
def __reduce__(self):
return self.__name__
def __hash__(self):
""" interface instances need to be hashable, and inheriting
from extensionclass makes instances unhashable unless we declare
a __hash__ method here"""
return id(self)
# We import this here to deal with module dependencies.
from Implements import getImplementsOfInstances, visitImplements, getImplements
from Implements import instancesOfObjectImplements
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Interfaces
This package implements the Python "scarecrow" proposal.
The package exports a single name, 'Interface' directly. Interface
is used to create an interface with a class statement, as in:
from Interface import Interface
class IMyInterface(Interface):
'''Interface documentation
'''
def meth(arg1, arg2):
'''Documentation for meth
'''
# Note that there is no self argument
To find out what you can do with interfaces, see the interface
interface, IInterface in the IInterface module.
The package has several public modules:
o Attribute has the implementation for interface attributes
for people who want to build interfaces by hand.
(Maybe someone should cry YAGNI for this. ;)
o Document has a utility for documenting an interface as structured text.
o Exceptions has the interface-defined exceptions
o IAttribute defines the attribute descriptor interface.
o IElement defined the base interface for IAttribute, IInterface,
and IMethod.
o IInterface defines the interface interface
o IMethod defined the method interface.
o Implements has various utilities for examining interface assertions.
o Method has the implementation for interface methods. See above.
o Verify has utilities for verifying (sort of) interfaces.
See the module doc strings for more information.
There is also a script, pyself.py in the package that can be used to
create interface skeletins. Run it without arguments to get documentation.
Revision information:
$Id$
"""
from _Interface import Interface
from Attribute import Attribute
Base = Interface # XXX We need to stamp out Base usage
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Provide a halfway believable rendition of Python 2.2's object
$Id$
"""
class _x:
def m(self):
pass
ClassTypes = (type(_x), )
MethodTypes = (type(_x.m), )
isInstance = isinstance
try:
object
except NameError:
# Python 2.1
try:
from ExtensionClass import Base as object
except ImportError:
class object: pass
else:
# Python 2.2
ClassTypes += (type, )
object = object
try:
import ExtensionClass
except ImportError:
# ExtensionClass is not present
pass
else:
# ExtensionClass is present
def isInstance(ob, klass):
if type(type(ob)) is type(klass):
return isinstance(ob, klass)
return 0
class _x(ExtensionClass.Base):
def m(self): pass
ClassTypes += (type(_x), )
MethodTypes += (type(_x.m), )
##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Z3 -> Z2 bridge utilities.
$Id$
"""
from Interface._InterfaceClass import Interface as Z2_InterfaceClass
from Interface import Interface as Z2_Interface
from Interface import Attribute as Z2_Attribute
from Interface.Method import Method as Z2_Method
from zope.interface.interface import InterfaceClass as Z3_InterfaceClass
from zope.interface.interface import Interface as Z3_Interface
from zope.interface.interface import Attribute as Z3_Attribute
from zope.interface.interface import Method as Z3_Method
_bridges = {Z3_Interface: Z2_Interface}
def fromZ3Interface(z3i):
""" Return a Zope 2 interface corresponding to 'z3i'.
o 'z3i' must be a Zope 3 interface.
"""
if not isinstance(z3i, Z3_InterfaceClass):
raise ValueError, 'Not a Zope 3 interface!'
if z3i in _bridges:
return _bridges[z3i]
name = z3i.getName()
bases = [ fromZ3Interface(x) for x in z3i.getBases() ]
attrs = {}
for k, v in z3i.namesAndDescriptions():
if isinstance(v, Z3_Method):
v = fromZ3Method(v)
elif isinstance(v, Z3_Attribute):
v = fromZ3Attribute(v)
attrs[k] = v
# XXX: Note that we pass the original interface's __module__;
# we may live to regret that.
z2i = Z2_InterfaceClass(name=name,
bases=tuple(bases),
attrs=attrs,
__doc__=z3i.getDoc(),
__module__=z3i.__module__)
_bridges[z3i] = z2i
return z2i
def fromZ3Attribute(z3a):
""" Return a Zope 2 interface attribute corresponding to 'z3a'.
o 'z3a' must be a Zope 3 interface attribute.
"""
if not isinstance(z3a, Z3_Attribute):
raise ValueError, 'Not a Zope 3 interface attribute!'
return Z2_Attribute(z3a.getName(), z3a.getDoc())
def fromZ3Method(z3m):
""" Return a Zope 2 interface method corresponding to 'z3m'.
o 'z3m' must be a Zope 3 interface method.
"""
if not isinstance(z3m, Z3_Method):
raise ValueError, 'Not a Zope 3 interface method!'
z2m = Z2_Method(z3m.getName(), z3m.getDoc())
sig = z3m.getSignatureInfo()
z2m.positional = sig['positional']
z2m.required = sig['required']
z2m.optional = sig['optional']
z2m.varargs = sig['varargs']
z2m.kwargs = sig['kwargs']
return z2m
def createZope3Bridge(zope3, package, name):
# Map a Zope 3 interface into a Zope2 interface, seated within 'package'
# as 'name'.
z2i = fromZ3Interface(zope3)
if name is not None:
z2i.__dict__['__name__'] = name
z2i.__dict__['__module__'] = package.__name__
setattr(package, z2i.getName(), z2i)
import warnings
warnings.warn("""\
The Interface.iclass module is no more.
This is a stub module to allow ZClasses that subclass ObjectManager
to continue to function - please fix your ZClasses (using the 'Subobjects'
tab)""",
DeprecationWarning)
# Old interface object. Provided for backwards compatibility - allows ZClasses
# that subclass ObjectManager to be used in 2.6.
class Interface:
def __init__(self, *args, **kwargs):
pass
""" Pretty-Print an Interface object as structured text (Yum) """
import string
def trim_doc_string(text):
"""
Trims a doc string to make it format
correctly with structured text.
"""
text=text.strip()
text=text.replace('\r\n', '\n')
lines=text.split('\n')
nlines=[lines[0]]
if len(lines) > 1:
min_indent=None
for line in lines[1:]:
indent=len(line) - len(line.lstrip())
if indent < min_indent or min_indent is None:
min_indent=indent
for line in lines[1:]:
nlines.append(line[min_indent:])
return '\n'.join(nlines)
def justify_and_indent(text, level, munge=0, width=72):
""" indent and justify text, rejustify (munge) if specified """
lines = []
if munge:
line = " " * level
text = (string.translate(text, string.maketrans("\r\n", " "))).strip.split()
for word in text:
line = ''.join([line, word])
if len(line) > width:
lines.append(line)
line = " " * level
else:
lines.append(line)
return '\n'.join(lines)
else:
text = text.replace("\r\n", "\n").split( "\n")
for line in text:
lines.append( (" " * level) + line)
return '\n'.join(lines)
def interface_as_stx(I, munge=0):
""" Output structured text format. Note, this will wack any existing
'structured' format of the text. """
outp = "%s\n\n" % I.getName()
level = 1
if I.getDoc():
outp = outp + justify_and_indent(trim_doc_string(I.getDoc()), level) + "\n\n"
if I.getBases():
outp = outp + (" " * level) + "This interface extends:\n\n"
level = level + 1
for b in I.getBases():
item = "o %s" % b.getName()
outp = outp + justify_and_indent(trim_doc_string(item), level, munge) + "\n\n"
level = level - 1
level = level + 1
for name, desc in I.namesAndDescriptions():
if hasattr(desc, 'getSignatureRepr'): # ugh...
item = "%s%s -- %s" % (desc.getName(), desc.getSignatureRepr(), desc.getDoc())
else:
item = "%s -- %s" % (desc.getName(), desc.getDoc())
outp = outp + justify_and_indent(trim_doc_string(item), level, munge) + "\n\n"
return outp
#!/usr/bin/env python
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Generate method skeletins for intefaces.
Usage: python pyskel.py dotted_name
Example:
cd lib/python
python Interface/pyskel.py Zope2.App.Security.IRoleService.IRoleService
The dotted name is the module name and interface object name connected
with a dot.
Revision information: $Id$
"""
import sys, os, re
sys.path.insert(0, os.getcwd())
from _object import isInstance
from types import ModuleType
from Interface.Method import Method
from Interface.Attribute import Attribute
class_re = re.compile(r'\s*class\s+([a-zA-Z_][a-zA-Z0-9_]*)')
def_re = re.compile(r'\s*def\s+([a-zA-Z_][a-zA-Z0-9_]*)')
attr_re = re.compile(r'\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*=\s*Attribute')
def rskel(iface, print_iface=1):
name = "%s.%s" % (iface.__module__, iface.__name__)
file = resolve(iface.__module__).__file__
if file.endswith('pyc'):
file = file[:-1]
order = guessOrder(open(file))
namesAndDescriptions = getAttributesInOrder(iface, order)
if namesAndDescriptions and print_iface:
print
print " ######################################"
print " # from:", name
for aname, ades in namesAndDescriptions:
if isInstance(ades, Method):
sig = ades.getSignatureString()[1:-1]
if sig: sig = "self, %s" % sig
else: sig = "self"
print
print " def %s(%s):" % (aname, sig)
print " 'See %s'" % name
elif isInstance(ades, Attribute):
print
print " # See %s" % name
print " %s = None" %aname
for base in iface.__bases__:
if base.__name__ not in ('Interface',):
rskel(base)
def skel(name):
iface = resolve(name)
class_name = iface.__name__
if class_name.startswith('I'):
class_name = class_name[1:]
print "from %s import %s" % (iface.__module__, iface.__name__)
print
print "class %s:" %class_name
print
print " __implements__ = ", iface.__name__
print
print " ############################################################"
print " # Implementation methods for interface"
print " #", name
rskel(iface, 0)
print
print " #"
print " ############################################################"
def resolve(name, _silly=('__doc__',), _globals={}):
# Support for file path syntax; this way I can use TAB to search for
# the module.
if '/' in name or name.endswith('.py'):
# We got a relative path. Let's try to get the full one and then
# make a package path out of it.
if not name.startswith('/'):
cwd = os.getcwd()
for path in sys.path[1:]: # Yeah, we need to exclude the cwd itself
if path != '' and cwd.startswith(path):
name = os.path.join(cwd[len(path)+1:], name)
name = os.path.normpath(name)
break
# get rid of the file ending :)
if name.endswith('.py'):
name = name[:-3]
name = name.replace('/', '.')
# Now to the regular lookup
if name[:1]=='.':
name='ZopeProducts'+name
if name[-1:] == '.':
name = name[:-1]
repeat = 1
else:
repeat = 0
names=name.split('.')
last=names[-1]
mod='.'.join(names[:-1])
while 1:
m=__import__(mod, _globals, _globals, _silly)
try:
a=getattr(m, last)
except AttributeError:
pass
else:
if not repeat or (type(a) is not ModuleType):
return a
mod += '.' + last
def guessOrder(source_file):
order = {} # { class name -> list of methods }
lines = source_file.readlines()
class_name = None
for line in lines:
m = class_re.match(line)
if m and m.groups():
class_name = m.groups()[0]
else:
for m in (def_re.match(line),
attr_re.match(line)):
if m and m.groups():
def_name = m.groups()[0]
name_order = order.get(class_name)
if name_order is None:
name_order = []
order[class_name] = name_order
name_order.append(def_name)
return order
def getAttributesInOrder(interface, order):
# order is the dictionary returned from guessOrder().
# interface is a metaclass-based interface object.
name_order = order.get(interface.__name__)
if name_order is None:
# Something's wrong. Oh well.
return interface.__dict__.items()
else:
items = []
for key, value in interface.namesAndDescriptions():
if key in name_order:
items.append((name_order.index(key), key, value))
else:
items.append((99999, key, value)) # Go to end.
items.sort()
return map(lambda item: item[1:], items)
if __name__ == '__main__':
for a in sys.argv[1:]:
skel(a)
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from Interface import Interface
class IFoo( Interface ):
"""
Dummy interface for unit tests.
"""
def bar( baz ):
"""
Just a note.
"""
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Packagize. """
======
Bridge
======
The ``bridge`` module provides functionality to convert a Zope 3
interface into a Zope 2 one. First we'll import all we know about
interfaces from the two generations:
>>> from Interface import Interface as Z2_Interface
>>> from Interface import Attribute as Z2_Attribute
>>> from Interface.Method import Method as Z2_Method
>>> from zope.interface import Interface as Z3_Interface
>>> from zope.interface import Attribute as Z3_Attribute
>>> from zope.schema import List, TextLine
An empty interface
------------------
>>> class IEmpty(Z3_Interface):
... pass
>>> from Interface.bridge import fromZ3Interface
>>> IEmptyConverted = fromZ3Interface(IEmpty)
>>> Z2_Interface.isEqualOrExtendedBy(IEmptyConverted)
1
>>> len(IEmptyConverted.names())
0
Bases
-----
>>> class IBase(Z3_Interface):
... pass
>>> class IDerived(IBase):
... pass
>>> IBase.getBases() == (Z3_Interface,)
True
>>> IDerived.getBases() == (IBase,)
True
>>> IDerived.extends(IBase)
True
>>> IDerived.extends(IEmpty)
False
>>> IBaseConverted = fromZ3Interface(IBase)
>>> IDerivedConverted = fromZ3Interface(IDerived)
>>> IBaseConverted.getBases() == (Z2_Interface,)
True
>>> IDerivedConverted.getBases() == (IBaseConverted,)
True
>>> IDerivedConverted.extends(IBaseConverted)
1
>>> IDerivedConverted.extends(IEmptyConverted)
0
Attributes
----------
>>> class IAttributes(Z3_Interface):
... one = Z3_Attribute('one', 'One attribute')
... another = Z3_Attribute('another', 'Another attribute')
>>> converted = fromZ3Interface(IAttributes)
>>> Z2_Interface.isEqualOrExtendedBy(converted)
1
>>> len(converted.names())
2
>>> 'one' in converted.names()
True
>>> 'another' in converted.names()
True
>>> one = converted.getDescriptionFor('one')
>>> isinstance(one, Z2_Attribute)
True
>>> one.getName()
'one'
>>> one.getDoc()
'One attribute'
>>> another = converted.getDescriptionFor('another')
>>> isinstance(another, Z2_Attribute)
True
>>> another.getName()
'another'
>>> another.getDoc()
'Another attribute'
Fields
------
>>> class IFields(Z3_Interface):
... one = TextLine(title=u'one', description=u'One field')
... another = List(title=u'another', description=u'Another field',
... value_type = TextLine())
>>> converted = fromZ3Interface(IFields)
>>> Z2_Interface.isEqualOrExtendedBy(converted)
1
>>> len(converted.names())
2
>>> 'one' in converted.names()
True
>>> 'another' in converted.names()
True
>>> one = converted.getDescriptionFor('one')
>>> isinstance(one, Z2_Attribute)
True
>>> one.getName()
'one'
>>> one.getDoc()
u'one\n\nOne field'
>>> another = converted.getDescriptionFor('another')
>>> isinstance(another, Z2_Attribute)
True
>>> another.getName()
'another'
>>> another.getDoc()
u'another\n\nAnother field'
Methods
-------
>>> class IMethods(Z3_Interface):
... def one():
... """One method."""
... def another(arg1, arg2):
... """Another method, taking arguments."""
>>> converted = fromZ3Interface(IMethods)
>>> Z2_Interface.isEqualOrExtendedBy(converted)
1
>>> len(converted.names())
2
>>> 'one' in converted.names()
True
>>> 'another' in converted.names()
True
>>> one = converted.getDescriptionFor('one')
>>> isinstance(one, Z2_Method)
True
>>> one.getName()
'one'
>>> one.getDoc()
'One method.'
>>> one.getSignatureString()
'()'
>>> another = converted.getDescriptionFor('another')
>>> isinstance(another, Z2_Method)
True
>>> another.getName()
'another'
>>> another.getDoc()
'Another method, taking arguments.'
>>> another.getSignatureString()
'(arg1, arg2)'
Invalid parameters
------------------
>>> fromZ3Interface(None)
Traceback (most recent call last):
...
ValueError: Not a Zope 3 interface!
>>> fromZ3Interface(object())
Traceback (most recent call last):
...
ValueError: Not a Zope 3 interface!
>>> class IZ2_NotAllowed(Z2_Interface):
... pass
>>> fromZ3Interface(IZ2_NotAllowed)
Traceback (most recent call last):
...
ValueError: Not a Zope 3 interface!
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from Interface.tests.IFoo import IFoo
__implements__ = IFoo
def bar( baz ):
pass
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from unittest import TestCase, TestSuite, main, makeSuite
from Interface import Interface
from Interface.Attribute import Attribute
class Test(TestCase):
def testBlech(self):
from Interface.Document import asStructuredText
self.assertEqual(asStructuredText(I2), '''\
I2
I2 doc
This interface extends:
o _I1
Attributes:
a1 -- no documentation
a2 -- a2 doc
Methods:
f21() -- f21 doc
f22() -- no documentation
f23() -- f23 doc
''')
def test_suite():
return TestSuite((
makeSuite(Test),
))
class _I1(Interface):
def f11(): pass
def f12(): pass
class I2(_I1):
"I2 doc"
a1 = Attribute('a1')
a2 = Attribute('a2', 'a2 doc')
def f21(): "f21 doc"
def f22(): pass
def f23(): "f23 doc"
if __name__=='__main__':
main(defaultTest='test_suite')
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from __future__ import nested_scopes
from Interface import Interface
from Interface.Implements import implements
from Interface.Exceptions import DoesNotImplement, BrokenImplementation
from Interface.Exceptions import BrokenMethodImplementation
import unittest, sys
class Test(unittest.TestCase):
def testSimple(self):
class I(Interface):
def f(): pass
class C: pass
self.assertRaises(BrokenImplementation, implements, C, I)
C.f=lambda self: None
implements(C, I)
self.assertEqual(C.__implements__, I)
def testAdd(self):
class I(Interface):
def f(): pass
class I2(Interface):
def g(): pass
class C:
__implements__=I2
self.assertRaises(BrokenImplementation, implements, C, I)
self.assertRaises(BrokenImplementation, implements, C, I2)
C.f=lambda self: None
implements(C, I)
self.assertEqual(C.__implements__, (I2, I))
self.assertRaises(BrokenImplementation, implements, C, I2)
C.g=C.f
implements(C, I)
implements(C, I2)
def test_suite():
loader=unittest.TestLoader()
return loader.loadTestsFromTestCase(Test)
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import unittest
import Interface
from unitfixtures import * # hehehe
from Interface.Exceptions import BrokenImplementation
from Interface.Implements import instancesOfObjectImplements
from Interface.Implements import objectImplements
from Interface import Interface
from Interface.Attribute import Attribute
class InterfaceTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testClassImplements(self):
assert IC.isImplementedByInstancesOf(C)
assert I1.isImplementedByInstancesOf(A)
assert I1.isImplementedByInstancesOf(B)
assert not I1.isImplementedByInstancesOf(C)
assert I1.isImplementedByInstancesOf(D)
assert I1.isImplementedByInstancesOf(E)
assert not I2.isImplementedByInstancesOf(A)
assert I2.isImplementedByInstancesOf(B)
assert not I2.isImplementedByInstancesOf(C)
assert not I2.isImplementedByInstancesOf(D)
assert not I2.isImplementedByInstancesOf(E)
def testUtil(self):
f = instancesOfObjectImplements
assert IC in f(C)
assert I1 in f(A)
assert not I1 in f(C)
assert I2 in f(B)
assert not I2 in f(C)
f = objectImplements
assert IC in f(C())
assert I1 in f(A())
assert not I1 in f(C())
assert I2 in f(B())
assert not I2 in f(C())
def testObjectImplements(self):
assert IC.isImplementedBy(C())
assert I1.isImplementedBy(A())
assert I1.isImplementedBy(B())
assert not I1.isImplementedBy(C())
assert I1.isImplementedBy(D())
assert I1.isImplementedBy(E())
assert not I2.isImplementedBy(A())
assert I2.isImplementedBy(B())
assert not I2.isImplementedBy(C())
assert not I2.isImplementedBy(D())
assert not I2.isImplementedBy(E())
def testDeferredClass(self):
a = A()
self.assertRaises(BrokenImplementation, a.ma)
def testInterfaceExtendsInterface(self):
assert BazInterface.extends(BobInterface)
assert BazInterface.extends(BarInterface)
assert BazInterface.extends(FunInterface)
assert not BobInterface.extends(FunInterface)
assert not BobInterface.extends(BarInterface)
assert BarInterface.extends(FunInterface)
assert not BarInterface.extends(BazInterface)
def testVerifyImplementation(self):
from Interface.Verify import verifyClass
assert verifyClass(FooInterface, Foo)
assert Interface.isImplementedBy(I1)
def test_names(self):
names = list(_I2.names()); names.sort()
self.assertEqual(names, ['f21', 'f22', 'f23'])
names = list(_I2.names(1)); names.sort()
self.assertEqual(names, ['a1', 'f11', 'f12', 'f21', 'f22', 'f23'])
def test_namesAndDescriptions(self):
names = [nd[0] for nd in _I2.namesAndDescriptions()]; names.sort()
self.assertEqual(names, ['f21', 'f22', 'f23'])
names = [nd[0] for nd in _I2.namesAndDescriptions(1)]; names.sort()
self.assertEqual(names, ['a1', 'f11', 'f12', 'f21', 'f22', 'f23'])
for name, d in _I2.namesAndDescriptions(1):
self.assertEqual(name, d.__name__)
def test_getDescriptionFor(self):
self.assertEqual(_I2.getDescriptionFor('f11').__name__, 'f11')
self.assertEqual(_I2.getDescriptionFor('f22').__name__, 'f22')
self.assertEqual(_I2.queryDescriptionFor('f33', self), self)
self.assertRaises(KeyError, _I2.getDescriptionFor, 'f33')
def testAttr(self):
description = _I2.getDescriptionFor('a1')
self.assertEqual(description.__name__, 'a1')
self.assertEqual(description.__doc__, 'This is an attribute')
class _I1(Interface):
a1 = Attribute("This is an attribute")
def f11(): pass
def f12(): pass
class __I1(_I1): pass
class ___I1(__I1): pass
class _I2(___I1):
def f21(): pass
def f22(): pass
def f23(): pass
def test_suite():
return unittest.makeSuite(InterfaceTests)
def main():
unittest.TextTestRunner().run(test_suite())
if __name__=="__main__":
main()
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""
Revision information:
$Id$
"""
from __future__ import nested_scopes
from Interface import Interface
from Interface.Verify import verifyClass, verifyObject
from Interface.Exceptions import DoesNotImplement, BrokenImplementation
from Interface.Exceptions import BrokenMethodImplementation
import unittest, sys
class Test(unittest.TestCase):
def testNotImplemented(self):
class C: pass
class I(Interface): pass
self.assertRaises(DoesNotImplement, verifyClass, I, C)
C.__implements__=I
verifyClass(I, C)
def testMissingAttr(self):
class I(Interface):
def f(): pass
class C:
__implements__=I
self.assertRaises(BrokenImplementation, verifyClass, I, C)
C.f=lambda self: None
verifyClass(I, C)
def testMissingAttr_with_Extended_Interface(self):
class II(Interface):
def f():
pass
class I(II):
pass
class C:
__implements__=I
self.assertRaises(BrokenImplementation, verifyClass, I, C)
C.f=lambda self: None
verifyClass(I, C)
def testWrongArgs(self):
class I(Interface):
def f(a): pass
class C:
def f(self, b): pass
__implements__=I
# We no longer require names to match.
#self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a: None
verifyClass(I, C)
C.f=lambda self, **kw: None
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, *args: None
verifyClass(I, C)
C.f=lambda self, a, *args, **kw: None
verifyClass(I, C)
C.f=lambda self, *args: None
verifyClass(I, C)
def testExtraArgs(self):
class I(Interface):
def f(a): pass
class C:
def f(self, a, b): pass
__implements__=I
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a: None
verifyClass(I, C)
C.f=lambda self, a, b=None: None
verifyClass(I, C)
def testNoVar(self):
class I(Interface):
def f(a, *args): pass
class C:
def f(self, a): pass
__implements__=I
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, *foo: None
verifyClass(I, C)
def testNoKW(self):
class I(Interface):
def f(a, **args): pass
class C:
def f(self, a): pass
__implements__=I
self.assertRaises(BrokenMethodImplementation, verifyClass, I, C)
C.f=lambda self, a, **foo: None
verifyClass(I, C)
def testModule(self):
from Interface.tests.IFoo import IFoo
from Interface.tests import dummy
verifyObject(IFoo, dummy)
def test_suite():
loader=unittest.TestLoader()
return loader.loadTestsFromTestCase(Test)
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import unittest, sys
from Interface.Implements import visitImplements
from Interface import Interface
from Interface.Exceptions import BadImplements
class I1(Interface): pass
class I2(Interface): pass
class I3(Interface): pass
class Test(unittest.TestCase):
def testSimpleImplements(self):
data=[]
visitImplements(I1, None, data.append)
self.assertEqual(data, [I1])
def testSimpleBadImplements(self):
data=[]
self.assertRaises(BadImplements,
visitImplements, unittest, None, data.append)
def testComplexImplements(self):
data=[]
visitImplements((I1, (I2, I3)), None, data.append)
data = map(lambda i: i.__name__, data)
self.assertEqual(data, ['I1', 'I2', 'I3'])
def testComplexBadImplements(self):
data=[]
self.assertRaises(BadImplements,
visitImplements, (I1, (I2, unittest)),
None, data.append)
def test_suite():
loader=unittest.TestLoader()
return loader.loadTestsFromTestCase(Test)
if __name__=='__main__':
unittest.TextTestRunner().run(test_suite())
##############################################################################
#
# Copyright (c) 2005 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Unit tests for Z3 -> Z2 bridge utilities.
$Id$
"""
import unittest
from zope.testing.doctest import DocFileSuite
def test_suite():
return unittest.TestSuite([
DocFileSuite('bridge.txt', package='Interface.tests'),
])
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
from Interface import Interface
from Interface.Attribute import Attribute
class mytest(Interface):
pass
class C:
def m1(self, a, b):
"return 1"
return 1
def m2(self, a, b):
"return 2"
return 2
# testInstancesOfClassImplements
# YAGNI IC=Interface.impliedInterface(C)
class IC(Interface):
def m1(a, b):
"return 1"
def m2(a, b):
"return 2"
C.__implements__=IC
class I1(Interface):
def ma():
"blah"
class I2(I1): pass
class I3(Interface): pass
class I4(Interface): pass
class A(I1.deferred()):
__implements__=I1
class B:
__implements__=I2, I3
class D(A, B): pass
class E(A, B):
__implements__ = A.__implements__, C.__implements__
class FooInterface(Interface):
""" This is an Abstract Base Class """
foobar = Attribute("fuzzed over beyond all recognition")
def aMethod(foo, bar, bingo):
""" This is aMethod """
def anotherMethod(foo=6, bar="where you get sloshed", bingo=(1,3,)):
""" This is anotherMethod """
def wammy(zip, *argues):
""" yadda yadda """
def useless(**keywords):
""" useless code is fun! """
class Foo:
""" A concrete class """
__implements__ = FooInterface,
foobar = "yeah"
def aMethod(self, foo, bar, bingo):
""" This is aMethod """
return "barf!"
def anotherMethod(self, foo=6, bar="where you get sloshed", bingo=(1,3,)):
""" This is anotherMethod """
return "barf!"
def wammy(self, zip, *argues):
""" yadda yadda """
return "barf!"
def useless(self, **keywords):
""" useless code is fun! """
return "barf!"
foo_instance = Foo()
class Blah:
pass
new = Interface.__class__
FunInterface = new('FunInterface')
BarInterface = new('BarInterface', [FunInterface])
BobInterface = new('BobInterface')
BazInterface = new('BazInterface', [BobInterface, BarInterface])
...@@ -22,7 +22,6 @@ from DTMLMethod import DTMLMethod, decapitate ...@@ -22,7 +22,6 @@ from DTMLMethod import DTMLMethod, decapitate
from PropertyManager import PropertyManager from PropertyManager import PropertyManager
from webdav.common import rfc1123_date from webdav.common import rfc1123_date
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from webdav.WriteLockInterface import WriteLockInterface
from sgmllib import SGMLParser from sgmllib import SGMLParser
from urllib import quote from urllib import quote
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
...@@ -38,7 +37,6 @@ class DTMLDocument(PropertyManager, DTMLMethod): ...@@ -38,7 +37,6 @@ class DTMLDocument(PropertyManager, DTMLMethod):
"""DTML Document objects are DocumentTemplate.HTML objects that act """DTML Document objects are DocumentTemplate.HTML objects that act
as methods whose 'self' is the DTML Document itself.""" as methods whose 'self' is the DTML Document itself."""
__implements__ = (WriteLockInterface,)
meta_type='DTML Document' meta_type='DTML Document'
icon ='p_/dtmldoc' icon ='p_/dtmldoc'
......
...@@ -24,7 +24,6 @@ from AccessControl import ClassSecurityInfo ...@@ -24,7 +24,6 @@ from AccessControl import ClassSecurityInfo
from AccessControl.Role import RoleManager from AccessControl.Role import RoleManager
from webdav.common import rfc1123_date from webdav.common import rfc1123_date
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from webdav.WriteLockInterface import WriteLockInterface
from ZDOM import ElementWithTitle from ZDOM import ElementWithTitle
from DateTime.DateTime import DateTime from DateTime.DateTime import DateTime
from urllib import quote from urllib import quote
...@@ -56,8 +55,6 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager, ...@@ -56,8 +55,6 @@ class DTMLMethod(RestrictedDTML, HTML, Acquisition.Implicit, RoleManager,
index_html=None # Prevent accidental acquisition index_html=None # Prevent accidental acquisition
_cache_namespace_keys=() _cache_namespace_keys=()
__implements__ = (WriteLockInterface,)
security = ClassSecurityInfo() security = ClassSecurityInfo()
security.declareObjectProtected(View) security.declareObjectProtected(View)
......
...@@ -24,7 +24,6 @@ from AccessControl import Unauthorized ...@@ -24,7 +24,6 @@ from AccessControl import Unauthorized
from AccessControl.Permissions import add_page_templates from AccessControl.Permissions import add_page_templates
from AccessControl.Permissions import add_user_folders from AccessControl.Permissions import add_user_folders
from Globals import DTMLFile from Globals import DTMLFile
from webdav.WriteLockInterface import WriteLockInterface
from zope.interface import implements from zope.interface import implements
import FindSupport import FindSupport
...@@ -84,7 +83,6 @@ class Folder( ...@@ -84,7 +83,6 @@ class Folder(
a management interface and can have arbitrary properties. a management interface and can have arbitrary properties.
""" """
__implements__ = (WriteLockInterface,)
implements(IFolder) implements(IFolder)
meta_type='Folder' meta_type='Folder'
......
##############################################################################
#
# Copyright (c) 2003 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Order support interfaces.
$Id$
"""
# create IOrderedContainer
from Interface.bridge import createZope3Bridge
from OFS.interfaces import IOrderedContainer as z3IOrderedContainer
import IOrderSupport
createZope3Bridge(z3IOrderedContainer, IOrderSupport, 'IOrderedContainer')
del createZope3Bridge
del z3IOrderedContainer
del IOrderSupport
...@@ -16,6 +16,8 @@ $Id$ ...@@ -16,6 +16,8 @@ $Id$
""" """
import struct import struct
from zope.contenttype import guess_content_type from zope.contenttype import guess_content_type
from zope.interface import implementedBy
from zope.interface import implements
from Globals import DTMLFile from Globals import DTMLFile
from Globals import InitializeClass from Globals import InitializeClass
from PropertyManager import PropertyManager from PropertyManager import PropertyManager
...@@ -27,8 +29,8 @@ from AccessControl.Permissions import view as View ...@@ -27,8 +29,8 @@ from AccessControl.Permissions import view as View
from AccessControl.Permissions import ftp_access from AccessControl.Permissions import ftp_access
from AccessControl.Permissions import delete_objects from AccessControl.Permissions import delete_objects
from webdav.common import rfc1123_date from webdav.common import rfc1123_date
from webdav.interfaces import IWriteLock
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from webdav.WriteLockInterface import WriteLockInterface
from SimpleItem import Item_w__name__ from SimpleItem import Item_w__name__
from cStringIO import StringIO from cStringIO import StringIO
from Globals import Persistent from Globals import Persistent
...@@ -77,7 +79,15 @@ class File(Persistent, Implicit, PropertyManager, ...@@ -77,7 +79,15 @@ class File(Persistent, Implicit, PropertyManager,
RoleManager, Item_w__name__, Cacheable): RoleManager, Item_w__name__, Cacheable):
"""A File object is a content object for arbitrary files.""" """A File object is a content object for arbitrary files."""
__implements__ = (WriteLockInterface, HTTPRangeSupport.HTTPRangeInterface) implements(implementedBy(Persistent),
implementedBy(Implicit),
implementedBy(PropertyManager),
implementedBy(RoleManager),
implementedBy(Item_w__name__),
implementedBy(Cacheable),
IWriteLock,
HTTPRangeSupport.HTTPRangeInterface,
)
meta_type='File' meta_type='File'
security = ClassSecurityInfo() security = ClassSecurityInfo()
...@@ -726,7 +736,6 @@ class Image(File): ...@@ -726,7 +736,6 @@ class Image(File):
as File objects. Images also have a string representation that as File objects. Images also have a string representation that
renders an HTML 'IMG' tag. renders an HTML 'IMG' tag.
""" """
__implements__ = (WriteLockInterface,)
meta_type='Image' meta_type='Image'
security = ClassSecurityInfo() security = ClassSecurityInfo()
......
...@@ -26,8 +26,7 @@ from Globals import InitializeClass ...@@ -26,8 +26,7 @@ from Globals import InitializeClass
from zope.interface import implements from zope.interface import implements
from zope.app.container.contained import notifyContainerModified from zope.app.container.contained import notifyContainerModified
from interfaces import IOrderedContainer as z3IOrderedContainer from interfaces import IOrderedContainer as IOrderedContainer
from IOrderSupport import IOrderedContainer as z2IOrderedContainer
from ObjectManager import ObjectManager from ObjectManager import ObjectManager
...@@ -41,8 +40,7 @@ class OrderSupport(object): ...@@ -41,8 +40,7 @@ class OrderSupport(object):
is totally user-specific. is totally user-specific.
""" """
__implements__ = z2IOrderedContainer implements(IOrderedContainer)
implements(z3IOrderedContainer)
security = ClassSecurityInfo() security = ClassSecurityInfo()
has_order_support = 1 has_order_support = 1
......
...@@ -66,9 +66,6 @@ class OrderedFolder(OrderSupport, Folder): ...@@ -66,9 +66,6 @@ class OrderedFolder(OrderSupport, Folder):
""" Extends the default Folder by order support. """ Extends the default Folder by order support.
""" """
__implements__ = (OrderSupport.__implements__,
Folder.__implements__)
implements(IOrderedFolder) implements(IOrderedFolder)
meta_type='Folder (Ordered)' meta_type='Folder (Ordered)'
......
...@@ -16,7 +16,6 @@ $Id$ ...@@ -16,7 +16,6 @@ $Id$
""" """
import time, App.Management, Globals, sys import time, App.Management, Globals, sys
from webdav.interfaces import IWriteLock from webdav.interfaces import IWriteLock
from webdav.WriteLockInterface import WriteLockInterface
from ZPublisher.Converters import type_converters from ZPublisher.Converters import type_converters
from Globals import InitializeClass from Globals import InitializeClass
from Globals import DTMLFile, MessageDialog from Globals import DTMLFile, MessageDialog
...@@ -585,8 +584,7 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -585,8 +584,7 @@ class DAVProperties(Virtual, PropertySheet, View):
def dav__supportedlock(self): def dav__supportedlock(self):
vself = self.v_self() vself = self.v_self()
out = '\n' out = '\n'
if IWriteLock.providedBy(vself) or \ if IWriteLock.providedBy(vself):
WriteLockInterface.isImplementedBy(vself):
out += (' <n:lockentry>\n' out += (' <n:lockentry>\n'
' <d:lockscope><d:exclusive/></d:lockscope>\n' ' <d:lockscope><d:exclusive/></d:lockscope>\n'
' <d:locktype><d:write/></d:locktype>\n' ' <d:locktype><d:write/></d:locktype>\n'
...@@ -599,8 +597,7 @@ class DAVProperties(Virtual, PropertySheet, View): ...@@ -599,8 +597,7 @@ class DAVProperties(Virtual, PropertySheet, View):
vself = self.v_self() vself = self.v_self()
out = '\n' out = '\n'
if IWriteLock.providedBy(vself) or \ if IWriteLock.providedBy(vself):
WriteLockInterface.isImplementedBy(vself):
locks = vself.wl_lockValues(killinvalids=1) locks = vself.wl_lockValues(killinvalids=1)
for lock in locks: for lock in locks:
......
...@@ -243,14 +243,14 @@ class FileTests(unittest.TestCase): ...@@ -243,14 +243,14 @@ class FileTests(unittest.TestCase):
self.assertEqual(len(results), 1) self.assertEqual(len(results), 1)
self.assertEqual(results[0][1], self.file) self.assertEqual(results[0][1], self.file)
def test_z2interfaces(self): def test_z3interfaces(self):
from Interface.Verify import verifyClass from zope.interface.verify import verifyClass
from OFS.Image import File from OFS.Image import File
from webdav.WriteLockInterface import WriteLockInterface from webdav.interfaces import IWriteLock
from ZPublisher.HTTPRangeSupport import HTTPRangeInterface from ZPublisher.HTTPRangeSupport import HTTPRangeInterface
verifyClass(HTTPRangeInterface, File) verifyClass(HTTPRangeInterface, File)
verifyClass(WriteLockInterface, File) verifyClass(IWriteLock, File)
def testUnicode(self): def testUnicode(self):
val = u'some unicode string here' val = u'some unicode string here'
...@@ -287,12 +287,12 @@ class ImageTests(FileTests): ...@@ -287,12 +287,12 @@ class ImageTests(FileTests):
def testViewImageOrFile(self): def testViewImageOrFile(self):
pass # dtml method,screw it pass # dtml method,screw it
def test_z2interfaces(self): def test_z3interfaces(self):
from Interface.Verify import verifyClass from zope.interface.verify import verifyClass
from OFS.Image import Image from OFS.Image import Image
from webdav.WriteLockInterface import WriteLockInterface from webdav.interfaces import IWriteLock
verifyClass(WriteLockInterface, Image) verifyClass(IWriteLock, Image)
def test_suite(): def test_suite():
return unittest.TestSuite(( return unittest.TestSuite((
......
...@@ -3,13 +3,6 @@ import unittest ...@@ -3,13 +3,6 @@ import unittest
class TestFolder(unittest.TestCase): class TestFolder(unittest.TestCase):
def test_z2interfaces(self):
from Interface.Verify import verifyClass
from OFS.Folder import Folder
from webdav.WriteLockInterface import WriteLockInterface
verifyClass(WriteLockInterface, Folder)
def test_z3interfaces(self): def test_z3interfaces(self):
from OFS.Folder import Folder from OFS.Folder import Folder
from OFS.interfaces import IFolder from OFS.interfaces import IFolder
......
...@@ -42,13 +42,6 @@ class TestOrderSupport(unittest.TestCase): ...@@ -42,13 +42,6 @@ class TestOrderSupport(unittest.TestCase):
f.o4 = DummyObject('o4', 'mt2') f.o4 = DummyObject('o4', 'mt2')
return f return f
def test_z2interfaces(self):
from Interface.Verify import verifyClass
from OFS.IOrderSupport import IOrderedContainer
from OFS.OrderSupport import OrderSupport
verifyClass(IOrderedContainer, OrderSupport)
def test_z3interfaces(self): def test_z3interfaces(self):
from OFS.interfaces import IOrderedContainer from OFS.interfaces import IOrderedContainer
from OFS.OrderSupport import OrderSupport from OFS.OrderSupport import OrderSupport
......
...@@ -3,15 +3,6 @@ import unittest ...@@ -3,15 +3,6 @@ import unittest
class TestOrderedFolder(unittest.TestCase): class TestOrderedFolder(unittest.TestCase):
def test_z2interfaces(self):
from Interface.Verify import verifyClass
from OFS.IOrderSupport import IOrderedContainer
from OFS.OrderedFolder import OrderedFolder
from webdav.WriteLockInterface import WriteLockInterface
verifyClass(IOrderedContainer, OrderedFolder)
verifyClass(WriteLockInterface, OrderedFolder)
def test_z3interfaces(self): def test_z3interfaces(self):
from OFS.interfaces import IOrderedContainer from OFS.interfaces import IOrderedContainer
from OFS.interfaces import IOrderedFolder from OFS.interfaces import IOrderedFolder
......
import unittest
class DTMLDocumentTests(unittest.TestCase):
def _getTargetClass(self):
from OFS.DTMLDocument import DTMLDocument
return DTMLDocument
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_class_conforms_to_IWriteLock(self):
from zope.interface.verify import verifyClass
from webdav.interfaces import IWriteLock
verifyClass(IWriteLock, self._getTargetClass())
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(DTMLDocumentTests),
))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
import unittest
class DTMLMethodTests(unittest.TestCase):
def _getTargetClass(self):
from OFS.DTMLMethod import DTMLMethod
return DTMLMethod
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_class_conforms_to_IWriteLock(self):
from zope.interface.verify import verifyClass
from webdav.interfaces import IWriteLock
verifyClass(IWriteLock, self._getTargetClass())
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(DTMLMethodTests),
))
if __name__ == '__main__':
unittest.main(defaultTest='test_suite')
##############################################################################
#
# Copyright (c) 2004, 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Z2 -> Z3 bridge utilities.
$Id$
"""
from Interface._InterfaceClass import Interface as Z2_InterfaceClass
from Interface import Interface as Z2_Interface
from Interface import Attribute as Z2_Attribute
from Interface.Method import Method as Z2_Method
from zope.interface.interface import InterfaceClass as Z3_InterfaceClass
from zope.interface.interface import Interface as Z3_Interface
from zope.interface.interface import Attribute as Z3_Attribute
from zope.interface.interface import Method as Z3_Method
_bridges = {Z2_Interface: Z3_Interface}
def fromZ2Interface(z2i):
""" Return a Zope 3 interface corresponding to 'z2i'.
o 'z2i' must be a Zope 2 interface.
"""
if not isinstance(z2i, Z2_InterfaceClass):
raise ValueError, 'Not a Zope 2 interface!'
if z2i in _bridges:
return _bridges[z2i]
name = z2i.getName()
bases = [ fromZ2Interface(x) for x in z2i.getBases() ]
attrs = {}
for k, v in z2i.namesAndDescriptions():
if isinstance(v, Z2_Method):
v = fromZ2Method(v)
elif isinstance(v, Z2_Attribute):
v = fromZ2Attribute(v)
attrs[k] = v
# XXX: Note that we pass the original interface's __module__;
# we may live to regret that.
z3i = Z3_InterfaceClass(name=name,
bases=tuple(bases),
attrs=attrs,
__doc__=z2i.getDoc(),
__module__=z2i.__module__)
_bridges[z2i] = z3i
return z3i
def fromZ2Attribute(z2a):
""" Return a Zope 3 interface attribute corresponding to 'z2a'.
o 'z2a' must be a Zope 2 interface attribute.
"""
if not isinstance(z2a, Z2_Attribute):
raise ValueError, 'Not a Zope 2 interface attribute!'
return Z3_Attribute(z2a.getName(), z2a.getDoc())
def fromZ2Method(z2m):
""" Return a Zope 3 interface method corresponding to 'z2m'.
o 'z2m' must be a Zope 2 interface method.
"""
if not isinstance(z2m, Z2_Method):
raise ValueError, 'Not a Zope 2 interface method!'
z3m = Z3_Method(z2m.getName(), z2m.getDoc())
sig = z2m.getSignatureInfo()
z3m.positional = sig['positional']
z3m.required = sig['required']
z3m.optional = sig['optional']
z3m.varargs = sig['varargs']
z3m.kwargs = sig['kwargs']
return z3m
...@@ -131,6 +131,8 @@ work. Later on, you will also have to change calls to ...@@ -131,6 +131,8 @@ work. Later on, you will also have to change calls to
``isImplementedBy`` has been deprecated (you'll see the ``isImplementedBy`` has been deprecated (you'll see the
DeprecationWarnings in your Zope log). DeprecationWarnings in your Zope log).
N.B.: As of Zope 2.12, the old Zope2 interfaces are *removed*.
Adapters Adapters
-------- --------
......
...@@ -37,7 +37,6 @@ from zope.publisher.interfaces.browser import IDefaultBrowserLayer ...@@ -37,7 +37,6 @@ from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.security.interfaces import IPermission from zope.security.interfaces import IPermission
from Products.Five import isFiveMethod from Products.Five import isFiveMethod
from Products.Five.bridge import fromZ2Interface
from Products.Five.browser.metaconfigure import page from Products.Five.browser.metaconfigure import page
debug_mode = App.config.getConfiguration().debug_mode debug_mode = App.config.getConfiguration().debug_mode
...@@ -105,29 +104,6 @@ def implements(_context, class_, interface): ...@@ -105,29 +104,6 @@ def implements(_context, class_, interface):
interface) interface)
) )
def createZope2Bridge(zope2, package, name):
# Map a Zope 2 interface into a Zope3 interface, seated within 'package'
# as 'name'.
z3i = fromZ2Interface(zope2)
if name is not None:
z3i.__dict__['__name__'] = name
z3i.__dict__['__module__'] = package.__name__
setattr(package, z3i.getName(), z3i)
def bridge(_context, zope2, package, name=None):
# Directive handler for <five:bridge> directive.
# N.B.: We have to do the work early, or else we won't be able
# to use the synthesized interface in other ZCML directives.
createZope2Bridge(zope2, package, name)
# Faux action, only for conflict resolution.
_context.action(
discriminator = (zope2,),
)
def pagesFromDirectory(_context, directory, module, for_=None, def pagesFromDirectory(_context, directory, module, for_=None,
layer=IDefaultBrowserLayer, permission='zope.Public'): layer=IDefaultBrowserLayer, permission='zope.Public'):
......
...@@ -94,12 +94,6 @@ ...@@ -94,12 +94,6 @@
handler=".fiveconfigure.pagesFromDirectory" handler=".fiveconfigure.pagesFromDirectory"
/> />
<meta:directive
name="bridge"
schema=".fivedirectives.IBridgeDirective"
handler=".fiveconfigure.bridge"
/>
<meta:directive <meta:directive
name="registerClass" name="registerClass"
schema=".fivedirectives.IRegisterClassDirective" schema=".fivedirectives.IRegisterClassDirective"
......
======
Bridge
======
The ``Five.bridge`` module provides functionality to convert a Zope 2
interface into a Zope 3 one. First we'll import all we know about
interfaces from the two generations:
>>> from Interface import Interface as Z2_Interface
>>> from Interface import Attribute as Z2_Attribute
>>> from zope.interface import Interface as Z3_Interface
>>> from zope.interface import Attribute as Z3_Attribute
>>> from zope.interface.interface import Method as Z3_Method
An empty interface
------------------
>>> class IEmpty(Z2_Interface):
... pass
>>> from Products.Five.bridge import fromZ2Interface
>>> IEmptyConverted = fromZ2Interface(IEmpty)
>>> Z3_Interface.isEqualOrExtendedBy(IEmptyConverted)
True
>>> len(IEmptyConverted.names())
0
Bases
-----
>>> class IBase(Z2_Interface):
... pass
>>> class IDerived(IBase):
... pass
>>> IBase.getBases() == (Z2_Interface,)
True
>>> IDerived.getBases() == (IBase,)
True
>>> IDerived.extends(IBase)
1
>>> IDerived.extends(IEmpty)
0
>>> IBaseConverted = fromZ2Interface(IBase)
>>> IDerivedConverted = fromZ2Interface(IDerived)
>>> IBaseConverted.getBases() == (Z3_Interface,)
True
>>> IDerivedConverted.getBases() == (IBaseConverted,)
True
>>> IDerivedConverted.extends(IBaseConverted)
True
>>> IDerivedConverted.extends(IEmptyConverted)
False
Attributes
----------
>>> class IAttributes(Z2_Interface):
... one = Z2_Attribute('one', 'One attribute')
... another = Z2_Attribute('another', 'Another attribute')
>>> converted = fromZ2Interface(IAttributes)
>>> Z3_Interface.isEqualOrExtendedBy(converted)
True
>>> len(converted.names())
2
>>> 'one' in converted.names()
True
>>> 'another' in converted.names()
True
>>> one = converted.getDescriptionFor('one')
>>> isinstance(one, Z3_Attribute)
True
>>> one.getName()
'one'
>>> one.getDoc()
'One attribute'
>>> another = converted.getDescriptionFor('another')
>>> isinstance(another, Z3_Attribute)
True
>>> another.getName()
'another'
>>> another.getDoc()
'Another attribute'
Methods
-------
>>> class IMethods(Z2_Interface):
... def one():
... """One method."""
... def another(arg1, arg2):
... """Another method, taking arguments."""
>>> converted = fromZ2Interface(IMethods)
>>> Z3_Interface.isEqualOrExtendedBy(converted)
True
>>> len(converted.names())
2
>>> 'one' in converted.names()
True
>>> 'another' in converted.names()
True
>>> one = converted.getDescriptionFor('one')
>>> isinstance(one, Z3_Method)
True
>>> one.getName()
'one'
>>> one.getDoc()
'One method.'
>>> one.getSignatureString()
'()'
>>> another = converted.getDescriptionFor('another')
>>> isinstance(another, Z3_Method)
True
>>> another.getName()
'another'
>>> another.getDoc()
'Another method, taking arguments.'
>>> another.getSignatureString()
'(arg1, arg2)'
Invalid parameters
------------------
>>> fromZ2Interface(None)
Traceback (most recent call last):
...
ValueError: Not a Zope 2 interface!
>>> fromZ2Interface(object())
Traceback (most recent call last):
...
ValueError: Not a Zope 2 interface!
>>> class IZ3_NotAllowed(Z3_Interface):
... pass
>>> fromZ2Interface(IZ3_NotAllowed)
Traceback (most recent call last):
...
ValueError: Not a Zope 2 interface!
##############################################################################
#
# Copyright (c) 2004, 2005 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Unit tests for Z2 -> Z3 bridge utilities.
$Id$
"""
import os, sys
if __name__ == '__main__':
execfile(os.path.join(sys.path[0], 'framework.py'))
def test_suite():
from Testing.ZopeTestCase import ZopeDocFileSuite
return ZopeDocFileSuite('bridge.txt', package="Products.Five.tests")
if __name__ == '__main__':
framework()
...@@ -19,7 +19,9 @@ import os ...@@ -19,7 +19,9 @@ import os
from zope.app.publisher.browser import viewmeta from zope.app.publisher.browser import viewmeta
from zope.component import zcml from zope.component import zcml
from zope.configuration.exceptions import ConfigurationError from zope.configuration.exceptions import ConfigurationError
from zope.interface import Interface, classImplements from zope.interface import classImplements
from zope.interface import implements
from zope.interface import Interface
from zope.publisher.interfaces.browser import IBrowserView from zope.publisher.interfaces.browser import IBrowserView
from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.publisher.interfaces.browser import IDefaultBrowserLayer
from zope.viewlet import interfaces from zope.viewlet import interfaces
......
...@@ -34,7 +34,6 @@ from AccessControl.Permissions import view, ftp_access, change_page_templates ...@@ -34,7 +34,6 @@ from AccessControl.Permissions import view, ftp_access, change_page_templates
from AccessControl.Permissions import view_management_screens from AccessControl.Permissions import view_management_screens
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from webdav.WriteLockInterface import WriteLockInterface
from Products.PageTemplates.PageTemplate import PageTemplate from Products.PageTemplates.PageTemplate import PageTemplate
from Products.PageTemplates.PageTemplateFile import PageTemplateFile from Products.PageTemplates.PageTemplateFile import PageTemplateFile
...@@ -69,8 +68,6 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable, ...@@ -69,8 +68,6 @@ class ZopePageTemplate(Script, PageTemplate, Historical, Cacheable,
Traversable, PropertyManager): Traversable, PropertyManager):
"Zope wrapper for Page Template using TAL, TALES, and METAL" "Zope wrapper for Page Template using TAL, TALES, and METAL"
__implements__ = (WriteLockInterface,)
meta_type = 'Page Template' meta_type = 'Page Template'
output_encoding = 'iso-8859-15' # provide default for old instances output_encoding = 'iso-8859-15' # provide default for old instances
......
...@@ -204,6 +204,11 @@ class ZPTUnicodeEncodingConflictResolution(ZopeTestCase): ...@@ -204,6 +204,11 @@ class ZPTUnicodeEncodingConflictResolution(ZopeTestCase):
class ZopePageTemplateFileTests(ZopeTestCase): class ZopePageTemplateFileTests(ZopeTestCase):
def test_class_conforms_to_IWriteLock(self):
from zope.interface.verify import verifyClass
from webdav.interfaces import IWriteLock
verifyClass(IWriteLock, ZopePageTemplate)
def testPT_RenderWithAscii(self): def testPT_RenderWithAscii(self):
manage_addPageTemplate(self.app, 'test', manage_addPageTemplate(self.app, 'test',
text=ascii_str, encoding='ascii') text=ascii_str, encoding='ascii')
......
...@@ -84,8 +84,6 @@ class DateIndex(UnIndex, PropertyManager): ...@@ -84,8 +84,6 @@ class DateIndex(UnIndex, PropertyManager):
"""Index for dates. """Index for dates.
""" """
__implements__ = UnIndex.__implements__
implements(IDateIndex) implements(IDateIndex)
meta_type = 'DateIndex' meta_type = 'DateIndex'
......
...@@ -56,8 +56,6 @@ class DateRangeIndex(UnIndex): ...@@ -56,8 +56,6 @@ class DateRangeIndex(UnIndex):
- Objects which match only during a specific interval. - Objects which match only during a specific interval.
""" """
__implements__ = UnIndex.__implements__
implements(IDateRangeIndex) implements(IDateRangeIndex)
security = ClassSecurityInfo() security = ClassSecurityInfo()
......
...@@ -24,9 +24,6 @@ class FieldIndex(UnIndex): ...@@ -24,9 +24,6 @@ class FieldIndex(UnIndex):
"""Index for simple fields. """Index for simple fields.
""" """
__implements__ = UnIndex.__implements__
meta_type="FieldIndex" meta_type="FieldIndex"
manage_options= ( manage_options= (
......
...@@ -35,9 +35,6 @@ class KeywordIndex(UnIndex): ...@@ -35,9 +35,6 @@ class KeywordIndex(UnIndex):
This should have an _apply_index that returns a relevance score This should have an _apply_index that returns a relevance score
""" """
__implements__ = UnIndex.__implements__
meta_type="KeywordIndex" meta_type="KeywordIndex"
manage_options= ( manage_options= (
......
...@@ -25,7 +25,6 @@ from BTrees.IIBTree import IITreeSet, IISet, intersection, union ...@@ -25,7 +25,6 @@ from BTrees.IIBTree import IITreeSet, IISet, intersection, union
from BTrees.Length import Length from BTrees.Length import Length
from zope.interface import implements from zope.interface import implements
from Products.PluginIndexes import PluggableIndex
from Products.PluginIndexes.common import safe_callable from Products.PluginIndexes.common import safe_callable
from Products.PluginIndexes.common.util import parseIndexRequest from Products.PluginIndexes.common.util import parseIndexRequest
from Products.PluginIndexes.interfaces import IPathIndex from Products.PluginIndexes.interfaces import IPathIndex
...@@ -50,8 +49,6 @@ class PathIndex(Persistent, SimpleItem): ...@@ -50,8 +49,6 @@ class PathIndex(Persistent, SimpleItem):
- the value is a mapping 'level of the path component' to - the value is a mapping 'level of the path component' to
'all docids with this path component on this level' 'all docids with this path component on this level'
""" """
__implements__ = (PluggableIndex.UniqueValueIndex,)
implements(IPathIndex, IUniqueValueIndex) implements(IPathIndex, IUniqueValueIndex)
meta_type="PathIndex" meta_type="PathIndex"
......
...@@ -30,7 +30,6 @@ from BTrees.IIBTree import difference, weightedIntersection ...@@ -30,7 +30,6 @@ from BTrees.IIBTree import difference, weightedIntersection
from BTrees.OIBTree import OIBTree from BTrees.OIBTree import OIBTree
from zope.interface import implements from zope.interface import implements
from Products.PluginIndexes import PluggableIndex
from Products.PluginIndexes.common import safe_callable from Products.PluginIndexes.common import safe_callable
from Products.PluginIndexes.common.ResultList import ResultList from Products.PluginIndexes.common.ResultList import ResultList
from Products.PluginIndexes.common.util import parseIndexRequest from Products.PluginIndexes.common.util import parseIndexRequest
...@@ -77,8 +76,6 @@ class TextIndex(Persistent, Implicit, SimpleItem): ...@@ -77,8 +76,6 @@ class TextIndex(Persistent, Implicit, SimpleItem):
This isn't exactly how things are represented in memory, many This isn't exactly how things are represented in memory, many
optimizations happen along the way. optimizations happen along the way.
""" """
__implements__ = (PluggableIndex.PluggableIndexInterface,)
implements(ITextIndex, IPluggableIndex) implements(ITextIndex, IPluggableIndex)
meta_type='TextIndex' meta_type='TextIndex'
......
...@@ -23,7 +23,6 @@ from BTrees.OOBTree import OOBTree ...@@ -23,7 +23,6 @@ from BTrees.OOBTree import OOBTree
from BTrees.IIBTree import IITreeSet,intersection,union from BTrees.IIBTree import IITreeSet,intersection,union
from zope.interface import implements from zope.interface import implements
from Products.PluginIndexes import PluggableIndex
from Products.PluginIndexes.common.util import parseIndexRequest from Products.PluginIndexes.common.util import parseIndexRequest
from Products.PluginIndexes.interfaces import IPluggableIndex from Products.PluginIndexes.interfaces import IPluggableIndex
from Products.PluginIndexes.interfaces import ITopicIndex from Products.PluginIndexes.interfaces import ITopicIndex
...@@ -41,8 +40,6 @@ class TopicIndex(Persistent, SimpleItem): ...@@ -41,8 +40,6 @@ class TopicIndex(Persistent, SimpleItem):
Every FilteredSet object consists of an expression and and IISet with all Every FilteredSet object consists of an expression and and IISet with all
Ids of indexed objects that eval with this expression to 1. Ids of indexed objects that eval with this expression to 1.
""" """
__implements__ = (PluggableIndex.PluggableIndexInterface,)
implements(ITopicIndex, IPluggableIndex) implements(ITopicIndex, IPluggableIndex)
meta_type="TopicIndex" meta_type="TopicIndex"
......
...@@ -11,7 +11,6 @@ ...@@ -11,7 +11,6 @@
# #
############################################################################## ##############################################################################
import common.PluggableIndex as PluggableIndex
import common.ResultList as ResultList import common.ResultList as ResultList
import common.UnIndex as UnIndex import common.UnIndex as UnIndex
......
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Pluggable Index interfaces.
$Id$
"""
# create PluggableIndexInterface, UniqueValueIndex, SortIndex
from Interface.bridge import createZope3Bridge
from Products.PluginIndexes.interfaces import IPluggableIndex
from Products.PluginIndexes.interfaces import ISortIndex
from Products.PluginIndexes.interfaces import IUniqueValueIndex
import PluggableIndex
createZope3Bridge(IPluggableIndex, PluggableIndex, 'PluggableIndexInterface')
createZope3Bridge(ISortIndex, PluggableIndex, 'SortIndex')
createZope3Bridge(IUniqueValueIndex, PluggableIndex, 'UniqueValueIndex')
del createZope3Bridge
del IPluggableIndex
del ISortIndex
del IUniqueValueIndex
del PluggableIndex
...@@ -27,7 +27,6 @@ from OFS.SimpleItem import SimpleItem ...@@ -27,7 +27,6 @@ from OFS.SimpleItem import SimpleItem
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from zope.interface import implements from zope.interface import implements
from Products.PluginIndexes import PluggableIndex
from Products.PluginIndexes.common import safe_callable from Products.PluginIndexes.common import safe_callable
from Products.PluginIndexes.common.util import parseIndexRequest from Products.PluginIndexes.common.util import parseIndexRequest
from Products.PluginIndexes.interfaces import IPluggableIndex from Products.PluginIndexes.interfaces import IPluggableIndex
...@@ -42,9 +41,6 @@ class UnIndex(SimpleItem): ...@@ -42,9 +41,6 @@ class UnIndex(SimpleItem):
"""Simple forward and reverse index. """Simple forward and reverse index.
""" """
__implements__ = (PluggableIndex.UniqueValueIndex,
PluggableIndex.SortIndex)
implements(IPluggableIndex, IUniqueValueIndex, ISortIndex) implements(IPluggableIndex, IUniqueValueIndex, ISortIndex)
def __init__( def __init__(
......
...@@ -28,7 +28,6 @@ from OFS.SimpleItem import SimpleItem ...@@ -28,7 +28,6 @@ from OFS.SimpleItem import SimpleItem
from DateTime.DateTime import DateTime from DateTime.DateTime import DateTime
from urllib import quote from urllib import quote
from webdav.Lockable import ResourceLockedError from webdav.Lockable import ResourceLockedError
from webdav.WriteLockInterface import WriteLockInterface
from Shared.DC.Scripts.Script import Script, BindingsUI, defaultBindings from Shared.DC.Scripts.Script import Script, BindingsUI, defaultBindings
from AccessControl import getSecurityManager from AccessControl import getSecurityManager
from OFS.History import Historical, html_diff from OFS.History import Historical, html_diff
...@@ -86,7 +85,6 @@ class PythonScript(Script, Historical, Cacheable): ...@@ -86,7 +85,6 @@ class PythonScript(Script, Historical, Cacheable):
not attempt to use the "exec" statement or certain restricted builtins. not attempt to use the "exec" statement or certain restricted builtins.
""" """
__implements__ = (WriteLockInterface,)
meta_type='Script (Python)' meta_type='Script (Python)'
_proxy_roles = () _proxy_roles = ()
......
...@@ -296,11 +296,19 @@ class TestPythonScriptGlobals(PythonScriptTestBase, WarningInterceptor): ...@@ -296,11 +296,19 @@ class TestPythonScriptGlobals(PythonScriptTestBase, WarningInterceptor):
self.assertEqual(f(), [0]) self.assertEqual(f(), [0])
self._free_warning_output() self._free_warning_output()
class PythonScriptInterfaceConformanceTests(unittest.TestCase):
def test_class_conforms_to_IWriteLock(self):
from zope.interface.verify import verifyClass
from webdav.interfaces import IWriteLock
verifyClass(IWriteLock, PythonScript)
def test_suite(): def test_suite():
suite = unittest.TestSuite() suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestPythonScriptNoAq)) suite.addTest(unittest.makeSuite(TestPythonScriptNoAq))
suite.addTest(unittest.makeSuite(TestPythonScriptErrors)) suite.addTest(unittest.makeSuite(TestPythonScriptErrors))
suite.addTest(unittest.makeSuite(TestPythonScriptGlobals)) suite.addTest(unittest.makeSuite(TestPythonScriptGlobals))
suite.addTest(unittest.makeSuite(PythonScriptInterfaceConformanceTests))
return suite return suite
......
...@@ -32,6 +32,7 @@ from urlparse import urlparse, urlunparse ...@@ -32,6 +32,7 @@ from urlparse import urlparse, urlunparse
from ZPublisher.BeforeTraverse import registerBeforeTraverse, \ from ZPublisher.BeforeTraverse import registerBeforeTraverse, \
unregisterBeforeTraverse, queryBeforeTraverse unregisterBeforeTraverse, queryBeforeTraverse
import logging import logging
from zope.interface import implements
b64_trans = string.maketrans('+/', '-.') b64_trans = string.maketrans('+/', '-.')
b64_untrans = string.maketrans('-.', '+/') b64_untrans = string.maketrans('-.', '+/')
...@@ -80,7 +81,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs): ...@@ -80,7 +81,7 @@ class BrowserIdManager(Item, Persistent, Implicit, RoleManager, Owned, Tabs):
{'label': 'Ownership', 'action':'manage_owner'} {'label': 'Ownership', 'action':'manage_owner'}
) )
__implements__ = (SessionInterfaces.BrowserIdManagerInterface, ) implements(SessionInterfaces.BrowserIdManagerInterface)
icon = 'misc_/Sessions/idmgr.gif' icon = 'misc_/Sessions/idmgr.gif'
......
...@@ -29,6 +29,7 @@ from BrowserIdManager import isAWellFormedBrowserId, getNewBrowserId,\ ...@@ -29,6 +29,7 @@ from BrowserIdManager import isAWellFormedBrowserId, getNewBrowserId,\
BROWSERID_MANAGER_NAME BROWSERID_MANAGER_NAME
from ZPublisher.BeforeTraverse import registerBeforeTraverse, \ from ZPublisher.BeforeTraverse import registerBeforeTraverse, \
unregisterBeforeTraverse unregisterBeforeTraverse
from zope.interface import implements
bad_path_chars_in=re.compile('[^a-zA-Z0-9-_~\,\. \/]').search bad_path_chars_in=re.compile('[^a-zA-Z0-9-_~\,\. \/]').search
LOG = getLogger('SessionDataManager') LOG = getLogger('SessionDataManager')
...@@ -80,7 +81,7 @@ class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs): ...@@ -80,7 +81,7 @@ class SessionDataManager(Item, Implicit, Persistent, RoleManager, Owned, Tabs):
icon='misc_/CoreSessionTracking/datamgr.gif' icon='misc_/CoreSessionTracking/datamgr.gif'
__implements__ = (SessionInterfaces.SessionDataManagerInterface, ) implements(SessionInterfaces.SessionDataManagerInterface)
manage_sessiondatamgr = Globals.DTMLFile('dtml/manageDataManager', manage_sessiondatamgr = Globals.DTMLFile('dtml/manageDataManager',
globals()) globals())
......
...@@ -20,11 +20,9 @@ Session APIs ...@@ -20,11 +20,9 @@ Session APIs
""" """
import Interface from zope.interface import Interface
class BrowserIdManagerInterface( class BrowserIdManagerInterface(Interface):
Interface.Base
):
""" """
Zope Browser Id Manager interface. Zope Browser Id Manager interface.
...@@ -152,9 +150,7 @@ class BrowserIdManagerInterface( ...@@ -152,9 +150,7 @@ class BrowserIdManagerInterface(
name and current browser id. name and current browser id.
""" """
class SessionDataManagerInterface( class SessionDataManagerInterface(Interface):
Interface.Base
):
""" """
Zope Session Data Manager interface. Zope Session Data Manager interface.
...@@ -199,7 +195,7 @@ class SessionDataManagerInterface( ...@@ -199,7 +195,7 @@ class SessionDataManagerInterface(
Permission required: Access arbitrary user session data Permission required: Access arbitrary user session data
""" """
class SessionDataManagerErr(Interface.Base): class SessionDataManagerErr(Interface):
""" """
Error raised during some session data manager operations, as Error raised during some session data manager operations, as
explained in the API documentation of the Session Data Manager. explained in the API documentation of the Session Data Manager.
...@@ -210,7 +206,7 @@ class SessionDataManagerErr(Interface.Base): ...@@ -210,7 +206,7 @@ class SessionDataManagerErr(Interface.Base):
from Products.Sessions import SessionDataManagerErr from Products.Sessions import SessionDataManagerErr
""" """
class BrowserIdManagerErr(Interface.Base): class BrowserIdManagerErr(Interface):
""" """
Error raised during some browser id manager operations, as Error raised during some browser id manager operations, as
explained in the API documentation of the Browser Id Manager. explained in the API documentation of the Browser Id Manager.
......
############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE
#
############################################################################
"""
Session APIs
See Also
- "Transient Object API":../../Transience/Help/TransienceInterfaces.py
"""
import Interface
class BrowserIdManagerInterface(
Interface.Base
):
"""
Zope Browser Id Manager interface.
A Zope Browser Id Manager is responsible for assigning ids to site
visitors, and for servicing requests from Session Data Managers
related to the browser id.
"""
def encodeUrl(url, style='querystring'):
"""
Encodes a provided URL with the current request's browser id
and returns the result. Two forms of URL-encoding are supported:
'querystring' and 'inline'. 'querystring' is the default.
If the 'querystring' form is used, the browser id name/value pair
are postfixed onto the URL as a query string. If the 'inline'
form is used, the browser id name/value pair are prefixed onto
the URL as the first two path segment elements.
For example:
The call encodeUrl('http://foo.com/amethod', style='querystring')
might return 'http://foo.com/amethod?_ZopeId=as9dfu0adfu0ad'.
The call encodeUrl('http://foo.com/amethod, style='inline')
might return 'http://foo.com/_ZopeId/as9dfu0adfu0ad/amethod'.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
"""
def getBrowserIdName():
"""
Returns a string with the name of the cookie/form variable which is
used by the current browser id manager as the name to look up when
attempting to obtain the browser id value. For example, '_ZopeId'.
Permission required: Access contents information
"""
def getBrowserId(create=1):
"""
If create=0, returns a the current browser id or None if there
is no browser id associated with the current request. If create=1,
returns the current browser id or a newly-created browser id if
there is no browser id associated with the current request. This
method is useful in conjunction with getBrowserIdName if you wish to
embed the browser-id-name/browser-id combination as a hidden value in
a POST-based form. The browser id is opaque, has no business meaning,
and its length, type, and composition are subject to change.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If ill-formed browser id
is found in REQUEST.
"""
def hasBrowserId():
"""
Returns true if there is a browser id for this request.
Permission required: Access contents information
"""
def isBrowserIdNew():
"""
Returns true if browser id is 'new'. A browser id is 'new'
when it is first created and the client has therefore not sent it
back to the server in any request.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
"""
def isBrowserIdFromForm():
"""
Returns true if browser id comes from a form variable (query
string or post).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
"""
def isBrowserIdFromCookie():
"""
Returns true if browser id comes from a cookie.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If there is no current browser id.
"""
def flushBrowserIdCookie():
"""
Deletes the browser id cookie from the client browser, iff the
'cookies' browser id namespace is being used.
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
a browser id namespace at the time of the call.
"""
def setBrowserIdCookieByForce(bid):
"""
Sets the browser id cookie to browser id 'bid' by force.
Useful when you need to 'chain' browser id cookies across domains
for the same user (perhaps temporarily using query strings).
Permission required: Access contents information
Raises: BrowserIdManagerErr. If the 'cookies' namespace isn't
a browser id namespace at the time of the call.
"""
def getHiddenFormField():
"""
Returns a string in the form:
<input type="hidden" name="_ZopeId" value="H7HJGYUFGFyHKH*">
Where the name and the value represent the current browser id
name and current browser id.
"""
class SessionDataManagerInterface(
Interface.Base
):
"""
Zope Session Data Manager interface.
A Zope Session Data Manager is responsible for maintaining Session
Data Objects, and for servicing requests from application code
related to Session Data Objects. It also communicates with a Browser
Id Manager to provide information about browser ids.
"""
def getBrowserIdManager():
"""
Returns the nearest acquirable browser id manager.
Raises SessionDataManagerErr if no browser id manager can be found.
Permission required: Access session data
"""
def getSessionData(create=1):
"""
Returns a Session Data Object associated with the current
browser id. If there is no current browser id, and create is true,
returns a new Session Data Object. If there is no current
browser id and create is false, returns None.
Permission required: Access session data
"""
def hasSessionData():
"""
Returns true if a Session Data Object associated with the
current browser id is found in the Session Data Container. Does
not create a Session Data Object if one does not exist.
Permission required: Access session data
"""
def getSessionDataByKey(key):
"""
Returns a Session Data Object associated with 'key'. If there is
no Session Data Object associated with 'key' return None.
Permission required: Access arbitrary user session data
"""
class SessionDataManagerErr(Interface.Base):
"""
Error raised during some session data manager operations, as
explained in the API documentation of the Session Data Manager.
This exception may be caught in PythonScripts. A successful
import of the exception for PythonScript use would need to be::
from Products.Sessions import SessionDataManagerErr
"""
class BrowserIdManagerErr(Interface.Base):
"""
Error raised during some browser id manager operations, as
explained in the API documentation of the Browser Id Manager.
This exception may be caught in PythonScripts. A successful
import of the exception for PythonScript use would need to be::
from Products.Sessions import BrowserIdManagerErr
"""
...@@ -42,6 +42,8 @@ from AccessControl.SecurityManagement import newSecurityManager, \ ...@@ -42,6 +42,8 @@ from AccessControl.SecurityManagement import newSecurityManager, \
from AccessControl.User import nobody from AccessControl.User import nobody
from logging import getLogger from logging import getLogger
from zope.interface import implements
from TransientObject import TransientObject from TransientObject import TransientObject
from Fake import FakeIOBTree from Fake import FakeIOBTree
...@@ -97,10 +99,10 @@ class TransientObjectContainer(SimpleItem): ...@@ -97,10 +99,10 @@ class TransientObjectContainer(SimpleItem):
meta_type = "Transient Object Container" meta_type = "Transient Object Container"
icon = "misc_/Transience/datacontainer.gif" icon = "misc_/Transience/datacontainer.gif"
__implements__ = (ItemWithId, implements(ItemWithId,
StringKeyedHomogeneousItemContainer, StringKeyedHomogeneousItemContainer,
TransientItemContainer TransientItemContainer,
) )
manage_options = ( manage_options = (
{ 'label': 'Manage', { 'label': 'Manage',
'action': 'manage_container', 'action': 'manage_container',
......
...@@ -74,9 +74,9 @@ Transient Objects ...@@ -74,9 +74,9 @@ Transient Objects
transient_object['foo'] = foo transient_object['foo'] = foo
""" """
import Interface from zope.interface import Interface
class Transient(Interface.Base): class Transient(Interface):
def invalidate(): def invalidate():
""" """
Invalidate (expire) the transient object. Invalidate (expire) the transient object.
...@@ -131,7 +131,7 @@ class Transient(Interface.Base): ...@@ -131,7 +131,7 @@ class Transient(Interface.Base):
container. container.
""" """
class DictionaryLike(Interface.Base): class DictionaryLike(Interface):
def keys(): def keys():
""" """
Return sequence of key elements. Return sequence of key elements.
...@@ -170,7 +170,7 @@ class DictionaryLike(Interface.Base): ...@@ -170,7 +170,7 @@ class DictionaryLike(Interface.Base):
# DictionaryLike does NOT support copy() # DictionaryLike does NOT support copy()
class ItemWithId(Interface.Base): class ItemWithId(Interface):
def getId(): def getId():
""" """
Returns a meaningful unique id for the object. Note that this id Returns a meaningful unique id for the object. Note that this id
...@@ -193,7 +193,7 @@ class TTWDictionary(DictionaryLike, ItemWithId): ...@@ -193,7 +193,7 @@ class TTWDictionary(DictionaryLike, ItemWithId):
Call __setitem__ with key k, value v. Call __setitem__ with key k, value v.
""" """
class ImmutablyValuedMappingOfPickleableObjects(Interface.Base): class ImmutablyValuedMappingOfPickleableObjects(Interface):
def __setitem__(k, v): def __setitem__(k, v):
""" """
Sets key k to value v, if k is both hashable and pickleable and Sets key k to value v, if k is both hashable and pickleable and
...@@ -216,7 +216,7 @@ class ImmutablyValuedMappingOfPickleableObjects(Interface.Base): ...@@ -216,7 +216,7 @@ class ImmutablyValuedMappingOfPickleableObjects(Interface.Base):
Remove the key/value pair related to key k. Remove the key/value pair related to key k.
""" """
class HomogeneousItemContainer(Interface.Base): class HomogeneousItemContainer(Interface):
""" """
An object which: An object which:
1. Contains zero or more subobjects, all of the same type. 1. Contains zero or more subobjects, all of the same type.
...@@ -271,7 +271,7 @@ class StringKeyedHomogeneousItemContainer(HomogeneousItemContainer): ...@@ -271,7 +271,7 @@ class StringKeyedHomogeneousItemContainer(HomogeneousItemContainer):
Returned object is acquisition-wrapped in self. Returned object is acquisition-wrapped in self.
""" """
class TransientItemContainer(Interface.Base): class TransientItemContainer(Interface):
def setTimeoutMinutes(timeout_mins): def setTimeoutMinutes(timeout_mins):
""" """
Set the number of minutes of inactivity allowable for subobjects Set the number of minutes of inactivity allowable for subobjects
......
...@@ -30,6 +30,7 @@ import Globals ...@@ -30,6 +30,7 @@ import Globals
import logging import logging
import sys import sys
from ZODB.POSException import ConflictError from ZODB.POSException import ConflictError
from zope.interface import implements
DEBUG = int(os.environ.get('Z_TOC_DEBUG', 0)) DEBUG = int(os.environ.get('Z_TOC_DEBUG', 0))
LOG = logging.getLogger('Zope.TransientObject') LOG = logging.getLogger('Zope.TransientObject')
...@@ -51,12 +52,12 @@ class TransientObject(Persistent, Implicit): ...@@ -51,12 +52,12 @@ class TransientObject(Persistent, Implicit):
""" Dictionary-like object that supports additional methods """ Dictionary-like object that supports additional methods
concerning expiration and containment in a transient object container concerning expiration and containment in a transient object container
""" """
__implements__ = (ItemWithId, # randomly generate an id implements(ItemWithId, # randomly generate an id
Transient, Transient,
DictionaryLike, DictionaryLike,
TTWDictionary, TTWDictionary,
ImmutablyValuedMappingOfPickleableObjects ImmutablyValuedMappingOfPickleableObjects
) )
security = ClassSecurityInfo() security = ClassSecurityInfo()
security.setDefaultAccess('allow') security.setDefaultAccess('allow')
...@@ -97,7 +98,7 @@ class TransientObject(Persistent, Implicit): ...@@ -97,7 +98,7 @@ class TransientObject(Persistent, Implicit):
# search our acquisition chain for a transient object container # search our acquisition chain for a transient object container
# and delete ourselves from it. # and delete ourselves from it.
for ob in getattr(self, 'aq_chain', []): for ob in getattr(self, 'aq_chain', []):
if TransientItemContainer.isImplementedBy(ob): if TransientItemContainer.providedBy(ob):
trans_ob_container = ob trans_ob_container = ob
break break
if trans_ob_container is not None: if trans_ob_container is not None:
......
...@@ -29,6 +29,7 @@ from Products.ZCTextIndex.SetOps import mass_weightedIntersection, \ ...@@ -29,6 +29,7 @@ from Products.ZCTextIndex.SetOps import mass_weightedIntersection, \
import ZODB import ZODB
from Persistence import Persistent from Persistence import Persistent
from zope.interface import implements
# Instead of storing floats, we generally store scaled ints. Binary pickles # Instead of storing floats, we generally store scaled ints. Binary pickles
# can store those more efficiently. The default SCALE_FACTOR of 1024 # can store those more efficiently. The default SCALE_FACTOR of 1024
...@@ -52,7 +53,7 @@ def unique(L): ...@@ -52,7 +53,7 @@ def unique(L):
class BaseIndex(Persistent): class BaseIndex(Persistent):
__implements__ = IIndex implements(IIndex)
def __init__(self, lexicon): def __init__(self, lexicon):
self._lexicon = lexicon self._lexicon = lexicon
......
...@@ -17,6 +17,7 @@ ...@@ -17,6 +17,7 @@
import math import math
from BTrees.IIBTree import IIBucket from BTrees.IIBTree import IIBucket
from zope.interface import implements
from Products.ZCTextIndex.IIndex import IIndex from Products.ZCTextIndex.IIndex import IIndex
from Products.ZCTextIndex.BaseIndex import BaseIndex, \ from Products.ZCTextIndex.BaseIndex import BaseIndex, \
...@@ -25,7 +26,7 @@ from Products.ZCTextIndex.BaseIndex import BaseIndex, \ ...@@ -25,7 +26,7 @@ from Products.ZCTextIndex.BaseIndex import BaseIndex, \
class CosineIndex(BaseIndex): class CosineIndex(BaseIndex):
__implements__ = IIndex implements(IIndex)
def __init__(self, lexicon): def __init__(self, lexicon):
BaseIndex.__init__(self, lexicon) BaseIndex.__init__(self, lexicon)
......
...@@ -14,12 +14,13 @@ ...@@ -14,12 +14,13 @@
from Products.ZCTextIndex.ISplitter import ISplitter from Products.ZCTextIndex.ISplitter import ISplitter
from Products.ZCTextIndex.PipelineFactory import element_factory from Products.ZCTextIndex.PipelineFactory import element_factory
from zope.interface import implements
import re import re
class HTMLWordSplitter: class HTMLWordSplitter:
__implements__ = ISplitter implements(ISplitter)
def process(self, text, wordpat=r"(?L)\w+"): def process(self, text, wordpat=r"(?L)\w+"):
splat = [] splat = []
......
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
"""Index Interface.""" """Index Interface."""
import Interface from zope.interface import Interface
class IIndex(Interface.Base): class IIndex(Interface):
"""Interface for an Index.""" """Interface for an Index."""
def length(): def length():
......
##############################################################################
#
# Copyright (c) 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Lexicon z2 interfaces.
$Id$
"""
# create ILexicon
from Interface.bridge import createZope3Bridge
from interfaces import ILexicon as z3ILexicon
import ILexicon
createZope3Bridge(z3ILexicon, ILexicon, 'ILexicon')
del createZope3Bridge
del z3ILexicon
...@@ -20,9 +20,9 @@ number of comparisons performed overall is M * log2(N). ...@@ -20,9 +20,9 @@ number of comparisons performed overall is M * log2(N).
""" """
import Interface from zope.interface import Interface
class INBest(Interface.Base): class INBest(Interface):
"""Interface for an N-Best chooser.""" """Interface for an N-Best chooser."""
def add(item, score): def add(item, score):
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
# #
############################################################################## ##############################################################################
from Interface import Interface from zope.interface import Interface
class IPipelineElement(Interface): class IPipelineElement(Interface):
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
# #
############################################################################## ##############################################################################
from Interface import Interface from zope.interface import Interface
class IPipelineElementFactory(Interface): class IPipelineElementFactory(Interface):
"""Class for creating pipeline elements by name""" """Class for creating pipeline elements by name"""
......
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
"""Query Parser Tree Interface.""" """Query Parser Tree Interface."""
import Interface from zope.interface import Interface
class IQueryParseTree(Interface.Base): class IQueryParseTree(Interface):
"""Interface for parse trees returned by parseQuery().""" """Interface for parse trees returned by parseQuery()."""
def nodeType(): def nodeType():
......
...@@ -14,9 +14,9 @@ ...@@ -14,9 +14,9 @@
"""Query Parser Interface.""" """Query Parser Interface."""
import Interface from zope.interface import Interface
class IQueryParser(Interface.Base): class IQueryParser(Interface):
"""Interface for Query Parsers.""" """Interface for Query Parsers."""
def parseQuery(query): def parseQuery(query):
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
# #
############################################################################## ##############################################################################
from Interface import Interface from zope.interface import Interface
class ISplitter(Interface): class ISplitter(Interface):
"""A splitter.""" """A splitter."""
......
...@@ -29,13 +29,11 @@ from zope.interface import implements ...@@ -29,13 +29,11 @@ from zope.interface import implements
from Products.ZCTextIndex.StopDict import get_stopdict from Products.ZCTextIndex.StopDict import get_stopdict
from Products.ZCTextIndex.ParseTree import QueryError from Products.ZCTextIndex.ParseTree import QueryError
from Products.ZCTextIndex.PipelineFactory import element_factory from Products.ZCTextIndex.PipelineFactory import element_factory
from ILexicon import ILexicon as z2ILexicon
from interfaces import ILexicon from interfaces import ILexicon
class Lexicon(Persistent): class Lexicon(Persistent):
__implements__ = z2ILexicon
implements(ILexicon) implements(ILexicon)
def __init__(self, *pipeline): def __init__(self, *pipeline):
......
...@@ -19,11 +19,12 @@ number of comparisons performed overall is M * log2(N). ...@@ -19,11 +19,12 @@ number of comparisons performed overall is M * log2(N).
""" """
from bisect import bisect from bisect import bisect
from zope.interface import implements
from Products.ZCTextIndex.INBest import INBest from Products.ZCTextIndex.INBest import INBest
class NBest: class NBest:
__implements__ = INBest implements(INBest)
def __init__(self, N): def __init__(self, N):
"Build an NBest object to remember the N best-scoring objects." "Build an NBest object to remember the N best-scoring objects."
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
from BTrees.IIBTree import IIBucket from BTrees.IIBTree import IIBucket
from BTrees.Length import Length from BTrees.Length import Length
from zope.interface import implements
from Products.ZCTextIndex.IIndex import IIndex from Products.ZCTextIndex.IIndex import IIndex
from Products.ZCTextIndex.BaseIndex import BaseIndex, \ from Products.ZCTextIndex.BaseIndex import BaseIndex, \
...@@ -28,7 +29,7 @@ from Products.ZCTextIndex.okascore import score ...@@ -28,7 +29,7 @@ from Products.ZCTextIndex.okascore import score
class OkapiIndex(BaseIndex): class OkapiIndex(BaseIndex):
__implements__ = IIndex implements(IIndex)
# BM25 free parameters. # BM25 free parameters.
K1 = 1.2 K1 = 1.2
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
############################################################################## ##############################################################################
"""Generic parser support: exception and parse tree nodes.""" """Generic parser support: exception and parse tree nodes."""
from zope.interface import implements
from BTrees.IIBTree import difference from BTrees.IIBTree import difference
...@@ -28,7 +29,7 @@ class ParseError(Exception): ...@@ -28,7 +29,7 @@ class ParseError(Exception):
class ParseTreeNode: class ParseTreeNode:
__implements__ = IQueryParseTree implements(IQueryParseTree)
_nodeType = None _nodeType = None
......
...@@ -11,13 +11,14 @@ ...@@ -11,13 +11,14 @@
# FOR A PARTICULAR PURPOSE # FOR A PARTICULAR PURPOSE
# #
############################################################################## ##############################################################################
from zope.interface import implements
from Products.ZCTextIndex.IPipelineElementFactory \ from Products.ZCTextIndex.IPipelineElementFactory \
import IPipelineElementFactory import IPipelineElementFactory
class PipelineElementFactory: class PipelineElementFactory:
__implements__ = IPipelineElementFactory implements(IPipelineElementFactory)
def __init__(self): def __init__(self):
self._groups = {} self._groups = {}
......
...@@ -56,6 +56,7 @@ Summarizing the default operator rules: ...@@ -56,6 +56,7 @@ Summarizing the default operator rules:
""" """
import re import re
from zope.interface import implements
from Products.ZCTextIndex.IQueryParser import IQueryParser from Products.ZCTextIndex.IQueryParser import IQueryParser
from Products.ZCTextIndex import ParseTree from Products.ZCTextIndex import ParseTree
...@@ -95,7 +96,7 @@ _tokenizer_regex = re.compile(r""" ...@@ -95,7 +96,7 @@ _tokenizer_regex = re.compile(r"""
class QueryParser: class QueryParser:
__implements__ = IQueryParser implements(IQueryParser)
# This class is not thread-safe; # This class is not thread-safe;
# each thread should have its own instance # each thread should have its own instance
......
...@@ -27,8 +27,6 @@ from AccessControl.SecurityInfo import ClassSecurityInfo ...@@ -27,8 +27,6 @@ from AccessControl.SecurityInfo import ClassSecurityInfo
from AccessControl.Permissions import manage_zcatalog_indexes, search_zcatalog from AccessControl.Permissions import manage_zcatalog_indexes, search_zcatalog
from zope.interface import implements from zope.interface import implements
from Products.PluginIndexes.common.PluggableIndex import \
PluggableIndexInterface
from Products.PluginIndexes.common.util import parseIndexRequest from Products.PluginIndexes.common.util import parseIndexRequest
from Products.PluginIndexes.common import safe_callable from Products.PluginIndexes.common import safe_callable
from Products.PluginIndexes.interfaces import IPluggableIndex from Products.PluginIndexes.interfaces import IPluggableIndex
...@@ -38,7 +36,6 @@ from Products.ZCTextIndex.Lexicon import \ ...@@ -38,7 +36,6 @@ from Products.ZCTextIndex.Lexicon import \
from Products.ZCTextIndex.NBest import NBest from Products.ZCTextIndex.NBest import NBest
from Products.ZCTextIndex.QueryParser import QueryParser from Products.ZCTextIndex.QueryParser import QueryParser
from CosineIndex import CosineIndex from CosineIndex import CosineIndex
from ILexicon import ILexicon as z2ILexicon
from interfaces import ILexicon from interfaces import ILexicon
from interfaces import IZCLexicon from interfaces import IZCLexicon
from interfaces import IZCTextIndex from interfaces import IZCTextIndex
...@@ -54,8 +51,6 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem): ...@@ -54,8 +51,6 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
"""Persistent text index. """Persistent text index.
""" """
__implements__ = PluggableIndexInterface
implements(IZCTextIndex, IPluggableIndex) implements(IZCTextIndex, IPluggableIndex)
## Magic class attributes ## ## Magic class attributes ##
...@@ -89,8 +84,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem): ...@@ -89,8 +84,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
if lexicon is None: if lexicon is None:
raise LookupError, 'Lexicon "%s" not found' % escape(lexicon_id) raise LookupError, 'Lexicon "%s" not found' % escape(lexicon_id)
if not (ILexicon.providedBy(lexicon) or if not ILexicon.providedBy(lexicon):
z2ILexicon.isImplementedBy(lexicon)):
raise ValueError('Object "%s" does not implement ' raise ValueError('Object "%s" does not implement '
'ZCTextIndex Lexicon interface' 'ZCTextIndex Lexicon interface'
% lexicon.getId()) % lexicon.getId())
...@@ -135,8 +129,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem): ...@@ -135,8 +129,7 @@ class ZCTextIndex(Persistent, Acquisition.Implicit, SimpleItem):
return self._v_lexicon return self._v_lexicon
except AttributeError: except AttributeError:
lexicon = getattr(aq_parent(aq_inner(self)), self.lexicon_id) lexicon = getattr(aq_parent(aq_inner(self)), self.lexicon_id)
if not (ILexicon.providedBy(lexicon) or if not ILexicon.providedBy(lexicon):
z2ILexicon.isImplementedBy(lexicon)):
raise TypeError('Object "%s" is not a ZCTextIndex Lexicon' raise TypeError('Object "%s" is not a ZCTextIndex Lexicon'
% repr(lexicon)) % repr(lexicon))
self._v_lexicon = lexicon self._v_lexicon = lexicon
......
...@@ -71,12 +71,6 @@ class StopWordPipelineElement: ...@@ -71,12 +71,6 @@ class StopWordPipelineElement:
class Test(unittest.TestCase): class Test(unittest.TestCase):
def test_z2interfaces(self):
from Interface.Verify import verifyClass
from Products.ZCTextIndex.ILexicon import ILexicon
verifyClass(ILexicon, Lexicon)
def test_z3interfaces(self): def test_z3interfaces(self):
from Products.ZCTextIndex.interfaces import ILexicon from Products.ZCTextIndex.interfaces import ILexicon
from zope.interface.verify import verifyClass from zope.interface.verify import verifyClass
......
############################################################################## ##############################################################################
# #
# Copyright (c) 2001, 2002 Zope Corporation and Contributors. # Copyright (c) 2008 Zope Corporation and Contributors.
# All Rights Reserved. # All Rights Reserved.
# #
# This software is subject to the provisions of the Zope Public License, # This software is subject to the provisions of the Zope Public License,
...@@ -13,31 +13,47 @@ ...@@ -13,31 +13,47 @@
############################################################################## ##############################################################################
import unittest import unittest
from Interface._Element import Element
class ElementTests(unittest.TestCase):
def test_taggedValues(self):
"""Test that we can update tagged values of more than one element
"""
e1 = Element("foo")
e2 = Element("bar")
e1.setTaggedValue("x", 1)
e2.setTaggedValue("x", 2)
self.assertEqual(e1.getTaggedValue("x"), 1)
self.assertEqual(e2.getTaggedValue("x"), 2)
def test_suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(ElementTests))
return suite
def test_suite(): class ParseTreeTests(unittest.TestCase):
return unittest.makeSuite(ElementTests)
def _conforms(self, klass):
from zope.interface.verify import verifyClass
from Products.ZCTextIndex.IQueryParseTree import IQueryParseTree
verifyClass(IQueryParseTree, klass)
def test_ParseTreeNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import ParseTreeNode
self._conforms(ParseTreeNode)
def test_OrNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import OrNode
self._conforms(OrNode)
def test_AndNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import AndNode
self._conforms(AndNode)
def main(): def test_NotNode_conforms_to_IQueryParseTree(self):
unittest.TextTestRunner().run(test_suite()) from Products.ZCTextIndex.ParseTree import NotNode
self._conforms(NotNode)
def test_GlobNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import GlobNode
self._conforms(GlobNode)
def test_AtomNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import AtomNode
self._conforms(AtomNode)
def test_PhraseNode_conforms_to_IQueryParseTree(self):
from Products.ZCTextIndex.ParseTree import PhraseNode
self._conforms(PhraseNode)
def test_suite():
return unittest.TestSuite((
unittest.makeSuite(ParseTreeTests),
))
if __name__=="__main__": if __name__=="__main__":
main() unittest.main(defaultTest='test_suite')
...@@ -15,10 +15,11 @@ ...@@ -15,10 +15,11 @@
from unittest import TestCase, TestSuite, main, makeSuite from unittest import TestCase, TestSuite, main, makeSuite
from Products.ZCTextIndex.IPipelineElement import IPipelineElement from Products.ZCTextIndex.IPipelineElement import IPipelineElement
from Products.ZCTextIndex.PipelineFactory import PipelineElementFactory from Products.ZCTextIndex.PipelineFactory import PipelineElementFactory
from zope.interface import implements
class NullPipelineElement: class NullPipelineElement:
__implements__ = IPipelineElement implements(IPipelineElement)
def process(source): def process(source):
pass pass
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment