summaryrefslogtreecommitdiff
path: root/src/zope/security/tests/test_zcml_functest.py
blob: b93273494437848ce3cf9dd8eb30a787389d3a8a (plain)
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
##############################################################################
#
# Copyright (c) 2001, 2002, 2003, 2012 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.
#
##############################################################################
"""Directives Tests
"""
import unittest
import io

def _skip_wo_zope_configuration(testfunc):
    try:
        import zope.configuration.xmlconfig
    except ImportError:
        return unittest.skip("No zope.configuration")(testfunc)
    else:
        return testfunc


def configfile(s):
    return io.StringIO(u"""<configure
      xmlns='http://namespaces.zope.org/zope'
      i18n_domain='zope'>
      %s
      </configure>
      """ % s)


class TestClassDirective(unittest.TestCase):

    def setUp(self):
        from zope.security.tests.exampleclass import ExampleClass
        try:
            del ExampleClass.__implements__
        except AttributeError:
            pass
        try:
            from zope.component.testing import setUp
        except ImportError:
            pass
        else:
            setUp()

    def tearDown(self):
        from zope.security.tests.exampleclass import ExampleClass
        try:
            del ExampleClass.__implements__
        except AttributeError:
            pass
        try:
            from zope.component.testing import tearDown
        except ImportError:
            pass
        else:
            tearDown()

    def _meta(self):
        from zope.configuration.xmlconfig import XMLConfig
        import zope.security
        XMLConfig('meta.zcml', zope.security)()

    @_skip_wo_zope_configuration
    def testEmptyDirective(self):
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
</class>
                       """)
        xmlconfig(f)


    @_skip_wo_zope_configuration
    def testImplements(self):
        from zope.component.interface import queryInterface
        from zope.configuration.xmlconfig import xmlconfig
        from zope.security.tests.exampleclass import ExampleClass
        from zope.security.tests.exampleclass import IExample
        self._meta()
        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample"), None)

        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
  <implements interface="zope.security.tests.exampleclass.IExample" />
</class>
                       """)
        xmlconfig(f)
        self.assertTrue(IExample.implementedBy(ExampleClass))

        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample"), IExample)


    @_skip_wo_zope_configuration
    def testMulImplements(self):
        from zope.component.interface import queryInterface
        from zope.configuration.xmlconfig import xmlconfig
        from zope.security.tests.exampleclass import ExampleClass
        from zope.security.tests.exampleclass import IExample
        from zope.security.tests.exampleclass import IExample2
        self._meta()
        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample"), None)
        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample2"), None)

        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
  <implements interface="
           zope.security.tests.exampleclass.IExample
           zope.security.tests.exampleclass.IExample2
                       " />
</class>
                       """)
        xmlconfig(f)
        self.assertTrue(IExample.implementedBy(ExampleClass))
        self.assertTrue(IExample2.implementedBy(ExampleClass))

        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample"), IExample)
        self.assertEqual(queryInterface(
            "zope.security.tests.exampleclass.IExample2"),
                         IExample2)

    @_skip_wo_zope_configuration
    def testRequire(self):
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<permission id="zope.View" title="Zope view permission" />
<class class="zope.security.tests.exampleclass.ExampleClass">
    <require permission="zope.View"
                      attributes="anAttribute anotherAttribute" />
</class>
                       """)
        xmlconfig(f)

    @_skip_wo_zope_configuration
    def testAllow(self):
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
    <allow attributes="anAttribute anotherAttribute" />
</class>
                       """)
        xmlconfig(f)

    @_skip_wo_zope_configuration
    def testMimic(self):
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
    <require like_class="zope.security.tests.exampleclass.ExampleClass" />
</class>
                       """)
        xmlconfig(f)


class TestFactorySubdirective(unittest.TestCase):

    def setUp(self):
        try:
            from zope.component.testing import setUp
        except ImportError:
            pass
        else:
            setUp()

    def tearDown(self):
        try:
            from zope.component.testing import tearDown
        except ImportError:
            pass
        else:
            tearDown()

    def _meta(self):
        from zope.configuration.xmlconfig import XMLConfig
        import zope.security
        XMLConfig('meta.zcml', zope.security)()

    @_skip_wo_zope_configuration
    def testFactory(self):
        from zope.component import getUtility
        from zope.component.interfaces import IFactory
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<permission id="zope.Foo" title="Zope Foo Permission" />

<class class="zope.security.tests.exampleclass.ExampleClass">
  <factory
      id="test.Example"
      title="Example content"
      description="Example description"
      />
