[Zope3-checkins] CVS: Zope3/src/zope/app/contentdirective/tests - __init__.py:1.1.2.1 exampleclass.py:1.1.2.1 test_directives.py:1.1.2.1 test_factory.py:1.1.2.1 test_modulehookup.py:1.1.2.1 test_requirepermissions.py:1.1.2.1

Jim Fulton jim@zope.com
Mon, 23 Dec 2002 14:31:33 -0500


Update of /cvs-repository/Zope3/src/zope/app/contentdirective/tests
In directory cvs.zope.org:/tmp/cvs-serv19908/zope/app/contentdirective/tests

Added Files:
      Tag: NameGeddon-branch
	__init__.py exampleclass.py test_directives.py test_factory.py 
	test_modulehookup.py test_requirepermissions.py 
Log Message:
Initial renaming before debugging

=== Added File Zope3/src/zope/app/contentdirective/tests/__init__.py ===
#
# This file is necessary to make this directory a package.


=== Added File Zope3/src/zope/app/contentdirective/tests/exampleclass.py ===
from zope.interface import Interface

class ExampleClass:
    pass
    
class IExample(Interface):
    pass

class IExampleContainer(Interface):
    pass


=== Added File Zope3/src/zope/app/contentdirective/tests/test_directives.py ===
##############################################################################
#
# 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.0 (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.
# 
##############################################################################
"""

$Id: test_directives.py,v 1.1.2.1 2002/12/23 19:31:32 jim Exp $
"""

import unittest
import sys
import os
from StringIO import StringIO

from zope.configuration.xmlconfig import xmlconfig, XMLConfig
from zope.configuration.xmlconfig import ZopeXMLConfigurationError
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.security.securitymanagement import newSecurityManager, system_user
import zope.configuration
import Zope.App.ComponentArchitecture
import Zope.App.Security
import Zope.App.ContentDirective
from zope.app.security.exceptions import UndefinedPermissionError

# explicitly import ExampleClass and IExample using full paths
# so that they are the same objects as resolve will get.
from zope.app.contentdirective.tests.exampleclass import ExampleClass, IExample


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

class TestContentDirective(PlacelessSetup, unittest.TestCase):
    def setUp(self):
        PlacelessSetup.setUp(self)
        newSecurityManager(system_user)
        XMLConfig('metameta.zcml', Zope.Configuration)()
        XMLConfig('meta.zcml', Zope.App.ContentDirective)()
        XMLConfig('meta.zcml', Zope.App.Security)()
        
        try:
            del ExampleClass.__implements__
        except AttributeError:
            pass
            
    def testEmptyDirective(self):
        f = configfile("""
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
</content>
                       """)
        xmlconfig(f)

            
    def testImplements(self):
        f = configfile("""
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
  <implements interface="Zope.App.ContentDirective.tests.ExampleClass.IExample" />
</content>
                       """)
        xmlconfig(f)
        self.failUnless(IExample.isImplementedByInstancesOf(ExampleClass))
        
        
    def testRequire(self):
        f = configfile("""
<permission id="Zope.View" title="Zope view permission" />
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <require permission="Zope.View"
                      attributes="anAttribute anotherAttribute" />
</content>
                       """)
        xmlconfig(f)

    def testAllow(self):
        f = configfile("""
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <allow attributes="anAttribute anotherAttribute" />
</content>
                       """)
        xmlconfig(f)
        
    def testMimic(self):
        f = configfile("""
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <require like_class="Zope.App.ContentDirective.tests.ExampleClass." />
</content>
                       """)
        xmlconfig(f)
        

class TestFactorySubdirective(PlacelessSetup, unittest.TestCase):
    def setUp(self):
        PlacelessSetup.setUp(self)
        newSecurityManager(system_user)
        XMLConfig('metameta.zcml', Zope.Configuration)()
        XMLConfig('meta.zcml', Zope.App.ContentDirective)()
        XMLConfig('meta.zcml', Zope.App.Security)()

    def testFactory(self):
        f = configfile("""
<permission id="Zope.Foo" title="Zope Foo Permission" />

<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <factory 
      id="Example" 
      permission="Zope.Foo"
      title="Example content"
      description="Example description"
    />
</content>
                       """)
        xmlconfig(f)


    def testFactoryUndefinedPermission(self):
         
        f = configfile("""
<permission id="Zope.Foo" title="Zope Foo Permission" />

<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <factory 
      id="Example" 
      permission="UndefinedPermission"
      title="Example content"
      description="Example description"
    />
</content>
            """)
        self.assertRaises(UndefinedPermissionError, xmlconfig, f,
                          testing=1)


