summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJason Madden <jason+github@nextthought.com>2017-09-08 07:14:17 -0500
committerGitHub <noreply@github.com>2017-09-08 07:14:17 -0500
commitd8565d6dc4758b42425be5adf2d4786d0c8d10a6 (patch)
tree6804eb7555563da9749445b5142cd7b9ed70bdbe
parented4d2b755b0af0d27fcd26211115babe99dbe4ff (diff)
parenta0372d5949642bd744c3d97628f136c51e743e38 (diff)
downloadzope-security-d8565d6dc4758b42425be5adf2d4786d0c8d10a6.tar.gz
Merge pull request #32 from zopefoundation/remove_u
Simplify _compat.py now that we only run on newer Pythons
-rw-r--r--CHANGES.rst3
-rw-r--r--src/zope/security/_compat.py27
-rw-r--r--src/zope/security/_definitions.py7
-rw-r--r--src/zope/security/checker.py3
-rw-r--r--src/zope/security/metadirectives.py33
-rw-r--r--src/zope/security/permission.py5
-rw-r--r--src/zope/security/tests/test_checker.py13
-rw-r--r--src/zope/security/tests/test_management.py14
-rw-r--r--src/zope/security/tests/test_metaconfigure.py17
-rw-r--r--src/zope/security/tests/test_proxy.py129
-rw-r--r--src/zope/security/tests/test_zcml_functest.py36
-rw-r--r--src/zope/security/zcml.py42
12 files changed, 149 insertions, 180 deletions
diff --git a/CHANGES.rst b/CHANGES.rst
index a911ce1..58d4122 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -29,6 +29,9 @@ Changes
default. In addition, iteration of all the custom iterator types
defined in itertools are also allowed by default.
+- Simplify the internal ``_compat.py`` module now that we only run on
+ newer Python versions. See `PR 32 <https://github.com/zopefoundation/zope.security/pull/32>`_.
+
4.1.1 (2017-05-17)
------------------
diff --git a/src/zope/security/_compat.py b/src/zope/security/_compat.py
index f3e441f..84ac98d 100644
--- a/src/zope/security/_compat.py
+++ b/src/zope/security/_compat.py
@@ -20,17 +20,9 @@ import types
py_impl = getattr(platform, 'python_implementation', lambda: None)
PYPY = py_impl() == 'PyPy'
-PURE_PYTHON = os.environ.get('PURE_PYTHON', False)
+PURE_PYTHON = os.environ.get('PURE_PYTHON', PYPY)
-if sys.version_info[0] < 3: #pragma NO COVER
-
- from StringIO import StringIO
- import cPickle as _pickle
-
- reload = reload
-
- def _u(s):
- return unicode(s, 'unicode_escape')
+if sys.version_info[0] < 3: # pragma: no cover
CLASS_TYPES = (type, types.ClassType)
_BUILTINS = '__builtin__'
@@ -38,17 +30,7 @@ if sys.version_info[0] < 3: #pragma NO COVER
PYTHON3 = False
PYTHON2 = True
- TEXT = unicode
-
-else: #pragma NO COVER
-
- from io import StringIO
- import pickle as _pickle
-
- from imp import reload
-
- def _u(s):
- return s
+else: # pragma: no cover
CLASS_TYPES = (type,)
_BUILTINS = 'builtins'
@@ -56,6 +38,5 @@ else: #pragma NO COVER
PYTHON3 = True
PYTHON2 = False
- TEXT = str
-_BLANK = _u('')
+_BLANK = u''
diff --git a/src/zope/security/_definitions.py b/src/zope/security/_definitions.py
index a54d7a8..e4f3867 100644
--- a/src/zope/security/_definitions.py
+++ b/src/zope/security/_definitions.py
@@ -17,12 +17,11 @@ import threading
import zope.interface
from zope.security import interfaces
-from zope.security._compat import _u
thread_local = threading.local()
@zope.interface.provider(interfaces.IPrincipal)
class system_user(object):
- id = _u('zope.security.management.system_user')
- title = _u('System')
- description = _u('')
+ id = u'zope.security.management.system_user'
+ title = u'System'
+ description = u''
diff --git a/src/zope/security/checker.py b/src/zope/security/checker.py
index e5e23c3..d617ef4 100644
--- a/src/zope/security/checker.py
+++ b/src/zope/security/checker.py
@@ -49,7 +49,6 @@ from zope.security.interfaces import Unauthorized
from zope.security._definitions import thread_local
from zope.security._compat import CLASS_TYPES
from zope.security._compat import PYTHON2
-from zope.security._compat import _u
from zope.security.proxy import Proxy
from zope.security.proxy import getChecker
@@ -687,7 +686,7 @@ BasicTypes_examples = {
}
if PYTHON2:
- BasicTypes_examples[unicode] = _u('uabc')
+ BasicTypes_examples[unicode] = u'uabc'
BasicTypes_examples[long] = long(65536)
diff --git a/src/zope/security/metadirectives.py b/src/zope/security/metadirectives.py
index a080372..1a81658 100644
--- a/src/zope/security/metadirectives.py
+++ b/src/zope/security/metadirectives.py
@@ -25,7 +25,6 @@ from zope.interface import Interface
import zope.security.zcml
from zope.security.i18n import ZopeMessageFactory as _
from zope.security.zcml import Permission
-from zope.security._compat import _u
class IClassDirective(zope.interface.Interface):
"""Make statements about a class"""
@@ -149,8 +148,8 @@ class IModule(Interface):
"""Group security declarations about a module"""
module = GlobalObject(
- title=_u("Module"),
- description=_u("Pointer to the module object."),
+ title=u"Module",
+ description=u"Pointer to the module object.",
required=True)
@@ -163,17 +162,17 @@ class IAllow(Interface):
"""
attributes = Tokens(
- title=_u("Attributes"),
- description=_u("The attributes to provide access to."),
- value_type = PythonIdentifier(),
+ title=u"Attributes",
+ description=u"The attributes to provide access to.",
+ value_type=PythonIdentifier(),
required=False)
interface = Tokens(
- title=_u("Interface"),
- description=_u("Interfaces whos names to provide access to. Access "
- "will be provided to all of the names defined by the "
- "interface(s). Multiple interfaces can be supplied."),
- value_type = GlobalInterface(),
+ title=u"Interface",
+ description=(u"Interfaces whos names to provide access to. Access "
+ u"will be provided to all of the names defined by the "
+ u"interface(s). Multiple interfaces can be supplied."),
+ value_type=GlobalInterface(),
required=False)
@@ -182,15 +181,15 @@ class IRequire(Interface):
The given permission is required to access any names provided
directly in the attributes attribute or any names defined by
- interfaces listed in the interface attribute.
+ interfaces listed in the interface attribute.
"""
attributes = Tokens(
- title=_u("Attributes"),
- description=_u("The attributes to require permission for."),
- value_type = PythonIdentifier(),
+ title=u"Attributes",
+ description=u"The attributes to require permission for.",
+ value_type=PythonIdentifier(),
required=False)
permission = Permission(
- title=_u("Permission ID"),
- description=_u("The id of the permission to require."))
+ title=u"Permission ID",
+ description=u"The id of the permission to require.")
diff --git a/src/zope/security/permission.py b/src/zope/security/permission.py
index efacde9..8044d4d 100644
--- a/src/zope/security/permission.py
+++ b/src/zope/security/permission.py
@@ -27,7 +27,6 @@ from zope.schema.vocabulary import SimpleVocabulary
from zope.security.checker import CheckerPublic
from zope.security.interfaces import IPermission
-from zope.security._compat import _u
@implementer(IPermission)
class Permission(object):
@@ -49,7 +48,7 @@ def allPermissions(context=None):
"""Get the ids of all defined permissions
"""
for id, permission in getUtilitiesFor(IPermission, context):
- if id != _u('zope.Public'):
+ if id != u'zope.Public':
yield id
def PermissionsVocabulary(context=None):
@@ -85,7 +84,7 @@ def PermissionIdsVocabulary(context=None):
terms.append(SimpleTerm(name, name, name))
terms = sorted(terms, key=operator.attrgetter('title'))
if has_public:
- terms.insert(0, SimpleTerm(CheckerPublic, 'zope.Public', _u('Public')))
+ terms.insert(0, SimpleTerm(CheckerPublic, 'zope.Public', u'Public'))
return SimpleVocabulary(terms)
directlyProvides(PermissionIdsVocabulary, IVocabularyFactory)
diff --git a/src/zope/security/tests/test_checker.py b/src/zope/security/tests/test_checker.py
index 692cbde..9aaee38 100644
--- a/src/zope/security/tests/test_checker.py
+++ b/src/zope/security/tests/test_checker.py
@@ -868,13 +868,12 @@ class _SelectCheckerBase(object):
def test_w_basic_types_NoProxy(self):
import datetime
from zope.i18nmessageid import Message
- from zope.security._compat import _u
msg = Message('msg')
for obj in [object(),
42,
3.14,
None,
- _u('text'),
+ u'text',
b'binary',
msg,
True,
@@ -1044,13 +1043,12 @@ class Test_defineChecker(unittest.TestCase):
return defineChecker(type_, checker)
def test_w_wrong_type(self):
- from zope.security._compat import _u
checker = object()
for obj in [object(),
42,
3.14,
None,
- _u('text'),
+ u'text',
b'binary',
True,
]:
@@ -2108,11 +2106,10 @@ class TestSecurityPolicy(unittest.TestCase):
class TestCheckerPublic(unittest.TestCase):
def test_that_pickling_CheckerPublic_retains_identity(self):
- from zope.security._compat import _pickle
+ import pickle
from zope.security.checker import CheckerPublic
- self.assertTrue(_pickle.loads(_pickle.dumps(CheckerPublic))
- is
- CheckerPublic)
+ self.assertIs(pickle.loads(pickle.dumps(CheckerPublic)),
+ CheckerPublic)
def test_that_CheckerPublic_identity_works_even_when_proxied(self):
from zope.security.checker import ProxyFactory
diff --git a/src/zope/security/tests/test_management.py b/src/zope/security/tests/test_management.py
index 8eee32b..83aca7b 100644
--- a/src/zope/security/tests/test_management.py
+++ b/src/zope/security/tests/test_management.py
@@ -172,17 +172,15 @@ class Test(unittest.TestCase):
def test_system_user(self):
from zope.security.management import system_user
- from zope.security._compat import TEXT
- from zope.security._compat import _u
+
self.assertEqual(system_user.id,
- _u('zope.security.management.system_user'))
+ u'zope.security.management.system_user')
- self.assertEqual(system_user.title, _u('System'))
+ self.assertEqual(system_user.title, u'System')
for name in 'id', 'title', 'description':
- self.assertTrue(isinstance(getattr(system_user, name), TEXT))
+ self.assertIsInstance(getattr(system_user, name),
+ type(u''))
def test_suite():
- return unittest.TestSuite((
- unittest.makeSuite(Test),
- ))
+ return unittest.defaultTestLoader.loadTestsFromName(__name__)
diff --git a/src/zope/security/tests/test_metaconfigure.py b/src/zope/security/tests/test_metaconfigure.py
index 934d034..3998268 100644
--- a/src/zope/security/tests/test_metaconfigure.py
+++ b/src/zope/security/tests/test_metaconfigure.py
@@ -218,10 +218,9 @@ class ClassDirectiveTests(unittest.TestCase):
from zope.schema import Field
from zope.interface import Interface
from zope.security.protectclass import protectSetAttribute
- from zope.security._compat import _u
class IFoo(Interface):
- bar = Field(_u("Bar"))
- baz = Field(_u("Baz"))
+ bar = Field(u"Bar")
+ baz = Field(u"Baz")
context = DummyZCMLContext()
directive = self._makeOne(context, Foo)
directive.require(context, permission='testing', set_schema=[IFoo])
@@ -258,9 +257,8 @@ class ClassDirectiveTests(unittest.TestCase):
from zope.component.interface import provideInterface
from zope.schema import Field
from zope.interface import Interface
- from zope.security._compat import _u
class IFoo(Interface):
- bar = Field(_u("Bar"), readonly=True)
+ bar = Field(u"Bar", readonly=True)
context = DummyZCMLContext()
directive = self._makeOne(context, Foo)
directive.require(context, permission='testing', set_schema=[IFoo])
@@ -650,11 +648,4 @@ class DummyZCMLContext(object):
def test_suite():
- return unittest.TestSuite([
- unittest.makeSuite(Test_dottedName),
- unittest.makeSuite(ClassDirectiveTests),
- unittest.makeSuite(Test_protectModule),
- unittest.makeSuite(Test_allow),
- unittest.makeSuite(Test_allow),
- ])
-
+ return unittest.defaultTestLoader.loadTestsFromName(__name__)
diff --git a/src/zope/security/tests/test_proxy.py b/src/zope/security/tests/test_proxy.py
index 20f66da..dd04d70 100644
--- a/src/zope/security/tests/test_proxy.py
+++ b/src/zope/security/tests/test_proxy.py
@@ -14,9 +14,8 @@
"""Security proxy tests
"""
import unittest
-import sys
-from zope.security._compat import PYTHON2, PYPY, PURE_PYTHON
+from zope.security._compat import PYTHON2, PURE_PYTHON
def _skip_if_not_Py2(testfunc):
return unittest.skipUnless(PYTHON2, "Only on Py2")(testfunc)
@@ -24,7 +23,20 @@ def _skip_if_not_Py2(testfunc):
def _skip_if_Py2(testfunc):
return unittest.skipIf(PYTHON2, "Only on Py3")(testfunc)
-class ProxyTestBase(object):
+# pylint:disable=protected-access,eval-used,too-many-lines,too-many-public-methods
+
+if not PYTHON2:
+ def coerce(*args):
+ raise NotImplementedError("Not on Python 3")
+ cmp = coerce
+ long = int
+
+class AbstractProxyTestBase(object):
+
+ # pylint:disable=no-member,blacklisted-name
+
+ def _getTargetClass(self):
+ raise NotImplementedError("Subclass responsibility")
def _makeOne(self, object, checker):
return self._getTargetClass()(object, checker)
@@ -108,9 +120,9 @@ class ProxyTestBase(object):
def test___delattr___w_checker_unauthorized(self):
from zope.security.interfaces import Unauthorized
class Foo(object):
- pass
+ def __init__(self):
+ self.bar = 'Bar'
target = Foo()
- target.bar = 'Bar'
checker = DummyChecker(Unauthorized)
proxy = self._makeOne(target, checker)
self.assertRaises(Unauthorized, delattr, proxy, 'bar')
@@ -120,9 +132,9 @@ class ProxyTestBase(object):
def test___delattr___w_checker_forbidden_attribute(self):
from zope.security.interfaces import ForbiddenAttribute
class Foo(object):
- pass
+ def __init__(self):
+ self.bar = 'Bar'
target = Foo()
- target.bar = 'Bar'
checker = DummyChecker(ForbiddenAttribute)
proxy = self._makeOne(target, checker)
self.assertRaises(ForbiddenAttribute, delattr, proxy, 'bar')
@@ -145,7 +157,7 @@ class ProxyTestBase(object):
address = _fmt_address(target)
self.assertEqual(str(proxy),
'<security proxied %s.object '
- 'instance at %s>' % (_BUILTINS, address))
+ 'instance at %s>' % (_BUILTINS, address))
def test__str__fails_return(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -177,7 +189,7 @@ class ProxyTestBase(object):
address = _fmt_address(target)
self.assertEqual(repr(proxy),
'<security proxied %s.object '
- 'instance at %s>' % (_BUILTINS, address))
+ 'instance at %s>' % (_BUILTINS, address))
def test__str__falls_through_to_repr_when_both_allowed(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -257,7 +269,6 @@ class ProxyTestBase(object):
@_skip_if_not_Py2
def test___cmp___w_other_proxy(self):
target = object()
- other = object()
checker = object() # checker not consulted
proxy = self._makeOne(target, checker)
o_proxy = self._makeOne(target, checker)
@@ -516,7 +527,7 @@ class ProxyTestBase(object):
def test___pow___w_x_proxied_forbidden(self):
from zope.security.interfaces import ForbiddenAttribute
- x, y, z = 3, 4, 7
+ y, z = 4, 7
checker = DummyChecker(ForbiddenAttribute)
proxy = self._makeOne(y, checker)
self.assertRaises(ForbiddenAttribute, lambda: pow(proxy, y, z))
@@ -1380,14 +1391,18 @@ class ProxyTestBase(object):
"x=%r; y=%r; expr=%r" % (x, y, expr))
-class ProxyCTests(unittest.TestCase, ProxyTestBase):
+@unittest.skipIf(PURE_PYTHON,
+ "Needs C extension")
+class ProxyCTests(AbstractProxyTestBase,
+ unittest.TestCase):
def _getTargetClass(self):
from zope.security.proxy import _Proxy
return _Proxy
-class ProxyPyTests(unittest.TestCase, ProxyTestBase):
+class ProxyPyTests(AbstractProxyTestBase,
+ unittest.TestCase):
def _getTargetClass(self):
from zope.security.proxy import ProxyPy
@@ -1537,7 +1552,7 @@ class Checker(object):
ok = 1
- unproxied_types = str,
+ unproxied_types = {str,}
def check_getattr(self, object, name):
if name not in ("foo", "next", "__class__", "__name__", "__module__"):
@@ -1560,7 +1575,7 @@ class Checker(object):
class Something:
def __init__(self):
- self.foo = [1,2,3]
+ self.foo = [1, 2, 3]
def __getitem__(self, key):
return self.foo[key]
def __setitem__(self, key, value):
@@ -1605,7 +1620,6 @@ class ProxyTests(unittest.TestCase):
self.c.ok = 1
def testDerivation(self):
- from zope.security._compat import PURE_PYTHON
if PURE_PYTHON:
from zope.proxy import PyProxyBase as ProxyBase
else:
@@ -1642,7 +1656,7 @@ class ProxyTests(unittest.TestCase):
def testGetAttrOK(self):
from zope.security.proxy import removeSecurityProxy
- self.assertEqual(removeSecurityProxy(self.p.foo), [1,2,3])
+ self.assertEqual(removeSecurityProxy(self.p.foo), [1, 2, 3])
def testGetAttrFail(self):
self.assertRaises(RuntimeError, lambda: self.p.bar)
@@ -1652,7 +1666,8 @@ class ProxyTests(unittest.TestCase):
self.assertEqual(self.p.foo, 42)
def testSetAttrFail(self):
- def doit(): self.p.bar = 42
+ def doit():
+ self.p.bar = 42
self.assertRaises(RuntimeError, doit)
def testGetItemOK(self):
@@ -1666,7 +1681,8 @@ class ProxyTests(unittest.TestCase):
self.assertEqual(self.p[0], 42)
def testSetItemFail(self):
- def doit(): del self.p[0]
+ def doit():
+ del self.p[0]
self.shouldFail(doit)
def testDelItemOK(self):
@@ -1676,7 +1692,8 @@ class ProxyTests(unittest.TestCase):
self.shouldFail(lambda: self.p[0])
def testDelItemFail(self):
- def doit(): self.p[10] = 42
+ def doit():
+ self.p[10] = 42
self.shouldFail(doit)
def testCallOK(self):
@@ -1741,7 +1758,8 @@ class ProxyTests(unittest.TestCase):
self.p[:] = [42]
def testSetSliceFail(self):
- def doit(): self.p[:] = [42]
+ def doit():
+ self.p[:] = [42]
self.shouldFail(doit)
def testContainsOK(self):
@@ -1786,9 +1804,9 @@ class ProxyTests(unittest.TestCase):
# aren't proxied.
from zope.security.proxy import ProxyFactory
from zope.security.proxy import removeSecurityProxy
- self.c.unproxied_types = [str, int, float]
+ self.c.unproxied_types = {str, int, float}
if PYTHON2:
- self.c.unproxied_types.append(long)
+ self.c.unproxied_types.add(long)
for expr in self.unops:
x = 1
y = eval(expr)
@@ -1804,9 +1822,9 @@ class ProxyTests(unittest.TestCase):
# unops that don't return a proxy
P = self.c.proxy
for func in (
- hex, oct,
- # lambda x: not x,
- ):
+ hex, oct,
+ # lambda x: not x,
+ ):
self.assertEqual(func(P(100)), func(100))
self.shouldFail(func, P(100))
@@ -1864,58 +1882,63 @@ class ProxyTests(unittest.TestCase):
from zope.security.proxy import removeSecurityProxy
P = self.c.proxy
- # Before 2.3, coerce() of two proxies returns them unchanged
- import sys
- fixed_coerce = sys.version_info >= (2, 3, 0)
-
x = P(1)
y = P(2)
a, b = coerce(x, y)
- self.assertTrue(a is x and b is y)
+ self.assertIs(a, x)
+ self.assertIs(b, y)
x = P(1)
y = P(2.1)
a, b = coerce(x, y)
- self.assertTrue(removeSecurityProxy(a) == 1.0 and b is y)
- if fixed_coerce:
- self.assertTrue(type(removeSecurityProxy(a)) is float and b is y)
+ self.assertEqual(removeSecurityProxy(a), 1.0)
+ self.assertIs(b, y)
+ self.assertIs(type(removeSecurityProxy(a)), float)
+ self.assertIs(b, y)
x = P(1.1)
y = P(2)
a, b = coerce(x, y)
- self.assertTrue(a is x and removeSecurityProxy(b) == 2.0)
- if fixed_coerce:
- self.assertTrue(a is x and type(removeSecurityProxy(b)) is float)
+ self.assertIs(a, x)
+ self.assertEqual(removeSecurityProxy(b), 2.0)
+ self.assertIs(a, x)
+ self.assertIs(type(removeSecurityProxy(b)), float)
x = P(1)
y = 2
a, b = coerce(x, y)
- self.assertTrue(a is x and b is y)
+ self.assertIs(a, x)
+ self.assertIs(b, y)
x = P(1)
y = 2.1
a, b = coerce(x, y)
- self.assertTrue(type(removeSecurityProxy(a)) is float and b is y)
+ self.assertIs(type(removeSecurityProxy(a)), float)
+ self.assertIs(b, y)
x = P(1.1)
y = 2
a, b = coerce(x, y)
- self.assertTrue(a is x and type(removeSecurityProxy(b)) is float)
+ self.assertIs(a, x)
+ self.assertIs(type(removeSecurityProxy(b)), float)
x = 1
y = P(2)
a, b = coerce(x, y)
- self.assertTrue(a is x and b is y)
+ self.assertIs(a, x)
+ self.assertIs(b, y)
x = 1.1
y = P(2)
a, b = coerce(x, y)
- self.assertTrue(a is x and type(removeSecurityProxy(b)) is float)
+ self.assertIs(a, x)
+ self.assertIs(type(removeSecurityProxy(b)), float)
x = 1
y = P(2.1)
a, b = coerce(x, y)
- self.assertTrue(type(removeSecurityProxy(a)) is float and b is y)
+ self.assertIs(type(removeSecurityProxy(a)), float)
+ self.assertIs(b, y)
def test_using_mapping_slots_hack():
@@ -1996,7 +2019,11 @@ class LocationProxySecurityCheckerTests(unittest.TestCase):
import sys
from zope.location.location import LocationProxy
import zope.security
- from zope.security._compat import reload
+ try:
+ from importlib import reload as _reload
+ except ImportError:
+ _reload = reload # Python 2
+
# This attribute is set when zope.security.decorator is imported, to
# show that it will be set too, if zope.security.proxy is imported
# we set it to a different value at first:
@@ -2006,20 +2033,10 @@ class LocationProxySecurityCheckerTests(unittest.TestCase):
# After deleting zope.security.decorator and reloading
# zope.security.proxy the attribute is set again:
del sys.modules["zope.security.decorator"]
- reload(zope.security)
+ _reload(zope.security)
self.assertTrue(
hasattr(LocationProxy, '__Security_checker__'))
def test_suite():
- suite = unittest.TestSuite((
- unittest.makeSuite(ProxyPyTests),
- unittest.makeSuite(Test_getTestProxyItems),
- unittest.makeSuite(Test_isinstance),
- # pre-geddon
- unittest.makeSuite(ProxyTests),
- unittest.makeSuite(LocationProxySecurityCheckerTests),
- ))
- if not (PYPY or PURE_PYTHON):
- suite.addTest(unittest.makeSuite(ProxyCTests))
- return suite
+ return unittest.defaultTestLoader.loadTestsFromName(__name__)
diff --git a/src/zope/security/tests/test_zcml_functest.py b/src/zope/security/tests/test_zcml_functest.py
index 5f79fae..b932734 100644
--- a/src/zope/security/tests/test_zcml_functest.py
+++ b/src/zope/security/tests/test_zcml_functest.py
@@ -14,24 +14,19 @@
"""Directives Tests
"""
import unittest
-
+import io
def _skip_wo_zope_configuration(testfunc):
try:
import zope.configuration.xmlconfig
except ImportError:
- from functools import update_wrapper
- def dummy(self):
- pass
- update_wrapper(dummy, testfunc)
- return dummy
+ return unittest.skip("No zope.configuration")(testfunc)
else:
return testfunc
def configfile(s):
- from zope.security._compat import StringIO
- return StringIO("""<configure
+ return io.StringIO(u"""<configure
xmlns='http://namespaces.zope.org/zope'
i18n_domain='zope'>
%s
@@ -270,11 +265,10 @@ class Context(object):
self.actions += ((discriminator, callable, args), )
def __repr__(self):
- from zope.security._compat import StringIO
import re
import pprint
atre = re.compile(' at [0-9a-fA-Fx]+')
- stream = StringIO()
+ 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()
@@ -339,19 +333,18 @@ def _pfx(name):
return module.__name__ + '.' + name
def defineDirectives():
- from zope.security._compat import StringIO
from zope.configuration.xmlconfig import XMLConfig
from zope.configuration.xmlconfig import xmlconfig
import zope.security
XMLConfig('meta.zcml', zope.security)()
- xmlconfig(StringIO("""<configure
+ 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 = []
+NOTSET = ()
P1 = "zope.Extravagant"
P2 = "zope.Paltry"
@@ -655,19 +648,19 @@ class TestRequireDirective(unittest.TestCase):
def apply_declaration(declaration):
'''Apply the xmlconfig machinery.'''
- from zope.security._compat import StringIO
from zope.configuration.xmlconfig import xmlconfig
- return xmlconfig(StringIO(declaration))
+ 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
- from zope.security._compat import _u
global IDummy
class IDummy(Interface):
- perm = zope.security.zcml.Permission(title=_u(''))
+ perm = zope.security.zcml.Permission(title=u'')
perms = []
@@ -706,11 +699,4 @@ class DirectivesTest(unittest.TestCase):
def test_suite():
-
- return unittest.TestSuite((
- unittest.makeSuite(TestClassDirective),
- unittest.makeSuite(TestFactorySubdirective),
- unittest.makeSuite(TestFactoryDirective),
- unittest.makeSuite(TestRequireDirective),
- unittest.makeSuite(DirectivesTest),
- ))
+ return unittest.defaultTestLoader.loadTestsFromName(__name__)
diff --git a/src/zope/security/zcml.py b/src/zope/security/zcml.py
index 4198405..8504321 100644
--- a/src/zope/security/zcml.py
+++ b/src/zope/security/zcml.py
@@ -24,7 +24,6 @@ from zope.schema.interfaces import IFromUnicode
from zope.security.permission import checkPermission
from zope.security.management import setSecurityPolicy
-from zope.security._compat import _u
@implementer(IFromUnicode)
class Permission(Id):
@@ -42,9 +41,9 @@ class Permission(Id):
if value != 'zope.Public':
self.context.action(
- discriminator = None,
- callable = checkPermission,
- args = (None, value),
+ discriminator=None,
+ callable=checkPermission,
+ args=(None, value),
# Delay execution till end. This is an
# optimization. We don't want to intersperse utility
@@ -53,39 +52,40 @@ class Permission(Id):
# utility definition, as extensive caches have to be
# rebuilt.
order=9999999,
- )
+ )
class ISecurityPolicyDirective(Interface):
"""Defines the security policy that will be used for Zope."""
component = GlobalObject(
- title=_u("Component"),
- description=_u("Pointer to the object that will handle the security."),
+ title=u"Component",
+ description=u"Pointer to the object that will handle the security.",
required=True)
def securityPolicy(_context, component):
_context.action(
- discriminator = 'defaultPolicy',
- callable = setSecurityPolicy,
- args = (component,) )
+ discriminator='defaultPolicy',
+ callable=setSecurityPolicy,
+ args=(component,)
+ )
class IPermissionDirective(Interface):
"""Define a new security object."""
id = Id(
- title=_u("Id"),
- description=_u("Id as which this object will be known and used."),
+ title=u"Id",
+ description=u"Id as which this object will be known and used.",
required=True)
title = MessageID(
- title=_u("Title"),
- description=_u("Provides a title for the object."),
+ title=u"Title",
+ description=u"Provides a title for the object.",
required=True)
description = MessageID(
- title=_u("Description"),
- description=_u("Provides a description for the object."),
+ title=u"Description",
+ description=u"Provides a description for the object.",
required=False)
def permission(_context, id, title, description=''):
@@ -99,13 +99,13 @@ class IRedefinePermission(Interface):
"""Define a permission to replace another permission."""
from_ = Permission(
- title=_u("Original permission"),
- description=_u("Original permission id to redefine."),
+ title=u"Original permission",
+ description=u"Original permission id to redefine.",
required=True)
to = Permission(
- title=_u("Substituted permission"),
- description=_u("Substituted permission id."),
+ title=u"Substituted permission",
+ description=u"Substituted permission id.",
required=True)
def redefinePermission(_context, from_, to):
@@ -113,6 +113,6 @@ def redefinePermission(_context, from_, to):
# check if context has any permission mappings yet
if not hasattr(_context, 'permission_mapping'):
- _context.permission_mapping={}
+ _context.permission_mapping = {}
_context.permission_mapping[from_] = to