This file is indexed.

/usr/share/pyshared/zope/container/constraints.py is in python-zope.container 3.12.0-0ubuntu2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
##############################################################################
#
# Copyright (c) 2003 Zope Foundation 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.
#
##############################################################################
"""Support for containment constraints

   Either a container or an object can provide constraints on the
   containment relationship.

   A container expresses constraints through a precondition on it's
   `__setitem__` method in it's interface.

   Preconditions can be simple callable objects, like functions. They
   should raise a ``zope.interface.Invalid`` exception to indicate that a
   constraint isn't satisfied:

   >>> def preNoZ(container, name, ob):
   ...     "Silly precondition example"
   ...     if name.startswith("Z"):
   ...         raise zope.interface.Invalid("Names can not start with Z")

   >>> class I1(zope.interface.Interface):
   ...     def __setitem__(name, on):
   ...         "Add an item"
   ...     __setitem__.precondition = preNoZ

   >>> from zope.container.interfaces import IContainer
   >>> class C1(object):
   ...     zope.interface.implements(I1, IContainer)
   ...     def __repr__(self):
   ...         return 'C1'

   Given such a precondition, we can then check whether an object can be
   added:

   >>> c1 = C1()
   >>> checkObject(c1, "bob", None)
   >>> checkObject(c1, "Zbob", None)
   Traceback (most recent call last):
   ...
   Invalid: Names can not start with Z

   We can also express constaints on the containers an object can be
   added to. We do this by setting a field constraint on an object's
   `__parent__` attribute:

   >>> import zope.schema

   A field constraint is a callable object that returns a boolean value:

   >>> def con1(container):
   ...     "silly container constraint"
   ...     if not hasattr(container, 'x'):
   ...         return False
   ...     return True

   >>> class I2(zope.interface.Interface):
   ...     __parent__ = zope.schema.Field(constraint = con1)

   >>> class O(object):
   ...     zope.interface.implements(I2)

   If the constraint isn't satisfied, we'll get a validation error when we
   check whether the object can be added:

   >>> checkObject(c1, "bob", O())
   Traceback (most recent call last):
   ...
   ConstraintNotSatisfied: C1

   Note that the validation error isn't very informative. For that
   reason, it's better for constraints to raise Invalid errors when they
   aren't satisfied:

   >>> def con1(container):
   ...     "silly container constraint"
   ...     if not hasattr(container, 'x'):
   ...         raise zope.interface.Invalid("What, no x?")
   ...     return True

   >>> class I2(zope.interface.Interface):
   ...     __parent__ = zope.schema.Field(constraint = con1)

   >>> class O(object):
   ...     zope.interface.implements(I2)

   >>> checkObject(c1, "bob", O())
   Traceback (most recent call last):
   ...
   Invalid: What, no x?

   >>> c1.x = 1
   >>> checkObject(c1, "bob", O())

   The `checkObject` function is handy when checking whether we can add an
   existing object to a container, but, sometimes, we want to check
   whether an object produced by a factory can be added.  To do this, we
   use `checkFactory`:

   >>> class Factory(object):
   ...     def __call__(self):
   ...         return O()
   ...     def getInterfaces(self):
   ...         return zope.interface.implementedBy(O)

   >>> factory = Factory()

   >>> checkFactory(c1, "bob", factory)
   True

   >>> del c1.x
   >>> checkFactory(c1, "bob", factory)
   False

   Unlike `checkObject`, `checkFactory`:

   - Returns a boolean value

   - Takes a factory (e.g. a class) rather than an argument.

   The container constraint we defined for C1 isn't actually used to
   check the factory:

   >>> c1.x = 1
   >>> checkFactory(c1, "Zbob", factory)
   True

   To work with `checkFactory`, a container precondition has to
   implement a factory method.  This is because a factory, rather than
   an object is passed.  To illustrate this, we'll make preNoZ its own
   factory method:

   >>> preNoZ.factory = preNoZ

   We can do this (silly thing) because preNoZ doesn't use the object
   argument.

   >>> checkFactory(c1, "Zbob", factory)
   False
   """
__docformat__ = 'restructuredtext'

import sys