</class>
                       """)
        xmlconfig(f)
        factory = getUtility(IFactory, 'test.Example')
        self.assertEqual(factory.title, "Example content")
        self.assertEqual(factory.description, "Example description")

    @_skip_wo_zope_configuration
    def testFactoryNoId(self):
        from zope.component import getUtility
        from zope.component.interfaces import IFactory
        from zope.component.interfaces import ComponentLookupError
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<permission id="zope.Foo" title="Zope Foo Permission" />

<class class="zope.security.tests.exampleclass.ExampleClass">
    <factory
      title="Example content"
      description="Example description"
    />
</class>
                       """)
        xmlconfig(f)
        self.assertRaises(ComponentLookupError, getUtility,
                          IFactory, 'Example')
        factory = getUtility(
            IFactory, 'zope.security.tests.exampleclass.ExampleClass')
        self.assertEqual(factory.title, "Example content")
        self.assertEqual(factory.description, "Example description")


    @_skip_wo_zope_configuration
    def testFactoryPublicPermission(self):
        from zope.component import getUtility
        from zope.component.interfaces import IFactory
        from zope.configuration.xmlconfig import xmlconfig
        self._meta()
        f = configfile("""
<class class="zope.security.tests.exampleclass.ExampleClass">
    <factory
      id="test.Example"
      title="Example content"
      description="Example description"
    />
</class>
            """)
        xmlconfig(f)
        factory = getUtility(IFactory, 'test.Example')
        self.assertTrue(hasattr(factory, '__Security_checker__'))


class Context(object):
    actions = ()

    def action(self, discriminator, callable, args):
        self.actions += ((discriminator, callable, args), )

    def __repr__(self):
        import re
        import pprint
        atre = re.compile(' at [0-9a-fA-Fx]+')
        stream = io.StringIO() if bytes is not str else io.BytesIO()
        pprinter = pprint.PrettyPrinter(stream=stream, width=60)
        pprinter.pprint(self.actions)
        r = stream.getvalue()
        return (''.join(atre.split(r))).strip()


template = """<configure
   xmlns='http://namespaces.zope.org/zope'
   xmlns:test='http://www.zope.org/NS/Zope3/test'
   i18n_domain='zope'>
   %s
   </configure>"""


class TestFactoryDirective(unittest.TestCase):

    def setUp(self):
        try:
            from zope.component.testing import setUp
        except ImportError:
            pass
        else:
            setUp()

    def tearDown(self):
        try:
            from zope.component.testing import tearDown
        except ImportError:
            pass
        else:
            tearDown()

    def meta(self):
        import zope.security
        from zope.configuration.xmlconfig import XMLConfig
        XMLConfig('meta.zcml', zope.security)()

    @_skip_wo_zope_configuration
    def testFactory(self):
        from zope.component import createObject
        from zope.configuration.xmlconfig import xmlconfig
        from zope.security import proxy
        from zope.security.tests import exampleclass
        self.meta()
        f = configfile('''
<permission id="zope.Foo" title="Zope Foo Permission" />
<class class="zope.security.tests.exampleclass.ExampleClass">
    <factory
      id="test.Example"
      title="Example content"
      description="Example description"
       />
</class>''')
        xmlconfig(f)
        obj = createObject('test.Example')
        self.assertTrue(proxy.isinstance(obj, exampleclass.ExampleClass))



def _pfx(name):
    from zope.security.tests import module
    return module.__name__ + '.' + name

def defineDirectives():
    from zope.configuration.xmlconfig import XMLConfig
    from zope.configuration.xmlconfig import xmlconfig
    import zope.security
    XMLConfig('meta.zcml', zope.security)()
    xmlconfig(io.StringIO(u"""<configure
        xmlns='http://namespaces.zope.org/zope'
        i18n_domain='zope'>
       <permission id="zope.Extravagant" title="extravagant" />
       <permission id="zope.Paltry" title="paltry" />
    </configure>"""))

NOTSET = ()

P1 = "zope.Extravagant"
P2 = "zope.Paltry"

