This file is indexed.

/usr/share/pyshared/zope/app/container/browser/tests/test_adding.py is in python-zope.app.container 3.9.2-0ubuntu1.

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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
##############################################################################
#
# Copyright (c) 2002 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.
#
##############################################################################
"""Adding implementation tests
"""
import doctest
import unittest

import zope.interface
import zope.security.checker
from zope.component.interfaces import IFactory
from zope.component.interfaces import ComponentLookupError
from zope.interface import implements, Interface, directlyProvides
from zope.publisher.browser import TestRequest
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.publisher.browser import BrowserView
from zope.browsermenu.interfaces import AddMenu
from zope.browsermenu.interfaces import IMenuItemType, IBrowserMenu
from zope.browsermenu.menu import BrowserMenuItem, BrowserMenu
from zope.security.interfaces import ForbiddenAttribute
from zope.exceptions.interfaces import UserError
from zope.traversing.api import getParent
from zope.traversing.browser import AbsoluteURL
from zope.traversing.browser.absoluteurl import absoluteURL
from zope.traversing.browser.interfaces import IAbsoluteURL
from zope.traversing.interfaces import IContainmentRoot

from zope.app.testing import ztapi
from zope.app.testing.placelesssetup import PlacelessSetup, setUp, tearDown
from zope.app.container.interfaces import IAdding
from zope.app.container.interfaces import IObjectAddedEvent
from zope.app.container.interfaces import IContainerNamesContainer
from zope.app.container.interfaces import INameChooser
from zope.app.container.interfaces import IContainer
from zope.app.container.contained import contained
from zope.app.container.browser.adding import Adding
from zope.app.container.sample import SampleContainer


class Root(object):
    implements(IContainmentRoot)

class Container(SampleContainer):
    pass

class CreationView(BrowserView):

    def action(self):
        return 'been there, done that'


class Content(object):
    pass

class Factory(object):

    implements(IFactory)

    title = ''
    description = ''

    def getInterfaces(self):
        return ()

    def __call__(self):
        return Content()


class AbsoluteURL(BrowserView):

    def __str__(self):
        if IContainmentRoot.providedBy(self.context):
            return ''
        name = self.context.__name__
        url = absoluteURL(getParent(self.context), self.request)
        url += '/' + name
        return url

    __call__ = __str__

def defineMenuItem(menuItemType, for_, action, title=u'', extra=None):
    newclass = type(title, (BrowserMenuItem,),
                    {'title':title, 'action':action,
                     '_for': for_, 'extra':extra})
    zope.interface.classImplements(newclass, menuItemType)
    ztapi.provideAdapter((for_, IBrowserRequest), menuItemType, newclass, title)

def registerAddMenu():
  ztapi.provideUtility(IMenuItemType, AddMenu, 'zope.app.container.add')
  ztapi.provideUtility(IBrowserMenu,
                       BrowserMenu('zope.app.container.add', u'', u''),
                       'zope.app.container.add')