from zope.dottedname.resolve import resolve
import zope.schema
from zope.interface import providedBy
from zope.container.interfaces import InvalidItemType, InvalidContainerType
from zope.container.i18n import ZopeMessageFactory as _
from zope.container.interfaces import IContainer

def checkObject(container, name, object):
    """Check containment constraints for an object and container
    """

    # check __setitem__ precondition
    containerProvided = providedBy(container)
    __setitem__ = containerProvided.get('__setitem__')
    if __setitem__ is not None:
        precondition = __setitem__.queryTaggedValue('precondition')
        if precondition is not None:
            precondition(container, name, object)

    # check that object is not being pasted into itself or its children.
    target = container
    while target is not None:
        if target is object:
            raise TypeError("Cannot add an object to itself or its children.")
        if zope.location.interfaces.ILocation.providedBy(target):
            target = target.__parent__
        else:
            target = None

    # check the constraint on __parent__
    __parent__ = providedBy(object).get('__parent__')
    if __parent__ is not None:
        try:
            validate = __parent__.validate
        except AttributeError:
            pass
        else:
            validate(container)


    if not containerProvided.extends(IContainer):
        # If it doesn't implement IContainer, it can't contain stuff.
        raise TypeError(
            _('Container is not a valid Zope container.')
            )

def checkFactory(container, name, factory):
    __setitem__ = providedBy(container).get('__setitem__')
    if __setitem__ is not None:
        precondition = __setitem__.queryTaggedValue('precondition')
        if precondition is not None:
            try:
                precondition = precondition.factory
            except AttributeError:
                pass
            else:
                try:
                    precondition(container, name, factory)
                except zope.interface.Invalid:
                    return False

    # check the constraint on __parent__
    __parent__ = factory.getInterfaces().get('__parent__')
    if __parent__ is not None:
        try:
            validate = __parent__.validate
        except AttributeError:
            pass
        else:
            try:
                validate(container)
            except zope.interface.Invalid:
                return False

    return True


class readproperty(object):

    def __init__(self, func):
        self.func = func

    def __get__(self, inst, class_):
        if inst is None:
            return self

        func = self.func
        return func(inst)


class IItemTypePrecondition(zope.interface.Interface):

    def __call__(container, name, object):
        """Test whether container setitem arguments are valid.

        Raise zope.interface.Invalid if the object is invalid.
        """

    def factory(container, name, factory):
        """Test whether objects provided by the factory are acceptable

        Return a boolean value.
        """


class _TypesBased(object):

    @readproperty
    def types(self):
        raw_types, module = self.raw_types
        types = []
        for t in raw_types:
            if isinstance(t, str):
                t = resolve(t, module)
            types.append(t)

        self.types = types
        return types

    def __init__(self, *types, **kw):
        if [t for t in types if isinstance(t, str)]:
            # have dotted names
            module = kw.get('module', sys._getframe(1).f_globals['__name__'])
            self.raw_types = types, module
        else:
            self.types = types


class ItemTypePrecondition(_TypesBased):
    """Specify a `__setitem__` precondition that restricts item types

    Items must be one of the given types.

    >>> class I1(zope.interface.Interface):
    ...     pass
    >>> class I2(zope.interface.Interface):
    ...     pass


    >>> precondition = ItemTypePrecondition(I1, I2)

    >>> class Ob(object):
    ...     pass
    >>> ob = Ob()

    >>> class Factory(object):
    ...     def __call__(self):
    ...         return Ob()
    ...     def getInterfaces(self):
    ...         return zope.interface.implementedBy(Ob)

    >>> factory = Factory()

    >>> try:
    ...     precondition(None, 'foo', ob)
    ... except InvalidItemType, v:
    ...     print v[0], (v[1] is ob), (v[2] == (I1, I2))
    ... else:
    ...     print 'Should have failed'
    None True True

    >>> try:
    ...     precondition.factory(None, 'foo', factory)
    ... except InvalidItemType, v:
    ...     print v[0], (v[1] is factory), (v[2] == (I1, I2))
    ... else:
    ...     print 'Should have failed'
    None True True

    >>> zope.interface.classImplements(Ob, I2)
    >>> precondition(None, 'foo', ob)
    >>> precondition.factory(None, 'foo', factory)

    """

    zope.interface.implements(IItemTypePrecondition)

    def __call__(self, container, name, object):
        for iface in self.types:
            if iface.providedBy(object):
                return
        raise InvalidItemType(container, object, self.types)

    def factory(self, container, name, factory):
        implemented = factory.getInterfaces()

        for iface in self.types:
            if implemented.isOrExtends(iface):
               return
        raise InvalidItemType(container, factory, self.types)