def test_suite():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(TestContentDirective))
    suite.addTest(loader.loadTestsFromTestCase(TestFactorySubdirective))
    return suite


if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())


=== Added File Zope3/src/zope/app/contentdirective/tests/test_factory.py ===
##############################################################################
#
# 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.0 (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.
# 
##############################################################################
""" Test handler for 'factory' subdirective of 'content' directive """

import unittest
import sys
import os
from cStringIO import StringIO

from zope.configuration.xmlconfig import xmlconfig, ZopeXMLConfigurationError
from zope.configuration.xmlconfig import XMLConfig
from zope.app.tests.placelesssetup import PlacelessSetup
from zope.security.securitymanagement import newSecurityManager, system_user

import zope.configuration
import Zope.App.Security
from zope.app.security.exceptions import UndefinedPermissionError

import Zope.App.ContentDirective
from zope.app.contentdirective.tests.exampleclass \
    import ExampleClass, IExample, IExampleContainer

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

class Test(PlacelessSetup, unittest.TestCase):
    def setUp(self):
        PlacelessSetup.setUp(self)
        newSecurityManager(system_user)
        XMLConfig('metameta.zcml', Zope.Configuration)()
        XMLConfig('meta.zcml', Zope.App.ContentDirective)()
        XMLConfig('meta.zcml', Zope.App.Security)()


    def testFactory(self):
        from zope.component import getService
        from zope.proxy.introspection import removeAllProxies
        f = configfile("""
<permission id="Zope.Foo" title="Zope Foo Permission" />
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <factory 
      id="Example" 
      permission="Zope.Foo"
      title="Example content"
      description="Example description"
       />
</content>
                       """)
        xmlconfig(f)
        obj = getService(None, "Factories").createObject('Example')
        obj = removeAllProxies(obj)
        self.failUnless(isinstance(obj, ExampleClass))

    def testFactoryDefaultId(self):
        from zope.component import getService
        from zope.proxy.introspection import removeAllProxies
        f = configfile("""
<permission id="Zope.Foo" title="Zope Foo Permission" />
<content class="Zope.App.ContentDirective.tests.ExampleClass.">
    <factory 
      permission="Zope.Foo"
      title="Example content"
      description="Example description"
       />
</content>
                       """)
        xmlconfig(f)
        obj = getService(None, "Factories").createObject(
            'Zope.App.ContentDirective.tests.ExampleClass.')
        obj = removeAllProxies(obj)
        self.failUnless(isinstance(obj, ExampleClass))


def test_suite():
    loader=unittest.TestLoader()
    return loader.loadTestsFromTestCase(Test)

if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())





=== Added File Zope3/src/zope/app/contentdirective/tests/test_modulehookup.py ===
##############################################################################
#
# 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.0 (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.
# 
##############################################################################
"""Preliminaries to hookup a test suite with the external TestModule.

This is necessary because the test framework interferes with seeing changes in
the running modules via the module namespace.  This enables having some
subject classes, instances, permissions, etc, that don't live in the test
modules, themselves."""

from zope.interface import Interface
from zope.schema import Text

PREFIX = "Zope.App.Security.tests.TestModule."
import zope.app.security.tests.test_module
TestModule.test_class = None
class I(Interface):
    def m1():
        pass
    def m2():
        pass

class I2(I):
    def m4():
        pass
    

class S(Interface):
    foo = Text()
    bar = Text()
    

TestModule.I = I
TestModule.I2 = I2
TestModule.S = S

template_bracket = """<zopeConfigure
   xmlns="http://namespaces.zope.org/zope">
   %s
</zopeConfigure>"""