class TestRequireDirective(unittest.TestCase):

    def setUp(self):
        from zope.interface import implementer
        from zope.security.tests import module
        try:
            from zope.component.testing import setUp
        except ImportError:
            pass
        else:
            setUp()
        defineDirectives()

        class B(object):
            def m1(self):
                return "m1"
            def m2(self):
                return "m2"
        @implementer(module.I)
        class C(B):
            def m3(self):
                return "m3"
            def m4(self):
                return "m4"
        module.test_base = B
        module.test_class = C
        module.test_instance = C()
        self.assertState()

    def tearDown(self):
        from zope.security.tests import module
        module.test_class = None
        try:
            from zope.component.testing import tearDown
        except ImportError:
            pass
        else:
            tearDown()

    def assertState(self, m1P=NOTSET, m2P=NOTSET, m3P=NOTSET):
        #Verify that class, instance, and methods have expected permissions
        from zope.security.checker import selectChecker
        from zope.security.tests import module
        checker = selectChecker(module.test_instance)
        self.assertEqual(checker.permission_id('m1'), (m1P or None))
        self.assertEqual(checker.permission_id('m2'), (m2P or None))
        self.assertEqual(checker.permission_id('m3'), (m3P or None))

    def assertDeclaration(self, declaration, **state):
        from zope.security.tests import module
        apply_declaration(module.template_bracket % declaration)
        self.assertState(**state)

    # "testSimple*" exercises tags that do NOT have children.  This mode
    # inherently sets the instances as well as the class attributes.

    @_skip_wo_zope_configuration
    def test_wo_any_attributes(self):
        from zope.configuration.exceptions import ConfigurationError
        from zope.security.tests import module
        declaration = ('''<class class="%s">
                            <require
                                permission="%s" />
                          </class>'''
                       % (_pfx("test_class"), P1))
        self.assertRaises(ConfigurationError,
                          apply_declaration,
                          module.template_bracket % declaration)

    # "testSimple*" exercises tags that do NOT have children.  This mode
    # inherently sets the instances as well as the class attributes.

    @_skip_wo_zope_configuration
    def testSimpleMethodsPlural(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m3"/>
                          </class>'''
                       % (_pfx("test_class"), P1))
        self.assertDeclaration(declaration, m1P=P1, m3P=P1)

    def assertSetattrState(self, m1P=NOTSET, m2P=NOTSET, m3P=NOTSET):
        # Verify that class, instance, and methods have expected permissions
        from zope.security.checker import selectChecker
        from zope.security.tests import module
        checker = selectChecker(module.test_instance)
        self.assertEqual(checker.setattr_permission_id('m1'), (m1P or None))
        self.assertEqual(checker.setattr_permission_id('m2'), (m2P or None))
        self.assertEqual(checker.setattr_permission_id('m3'), (m3P or None))

    def assertSetattrDeclaration(self, declaration, **state):
        self.assertSetattrState(**state)

    @_skip_wo_zope_configuration
    def test_set_attributes(self):
        from zope.security.checker import selectChecker
        from zope.security.tests import module
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                set_attributes="m1 m3"/>
                          </class>'''
                       % (_pfx("test_class"), P1))
        apply_declaration(module.template_bracket % declaration)
        checker = selectChecker(module.test_instance)
        self.assertEqual(checker.setattr_permission_id('m1'), P1)
        self.assertEqual(checker.setattr_permission_id('m2'), None)
        self.assertEqual(checker.setattr_permission_id('m3'), P1)

    @_skip_wo_zope_configuration
    def test_set_schema(self):
        from zope.component.interface import queryInterface
        from zope.security.checker import selectChecker
        from zope.security.tests import module
        self.assertEqual(queryInterface(_pfx("S")), None)

        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                set_schema="%s"/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("S")))
        apply_declaration(module.template_bracket % declaration)

        self.assertEqual(queryInterface(_pfx("S")), module.S)


        checker = selectChecker(module.test_instance)
        self.assertEqual(checker.setattr_permission_id('m1'), None)
        self.assertEqual(checker.setattr_permission_id('m2'), None)
        self.assertEqual(checker.setattr_permission_id('m3'), None)
        self.assertEqual(checker.setattr_permission_id('foo'), P1)
        self.assertEqual(checker.setattr_permission_id('bar'), P1)
        self.assertEqual(checker.setattr_permission_id('baro'), None)

    @_skip_wo_zope_configuration
    def test_multiple_set_schema(self):
        from zope.component.interface import queryInterface
        from zope.security.checker import selectChecker
        from zope.security.tests import module
        self.assertEqual(queryInterface(_pfx("S")), None)
        self.assertEqual(queryInterface(_pfx("S2")), None)

        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                set_schema="%s %s"/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("S"), _pfx("S2")))
        apply_declaration(module.template_bracket % declaration)

        self.assertEqual(queryInterface(_pfx("S")), module.S)
        self.assertEqual(queryInterface(_pfx("S2")), module.S2)


        checker = selectChecker(module.test_instance)
        self.assertEqual(checker.setattr_permission_id('m1'), None)
        self.assertEqual(checker.setattr_permission_id('m2'), None)
        self.assertEqual(checker.setattr_permission_id('m3'), None)
        self.assertEqual(checker.setattr_permission_id('foo'), P1)
        self.assertEqual(checker.setattr_permission_id('bar'), P1)
        self.assertEqual(checker.setattr_permission_id('foo2'), P1)
        self.assertEqual(checker.setattr_permission_id('bar2'), P1)
        self.assertEqual(checker.setattr_permission_id('baro'), None)

    @_skip_wo_zope_configuration
    def testSimpleInterface(self):
        from zope.component.interface import queryInterface
        from zope.security.tests import module
        self.assertEqual(queryInterface(_pfx("I")), None)

        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                interface="%s"/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("I")))
        # m1 and m2 are in the interface, so should be set, and m3 should not:
        self.assertDeclaration(declaration, m1P=P1, m2P=P1)

        # Make sure we know about the interfaces
        self.assertEqual(queryInterface(_pfx("I")), module.I)


    @_skip_wo_zope_configuration
    def testMultipleInterface(self):
        from zope.component.interface import queryInterface
        from zope.security.tests import module
        self.assertEqual(queryInterface(_pfx("I3")), None)
        self.assertEqual(queryInterface(_pfx("I4")), None)

        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                interface="  %s
                                             %s  "/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("I3"), _pfx("I4")))
        self.assertDeclaration(declaration, m3P=P1, m2P=P1)

        # Make sure we know about the interfaces
        self.assertEqual(queryInterface(_pfx("I3")), module.I3)
        self.assertEqual(queryInterface(_pfx("I4")), module.I4)

    # "testComposite*" exercises tags that DO have children.
    # "testComposite*TopPerm" exercises tags with permission in containing tag.
    # "testComposite*ElementPerm" exercises tags w/permission in children.

    @_skip_wo_zope_configuration
    def testCompositeNoPerm(self):
        # Establish rejection of declarations lacking a permission spec.
        from zope.configuration.xmlconfig import ZopeXMLConfigurationError
        declaration = ('''<class class="%s">
                            <require
                                attributes="m1"/>
                          </class>'''
                       % (_pfx("test_class")))
        self.assertRaises(ZopeXMLConfigurationError,
                          self.assertDeclaration,
                          declaration)



    @_skip_wo_zope_configuration
    def testCompositeMethodsPluralElementPerm(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m3"/>
                          </class>'''
                       % (_pfx("test_class"), P1))
        self.assertDeclaration(declaration,
                               m1P=P1, m3P=P1)

    @_skip_wo_zope_configuration
    def testCompositeInterfaceTopPerm(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                interface="%s"/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("I")))
        self.assertDeclaration(declaration,
                               m1P=P1, m2P=P1)


    @_skip_wo_zope_configuration
    def testSubInterfaces(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                interface="%s"/>
                          </class>'''
                       % (_pfx("test_class"), P1, _pfx("I2")))
        # m1 and m2 are in the interface, so should be set, and m3 should not:
        self.assertDeclaration(declaration, m1P=P1, m2P=P1)


    @_skip_wo_zope_configuration
    def testMimicOnly(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m2"/>
                          </class>
                          <class class="%s">
                            <require like_class="%s" />
                          </class>
                          ''' % (_pfx("test_base"), P1,
                _pfx("test_class"), _pfx("test_base")))
        # m1 and m2 are in the interface, so should be set, and m3 should not:
        self.assertDeclaration(declaration,
                               m1P=P1, m2P=P1)


    @_skip_wo_zope_configuration
    def testMimicAsDefault(self):
        declaration = ('''<class class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m2"/>
                          </class>
                          <class class="%s">
                            <require like_class="%s" />
                            <require
                                permission="%s"
                                attributes="m2 m3"/>
                          </class>
                          ''' % (_pfx("test_base"), P1,
                _pfx("test_class"), _pfx("test_base"), P2))

        # m1 and m2 are in the interface, so should be set, and m3 should not:
        self.assertDeclaration(declaration,
                               m1P=P1, m2P=P2, m3P=P2)


def apply_declaration(declaration):
    '''Apply the xmlconfig machinery.'''
    from zope.configuration.xmlconfig import xmlconfig
    if isinstance(declaration, bytes):
        declaration = declaration.decode("utf-8")
    return xmlconfig(io.StringIO(declaration))


@_skip_wo_zope_configuration
def make_dummy():
    from zope.interface import Interface
    import zope.security.zcml
    global IDummy
    class IDummy(Interface):
        perm = zope.security.zcml.Permission(title=u'')


perms = []

def dummy(context_, perm):
    global perms
    perms.append(perm)


class DirectivesTest(unittest.TestCase):

    def setUp(self):
        try:
            from zope.component.testing import setUp
        except ImportError:
            pass
        else:
            setUp()

    def tearDown(self):
        del perms[:]
        try:
            from zope.component.testing import tearDown
        except ImportError:
            pass
        else:
            tearDown()

    @_skip_wo_zope_configuration
    def testRedefinePermission(self):
        from zope.configuration import xmlconfig
        from zope.security import tests
        make_dummy()
        xmlconfig.file("redefineperms.zcml", tests)
        self.assertEqual(perms, ['zope.Security'])


def test_suite():
    return unittest.defaultTestLoader.loadTestsFromName(__name__)