def contains(*types):
    """Declare that a container type contains only the given types

    This is used within a class suite defining an interface to create
    a __setitem__ specification with a precondition allowing only the
    given types:

      >>> class IFoo(zope.interface.Interface):
      ...     pass
      >>> class IBar(zope.interface.Interface):
      ...     pass
      >>> class IFooBarContainer(IContainer):
      ...     contains(IFoo, IBar)

      >>> __setitem__ = IFooBarContainer['__setitem__']
      >>> __setitem__.getTaggedValue('precondition').types == (IFoo, IBar)
      True

    It is invalid to call contains outside a class suite:

      >>> contains(IFoo, IBar)
      Traceback (most recent call last):
      ...
      TypeError: contains not called from suite
    """

    frame = sys._getframe(1)
    f_locals = frame.f_locals
    f_globals = frame.f_globals

    if not (f_locals is not f_globals
            and f_locals.get('__module__')
            and f_locals.get('__module__') == f_globals.get('__name__')
            ):
        raise TypeError("contains not called from suite")

    def __setitem__(key, value):
        pass
    __setitem__.__doc__ = IContainer['__setitem__'].__doc__
    __setitem__.precondition = ItemTypePrecondition(
        *types,
        **dict(module=f_globals['__name__'])
        )
    f_locals['__setitem__'] = __setitem__


class IContainerTypesConstraint(zope.interface.Interface):

    def __call__(object):
        """Test whether object is valid.

        Return True if valid.
        Raise zope.interface.Invalid if the objet is invalid.
        """


class ContainerTypesConstraint(_TypesBased):
    """Constrain a container to be one of a number of types

    >>> class I1(zope.interface.Interface):
    ...     pass
    >>> class I2(zope.interface.Interface):
    ...     pass
    >>> class Ob(object):
    ...     pass
    >>> ob = Ob()
    >>> constraint = ContainerTypesConstraint(I1, I2)
    >>> try:
    ...     constraint(ob)
    ... except InvalidContainerType, v:
    ...     print (v[0] is ob), (v[1] == (I1, I2))
    ... else:
    ...     print 'Should have failed'
    True True

    >>> zope.interface.classImplements(Ob, I2)
    >>> constraint(Ob())
    True

    """

    zope.interface.implements(IContainerTypesConstraint)

    def __call__(self, object):
       for iface in self.types:
           if iface.providedBy(object):
               return True
       else:
           raise InvalidContainerType(object, self.types)


def containers(*types):
    """Declare the container types a type can be contained in

    This is used within a class suite defining an interface to create
    a __parent__ specification with a constraint allowing only the
    given types:

      >>> class IFoo(IContainer):
      ...     pass
      >>> class IBar(IContainer):
      ...     pass

      >>> from zope.location.interfaces import IContained
      >>> class IFooBarContained(IContained):
      ...     containers(IFoo, IBar)

      >>> __parent__ = IFooBarContained['__parent__']
      >>> __parent__.constraint.types == (IFoo, IBar)
      True

    It is invalid to call containers outside a class suite:

      >>> containers(IFoo, IBar)
      Traceback (most recent call last):
      ...
      TypeError: containers not called from suite
    """

    frame = sys._getframe(1)
    f_locals = frame.f_locals
    f_globals = frame.f_globals

    if not (f_locals is not f_globals
            and f_locals.get('__module__')
            and f_locals.get('__module__') == f_globals.get('__name__')
            ):
        raise TypeError("containers not called from suite")

    __parent__ = zope.schema.Field(
        constraint = ContainerTypesConstraint(
            *types,
            **dict(module=f_globals['__name__'])
            )
        )
    f_locals['__parent__'] = __parent__