class Test(PlacelessSetup, unittest.TestCase):

    def setUp(self):
        super(Test, self).setUp()

    def test(self):
        container = Container()
        request = TestRequest()
        adding = Adding(container, request)
        ztapi.browserView(IAdding, "Thing", CreationView)
        self.assertEqual(adding.contentName, None)
        view = adding.publishTraverse(request, 'Thing=foo')
        self.assertEqual(view.action(), 'been there, done that')
        self.assertEqual(adding.contentName, 'foo')

        o = object()
        result = adding.add(o)

        # Check the state of the container and result
        self.assertEqual(container["foo"], o)
        self.assertEqual(result, o)

    def testNoNameGiven(self):
        container = Container()
        request = TestRequest()
        adding = Adding(container, request)
        ztapi.browserView(IAdding, "Thing", CreationView)

        self.assertEqual(adding.contentName, None)
        view = adding.publishTraverse(request, 'Thing=')
        self.assertEqual(adding.contentName, '')

    def testAction(self):
        # make a private factory
        ztapi.provideUtility(IFactory, Factory(), 'fooprivate')

        factory = Factory()
        factory.__Security_checker__ = zope.security.checker.NamesChecker(
            ['__call__'])
        ztapi.provideUtility(IFactory, factory, 'foo')

        container = Container()
        adding = Adding(container, TestRequest())
        adding.nextURL = lambda: '.'
        adding.nameAllowed = lambda: True

        # we can't use a private factory:
        self.assertRaises(ForbiddenAttribute,
                          adding.action, type_name='fooprivate', id='bar')

        # typical add - id is provided by user
        adding.action(type_name='foo', id='bar')
        self.assert_('bar' in container)

        # missing type_name
        self.assertRaises(UserError, adding.action, id='bar')

        # missing id
        self.assertRaises(KeyError, adding.action, type_name='foo')

        # bad type_name
        self.assertRaises(ComponentLookupError, adding.action,
            type_name='***', id='bar')

        # alternative add - id is provided internally instead of from user
        adding.nameAllowed = lambda: False
        adding.contentName = 'baz'
        adding.action(type_name='foo')
        self.assert_('baz' in container)

        # alternative add w/missing contentName
        # Note: Passing is None as object name might be okay, if the container
        #       is able to hand out ids itself. Let's not require a content
        #       name to be specified!
        # For the container, (or really, the chooser, to choose, we have to
        # marke the container as a ContainerNamesContainer
        directlyProvides(container, IContainerNamesContainer)
        adding.contentName = None
        adding.action(type_name='foo')
        self.assert_('Content' in container)


    def test_action(self):
        container = Container()
        container = contained(container, Root(), "container")
        request = TestRequest()
        adding = Adding(container, request)
        adding.__name__ = '+'
        ztapi.browserView(IAdding, "Thing", CreationView)
        ztapi.browserView(Interface, "absolute_url", AbsoluteURL)
        ztapi.browserView(None, '', AbsoluteURL, providing=IAbsoluteURL)
        self.assertRaises(UserError, adding.action, '', 'foo')
        adding.action('Thing', 'foo')
        self.assertEqual(adding.request.response.getHeader('location'),
                         '/container/+/Thing=foo')
        adding.action('Thing/screen1', 'foo')
        self.assertEqual(adding.request.response.getHeader('location'),
                         '/container/+/Thing/screen1=foo')

    def test_publishTraverse_factory(self):
        factory = Factory()
        ztapi.provideUtility(IFactory, factory, 'foo')
        container = Container()
        request = TestRequest()
        adding = Adding(container, request)
        self.assert_(adding.publishTraverse(request, 'foo') is factory)


def test_constraint_driven_addingInfo():
    """
    >>> registerAddMenu()

    >>> class TestMenu(zope.interface.Interface):
    ...     pass
    >>> zope.interface.directlyProvides(TestMenu, IMenuItemType)

    >>> ztapi.provideUtility(IMenuItemType, TestMenu, 'TestMenu')
    >>> ztapi.provideUtility(IBrowserMenu, BrowserMenu('TestMenu', u'', u''),
    ...                      'TestMenu')

    >>> defineMenuItem(TestMenu, IAdding, '', 'item1')
    >>> defineMenuItem(TestMenu, IAdding, '', 'Item2')

    >>> defineMenuItem(AddMenu, IAdding, '', 'item3', extra={'factory': 'f1'})
    >>> defineMenuItem(AddMenu, IAdding, '', 'item4', extra={'factory': 'f2'})

    >>> class F1(object):
    ...     pass

    >>> class F2(object):
    ...     pass

    >>> def pre(container, name, object):
    ...     if not isinstance(object, F1):
    ...         raise zope.interface.Invalid()
    >>> def prefactory(container, name, factory):
    ...     if factory._callable is not F1:
    ...         raise zope.interface.Invalid()
    >>> pre.factory = prefactory


    >>> class IContainer(zope.interface.Interface):
    ...     def __setitem__(name, object):
    ...         pass
    ...     __setitem__.precondition = pre


    >>> class Container(object):
    ...     zope.interface.implements(IContainer)

    >>> from zope.component.factory import Factory
    >>> ztapi.provideUtility(IFactory, Factory(F1), 'f1')
    >>> ztapi.provideUtility(IFactory, Factory(F2), 'f2')

    >>> from zope.app.container.browser.adding import Adding
    >>> adding = Adding(Container(), TestRequest())
    >>> items = adding.addingInfo()
    >>> len(items)
    1
    >>> items[0]['title']
    u'item3'

    >>> adding.menu_id = 'TestMenu'
    >>> items = adding.addingInfo()
    >>> len(items)
    3
    >>> items[0]['title']
    u'item1'
    >>> items[1]['title'] # the collator ordered this one correctly!
    u'Item2'
    >>> items[2]['title']
    u'item3'
    """