=== Added File Zope3/src/zope/app/contentdirective/tests/test_requirepermissions.py ===
##############################################################################
#
# 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.0 (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.
# 
##############################################################################
""" Test handler for 'require' subdirective of 'content' directive """

import unittest
from cStringIO import StringIO

import zope.configuration
import Zope.App.Security
from Zope.App.Security import protectClass
from zope.app.security.exceptions import UndefinedPermissionError
from zope.security.checker import selectChecker
from zope.exceptions import Forbidden


# So we can use config parser to exercise protectClass stuff.
from zope.configuration.xmlconfig import xmlconfig, ZopeXMLConfigurationError
from zope.configuration.xmlconfig import XMLConfig

from zope.app.contentdirective.tests.test_modulehookup import * # XXX I hate this!

from zope.testing.cleanup import CleanUp # Base class w registry cleanup

import Zope.App.ContentDirective

def defineDirectives():
    XMLConfig('metameta.zcml', Zope.Configuration)()
    XMLConfig('meta.zcml', Zope.App.ContentDirective)()
    XMLConfig('meta.zcml', Zope.App.Security)()
    xmlconfig(StringIO("""<zopeConfigure
        xmlns='http://namespaces.zope.org/zope' >
       <permission id="extravagant" title="extravagant" />
       <permission id="paltry" title="paltry" />
    </zopeConfigure>"""))

NOTSET = []

P1 = "extravagant"
P2 = "paltry"

class Test(CleanUp, unittest.TestCase):

    def setUp(self):
        defineDirectives()
        class B:
            def m1(self):
                return "m1"
            def m2(self):
                return "m2"
        class C(B):
            __implements__ = I
            def m3(self):
                return "m3"
            def m4(self):
                return "m4"
        TestModule.test_base = B
        TestModule.test_class = C
        TestModule.test_instance = C()
        self.assertState()

    def tearDown(self):
        CleanUp.tearDown(self)
        TestModule.test_class = None

    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.exceptions import Forbidden

        checker = selectChecker(TestModule.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):
        apply_declaration(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.

    def testSimpleMethodsPlural(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s" 
                                attributes="m1 m3"/>
                          </content>"""
                       % (PREFIX+"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.exceptions import Forbidden

        checker = selectChecker(TestModule.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)

    def test_set_attributes(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s" 
                                set_attributes="m1 m3"/>
                          </content>"""
                       % (PREFIX+"test_class", P1))
        apply_declaration(template_bracket % declaration)
        checker = selectChecker(TestModule.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)

    def test_set_schema(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s" 
                                set_schema="%s"/>
                          </content>"""
                       % (PREFIX+"test_class", P1, PREFIX+"S"))
        apply_declaration(template_bracket % declaration)
        checker = selectChecker(TestModule.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)

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

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

    def testCompositeNoPerm(self):
        # Establish rejection of declarations lacking a permission spec.
        declaration = ("""<content class="%s">
                            <require
                                attributes="m1"/>
                          </content>"""
                       % (PREFIX+"test_class"))
        self.assertRaises(ZopeXMLConfigurationError,
                          self.assertDeclaration,
                          declaration)



    def testCompositeMethodsPluralElementPerm(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m3"/>
                          </content>"""
                       % (PREFIX+"test_class", P1))
        self.assertDeclaration(declaration,
                               m1P=P1, m3P=P1)

    def testCompositeInterfaceTopPerm(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s"
                                interface="%s"/>
                          </content>"""
                       % (PREFIX+"test_class", P1, PREFIX+"I"))
        self.assertDeclaration(declaration,
                               m1P=P1, m2P=P1)


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


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

    def testMimicAsDefault(self):
        declaration = ("""<content class="%s">
                            <require
                                permission="%s"
                                attributes="m1 m2"/>
                          </content>
                          <content class="%s">
                            <require like_class="%s" />
                            <require
                                permission="%s"
                                attributes="m2 m3"/>
                          </content>
                          """ % (PREFIX+"test_base", P1,
                PREFIX+"test_class", PREFIX+"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."""
    return xmlconfig(StringIO(declaration))

def test_suite():
    loader=unittest.TestLoader()
    return loader.loadTestsFromTestCase(Test)

if __name__=='__main__':
    unittest.TextTestRunner().run(test_suite())