summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichael Howitz <mh@gocept.com>2022-12-23 09:27:18 +0100
committerGitHub <noreply@github.com>2022-12-23 09:27:18 +0100
commite2d9d9d49ceadb0c62ab96117ffc4dfa532819e0 (patch)
tree62e9110f084d572bf06f25115c8f1f794a8f19e9
parent831a34f5cf3e2c4297e0da35c4f38e7cf12fac16 (diff)
downloadzope-security-e2d9d9d49ceadb0c62ab96117ffc4dfa532819e0.tar.gz
Config with c code template 831a34f5 (#91)
* Drop support for Python 2.7, 3.5, 3.6.
-rw-r--r--.github/workflows/tests.yml43
-rwxr-xr-x.manylinux-install.sh6
-rw-r--r--.meta.toml7
-rw-r--r--CHANGES.rst4
-rw-r--r--appveyor.yml3
-rw-r--r--setup.cfg2
-rw-r--r--setup.py18
-rw-r--r--src/zope/security/_compat.py20
-rw-r--r--src/zope/security/_definitions.py8
-rw-r--r--src/zope/security/_proxy.c63
-rw-r--r--src/zope/security/_zope_security_checker.c53
-rw-r--r--src/zope/security/adapter.py4
-rw-r--r--src/zope/security/checker.py109
-rw-r--r--src/zope/security/decorator.py4
-rw-r--r--src/zope/security/examples/sandbox.py12
-rw-r--r--src/zope/security/examples/sandbox_security.py4
-rw-r--r--src/zope/security/metaconfigure.py2
-rw-r--r--src/zope/security/metadirectives.py24
-rw-r--r--src/zope/security/permission.py6
-rw-r--r--src/zope/security/proxy.py99
-rw-r--r--src/zope/security/simplepolicies.py2
-rw-r--r--src/zope/security/testing.py17
-rw-r--r--src/zope/security/tests/__init__.py2
-rw-r--r--src/zope/security/tests/exampleclass.py2
-rw-r--r--src/zope/security/tests/test_adapter.py52
-rw-r--r--src/zope/security/tests/test_checker.py172
-rw-r--r--src/zope/security/tests/test_decorator.py16
-rw-r--r--src/zope/security/tests/test_location.py2
-rw-r--r--src/zope/security/tests/test_management.py10
-rw-r--r--src/zope/security/tests/test_metaconfigure.py12
-rw-r--r--src/zope/security/tests/test_permission.py12
-rw-r--r--src/zope/security/tests/test_protectclass.py2
-rw-r--r--src/zope/security/tests/test_proxy.py466
-rw-r--r--src/zope/security/tests/test_simpleinteraction.py2
-rw-r--r--src/zope/security/tests/test_simplepolicies.py14
-rw-r--r--src/zope/security/tests/test_zcml.py10
-rw-r--r--src/zope/security/tests/test_zcml_functest.py41
-rw-r--r--src/zope/security/zcml.py30
-rw-r--r--tox.ini11
39 files changed, 400 insertions, 966 deletions
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 9a7f8c9..9551c7b 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -96,11 +96,7 @@ jobs:
fail-fast: false
matrix:
python-version:
- - "2.7"
- - "3.5"
- - "pypy-2.7"
- "pypy-3.7"
- - "3.6"
- "3.7"
- "3.8"
- "3.9"
@@ -109,11 +105,7 @@ jobs:
os: [ubuntu-20.04, macos-latest]
exclude:
- os: macos-latest
- python-version: "pypy-2.7"
- - os: macos-latest
python-version: "pypy-3.7"
- - os: macos-latest
- python-version: "3.5"
steps:
- name: checkout
@@ -141,16 +133,7 @@ jobs:
restore-keys: |
${{ runner.os }}-pip-
- - name: Install Build Dependencies (PyPy2)
- if: >
- startsWith(matrix.python-version, 'pypy-2.7')
- run: |
- pip install -U pip
- pip install -U setuptools wheel twine "cffi != 1.15.1"
- pip install -U zope.proxy
- - name: Install Build Dependencies (other Python versions)
- if: >
- !startsWith(matrix.python-version, 'pypy-2.7')
+ - name: Install Build Dependencies
run: |
pip install -U pip
pip install -U setuptools wheel twine cffi
@@ -160,9 +143,6 @@ jobs:
if: >
startsWith(runner.os, 'Mac')
&& !(startsWith(matrix.python-version, 'pypy')
- || matrix.python-version == '2.7'
- || matrix.python-version == '3.5'
- || matrix.python-version == '3.6'
|| matrix.python-version == '3.7')
env:
MACOSX_DEPLOYMENT_TARGET: 10.9
@@ -177,9 +157,6 @@ jobs:
if: >
startsWith(runner.os, 'Mac')
&& !(startsWith(matrix.python-version, 'pypy')
- || matrix.python-version == '2.7'
- || matrix.python-version == '3.5'
- || matrix.python-version == '3.6'
|| matrix.python-version == '3.7')
env:
MACOSX_DEPLOYMENT_TARGET: 11.0
@@ -194,9 +171,6 @@ jobs:
if: >
!startsWith(runner.os, 'Mac')
|| startsWith(matrix.python-version, 'pypy')
- || matrix.python-version == '2.7'
- || matrix.python-version == '3.5'
- || matrix.python-version == '3.6'
|| matrix.python-version == '3.7'
run: |
# Next, build the wheel *in place*. This helps ccache, and also lets us cache the configure
@@ -207,7 +181,6 @@ jobs:
- name: Install zope.security and dependencies
run: |
# Install to collect dependencies into the (pip) cache.
- pip install -U 'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"'
pip install .[test]
- name: Check zope.security build
@@ -225,9 +198,6 @@ jobs:
if: >
startsWith(runner.os, 'Mac')
&& !(startsWith(matrix.python-version, 'pypy')
- || matrix.python-version == '2.7'
- || matrix.python-version == '3.5'
- || matrix.python-version == '3.6'
|| matrix.python-version == '3.7')
uses: actions/upload-artifact@v3
with:
@@ -264,11 +234,7 @@ jobs:
fail-fast: false
matrix:
python-version:
- - "2.7"
- - "3.5"
- - "pypy-2.7"
- "pypy-3.7"
- - "3.6"
- "3.7"
- "3.8"
- "3.9"
@@ -277,11 +243,7 @@ jobs:
os: [ubuntu-20.04, macos-latest]
exclude:
- os: macos-latest
- python-version: "pypy-2.7"
- - os: macos-latest
python-version: "pypy-3.7"
- - os: macos-latest
- python-version: "3.5"
steps:
- name: checkout
@@ -318,7 +280,6 @@ jobs:
run: |
pip install -U wheel setuptools
pip install -U coverage
- pip install -U 'faulthandler; python_version == "2.7" and platform_python_implementation == "CPython"'
pip install -U 'cffi; platform_python_implementation == "CPython"'
# Unzip into src/ so that testrunner can find the .so files
# when we ask it to load tests from that directory. This
@@ -498,8 +459,6 @@ jobs:
# An alternate way to do this is to run the container directly with a uses:
# and then the script runs inside it. That may work better with caching.
# See https://github.com/pyca/bcrypt/blob/f6b5ee2eda76d077c531362ac65e16f045cf1f29/.github/workflows/wheel-builder.yml
- # The 2010 image is the most recent spec that comes with Python 2.7,
- # and only up through the tag 2021-02-06-3d322a5
env:
DOCKER_IMAGE: quay.io/pypa/${{ matrix.image }}
run: |
diff --git a/.manylinux-install.sh b/.manylinux-install.sh
index 8e5bb9c..8f736da 100755
--- a/.manylinux-install.sh
+++ b/.manylinux-install.sh
@@ -28,9 +28,6 @@ yum -y install libffi-devel
tox_env_map() {
case $1 in
- *"cp27"*) echo 'py27';;
- *"cp35"*) echo 'py35';;
- *"cp36"*) echo 'py36';;
*"cp37"*) echo 'py37';;
*"cp38"*) echo 'py38';;
*"cp39"*) echo 'py39';;
@@ -43,10 +40,7 @@ tox_env_map() {
# Compile wheels
for PYBIN in /opt/python/*/bin; do
if \
- [[ "${PYBIN}" == *"cp27"* ]] || \
- [[ "${PYBIN}" == *"cp35"* ]] || \
[[ "${PYBIN}" == *"cp311"* ]] || \
- [[ "${PYBIN}" == *"cp36"* ]] || \
[[ "${PYBIN}" == *"cp37"* ]] || \
[[ "${PYBIN}" == *"cp38"* ]] || \
[[ "${PYBIN}" == *"cp39"* ]] || \
diff --git a/.meta.toml b/.meta.toml
index e6bc2a1..28cb8fe 100644
--- a/.meta.toml
+++ b/.meta.toml
@@ -2,14 +2,13 @@
# https://github.com/zopefoundation/meta/tree/master/config/c-code
[meta]
template = "c-code"
-commit-id = "342271a70d886e753e5cc629e8a81b3cfab692ac"
+commit-id = "46a3f3bc"
[python]
with-appveyor = true
with-windows = false
with-pypy = true
with-future-python = false
-with-legacy-python = true
with-docs = true
with-sphinx-doctests = true
with-macos = false
@@ -17,7 +16,7 @@ with-macos = false
[tox]
use-flake8 = true
additional-envlist = [
- "py27-watch, py37-watch",
+ "py37-watch, py311-watch",
]
testenv-setenv = [
"ZOPE_INTERFACE_STRICT_IRO=1",
@@ -48,8 +47,8 @@ additional-config = [
[github-actions]
additional-config = [
- "- [\"2.7\", \"py27-watch\"]",
"- [\"3.7\", \"py37-watch\"]",
+ "- [\"3.11\", \"py311-watch\"]",
]
additional-build-dependencies = [
"zope.proxy",
diff --git a/CHANGES.rst b/CHANGES.rst
index 66223e8..0e86f75 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,10 +2,10 @@
Changes
=========
-5.9 (unreleased)
+6.0 (unreleased)
================
-- Nothing changed yet.
+- Drop support for Python 2.7, 3.5, 3.6.
5.8 (2022-11-30)
diff --git a/appveyor.yml b/appveyor.yml
index f798e96..6344764 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -9,9 +9,6 @@ environment:
ZOPE_INTERFACE_STRICT_IRO: 1
matrix:
- - python: 27-x64
- - python: 35-x64
- - python: 36-x64
- python: 37-x64
- python: 38-x64
- python: 39-x64
diff --git a/setup.cfg b/setup.cfg
index 5d7fd75..916fb60 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -1,7 +1,7 @@
# Generated from:
# https://github.com/zopefoundation/meta/tree/master/config/c-code
[bdist_wheel]
-universal = 1
+universal = 0
[zest.releaser]
create-wheel = no
diff --git a/setup.py b/setup.py
index b1d224f..4f42035 100644
--- a/setup.py
+++ b/setup.py
@@ -69,7 +69,7 @@ def read(*rnames):
# Sniff the location of the headers in the package distribution
-class ModuleHeaderDir(object):
+class ModuleHeaderDir:
def __init__(self, require_spec, where='../..'):
# By default, assume top-level pkg has the same name as the dist.
@@ -129,7 +129,7 @@ TESTS_REQUIRE = [
setup(name='zope.security',
- version='5.9.dev0',
+ version='6.0.dev0',
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
description='Zope Security Framework',
@@ -145,11 +145,7 @@ setup(name='zope.security',
'Intended Audience :: Developers',
'License :: OSI Approved :: Zope Public License',
'Programming Language :: Python',
- 'Programming Language :: Python :: 2',
- 'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
- 'Programming Language :: Python :: 3.5',
- 'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
@@ -164,10 +160,10 @@ setup(name='zope.security',
],
url='http://github.com/zopefoundation/zope.security',
project_urls={
- 'Documentation': 'https://zopesecurity.readthedocs.io',
- 'Issue Tracker': ('https://github.com/zopefoundation'
- '/zope.security/issues'),
- 'Sources': 'https://github.com/zopefoundation/zope.security',
+ 'Documentation': 'https://zopesecurity.readthedocs.io',
+ 'Issue Tracker': ('https://github.com/zopefoundation'
+ '/zope.security/issues'),
+ 'Sources': 'https://github.com/zopefoundation/zope.security',
},
license='ZPL 2.1',
packages=find_packages('src'),
@@ -178,7 +174,7 @@ setup(name='zope.security',
'build_ext': optional_build_ext,
},
ext_modules=ext_modules,
- python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*',
+ python_requires='>=3.7',
install_requires=[
'setuptools',
'zope.component',
diff --git a/src/zope/security/_compat.py b/src/zope/security/_compat.py
index 99f0d75..0d95d9f 100644
--- a/src/zope/security/_compat.py
+++ b/src/zope/security/_compat.py
@@ -15,32 +15,14 @@
"""
import os
import platform
-import sys
-import types
py_impl = getattr(platform, 'python_implementation', lambda: None)
PYPY = py_impl() == 'PyPy'
PURE_PYTHON = os.environ.get('PURE_PYTHON', PYPY)
-if sys.version_info[0] < 3: # pragma: no cover
- CLASS_TYPES = (type, types.ClassType)
- _BUILTINS = '__builtin__'
-
- PYTHON3 = False
- PYTHON2 = True
-
-else: # pragma: no cover
-
- CLASS_TYPES = (type,)
- _BUILTINS = 'builtins'
-
- PYTHON3 = True
- PYTHON2 = False
-
-
-class implementer_if_needed(object):
+class implementer_if_needed:
# Helper to make sure we don't redundantly implement interfaces
# already inherited. Doing so tends to produce problems with the
# C3 order. Even though here we could easily statically determine
diff --git a/src/zope/security/_definitions.py b/src/zope/security/_definitions.py
index f1d0176..efbfc7a 100644
--- a/src/zope/security/_definitions.py
+++ b/src/zope/security/_definitions.py
@@ -24,10 +24,10 @@ thread_local = threading.local()
@zope.interface.implementer(interfaces.ISystemPrincipal)
-class SystemUser(object):
- id = u'zope.security.management.system_user'
- title = u'System'
- description = u''
+class SystemUser:
+ id = 'zope.security.management.system_user'
+ title = 'System'
+ description = ''
system_user = SystemUser()
diff --git a/src/zope/security/_proxy.c b/src/zope/security/_proxy.c
index 04321d7..ce42c54 100644
--- a/src/zope/security/_proxy.c
+++ b/src/zope/security/_proxy.c
@@ -19,53 +19,29 @@ Security Proxy Implementation
static PyObject *__class__str = 0, *__name__str = 0, *__module__str = 0;
-// Compatibility with Python 2
-#if PY_MAJOR_VERSION < 3
- #define IS_STRING PyString_Check
-
- #define MAKE_STRING(name) PyString_AS_STRING(name)
-
- #define FROM_STRING PyString_FromString
-
- #define FROM_STRING_FORMAT PyString_FromFormat
+#define PyInt_FromLong PyLong_FromLong
- #define INTERN PyString_InternFromString
+#define IS_STRING PyUnicode_Check
- #define MOD_ERROR_VAL
+#define MAKE_STRING(name) PyBytes_AS_STRING( \
+ PyUnicode_AsUTF8String(name))
- #define MOD_SUCCESS_VAL(val)
-
- #define MOD_INIT(name) void init##name(void)
-
- #define MOD_DEF(ob, name, doc, methods) \
- ob = Py_InitModule3(name, methods, doc);
-
-#else
+#define FROM_STRING PyUnicode_FromString
- #define PyInt_FromLong PyLong_FromLong
+#define FROM_STRING_FORMAT PyUnicode_FromFormat
- #define IS_STRING PyUnicode_Check
+#define INTERN PyUnicode_InternFromString
- #define MAKE_STRING(name) PyBytes_AS_STRING( \
- PyUnicode_AsUTF8String(name))
+#define MOD_ERROR_VAL NULL
- #define FROM_STRING PyUnicode_FromString
+#define MOD_SUCCESS_VAL(val) val
- #define FROM_STRING_FORMAT PyUnicode_FromFormat
+#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
- #define INTERN PyUnicode_InternFromString
-
- #define MOD_ERROR_VAL NULL
-
- #define MOD_SUCCESS_VAL(val) val
-
- #define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
-
- #define MOD_DEF(ob, name, doc, methods) \
- static struct PyModuleDef moduledef = { \
- PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
- ob = PyModule_Create(&moduledef);
-#endif
+#define MOD_DEF(ob, name, doc, methods) \
+ static struct PyModuleDef moduledef = { \
+ PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
+ ob = PyModule_Create(&moduledef);
#define DECLARE_STRING(N) static PyObject *str_##N
@@ -931,16 +907,9 @@ static PyTypeObject SecurityProxyType = {
(getattrofunc)proxy_getattro, /* tp_getattro */
(setattrofunc)proxy_setattro, /* tp_setattro */
0, /* tp_as_buffer */
-#if PY_MAJOR_VERSION < 3
Py_TPFLAGS_DEFAULT |
- Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_HAVE_GC, /* tp_flags */
-#else // Py_TPFLAGS_CHECKTYPES is always true in Python 3 and removed.
- Py_TPFLAGS_DEFAULT |
- Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
-#endif
+ Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
proxy_doc, /* tp_doc */
(traverseproc)proxy_traverse, /* tp_traverse */
0, /* tp_clear */
diff --git a/src/zope/security/_zope_security_checker.c b/src/zope/security/_zope_security_checker.c
index 63b0548..23d7fb9 100644
--- a/src/zope/security/_zope_security_checker.c
+++ b/src/zope/security/_zope_security_checker.c
@@ -17,55 +17,32 @@ static PyObject *_checkers, *_defaultChecker, *_available_by_default, *NoProxy;
static PyObject *Proxy, *thread_local, *CheckerPublic;
static PyObject *ForbiddenAttribute, *Unauthorized;
-// Compatibility with Python 2
-#if PY_MAJOR_VERSION < 3
- #define IS_STRING PyString_Check
- #define MAKE_STRING(name) PyString_AS_STRING(name)
+#define PyInt_FromLong PyLong_FromLong
- #define FROM_STRING PyString_FromString
+#define IS_STRING PyUnicode_Check
- #define FROM_STRING_FORMAT PyString_FromFormat
+#define MAKE_STRING(name) PyBytes_AS_STRING( \
+ PyUnicode_AsUTF8String(name))
- #define INTERN PyString_InternFromString
+#define FROM_STRING PyUnicode_FromString
- #define MOD_ERROR_VAL
+#define FROM_STRING_FORMAT PyUnicode_FromFormat
- #define MOD_SUCCESS_VAL(val)
+#define INTERN PyUnicode_InternFromString
- #define MOD_INIT(name) void init##name(void)
+#define MOD_ERROR_VAL NULL
- #define MOD_DEF(ob, name, doc, methods) \
- ob = Py_InitModule3(name, methods, doc);
+#define MOD_SUCCESS_VAL(val) val
-#else
+#define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
- #define PyInt_FromLong PyLong_FromLong
+#define MOD_DEF(ob, name, doc, methods) \
+ static struct PyModuleDef moduledef = { \
+ PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
+ ob = PyModule_Create(&moduledef);
- #define IS_STRING PyUnicode_Check
-
- #define MAKE_STRING(name) PyBytes_AS_STRING( \
- PyUnicode_AsUTF8String(name))
-
- #define FROM_STRING PyUnicode_FromString
-
- #define FROM_STRING_FORMAT PyUnicode_FromFormat
-
- #define INTERN PyUnicode_InternFromString
-
- #define MOD_ERROR_VAL NULL
-
- #define MOD_SUCCESS_VAL(val) val
-
- #define MOD_INIT(name) PyMODINIT_FUNC PyInit_##name(void)
-
- #define MOD_DEF(ob, name, doc, methods) \
- static struct PyModuleDef moduledef = { \
- PyModuleDef_HEAD_INIT, name, doc, -1, methods, }; \
- ob = PyModule_Create(&moduledef);
-
- #define statichere static
-#endif
+#define statichere static
#define DECLARE_STRING(N) static PyObject *str_##N
diff --git a/src/zope/security/adapter.py b/src/zope/security/adapter.py
index 0f5bc84..1905710 100644
--- a/src/zope/security/adapter.py
+++ b/src/zope/security/adapter.py
@@ -45,7 +45,7 @@ def assertLocation(adapter, parent):
return adapter
-class LocatingTrustedAdapterFactory(object):
+class LocatingTrustedAdapterFactory:
"""
Adapt an adapter factory to provide trusted and (locatable) adapters.
@@ -109,7 +109,7 @@ class TrustedAdapterFactory(LocatingTrustedAdapterFactory):
return self._customizeUnprotected(adapter, context)
-class LocatingUntrustedAdapterFactory(object):
+class LocatingUntrustedAdapterFactory:
"""
Adapt an adapter factory to provide locatable untrusted adapters
diff --git a/src/zope/security/checker.py b/src/zope/security/checker.py
index ae8ab5a..db7a167 100644
--- a/src/zope/security/checker.py
+++ b/src/zope/security/checker.py
@@ -75,9 +75,7 @@ from zope.interface import implementer
from zope.interface.interfaces import IDeclaration
from zope.interface.interfaces import IInterface
-from zope.security._compat import CLASS_TYPES
from zope.security._compat import PURE_PYTHON
-from zope.security._compat import PYTHON2
from zope.security._compat import implementer_if_needed
from zope.security._definitions import thread_local
from zope.security.interfaces import ForbiddenAttribute
@@ -109,7 +107,7 @@ def ProxyFactory(object, checker=None):
The proxy checker is looked up if not provided.
"""
- if type(object) is Proxy:
+ if isinstance(object, Proxy):
if checker is None or checker is getChecker(object):
return object
else:
@@ -197,7 +195,7 @@ def canAccess(obj, name):
@implementer(INameBasedChecker)
-class CheckerPy(object):
+class CheckerPy:
"""
The Python reference implementation of
:class:`zope.security.interfaces.INameBasedChecker`.
@@ -280,7 +278,7 @@ class CheckerPy(object):
def proxy(self, value):
'See IChecker'
- if type(value) is Proxy:
+ if isinstance(value, Proxy):
return value
checker = getattr(value, '__Security_checker__', None)
if checker is None:
@@ -295,7 +293,7 @@ Checker = CheckerPy # in case no C optimizations
# Helper class for __traceback_supplement__
-class TracebackSupplement(object):
+class TracebackSupplement:
def __init__(self, obj):
self.obj = obj
@@ -305,7 +303,7 @@ class TracebackSupplement(object):
try:
cls = self.obj.__class__
if hasattr(cls, "__module__"):
- s = "%s.%s" % (cls.__module__, cls.__name__)
+ s = "{}.{}".format(cls.__module__, cls.__name__)
else: # pragma: no cover XXX
s = str(cls.__name__)
result.append(" - class: " + s)
@@ -314,7 +312,7 @@ class TracebackSupplement(object):
try:
cls = type(self.obj)
if hasattr(cls, "__module__"):
- s = "%s.%s" % (cls.__module__, cls.__name__)
+ s = "{}.{}".format(cls.__module__, cls.__name__)
else: # pragma: no cover XXX
s = str(cls.__name__)
result.append(" - type: " + s)
@@ -323,7 +321,7 @@ class TracebackSupplement(object):
return "\n".join(result)
-class Global(object):
+class Global:
"""A global object that behaves like a string.
We want this to behave as a global, meaning it's pickled
@@ -342,8 +340,8 @@ class Global(object):
return self.__name__
def __repr__(self):
- return "%s(%s,%s)" % (self.__class__.__name__,
- self.__name__, self.__module__)
+ return "{}({},{})".format(self.__class__.__name__,
+ self.__name__, self.__module__)
CheckerPublic = Global('CheckerPublic')
@@ -412,7 +410,7 @@ def MultiChecker(specs):
data = {}
for spec in specs:
- if type(spec) is tuple:
+ if isinstance(spec, tuple):
names, permission_id = spec
if IInterface.providedBy(names):
names = names.names(all=True)
@@ -470,7 +468,7 @@ def getCheckerForInstancesOf(class_):
return _checkers.get(class_)
-DEFINABLE_TYPES = CLASS_TYPES + (types.ModuleType,)
+DEFINABLE_TYPES = (type, types.ModuleType)
def defineChecker(type_, checker):
@@ -589,7 +587,7 @@ class CombinedChecker(Checker):
raise unauthorized_exception
-class CheckerLoggingMixin(object):
+class CheckerLoggingMixin:
"""
Debugging mixin for checkers.
@@ -611,26 +609,26 @@ class CheckerLoggingMixin(object):
def check(self, object, name):
try:
- super(CheckerLoggingMixin, self).check(object, name)
+ super().check(object, name)
if self.verbosity > 1:
if name in _available_by_default:
self._log('[CHK] + Always available: %s on %r'
% (name, object), 2)
else:
self._log(
- '[CHK] + Granted: %s on %r' % (name, object), 2)
+ '[CHK] + Granted: {} on {!r}'.format(name, object), 2)
except Unauthorized:
self._log(
- '[CHK] - Unauthorized: %s on %r' % (name, object))
+ '[CHK] - Unauthorized: {} on {!r}'.format(name, object))
raise
except ForbiddenAttribute:
self._log(
- '[CHK] - Forbidden: %s on %r' % (name, object))
+ '[CHK] - Forbidden: {} on {!r}'.format(name, object))
raise
def check_getattr(self, object, name):
try:
- super(CheckerLoggingMixin, self).check(object, name)
+ super().check(object, name)
if self.verbosity > 1:
if name in _available_by_default:
self._log(
@@ -642,28 +640,31 @@ class CheckerLoggingMixin(object):
% (name, object), 2)
except Unauthorized:
self._log(
- '[CHK] - Unauthorized getattr: %s on %r' % (name, object))
+ '[CHK] - Unauthorized getattr: {} on {!r}'.format(name, object)
+ )
raise
except ForbiddenAttribute:
self._log(
- '[CHK] - Forbidden getattr: %s on %r' % (name, object))
+ '[CHK] - Forbidden getattr: {} on {!r}'.format(name, object))
raise
__setitem__ = check_getattr
def check_setattr(self, object, name):
try:
- super(CheckerLoggingMixin, self).check_setattr(object, name)
+ super().check_setattr(object, name)
if self.verbosity > 1:
self._log(
- '[CHK] + Granted setattr: %s on %r' % (name, object), 2)
+ '[CHK] + Granted setattr: {} on {!r}'.format(
+ name, object), 2)
except Unauthorized:
self._log(
- '[CHK] - Unauthorized setattr: %s on %r' % (name, object))
+ '[CHK] - Unauthorized setattr: {} on {!r}'.format(
+ name, object))
raise
except ForbiddenAttribute:
self._log(
- '[CHK] - Forbidden setattr: %s on %r' % (name, object))
+ '[CHK] - Forbidden setattr: {} on {!r}'.format(name, object))
raise
@@ -784,14 +785,10 @@ _basic_types = {
datetime.date: NoProxy,
datetime.time: NoProxy,
datetime.tzinfo: NoProxy,
+ type({}.values()): NoProxy,
+ type({}.keys()): NoProxy,
+ type({}.items()): NoProxy,
}
-if PYTHON2: # pragma: no cover
- _basic_types[long] = NoProxy # noqa: F821 undefined name 'long'
- _basic_types[unicode] = NoProxy # noqa: F821 undefined name 'unicode'
-else:
- _basic_types[type({}.values())] = NoProxy
- _basic_types[type({}.keys())] = NoProxy
- _basic_types[type({}.items())] = NoProxy
try:
import pytz
@@ -819,12 +816,8 @@ BasicTypes_examples = {
Message: Message('message', domain='hello')
}
-if PYTHON2: # pragma: no cover
- BasicTypes_examples[unicode] = u'uabc' # noqa: F821 undefined name
- BasicTypes_examples[long] = long(65536) # noqa: F821 undefined name
-
-class _Sequence(object):
+class _Sequence:
def __len__(self):
raise NotImplementedError()
@@ -891,8 +884,8 @@ _default_checkers = {
type(().__repr__): _callableChecker,
type: _typeChecker,
types.ModuleType: lambda module: _checkers.get(module, _namedChecker),
- type(iter([])): _iteratorChecker, # Same types in Python 2.2.1,
- type(iter(())): _iteratorChecker, # different in Python 2.3.
+ type(iter([])): _iteratorChecker,
+ type(iter(())): _iteratorChecker,
type(iter({})): _iteratorChecker,
type(iter(set())): _iteratorChecker,
type(iter(_Sequence())): _iteratorChecker,
@@ -903,8 +896,7 @@ _default_checkers = {
_implied=CheckerPublic,
subscribe=CheckerPublic,
# To iterate, Python calls __len__ as a hint.
- # Python 2 ignores AttributeErrors, but Python 3
- # lets them pass.
+ # AttributeErrors are passed.
__len__=CheckerPublic,
),
zope.interface.interface.Method: InterfaceChecker(
@@ -915,13 +907,6 @@ _default_checkers = {
zope.interface.declarations.Declaration: _Declaration_checker,
abc.ABCMeta: _typeChecker,
}
-if PYTHON2: # pragma: no cover
- _default_checkers[types.ClassType] = _typeChecker
- _default_checkers[types.InstanceType] = _instanceChecker
- # slot description
- _default_checkers[type({}.iteritems())] = _iteratorChecker
- _default_checkers[type({}.iterkeys())] = _iteratorChecker
- _default_checkers[type({}.itervalues())] = _iteratorChecker
def _fixup_dictlike(dict_type):
@@ -940,10 +925,6 @@ def _fixup_dictlike(dict_type):
def _fixup_odict():
- # OrderedDicts have three different implementations: Python 2 (pure
- # python, returns generators and lists), Python <=3.4 (pure Python,
- # uses view classes) and CPython 3.5+ (implemented in C). These should
- # all be iterable.
from collections import OrderedDict
# The `_fixup_dictlike` is detected as undefined because it is deleted
@@ -1008,12 +989,12 @@ def _fixup_zope_interface():
pass
@implementer(I1)
- class Obj(object):
+ class Obj:
pass
o = Obj()
- # This will be athe zope.interface.implementedBy from the class
+ # This will be the zope.interface.implementedBy from the class
# a zope.interface.declarations.Implements
_default_checkers[type(providedBy(o))] = NoProxy
@@ -1028,7 +1009,7 @@ del _fixup_zope_interface
def _fixup_itertools():
# itertools.groupby is a built-in custom iterator type introduced
- # in python2.4. It should have the same checker as other built-in
+ # in Python 2.4. It should have the same checker as other built-in
# iterators.
# Also, itertools._grouper also needs to be exposed as an
@@ -1053,40 +1034,24 @@ def _fixup_itertools():
return x
iterable = (1, 2, 3)
pred_iterable = (pred, iterable)
- missing_in_py3 = {'ifilter', 'ifilterfalse', 'imap',
- 'izip', 'izip_longest'}
- missing_in_py2 = {'zip_longest', 'accumulate', 'compress',
- 'combinations', 'combinations_with_replacement'}
- missing = missing_in_py3 if sys.version_info[0] >= 3 else missing_in_py2
for func, args in (
('count', ()),
('cycle', ((),)),
('dropwhile', pred_iterable),
- ('ifilter', pred_iterable),
- ('ifilterfalse', pred_iterable),
- ('imap', pred_iterable),
('islice', (iterable, 2)),
- ('izip', (iterable,)),
- ('izip_longest', (iterable,)),
('permutations', (iterable,)),
('product', (iterable,)),
('repeat', (1, 2)),
('starmap', pred_iterable),
('takewhile', pred_iterable),
('tee', (iterable,)),
- # Python 3 additions
('zip_longest', (iterable,)),
('accumulate', (iterable,)),
('compress', (iterable, ())),
('combinations', (iterable, 1)),
('combinations_with_replacement', (iterable, 1)),
):
- try:
- func = getattr(itertools, func)
- except AttributeError:
- assert func in missing, "Expected %s but not found" % (func,)
- # The following line is hit on PY2, but it doesn't always show:
- continue # pragma: no cover
+ func = getattr(itertools, func)
result = func(*args)
if func == itertools.tee:
diff --git a/src/zope/security/decorator.py b/src/zope/security/decorator.py
index 18751d8..5ad9649 100644
--- a/src/zope/security/decorator.py
+++ b/src/zope/security/decorator.py
@@ -27,7 +27,7 @@ from zope.security.proxy import Proxy
from zope.security.proxy import getChecker
-class DecoratedSecurityCheckerDescriptor(object):
+class DecoratedSecurityCheckerDescriptor:
"""Descriptor for a Decorator that provides a decorated security checker.
"""
@@ -36,7 +36,7 @@ class DecoratedSecurityCheckerDescriptor(object):
return self
else:
proxied_object = getProxiedObject(inst)
- if type(proxied_object) is Proxy:
+ if isinstance(proxied_object, Proxy):
checker = getChecker(proxied_object)
else:
checker = getattr(proxied_object, '__Security_checker__', None)
diff --git a/src/zope/security/examples/sandbox.py b/src/zope/security/examples/sandbox.py
index 70dd5a8..b10d7b6 100644
--- a/src/zope/security/examples/sandbox.py
+++ b/src/zope/security/examples/sandbox.py
@@ -70,7 +70,7 @@ class SandboxError(Exception):
pass
-class Identity(object):
+class Identity:
"""Mixin for pretty printing and identity method"""
def __init__(self, id, *args, **kw):
@@ -80,7 +80,7 @@ class Identity(object):
return self.id
def __str__(self):
- return "<%s> %s" % (str(self.__class__.__name__), str(self.id))
+ return "<{}> {}".format(str(self.__class__.__name__), str(self.id))
__repr__ = __str__
@@ -165,13 +165,13 @@ class Sandbox(Identity):
destination.addAgent(agent)
del self._agents[agent.getId()]
else:
- raise SandboxError("couldn't transport agent %s to %s" % (
+ raise SandboxError("couldn't transport agent {} to {}".format(
agent, destination)
)
@implementer(IService)
-class Service(object):
+class Service:
def getId(self):
return self.__class__.__name__
@@ -231,7 +231,7 @@ def action_find_time(agent, home):
return time_service.getTime()
-class TimeGenerator(object):
+class TimeGenerator:
"""Represents the passage of time in the agent simulation.
each turn represents some discrete unit of time, during
@@ -283,7 +283,7 @@ class TimeGenerator(object):
def WanderLust(agent):
""" is agent ready to move """
- if int(random.random()*100) <= 30:
+ if int(random.random() * 100) <= 30:
return 1
diff --git a/src/zope/security/examples/sandbox_security.py b/src/zope/security/examples/sandbox_security.py
index d102c5f..3618f06 100644
--- a/src/zope/security/examples/sandbox_security.py
+++ b/src/zope/security/examples/sandbox_security.py
@@ -52,7 +52,7 @@ ALL = 'All'
def NoSetAttr(name): return NotAllowed
-class SimulationSecurityDatabase(object):
+class SimulationSecurityDatabase:
"""Security Database
In the database, locations are mapped to authentication tokens to
@@ -106,7 +106,7 @@ class SimulationSecurityPolicy(simplepolicies.ParanoidSecurityPolicy):
@implementer(IParticipation)
-class AgentParticipation(object):
+class AgentParticipation:
"""Agent Participation during the Simulation.
A very simple participation that is specific to the simulations.
diff --git a/src/zope/security/metaconfigure.py b/src/zope/security/metaconfigure.py
index b09c725..c4d3b90 100644
--- a/src/zope/security/metaconfigure.py
+++ b/src/zope/security/metaconfigure.py
@@ -46,7 +46,7 @@ class ProtectionDeclarationException(Exception):
pass
-class ClassDirective(object):
+class ClassDirective:
def __init__(self, _context, class_):
self.__id = dottedName(class_) # this would barf on a module, anyway
diff --git a/src/zope/security/metadirectives.py b/src/zope/security/metadirectives.py
index c7e82e2..34cee99 100644
--- a/src/zope/security/metadirectives.py
+++ b/src/zope/security/metadirectives.py
@@ -156,8 +156,8 @@ class IModule(Interface):
"""Group security declarations about a module"""
module = GlobalObject(
- title=u"Module",
- description=u"Pointer to the module object.",
+ title="Module",
+ description="Pointer to the module object.",
required=True)
@@ -170,16 +170,16 @@ class IAllow(Interface):
"""
attributes = Tokens(
- title=u"Attributes",
- description=u"The attributes to provide access to.",
+ title="Attributes",
+ description="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 "
- u"will be provided to all of the names defined by the "
- u"interface(s). Multiple interfaces can be supplied."),
+ title="Interface",
+ description=("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(),
required=False)
@@ -193,11 +193,11 @@ class IRequire(Interface):
"""
attributes = Tokens(
- title=u"Attributes",
- description=u"The attributes to require permission for.",
+ title="Attributes",
+ description="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="Permission ID",
+ description="The ID of the permission to require.")
diff --git a/src/zope/security/permission.py b/src/zope/security/permission.py
index 8fc2837..9103477 100644
--- a/src/zope/security/permission.py
+++ b/src/zope/security/permission.py
@@ -31,12 +31,12 @@ from zope.security.interfaces import IPermission
@implementer(IPermission)
-class Permission(object):
+class Permission:
"""
Default implementation of :class:`zope.security.interfaces.IPermission`.
"""
- def __init__(self, id, title=u"", description=u""):
+ def __init__(self, id, title="", description=""):
self.id = id
self.title = title
self.description = description
@@ -103,7 +103,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, 'Public'))
return SimpleVocabulary(terms)
diff --git a/src/zope/security/proxy.py b/src/zope/security/proxy.py
index 52a7189..c8db35a 100644
--- a/src/zope/security/proxy.py
+++ b/src/zope/security/proxy.py
@@ -21,7 +21,6 @@ import sys
from zope.proxy import PyProxyBase
-from zope.security._compat import _BUILTINS
from zope.security._compat import PURE_PYTHON
@@ -81,7 +80,7 @@ class ProxyPy(PyProxyBase):
__slots__ = ('_wrapped', '_checker')
def __new__(cls, value, checker):
- inst = super(ProxyPy, cls).__new__(cls)
+ inst = super().__new__(cls)
inst._wrapped = value
inst._checker = checker
return inst
@@ -98,10 +97,10 @@ class ProxyPy(PyProxyBase):
# Only allow _wrapped and _checker to be accessed from inside.
if sys._getframe(1).f_locals.get('self') is not self:
raise AttributeError(name)
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
if name == '_wrapped':
return wrapped
- checker = super(ProxyPy, self).__getattribute__('_checker')
+ checker = super().__getattribute__('_checker')
if name == '_checker':
return checker
if name not in ('__cmp__', '__hash__', '__bool__', '__nonzero__',
@@ -131,7 +130,7 @@ class ProxyPy(PyProxyBase):
# this one attribute.
val = getattr(wrapped, name)
else:
- val = super(ProxyPy, self).__getattribute__(name)
+ val = super().__getattribute__(name)
return checker.proxy(val)
def __getattr__(self, name):
@@ -154,94 +153,71 @@ class ProxyPy(PyProxyBase):
# but we're consistent. We would provide a better error
# message or even subclass of AttributeError, but that's liable to
# break (doc)tests.
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- checker = super(ProxyPy, self).__getattribute__('_checker')
+ wrapped = super().__getattribute__('_wrapped')
+ checker = super().__getattribute__('_checker')
checker.check_getattr(wrapped, name)
raise AttributeError(name)
def __setattr__(self, name, value):
if name in ('_wrapped', '_checker'):
- return super(ProxyPy, self).__setattr__(name, value)
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- checker = super(ProxyPy, self).__getattribute__('_checker')
+ return super().__setattr__(name, value)
+ wrapped = super().__getattribute__('_wrapped')
+ checker = super().__getattribute__('_checker')
checker.check_setattr(wrapped, name)
setattr(wrapped, name, value)
def __delattr__(self, name):
if name in ('_wrapped', '_checker'):
raise AttributeError()
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- checker = super(ProxyPy, self).__getattribute__('_checker')
+ wrapped = super().__getattribute__('_wrapped')
+ checker = super().__getattribute__('_checker')
checker.check_setattr(wrapped, name)
delattr(wrapped, name)
- @_check_name
- def __getslice__(self, start, end): # pragma: no cover PY2
- wrapped = object.__getattribute__(self, '_wrapped')
- try:
- getslice = wrapped.__getslice__
- except AttributeError:
- return wrapped.__getitem__(slice(start, end))
- return getslice(start, end)
-
- @_check_name
- def __setslice__(self, start, end, value): # pragma: no cover PY2
- wrapped = object.__getattribute__(self, '_wrapped')
- try:
- setslice = wrapped.__setslice__
- except AttributeError:
- return wrapped.__setitem__(slice(start, end), value)
- return setslice(start, end, value)
-
- def __cmp__(self, other): # pragma: no cover PY2
- # no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- return cmp(wrapped, other) # noqa: F821 undefined name 'cmp'
-
def __lt__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped < other
def __le__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped <= other
def __eq__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped == other
def __ne__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped != other
def __ge__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped >= other
def __gt__(self, other):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return wrapped > other
def __hash__(self):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return hash(wrapped)
def __nonzero__(self):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
return bool(wrapped)
__bool__ = __nonzero__
def __length_hint__(self):
# no check
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
+ wrapped = super().__getattribute__('_wrapped')
try:
hint = wrapped.__length_hint__
except AttributeError:
@@ -249,13 +225,6 @@ class ProxyPy(PyProxyBase):
else:
return hint()
- def __coerce__(self, other): # pragma: no cover PY2
- # For some reason _check_name does not work for coerce()
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- checker = super(ProxyPy, self).__getattribute__('_checker')
- checker.check(wrapped, '__coerce__')
- return super(ProxyPy, self).__coerce__(other)
-
def __str__(self):
try:
return _check_name(PyProxyBase.__str__)(self)
@@ -266,8 +235,8 @@ class ProxyPy(PyProxyBase):
raise
except: # noqa: E722 do not use bare 'except'
# The C implementation catches all exceptions.
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- return '<security proxied %s.%s instance at %s>' % (
+ wrapped = super().__getattribute__('_wrapped')
+ return '<security proxied {}.{} instance at {}>'.format(
wrapped.__class__.__module__, wrapped.__class__.__name__,
_fmt_address(wrapped))
@@ -280,8 +249,8 @@ class ProxyPy(PyProxyBase):
except TypeError:
raise
except: # noqa: E722 do not use bare 'except'
- wrapped = super(ProxyPy, self).__getattribute__('_wrapped')
- return '<security proxied %s.%s instance at %s>' % (
+ wrapped = super().__getattribute__('_wrapped')
+ return '<security proxied {}.{} instance at {}>'.format(
wrapped.__class__.__module__, wrapped.__class__.__name__,
_fmt_address(wrapped))
@@ -292,15 +261,15 @@ for name in ['__call__',
# '__unicode__', # Unchecked in C proxy
'__reduce__',
'__reduce_ex__',
- # '__lt__', # Unchecked in C proxy (rich coparison)
- # '__le__', # Unchecked in C proxy (rich coparison)
- # '__eq__', # Unchecked in C proxy (rich coparison)
- # '__ne__', # Unchecked in C proxy (rich coparison)
- # '__ge__', # Unchecked in C proxy (rich coparison)
- # '__gt__', # Unchecked in C proxy (rich coparison)
- # '__nonzero__', # Unchecked in C proxy (rich coparison)
- # '__bool__', # Unchecked in C proxy (rich coparison)
- # '__hash__', # Unchecked in C proxy (rich coparison)
+ # '__lt__', # Unchecked in C proxy (rich comparison)
+ # '__le__', # Unchecked in C proxy (rich comparison)
+ # '__eq__', # Unchecked in C proxy (rich comparison)
+ # '__ne__', # Unchecked in C proxy (rich comparison)
+ # '__ge__', # Unchecked in C proxy (rich comparison)
+ # '__gt__', # Unchecked in C proxy (rich comparison)
+ # '__nonzero__', # Unchecked in C proxy (rich comparison)
+ # '__bool__', # Unchecked in C proxy (rich comparison)
+ # '__hash__', # Unchecked in C proxy (rich comparison)
# '__cmp__', # Unchecked in C proxy
'__getitem__',
'__setitem__',
@@ -380,7 +349,7 @@ def getCheckerPy(proxy):
return super(ProxyPy, proxy).__getattribute__('_checker')
-_builtin_isinstance = sys.modules[_BUILTINS].isinstance
+_builtin_isinstance = sys.modules['builtins'].isinstance
def getObjectPy(proxy):
diff --git a/src/zope/security/simplepolicies.py b/src/zope/security/simplepolicies.py
index feaa104..7035e07 100644
--- a/src/zope/security/simplepolicies.py
+++ b/src/zope/security/simplepolicies.py
@@ -29,7 +29,7 @@ from zope.security.interfaces import ISecurityPolicy
@zope.interface.implementer(IInteraction)
@zope.interface.provider(ISecurityPolicy)
-class ParanoidSecurityPolicy(object):
+class ParanoidSecurityPolicy:
"""
Prohibit all access by any non-system principal, unless the item
is :data:`public <zope.security.checker.CheckerPublic>`.
diff --git a/src/zope/security/testing.py b/src/zope/security/testing.py
index be551ce..f725912 100644
--- a/src/zope/security/testing.py
+++ b/src/zope/security/testing.py
@@ -17,30 +17,17 @@ Testing support code.
This module provides some helper/stub objects for setting up interactions.
"""
import contextlib
-import re
-
-from zope.testing import renormalizing
import zope.security.management
from zope import component
from zope import interface
from zope.security import interfaces
-from zope.security._compat import PYTHON2 as PY2
from zope.security.interfaces import PUBLIC_PERMISSION_NAME
from zope.security.permission import Permission
-_str_prefix = 'b' if PY2 else 'u'
-
-rules = [
- (re.compile(_str_prefix + "('.*?')"), r"\1"),
- (re.compile(_str_prefix + '(".*?")'), r"\1"),
-]
-output_checker = renormalizing.RENormalizing(rules)
-
-
@interface.implementer(interfaces.IPrincipal)
-class Principal(object):
+class Principal:
"""
A trivial implementation of :class:`zope.security.interfaces.IPrincipal`.
"""
@@ -55,7 +42,7 @@ class Principal(object):
@interface.implementer(interfaces.IParticipation)
-class Participation(object):
+class Participation:
"""
A trivial implementation of
:class:`zope.security.interfaces.IParticipation`.
diff --git a/src/zope/security/tests/__init__.py b/src/zope/security/tests/__init__.py
index e8db221..70e1049 100644
--- a/src/zope/security/tests/__init__.py
+++ b/src/zope/security/tests/__init__.py
@@ -1,7 +1,7 @@
import io
-class QuietWatchingChecker(object):
+class QuietWatchingChecker:
# zope.testrunner does not support setUp/tearDownModule,
# so we use a mixin class to make sure we don't flood stderr
# with pointless printing when testing watching checkers
diff --git a/src/zope/security/tests/exampleclass.py b/src/zope/security/tests/exampleclass.py
index 385dda0..9feab5a 100644
--- a/src/zope/security/tests/exampleclass.py
+++ b/src/zope/security/tests/exampleclass.py
@@ -16,7 +16,7 @@
from zope.interface import Interface
-class ExampleClass(object):
+class ExampleClass:
pass
diff --git a/src/zope/security/tests/test_adapter.py b/src/zope/security/tests/test_adapter.py
index 20a3975..6fd274c 100644
--- a/src/zope/security/tests/test_adapter.py
+++ b/src/zope/security/tests/test_adapter.py
@@ -30,7 +30,7 @@ class Test_assertLocation(unittest.TestCase):
return assertLocation(adapter, parent)
def test_w_non_ILocation(self):
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
parent = object()
@@ -41,7 +41,7 @@ class Test_assertLocation(unittest.TestCase):
def test_w_ILocation_no_parent(self):
@implementer(ILocation)
- class _Adapter(object):
+ class _Adapter:
__parent__ = None
adapter = _Adapter()
parent = object()
@@ -53,7 +53,7 @@ class Test_assertLocation(unittest.TestCase):
parent = object()
@implementer(ILocation)
- class _Adapter(object):
+ class _Adapter:
__parent__ = parent
adapter = _Adapter()
new_parent = object()
@@ -72,7 +72,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
return self._getTargetClass()(factory)
def _makeFactory(self):
- class _Factory(object):
+ class _Factory:
__name__ = 'testing'
__module__ = 'zope.security.tests.test_adapter'
_called_with = ()
@@ -93,7 +93,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
before = factory.__dict__.copy()
@@ -108,7 +108,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
extra = object()
@@ -126,7 +126,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
returned = ltaf(adapter)
@@ -139,7 +139,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
returned = ltaf(adapter)
@@ -152,7 +152,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
proxy = ProxyFactory(adapter)
@@ -174,7 +174,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
extra = object()
@@ -197,10 +197,10 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
- class _Extra(object):
+ class _Extra:
pass
adapter = _NotAdapter()
extra = _Extra()
@@ -226,7 +226,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _Adapter(object):
+ class _Adapter:
pass
adapter = _Adapter()
proxy = ProxyFactory(adapter)
@@ -254,7 +254,7 @@ class LocatingTrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _Adapter(object):
+ class _Adapter:
pass
adapter = _Adapter()
proxy = ProxyFactory(adapter)
@@ -282,7 +282,7 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
return self._getTargetClass()(factory)
def _makeFactory(self):
- class _Factory(object):
+ class _Factory:
__name__ = 'testing'
__module__ = 'zope.security.tests.test_adapter'
@@ -297,7 +297,7 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
proxy = ProxyFactory(adapter)
@@ -318,7 +318,7 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
extra = object()
@@ -340,10 +340,10 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
- class _Extra(object):
+ class _Extra:
pass
adapter = _NotAdapter()
extra = _Extra()
@@ -367,7 +367,7 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _Adapter(object):
+ class _Adapter:
pass
adapter = _Adapter()
proxy = ProxyFactory(adapter)
@@ -392,7 +392,7 @@ class TrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _Adapter(object):
+ class _Adapter:
pass
adapter = _Adapter()
proxy = ProxyFactory(adapter)
@@ -419,7 +419,7 @@ class LocatingUntrustedAdapterFactoryTests(unittest.TestCase):
return self._getTargetClass()(factory)
def _makeFactory(self):
- class _Factory(object):
+ class _Factory:
__name__ = 'testing'
__module__ = 'zope.security.tests.test_adapter'
_called_with = ()
@@ -440,7 +440,7 @@ class LocatingUntrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
before = factory.__dict__.copy()
@@ -457,7 +457,7 @@ class LocatingUntrustedAdapterFactoryTests(unittest.TestCase):
factory = self._makeFactory()
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
extra = object()
@@ -477,7 +477,7 @@ class LocatingUntrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
returned = ltaf(adapter)
@@ -490,7 +490,7 @@ class LocatingUntrustedAdapterFactoryTests(unittest.TestCase):
directlyProvides(factory, ILocation)
ltaf = self._makeOne(factory)
- class _NotAdapter(object):
+ class _NotAdapter:
pass
adapter = _NotAdapter()
returned = ltaf(adapter)
diff --git a/src/zope/security/tests/test_checker.py b/src/zope/security/tests/test_checker.py
index a102ad6..457ecd7 100644
--- a/src/zope/security/tests/test_checker.py
+++ b/src/zope/security/tests/test_checker.py
@@ -16,8 +16,6 @@
import unittest
from zope.security import checker as sec_checker
-from zope.security._compat import PYTHON2 as PY2
-from zope.security._compat import PYTHON3 as PY3
from zope.security.tests import QuietWatchingChecker
@@ -86,7 +84,7 @@ class Test_ProxyFactory(unittest.TestCase):
from zope.security.proxy import getObject
_check = object() # don't use a func, due to bound method
- class _WithChecker(object):
+ class _WithChecker:
__Security_checker__ = _check
obj = _WithChecker()
returned = self._callFUT(obj)
@@ -101,7 +99,7 @@ class Test_ProxyFactory(unittest.TestCase):
from zope.security.proxy import getChecker
from zope.security.proxy import getObject
- class _Obj(object):
+ class _Obj:
pass
obj = _Obj()
_checker = Checker({})
@@ -125,7 +123,7 @@ class Test_canWrite(unittest.TestCase):
return canWrite(obj, name)
def _makeChecker(self, ch_get=None, ch_set=None):
- class _Checker(object):
+ class _Checker:
def check_getattr(self, obj, name):
if ch_get is not None:
raise ch_get()
@@ -180,7 +178,7 @@ class Test_canAccess(unittest.TestCase):
return canAccess(obj, name)
def _makeChecker(self, ch_get=None):
- class _Checker(object):
+ class _Checker:
def check_getattr(self, obj, name):
if ch_get is not None:
raise ch_get()
@@ -284,7 +282,7 @@ class CheckerTestsBase(QuietWatchingChecker):
def test_check_setattr_w_interaction_allows(self):
from zope.security._definitions import thread_local
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return True
checker = self._makeOne(set_permissions={'name': 'view'})
@@ -299,7 +297,7 @@ class CheckerTestsBase(QuietWatchingChecker):
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
checker = self._makeOne(set_permissions={'name': 'view'})
@@ -332,7 +330,7 @@ class CheckerTestsBase(QuietWatchingChecker):
def test_check_non_public_w_interaction_allows(self):
from zope.security._definitions import thread_local
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return True
checker = self._makeOne({'name': 'view'})
@@ -347,7 +345,7 @@ class CheckerTestsBase(QuietWatchingChecker):
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
checker = self._makeOne({'name': 'view'})
@@ -383,7 +381,7 @@ class CheckerTestsBase(QuietWatchingChecker):
from zope.security.proxy import getObject
_check = object() # don't use a func, due to bound method
- class _WithChecker(object):
+ class _WithChecker:
__Security_checker__ = _check
obj = _WithChecker()
checker = self._makeOne()
@@ -399,7 +397,7 @@ class CheckerTestsBase(QuietWatchingChecker):
from zope.security.proxy import getChecker
from zope.security.proxy import getObject
- class _Obj(object):
+ class _Obj:
pass
obj = _Obj()
_checker = Checker({})
@@ -448,8 +446,6 @@ class CheckerTestsBase(QuietWatchingChecker):
self.assertEqual(proxy // Decimal('1'), Decimal('1'))
self.assertEqual(float(proxy), 1.1)
self.assertEqual(int(proxy), 1)
- if PY2: # pragma: no cover PY2
- self.assertEqual(long(proxy), 1) # noqa: F821 undefined name
self.assertEqual(proxy ** 2, Decimal('1.21'))
self.assertEqual(1 ** proxy, Decimal('1'))
self.assertEqual(proxy.adjusted(), 0)
@@ -513,7 +509,7 @@ class CheckerTestsBase(QuietWatchingChecker):
pass
@implementer(I1)
- class Obj(object):
+ class Obj:
pass
o = Obj()
@@ -546,7 +542,7 @@ class CheckerTestsBase(QuietWatchingChecker):
pass
@implementer(I1)
- class Obj(object):
+ class Obj:
pass
o = Obj()
@@ -571,7 +567,7 @@ class CheckerTestsBase(QuietWatchingChecker):
from zope.security.checker import _iteratorChecker
from zope.security.proxy import Proxy
- class Iter(object):
+ class Iter:
__Security_checker__ = _iteratorChecker
items = (0, 1, 2)
@@ -673,7 +669,6 @@ class TestTracebackSupplement(unittest.TestCase):
return self._getTargetClass()(obj)
def test_getInfo_builtin_types(self):
- from zope.security._compat import _BUILTINS
for val, typ in [('', 'str'),
(0, 'int'),
(1.0, 'float'),
@@ -683,12 +678,12 @@ class TestTracebackSupplement(unittest.TestCase):
]:
tbs = self._makeOne(val)
self.assertEqual(tbs.getInfo().splitlines(),
- [' - class: %s.%s' % (_BUILTINS, typ),
- ' - type: %s.%s' % (_BUILTINS, typ),
+ [' - class: builtins.{}'.format(typ),
+ ' - type: builtins.{}'.format(typ),
])
def test_getInfo_newstyle_instance(self):
- class C(object):
+ class C:
pass
tbs = self._makeOne(C())
self.assertEqual(tbs.getInfo().splitlines(),
@@ -704,11 +699,8 @@ class TestTracebackSupplement(unittest.TestCase):
lines = tbs.getInfo().splitlines()
self.assertEqual(lines[0],
' - class: %s.C' % self.__class__.__module__)
- kind = ('__builtin__.instance'
- if PY2
- else '%s.C' % self.__class__.__module__)
self.assertEqual(lines[1],
- ' - type: ' + kind)
+ ' - type: %s.C' % self.__class__.__module__)
class TestGlobal(unittest.TestCase):
@@ -940,7 +932,7 @@ class Test_MultiChecker(unittest.TestCase):
[(('foo', 'bar'), CheckerPublic), spec])
-class _SelectCheckerBase(object):
+class _SelectCheckerBase:
# pylint:disable=no-member
def _callFUT(self, obj):
@@ -963,7 +955,7 @@ class _SelectCheckerBase(object):
42,
3.14,
None,
- u'text',
+ 'text',
b'binary',
msg,
True,
@@ -979,7 +971,7 @@ class _SelectCheckerBase(object):
from zope.security.checker import Checker
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = _checkers[Foo] = Checker({})
self.assertIs(self._callFUT(Foo()), checker)
@@ -988,7 +980,7 @@ class _SelectCheckerBase(object):
from zope.security.checker import Checker
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = Checker({})
@@ -1001,7 +993,7 @@ class _SelectCheckerBase(object):
from zope.security.checker import NoProxy
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
def _factory(obj):
@@ -1012,7 +1004,7 @@ class _SelectCheckerBase(object):
def test_w_factory_returning_None(self):
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
def _factory(obj):
@@ -1024,7 +1016,7 @@ class _SelectCheckerBase(object):
from zope.security.checker import Checker
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = Checker({})
@@ -1045,40 +1037,24 @@ class _SelectCheckerBase(object):
return x
iterable = (1, 2, 3)
pred_iterable = (pred, iterable)
- missing_in_py3 = {'ifilter', 'ifilterfalse', 'imap',
- 'izip', 'izip_longest'}
- missing_in_py2 = {'zip_longest', 'accumulate', 'compress',
- 'combinations', 'combinations_with_replacement'}
- missing = missing_in_py3 if PY3 else missing_in_py2
for func, args in (
('count', ()),
('cycle', ((),)),
('dropwhile', pred_iterable),
- ('ifilter', pred_iterable),
- ('ifilterfalse', pred_iterable),
- ('imap', pred_iterable),
('islice', (iterable, 2)),
- ('izip', (iterable,)),
- ('izip_longest', (iterable,)),
('permutations', (iterable,)),
('product', (iterable,)),
('repeat', (1, 2)),
('starmap', pred_iterable),
('takewhile', pred_iterable),
('tee', (iterable,)),
- # Python 3 additions
('zip_longest', (iterable,)),
('accumulate', (iterable,)),
('compress', (iterable, ())),
('combinations', (iterable, 1)),
('combinations_with_replacement', (iterable, 1)),
):
- try:
- func = getattr(itertools, func)
- except AttributeError:
- if func in missing:
- continue
- self.fail("Attribute error raised", func)
+ func = getattr(itertools, func)
__traceback_info__ = func
result = func(*args)
if func == itertools.tee:
@@ -1118,14 +1094,14 @@ class Test_getCheckerForInstancesOf(unittest.TestCase):
return getCheckerForInstancesOf(obj)
def test_miss(self):
- class Unknown(object):
+ class Unknown:
pass
self.assertIsNone(self._callFUT(Unknown))
def test_hit(self):
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = _checkers[Foo] = object()
self.assertIs(self._callFUT(Foo), checker)
@@ -1151,7 +1127,7 @@ class Test_defineChecker(unittest.TestCase):
42,
3.14,
None,
- u'text',
+ 'text',
b'binary',
True,
]:
@@ -1162,7 +1138,7 @@ class Test_defineChecker(unittest.TestCase):
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker1, checker2 = object(), object()
_checkers[Foo] = checker1
@@ -1172,7 +1148,7 @@ class Test_defineChecker(unittest.TestCase):
from zope.security.checker import _checkers
checker = object()
- class Foo(object):
+ class Foo:
pass
self._callFUT(Foo, checker)
self.assertIs(_checkers[Foo], checker)
@@ -1210,14 +1186,14 @@ class Test_undefineChecker(unittest.TestCase):
return undefineChecker(type_)
def test_miss(self):
- class Foo(object):
+ class Foo:
pass
self.assertRaises(KeyError, self._callFUT, Foo)
def test_hit(self):
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
_checkers[Foo] = object()
self._callFUT(Foo)
@@ -1275,7 +1251,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.checker import CheckerPublic
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1292,7 +1268,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1310,7 +1286,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1345,7 +1321,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1376,7 +1352,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.checker import CheckerPublic
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1393,7 +1369,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1411,7 +1387,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1446,7 +1422,7 @@ class TestCombinedChecker(QuietWatchingChecker,
from zope.security._definitions import thread_local
from zope.security.interfaces import Unauthorized
- class _Interaction(object):
+ class _Interaction:
def checkPermission(self, obj, perm):
return False
@@ -1477,7 +1453,7 @@ class TestCheckerLoggingMixin(unittest.TestCase):
return CheckerLoggingMixin
def _makeOne(self, raising=None):
- class _Checker(object):
+ class _Checker:
def __init__(self, raising, stream):
self._file = stream
self._raising = raising
@@ -1498,7 +1474,7 @@ class TestCheckerLoggingMixin(unittest.TestCase):
return _Stream()
def _makeObject(self):
- class _Object(object):
+ class _Object:
def __repr__(self):
return 'TESTING'
return _Object()
@@ -1653,14 +1629,14 @@ class Test__instanceChecker(unittest.TestCase):
def test_miss(self):
from zope.security.checker import _defaultChecker
- class Foo(object):
+ class Foo:
pass
self.assertIs(self._callFUT(Foo()), _defaultChecker)
def test_hit(self):
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = _checkers[Foo] = object()
self.assertIs(self._callFUT(Foo()), checker)
@@ -1698,7 +1674,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
unittest.TestCase):
def setUp(self):
- super(TestSecurityPolicy, self).setUp()
+ super().setUp()
from zope.security.management import newInteraction
from zope.security.management import setSecurityPolicy
@@ -1707,7 +1683,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
newInteraction()
def tearDown(self):
- super(TestSecurityPolicy, self).tearDown()
+ super().tearDown()
from zope.security.management import endInteraction
from zope.security.management import setSecurityPolicy
@@ -1719,8 +1695,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
# Py3 has no ClassType and no old-style classes
import types
old_type = getattr(types, 'ClassType', type)
- self.assertTrue((PY2 and old_type is not type)
- or (PY3 and old_type is type))
+ self.assertTrue(old_type is type)
return old_type
def _makeSecurityPolicy(self):
@@ -1729,27 +1704,16 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.interfaces import ISecurityPolicy
@implementer(ISecurityPolicy)
- class SecurityPolicy(object):
+ class SecurityPolicy:
def checkPermission(self, permission, _object):
return permission == 'test_allowed'
return SecurityPolicy
- def test_defineChecker_oldstyle_class(self):
- from zope.security.checker import NamesChecker
- from zope.security.checker import defineChecker
- old_type = self._get_old_class_type()
-
- class ClassicClass:
- __metaclass__ = old_type
- self.assertIsInstance(ClassicClass, old_type)
-
- defineChecker(ClassicClass, NamesChecker())
-
- def test_defineChecker_newstyle_class(self):
+ def test_defineChecker_class(self):
from zope.security.checker import NamesChecker
from zope.security.checker import defineChecker
- class NewStyleClass(object):
+ class NewStyleClass:
pass
self.assertIsInstance(NewStyleClass, type)
defineChecker(NewStyleClass, NamesChecker())
@@ -1789,7 +1753,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
self.assertIsInstance(OldInst, old_type)
- class NewInst(OldInst, object):
+ class NewInst(OldInst):
# This is not needed, but left in to show the change of metaclass
# __metaclass__ = type
def gete(self):
@@ -2018,7 +1982,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.checker import NamesChecker
checker = NamesChecker(())
- class C(object):
+ class C:
pass
self.assertEqual(checker.check(C, '__hash__'), None)
self.assertEqual(checker.check(C, '__nonzero__'), None)
@@ -2059,7 +2023,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.proxy import Proxy
from zope.security.proxy import getChecker
- class SomeClass(object):
+ class SomeClass:
pass
checker = NamesChecker()
specific_checker = NamesChecker()
@@ -2092,7 +2056,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.checker import defineChecker
from zope.security.checker import undefineChecker
- class SomeClass(object):
+ class SomeClass:
pass
obj = SomeClass()
@@ -2109,7 +2073,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.checker import NamesChecker
from zope.security.checker import ProxyFactory
- class SomeClass(object):
+ class SomeClass:
pass
obj = SomeClass()
checker = NamesChecker()
@@ -2143,7 +2107,7 @@ class TestSecurityPolicy(QuietWatchingChecker,
from zope.security.checker import defineChecker
from zope.security.interfaces import Forbidden
- class SomeClass(object):
+ class SomeClass:
pass
obj = SomeClass()
@@ -2257,7 +2221,7 @@ class TestMixinDecoratedChecker(unittest.TestCase):
from zope.security.interfaces import ISecurityPolicy
@implementer(ISecurityPolicy)
- class RecordedSecurityPolicy(object):
+ class RecordedSecurityPolicy:
def __init__(self):
self._checked = []
self.permissions = {}
@@ -2319,12 +2283,12 @@ class TestCombinedCheckerMixin(QuietWatchingChecker,
unittest.TestCase):
def setUp(self):
- super(TestCombinedCheckerMixin, self).setUp()
+ super().setUp()
self.decoratedSetUp()
def tearDown(self):
self.decoratedTearDown()
- super(TestCombinedCheckerMixin, self).tearDown()
+ super().tearDown()
def test_checking(self):
from zope.security.checker import CombinedChecker
@@ -2370,7 +2334,7 @@ class TestBasicTypes(unittest.TestCase):
from zope.security.checker import BasicTypes
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = object()
BasicTypes[Foo] = checker
@@ -2381,7 +2345,7 @@ class TestBasicTypes(unittest.TestCase):
from zope.security.checker import BasicTypes
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = object()
BasicTypes[Foo] = checker
@@ -2397,10 +2361,10 @@ class TestBasicTypes(unittest.TestCase):
from zope.security.checker import BasicTypes
from zope.security.checker import _checkers
- class Foo(object):
+ class Foo:
pass
checker = object()
- BasicTypes.update({Foo: checker})
+ BasicTypes.update({Foo: checker})
self.assertIs(BasicTypes[Foo], checker)
self.assertIs(_checkers[Foo], checker)
@@ -2410,10 +2374,10 @@ class TestBasicTypes(unittest.TestCase):
from zope.security.checker import _checkers
from zope.security.checker import _clear
- class MyType(object):
+ class MyType:
pass
- class MyType2(object):
+ class MyType2:
pass
# When an item is added to the basic types, it should also be added to
@@ -2450,12 +2414,6 @@ class TestBasicTypes(unittest.TestCase):
self.assertIn(int, keys)
self.assertIn(float, keys)
self.assertIn(str, keys)
- try:
- unicode
- except NameError:
- pass
- else: # pragma: no cover PY2
- self.assertIn(unicode, keys) # noqa: F821 undefined name 'unicode'
self.assertIn(object, keys)
# ...
diff --git a/src/zope/security/tests/test_decorator.py b/src/zope/security/tests/test_decorator.py
index 756177a..c56a996 100644
--- a/src/zope/security/tests/test_decorator.py
+++ b/src/zope/security/tests/test_decorator.py
@@ -22,12 +22,12 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
unittest.TestCase):
def setUp(self):
- super(DecoratedSecurityCheckerDescriptorTests, self).setUp()
+ super().setUp()
from zope.security.checker import _clear
_clear()
def tearDown(self):
- super(DecoratedSecurityCheckerDescriptorTests, self).tearDown()
+ super().tearDown()
from zope.security.checker import _clear
_clear()
@@ -44,7 +44,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import NoProxy
from zope.security.checker import defineChecker
- class Foo(object):
+ class Foo:
a = 'a'
defineChecker(Foo, NoProxy)
foo = Foo()
@@ -65,7 +65,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import defineChecker
from zope.security.interfaces import ForbiddenAttribute
- class Foo(object):
+ class Foo:
a = 'a'
fooChecker = NamesChecker(['a']) # a is public
defineChecker(Foo, fooChecker)
@@ -96,7 +96,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import NoProxy
from zope.security.checker import defineChecker
- class Foo(object):
+ class Foo:
a = 'a'
foo = Foo()
defineChecker(Foo, NoProxy)
@@ -116,7 +116,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import NoProxy
from zope.security.checker import defineChecker
- class Foo(object):
+ class Foo:
a = 'a'
fooChecker = NamesChecker(['a']) # a is public
defineChecker(Foo, fooChecker)
@@ -137,7 +137,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import defineChecker
from zope.security.proxy import ProxyFactory
- class Foo(object):
+ class Foo:
a = 'a'
fooChecker = NamesChecker(['a']) # a is public
defineChecker(Foo, fooChecker)
@@ -162,7 +162,7 @@ class DecoratedSecurityCheckerDescriptorTests(QuietWatchingChecker,
from zope.security.checker import NoProxy
from zope.security.checker import defineChecker
- class Foo(object):
+ class Foo:
a = 'a'
defineChecker(Foo, NoProxy)
foo = Foo()
diff --git a/src/zope/security/tests/test_location.py b/src/zope/security/tests/test_location.py
index a620605..5de73a5 100644
--- a/src/zope/security/tests/test_location.py
+++ b/src/zope/security/tests/test_location.py
@@ -28,7 +28,7 @@ class LocationSecurityProxyTests(QuietWatchingChecker,
from zope.security.checker import defineChecker
from zope.security.proxy import ProxyFactory
- class Unlocated(object):
+ class Unlocated:
a = 'a'
unlocated = Unlocated()
located = LocationProxy(unlocated)
diff --git a/src/zope/security/tests/test_management.py b/src/zope/security/tests/test_management.py
index 6fb62cf7..7cc7e3b 100644
--- a/src/zope/security/tests/test_management.py
+++ b/src/zope/security/tests/test_management.py
@@ -141,7 +141,7 @@ class Test(unittest.TestCase):
permission = 'zope.Test'
obj = object()
- class PolicyStub(object):
+ class PolicyStub:
def checkPermission(s, p, o,):
self.assertTrue(p is permission)
self.assertTrue(o is obj)
@@ -161,7 +161,7 @@ class Test(unittest.TestCase):
obj = object()
- class ForbiddenPolicyStub(object):
+ class ForbiddenPolicyStub:
def checkPermission(s, p, o):
return False
@@ -179,13 +179,13 @@ class Test(unittest.TestCase):
from zope.security.management import system_user
self.assertEqual(system_user.id,
- u'zope.security.management.system_user')
+ 'zope.security.management.system_user')
- self.assertEqual(system_user.title, u'System')
+ self.assertEqual(system_user.title, 'System')
for name in 'id', 'title', 'description':
self.assertIsInstance(getattr(system_user, name),
- type(u''))
+ str)
verifyObject(IPrincipal, system_user)
verifyObject(ISystemPrincipal, system_user)
diff --git a/src/zope/security/tests/test_metaconfigure.py b/src/zope/security/tests/test_metaconfigure.py
index a446b72..76471bd 100644
--- a/src/zope/security/tests/test_metaconfigure.py
+++ b/src/zope/security/tests/test_metaconfigure.py
@@ -104,7 +104,7 @@ class ClassDirectiveTests(unittest.TestCase):
def test_require_only_like_class(self):
from zope.security.protectclass import protectLikeUnto
- class Bar(object):
+ class Bar:
pass
context = DummyZCMLContext()
directive = self._makeOne(context, Foo)
@@ -230,8 +230,8 @@ class ClassDirectiveTests(unittest.TestCase):
from zope.security.protectclass import protectSetAttribute
class IFoo(Interface):
- bar = Field(u"Bar")
- baz = Field(u"Baz")
+ bar = Field("Bar")
+ baz = Field("Baz")
context = DummyZCMLContext()
directive = self._makeOne(context, Foo)
directive.require(context, permission='testing', set_schema=[IFoo])
@@ -271,7 +271,7 @@ class ClassDirectiveTests(unittest.TestCase):
from zope.schema import Field
class IFoo(Interface):
- bar = Field(u"Bar", readonly=True)
+ bar = Field("Bar", readonly=True)
context = DummyZCMLContext()
directive = self._makeOne(context, Foo)
directive.require(context, permission='testing', set_schema=[IFoo])
@@ -423,7 +423,7 @@ class ClassDirectiveTests(unittest.TestCase):
self.assertEqual(context._actions[1]['args'], ('', IFactory))
-class Foo(object):
+class Foo:
pass
@@ -662,7 +662,7 @@ class Test_requre(unittest.TestCase):
('testing', 'baz', perm))
-class DummyZCMLContext(object):
+class DummyZCMLContext:
def __init__(self):
self._actions = []
diff --git a/src/zope/security/tests/test_permission.py b/src/zope/security/tests/test_permission.py
index 075aed0..2326f37 100644
--- a/src/zope/security/tests/test_permission.py
+++ b/src/zope/security/tests/test_permission.py
@@ -48,15 +48,15 @@ class PermissionTests(unittest.TestCase):
def test_ctor_only_id(self):
permission = self._makeOne('testing')
- self.assertEqual(permission.id, u'testing')
- self.assertEqual(permission.title, u'')
- self.assertEqual(permission.description, u'')
+ self.assertEqual(permission.id, 'testing')
+ self.assertEqual(permission.title, '')
+ self.assertEqual(permission.description, '')
def test_ctor_w_title_and_description(self):
- permission = self._makeOne('testing', u'TITLE', u'DESCRIPTION')
+ permission = self._makeOne('testing', 'TITLE', 'DESCRIPTION')
self.assertEqual(permission.id, 'testing')
- self.assertEqual(permission.title, u'TITLE')
- self.assertEqual(permission.description, u'DESCRIPTION')
+ self.assertEqual(permission.title, 'TITLE')
+ self.assertEqual(permission.description, 'DESCRIPTION')
class Test_checkPermission(PlacelessSetup, unittest.TestCase):
diff --git a/src/zope/security/tests/test_protectclass.py b/src/zope/security/tests/test_protectclass.py
index c1cdc09..4cbd95c 100644
--- a/src/zope/security/tests/test_protectclass.py
+++ b/src/zope/security/tests/test_protectclass.py
@@ -132,7 +132,7 @@ class Test_protectLikeUnto(unittest.TestCase):
foo_checker.set_permissions)
-class Foo(object):
+class Foo:
bar = 'Bar'
diff --git a/src/zope/security/tests/test_proxy.py b/src/zope/security/tests/test_proxy.py
index 3570cad..68f370a 100644
--- a/src/zope/security/tests/test_proxy.py
+++ b/src/zope/security/tests/test_proxy.py
@@ -16,39 +16,14 @@
import unittest
from zope.security._compat import PURE_PYTHON
-from zope.security._compat import PYTHON2
-def _skip_if_not_Py2(testfunc):
- return unittest.skipUnless(PYTHON2, "Only on Py2")(testfunc)
-
# pylint:disable=protected-access,eval-used,too-many-lines,too-many-public-methods
-
-if not PYTHON2: # pragma: PY3
- def coerce(*args):
- raise NotImplementedError("Not on Python 3")
- cmp = coerce
- long = int
- unicode = str
-
-
-class AbstractProxyTestBase(object):
+class AbstractProxyTestBase:
# pylint:disable=no-member,blacklisted-name
- assertRaisesRegex = getattr(unittest.TestCase, 'assertRaisesRegex',
- unittest.TestCase.assertRaisesRegexp)
-
- # The names of attributes that are spelled different on Py2
- # vs Py3
- itruediv = '__itruediv__' if not PYTHON2 else '__idiv__'
- idiv = itruediv
- div = '__truediv__' if not PYTHON2 else '__div__'
- truediv = div
- getslice = '__getitem__' if not PYTHON2 else '__getslice__'
- setslice = '__setitem__' if not PYTHON2 else '__setslice__'
-
def _getTargetClass(self):
raise NotImplementedError("Subclass responsibility")
@@ -59,7 +34,7 @@ class AbstractProxyTestBase(object):
self.assertRaises(ValueError, self._makeOne, object(), None)
def test___getattr___w_checker_ok(self):
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker()
@@ -72,7 +47,7 @@ class AbstractProxyTestBase(object):
def test___getattr___w_checker_unauthorized(self):
from zope.security.interfaces import Unauthorized
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker(Unauthorized)
@@ -83,7 +58,7 @@ class AbstractProxyTestBase(object):
def test___getattr___w_checker_forbidden_attribute(self):
from zope.security.interfaces import ForbiddenAttribute
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker(ForbiddenAttribute)
@@ -94,7 +69,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, 'bar')
def test__getattr__w_checker_ok_dynamic_attribute_called_once(self):
- class Dynamic(object):
+ class Dynamic:
count = 0
def __getattr__(self, name):
@@ -113,7 +88,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(1, target.count)
def test___setattr___w_checker_ok(self):
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker()
@@ -126,7 +101,7 @@ class AbstractProxyTestBase(object):
def test___setattr___w_checker_unauthorized(self):
from zope.security.interfaces import Unauthorized
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker(Unauthorized)
@@ -137,7 +112,7 @@ class AbstractProxyTestBase(object):
def test___setattr___w_checker_forbidden_attribute(self):
from zope.security.interfaces import ForbiddenAttribute
- class Foo(object):
+ class Foo:
bar = 'Bar'
target = Foo()
checker = DummyChecker(ForbiddenAttribute)
@@ -146,7 +121,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, 'bar')
def test___delattr___w_checker_ok(self):
- class Foo(object):
+ class Foo:
bar = None
target = Foo()
target.bar = 'Bar'
@@ -160,7 +135,7 @@ class AbstractProxyTestBase(object):
def test___delattr___w_checker_unauthorized(self):
from zope.security.interfaces import Unauthorized
- class Foo(object):
+ class Foo:
def __init__(self):
self.bar = 'Bar'
target = Foo()
@@ -173,7 +148,7 @@ class AbstractProxyTestBase(object):
def test___delattr___w_checker_forbidden_attribute(self):
from zope.security.interfaces import ForbiddenAttribute
- class Foo(object):
+ class Foo:
def __init__(self):
self.bar = 'Bar'
target = Foo()
@@ -190,7 +165,6 @@ class AbstractProxyTestBase(object):
self.assertEqual(str(proxy), str(target))
def test___str___checker_forbids_str(self):
- from zope.security._compat import _BUILTINS
from zope.security.interfaces import ForbiddenAttribute
from zope.security.proxy import _fmt_address
target = object()
@@ -198,13 +172,13 @@ class AbstractProxyTestBase(object):
proxy = self._makeOne(target, checker)
address = _fmt_address(target)
self.assertEqual(str(proxy),
- '<security proxied %s.object '
- 'instance at %s>' % (_BUILTINS, address))
+ '<security proxied builtins.object '
+ 'instance at %s>' % address)
def test___str___fails_return(self):
from zope.security.interfaces import ForbiddenAttribute
- class CustomStr(object):
+ class CustomStr:
def __str__(self):
"<CustomStr>" # Docstring, not a return
@@ -223,7 +197,6 @@ class AbstractProxyTestBase(object):
self.assertEqual(repr(proxy), repr(target))
def test___repr___checker_forbids_str(self):
- from zope.security._compat import _BUILTINS
from zope.security.interfaces import ForbiddenAttribute
from zope.security.proxy import _fmt_address
target = object()
@@ -231,13 +204,13 @@ class AbstractProxyTestBase(object):
proxy = self._makeOne(target, checker)
address = _fmt_address(target)
self.assertEqual(repr(proxy),
- '<security proxied %s.object '
- 'instance at %s>' % (_BUILTINS, address))
+ '<security proxied builtins.object '
+ 'instance at %s>' % address)
def test___str___falls_through_to_repr_when_both_allowed(self):
from zope.security.interfaces import ForbiddenAttribute
- class CustomRepr(object):
+ class CustomRepr:
def __repr__(self):
return "<CustomRepr>"
@@ -252,7 +225,7 @@ class AbstractProxyTestBase(object):
def test___str___doesnot_fall_through_to_repr_when_str_not_allowed(self):
from zope.security.interfaces import ForbiddenAttribute
- class CustomRepr(object):
+ class CustomRepr:
def __repr__(self):
return "<CustomRepr>"
@@ -266,7 +239,7 @@ class AbstractProxyTestBase(object):
def test___str___doesnot_fall_through_to_repr_when_repr_not_allowed(self):
from zope.security.interfaces import ForbiddenAttribute
- class CustomRepr(object):
+ class CustomRepr:
def __repr__(self):
return "<CustomRepr>"
@@ -280,7 +253,7 @@ class AbstractProxyTestBase(object):
def test___str___falls_through_to_repr_but_repr_fails_return(self):
from zope.security.interfaces import ForbiddenAttribute
- class CustomRepr(object):
+ class CustomRepr:
def __repr__(self):
"<CustomRepr>" # Docstring, not a return
@@ -292,36 +265,6 @@ class AbstractProxyTestBase(object):
with self.assertRaises(TypeError):
repr(proxy)
- @_skip_if_not_Py2
- def test___cmp___w_self(self): # pragma: no cover
- target = object()
- checker = object() # checker not consulted
- proxy = self._makeOne(target, checker)
- self.assertEqual(cmp(proxy, proxy), 0)
-
- @_skip_if_not_Py2
- def test___cmp___w_target(self): # pragma: no cover
- target = object()
- checker = object() # checker not consulted
- proxy = self._makeOne(target, checker)
- self.assertEqual(cmp(proxy, target), 0)
-
- @_skip_if_not_Py2
- def test___cmp___w_other(self): # pragma: no cover
- target = object()
- other = object()
- checker = object() # checker not consulted
- proxy = self._makeOne(target, checker)
- self.assertNotEqual(cmp(proxy, other), 0)
-
- @_skip_if_not_Py2
- def test___cmp___w_other_proxy(self): # pragma: no cover
- target = object()
- checker = object() # checker not consulted
- proxy = self._makeOne(target, checker)
- o_proxy = self._makeOne(target, checker)
- self.assertEqual(cmp(proxy, o_proxy), 0)
-
def test__le__(self):
target = 1
checker = object() # checker not consulted
@@ -353,7 +296,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(hash(proxy), hash(target))
def test___call___w_checker_ok(self):
- class Foo(object):
+ class Foo:
def __call__(self):
return 'Bar'
target = Foo()
@@ -366,7 +309,7 @@ class AbstractProxyTestBase(object):
def test___call___w_checker_unauthorized(self):
from zope.security.interfaces import Unauthorized
- class Foo(object):
+ class Foo:
def __call__(self):
raise AssertionError("Never called")
target = Foo()
@@ -378,7 +321,7 @@ class AbstractProxyTestBase(object):
def test___call___w_checker_forbidden_attribute(self):
from zope.security.interfaces import ForbiddenAttribute
- class Foo(object):
+ class Foo:
def __call__(self):
raise AssertionError("Never called")
target = Foo()
@@ -417,57 +360,6 @@ class AbstractProxyTestBase(object):
self.assertRaises(ForbiddenAttribute, float, proxy)
self.assertEqual(checker._checked, '__float__')
- @_skip_if_not_Py2
- def test___long___w_checker_allows(self): # pragma: no cover
- target = 3.0
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- self.assertEqual(long(proxy), long(target))
- self.assertEqual(checker._checked, '__long__')
-
- @_skip_if_not_Py2
- def test___long___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = 3
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertRaises(ForbiddenAttribute, long, proxy)
- self.assertEqual(checker._checked, '__long__')
-
- @_skip_if_not_Py2
- def test___oct___w_checker_allows(self): # pragma: no cover
- target = 3
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- self.assertEqual(oct(proxy), oct(target))
- self.assertEqual(checker._checked, '__oct__')
-
- @_skip_if_not_Py2
- def test___oct___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = 3
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertRaises(ForbiddenAttribute, oct, proxy)
- self.assertEqual(checker._checked, '__oct__')
-
- @_skip_if_not_Py2
- def test___hex___w_checker_allows(self): # pragma: no cover
- target = 3
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- self.assertEqual(hex(proxy), hex(target))
- self.assertEqual(checker._checked, '__hex__')
-
- @_skip_if_not_Py2
- def test___hex___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = 3
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertRaises(ForbiddenAttribute, hex, proxy)
- self.assertEqual(checker._checked, '__hex__')
-
def test___add___w_checker_allows(self):
target = 3
checker = DummyChecker()
@@ -518,7 +410,7 @@ class AbstractProxyTestBase(object):
checker = DummyChecker()
proxy = self._makeOne(target, checker)
self.assertEqual(proxy / 2, target / 2)
- self.assertEqual(checker._checked, self.div)
+ self.assertEqual(checker._checked, '__truediv__')
def test___div___w_checker_forbids(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -526,14 +418,14 @@ class AbstractProxyTestBase(object):
checker = DummyChecker(ForbiddenAttribute)
proxy = self._makeOne(target, checker)
self.assertRaises(ForbiddenAttribute, lambda: proxy / 2)
- self.assertEqual(checker._checked, self.div)
+ self.assertEqual(checker._checked, '__truediv__')
def test___truediv___w_checker_allows(self):
target = 3.0
checker = DummyChecker()
proxy = self._makeOne(target, checker)
self.assertEqual(proxy / 2, target / 2)
- self.assertEqual(checker._checked, self.truediv)
+ self.assertEqual(checker._checked, '__truediv__')
def test___truediv___w_checker_forbids(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -541,7 +433,7 @@ class AbstractProxyTestBase(object):
checker = DummyChecker(ForbiddenAttribute)
proxy = self._makeOne(target, checker)
self.assertRaises(ForbiddenAttribute, lambda: proxy / 2)
- self.assertEqual(checker._checked, self.truediv)
+ self.assertEqual(checker._checked, '__truediv__')
def test___floordiv___w_checker_allows(self):
target = 3
@@ -759,23 +651,6 @@ class AbstractProxyTestBase(object):
self.assertRaises(ForbiddenAttribute, lambda: proxy | 2)
self.assertEqual(checker._checked, '__or__')
- @_skip_if_not_Py2
- def test___coerce___w_checker_allows(self): # pragma: no cover
- target = 3
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- self.assertEqual(coerce(proxy, 4.0), coerce(target, 4.0))
- self.assertEqual(checker._checked, '__coerce__')
-
- @_skip_if_not_Py2
- def test___coerce___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = 3
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertRaises(ForbiddenAttribute, coerce, proxy, 4.0)
- self.assertEqual(checker._checked, '__coerce__')
-
def test___iadd___not_inplace_checker_allows(self):
target = 3
checker = DummyChecker()
@@ -786,7 +661,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__iadd__')
def test___iadd___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -820,7 +695,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__isub__')
def test___isub___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -854,7 +729,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__imul__')
def test___imul___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -885,10 +760,10 @@ class AbstractProxyTestBase(object):
proxy /= 3
self.assertIsNot(proxy, before)
self.assertEqual(proxy, 2)
- self.assertEqual(checker._checked, self.idiv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___idiv___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -902,7 +777,7 @@ class AbstractProxyTestBase(object):
proxy /= 3
self.assertIs(proxy, before)
self.assertEqual(target.value, 2)
- self.assertEqual(checker._checked, self.idiv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___idiv___w_checker_forbids(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -911,7 +786,7 @@ class AbstractProxyTestBase(object):
proxy = self._makeOne(target, checker)
with self.assertRaises(ForbiddenAttribute):
proxy /= 3
- self.assertEqual(checker._checked, self.idiv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___itruediv___not_inplace_checker_allows(self):
target = 6
@@ -920,10 +795,10 @@ class AbstractProxyTestBase(object):
proxy /= 3
self.assertIsNot(proxy, before)
self.assertEqual(proxy, 2)
- self.assertEqual(checker._checked, self.itruediv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___itruediv___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -937,7 +812,7 @@ class AbstractProxyTestBase(object):
proxy /= 3
self.assertIs(proxy, before)
self.assertEqual(target.value, 2)
- self.assertEqual(checker._checked, self.itruediv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___itruediv___w_checker_forbids(self):
from zope.security.interfaces import ForbiddenAttribute
@@ -946,7 +821,7 @@ class AbstractProxyTestBase(object):
proxy = self._makeOne(target, checker)
with self.assertRaises(ForbiddenAttribute):
proxy /= 3
- self.assertEqual(checker._checked, self.itruediv)
+ self.assertEqual(checker._checked, '__itruediv__')
def test___ifloordiv___not_inplace_checker_allows(self):
target = 6
@@ -958,7 +833,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__ifloordiv__')
def test___ifloordiv___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -992,7 +867,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__imod__')
def test___imod___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1026,7 +901,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__ipow__')
def test___ipow___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1060,7 +935,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__ilshift__')
def test___ilshift___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1094,7 +969,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__irshift__')
def test___irshift___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1128,7 +1003,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__iand__')
def test___iand___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1162,7 +1037,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(proxy, 4)
def test___ixor___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1198,7 +1073,7 @@ class AbstractProxyTestBase(object):
self.assertEqual(checker._checked, '__ior__')
def test___ior___inplace_checker_allows(self):
- class Foo(object):
+ class Foo:
def __init__(self, value):
self.value = value
@@ -1324,38 +1199,28 @@ class AbstractProxyTestBase(object):
self.assertRaises(ForbiddenAttribute, _try)
self.assertEqual(checker._checked, '__setitem__')
- @_skip_if_not_Py2
- def test___getslice___w_checker_allows(self): # pragma: no cover
- target = [0, 1, 2]
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- self.assertEqual(proxy[1:3], [1, 2])
- self.assertEqual(checker._checked, self.getslice)
-
def test___getslice___error_propagates(self):
class Missing(Exception):
pass
- class Get(object):
+ class Get:
def __getitem__(self, x):
raise Missing('__getitem__')
- def __getslice__(self, start, stop): # PY2
- raise Missing("__getslice__") # pragma: no cover
target = Get()
checker = DummyChecker()
proxy = self._makeOne(target, checker)
with self.assertRaisesRegex(Missing,
- self.getslice):
+ '__getitem__'):
proxy[1:2]
- self.assertEqual(checker._checked, self.getslice)
+ self.assertEqual(checker._checked, '__getitem__')
def test___getslice___dne_uses_getitem(self):
class Missing(Exception):
pass
- class Get(object):
+ class Get:
def __getitem__(self, x):
raise Missing('__getitem__')
@@ -1366,62 +1231,30 @@ class AbstractProxyTestBase(object):
'__getitem__'):
proxy[1:2]
- self.assertEqual(checker._checked, self.getslice)
-
- @_skip_if_not_Py2
- def test___getslice___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = [0, 1, 2]
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertRaises(ForbiddenAttribute, lambda: proxy[0:2])
- self.assertEqual(checker._checked, '__getslice__')
-
- @_skip_if_not_Py2
- def test___setslice___w_checker_allows(self): # pragma: no cover
- target = [0, 1, 2]
- checker = DummyChecker()
- proxy = self._makeOne(target, checker)
- proxy[1:3] = [3, 4]
- self.assertEqual(target, [0, 3, 4])
- self.assertEqual(checker._checked, '__setslice__')
-
- @_skip_if_not_Py2
- def test___setslice___w_checker_forbids(self): # pragma: no cover
- from zope.security.interfaces import ForbiddenAttribute
- target = [0, 1, 2]
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
-
- def _try():
- proxy[1:3] = [3, 4]
- self.assertRaises(ForbiddenAttribute, _try)
- self.assertEqual(checker._checked, '__setslice__')
+ self.assertEqual(checker._checked, '__getitem__')
def test___setslice___error_propagates(self):
class Missing(Exception):
pass
- class Set(object):
+ class Set:
def __setitem__(self, k, v):
raise Missing('__setitem__')
- def __setslice__(self, start, stop, value): # PY2
- raise Missing("__setslice__") # pragma: no cover
target = Set()
checker = DummyChecker()
proxy = self._makeOne(target, checker)
with self.assertRaisesRegex(Missing,
- self.setslice):
+ '__setitem__'):
proxy[1:2] = 1
- self.assertEqual(checker._checked, self.setslice)
+ self.assertEqual(checker._checked, '__setitem__')
def test___setslice___dne_uses_setitem(self):
class Missing(Exception):
pass
- class Set(object):
+ class Set:
def __setitem__(self, k, v):
raise Missing('__setitem__')
@@ -1432,7 +1265,7 @@ class AbstractProxyTestBase(object):
'__setitem__'):
proxy[1:2] = 1
- self.assertEqual(checker._checked, self.setslice)
+ self.assertEqual(checker._checked, '__setitem__')
def test___getitem___mapping_hit_w_checker_allows(self):
target = {'a': 0, 'b': 1, 'c': 2}
@@ -1491,60 +1324,10 @@ class AbstractProxyTestBase(object):
z = eval(expr)
first = 0
else:
- self.assertEqual(removeSecurityProxy(eval(expr)), z,
- "x=%r; y=%r; expr=%r" % (x, y, expr))
-
- @_skip_if_not_Py2
- def test___unicode___allowed_by_default(self): # pragma: no cover
- # https://github.com/zopefoundation/zope.security/issues/10
- class Foo(object):
- def __unicode__(self):
- return u'I am unicode'
-
- checker = object() # checker not consulted
- target = Foo()
- proxy = self._makeOne(target, checker)
- self.assertEqual(unicode(target), u'I am unicode')
- self.assertEqual(unicode(target), unicode(proxy))
-
- @_skip_if_not_Py2
- def test___unicode___falls_through_to_str_by_default(self): # pragma: no cover # noqa: E501 line too long
- # https://github.com/zopefoundation/zope.security/issues/10
- class Foo(object):
- def __str__(self):
- return 'I am str'
-
- checker = object() # checker not consulted
- target = Foo()
- proxy = self._makeOne(target, checker)
- self.assertEqual(unicode(target), u'I am str')
- self.assertIsInstance(unicode(target), unicode)
- self.assertEqual(unicode(target), unicode(proxy))
- self.assertIsInstance(unicode(proxy), unicode)
-
- @_skip_if_not_Py2
- def test___unicode___falls_through_to_str_even_if_str_not_allowed(self): # pragma: no cover # noqa: E501 line too long
- # https://github.com/zopefoundation/zope.security/issues/10
- # Note that this is inconsistent with str() and probably not a good
- # idea overall, so this test is strictly a regression test.
- from zope.security.interfaces import ForbiddenAttribute
-
- class Foo(object):
- def __str__(self):
- return 'I am str'
-
- target = Foo()
- checker = DummyChecker(ForbiddenAttribute)
- proxy = self._makeOne(target, checker)
- self.assertEqual(unicode(target), u'I am str')
- self.assertIsInstance(unicode(target), unicode)
-
- # Asking for the unicode of the proxy silently falls through
- # to the str without any checks
- self.assertEqual(unicode(target), unicode(proxy))
-
- # And set str itself is checked and proxied
- self.assertIn("<security proxied", str(proxy))
+ self.assertEqual(
+ removeSecurityProxy(eval(expr)),
+ z,
+ "x={!r}; y={!r}; expr={!r}".format(x, y, expr))
@unittest.skipIf(PURE_PYTHON,
@@ -1659,7 +1442,7 @@ class ProxyPyTests(AbstractProxyTestBase,
self.assertIs(self, getObjectPy(self))
def test_get_reduce(self):
- class Reduce(object):
+ class Reduce:
def __reduce__(self):
return 1
@@ -1672,7 +1455,7 @@ class ProxyPyTests(AbstractProxyTestBase,
self.assertEqual(2, proxy.__reduce_ex__(2))
def test__module__(self):
- class WithModule(object):
+ class WithModule:
__module__ = 'foo'
module = WithModule()
@@ -1680,7 +1463,7 @@ class ProxyPyTests(AbstractProxyTestBase,
self.assertEqual(WithModule.__module__, proxy.__module__)
-class DummyChecker(object):
+class DummyChecker:
_proxied = _checked = None
def __init__(self, raising=None, allowed=()):
@@ -1731,7 +1514,7 @@ class Test_isinstance(unittest.TestCase):
return isinstance(object, cls)
def test_w_unproxied_object(self):
- class Foo(object):
+ class Foo:
pass
target = Foo()
self.assertTrue(self._callFUT(target, Foo))
@@ -1741,7 +1524,7 @@ class Test_isinstance(unittest.TestCase):
from zope.security.checker import Checker
from zope.security.proxy import Proxy
- class Foo(object):
+ class Foo:
pass
target = Foo()
proxy = Proxy(target, Checker({}))
@@ -1751,7 +1534,7 @@ class Test_isinstance(unittest.TestCase):
# pre-geddon
-class Checker(object):
+class Checker:
ok = 1
@@ -1808,16 +1591,6 @@ class Something:
def __len__(self):
return 42
- def __nonzero__(self): # PY2
- return 1 # pragma: no cover
-
- def __getslice__(self, i, j): # PY2
- return [42] # pragma: no cover
-
- def __setslice__(self, i, j, value): # PY2
- if value != [42]: # pragma: no cover
- raise AssertionError("Value should be [42]")
-
def __contains__(self, x):
return x == 42
@@ -1934,13 +1707,6 @@ class ProxyFactoryTests(unittest.TestCase):
def testNextFail(self):
self.shouldFail(self.p.next)
- @_skip_if_not_Py2
- def testCompareOK(self): # pragma: no cover
- self.assertEqual(cmp(self.p, self.x), 0)
-
-# def testCompareFail(self):
-# self.shouldFail(cmp, self.p, self.x)
-
def testHashOK(self):
self.assertEqual(hash(self.p), hash(self.x))
@@ -1959,11 +1725,6 @@ class ProxyFactoryTests(unittest.TestCase):
def testLenFail(self):
self.shouldFail(len, self.p)
- @_skip_if_not_Py2
- def testSliceOK(self): # pragma: no cover
- from zope.security.proxy import removeSecurityProxy
- self.assertEqual(removeSecurityProxy(self.p[:]), [42])
-
def testSliceFail(self):
self.shouldFail(lambda: self.p[:])
@@ -1992,7 +1753,7 @@ class ProxyFactoryTests(unittest.TestCase):
def testProxiedClassicClassAsDictKey(self):
from zope.security.proxy import ProxyFactory
- class C(object):
+ class C:
pass
d = {C: C()}
pC = ProxyFactory(C, self.c)
@@ -2001,15 +1762,13 @@ class ProxyFactoryTests(unittest.TestCase):
def testProxiedNewClassAsDictKey(self):
from zope.security.proxy import ProxyFactory
- class C(object):
+ class C:
pass
d = {C: C()}
pC = ProxyFactory(C, self.c)
self.assertEqual(d[pC], d[C])
unops = ["-x", "+x", "abs(x)", "~x", "int(x)", "float(x)"]
- if PYTHON2:
- unops.append("long(x)") # pragma: no cover
def _make_eval(self, expr, locs):
def _eval(*args):
@@ -2024,8 +1783,6 @@ class ProxyFactoryTests(unittest.TestCase):
from zope.security.proxy import ProxyFactory
from zope.security.proxy import removeSecurityProxy
self.c.unproxied_types = {str, int, float}
- if PYTHON2:
- self.c.unproxied_types.add(long) # pragma: no cover
for expr in self.unops:
x = 1
@@ -2034,20 +1791,9 @@ class ProxyFactoryTests(unittest.TestCase):
x = ProxyFactory(1, self.c)
z = eval(expr)
self.assertEqual(removeSecurityProxy(z), y,
- "x=%r; expr=%r" % (x, expr))
+ "x={!r}; expr={!r}".format(x, expr))
self.shouldFail(self._make_eval(expr, locals()), x)
- @_skip_if_not_Py2
- def test_odd_unops(self): # pragma: no cover
- # unops that don't return a proxy
- P = self.c.proxy
- for func in (
- hex, oct,
- # lambda x: not x,
- ):
- self.assertEqual(func(P(100)), func(100))
- self.shouldFail(func, P(100))
-
binops = [
"x+y", "x-y", "x*y", "x/y", "divmod(x, y)", "x**y", "x//y",
"x<<y", "x>>y", "x&y", "x|y", "x^y",
@@ -2064,8 +1810,10 @@ class ProxyFactoryTests(unittest.TestCase):
z = eval(expr)
first = 0
else:
- self.assertEqual(removeSecurityProxy(eval(expr)), z,
- "x=%r; y=%r; expr=%r" % (x, y, expr))
+ self.assertEqual(
+ removeSecurityProxy(eval(expr)),
+ z,
+ "x={!r}; y={!r}; expr={!r}".format(x, y, expr))
self.shouldFail(self._make_eval(expr, locals()), x, y)
def test_inplace(self):
@@ -2097,69 +1845,6 @@ class ProxyFactoryTests(unittest.TestCase):
pa **= 2
self.shouldFail(doit2)
- @_skip_if_not_Py2
- def test_coerce(self): # pragma: no cover
- from zope.security.proxy import removeSecurityProxy
- P = self.c.proxy
-
- x = P(1)
- y = P(2)
- a, b = coerce(x, y)
- self.assertIs(a, x)
- self.assertIs(b, y)
-
- x = P(1)
- y = P(2.1)
- a, b = coerce(x, 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.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.assertIs(a, x)
- self.assertIs(b, y)
-
- x = P(1)
- y = 2.1
- a, b = coerce(x, y)
- self.assertIs(type(removeSecurityProxy(a)), float)
- self.assertIs(b, y)
-
- x = P(1.1)
- y = 2
- a, b = coerce(x, y)
- self.assertIs(a, x)
- self.assertIs(type(removeSecurityProxy(b)), float)
-
- x = 1
- y = P(2)
- a, b = coerce(x, y)
- self.assertIs(a, x)
- self.assertIs(b, y)
-
- x = 1.1
- y = P(2)
- a, b = coerce(x, y)
- self.assertIs(a, x)
- self.assertIs(type(removeSecurityProxy(b)), float)
-
- x = 1
- y = P(2.1)
- a, b = coerce(x, y)
- self.assertIs(type(removeSecurityProxy(a)), float)
- self.assertIs(b, y)
-
def test_iterate_interface(self):
# This used to work on Python 2, but fail on Python 3.
# See https://github.com/zopefoundation/zope.interface/issues/141
@@ -2257,14 +1942,11 @@ class LocationProxySecurityCheckerTests(unittest.TestCase):
# Regression test for a problem introduced in 3.8.1 and fixed in
# 3.8.3. For details see change log.
import sys
+ from importlib import reload as _reload
from zope.location.location import LocationProxy
import zope.security
- try:
- from importlib import reload as _reload
- except ImportError: # pragma: PY2
- _reload = reload # noqa: F821 undefined name 'reload'
# This attribute is set when zope.security.decorator is imported, to
# show that it will be set too, if zope.security.proxy is imported
diff --git a/src/zope/security/tests/test_simpleinteraction.py b/src/zope/security/tests/test_simpleinteraction.py
index b5b5c4a..4fefddf 100644
--- a/src/zope/security/tests/test_simpleinteraction.py
+++ b/src/zope/security/tests/test_simpleinteraction.py
@@ -16,7 +16,7 @@
import unittest
-class RequestStub(object):
+class RequestStub:
def __init__(self, principal=None):
self.principal = principal
diff --git a/src/zope/security/tests/test_simplepolicies.py b/src/zope/security/tests/test_simplepolicies.py
index e55d0e3..391f942 100644
--- a/src/zope/security/tests/test_simplepolicies.py
+++ b/src/zope/security/tests/test_simplepolicies.py
@@ -14,7 +14,7 @@
import unittest
-class ConformsToIInteraction(object):
+class ConformsToIInteraction:
def _getTargetClass(self):
raise NotImplementedError("Subclass responsibility")
@@ -48,7 +48,7 @@ class ParanoidSecurityPolicyTests(unittest.TestCase,
self.assertEqual(policy.participations, [])
def test_ctor_w_participations(self):
- class Participation(object):
+ class Participation:
interaction = None
p1, p2, p3 = Participation(), Participation(), Participation()
policy = self._makeOne(p1, p2, p3)
@@ -58,19 +58,19 @@ class ParanoidSecurityPolicyTests(unittest.TestCase,
self.assertTrue(p3.interaction is policy)
def test_add_w_foreign_participation(self):
- class Participation(object):
+ class Participation:
interaction = object()
policy = self._makeOne()
self.assertRaises(ValueError, policy.add, Participation())
def test_remove_w_foreign_participation(self):
- class Participation(object):
+ class Participation:
interaction = object()
policy = self._makeOne()
self.assertRaises(ValueError, policy.remove, Participation())
def test_remove(self):
- class Participation(object):
+ class Participation:
interaction = None
p1, p2, p3 = Participation(), Participation(), Participation()
policy = self._makeOne(p1, p2, p3)
@@ -90,7 +90,7 @@ class ParanoidSecurityPolicyTests(unittest.TestCase,
def test_checkPermission_w_non_public_only_system_user(self):
from zope.security._definitions import system_user
- class Participation(object):
+ class Participation:
interaction = None
principal = system_user
policy = self._makeOne(Participation())
@@ -99,7 +99,7 @@ class ParanoidSecurityPolicyTests(unittest.TestCase,
self.assertTrue(policy.checkPermission(permission, target))
def test_checkPermission_w_non_public_other_user(self):
- class Participation(object):
+ class Participation:
interaction = None
principal = object()
policy = self._makeOne(Participation())
diff --git a/src/zope/security/tests/test_zcml.py b/src/zope/security/tests/test_zcml.py
index db04952..366ee4c 100644
--- a/src/zope/security/tests/test_zcml.py
+++ b/src/zope/security/tests/test_zcml.py
@@ -16,7 +16,7 @@ import unittest
from zope.security.interfaces import PUBLIC_PERMISSION_NAME as zope_Public
-class ConformsToIFromUnicode(object):
+class ConformsToIFromUnicode:
def test_class_conforms_to_IFromUnicode(self):
from zope.interface.verify import verifyClass
@@ -152,7 +152,7 @@ class Test_redefinePermission(unittest.TestCase):
def test_wo_existing_mapping(self):
z_context = DummyZCMLContext()
- class Context(object):
+ class Context:
pass
context = z_context.context = Context()
after = object()
@@ -162,7 +162,7 @@ class Test_redefinePermission(unittest.TestCase):
def test_w_existing_mapping_wo_existing_key(self):
z_context = DummyZCMLContext()
- class Context(object):
+ class Context:
pass
context = z_context.context = Context()
mapping = context.permission_mapping = {}
@@ -174,7 +174,7 @@ class Test_redefinePermission(unittest.TestCase):
def test_w_existing_mapping_w_existing_key(self):
z_context = DummyZCMLContext()
- class Context(object):
+ class Context:
pass
context = z_context.context = Context()
mapping = context.permission_mapping = {}
@@ -185,7 +185,7 @@ class Test_redefinePermission(unittest.TestCase):
self.assertIs(context.permission_mapping['before.permission'], after)
-class DummyZCMLContext(object):
+class DummyZCMLContext:
def __init__(self):
self._actions = []
diff --git a/src/zope/security/tests/test_zcml_functest.py b/src/zope/security/tests/test_zcml_functest.py
index 3f5991a..5186586 100644
--- a/src/zope/security/tests/test_zcml_functest.py
+++ b/src/zope/security/tests/test_zcml_functest.py
@@ -18,7 +18,7 @@ import unittest
def configfile(s):
- return io.StringIO(u"""<configure
+ return io.StringIO("""<configure
xmlns='http://namespaces.zope.org/zope'
i18n_domain='zope'>
%s
@@ -283,7 +283,7 @@ def defineDirectives():
import zope.security
XMLConfig('meta.zcml', zope.security)()
- xmlconfig(io.StringIO(u"""<configure
+ xmlconfig(io.StringIO("""<configure
xmlns='http://namespaces.zope.org/zope'
i18n_domain='zope'>
<permission id="zope.Extravagant" title="extravagant" />
@@ -307,7 +307,7 @@ class TestRequireDirective(unittest.TestCase):
setUp()
defineDirectives()
- class B(object):
+ class B:
def m1(self):
raise AssertionError("Never called")
@@ -528,34 +528,39 @@ class TestRequireDirective(unittest.TestCase):
self.assertDeclaration(declaration, m1P=P1, m2P=P1)
def testMimicOnly(self):
- declaration = ('''<class class="%s">
+ declaration = ('''<class class="{}">
<require
- permission="%s"
+ permission="{}"
attributes="m1 m2"/>
</class>
- <class class="%s">
- <require like_class="%s" />
+ <class class="{}">
+ <require like_class="{}" />
</class>
- ''' % (_pfx("test_base"), P1,
- _pfx("test_class"), _pfx("test_base")))
+ '''.format(_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)
def testMimicAsDefault(self):
- declaration = ('''<class class="%s">
+ declaration = (
+ '''<class class="{}">
<require
- permission="%s"
+ permission="{}"
attributes="m1 m2"/>
</class>
- <class class="%s">
- <require like_class="%s" />
+ <class class="{}">
+ <require like_class="{}" />
<require
- permission="%s"
+ permission="{}"
attributes="m2 m3"/>
</class>
- ''' % (_pfx("test_base"), P1,
- _pfx("test_class"), _pfx("test_base"), P2))
+ '''.format(
+ _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,
@@ -565,8 +570,6 @@ class TestRequireDirective(unittest.TestCase):
def apply_declaration(declaration):
'''Apply the xmlconfig machinery.'''
from zope.configuration.xmlconfig import xmlconfig
- if isinstance(declaration, bytes):
- declaration = declaration.decode("utf-8") # pragma: no cover PY2
return xmlconfig(io.StringIO(declaration))
@@ -577,7 +580,7 @@ def make_dummy():
global IDummy
class IDummy(Interface):
- perm = zope.security.zcml.Permission(title=u'')
+ perm = zope.security.zcml.Permission(title='')
perms = []
diff --git a/src/zope/security/zcml.py b/src/zope/security/zcml.py
index 1f48138..d24e04d 100644
--- a/src/zope/security/zcml.py
+++ b/src/zope/security/zcml.py
@@ -33,13 +33,13 @@ class Permission(Id):
"""
def fromUnicode(self, value):
- u = super(Permission, self).fromUnicode(value)
+ u = super().fromUnicode(value)
map = getattr(self.context, 'permission_mapping', {})
return map.get(u, u)
def _validate(self, value):
- super(Permission, self)._validate(value)
+ super()._validate(value)
if value != zope_Public:
self.context.action(
@@ -61,8 +61,8 @@ 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="Component",
+ description="Pointer to the object that will handle the security.",
required=True)
@@ -78,22 +78,22 @@ 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="ID",
+ description="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="Title",
+ description="Provides a title for the object.",
required=True)
description = MessageID(
- title=u"Description",
- description=u"Provides a description for the object.",
+ title="Description",
+ description="Provides a description for the object.",
required=False)
-def permission(_context, id, title, description=u''):
+def permission(_context, id, title, description=''):
from zope.component.zcml import utility
from zope.security.interfaces import IPermission
@@ -106,13 +106,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="Original permission",
+ description="Original permission ID to redefine.",
required=True)
to = Permission(
- title=u"Substituted permission",
- description=u"Substituted permission ID.",
+ title="Substituted permission",
+ description="Substituted permission ID.",
required=True)
diff --git a/tox.ini b/tox.ini
index 761ba12..8a47458 100644
--- a/tox.ini
+++ b/tox.ini
@@ -4,31 +4,27 @@
minversion = 3.18
envlist =
lint
- py27,py27-pure
- py35,py35-pure
- py36,py36-pure
py37,py37-pure
py38,py38-pure
py39,py39-pure
py310,py310-pure
py311,py311-pure
- pypy
pypy3
docs
coverage
- py27-watch, py37-watch
+ py37-watch, py311-watch
[testenv]
usedevelop = true
deps =
setenv =
pure: PURE_PYTHON=1
- !pure-!pypy-!pypy3: PURE_PYTHON=0
+ !pure-!pypy3: PURE_PYTHON=0
ZOPE_INTERFACE_STRICT_IRO=1
watch: ZOPE_WATCH_CHECKERS=1
commands =
zope-testrunner --test-path=src {posargs:-vc}
- !py27-!pypy: sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest
+ sphinx-build -b doctest -d {envdir}/.cache/doctrees docs {envdir}/.cache/doctest
extras =
test
docs
@@ -64,6 +60,7 @@ deps =
[testenv:isort-apply]
basepython = python3
+skip_install = true
commands_pre =
deps =
isort