def test_constraint_driven_add():
    """
    >>> from zope.app.container.sample import SampleContainer
    >>> from zope.app.container.browser.adding import Adding

    >>> class F1(object):
    ...     pass

    >>> class F2(object):
    ...     pass

    >>> def pre(container, name, object):
    ...     "a mock item constraint "
    ...     if not isinstance(object, F1):
    ...         raise zope.interface.Invalid('not a valid child')

    >>> class ITestContainer(zope.interface.Interface):
    ...     def __setitem__(name, object):
    ...         pass
    ...     __setitem__.precondition = pre

    >>> class Container(SampleContainer):
    ...     zope.interface.implements(ITestContainer)

    >>> adding = Adding(Container(), TestRequest())
    >>> c = adding.add(F1())

    This test should fail, because the container only
    accepts instances of F1

    >>> adding.add(F2())
    Traceback (most recent call last):
    ...
    Invalid: not a valid child

    >>> class ValidContainer(SampleContainer):
    ...     zope.interface.implements(ITestContainer)

    >>> def constr(container):
    ...     "a mock container constraint"
    ...     if not isinstance(container, ValidContainer):
    ...         raise zope.interface.Invalid('not a valid container')
    ...     return True

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

    >>> zope.interface.classImplements(F1, I2)

    This adding now fails, because the Container is not a valid
    parent for F1

    >>> c = adding.add(F1())
    Traceback (most recent call last):
    ...
    Invalid: not a valid container

    >>> adding = Adding(ValidContainer(), TestRequest())
    >>> c = adding.add(F1())

    """


def test_nameAllowed():
    """
    Test for nameAllowed in adding.py

    >>> from zope.app.container.browser.adding import Adding
    >>> from zope.app.container.interfaces import IContainerNamesContainer

    Class implements IContainerNamesContainer

    >>> class FakeContainer(object):
    ...    zope.interface.implements(IContainerNamesContainer)

    nameAllowed returns False if the class imlements
    IContainerNamesContainer

    >>> adding = Adding(FakeContainer(),TestRequest())
    >>> adding.nameAllowed()
    False

    Fake class without IContainerNamesContainer

    >>> class Fake(object):
    ...    pass

    nameAllowed returns True if the class
    doesn't imlement IContainerNamesContainer

    >>> adding = Adding(Fake(),TestRequest())
    >>> adding.nameAllowed()
    True

    """



def test_chooseName():
    """If user don't enter name, pick one

    >>> class MyContainer(object):
    ...    args = {}
    ...    zope.interface.implements(INameChooser, IContainer)
    ...    def chooseName(self, name, object):
    ...        self.args["choose"] = name, object
    ...        return 'pickone'
    ...    def checkName(self, name, object):
    ...        self.args["check"] = name, object
    ...    def __setitem__(self, name, object):
    ...        setattr(self, name, object)
    ...        self.name = name
    ...    def __getitem__(self, key):
    ...        return getattr(self, key)

    >>> request = TestRequest()
    >>> mycontainer = MyContainer()
    >>> adding = Adding(mycontainer, request)
    >>> o = object()
    >>> add_obj = adding.add(o)
    >>> mycontainer.name
    'pickone'
    >>> add_obj is o
    True

    Make sure right arguments passed to INameChooser adapter:

    >>> name, obj = mycontainer.args["choose"]
    >>> name
    ''
    >>> obj is o
    True
    >>> name, obj = mycontainer.args["check"]
    >>> name
    'pickone'
    >>> obj is o
    True
    """



def test_SingleMenuItem_and_CustomAddView_NonICNC():
    """
    This tests the condition if the content has Custom Add views and
    the container contains only a single content object

    >>> registerAddMenu()
    >>> defineMenuItem(AddMenu, IAdding, '', 'item3', extra={'factory': 'f1'})

    >>> class F1(object):
    ...     pass

    >>> class F2(object):
    ...     pass

    >>> def pre(container, name, object):
    ...     if not isinstance(object, F1):
    ...         raise zope.interface.Invalid()
    >>> def prefactory(container, name, factory):
    ...     if factory._callable is not F1:
    ...         raise zope.interface.Invalid()
    >>> pre.factory = prefactory


    >>> class IContainer(zope.interface.Interface):
    ...     def __setitem__(name, object):
    ...         pass
    ...     __setitem__.precondition = pre


    >>> class Container(object):
    ...     zope.interface.implements(IContainer)

    >>> from zope.component.factory import Factory
    >>> ztapi.provideUtility(IFactory, Factory(F1), 'f1')
    >>> ztapi.provideUtility(IFactory, Factory(F2), 'f2')

    >>> from zope.app.container.browser.adding import Adding
    >>> adding = Adding(Container(), TestRequest())
    >>> items = adding.addingInfo()
    >>> len(items)
    1

    isSingleMenuItem returns True if there is only one content class
    inside the Container

    >>> adding.isSingleMenuItem()
    True

    hasCustomAddView will return False as the content does not have
    a custom Add View

    >>> adding.hasCustomAddView()
    True

    """

def test_SingleMenuItem_and_NoCustomAddView_NonICNC():
    """

    This function checks the case where there is a single content object
    and there is non custom add view . Also the container does not
    implement IContainerNamesContainer

    >>> registerAddMenu()
    >>> defineMenuItem(AddMenu, None, '', 'item3', extra={'factory': ''})
    >>> class F1(object):
    ...     pass

    >>> class F2(object):
    ...     pass

    >>> def pre(container, name, object):
    ...     if not isinstance(object, F1):
    ...         raise zope.interface.Invalid()
    >>> def prefactory(container, name, factory):
    ...     if factory._callable is not F1:
    ...         raise zope.interface.Invalid()
    >>> pre.factory = prefactory


    >>> class IContainer(zope.interface.Interface):
    ...     def __setitem__(name, object):
    ...         pass
    ...     __setitem__.precondition = pre


    >>> class Container(object):
    ...     zope.interface.implements(IContainer)

    >>> from zope.component.factory import Factory
    >>> ztapi.provideUtility(IFactory, Factory(F1), 'f1')
    >>> ztapi.provideUtility(IFactory, Factory(F2), 'f2')

    >>> from zope.app.container.browser.adding import Adding
    >>> adding = Adding(Container(), TestRequest())
    >>> items = adding.addingInfo()
    >>> len(items)
    1

    The isSingleMenuItem will return True if there is one single content
    that can be added inside the Container

    >>> adding.isSingleMenuItem()
    True

    hasCustomAddView will return False as the content does not have
    a custom Add View

    >>> adding.hasCustomAddView()
    False

    """

def test_isSingleMenuItem_with_ICNC():
    """
    This test checks for whether there is a single content that can be added
    and the container uses IContainerNamesContaienr

    >>> registerAddMenu()
    >>> defineMenuItem(AddMenu, None, '', 'item3', extra={'factory': ''})

    >>> class F1(object):
    ...     pass

    >>> class F2(object):
    ...     pass

    >>> def pre(container, name, object):
    ...     if not isinstance(object, F1):
    ...         raise zope.interface.Invalid()
    >>> def prefactory(container, name, factory):
    ...     if factory._callable is not F1:
    ...         raise zope.interface.Invalid()
    >>> pre.factory = prefactory


    >>> class IContainer(zope.interface.Interface):
    ...     def __setitem__(name, object):
    ...         pass
    ...     __setitem__.precondition = pre


    >>> class Container(object):
    ...     zope.interface.implements(IContainer, IContainerNamesContainer)

    >>> from zope.app.container.browser.adding import Adding
    >>> adding = Adding(Container(), TestRequest())
    >>> items = adding.addingInfo()
    >>> len(items)
    1
    >>> adding.isSingleMenuItem()
    True
    >>> adding.hasCustomAddView()
    False

    """

def test_suite():
    return unittest.TestSuite((
        unittest.makeSuite(Test),
        doctest.DocTestSuite(setUp=setUp, tearDown=tearDown),
        ))

if __name__=='__main__':
    unittest.main(defaultTest='test_suite')