summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGES.rst12
-rw-r--r--CONTRIBUTORS.txt2
-rw-r--r--docs/narr/advanced-features.rst2
-rw-r--r--docs/narr/viewconfig.rst12
-rw-r--r--pyproject.toml8
-rw-r--r--src/pyramid/asset.py4
-rw-r--r--src/pyramid/authentication.py42
-rw-r--r--src/pyramid/authorization.py14
-rw-r--r--src/pyramid/config/__init__.py16
-rw-r--r--src/pyramid/config/actions.py8
-rw-r--r--src/pyramid/config/adapters.py2
-rw-r--r--src/pyramid/config/assets.py16
-rw-r--r--src/pyramid/config/factories.py8
-rw-r--r--src/pyramid/config/i18n.py2
-rw-r--r--src/pyramid/config/routes.py19
-rw-r--r--src/pyramid/config/security.py2
-rw-r--r--src/pyramid/config/settings.py4
-rw-r--r--src/pyramid/config/views.py27
-rw-r--r--src/pyramid/config/zca.py4
-rw-r--r--src/pyramid/csrf.py18
-rw-r--r--src/pyramid/decorator.py2
-rw-r--r--src/pyramid/events.py10
-rw-r--r--src/pyramid/exceptions.py9
-rw-r--r--src/pyramid/i18n.py6
-rw-r--r--src/pyramid/interfaces.py244
-rw-r--r--src/pyramid/paster.py6
-rw-r--r--src/pyramid/path.py6
-rw-r--r--src/pyramid/predicates.py13
-rw-r--r--src/pyramid/registry.py6
-rw-r--r--src/pyramid/renderers.py20
-rw-r--r--src/pyramid/request.py4
-rw-r--r--src/pyramid/response.py6
-rw-r--r--src/pyramid/scripting.py6
-rw-r--r--src/pyramid/scripts/pserve.py14
-rw-r--r--src/pyramid/scripts/pviews.py19
-rw-r--r--src/pyramid/security.py9
-rw-r--r--src/pyramid/session.py4
-rw-r--r--src/pyramid/settings.py16
-rw-r--r--src/pyramid/static.py5
-rw-r--r--src/pyramid/testing.py12
-rw-r--r--src/pyramid/traversal.py14
-rw-r--r--src/pyramid/tweens.py2
-rw-r--r--src/pyramid/url.py4
-rw-r--r--src/pyramid/util.py18
-rw-r--r--src/pyramid/view.py40
-rw-r--r--src/pyramid/wsgi.py4
-rw-r--r--tests/pkgs/defpermbugapp/__init__.py2
-rw-r--r--tests/pkgs/fixtureapp/__init__.py2
-rw-r--r--tests/test_authentication.py24
-rw-r--r--tests/test_authorization.py91
-rw-r--r--tests/test_config/test_actions.py11
-rw-r--r--tests/test_config/test_adapters.py24
-rw-r--r--tests/test_config/test_assets.py4
-rw-r--r--tests/test_config/test_init.py69
-rw-r--r--tests/test_config/test_predicates.py55
-rw-r--r--tests/test_config/test_routes.py12
-rw-r--r--tests/test_config/test_security.py31
-rw-r--r--tests/test_config/test_settings.py4
-rw-r--r--tests/test_config/test_testing.py2
-rw-r--r--tests/test_config/test_tweens.py5
-rw-r--r--tests/test_config/test_views.py460
-rw-r--r--tests/test_docs.py8
-rw-r--r--tests/test_events.py31
-rw-r--r--tests/test_i18n.py4
-rw-r--r--tests/test_integration.py10
-rw-r--r--tests/test_path.py25
-rw-r--r--tests/test_predicates.py2
-rw-r--r--tests/test_registry.py8
-rw-r--r--tests/test_renderers.py8
-rw-r--r--tests/test_request.py8
-rw-r--r--tests/test_response.py1
-rw-r--r--tests/test_router.py268
-rw-r--r--tests/test_scripts/test_proutes.py41
-rw-r--r--tests/test_scripts/test_pviews.py59
-rw-r--r--tests/test_security.py42
-rw-r--r--tests/test_session.py3
-rw-r--r--tests/test_settings.py12
-rw-r--r--tests/test_testing.py16
-rw-r--r--tests/test_traversal.py17
-rw-r--r--tests/test_tweens.py2
-rw-r--r--tests/test_url.py16
-rw-r--r--tests/test_urldispatch.py6
-rw-r--r--tests/test_util.py6
-rw-r--r--tests/test_view.py6
-rw-r--r--tests/test_viewderivers.py11
-rw-r--r--tox.ini4
86 files changed, 1266 insertions, 865 deletions
diff --git a/CHANGES.rst b/CHANGES.rst
index 3bd14705d..753997bf4 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -4,6 +4,9 @@ unreleased
Features
--------
+- The ``aslist`` method now handles non-string object when flattening.
+ See https://github.com/Pylons/pyramid/pull/3594
+
- It is now possible to pass multiple values to the ``header`` predicate
for route and view configuration.
See https://github.com/Pylons/pyramid/pull/3576
@@ -19,10 +22,13 @@ Features
- ``pyramid.config.Configurator.set_security_policy``.
- ``pyramid.interfaces.ISecurityPolicy``
- ``pyramid.request.Request.authenticated_identity``.
+ - ``pyramid.request.Request.is_authenticated``
- ``pyramid.authentication.SessionAuthenticationHelper``
- ``pyramid.authorization.ACLHelper``
+ - ``is_authenticated=True/False`` predicate for route and view configs
- See https://github.com/Pylons/pyramid/pull/3465
+ See https://github.com/Pylons/pyramid/pull/3465 and
+ https://github.com/Pylons/pyramid/pull/3598
- Changed the default ``serializer`` on
``pyramid.session.SignedCookieSessionFactory`` to use
@@ -116,6 +122,10 @@ Features
are now importable from the ``pyramid.authorization`` namespace.
See https://github.com/Pylons/pyramid/pull/3563
+- ``pserve`` now outputs verbose messaging to `stderr` instead of `stdout`
+ to circumvent buffering issues that exist by default on `stdout`.
+ See https://github.com/Pylons/pyramid/pull/3593
+
Deprecations
------------
diff --git a/CONTRIBUTORS.txt b/CONTRIBUTORS.txt
index 550639ae0..d527b1a04 100644
--- a/CONTRIBUTORS.txt
+++ b/CONTRIBUTORS.txt
@@ -352,3 +352,5 @@ Contributors
- Andrea Borghi, 2019/11/11
- Sergey Maranchuk, 2020/04/18
+
+- Thibault Ravera, 2020/06/03 \ No newline at end of file
diff --git a/docs/narr/advanced-features.rst b/docs/narr/advanced-features.rst
index 6e819ff5b..6f3b4e11b 100644
--- a/docs/narr/advanced-features.rst
+++ b/docs/narr/advanced-features.rst
@@ -34,7 +34,7 @@ For our example above, you can do this instead:
.. code-block:: python
:linenos:
- @view_config(route_name="items", effective_principals=pyramid.authorization.Authenticated)
+ @view_config(route_name="items", is_authenticated=True)
def auth_view(request):
# do one thing
diff --git a/docs/narr/viewconfig.rst b/docs/narr/viewconfig.rst
index b43ebb93e..de82fc075 100644
--- a/docs/narr/viewconfig.rst
+++ b/docs/narr/viewconfig.rst
@@ -494,6 +494,15 @@ configured view.
.. versionadded:: 1.4a3
+``is_authenticated``
+ This value, if specified, must be either ``True`` or ``False``.
+ If it is specified and ``True``, only a request from an authenticated user, as
+ determined by the :term:`security policy` in use, will satisfy the predicate.
+ If it is specified and ``False``, only a request from a user who is not
+ authenticated will satisfy the predicate.
+
+ .. versionadded:: 2.0
+
``effective_principals``
If specified, this value should be a :term:`principal` identifier or a
sequence of principal identifiers. If the
@@ -505,6 +514,9 @@ configured view.
.. versionadded:: 1.4a4
+ .. deprecated:: 2.0
+ Use ``is_authenticated`` or a custom predicate.
+
``custom_predicates``
If ``custom_predicates`` is specified, it must be a sequence of references to
custom predicate callables. Custom predicates can be combined with
diff --git a/pyproject.toml b/pyproject.toml
index 6e28b2347..36187efd1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -18,14 +18,16 @@ exclude = '''
)/
'''
- # This next section only exists for people that have their editors
-# automatically call isort, black already sorts entries on its own when run.
+# This next section only exists for people that have their editors
+# automatically call isort.
[tool.isort]
+profile = "black"
multi_line_output = 3
+src_paths = ["src", "tests"]
+skip_glob = ["docs/*"]
include_trailing_comma = true
force_grid_wrap = false
combine_as_imports = true
-use_parenthesis = true
line_length = 79
force_sort_within_sections = true
no_lines_before = "THIRDPARTY"
diff --git a/src/pyramid/asset.py b/src/pyramid/asset.py
index b657bf68f..f5900f443 100644
--- a/src/pyramid/asset.py
+++ b/src/pyramid/asset.py
@@ -18,9 +18,9 @@ def resolve_asset_spec(spec, pname='__main__'):
def asset_spec_from_abspath(abspath, package):
- """ Try to convert an absolute path to a resource in a package to
+ """Try to convert an absolute path to a resource in a package to
a resource specification if possible; otherwise return the
- absolute path. """
+ absolute path."""
if getattr(package, '__name__', None) == '__main__':
return abspath
pp = package_path(package) + os.path.sep
diff --git a/src/pyramid/authentication.py b/src/pyramid/authentication.py
index d5c5f8426..8faf84d68 100644
--- a/src/pyramid/authentication.py
+++ b/src/pyramid/authentication.py
@@ -43,7 +43,7 @@ class CallbackAuthenticationPolicy:
return princid
def authenticated_userid(self, request):
- """ Return the authenticated userid or ``None``.
+ """Return the authenticated userid or ``None``.
If no callback is registered, this will be the same as
``unauthenticated_userid``.
@@ -95,7 +95,7 @@ class CallbackAuthenticationPolicy:
)
def effective_principals(self, request):
- """ A list of effective principals derived from request.
+ """A list of effective principals derived from request.
This will return a list of principals including, at least,
:data:`pyramid.authorization.Everyone`. If there is no authenticated
@@ -179,7 +179,7 @@ class CallbackAuthenticationPolicy:
@implementer(IAuthenticationPolicy)
class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
- """ A :app:`Pyramid` :term:`authentication policy` which
+ """A :app:`Pyramid` :term:`authentication policy` which
obtains data from the :mod:`repoze.who` 1.X WSGI 'API' (the
``repoze.who.identity`` key in the WSGI environment).
@@ -218,7 +218,7 @@ class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
return identifier
def authenticated_userid(self, request):
- """ Return the authenticated userid or ``None``.
+ """Return the authenticated userid or ``None``.
If no callback is registered, this will be the same as
``unauthenticated_userid``.
@@ -272,7 +272,7 @@ class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
return identity['repoze.who.userid']
def effective_principals(self, request):
- """ A list of effective principals derived from the identity.
+ """A list of effective principals derived from the identity.
This will return a list of principals including, at least,
:data:`pyramid.authorization.Everyone`. If there is no identity, or
@@ -345,7 +345,7 @@ class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
return effective_principals
def remember(self, request, userid, **kw):
- """ Store the ``userid`` as ``repoze.who.userid``.
+ """Store the ``userid`` as ``repoze.who.userid``.
The identity to authenticated to :mod:`repoze.who`
will contain the given userid as ``userid``, and
@@ -361,7 +361,7 @@ class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
return identifier.remember(environ, identity)
def forget(self, request):
- """ Forget the current authenticated user.
+ """Forget the current authenticated user.
Return headers that, if included in a response, will delete the
cookie responsible for tracking the current user.
@@ -376,7 +376,7 @@ class RepozeWho1AuthenticationPolicy(CallbackAuthenticationPolicy):
@implementer(IAuthenticationPolicy)
class RemoteUserAuthenticationPolicy(CallbackAuthenticationPolicy):
- """ A :app:`Pyramid` :term:`authentication policy` which
+ """A :app:`Pyramid` :term:`authentication policy` which
obtains data from the ``REMOTE_USER`` WSGI environment variable.
Constructor Arguments
@@ -415,13 +415,13 @@ class RemoteUserAuthenticationPolicy(CallbackAuthenticationPolicy):
return request.environ.get(self.environ_key)
def remember(self, request, userid, **kw):
- """ A no-op. The ``REMOTE_USER`` does not provide a protocol for
+ """A no-op. The ``REMOTE_USER`` does not provide a protocol for
remembering the user. This will be application-specific and can
be done somewhere else or in a subclass."""
return []
def forget(self, request):
- """ A no-op. The ``REMOTE_USER`` does not provide a protocol for
+ """A no-op. The ``REMOTE_USER`` does not provide a protocol for
forgetting the user. This will be application-specific and can
be done somewhere else or in a subclass."""
return []
@@ -571,7 +571,7 @@ class AuthTktAuthenticationPolicy(CallbackAuthenticationPolicy):
``samesite``
Default: ``'Lax'``. The 'samesite' option of the session cookie. Set
- the value to ``None`` to turn off the samesite option.
+ the value to the string ``'None'`` to turn off the samesite option.
.. versionchanged:: 1.4
@@ -637,7 +637,7 @@ class AuthTktAuthenticationPolicy(CallbackAuthenticationPolicy):
return result['userid']
def remember(self, request, userid, **kw):
- """ Accepts the following kw args: ``max_age=<int-seconds>,
+ """Accepts the following kw args: ``max_age=<int-seconds>,
``tokens=<sequence-of-ascii-strings>``.
Return a list of headers which will set appropriate cookies on
@@ -1046,7 +1046,7 @@ class AuthTktCookieHelper:
return headers
def identify(self, request):
- """ Return a dictionary with authentication information, or ``None``
+ """Return a dictionary with authentication information, or ``None``
if no valid auth_tkt is attached to ``request``"""
environ = request.environ
cookie = request.cookies.get(self.cookie_name)
@@ -1114,13 +1114,13 @@ class AuthTktCookieHelper:
return identity
def forget(self, request):
- """ Return a set of expires Set-Cookie headers, which will destroy
+ """Return a set of expires Set-Cookie headers, which will destroy
any existing auth_tkt cookie when attached to a response"""
request._authtkt_reissue_revoked = True
return self._get_cookies(request, None)
def remember(self, request, userid, max_age=None, tokens=()):
- """ Return a set of Set-Cookie headers; when set into a response,
+ """Return a set of Set-Cookie headers; when set into a response,
these headers will represent a valid authentication ticket.
``max_age``
@@ -1200,7 +1200,7 @@ class AuthTktCookieHelper:
@implementer(IAuthenticationPolicy)
class SessionAuthenticationPolicy(CallbackAuthenticationPolicy):
- """ A :app:`Pyramid` authentication policy which gets its data from the
+ """A :app:`Pyramid` authentication policy which gets its data from the
configured :term:`session`. For this authentication policy to work, you
will have to follow the instructions in the :ref:`sessions_chapter` to
configure a :term:`session factory`.
@@ -1247,7 +1247,7 @@ class SessionAuthenticationPolicy(CallbackAuthenticationPolicy):
class SessionAuthenticationHelper:
- """ A helper for use with a :term:`security policy` which stores user data
+ """A helper for use with a :term:`security policy` which stores user data
in the configured :term:`session`.
Constructor Arguments
@@ -1280,7 +1280,7 @@ class SessionAuthenticationHelper:
@implementer(IAuthenticationPolicy)
class BasicAuthAuthenticationPolicy(CallbackAuthenticationPolicy):
- """ A :app:`Pyramid` authentication policy which uses HTTP standard basic
+ """A :app:`Pyramid` authentication policy which uses HTTP standard basic
authentication protocol to authenticate users. To use this policy you will
need to provide a callback which checks the supplied user credentials
against your source of login data.
@@ -1338,14 +1338,14 @@ class BasicAuthAuthenticationPolicy(CallbackAuthenticationPolicy):
return credentials.username
def remember(self, request, userid, **kw):
- """ A no-op. Basic authentication does not provide a protocol for
+ """A no-op. Basic authentication does not provide a protocol for
remembering the user. Credentials are sent on every request.
"""
return []
def forget(self, request):
- """ Returns challenge headers. This should be attached to a response
+ """Returns challenge headers. This should be attached to a response
to indicate that credentials are required."""
return [('WWW-Authenticate', 'Basic realm="%s"' % self.realm)]
@@ -1366,7 +1366,7 @@ HTTPBasicCredentials = namedtuple(
def extract_http_basic_credentials(request):
- """ A helper function for extraction of HTTP Basic credentials
+ """A helper function for extraction of HTTP Basic credentials
from a given :term:`request`.
Returns a :class:`.HTTPBasicCredentials` 2-tuple with ``username`` and
diff --git a/src/pyramid/authorization.py b/src/pyramid/authorization.py
index f148fae32..eadd46f85 100644
--- a/src/pyramid/authorization.py
+++ b/src/pyramid/authorization.py
@@ -15,8 +15,8 @@ with warnings.catch_warnings():
from pyramid.security import (
ACLAllowed as _ACLAllowed,
ACLDenied as _ACLDenied,
- AllPermissionsList as _AllPermissionsList,
Allow,
+ AllPermissionsList as _AllPermissionsList,
Authenticated,
Deny,
Everyone,
@@ -48,7 +48,7 @@ DENY_ALL = (Deny, Everyone, ALL_PERMISSIONS) # api
@implementer(IAuthorizationPolicy)
class ACLAuthorizationPolicy:
- """ An :term:`authorization policy` which consults an :term:`ACL`
+ """An :term:`authorization policy` which consults an :term:`ACL`
object attached to a :term:`context` to determine authorization
information about a :term:`principal` or multiple principals.
This class is a wrapper around :class:`.ACLHelper`, refer to that class for
@@ -68,14 +68,14 @@ class ACLAuthorizationPolicy:
self.helper = ACLHelper()
def permits(self, context, principals, permission):
- """ Return an instance of
+ """Return an instance of
:class:`pyramid.authorization.ACLAllowed` instance if the policy
permits access, return an instance of
:class:`pyramid.authorization.ACLDenied` if not."""
return self.helper.permits(context, principals, permission)
def principals_allowed_by_permission(self, context, permission):
- """ Return the set of principals explicitly granted the
+ """Return the set of principals explicitly granted the
permission named ``permission`` according to the ACL directly
attached to the ``context`` as well as inherited ACLs based on
the :term:`lineage`."""
@@ -85,7 +85,7 @@ class ACLAuthorizationPolicy:
class ACLHelper:
- """ A helper for use with constructing a :term:`security policy` which
+ """A helper for use with constructing a :term:`security policy` which
consults an :term:`ACL` object attached to a :term:`context` to determine
authorization information about a :term:`principal` or multiple principals.
If the context is part of a :term:`lineage`, the context's parents are
@@ -94,7 +94,7 @@ class ACLHelper:
"""
def permits(self, context, principals, permission):
- """ Return an instance of :class:`pyramid.authorization.ACLAllowed` if
+ """Return an instance of :class:`pyramid.authorization.ACLAllowed` if
the ACL allows access a user with the given principals, return an
instance of :class:`pyramid.authorization.ACLDenied` if not.
@@ -152,7 +152,7 @@ class ACLHelper:
)
def principals_allowed_by_permission(self, context, permission):
- """ Return the set of principals explicitly granted the permission
+ """Return the set of principals explicitly granted the permission
named ``permission`` according to the ACL directly attached to the
``context`` as well as inherited ACLs based on the :term:`lineage`.
diff --git a/src/pyramid/config/__init__.py b/src/pyramid/config/__init__.py
index 3d05617ca..fa90f2dd2 100644
--- a/src/pyramid/config/__init__.py
+++ b/src/pyramid/config/__init__.py
@@ -334,7 +334,7 @@ class Configurator(
default_view_mapper=None,
exceptionresponse_view=default_exceptionresponse_view,
):
- """ When you pass a non-``None`` ``registry`` argument to the
+ """When you pass a non-``None`` ``registry`` argument to the
:term:`Configurator` constructor, no initial setup is performed
against the registry. This is because the registry you pass in may
have already been initialized for use under :app:`Pyramid` via a
@@ -450,7 +450,7 @@ class Configurator(
return '%s:%s' % (package, filename)
def _fix_registry(self):
- """ Fix up a ZCA component registry that is not a
+ """Fix up a ZCA component registry that is not a
pyramid.registry.Registry by adding analogues of ``has_listeners``,
``notify``, ``queryAdapterOrSelf``, and ``registerSelfAdapter``
through monkey-patching."""
@@ -714,7 +714,7 @@ class Configurator(
return m
def with_package(self, package):
- """ Return a new Configurator instance with the same registry
+ """Return a new Configurator instance with the same registry
as this configurator. ``package`` may be an actual Python package
object or a :term:`dotted Python name` representing a package."""
configurator = self.__class__(
@@ -731,7 +731,7 @@ class Configurator(
return configurator
def maybe_dotted(self, dotted):
- """ Resolve the :term:`dotted Python name` ``dotted`` to a
+ """Resolve the :term:`dotted Python name` ``dotted`` to a
global Python object. If ``dotted`` is not a string, return
it without attempting to do any name resolution. If
``dotted`` is a relative dotted name (e.g. ``.foo.bar``,
@@ -740,7 +740,7 @@ class Configurator(
return self.name_resolver.maybe_resolve(dotted)
def absolute_asset_spec(self, relative_spec):
- """ Resolve the potentially relative :term:`asset
+ """Resolve the potentially relative :term:`asset
specification` string passed as ``relative_spec`` into an
absolute asset specification string and return the string.
Use the ``package`` of this configurator as the package to
@@ -755,7 +755,7 @@ class Configurator(
absolute_resource_spec = absolute_asset_spec # b/w compat forever
def begin(self, request=_marker):
- """ Indicate that application or test configuration has begun.
+ """Indicate that application or test configuration has begun.
This pushes a dictionary containing the :term:`application
registry` implied by ``registry`` attribute of this
configurator and the :term:`request` implied by the
@@ -781,7 +781,7 @@ class Configurator(
self.manager.push({'registry': self.registry, 'request': request})
def end(self):
- """ Indicate that application or test configuration has ended.
+ """Indicate that application or test configuration has ended.
This pops the last value pushed onto the :term:`thread local`
stack (usually by the ``begin`` method) and returns that
value.
@@ -882,7 +882,7 @@ class Configurator(
)
def make_wsgi_app(self):
- """ Commits any pending configuration statements, sends a
+ """Commits any pending configuration statements, sends a
:class:`pyramid.events.ApplicationCreated` event to all listeners,
adds this configuration's registry to
:attr:`pyramid.config.global_registries`, and returns a
diff --git a/src/pyramid/config/actions.py b/src/pyramid/config/actions.py
index b19f35b9b..e13358ce9 100644
--- a/src/pyramid/config/actions.py
+++ b/src/pyramid/config/actions.py
@@ -37,7 +37,7 @@ class ActionConfiguratorMixin:
introspectables=(),
**extra
):
- """ Register an action which will be executed when
+ """Register an action which will be executed when
:meth:`pyramid.config.Configurator.commit` is called (or executed
immediately if ``autocommit`` is ``True``).
@@ -187,8 +187,8 @@ class ActionState:
introspectables=(),
**extra
):
- """Add an action with the given discriminator, callable and arguments
- """
+ """Add an action with the given discriminator, callable, and
+ arguments"""
if kw is None:
kw = {}
action = extra
@@ -541,7 +541,7 @@ class ActionInfo:
def action_method(wrapped):
- """ Wrapper to provide the right conflict info report data when a method
+ """Wrapper to provide the right conflict info report data when a method
that calls Configurator.action calls another that does the same. Not a
documented API but used by some external systems."""
diff --git a/src/pyramid/config/adapters.py b/src/pyramid/config/adapters.py
index 5035651cb..a64c251ca 100644
--- a/src/pyramid/config/adapters.py
+++ b/src/pyramid/config/adapters.py
@@ -161,7 +161,7 @@ class AdaptersConfiguratorMixin:
@action_method
def add_response_adapter(self, adapter, type_or_iface):
- """ When an object of type (or interface) ``type_or_iface`` is
+ """When an object of type (or interface) ``type_or_iface`` is
returned from a view callable, Pyramid will use the adapter
``adapter`` to convert it into an object which implements the
:class:`pyramid.interfaces.IResponse` interface. If ``adapter`` is
diff --git a/src/pyramid/config/assets.py b/src/pyramid/config/assets.py
index 0522f8d2d..0dd7cf2c2 100644
--- a/src/pyramid/config/assets.py
+++ b/src/pyramid/config/assets.py
@@ -20,7 +20,7 @@ class OverrideProvider(pkg_resources.DefaultProvider):
return overrides
def get_resource_filename(self, manager, resource_name):
- """ Return a true filesystem path for resource_name,
+ """Return a true filesystem path for resource_name,
co-ordinating the extraction with manager, if the resource
must be unpacked to the filesystem.
"""
@@ -164,23 +164,19 @@ class PackageOverrides:
return self._real_loader
def get_data(self, path):
- """ See IPEP302Loader.
- """
+ """See IPEP302Loader."""
return self.real_loader.get_data(path)
def is_package(self, fullname):
- """ See IPEP302Loader.
- """
+ """See IPEP302Loader."""
return self.real_loader.is_package(fullname)
def get_code(self, fullname):
- """ See IPEP302Loader.
- """
+ """See IPEP302Loader."""
return self.real_loader.get_code(fullname)
def get_source(self, fullname):
- """ See IPEP302Loader.
- """
+ """See IPEP302Loader."""
return self.real_loader.get_source(fullname)
@@ -321,7 +317,7 @@ class AssetsConfiguratorMixin:
@action_method
def override_asset(self, to_override, override_with, _override=None):
- """ Add a :app:`Pyramid` asset override to the current
+ """Add a :app:`Pyramid` asset override to the current
configuration state.
``to_override`` is an :term:`asset specification` to the
diff --git a/src/pyramid/config/factories.py b/src/pyramid/config/factories.py
index 9636d0bad..9e1d3a747 100644
--- a/src/pyramid/config/factories.py
+++ b/src/pyramid/config/factories.py
@@ -18,7 +18,7 @@ from pyramid.util import InstancePropertyHelper, get_callable_name
class FactoriesConfiguratorMixin:
@action_method
def set_root_factory(self, factory):
- """ Add a :term:`root factory` to the current configuration
+ """Add a :term:`root factory` to the current configuration
state. If the ``factory`` argument is ``None`` a default root
factory will be registered.
@@ -76,7 +76,7 @@ class FactoriesConfiguratorMixin:
@action_method
def set_request_factory(self, factory):
- """ The object passed as ``factory`` should be an object (or a
+ """The object passed as ``factory`` should be an object (or a
:term:`dotted Python name` which refers to an object) which
will be used by the :app:`Pyramid` router to create all
request objects. This factory object must have the same
@@ -110,7 +110,7 @@ class FactoriesConfiguratorMixin:
@action_method
def set_response_factory(self, factory):
- """ The object passed as ``factory`` should be an object (or a
+ """The object passed as ``factory`` should be an object (or a
:term:`dotted Python name` which refers to an object) which
will be used by the :app:`Pyramid` as the default response
objects. The factory should conform to the
@@ -140,7 +140,7 @@ class FactoriesConfiguratorMixin:
def add_request_method(
self, callable=None, name=None, property=False, reify=False
):
- """ Add a property or method to the request object.
+ """Add a property or method to the request object.
When adding a method to the request, ``callable`` may be any
function that receives the request object as the first
diff --git a/src/pyramid/config/i18n.py b/src/pyramid/config/i18n.py
index f4bea0d71..d70a8f25a 100644
--- a/src/pyramid/config/i18n.py
+++ b/src/pyramid/config/i18n.py
@@ -45,7 +45,7 @@ class I18NConfiguratorMixin:
@action_method
def add_translation_dirs(self, *specs, **kw):
- """ Add one or more :term:`translation directory` paths to the
+ """Add one or more :term:`translation directory` paths to the
current configuration state. The ``specs`` argument is a
sequence that may contain absolute directory paths
(e.g. ``/usr/share/locale``) or :term:`asset specification`
diff --git a/src/pyramid/config/routes.py b/src/pyramid/config/routes.py
index a12e18fa8..4ebae89cc 100644
--- a/src/pyramid/config/routes.py
+++ b/src/pyramid/config/routes.py
@@ -40,7 +40,7 @@ class RoutesConfiguratorMixin:
inherit_slash=None,
**predicates
):
- """ Add a :term:`route configuration` to the current configuration
+ """Add a :term:`route configuration` to the current configuration
state. Arguments to ``add_route`` are divided into *predicate*
and *non-predicate* types. :term:`Route predicate` arguments
narrow the circumstances in which a route will match a
@@ -268,6 +268,17 @@ class RoutesConfiguratorMixin:
Removed support for media ranges.
+ is_authenticated
+
+ This value, if specified, must be either ``True`` or ``False``.
+ If it is specified and ``True``, only a request from an authenticated
+ user, as determined by the :term:`security policy` in use, will
+ satisfy the predicate.
+ If it is specified and ``False``, only a request from a user who is
+ not authenticated will satisfy the predicate.
+
+ .. versionadded:: 2.0
+
effective_principals
If specified, this value should be a :term:`principal` identifier or
@@ -282,6 +293,7 @@ class RoutesConfiguratorMixin:
.. versionadded:: 1.4a4
.. deprecated:: 2.0
+ Use ``is_authenticated`` or a custom predicate.
custom_predicates
@@ -505,7 +517,7 @@ class RoutesConfiguratorMixin:
def add_route_predicate(
self, name, factory, weighs_more_than=None, weighs_less_than=None
):
- """ Adds a route predicate factory. The view predicate can later be
+ """Adds a route predicate factory. The view predicate can later be
named as a keyword argument to
:meth:`pyramid.config.Configurator.add_route`.
@@ -537,6 +549,7 @@ class RoutesConfiguratorMixin:
('request_param', p.RequestParamPredicate),
('header', p.HeaderPredicate),
('accept', p.AcceptPredicate),
+ ('is_authenticated', p.IsAuthenticatedPredicate),
('effective_principals', p.EffectivePrincipalsPredicate),
('custom', p.CustomPredicate),
('traverse', p.TraversePredicate),
@@ -544,7 +557,7 @@ class RoutesConfiguratorMixin:
self.add_route_predicate(name, factory)
def get_routes_mapper(self):
- """ Return the :term:`routes mapper` object associated with
+ """Return the :term:`routes mapper` object associated with
this configurator's :term:`registry`."""
mapper = self.registry.queryUtility(IRoutesMapper)
if mapper is None:
diff --git a/src/pyramid/config/security.py b/src/pyramid/config/security.py
index a661bef96..8939cf62e 100644
--- a/src/pyramid/config/security.py
+++ b/src/pyramid/config/security.py
@@ -24,7 +24,7 @@ class SecurityConfiguratorMixin:
@action_method
def set_security_policy(self, policy):
- """ Override the :app:`Pyramid` :term:`security policy` in the current
+ """Override the :app:`Pyramid` :term:`security policy` in the current
configuration. The ``policy`` argument must be an instance
of a security policy or a :term:`dotted Python name`
that points at an instance of a security policy.
diff --git a/src/pyramid/config/settings.py b/src/pyramid/config/settings.py
index 076c455d4..3ed0bbccd 100644
--- a/src/pyramid/config/settings.py
+++ b/src/pyramid/config/settings.py
@@ -46,12 +46,12 @@ class SettingsConfiguratorMixin:
.. note:: the :attr:`pyramid.registry.Registry.settings` API
performs the same duty.
- """
+ """
return self.registry.settings
def Settings(d=None, _environ_=os.environ, **kw):
- """ Deployment settings. Update application settings (usually
+ """Deployment settings. Update application settings (usually
from PasteDeploy keywords) with framework-specific key/value pairs
(e.g. find ``PYRAMID_DEBUG_AUTHORIZATION`` in os.environ and jam into
keyword args)."""
diff --git a/src/pyramid/config/views.py b/src/pyramid/config/views.py
index a064ebd05..0d0002f83 100644
--- a/src/pyramid/config/views.py
+++ b/src/pyramid/config/views.py
@@ -204,7 +204,7 @@ def predicated_view(view, info):
def viewdefaults(wrapped):
- """ Decorator for add_view-like methods which takes into account
+ """Decorator for add_view-like methods which takes into account
__view_defaults__ attached to view it is passed. Not a documented API but
used by some external systems."""
@@ -266,7 +266,7 @@ class ViewsConfiguratorMixin:
exception_only=False,
**view_options
):
- """ Add a :term:`view configuration` to the current
+ """Add a :term:`view configuration` to the current
configuration state. Arguments to ``add_view`` are broken
down below into *predicate* arguments and *non-predicate*
arguments. Predicate arguments narrow the circumstances in
@@ -712,6 +712,17 @@ class ViewsConfiguratorMixin:
.. versionadded:: 1.4a3
+ is_authenticated
+
+ This value, if specified, must be either ``True`` or ``False``.
+ If it is specified and ``True``, only a request from an authenticated
+ user, as determined by the :term:`security policy` in use, will
+ satisfy the predicate.
+ If it is specified and ``False``, only a request from a user who is
+ not authenticated will satisfy the predicate.
+
+ .. versionadded:: 2.0
+
effective_principals
If specified, this value should be a :term:`principal` identifier or
@@ -726,6 +737,7 @@ class ViewsConfiguratorMixin:
.. versionadded:: 1.4a4
.. deprecated:: 2.0
+ Use ``is_authenticated`` or a custom predicate.
custom_predicates
@@ -1205,6 +1217,7 @@ class ViewsConfiguratorMixin:
('request_type', p.RequestTypePredicate),
('match_param', p.MatchParamPredicate),
('physical_path', p.PhysicalPathPredicate),
+ ('is_authenticated', p.IsAuthenticatedPredicate),
('effective_principals', p.EffectivePrincipalsPredicate),
('custom', p.CustomPredicate),
):
@@ -1505,7 +1518,7 @@ class ViewsConfiguratorMixin:
a :term:`renderer` to convert the user-supplied view result to
a :term:`response` object. If a ``renderer`` argument is not
supplied, the user-supplied view must itself return a
- :term:`response` object. """
+ :term:`response` object."""
return self._derive_view(view, attr=attr, renderer=renderer)
# b/w compat
@@ -1600,7 +1613,7 @@ class ViewsConfiguratorMixin:
match_param=None,
**view_options
):
- """ Add a forbidden view to the current configuration state. The
+ """Add a forbidden view to the current configuration state. The
view will be called when Pyramid or application code raises a
:exc:`pyramid.httpexceptions.HTTPForbidden` exception and the set of
circumstances implied by the predicates provided are matched. The
@@ -1701,7 +1714,7 @@ class ViewsConfiguratorMixin:
append_slash=False,
**view_options
):
- """ Add a default :term:`Not Found View` to the current configuration
+ """Add a default :term:`Not Found View` to the current configuration
state. The view will be called when Pyramid or application code raises
an :exc:`pyramid.httpexceptions.HTTPNotFound` exception (e.g., when a
view cannot be found for the request). The simplest example is:
@@ -1839,7 +1852,7 @@ class ViewsConfiguratorMixin:
# force all other arguments to be specified as key=value
**view_options
):
- """ Add an :term:`exception view` for the specified ``exception`` to
+ """Add an :term:`exception view` for the specified ``exception`` to
the current configuration state. The view will be called when Pyramid
or application code raises the given exception.
@@ -1925,7 +1938,7 @@ class ViewsConfiguratorMixin:
@action_method
def add_static_view(self, name, path, **kw):
- """ Add a view used to render static assets such as images
+ """Add a view used to render static assets such as images
and CSS files.
The ``name`` argument is a string representing an
diff --git a/src/pyramid/config/zca.py b/src/pyramid/config/zca.py
index 69b65a8eb..aec38b885 100644
--- a/src/pyramid/config/zca.py
+++ b/src/pyramid/config/zca.py
@@ -3,7 +3,7 @@ from pyramid.threadlocal import get_current_registry
class ZCAConfiguratorMixin:
def hook_zca(self):
- """ Call :func:`zope.component.getSiteManager.sethook` with the
+ """Call :func:`zope.component.getSiteManager.sethook` with the
argument :data:`pyramid.threadlocal.get_current_registry`, causing
the :term:`Zope Component Architecture` 'global' APIs such as
:func:`zope.component.getSiteManager`,
@@ -15,7 +15,7 @@ class ZCAConfiguratorMixin:
getSiteManager.sethook(get_current_registry)
def unhook_zca(self):
- """ Call :func:`zope.component.getSiteManager.reset` to undo the
+ """Call :func:`zope.component.getSiteManager.reset` to undo the
action of :meth:`pyramid.config.Configurator.hook_zca`."""
from zope.component import getSiteManager
diff --git a/src/pyramid/csrf.py b/src/pyramid/csrf.py
index 4c3689714..7f4f72f44 100644
--- a/src/pyramid/csrf.py
+++ b/src/pyramid/csrf.py
@@ -17,7 +17,7 @@ from pyramid.util import (
@implementer(ICSRFStoragePolicy)
class LegacySessionCSRFStoragePolicy:
- """ A CSRF storage policy that defers control of CSRF storage to the
+ """A CSRF storage policy that defers control of CSRF storage to the
session.
This policy maintains compatibility with legacy ISession implementations
@@ -36,7 +36,7 @@ class LegacySessionCSRFStoragePolicy:
return request.session.new_csrf_token()
def get_csrf_token(self, request):
- """ Returns the currently active CSRF token from the session,
+ """Returns the currently active CSRF token from the session,
generating a new one if needed."""
return request.session.get_csrf_token()
@@ -50,7 +50,7 @@ class LegacySessionCSRFStoragePolicy:
@implementer(ICSRFStoragePolicy)
class SessionCSRFStoragePolicy:
- """ A CSRF storage policy that persists the CSRF token in the session.
+ """A CSRF storage policy that persists the CSRF token in the session.
Note that using this CSRF implementation requires that
a :term:`session factory` is configured.
@@ -76,7 +76,7 @@ class SessionCSRFStoragePolicy:
return token
def get_csrf_token(self, request):
- """ Returns the currently active CSRF token from the session,
+ """Returns the currently active CSRF token from the session,
generating a new one if needed."""
token = request.session.get(self.key, None)
if not token:
@@ -93,7 +93,7 @@ class SessionCSRFStoragePolicy:
@implementer(ICSRFStoragePolicy)
class CookieCSRFStoragePolicy:
- """ An alternative CSRF implementation that stores its information in
+ """An alternative CSRF implementation that stores its information in
unauthenticated cookies, known as the 'Double Submit Cookie' method in the
`OWASP CSRF guidelines
<https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie>`_.
@@ -145,7 +145,7 @@ class CookieCSRFStoragePolicy:
return token
def get_csrf_token(self, request):
- """ Returns the currently active CSRF token by checking the cookies
+ """Returns the currently active CSRF token by checking the cookies
sent with the current request."""
bound_cookies = self.cookie_profile.bind(request)
token = bound_cookies.get_value()
@@ -162,7 +162,7 @@ class CookieCSRFStoragePolicy:
def get_csrf_token(request):
- """ Get the currently active CSRF token for the request passed, generating
+ """Get the currently active CSRF token for the request passed, generating
a new one using ``new_csrf_token(request)`` if one does not exist. This
calls the equivalent method in the chosen CSRF protection implementation.
@@ -175,7 +175,7 @@ def get_csrf_token(request):
def new_csrf_token(request):
- """ Generate a new CSRF token for the request passed and persist it in an
+ """Generate a new CSRF token for the request passed and persist it in an
implementation defined manner. This calls the equivalent method in the
chosen CSRF protection implementation.
@@ -190,7 +190,7 @@ def new_csrf_token(request):
def check_csrf_token(
request, token='csrf_token', header='X-CSRF-Token', raises=True
):
- """ Check the CSRF token returned by the
+ """Check the CSRF token returned by the
:class:`pyramid.interfaces.ICSRFStoragePolicy` implementation against the
value in ``request.POST.get(token)`` (if a POST request) or
``request.headers.get(header)``. If a ``token`` keyword is not supplied to
diff --git a/src/pyramid/decorator.py b/src/pyramid/decorator.py
index 82579182a..56c74c5b6 100644
--- a/src/pyramid/decorator.py
+++ b/src/pyramid/decorator.py
@@ -2,7 +2,7 @@ from functools import update_wrapper
class reify:
- """ Use as a class method decorator. It operates almost exactly like the
+ """Use as a class method decorator. It operates almost exactly like the
Python ``@property`` decorator, but it puts the result of the method it
decorates into the instance dict after the first call, effectively
replacing the function it decorates with an instance variable. It is, in
diff --git a/src/pyramid/events.py b/src/pyramid/events.py
index 86e7c3454..648f5ce98 100644
--- a/src/pyramid/events.py
+++ b/src/pyramid/events.py
@@ -12,7 +12,7 @@ from pyramid.interfaces import (
class subscriber:
- """ Decorator activated via a :term:`scan` which treats the function
+ """Decorator activated via a :term:`scan` which treats the function
being decorated as an event subscriber for the set of interfaces passed
as ``*ifaces`` and the set of predicate terms passed as ``**predicates``
to the decorator constructor.
@@ -112,7 +112,7 @@ class subscriber:
@implementer(INewRequest)
class NewRequest:
- """ An instance of this class is emitted as an :term:`event`
+ """An instance of this class is emitted as an :term:`event`
whenever :app:`Pyramid` begins to process a new request. The
event instance has an attribute, ``request``, which is a
:term:`request` object. This event class implements the
@@ -124,7 +124,7 @@ class NewRequest:
@implementer(INewResponse)
class NewResponse:
- """ An instance of this class is emitted as an :term:`event`
+ """An instance of this class is emitted as an :term:`event`
whenever any :app:`Pyramid` :term:`view` or :term:`exception
view` returns a :term:`response`.
@@ -183,7 +183,7 @@ class BeforeTraversal:
@implementer(IContextFound)
class ContextFound:
- """ An instance of this class is emitted as an :term:`event` after
+ """An instance of this class is emitted as an :term:`event` after
the :app:`Pyramid` :term:`router` finds a :term:`context`
object (after it performs traversal) but before any view code is
executed. The instance has an attribute, ``request``, which is
@@ -212,7 +212,7 @@ AfterTraversal = ContextFound # b/c as of 1.0
@implementer(IApplicationCreated)
class ApplicationCreated:
- """ An instance of this class is emitted as an :term:`event` when
+ """An instance of this class is emitted as an :term:`event` when
the :meth:`pyramid.config.Configurator.make_wsgi_app` is
called. The instance has an attribute, ``app``, which is an
instance of the :term:`router` that will handle WSGI requests.
diff --git a/src/pyramid/exceptions.py b/src/pyramid/exceptions.py
index 122209d48..a82463498 100644
--- a/src/pyramid/exceptions.py
+++ b/src/pyramid/exceptions.py
@@ -77,12 +77,12 @@ class URLDecodeError(UnicodeDecodeError):
class ConfigurationError(Exception):
- """ Raised when inappropriate input values are supplied to an API
+ """Raised when inappropriate input values are supplied to an API
method of a :term:`Configurator`"""
class ConfigurationConflictError(ConfigurationError):
- """ Raised when a configuration conflict is detected during action
+ """Raised when a configuration conflict is detected during action
processing"""
def __init__(self, conflicts):
@@ -100,8 +100,7 @@ class ConfigurationConflictError(ConfigurationError):
class ConfigurationExecutionError(ConfigurationError):
- """An error occurred during execution of a configuration action
- """
+ """An error occurred during execution of a configuration action"""
def __init__(self, etype, evalue, info):
self.etype, self.evalue, self.info = etype, evalue, info
@@ -111,7 +110,7 @@ class ConfigurationExecutionError(ConfigurationError):
class CyclicDependencyError(Exception):
- """ The exception raised when the Pyramid topological sorter detects a
+ """The exception raised when the Pyramid topological sorter detects a
cyclic dependency."""
def __init__(self, cycles):
diff --git a/src/pyramid/i18n.py b/src/pyramid/i18n.py
index 8bf091c58..29ab395ef 100644
--- a/src/pyramid/i18n.py
+++ b/src/pyramid/i18n.py
@@ -112,7 +112,7 @@ class Localizer:
def default_locale_negotiator(request):
- """ The default :term:`locale negotiator`. Returns a locale name
+ """The default :term:`locale negotiator`. Returns a locale name
or ``None``.
- First, the negotiator looks for the ``_LOCALE_`` attribute of
@@ -139,7 +139,7 @@ def default_locale_negotiator(request):
def negotiate_locale_name(request):
- """ Negotiate and return the :term:`locale name` associated with
+ """Negotiate and return the :term:`locale name` associated with
the current request."""
try:
registry = request.registry
@@ -167,7 +167,7 @@ def get_locale_name(request):
def make_localizer(current_locale_name, translation_directories):
- """ Create a :class:`pyramid.i18n.Localizer` object
+ """Create a :class:`pyramid.i18n.Localizer` object
corresponding to the provided locale name from the
translations found in the list of translation directories."""
translations = Translations()
diff --git a/src/pyramid/interfaces.py b/src/pyramid/interfaces.py
index e92662f11..ffac7f641 100644
--- a/src/pyramid/interfaces.py
+++ b/src/pyramid/interfaces.py
@@ -4,7 +4,7 @@ from zope.interface import Attribute, Interface
class IContextFound(Interface):
- """ An event type that is emitted after :app:`Pyramid` finds a
+ """An event type that is emitted after :app:`Pyramid` finds a
:term:`context` object but before it calls any view code. See the
documentation attached to :class:`pyramid.events.ContextFound`
for more information.
@@ -33,7 +33,7 @@ class IBeforeTraversal(Interface):
class INewRequest(Interface):
- """ An event type that is emitted whenever :app:`Pyramid`
+ """An event type that is emitted whenever :app:`Pyramid`
begins to process a new request. See the documentation attached
to :class:`pyramid.events.NewRequest` for more information."""
@@ -41,7 +41,7 @@ class INewRequest(Interface):
class INewResponse(Interface):
- """ An event type that is emitted whenever any :app:`Pyramid`
+ """An event type that is emitted whenever any :app:`Pyramid`
view returns a response. See the
documentation attached to :class:`pyramid.events.NewResponse`
for more information."""
@@ -51,7 +51,7 @@ class INewResponse(Interface):
class IApplicationCreated(Interface):
- """ Event issued when the
+ """Event issued when the
:meth:`pyramid.config.Configurator.make_wsgi_app` method
is called. See the documentation attached to
:class:`pyramid.events.ApplicationCreated` for more
@@ -71,7 +71,7 @@ IWSGIApplicationCreatedEvent = IApplicationCreated # b /c
class IResponse(Interface):
- """ Represents a WSGI response using the WebOb response interface.
+ """Represents a WSGI response using the WebOb response interface.
Some attribute and method documentation of this interface references
:rfc:`2616`.
@@ -84,7 +84,7 @@ class IResponse(Interface):
)
def __call__(environ, start_response):
- """ :term:`WSGI` call interface, should call the start_response
+ """:term:`WSGI` call interface, should call the start_response
callback and should return an iterable"""
accept_ranges = Attribute(
@@ -110,8 +110,18 @@ class IResponse(Interface):
)
def app_iter_range(start, stop):
- """ Return a new app_iter built from the response app_iter that
- serves up only the given start:stop range. """
+ """Return a new app_iter built from the response app_iter that
+ serves up only the given start:stop range."""
+
+ authenticated_identity = Attribute(
+ """An object representing the authenticated user, as determined by
+ the security policy in use, or ``None`` for unauthenticated requests.
+ The object's class and meaning is defined by the security policy."""
+ )
+
+ authenticated_userid = Attribute(
+ """A string to identify the authenticated user or ``None``."""
+ )
body = Attribute(
"""The body of the response, as a str. This will read in the entire
@@ -135,7 +145,7 @@ class IResponse(Interface):
charset = Attribute("""Get/set the charset (in the Content-Type)""")
def conditional_response_app(environ, start_response):
- """ Like the normal __call__ interface, but checks conditional
+ """Like the normal __call__ interface, but checks conditional
headers:
- If-Modified-Since (304 Not Modified; only on GET, HEAD)
@@ -205,12 +215,12 @@ class IResponse(Interface):
)
def delete_cookie(name, path='/', domain=None):
- """ Delete a cookie from the client. Note that path and domain must
+ """Delete a cookie from the client. Note that path and domain must
match how the cookie was originally set. This sets the cookie to the
- empty string, and max_age=0 so that it should expire immediately. """
+ empty string, and max_age=0 so that it should expire immediately."""
def encode_content(encoding='gzip', lazy=False):
- """ Encode the content with the given encoding (only gzip and
+ """Encode the content with the given encoding (only gzip and
identity are supported)."""
environ = Attribute(
@@ -233,6 +243,11 @@ class IResponse(Interface):
headers = Attribute(""" The headers in a dictionary-like object """)
+ is_authenticated = Attribute(
+ """A boolean indicating whether the request has an authenticated
+ user, as determined by the security policy in use."""
+ )
+
last_modified = Attribute(
""" Gets and sets and deletes the Last-Modified header. For more
information on Last-Modified see RFC 2616 section 14.29. Converts
@@ -245,15 +260,15 @@ class IResponse(Interface):
)
def md5_etag(body=None, set_content_md5=False):
- """ Generate an etag for the response object using an MD5 hash of the
+ """Generate an etag for the response object using an MD5 hash of the
body (the body parameter, or self.body if not given). Sets self.etag.
- If set_content_md5 is True sets self.content_md5 as well """
+ If set_content_md5 is True sets self.content_md5 as well"""
def merge_cookies(resp):
- """ Merge the cookies that were set on this response with the given
+ """Merge the cookies that were set on this response with the given
resp object (which can be any WSGI application). If the resp is a
webob.Response object, then the other object will be modified
- in-place. """
+ in-place."""
pragma = Attribute(
""" Gets and sets and deletes the Pragma header. For more information
@@ -299,7 +314,7 @@ class IResponse(Interface):
)
def unset_cookie(name, strict=True):
- """ Unset a cookie with the given name (remove it from the
+ """Unset a cookie with the given name (remove it from the
response)."""
vary = Attribute(
@@ -319,7 +334,7 @@ class IException(Interface): # not an API
class IExceptionResponse(IException, IResponse):
- """ An interface representing a WSGI response which is also an exception
+ """An interface representing a WSGI response which is also an exception
object. Register an exception view using this interface as a ``context``
to apply the registered view for all exception types raised by
:app:`Pyramid` internally (any exception that inherits from
@@ -341,18 +356,18 @@ class IDict(Interface):
""" Set a key/value pair into the dictionary"""
def __delitem__(k):
- """ Delete an item from the dictionary which is passed to the
+ """Delete an item from the dictionary which is passed to the
renderer as the renderer globals dictionary."""
def __getitem__(k):
- """ Return the value for key ``k`` from the dictionary or raise a
+ """Return the value for key ``k`` from the dictionary or raise a
KeyError if the key doesn't exist"""
def __iter__():
""" Return an iterator over the keys of this dictionary """
def get(k, default=None):
- """ Return the value for key ``k`` from the renderer dictionary, or
+ """Return the value for key ``k`` from the renderer dictionary, or
the default if no such value exists."""
def items():
@@ -365,20 +380,20 @@ class IDict(Interface):
""" Return a list of values from the dictionary """
def pop(k, default=None):
- """ Pop the key k from the dictionary and return its value. If k
+ """Pop the key k from the dictionary and return its value. If k
doesn't exist, and default is provided, return the default. If k
doesn't exist and default is not provided, raise a KeyError."""
def popitem():
- """ Pop the item with key k from the dictionary and return it as a
+ """Pop the item with key k from the dictionary and return it as a
two-tuple (k, v). If k doesn't exist, raise a KeyError."""
def setdefault(k, default=None):
- """ Return the existing value for key ``k`` in the dictionary. If no
- value with ``k`` exists in the dictionary, set the ``default``
- value into the dictionary under the k name passed. If a value already
- existed in the dictionary, return it. If a value did not exist in
- the dictionary, return the default"""
+ """Return the existing value for key ``k`` in the dictionary. If no
+ value with ``k`` exists in the dictionary, set the ``default``
+ value into the dictionary under the k name passed. If a value already
+ existed in the dictionary, return it. If a value did not exist in
+ the dictionary, return the default"""
def update(d):
""" Update the renderer dictionary with another dictionary ``d``."""
@@ -415,7 +430,7 @@ class IBeforeRender(IDict):
class IRendererInfo(Interface):
- """ An object implementing this interface is passed to every
+ """An object implementing this interface is passed to every
:term:`renderer factory` constructor as its only argument (conventionally
named ``info``)"""
@@ -439,7 +454,7 @@ class IRendererInfo(Interface):
class IRendererFactory(Interface):
def __call__(info):
- """ Return an object that implements
+ """Return an object that implements
:class:`pyramid.interfaces.IRenderer`. ``info`` is an
object that implements :class:`pyramid.interfaces.IRendererInfo`.
"""
@@ -447,7 +462,7 @@ class IRendererFactory(Interface):
class IRenderer(Interface):
def __call__(value, system):
- """ Call the renderer with the result of the
+ """Call the renderer with the result of the
view (``value``) passed in and return a result (a string or
unicode object useful as a response body). Values computed by
the system are passed by the system in the ``system``
@@ -461,7 +476,7 @@ class IRenderer(Interface):
class IViewMapper(Interface):
def __call__(self, object):
- """ Provided with an arbitrary object (a function, class, or
+ """Provided with an arbitrary object (a function, class, or
instance), returns a callable with the call signature ``(context,
request)``. The callable returned should itself return a Response
object. An IViewMapper is returned by
@@ -484,38 +499,38 @@ class IViewMapperFactory(Interface):
class ISecurityPolicy(Interface):
def authenticated_identity(request):
- """ Return the :term:`identity` of the current user. The object can be
+ """Return the :term:`identity` of the current user. The object can be
of any shape, such as a simple ID string or an ORM object.
"""
def authenticated_userid(request):
- """ Return a :term:`userid` string identifying the trusted and
+ """Return a :term:`userid` string identifying the trusted and
verified user, or ``None`` if unauthenticated.
"""
def permits(request, context, permission):
- """ Return an instance of :class:`pyramid.security.Allowed` if a user
+ """Return an instance of :class:`pyramid.security.Allowed` if a user
of the given identity is allowed the ``permission`` in the current
``context``, else return an instance of
:class:`pyramid.security.Denied`.
"""
def remember(request, userid, **kw):
- """ Return a set of headers suitable for 'remembering' the
+ """Return a set of headers suitable for 'remembering' the
:term:`userid` named ``userid`` when set in a response. An individual
security policy and its consumers can decide on the composition and
meaning of ``**kw``.
"""
def forget(request, **kw):
- """ Return a set of headers suitable for 'forgetting' the
+ """Return a set of headers suitable for 'forgetting' the
current user on subsequent requests. An individual security policy and
its consumers can decide on the composition and meaning of ``**kw``.
"""
class IAuthenticationPolicy(Interface):
- """ An object representing a Pyramid authentication policy.
+ """An object representing a Pyramid authentication policy.
.. deprecated:: 2.0
@@ -525,7 +540,7 @@ class IAuthenticationPolicy(Interface):
"""
def authenticated_userid(request):
- """ Return the authenticated :term:`userid` or ``None`` if
+ """Return the authenticated :term:`userid` or ``None`` if
no authenticated userid can be found. This method of the
policy should ensure that a record exists in whatever
persistent store is used related to the user (the user
@@ -536,7 +551,7 @@ class IAuthenticationPolicy(Interface):
"""
def unauthenticated_userid(request):
- """ Return the *unauthenticated* userid. This method
+ """Return the *unauthenticated* userid. This method
performs the same duty as ``authenticated_userid`` but is
permitted to return the userid based only on data present
in the request; it needn't (and shouldn't) check any
@@ -551,7 +566,7 @@ class IAuthenticationPolicy(Interface):
"""
def effective_principals(request):
- """ Return a sequence representing the effective principals
+ """Return a sequence representing the effective principals
typically including the :term:`userid` and any groups belonged
to by the current user, always including 'system' groups such
as ``pyramid.authorization.Everyone`` and
@@ -560,7 +575,7 @@ class IAuthenticationPolicy(Interface):
"""
def remember(request, userid, **kw):
- """ Return a set of headers suitable for 'remembering' the
+ """Return a set of headers suitable for 'remembering' the
:term:`userid` named ``userid`` when set in a response. An
individual authentication policy and its consumers can
decide on the composition and meaning of ``**kw``.
@@ -568,14 +583,14 @@ class IAuthenticationPolicy(Interface):
"""
def forget(request):
- """ Return a set of headers suitable for 'forgetting' the
+ """Return a set of headers suitable for 'forgetting' the
current user on subsequent requests.
"""
class IAuthorizationPolicy(Interface):
- """ An object representing a Pyramid authorization policy.
+ """An object representing a Pyramid authorization policy.
.. deprecated:: 2.0
@@ -585,14 +600,14 @@ class IAuthorizationPolicy(Interface):
"""
def permits(context, principals, permission):
- """ Return an instance of :class:`pyramid.security.Allowed` if any
+ """Return an instance of :class:`pyramid.security.Allowed` if any
of the ``principals`` is allowed the ``permission`` in the current
``context``, else return an instance of
:class:`pyramid.security.Denied`.
"""
def principals_allowed_by_permission(context, permission):
- """ Return a set of principal identifiers allowed by the
+ """Return a set of principal identifiers allowed by the
``permission`` in ``context``. This behavior is optional; if you
choose to not implement it you should define this method as
something which raises a ``NotImplementedError``. This method
@@ -620,24 +635,24 @@ class IMultiDict(IDict): # docs-only interface
"""
def extend(other=None, **kwargs):
- """ Add a set of keys and values, not overwriting any previous
+ """Add a set of keys and values, not overwriting any previous
values. The ``other`` structure may be a list of two-tuples or a
dictionary. If ``**kwargs`` is passed, its value *will* overwrite
existing values."""
def getall(key):
- """ Return a list of all values matching the key (may be an empty
- list) """
+ """Return a list of all values matching the key (may be an empty
+ list)"""
def getone(key):
- """ Get one value matching the key, raising a KeyError if multiple
- values were found. """
+ """Get one value matching the key, raising a KeyError if multiple
+ values were found."""
def mixed():
- """ Returns a dictionary where the values are either single values,
+ """Returns a dictionary where the values are either single values,
or a list of values when a key/value appears more than once in this
dictionary. This is similar to the kind of dictionary often used to
- represent the variables in a web request. """
+ represent the variables in a web request."""
# internal interfaces
@@ -648,7 +663,7 @@ class IRequest(Interface):
class ITweens(Interface):
- """ Marker interface for utility registration representing the ordered
+ """Marker interface for utility registration representing the ordered
set of a configuration's tween factories"""
@@ -656,7 +671,7 @@ class IRequestHandler(Interface):
""" """
def __call__(self, request):
- """ Must return a tuple of IReqest, IResponse or raise an exception.
+ """Must return a tuple of IReqest, IResponse or raise an exception.
The ``request`` argument will be an instance of an object that
provides IRequest."""
@@ -665,7 +680,7 @@ IRequest.combined = IRequest # for exception view lookups
class IRequestExtensions(Interface):
- """ Marker interface for storing request extensions (properties and
+ """Marker interface for storing request extensions (properties and
methods) which will be added to the request object."""
descriptors = Attribute(
@@ -675,7 +690,7 @@ class IRequestExtensions(Interface):
class IRouteRequest(Interface):
- """ *internal only* interface used as in a utility lookup to find
+ """*internal only* interface used as in a utility lookup to find
route-specific interfaces. Not an API."""
@@ -704,7 +719,7 @@ class IResponseFactory(Interface):
""" A utility which generates a response """
def __call__(request):
- """ Return a response object implementing IResponse,
+ """Return a response object implementing IResponse,
e.g. :class:`pyramid.response.Response`). It should handle the
case when ``request`` is ``None``."""
@@ -716,7 +731,7 @@ class IRequestFactory(Interface):
""" Return an instance of ``pyramid.request.Request``"""
def blank(path):
- """ Return an empty request object (see
+ """Return an empty request object (see
:meth:`pyramid.request.Request.blank`)"""
@@ -740,12 +755,12 @@ class ISecuredView(IView):
""" Guaranteed-permissive version of __call__ """
def __permitted__(context, request):
- """ Return True if view execution will be permitted using the
+ """Return True if view execution will be permitted using the
context and request, False otherwise"""
class IMultiView(ISecuredView):
- """ *internal only*. A multiview is a secured view that is a
+ """*internal only*. A multiview is a secured view that is a
collection of other views. Each of the views is associated with
zero or more predicates. Not an API."""
@@ -765,7 +780,7 @@ class IDefaultRootFactory(Interface):
class ITraverser(Interface):
def __call__(request):
- """ Return a dictionary with (at least) the keys ``root``,
+ """Return a dictionary with (at least) the keys ``root``,
``context``, ``view_name``, ``subpath``, ``traversed``,
``virtual_root``, and ``virtual_root_path``. These values are
typically the result of an object graph traversal. ``root`` is the
@@ -793,8 +808,7 @@ ITraverserFactory = ITraverser # b / c for 1.0 code
class IViewPermission(Interface):
def __call__(context, request):
- """ Return True if the permission allows, return False if it denies.
- """
+ """Return True if the permission allows, return False if it denies."""
class IRouter(Interface):
@@ -879,7 +893,7 @@ class IExecutionPolicy(Interface):
class ISettings(IDict):
- """ Runtime settings utility for pyramid; represents the
+ """Runtime settings utility for pyramid; represents the
deployment settings for the application. Implements a mapping
interface."""
@@ -903,7 +917,7 @@ ILogger = IDebugLogger # b/c
class IRoutePregenerator(Interface):
def __call__(request, elements, kw):
- """ A pregenerator is a function associated by a developer with a
+ """A pregenerator is a function associated by a developer with a
:term:`route`. The pregenerator for a route is called by
:meth:`pyramid.request.Request.route_url` in order to adjust the set
of arguments passed to it by the user for special purposes, such as
@@ -927,7 +941,7 @@ class IRoutePregenerator(Interface):
class IRoute(Interface):
- """ Interface representing the type of object returned from
+ """Interface representing the type of object returned from
``IRoutesMapper.get_route``"""
name = Attribute('The route name')
@@ -970,14 +984,14 @@ class IRoutesMapper(Interface):
""" Interface representing a Routes ``Mapper`` object """
def get_routes():
- """ Return a sequence of Route objects registered in the mapper.
+ """Return a sequence of Route objects registered in the mapper.
Static routes will not be returned in this sequence."""
def has_routes():
""" Returns ``True`` if any route has been registered. """
def get_route(name):
- """ Returns an ``IRoute`` object if a route with the name ``name``
+ """Returns an ``IRoute`` object if a route with the name ``name``
was registered, otherwise return ``None``."""
def connect(
@@ -991,15 +1005,15 @@ class IRoutesMapper(Interface):
""" Add a new route. """
def generate(name, kw):
- """ Generate a URL using the route named ``name`` with the
+ """Generate a URL using the route named ``name`` with the
keywords implied by kw"""
def __call__(request):
- """ Return a dictionary containing matching information for
+ """Return a dictionary containing matching information for
the request; the ``route`` key of this dictionary will either
be a Route object or ``None`` if no route matched; the
``match`` key will be the matchdict or ``None`` if no route
- matched. Static routes will not be considered for matching. """
+ matched. Static routes will not be considered for matching."""
class IResourceURL(Interface):
@@ -1018,11 +1032,10 @@ class IResourceURL(Interface):
class IPEP302Loader(Interface):
- """ See http://www.python.org/dev/peps/pep-0302/#id30.
- """
+ """See http://www.python.org/dev/peps/pep-0302/#id30."""
def get_data(path):
- """ Retrieve data for and arbitrary "files" from storage backend.
+ """Retrieve data for and arbitrary "files" from storage backend.
Raise IOError for not found.
@@ -1030,11 +1043,10 @@ class IPEP302Loader(Interface):
"""
def is_package(fullname):
- """ Return True if the module specified by 'fullname' is a package.
- """
+ """Return True if the module specified by 'fullname' is a package."""
def get_code(fullname):
- """ Return the code object for the module identified by 'fullname'.
+ """Return the code object for the module identified by 'fullname'.
Return 'None' if it's a built-in or extension module.
@@ -1045,7 +1057,7 @@ class IPEP302Loader(Interface):
"""
def get_source(fullname):
- """ Return the source code for the module identified by 'fullname'.
+ """Return the source code for the module identified by 'fullname'.
Return a string, using newline characters for line endings, or None
if the source is not available.
@@ -1054,7 +1066,7 @@ class IPEP302Loader(Interface):
"""
def get_filename(fullname):
- """ Return the value of '__file__' if the named module was loaded.
+ """Return the value of '__file__' if the named module was loaded.
If the module is not found, raise ImportError.
"""
@@ -1079,18 +1091,18 @@ class ILocaleNegotiator(Interface):
class ITranslationDirectories(Interface):
- """ A list object representing all known translation directories
+ """A list object representing all known translation directories
for an application"""
class IDefaultPermission(Interface):
- """ A string object representing the default permission to be used
+ """A string object representing the default permission to be used
for all view configurations which do not explicitly declare their
own."""
class IDefaultCSRFOptions(Interface):
- """ An object representing the default CSRF settings to be used for
+ """An object representing the default CSRF settings to be used for
all view configurations which do not explicitly declare their own."""
require_csrf = Attribute(
@@ -1108,15 +1120,15 @@ class IDefaultCSRFOptions(Interface):
class ISessionFactory(Interface):
- """ An interface representing a factory which accepts a request object and
- returns an ISession object """
+ """An interface representing a factory which accepts a request object and
+ returns an ISession object"""
def __call__(request):
""" Return an ISession object """
class ISession(IDict):
- """ An interface representing a session (a web session object,
+ """An interface representing a session (a web session object,
usually accessed via ``request.session``.
Keys and values of a session must be JSON-serializable.
@@ -1151,7 +1163,7 @@ class ISession(IDict):
# special methods
def invalidate():
- """ Invalidate the session. The action caused by
+ """Invalidate the session. The action caused by
``invalidate`` is implementation-dependent, but it should have
the effect of completely dissociating any data stored in the
session with the current request. It might set response
@@ -1164,7 +1176,7 @@ class ISession(IDict):
"""
def changed():
- """ Mark the session as changed. A user of a session should
+ """Mark the session as changed. A user of a session should
call this method after he or she mutates a mutable object that
is *a value of the session* (it should not be required after
mutating the session itself). For example, if the user has
@@ -1176,20 +1188,20 @@ class ISession(IDict):
internal dictionary."""
def flash(msg, queue='', allow_duplicate=True):
- """ Push a flash message onto the end of the flash queue represented
+ """Push a flash message onto the end of the flash queue represented
by ``queue``. An alternate flash message queue can used by passing
an optional ``queue``, which must be a string. If
``allow_duplicate`` is false, if the ``msg`` already exists in the
queue, it will not be re-added."""
def pop_flash(queue=''):
- """ Pop a queue from the flash storage. The queue is removed from
+ """Pop a queue from the flash storage. The queue is removed from
flash storage after this message is called. The queue is returned;
it is a list of flash messages added by
:meth:`pyramid.interfaces.ISession.flash`"""
def peek_flash(queue=''):
- """ Peek at a queue in the flash storage. The queue remains in
+ """Peek at a queue in the flash storage. The queue remains in
flash storage after this message is called. The queue is returned;
it is a list of flash messages added by
:meth:`pyramid.interfaces.ISession.flash`
@@ -1197,18 +1209,18 @@ class ISession(IDict):
class ICSRFStoragePolicy(Interface):
- """ An object that offers the ability to verify CSRF tokens and generate
+ """An object that offers the ability to verify CSRF tokens and generate
new ones."""
def new_csrf_token(request):
- """ Create and return a new, random cross-site request forgery
+ """Create and return a new, random cross-site request forgery
protection token. The token will be an ascii-compatible unicode
string.
"""
def get_csrf_token(request):
- """ Return a cross-site request forgery protection token. It
+ """Return a cross-site request forgery protection token. It
will be an ascii-compatible unicode string. If a token was previously
set for this user via ``new_csrf_token``, that token will be returned.
If no CSRF token was previously set, ``new_csrf_token`` will be
@@ -1218,7 +1230,7 @@ class ICSRFStoragePolicy(Interface):
"""
def check_csrf_token(request, token):
- """ Determine if the supplied ``token`` is valid. Most implementations
+ """Determine if the supplied ``token`` is valid. Most implementations
should simply compare the ``token`` to the current value of
``get_csrf_token`` but it is possible to verify the token using
any mechanism necessary using this method.
@@ -1230,12 +1242,12 @@ class ICSRFStoragePolicy(Interface):
class IIntrospector(Interface):
def get(category_name, discriminator, default=None):
- """ Get the IIntrospectable related to the category_name and the
+ """Get the IIntrospectable related to the category_name and the
discriminator (or discriminator hash) ``discriminator``. If it does
- not exist in the introspector, return the value of ``default`` """
+ not exist in the introspector, return the value of ``default``"""
def get_category(category_name, default=None, sort_key=None):
- """ Get a sequence of dictionaries in the form
+ """Get a sequence of dictionaries in the form
``[{'introspectable':IIntrospectable, 'related':[sequence of related
IIntrospectables]}, ...]`` where each introspectable is part of the
category associated with ``category_name`` .
@@ -1250,11 +1262,11 @@ class IIntrospector(Interface):
``sorted`` callable)."""
def categories():
- """ Return a sorted sequence of category names known by
- this introspector """
+ """Return a sorted sequence of category names known by
+ this introspector"""
def categorized(sort_key=None):
- """ Get a sequence of tuples in the form ``[(category_name,
+ """Get a sequence of tuples in the form ``[(category_name,
[{'introspectable':IIntrospectable, 'related':[sequence of related
IIntrospectables]}, ...])]`` representing all known
introspectables. If ``sort_key`` is ``None``, each introspectables
@@ -1264,19 +1276,19 @@ class IIntrospector(Interface):
``key`` function of Python's ``sorted`` callable)."""
def remove(category_name, discriminator):
- """ Remove the IIntrospectable related to ``category_name`` and
+ """Remove the IIntrospectable related to ``category_name`` and
``discriminator`` from the introspector, and fix up any relations
that the introspectable participates in. This method will not raise
an error if an introspectable related to the category name and
discriminator does not exist."""
def related(intr):
- """ Return a sequence of IIntrospectables related to the
+ """Return a sequence of IIntrospectables related to the
IIntrospectable ``intr``. Return the empty sequence if no relations
for exist."""
def add(intr):
- """ Add the IIntrospectable ``intr`` (use instead of
+ """Add the IIntrospectable ``intr`` (use instead of
:meth:`pyramid.interfaces.IIntrospector.add` when you have a custom
IIntrospectable). Replaces any existing introspectable registered
using the same category/discriminator.
@@ -1285,7 +1297,7 @@ class IIntrospector(Interface):
indirectly by :meth:`pyramid.interfaces.IIntrospector.register`"""
def relate(*pairs):
- """ Given any number of ``(category_name, discriminator)`` pairs
+ """Given any number of ``(category_name, discriminator)`` pairs
passed as positional arguments, relate the associated introspectables
to each other. The introspectable related to each pair must have
already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
@@ -1297,7 +1309,7 @@ class IIntrospector(Interface):
"""
def unrelate(*pairs):
- """ Given any number of ``(category_name, discriminator)`` pairs
+ """Given any number of ``(category_name, discriminator)`` pairs
passed as positional arguments, unrelate the associated introspectables
from each other. The introspectable related to each pair must have
already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
@@ -1310,7 +1322,7 @@ class IIntrospector(Interface):
class IIntrospectable(Interface):
- """ An introspectable object used for configuration introspection. In
+ """An introspectable object used for configuration introspection. In
addition to the methods below, objects which implement this interface
must also implement all the methods of Python's
``collections.MutableMapping`` (the "dictionary interface"), and must be
@@ -1335,19 +1347,19 @@ class IIntrospectable(Interface):
)
def relate(category_name, discriminator):
- """ Indicate an intent to relate this IIntrospectable with another
+ """Indicate an intent to relate this IIntrospectable with another
IIntrospectable (the one associated with the ``category_name`` and
``discriminator``) during action execution.
"""
def unrelate(category_name, discriminator):
- """ Indicate an intent to break the relationship between this
+ """Indicate an intent to break the relationship between this
IIntrospectable with another IIntrospectable (the one associated with
the ``category_name`` and ``discriminator``) during action execution.
"""
def register(introspector, action_info):
- """ Register this IIntrospectable with an introspector. This method
+ """Register this IIntrospectable with an introspector. This method
is invoked during action execution. Adds the introspectable and its
relations to the introspector. ``introspector`` should be an object
implementing IIntrospector. ``action_info`` should be a object
@@ -1368,7 +1380,7 @@ class IIntrospectable(Interface):
def __hash__():
- """ Introspectables must be hashable. The typical implementation of
+ """Introspectables must be hashable. The typical implementation of
an introsepectable's __hash__ is::
return hash((self.category_name,) + (self.discriminator,))
@@ -1376,7 +1388,7 @@ class IIntrospectable(Interface):
class IActionInfo(Interface):
- """ Class which provides code introspection capability associated with an
+ """Class which provides code introspection capability associated with an
action. The ParserInfo class used by ZCML implements the same interface.
"""
@@ -1387,8 +1399,8 @@ class IActionInfo(Interface):
)
def __str__():
- """ Return a representation of the action information (including
- source code from file, if possible) """
+ """Return a representation of the action information (including
+ source code from file, if possible)"""
class IAssetDescriptor(Interface):
@@ -1455,7 +1467,7 @@ class IPredicateInfo(Interface):
)
def maybe_dotted(value):
- """ Resolve the :term:`dotted Python name` ``dotted`` to a
+ """Resolve the :term:`dotted Python name` ``dotted`` to a
global Python object. If ``dotted`` is not a string, return
it without attempting to do any name resolution. If
``dotted`` is a relative dotted name (e.g. ``.foo.bar``,
@@ -1546,7 +1558,7 @@ class IViewDeriver(Interface):
class IViewDeriverInfo(Interface):
- """ An object implementing this interface is passed to every
+ """An object implementing this interface is passed to every
:term:`view deriver` during configuration."""
registry = Attribute(
diff --git a/src/pyramid/paster.py b/src/pyramid/paster.py
index 00c1a8915..f14acacf7 100644
--- a/src/pyramid/paster.py
+++ b/src/pyramid/paster.py
@@ -14,7 +14,7 @@ def setup_logging(config_uri, global_conf=None):
def get_app(config_uri, name=None, options=None):
- """ Return the WSGI application named ``name`` in the PasteDeploy
+ """Return the WSGI application named ``name`` in the PasteDeploy
config file specified by ``config_uri``.
``options``, if passed, should be a dictionary used as variable assignments
@@ -31,7 +31,7 @@ def get_app(config_uri, name=None, options=None):
def get_appsettings(config_uri, name=None, options=None):
- """ Return a dictionary representing the key/value pairs in an ``app``
+ """Return a dictionary representing the key/value pairs in an ``app``
section within the file represented by ``config_uri``.
``options``, if passed, should be a dictionary used as variable assignments
@@ -48,7 +48,7 @@ def get_appsettings(config_uri, name=None, options=None):
def bootstrap(config_uri, request=None, options=None):
- """ Load a WSGI application from the PasteDeploy config file specified
+ """Load a WSGI application from the PasteDeploy config file specified
by ``config_uri``. The environment will be configured as if it is
currently serving ``request``, leaving a natural environment in place
to write scripts that can generate URLs and utilize renderers.
diff --git a/src/pyramid/path.py b/src/pyramid/path.py
index 6d387f55b..3c0c1a682 100644
--- a/src/pyramid/path.py
+++ b/src/pyramid/path.py
@@ -25,7 +25,7 @@ def caller_module(level=2, sys=sys):
def package_name(pkg_or_module):
- """ If this function is passed a module, return the dotted Python
+ """If this function is passed a module, return the dotted Python
package name of the package in which the module lives. If this
function is passed a package, return the dotted Python package
name of the package itself."""
@@ -119,7 +119,7 @@ class Resolver:
class AssetResolver(Resolver):
- """ A class used to resolve an :term:`asset specification` to an
+ """A class used to resolve an :term:`asset specification` to an
:term:`asset descriptor`.
.. versionadded:: 1.3
@@ -215,7 +215,7 @@ class AssetResolver(Resolver):
class DottedNameResolver(Resolver):
- """ A class used to resolve a :term:`dotted Python name` to a package or
+ """A class used to resolve a :term:`dotted Python name` to a package or
module object.
.. versionadded:: 1.3
diff --git a/src/pyramid/predicates.py b/src/pyramid/predicates.py
index 576bbbce6..fe8bc228c 100644
--- a/src/pyramid/predicates.py
+++ b/src/pyramid/predicates.py
@@ -276,6 +276,19 @@ class PhysicalPathPredicate:
return False
+class IsAuthenticatedPredicate:
+ def __init__(self, val, config):
+ self.val = val
+
+ def text(self):
+ return "is_authenticated = %r" % (self.val,)
+
+ phash = text
+
+ def __call__(self, context, request):
+ return request.is_authenticated == self.val
+
+
class EffectivePrincipalsPredicate:
def __init__(self, val, config):
if is_nonstr_iter(val):
diff --git a/src/pyramid/registry.py b/src/pyramid/registry.py
index 6f6ef5f77..66519398c 100644
--- a/src/pyramid/registry.py
+++ b/src/pyramid/registry.py
@@ -9,7 +9,7 @@ from pyramid.path import CALLER_PACKAGE, caller_package
class Registry(Components, dict):
- """ A registry object is an :term:`application registry`.
+ """A registry object is an :term:`application registry`.
It is used by the framework itself to perform mappings of URLs to view
callables, as well as servicing other various framework duties. A registry
@@ -265,7 +265,7 @@ class Introspectable(dict):
class Deferred:
- """ Can be used by a third-party configuration extender to wrap a
+ """Can be used by a third-party configuration extender to wrap a
:term:`discriminator` during configuration if an immediately hashable
discriminator cannot be computed because it relies on unresolved values.
The function should accept no arguments and should return a hashable
@@ -285,7 +285,7 @@ class Deferred:
def undefer(v):
- """ Function which accepts an object and returns it unless it is a
+ """Function which accepts an object and returns it unless it is a
:class:`pyramid.registry.Deferred` instance. If it is an instance of
that class, its ``resolve`` method is called, and the result of the
method is returned."""
diff --git a/src/pyramid/renderers.py b/src/pyramid/renderers.py
index 8da6270c3..a15909cc0 100644
--- a/src/pyramid/renderers.py
+++ b/src/pyramid/renderers.py
@@ -19,7 +19,7 @@ from pyramid.util import hide_attrs
def render(renderer_name, value, request=None, package=None):
- """ Using the renderer ``renderer_name`` (a template
+ """Using the renderer ``renderer_name`` (a template
or a static renderer), render the value (or set of values) present
in ``value``. Return the result of the renderer's ``__call__``
method (usually a string or Unicode).
@@ -72,7 +72,7 @@ def render(renderer_name, value, request=None, package=None):
def render_to_response(
renderer_name, value, request=None, package=None, response=None
):
- """ Using the renderer ``renderer_name`` (a template
+ """Using the renderer ``renderer_name`` (a template
or a static renderer), render the value (or set of values) using
the result of the renderer's ``__call__`` method (usually a string
or Unicode) as the response body.
@@ -133,7 +133,7 @@ def render_to_response(
def get_renderer(renderer_name, package=None, registry=None):
- """ Return the renderer object for the renderer ``renderer_name``.
+ """Return the renderer object for the renderer ``renderer_name``.
You may supply a relative asset spec as ``renderer_name``. If
the ``package`` argument is supplied, a relative renderer name
@@ -178,7 +178,7 @@ _marker = object()
class JSON:
- """ Renderer that returns a JSON-encoded string.
+ """Renderer that returns a JSON-encoded string.
Configure a custom JSON renderer using the
:meth:`~pyramid.config.Configurator.add_renderer` API at application
@@ -226,7 +226,7 @@ class JSON:
"""
def __init__(self, serializer=json.dumps, adapters=(), **kw):
- """ Any keyword arguments will be passed to the ``serializer``
+ """Any keyword arguments will be passed to the ``serializer``
function."""
self.serializer = serializer
self.kw = kw
@@ -235,7 +235,7 @@ class JSON:
self.add_adapter(type, adapter)
def add_adapter(self, type_or_iface, adapter):
- """ When an object of the type (or interface) ``type_or_iface`` fails
+ """When an object of the type (or interface) ``type_or_iface`` fails
to automatically encode using the serializer, the renderer will use
the adapter ``adapter`` to convert it into a JSON-serializable
object. The adapter must accept two arguments: the object and the
@@ -261,7 +261,7 @@ class JSON:
)
def __call__(self, info):
- """ Returns a plain JSON-encoded string with content-type
+ """Returns a plain JSON-encoded string with content-type
``application/json``. The content-type may be overridden by
setting ``request.response.content_type``."""
@@ -299,7 +299,7 @@ JSONP_VALID_CALLBACK = re.compile(r"^[$a-z_][$0-9a-z_\.\[\]]+[^.]$", re.I)
class JSONP(JSON):
- """ `JSONP <https://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper
+ """`JSONP <https://en.wikipedia.org/wiki/JSONP>`_ renderer factory helper
which implements a hybrid json/jsonp renderer. JSONP is useful for
making cross-domain AJAX requests.
@@ -366,7 +366,7 @@ class JSONP(JSON):
JSON.__init__(self, **kw)
def __call__(self, info):
- """ Returns JSONP-encoded string with content-type
+ """Returns JSONP-encoded string with content-type
``application/javascript`` if query parameter matching
``self.param_name`` is present in request.GET; otherwise returns
plain-JSON encoded string with content-type ``application/json``"""
@@ -499,7 +499,7 @@ class RendererHelper:
class NullRendererHelper(RendererHelper):
- """ Special renderer helper that has render_* methods which simply return
+ """Special renderer helper that has render_* methods which simply return
the value they are fed rather than converting them to response objects;
useful for testing purposes and special case view configuration
registrations that want to use the view configuration machinery but do
diff --git a/src/pyramid/request.py b/src/pyramid/request.py
index ef0efaa64..e5cfb37b8 100644
--- a/src/pyramid/request.py
+++ b/src/pyramid/request.py
@@ -188,7 +188,7 @@ class Request(
@reify
def session(self):
- """ Obtain the :term:`session` object associated with this
+ """Obtain the :term:`session` object associated with this
request. If a :term:`session factory` has not been registered
during application configuration, a
:class:`pyramid.exceptions.ConfigurationError` will be raised"""
@@ -218,7 +218,7 @@ class Request(
return response_factory(self)
def is_response(self, ob):
- """ Return ``True`` if the object passed as ``ob`` is a valid
+ """Return ``True`` if the object passed as ``ob`` is a valid
response object, ``False`` otherwise."""
if ob.__class__ is Response:
return True
diff --git a/src/pyramid/response.py b/src/pyramid/response.py
index c9beb9e0d..3090d7e75 100644
--- a/src/pyramid/response.py
+++ b/src/pyramid/response.py
@@ -70,7 +70,7 @@ class FileResponse(Response):
class FileIter:
- """ A fixed-block-size iterator for use as a WSGI app_iter.
+ """A fixed-block-size iterator for use as a WSGI app_iter.
``file`` is a Python file pointer (or at least an object with a ``read``
method that takes a size hint).
@@ -96,7 +96,7 @@ class FileIter:
class response_adapter:
- """ Decorator activated via a :term:`scan` which treats the function
+ """Decorator activated via a :term:`scan` which treats the function
being decorated as a :term:`response adapter` for the set of types or
interfaces passed as ``*types_or_ifaces`` to the decorator constructor.
@@ -183,7 +183,7 @@ class response_adapter:
def _get_response_factory(registry):
- """ Obtain a :class: `pyramid.response.Response` using the
+ """Obtain a :class: `pyramid.response.Response` using the
`pyramid.interfaces.IResponseFactory`.
"""
response_factory = registry.queryUtility(
diff --git a/src/pyramid/scripting.py b/src/pyramid/scripting.py
index bf23f1008..bb2947301 100644
--- a/src/pyramid/scripting.py
+++ b/src/pyramid/scripting.py
@@ -7,7 +7,7 @@ from pyramid.traversal import DefaultRootFactory
def get_root(app, request=None):
- """ Return a tuple composed of ``(root, closer)`` when provided a
+ """Return a tuple composed of ``(root, closer)`` when provided a
:term:`router` instance as the ``app`` argument. The ``root``
returned is the application root object. The ``closer`` returned
is a callable (accepting no arguments) that should be called when
@@ -33,7 +33,7 @@ def get_root(app, request=None):
def prepare(request=None, registry=None):
- """ This function pushes data onto the Pyramid threadlocal stack
+ """This function pushes data onto the Pyramid threadlocal stack
(request and registry), making those objects 'current'. It
returns a dictionary useful for bootstrapping a Pyramid
application in a scripting environment.
@@ -128,7 +128,7 @@ class AppEnvironment(dict):
def _make_request(path, registry=None):
- """ Return a :meth:`pyramid.request.Request` object anchored at a
+ """Return a :meth:`pyramid.request.Request` object anchored at a
given path. The object returned will be generated from the supplied
registry's :term:`Request Factory` using the
:meth:`pyramid.interfaces.IRequestFactory.blank` method.
diff --git a/src/pyramid/scripts/pserve.py b/src/pyramid/scripts/pserve.py
index ce0c454e6..6906a0410 100644
--- a/src/pyramid/scripts/pserve.py
+++ b/src/pyramid/scripts/pserve.py
@@ -143,7 +143,7 @@ class PServeCommand:
def out(self, msg): # pragma: no cover
if self.args.verbose > 0:
- print(msg)
+ print(msg, file=sys.stderr)
def get_config_path(self, loader):
return os.path.abspath(loader.uri.path)
@@ -296,7 +296,9 @@ def wsgiref_server_runner(wsgi_app, global_conf, **kw): # pragma: no cover
host = kw.get('host', '0.0.0.0')
port = int(kw.get('port', 8080))
server = make_server(host, port, wsgi_app)
- print('Starting HTTP server on http://%s:%s' % (host, port))
+ print(
+ 'Starting HTTP server on http://%s:%s' % (host, port), file=sys.stderr
+ )
server.serve_forever()
@@ -416,10 +418,14 @@ def cherrypy_server_runner(
if host == '0.0.0.0':
print(
'serving on 0.0.0.0:%s view at %s://127.0.0.1:%s'
- % (port, protocol, port)
+ % (port, protocol, port),
+ file=sys.stderr,
)
else:
- print('serving on %s://%s:%s' % (protocol, host, port))
+ print(
+ 'serving on %s://%s:%s' % (protocol, host, port),
+ file=sys.stderr,
+ )
server.start()
except (KeyboardInterrupt, SystemExit):
server.stop()
diff --git a/src/pyramid/scripts/pviews.py b/src/pyramid/scripts/pviews.py
index db7f10b20..2731950b4 100644
--- a/src/pyramid/scripts/pviews.py
+++ b/src/pyramid/scripts/pviews.py
@@ -84,15 +84,16 @@ class PViewsCommand:
find a :app:`Pyramid` view based on introspection of :term:`view
configuration` within the application registry; return the view.
"""
- from zope.interface import providedBy
- from zope.interface import implementer
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IRootFactory
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IRoutesMapper
- from pyramid.interfaces import ITraverser
- from pyramid.traversal import DefaultRootFactory
- from pyramid.traversal import ResourceTreeTraverser
+ from zope.interface import implementer, providedBy
+
+ from pyramid.interfaces import (
+ IRequest,
+ IRootFactory,
+ IRouteRequest,
+ IRoutesMapper,
+ ITraverser,
+ )
+ from pyramid.traversal import DefaultRootFactory, ResourceTreeTraverser
registry = request.registry
q = registry.queryUtility
diff --git a/src/pyramid/security.py b/src/pyramid/security.py
index 58bc72116..cbab0a0f2 100644
--- a/src/pyramid/security.py
+++ b/src/pyramid/security.py
@@ -122,7 +122,7 @@ deprecated(
def view_execution_permitted(context, request, name=''):
- """ If the view specified by ``context`` and ``name`` is protected
+ """If the view specified by ``context`` and ``name`` is protected
by a :term:`permission`, check the permission associated with the
view using the effective authentication/authorization policies and
the ``request``. Return a boolean result. If no
@@ -244,8 +244,13 @@ class SecurityAPIMixin:
return None
return policy.authenticated_userid(self)
+ @property
+ def is_authenticated(self):
+ """Return ``True`` if a user is authenticated for this request."""
+ return self.authenticated_identity is not None
+
def has_permission(self, permission, context=None):
- """ Given a permission and an optional context, returns an instance of
+ """Given a permission and an optional context, returns an instance of
:data:`pyramid.security.Allowed` if the permission is granted to this
request with the provided context, or the context already associated
with the request. Otherwise, returns an instance of
diff --git a/src/pyramid/session.py b/src/pyramid/session.py
index 5d5f3b939..8c27aa674 100644
--- a/src/pyramid/session.py
+++ b/src/pyramid/session.py
@@ -12,7 +12,7 @@ from pyramid.util import bytes_, text_
def manage_accessed(wrapped):
- """ Decorator which causes a cookie to be renewed when an accessor
+ """Decorator which causes a cookie to be renewed when an accessor
method is called."""
def accessed(session, *arg, **kw):
@@ -27,7 +27,7 @@ def manage_accessed(wrapped):
def manage_changed(wrapped):
- """ Decorator which causes a cookie to be set when a setter method
+ """Decorator which causes a cookie to be set when a setter method
is called."""
def changed(session, *arg, **kw):
diff --git a/src/pyramid/settings.py b/src/pyramid/settings.py
index d1eb4ff14..56ddcaf5a 100644
--- a/src/pyramid/settings.py
+++ b/src/pyramid/settings.py
@@ -3,7 +3,7 @@ falsey = frozenset(('f', 'false', 'n', 'no', 'off', '0'))
def asbool(s):
- """ Return the boolean value ``True`` if the case-lowered value of string
+ """Return the boolean value ``True`` if the case-lowered value of string
input ``s`` is a :term:`truthy string`. If ``s`` is already one of the
boolean values ``True`` or ``False``, return it."""
if s is None:
@@ -21,14 +21,18 @@ def aslist_cronly(value):
def aslist(value, flatten=True):
- """ Return a list of strings, separating the input based on newlines
- and, if flatten=True (the default), also split on spaces within
- each line."""
+ """Return a list, separating the input based on newlines.
+ Also if ``flatten`` is ``True`` (the default), and if the line
+ is a string, then the line will be split on spaces.
+ """
values = aslist_cronly(value)
if not flatten:
return values
result = []
for value in values:
- subvalues = value.split()
- result.extend(subvalues)
+ if isinstance(value, str):
+ value = value.split()
+ result.extend(value)
+ else:
+ result.append(value)
return result
diff --git a/src/pyramid/static.py b/src/pyramid/static.py
index ccd6404da..8b19c7b16 100644
--- a/src/pyramid/static.py
+++ b/src/pyramid/static.py
@@ -13,7 +13,7 @@ from pyramid.traversal import traversal_path_info
class static_view:
- """ An instance of this class is a callable which can act as a
+ """An instance of this class is a callable which can act as a
:app:`Pyramid` :term:`view callable`; this view will serve
static files from a directory on disk based on the ``root_dir``
you provide to its constructor.
@@ -211,7 +211,8 @@ class static_view:
# identity is acceptable
if not request.accept_encoding:
identity_path = next(
- (path for path, encoding in files if encoding is None), None,
+ (path for path, encoding in files if encoding is None),
+ None,
)
return identity_path, None
diff --git a/src/pyramid/testing.py b/src/pyramid/testing.py
index 8ee9f976c..ddfe2a660 100644
--- a/src/pyramid/testing.py
+++ b/src/pyramid/testing.py
@@ -114,7 +114,7 @@ class DummyTemplateRenderer:
return val
def assert_(self, **kw):
- """ Accept an arbitrary set of assertion key/value pairs. For
+ """Accept an arbitrary set of assertion key/value pairs. For
each assertion key/value pair assert that the renderer
(eg. :func:`pyramid.renderers.render_to_response`)
received the key with a value that equals the asserted
@@ -145,7 +145,7 @@ class DummyResource:
def __init__(
self, __name__=None, __parent__=None, __provides__=None, **kw
):
- """ The resource's ``__name__`` attribute will be set to the
+ """The resource's ``__name__`` attribute will be set to the
value of the ``__name__`` argument, and the resource's
``__parent__`` attribute will be set to the value of the
``__parent__`` argument. If ``__provides__`` is specified, it
@@ -168,7 +168,7 @@ class DummyResource:
self.subs = {}
def __setitem__(self, name, val):
- """ When the ``__setitem__`` method is called, the object
+ """When the ``__setitem__`` method is called, the object
passed in as ``val`` will be decorated with a ``__parent__``
attribute pointing at the dummy resource and a ``__name__``
attribute that is the value of ``name``. The value will then
@@ -213,7 +213,7 @@ class DummyResource:
return name in self.subs
def clone(self, __name__=_marker, __parent__=_marker, **kw):
- """ Create a clone of the resource object. If ``__name__`` or
+ """Create a clone of the resource object. If ``__name__`` or
``__parent__`` arguments are passed, use these values to
override the existing ``__name__`` or ``__parent__`` of the
resource. If any extra keyword args are passed in via the ``kw``
@@ -279,7 +279,7 @@ class DummyRequest(
AuthenticationAPIMixin,
ViewMethodsMixin,
):
- """ A DummyRequest object (incompletely) imitates a :term:`request` object.
+ """A DummyRequest object (incompletely) imitates a :term:`request` object.
The ``params``, ``environ``, ``headers``, ``path``, and
``cookies`` arguments correspond to their :term:`WebOb`
@@ -554,7 +554,7 @@ def cleanUp(*arg, **kw):
class DummyRendererFactory:
- """ Registered by
+ """Registered by
:meth:`pyramid.config.Configurator.testing_add_renderer` as
a dummy renderer factory. The indecision about what to use as a
key (a spec vs. a relative name) is caused by test suites in the
diff --git a/src/pyramid/traversal.py b/src/pyramid/traversal.py
index 39cfc4f2e..dadeeda64 100644
--- a/src/pyramid/traversal.py
+++ b/src/pyramid/traversal.py
@@ -20,7 +20,7 @@ PATH_SAFE = PATH_SEGMENT_SAFE + "/"
def find_root(resource):
- """ Find the root node in the resource tree to which ``resource``
+ """Find the root node in the resource tree to which ``resource``
belongs. Note that ``resource`` should be :term:`location`-aware.
Note that the root resource is available in the request object by
accessing the ``request.root`` attribute.
@@ -33,7 +33,7 @@ def find_root(resource):
def find_resource(resource, path):
- """ Given a resource object and a string or tuple representing a path
+ """Given a resource object and a string or tuple representing a path
(such as the return value of :func:`pyramid.traversal.resource_path` or
:func:`pyramid.traversal.resource_path_tuple`), return a resource in this
application's resource tree at the specified path. The resource passed
@@ -109,7 +109,7 @@ def find_interface(resource, class_or_interface):
def resource_path(resource, *elements):
- """ Return a string object representing the absolute physical path of the
+ """Return a string object representing the absolute physical path of the
resource object based on its position in the resource tree, e.g
``/foo/bar``. Any positional arguments passed in as ``elements`` will be
appended as path segments to the end of the resource path. For instance,
@@ -361,7 +361,7 @@ model_path_tuple = resource_path_tuple # b/w compat (forever)
def _resource_path_list(resource, *elements):
- """ Implementation detail shared by resource_path and
+ """Implementation detail shared by resource_path and
resource_path_tuple"""
path = [loc.__name__ or '' for loc in lineage(resource)]
path.reverse()
@@ -418,7 +418,7 @@ def virtual_root(resource, request):
def traversal_path(path):
- """ Variant of :func:`pyramid.traversal.traversal_path_info` suitable for
+ """Variant of :func:`pyramid.traversal.traversal_path_info` suitable for
decoding paths that are URL-encoded.
If this function is passed a string, it *must* be directly encodeable to
@@ -437,7 +437,7 @@ def traversal_path(path):
@lru_cache(1000)
def traversal_path_info(path):
- """ Given``path``, return a tuple representing that path which can be
+ """Given``path``, return a tuple representing that path which can be
used to traverse a resource tree. ``path`` is assumed to be an
already-URL-decoded ``str`` type as if it had come to us from an upstream
WSGI server as the ``PATH_INFO`` environ variable.
@@ -581,7 +581,7 @@ def quote_path_segment(segment, safe=PATH_SEGMENT_SAFE):
@implementer(ITraverser)
class ResourceTreeTraverser:
- """ A resource tree traverser that should be used (for speed) when
+ """A resource tree traverser that should be used (for speed) when
every resource in the tree supplies a ``__name__`` and
``__parent__`` attribute (ie. every resource in the tree is
:term:`location` aware) ."""
diff --git a/src/pyramid/tweens.py b/src/pyramid/tweens.py
index b5660b44b..b4a9ad641 100644
--- a/src/pyramid/tweens.py
+++ b/src/pyramid/tweens.py
@@ -20,7 +20,7 @@ def _error_handler(request, exc):
def excview_tween_factory(handler, registry):
- """ A :term:`tween` factory which produces a tween that catches an
+ """A :term:`tween` factory which produces a tween that catches an
exception raised by downstream tweens (or the main Pyramid request
handler) and, if possible, converts it into a Response using an
:term:`exception view`.
diff --git a/src/pyramid/url.py b/src/pyramid/url.py
index 438400ae8..b60bed96d 100644
--- a/src/pyramid/url.py
+++ b/src/pyramid/url.py
@@ -57,8 +57,8 @@ def parse_url_overrides(request, kw):
class URLMethodsMixin:
- """ Request methods mixin for BaseRequest having to do with URL
- generation """
+ """Request methods mixin for BaseRequest having to do with URL
+ generation"""
def _partial_application_url(self, scheme=None, host=None, port=None):
"""
diff --git a/src/pyramid/util.py b/src/pyramid/util.py
index 4a92986ae..f8d082348 100644
--- a/src/pyramid/util.py
+++ b/src/pyramid/util.py
@@ -28,7 +28,7 @@ class DottedNameResolver(_DottedNameResolver):
def text_(s, encoding='latin-1', errors='strict'):
- """ If ``s`` is an instance of ``bytes``, return
+ """If ``s`` is an instance of ``bytes``, return
``s.decode(encoding, errors)``, otherwise return ``s``"""
if isinstance(s, bytes):
return s.decode(encoding, errors)
@@ -36,7 +36,7 @@ def text_(s, encoding='latin-1', errors='strict'):
def bytes_(s, encoding='latin-1', errors='strict'):
- """ If ``s`` is an instance of ``str``, return
+ """If ``s`` is an instance of ``str``, return
``s.encode(encoding, errors)``, otherwise return ``s``"""
if isinstance(s, str):
return s.encode(encoding, errors)
@@ -102,7 +102,7 @@ class InstancePropertyHelper:
@classmethod
def make_property(cls, callable, name=None, reify=False):
- """ Convert a callable into one suitable for adding to the
+ """Convert a callable into one suitable for adding to the
instance. This will return a 2-tuple containing the computed
(name, property) pair.
"""
@@ -188,13 +188,13 @@ class InstancePropertyHelper:
class InstancePropertyMixin:
- """ Mixin that will allow an instance to add properties at
+ """Mixin that will allow an instance to add properties at
run-time as if they had been defined via @property or @reify
on the class itself.
"""
def set_property(self, callable, name=None, reify=False):
- """ Add a callable or a property descriptor to the instance.
+ """Add a callable or a property descriptor to the instance.
Properties, unlike attributes, are lazily evaluated by executing
an underlying callable when accessed. They can be useful for
@@ -251,7 +251,7 @@ class InstancePropertyMixin:
class WeakOrderedSet:
- """ Maintain a set of items.
+ """Maintain a set of items.
Each item is stored as a weakref to avoid extending their lifetime.
@@ -346,7 +346,7 @@ def strings_differ(string1, string2):
def object_description(object):
- """ Produce a human-consumable text description of ``object``,
+ """Produce a human-consumable text description of ``object``,
usually involving a Python dotted name. For example:
>>> object_description(None)
@@ -423,7 +423,7 @@ LAST = Sentinel('LAST')
class TopologicalSorter:
- """ A utility class which can be used to perform topological sorts against
+ """A utility class which can be used to perform topological sorts against
tuple-like data."""
def __init__(
@@ -460,7 +460,7 @@ class TopologicalSorter:
self.order.remove((name, u))
def add(self, name, val, after=None, before=None):
- """ Add a node to the sort input. The ``name`` should be a string or
+ """Add a node to the sort input. The ``name`` should be a string or
any other hashable object, the ``val`` should be the sortable (doesn't
need to be hashable). ``after`` and ``before`` represents the name of
one of the other sortables (or a sequence of such named) or one of the
diff --git a/src/pyramid/view.py b/src/pyramid/view.py
index 3911ad375..1541cdb23 100644
--- a/src/pyramid/view.py
+++ b/src/pyramid/view.py
@@ -26,7 +26,7 @@ _marker = object()
def render_view_to_response(context, request, name='', secure=True):
- """ Call the :term:`view callable` configured with a :term:`view
+ """Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request`` and
return a :term:`response` object. This function will return
@@ -77,7 +77,7 @@ def render_view_to_response(context, request, name='', secure=True):
def render_view_to_iterable(context, request, name='', secure=True):
- """ Call the :term:`view callable` configured with a :term:`view
+ """Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request`` and
return an iterable object which represents the body of a response.
@@ -108,7 +108,7 @@ def render_view_to_iterable(context, request, name='', secure=True):
def render_view(context, request, name='', secure=True):
- """ Call the :term:`view callable` configured with a :term:`view
+ """Call the :term:`view callable` configured with a :term:`view
configuration` that matches the :term:`view name` ``name``
registered against the specified ``context`` and ``request``
and unwind the view response's ``app_iter`` (see
@@ -136,7 +136,7 @@ def render_view(context, request, name='', secure=True):
class view_config:
- """ A function, class or method :term:`decorator` which allows a
+ """A function, class or method :term:`decorator` which allows a
developer to create view registrations nearer to a :term:`view
callable` definition than use :term:`imperative
configuration` to do the same.
@@ -196,11 +196,27 @@ class view_config:
See also :ref:`mapping_views_using_a_decorator_section` for
details about using :class:`pyramid.view.view_config`.
- .. warning::
+ .. note::
- ``view_config`` will work ONLY on module top level members
- because of the limitation of ``venusian.Scanner.scan``.
+ Because of a limitation with ``venusian.Scanner.scan``, note that
+ ``view_config`` will work only for the following conditions.
+ - In Python packages that have an ``__init__.py`` file in their
+ directory.
+
+ .. seealso::
+
+ See also https://github.com/Pylons/venusian/issues/68
+
+ - On module top level members.
+ - On Python source (``.py``) files.
+ Compiled Python files (``.pyc``, ``.pyo``) without a corresponding
+ source file are ignored.
+
+ .. seealso::
+
+ See also the `Venusian documentation
+ <https://docs.pylonsproject.org/projects/venusian/en/latest/#using-venusian>`_.
"""
venusian = venusian # for testing injection
@@ -246,7 +262,7 @@ bfg_view = view_config # bw compat (forever)
def view_defaults(**settings):
- """ A class :term:`decorator` which, when applied to a class, will
+ """A class :term:`decorator` which, when applied to a class, will
provide defaults for all view configurations that use the class. This
decorator accepts all the arguments accepted by
:meth:`pyramid.view.view_config`, and each has the same meaning.
@@ -262,7 +278,7 @@ def view_defaults(**settings):
class AppendSlashNotFoundViewFactory:
- """ There can only be one :term:`Not Found view` in any
+ """There can only be one :term:`Not Found view` in any
:app:`Pyramid` application. Even if you use
:func:`pyramid.view.append_slash_notfound_view` as the Not
Found view, :app:`Pyramid` still must generate a ``404 Not
@@ -667,13 +683,13 @@ def _call_view(
class ViewMethodsMixin:
- """ Request methods mixin for BaseRequest having to do with executing
- views """
+ """Request methods mixin for BaseRequest having to do with executing
+ views"""
def invoke_exception_view(
self, exc_info=None, request=None, secure=True, reraise=False
):
- """ Executes an exception view related to the request it's called upon.
+ """Executes an exception view related to the request it's called upon.
The arguments it takes are these:
``exc_info``
diff --git a/src/pyramid/wsgi.py b/src/pyramid/wsgi.py
index 5aec62b77..0eef0f19a 100644
--- a/src/pyramid/wsgi.py
+++ b/src/pyramid/wsgi.py
@@ -4,7 +4,7 @@ from pyramid.request import call_app_with_subpath_as_path_info
def wsgiapp(wrapped):
- """ Decorator to turn a WSGI application into a :app:`Pyramid`
+ """Decorator to turn a WSGI application into a :app:`Pyramid`
:term:`view callable`. This decorator differs from the
:func:`pyramid.wsgi.wsgiapp2` decorator inasmuch as fixups of
``PATH_INFO`` and ``SCRIPT_NAME`` within the WSGI environment *are
@@ -45,7 +45,7 @@ def wsgiapp(wrapped):
def wsgiapp2(wrapped):
- """ Decorator to turn a WSGI application into a :app:`Pyramid`
+ """Decorator to turn a WSGI application into a :app:`Pyramid`
view callable. This decorator differs from the
:func:`pyramid.wsgi.wsgiapp` decorator inasmuch as fixups of
``PATH_INFO`` and ``SCRIPT_NAME`` within the WSGI environment
diff --git a/tests/pkgs/defpermbugapp/__init__.py b/tests/pkgs/defpermbugapp/__init__.py
index fe8611870..d7536b547 100644
--- a/tests/pkgs/defpermbugapp/__init__.py
+++ b/tests/pkgs/defpermbugapp/__init__.py
@@ -20,8 +20,8 @@ def z_view(request):
def includeme(config):
- from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.authentication import AuthTktAuthenticationPolicy
+ from pyramid.authorization import ACLAuthorizationPolicy
authn_policy = AuthTktAuthenticationPolicy('seekt1t', hashalg='sha512')
authz_policy = ACLAuthorizationPolicy()
diff --git a/tests/pkgs/fixtureapp/__init__.py b/tests/pkgs/fixtureapp/__init__.py
index ffc8adb4a..70e69b7d7 100644
--- a/tests/pkgs/fixtureapp/__init__.py
+++ b/tests/pkgs/fixtureapp/__init__.py
@@ -8,7 +8,7 @@ def includeme(config):
name='dummyskin.html',
request_type='.views.IDummy',
)
- from .models import fixture, IFixture
+ from .models import IFixture, fixture
config.registry.registerUtility(fixture, IFixture)
config.add_view('.views.fixture_view', name='another.html')
diff --git a/tests/test_authentication.py b/tests/test_authentication.py
index bfb110f5e..32f687ee2 100644
--- a/tests/test_authentication.py
+++ b/tests/test_authentication.py
@@ -239,12 +239,14 @@ class TestRepozeWho1AuthenticationPolicy(unittest.TestCase):
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
def test_instance_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAuthenticationPolicy
verifyObject(IAuthenticationPolicy, self._makeOne())
@@ -328,8 +330,7 @@ class TestRepozeWho1AuthenticationPolicy(unittest.TestCase):
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals_userid_only(self):
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
+ from pyramid.authorization import Authenticated, Everyone
request = DummyRequest(
{'repoze.who.identity': {'repoze.who.userid': 'fred'}}
@@ -341,8 +342,7 @@ class TestRepozeWho1AuthenticationPolicy(unittest.TestCase):
)
def test_effective_principals_userid_and_groups(self):
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
+ from pyramid.authorization import Authenticated, Everyone
request = DummyRequest(
{
@@ -467,12 +467,14 @@ class TestRemoteUserAuthenticationPolicy(unittest.TestCase):
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
def test_instance_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAuthenticationPolicy
verifyObject(IAuthenticationPolicy, self._makeOne())
@@ -505,8 +507,7 @@ class TestRemoteUserAuthenticationPolicy(unittest.TestCase):
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals(self):
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
+ from pyramid.authorization import Authenticated, Everyone
request = DummyRequest({'REMOTE_USER': 'fred'})
policy = self._makeOne()
@@ -619,8 +620,7 @@ class TestAuthTktAuthenticationPolicy(unittest.TestCase):
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals(self):
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
+ from pyramid.authorization import Authenticated, Everyone
request = DummyRequest({})
@@ -654,12 +654,14 @@ class TestAuthTktAuthenticationPolicy(unittest.TestCase):
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
def test_instance_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAuthenticationPolicy
verifyObject(IAuthenticationPolicy, self._makeOne(None, None))
@@ -1478,12 +1480,14 @@ class TestSessionAuthenticationPolicy(unittest.TestCase):
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
def test_instance_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAuthenticationPolicy
verifyObject(IAuthenticationPolicy, self._makeOne())
@@ -1540,8 +1544,7 @@ class TestSessionAuthenticationPolicy(unittest.TestCase):
self.assertEqual(policy.effective_principals(request), [Everyone])
def test_effective_principals(self):
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
+ from pyramid.authorization import Authenticated, Everyone
request = DummyRequest(session={'userid': 'fred'})
@@ -1637,6 +1640,7 @@ class TestBasicAuthAuthenticationPolicy(unittest.TestCase):
def test_class_implements_IAuthenticationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthenticationPolicy
verifyClass(IAuthenticationPolicy, self._getTargetClass())
diff --git a/tests/test_authorization.py b/tests/test_authorization.py
index aea651501..303ca2c5d 100644
--- a/tests/test_authorization.py
+++ b/tests/test_authorization.py
@@ -20,12 +20,14 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
def test_class_implements_IAuthorizationPolicy(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAuthorizationPolicy
verifyClass(IAuthorizationPolicy, self._getTargetClass())
def test_instance_implements_IAuthorizationPolicy(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAuthorizationPolicy
verifyObject(IAuthorizationPolicy, self._makeOne())
@@ -36,12 +38,14 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(policy.permits(context, [], 'view'), False)
def test_permits(self):
- from pyramid.authorization import Deny
- from pyramid.authorization import Allow
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
- from pyramid.authorization import ALL_PERMISSIONS
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import (
+ ALL_PERMISSIONS,
+ DENY_ALL,
+ Allow,
+ Authenticated,
+ Deny,
+ Everyone,
+ )
root = DummyContext()
community = DummyContext(__name__='community', __parent__=root)
@@ -145,8 +149,7 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(result, False)
def test_principals_allowed_by_permission_direct(self):
- from pyramid.authorization import Allow
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import DENY_ALL, Allow
context = DummyContext()
acl = [
@@ -162,8 +165,7 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(result, ['chrism'])
def test_principals_allowed_by_permission_callable_acl(self):
- from pyramid.authorization import Allow
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import DENY_ALL, Allow
context = DummyContext()
acl = lambda: [
@@ -191,10 +193,12 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(list(result), [])
def test_principals_allowed_by_permission(self):
- from pyramid.authorization import Allow
- from pyramid.authorization import Deny
- from pyramid.authorization import DENY_ALL
- from pyramid.authorization import ALL_PERMISSIONS
+ from pyramid.authorization import (
+ ALL_PERMISSIONS,
+ DENY_ALL,
+ Allow,
+ Deny,
+ )
root = DummyContext(__name__='', __parent__=None)
community = DummyContext(__name__='community', __parent__=root)
@@ -236,8 +240,7 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(result, [])
def test_principals_allowed_by_permission_deny_not_permission_in_acl(self):
- from pyramid.authorization import Deny
- from pyramid.authorization import Everyone
+ from pyramid.authorization import Deny, Everyone
context = DummyContext()
acl = [(Deny, Everyone, 'write')]
@@ -249,8 +252,7 @@ class TestACLAuthorizationPolicy(unittest.TestCase):
self.assertEqual(result, [])
def test_principals_allowed_by_permission_deny_permission_in_acl(self):
- from pyramid.authorization import Deny
- from pyramid.authorization import Everyone
+ from pyramid.authorization import Deny, Everyone
context = DummyContext()
acl = [(Deny, Everyone, 'read')]
@@ -289,13 +291,15 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result.context, context)
def test_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Deny
- from pyramid.authorization import Allow
- from pyramid.authorization import Everyone
- from pyramid.authorization import Authenticated
- from pyramid.authorization import ALL_PERMISSIONS
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import (
+ ALL_PERMISSIONS,
+ DENY_ALL,
+ ACLHelper,
+ Allow,
+ Authenticated,
+ Deny,
+ Everyone,
+ )
helper = ACLHelper()
root = DummyContext()
@@ -385,8 +389,7 @@ class TestACLHelper(unittest.TestCase):
)
def test_string_permissions_in_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
+ from pyramid.authorization import ACLHelper, Allow
helper = ACLHelper()
root = DummyContext()
@@ -398,8 +401,7 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result, False)
def test_callable_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
+ from pyramid.authorization import ACLHelper, Allow
helper = ACLHelper()
context = DummyContext()
@@ -409,9 +411,7 @@ class TestACLHelper(unittest.TestCase):
self.assertTrue(result)
def test_principals_allowed_by_permission_direct(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import DENY_ALL, ACLHelper, Allow
helper = ACLHelper()
context = DummyContext()
@@ -427,9 +427,7 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result, ['chrism'])
def test_principals_allowed_by_permission_callable_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
- from pyramid.authorization import DENY_ALL
+ from pyramid.authorization import DENY_ALL, ACLHelper, Allow
helper = ACLHelper()
context = DummyContext()
@@ -445,8 +443,7 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result, ['chrism'])
def test_principals_allowed_by_permission_string_permission(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
+ from pyramid.authorization import ACLHelper, Allow
helper = ACLHelper()
context = DummyContext()
@@ -458,11 +455,13 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(list(result), [])
def test_principals_allowed_by_permission(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Allow
- from pyramid.authorization import Deny
- from pyramid.authorization import DENY_ALL
- from pyramid.authorization import ALL_PERMISSIONS
+ from pyramid.authorization import (
+ ALL_PERMISSIONS,
+ DENY_ALL,
+ ACLHelper,
+ Allow,
+ Deny,
+ )
helper = ACLHelper()
root = DummyContext(__name__='', __parent__=None)
@@ -505,9 +504,7 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result, [])
def test_principals_allowed_by_permission_deny_not_permission_in_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Deny
- from pyramid.authorization import Everyone
+ from pyramid.authorization import ACLHelper, Deny, Everyone
helper = ACLHelper()
context = DummyContext()
@@ -519,9 +516,7 @@ class TestACLHelper(unittest.TestCase):
self.assertEqual(result, [])
def test_principals_allowed_by_permission_deny_permission_in_acl(self):
- from pyramid.authorization import ACLHelper
- from pyramid.authorization import Deny
- from pyramid.authorization import Everyone
+ from pyramid.authorization import ACLHelper, Deny, Everyone
helper = ACLHelper()
context = DummyContext()
diff --git a/tests/test_config/test_actions.py b/tests/test_config/test_actions.py
index b1f4b4b99..ea6f6cf80 100644
--- a/tests/test_config/test_actions.py
+++ b/tests/test_config/test_actions.py
@@ -23,9 +23,12 @@ class ActionConfiguratorMixinTests(unittest.TestCase):
exception_view=False,
):
from zope.interface import Interface
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IView,
+ IViewClassifier,
+ )
if exception_view: # pragma: no cover
classifier = IExceptionViewClassifier
@@ -1041,12 +1044,14 @@ class TestActionInfo(unittest.TestCase):
def test_class_conforms(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IActionInfo
verifyClass(IActionInfo, self._getTargetClass())
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IActionInfo
verifyObject(IActionInfo, self._makeOne('f', 0, 'f', 'f'))
diff --git a/tests/test_config/test_adapters.py b/tests/test_config/test_adapters.py
index 8c7f00751..22b60961a 100644
--- a/tests/test_config/test_adapters.py
+++ b/tests/test_config/test_adapters.py
@@ -11,8 +11,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
return config
def test_add_subscriber_defaults(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -36,8 +35,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 2)
def test_add_subscriber_iface_specified(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -61,8 +59,8 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 1)
def test_add_subscriber_dottednames(self):
- import tests.test_config
from pyramid.interfaces import INewRequest
+ import tests.test_config
config = self._makeOne(autocommit=True)
config.add_subscriber(
@@ -75,8 +73,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(handler.required, (INewRequest,))
def test_add_object_event_subscriber(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -100,8 +97,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 1)
def test_add_subscriber_with_specific_type_and_predicates_True(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -132,8 +128,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 1)
def test_add_subscriber_with_default_type_predicates_True(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -164,8 +159,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 1)
def test_add_subscriber_with_specific_type_and_predicates_False(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -193,8 +187,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(len(L), 0)
def test_add_subscriber_with_default_type_predicates_False(self):
- from zope.interface import implementer
- from zope.interface import Interface
+ from zope.interface import Interface, implementer
class IEvent(Interface):
pass
@@ -347,6 +340,7 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
def test_add_resource_url_nodefault_resource_iface(self):
from zope.interface import Interface
+
from pyramid.interfaces import IResourceURL
config = self._makeOne(autocommit=True)
diff --git a/tests/test_config/test_assets.py b/tests/test_config/test_assets.py
index 3cfea7fe4..1d2cfcd5c 100644
--- a/tests/test_config/test_assets.py
+++ b/tests/test_config/test_assets.py
@@ -536,24 +536,28 @@ class TestPackageOverrides(unittest.TestCase):
def test_class_conforms_to_IPackageOverrides(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IPackageOverrides
verifyClass(IPackageOverrides, self._getTargetClass())
def test_instance_conforms_to_IPackageOverrides(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IPackageOverrides
verifyObject(IPackageOverrides, self._makeOne())
def test_class_conforms_to_IPEP302Loader(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IPEP302Loader
verifyClass(IPEP302Loader, self._getTargetClass())
def test_instance_conforms_to_IPEP302Loader(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IPEP302Loader
verifyObject(IPEP302Loader, self._makeOne())
diff --git a/tests/test_config/test_init.py b/tests/test_config/test_init.py
index 5ca3063c5..0a9e2988c 100644
--- a/tests/test_config/test_init.py
+++ b/tests/test_config/test_init.py
@@ -31,9 +31,11 @@ class ConfiguratorTests(unittest.TestCase):
name='',
exception_view=False,
):
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IView,
+ IViewClassifier,
+ )
if exception_view: # pragma: no cover
classifier = IExceptionViewClassifier
@@ -66,9 +68,9 @@ class ConfiguratorTests(unittest.TestCase):
def test_ctor_no_registry(self):
import sys
- from pyramid.interfaces import ISettings
+
from pyramid.config import Configurator
- from pyramid.interfaces import IRendererFactory
+ from pyramid.interfaces import IRendererFactory, ISettings
config = Configurator()
this_pkg = sys.modules['tests.test_config']
@@ -177,6 +179,7 @@ class ConfiguratorTests(unittest.TestCase):
def test_ctor_with_package_registry(self):
import sys
+
from pyramid.config import Configurator
pkg = sys.modules['pyramid']
@@ -297,8 +300,8 @@ class ConfiguratorTests(unittest.TestCase):
)
def test_ctor_httpexception_view_default(self):
- from pyramid.interfaces import IExceptionResponse
from pyramid.httpexceptions import default_exceptionresponse_view
+ from pyramid.interfaces import IExceptionResponse
config = self._makeOne()
view = self._getViewCallable(
@@ -428,8 +431,7 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(reg.events, (1,))
def test__fix_registry_queryAdapterOrSelf(self):
- from zope.interface import Interface
- from zope.interface import implementer
+ from zope.interface import Interface, implementer
class IFoo(Interface):
pass
@@ -494,6 +496,7 @@ class ConfiguratorTests(unittest.TestCase):
def test_setup_registry_registers_default_exceptionresponse_views(self):
from webob.exc import WSGIHTTPException
+
from pyramid.interfaces import IExceptionResponse
from pyramid.view import default_exceptionresponse_view
@@ -533,6 +536,7 @@ class ConfiguratorTests(unittest.TestCase):
def test_setup_registry_registers_default_webob_iresponse_adapter(self):
from webob import Response
+
from pyramid.interfaces import IResponse
config = self._makeOne()
@@ -543,10 +547,11 @@ class ConfiguratorTests(unittest.TestCase):
)
def test_setup_registry_explicit_notfound_trumps_iexceptionresponse(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
+
from pyramid.httpexceptions import HTTPNotFound
from pyramid.registry import Registry
+ from pyramid.renderers import null_renderer
reg = Registry()
config = self._makeOne(reg, autocommit=True)
@@ -566,8 +571,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(result, 'OK')
def test_setup_registry_custom_settings(self):
- from pyramid.registry import Registry
from pyramid.interfaces import ISettings
+ from pyramid.registry import Registry
settings = {'reload_templates': True, 'mysetting': True}
reg = Registry()
@@ -579,8 +584,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(settings['mysetting'], True)
def test_setup_registry_debug_logger_None_default(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IDebugLogger
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -589,8 +594,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(logger.name, 'tests.test_config')
def test_setup_registry_debug_logger_non_None(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IDebugLogger
+ from pyramid.registry import Registry
logger = object()
reg = Registry()
@@ -600,8 +605,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(logger, result)
def test_setup_registry_debug_logger_name(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IDebugLogger
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -610,8 +615,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(result.name, 'foo')
def test_setup_registry_authentication_policy(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IAuthenticationPolicy
+ from pyramid.registry import Registry
policy = object()
reg = Registry()
@@ -622,8 +627,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(policy, result)
def test_setup_registry_authentication_policy_dottedname(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IAuthenticationPolicy
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -635,8 +640,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(result, tests.test_config)
def test_setup_registry_authorization_policy_dottedname(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IAuthorizationPolicy
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -661,8 +666,8 @@ class ConfiguratorTests(unittest.TestCase):
config = self.assertRaises(ConfigurationExecutionError, config.commit)
def test_setup_registry_no_default_root_factory(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IRootFactory
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -671,8 +676,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(reg.queryUtility(IRootFactory), None)
def test_setup_registry_dottedname_root_factory(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IRootFactory
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -684,8 +689,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(reg.getUtility(IRootFactory), tests.test_config)
def test_setup_registry_locale_negotiator_dottedname(self):
- from pyramid.registry import Registry
from pyramid.interfaces import ILocaleNegotiator
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -698,8 +703,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(utility, tests.test_config)
def test_setup_registry_locale_negotiator(self):
- from pyramid.registry import Registry
from pyramid.interfaces import ILocaleNegotiator
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -711,8 +716,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(utility, negotiator)
def test_setup_registry_request_factory(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IRequestFactory
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -724,8 +729,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(utility, factory)
def test_setup_registry_response_factory(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IResponseFactory
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -737,8 +742,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(utility, factory)
def test_setup_registry_request_factory_dottedname(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IRequestFactory
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -751,8 +756,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(utility, tests.test_config)
def test_setup_registry_alternate_renderers(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IRendererFactory
+ from pyramid.registry import Registry
renderer = object()
reg = Registry()
@@ -762,8 +767,8 @@ class ConfiguratorTests(unittest.TestCase):
self.assertEqual(reg.getUtility(IRendererFactory, 'yeah'), renderer)
def test_setup_registry_default_permission(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IDefaultPermission
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -829,8 +834,8 @@ test_config.dummy_include2"""
def test_make_wsgi_app(self):
import pyramid.config
- from pyramid.router import Router
from pyramid.interfaces import IApplicationCreated
+ from pyramid.router import Router
manager = DummyThreadLocalManager()
config = self._makeOne()
@@ -920,9 +925,10 @@ test_config.dummy_include2"""
root_config.include(dummy_subapp, route_prefix='nested')
def test_include_with_missing_source_file(self):
- from pyramid.exceptions import ConfigurationError
import inspect
+ from pyramid.exceptions import ConfigurationError
+
config = self._makeOne()
class DummyInspect:
@@ -973,8 +979,9 @@ test_config.dummy_include2"""
def test_scan_integration(self):
from zope.interface import alsoProvides
+
from pyramid.view import render_view_to_response
- import tests.test_config.pkgs.scannable as package
+ from tests.test_config.pkgs import scannable as package
config = self._makeOne(autocommit=True)
config.scan(package)
@@ -1079,8 +1086,9 @@ test_config.dummy_include2"""
def test_scan_integration_with_ignore(self):
from zope.interface import alsoProvides
+
from pyramid.view import render_view_to_response
- import tests.test_config.pkgs.scannable as package
+ from tests.test_config.pkgs import scannable as package
config = self._makeOne(autocommit=True)
config.scan(package, ignore='tests.test_config.pkgs.scannable.another')
@@ -1100,6 +1108,7 @@ test_config.dummy_include2"""
def test_scan_integration_dottedname_package(self):
from zope.interface import alsoProvides
+
from pyramid.view import render_view_to_response
config = self._makeOne(autocommit=True)
@@ -1143,8 +1152,8 @@ test_config.dummy_include2"""
sys.path.remove(path)
def test_scan_integration_conflict(self):
- from tests.test_config.pkgs import selfscan
from pyramid.config import Configurator
+ from tests.test_config.pkgs import selfscan
c = Configurator()
c.scan(selfscan)
diff --git a/tests/test_config/test_predicates.py b/tests/test_config/test_predicates.py
index 8017fc898..9d13d84fd 100644
--- a/tests/test_config/test_predicates.py
+++ b/tests/test_config/test_predicates.py
@@ -5,8 +5,8 @@ from pyramid.util import text_
class TestPredicateList(unittest.TestCase):
def _makeOne(self):
- from pyramid.config.predicates import PredicateList
from pyramid import predicates
+ from pyramid.config.predicates import PredicateList
inst = PredicateList()
for name, factory in (
@@ -19,6 +19,7 @@ class TestPredicateList(unittest.TestCase):
('containment', predicates.ContainmentPredicate),
('request_type', predicates.RequestTypePredicate),
('match_param', predicates.MatchParamPredicate),
+ ('is_authenticated', predicates.IsAuthenticatedPredicate),
('custom', predicates.CustomPredicate),
('traverse', predicates.TraversePredicate),
):
@@ -38,6 +39,19 @@ class TestPredicateList(unittest.TestCase):
def test_ordering_number_of_predicates(self):
from pyramid.config.predicates import predvalseq
+ order0, _, _ = self._callFUT(
+ xhr='xhr',
+ request_method='request_method',
+ path_info='path_info',
+ request_param='param',
+ match_param='foo=bar',
+ header='header',
+ accept='accept',
+ is_authenticated=True,
+ containment='containment',
+ request_type='request_type',
+ custom=predvalseq([DummyCustomPredicate()]),
+ )
order1, _, _ = self._callFUT(
xhr='xhr',
request_method='request_method',
@@ -121,6 +135,7 @@ class TestPredicateList(unittest.TestCase):
)
order11, _, _ = self._callFUT(xhr='xhr')
order12, _, _ = self._callFUT()
+ self.assertTrue(order1 > order0)
self.assertEqual(order1, order2)
self.assertTrue(order3 > order2)
self.assertTrue(order4 > order3)
@@ -131,7 +146,7 @@ class TestPredicateList(unittest.TestCase):
self.assertTrue(order9 > order8)
self.assertTrue(order10 > order9)
self.assertTrue(order11 > order10)
- self.assertTrue(order12 > order10)
+ self.assertTrue(order12 > order11)
def test_ordering_importance_of_predicates(self):
from pyramid.config.predicates import predvalseq
@@ -145,7 +160,8 @@ class TestPredicateList(unittest.TestCase):
order7, _, _ = self._callFUT(containment='containment')
order8, _, _ = self._callFUT(request_type='request_type')
order9, _, _ = self._callFUT(match_param='foo=bar')
- order10, _, _ = self._callFUT(
+ order10, _, _ = self._callFUT(is_authenticated=True)
+ order11, _, _ = self._callFUT(
custom=predvalseq([DummyCustomPredicate()])
)
self.assertTrue(order1 > order2)
@@ -157,6 +173,7 @@ class TestPredicateList(unittest.TestCase):
self.assertTrue(order7 > order8)
self.assertTrue(order8 > order9)
self.assertTrue(order9 > order10)
+ self.assertTrue(order10 > order11)
def test_ordering_importance_and_number(self):
from pyramid.config.predicates import predvalseq
@@ -296,6 +313,7 @@ class TestPredicateList(unittest.TestCase):
]
),
match_param='foo=bar',
+ is_authenticated=False,
)
self.assertEqual(predicates[0].text(), 'xhr = True')
self.assertEqual(
@@ -308,9 +326,10 @@ class TestPredicateList(unittest.TestCase):
self.assertEqual(predicates[6].text(), 'containment = containment')
self.assertEqual(predicates[7].text(), 'request_type = request_type')
self.assertEqual(predicates[8].text(), "match_param foo=bar")
- self.assertEqual(predicates[9].text(), 'custom predicate')
- self.assertEqual(predicates[10].text(), 'classmethod predicate')
- self.assertTrue(predicates[11].text().startswith('custom predicate'))
+ self.assertEqual(predicates[9].text(), "is_authenticated = False")
+ self.assertEqual(predicates[10].text(), 'custom predicate')
+ self.assertEqual(predicates[11].text(), 'classmethod predicate')
+ self.assertTrue(predicates[12].text().startswith('custom predicate'))
def test_predicate_text_is_correct_when_multiple(self):
_, predicates, _ = self._callFUT(
@@ -434,6 +453,30 @@ class TestPredicateList(unittest.TestCase):
request.headers = {'foo': 'nobar', 'spamme': 'ham'}
self.assertFalse(predicates[0](Dummy(), request))
+ def test_is_authenticated_true_matches(self):
+ _, predicates, _ = self._callFUT(is_authenticated=True)
+ request = DummyRequest()
+ request.is_authenticated = True
+ self.assertTrue(predicates[0](Dummy(), request))
+
+ def test_is_authenticated_true_fails(self):
+ _, predicates, _ = self._callFUT(is_authenticated=True)
+ request = DummyRequest()
+ request.is_authenticated = False
+ self.assertFalse(predicates[0](Dummy(), request))
+
+ def test_is_authenticated_false_matches(self):
+ _, predicates, _ = self._callFUT(is_authenticated=False)
+ request = DummyRequest()
+ request.is_authenticated = False
+ self.assertTrue(predicates[0](Dummy(), request))
+
+ def test_is_authenticated_false_fails(self):
+ _, predicates, _ = self._callFUT(is_authenticated=False)
+ request = DummyRequest()
+ request.is_authenticated = True
+ self.assertFalse(predicates[0](Dummy(), request))
+
def test_unknown_predicate(self):
from pyramid.exceptions import ConfigurationError
diff --git a/tests/test_config/test_routes.py b/tests/test_config/test_routes.py
index 8227784ec..605f61857 100644
--- a/tests/test_config/test_routes.py
+++ b/tests/test_config/test_routes.py
@@ -184,6 +184,18 @@ class RoutesConfiguratorMixinTests(unittest.TestCase):
request.params = {}
self.assertEqual(predicate(None, request), False)
+ def test_add_route_with_is_authenticated(self):
+ config = self._makeOne(autocommit=True)
+ config.add_route('name', 'path', is_authenticated=True)
+ route = self._assertRoute(config, 'name', 'path', 1)
+ predicate = route.predicates[0]
+ request = self._makeRequest(config)
+ request.is_authenticated = True
+ self.assertEqual(predicate(None, request), True)
+ request = self._makeRequest(config)
+ request.is_authenticated = False
+ self.assertEqual(predicate(None, request), False)
+
def test_add_route_with_custom_predicates(self):
import warnings
diff --git a/tests/test_config/test_security.py b/tests/test_config/test_security.py
index 6c73ead1e..71142a8fa 100644
--- a/tests/test_config/test_security.py
+++ b/tests/test_config/test_security.py
@@ -20,8 +20,7 @@ class ConfiguratorSecurityMethodsTests(unittest.TestCase):
self.assertEqual(config.registry.getUtility(ISecurityPolicy), policy)
def test_set_authentication_policy_with_security_policy(self):
- from pyramid.interfaces import IAuthorizationPolicy
- from pyramid.interfaces import ISecurityPolicy
+ from pyramid.interfaces import IAuthorizationPolicy, ISecurityPolicy
config = self._makeOne()
security_policy = object()
@@ -46,9 +45,11 @@ class ConfiguratorSecurityMethodsTests(unittest.TestCase):
)
def test_set_authentication_policy_with_authz_policy(self):
- from pyramid.interfaces import IAuthenticationPolicy
- from pyramid.interfaces import IAuthorizationPolicy
- from pyramid.interfaces import ISecurityPolicy
+ from pyramid.interfaces import (
+ IAuthenticationPolicy,
+ IAuthorizationPolicy,
+ ISecurityPolicy,
+ )
from pyramid.security import LegacySecurityPolicy
config = self._makeOne()
@@ -65,9 +66,11 @@ class ConfiguratorSecurityMethodsTests(unittest.TestCase):
)
def test_set_authentication_policy_with_authz_policy_autocommit(self):
- from pyramid.interfaces import IAuthenticationPolicy
- from pyramid.interfaces import IAuthorizationPolicy
- from pyramid.interfaces import ISecurityPolicy
+ from pyramid.interfaces import (
+ IAuthenticationPolicy,
+ IAuthorizationPolicy,
+ ISecurityPolicy,
+ )
from pyramid.security import LegacySecurityPolicy
config = self._makeOne(autocommit=True)
@@ -100,8 +103,10 @@ class ConfiguratorSecurityMethodsTests(unittest.TestCase):
)
def test_set_authorization_policy_with_authn_policy(self):
- from pyramid.interfaces import IAuthorizationPolicy
- from pyramid.interfaces import IAuthenticationPolicy
+ from pyramid.interfaces import (
+ IAuthenticationPolicy,
+ IAuthorizationPolicy,
+ )
config = self._makeOne()
authn_policy = object()
@@ -114,8 +119,10 @@ class ConfiguratorSecurityMethodsTests(unittest.TestCase):
)
def test_set_authorization_policy_with_authn_policy_autocommit(self):
- from pyramid.interfaces import IAuthorizationPolicy
- from pyramid.interfaces import IAuthenticationPolicy
+ from pyramid.interfaces import (
+ IAuthenticationPolicy,
+ IAuthorizationPolicy,
+ )
config = self._makeOne(autocommit=True)
authn_policy = object()
diff --git a/tests/test_config/test_settings.py b/tests/test_config/test_settings.py
index 2fe769add..39a384b3d 100644
--- a/tests/test_config/test_settings.py
+++ b/tests/test_config/test_settings.py
@@ -50,8 +50,8 @@ class TestSettingsConfiguratorMixin(unittest.TestCase):
self.assertEqual(settings['b'], 2)
def test_add_settings_settings_not_yet_registered(self):
- from pyramid.registry import Registry
from pyramid.interfaces import ISettings
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
@@ -60,8 +60,8 @@ class TestSettingsConfiguratorMixin(unittest.TestCase):
self.assertEqual(settings['a'], 1)
def test_add_settings_settings_None(self):
- from pyramid.registry import Registry
from pyramid.interfaces import ISettings
+ from pyramid.registry import Registry
reg = Registry()
config = self._makeOne(reg)
diff --git a/tests/test_config/test_testing.py b/tests/test_config/test_testing.py
index e379e41bc..5cdd19b50 100644
--- a/tests/test_config/test_testing.py
+++ b/tests/test_config/test_testing.py
@@ -54,8 +54,8 @@ class TestingConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(val, True)
def test_testing_resources(self):
- from pyramid.traversal import find_resource
from pyramid.interfaces import ITraverser
+ from pyramid.traversal import find_resource
ob1 = object()
ob2 = object()
diff --git a/tests/test_config/test_tweens.py b/tests/test_config/test_tweens.py
index b8cf15e12..19c938a0c 100644
--- a/tests/test_config/test_tweens.py
+++ b/tests/test_config/test_tweens.py
@@ -45,8 +45,7 @@ class TestTweensConfiguratorMixin(unittest.TestCase):
def test_add_tweens_names_with_underover(self):
from pyramid.interfaces import ITweens
- from pyramid.tweens import excview_tween_factory
- from pyramid.tweens import MAIN
+ from pyramid.tweens import MAIN, excview_tween_factory
config = self._makeOne()
config.add_tween('tests.test_config.dummy_tween_factory', over=MAIN)
@@ -316,7 +315,7 @@ class TestTweens(unittest.TestCase):
)
def test_implicit_ordering_5(self):
- from pyramid.tweens import MAIN, INGRESS
+ from pyramid.tweens import INGRESS, MAIN
tweens = self._makeOne()
add = tweens.add_implicit
diff --git a/tests/test_config/test_views.py b/tests/test_config/test_views.py
index 2a55ad45d..65271f0d6 100644
--- a/tests/test_config/test_views.py
+++ b/tests/test_config/test_views.py
@@ -32,10 +32,13 @@ class TestViewsConfigurationMixin(unittest.TestCase):
name='',
):
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
if exc_iface:
classifier = IExceptionViewClassifier
@@ -113,9 +116,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_view_with_request_type(self):
- from pyramid.renderers import null_renderer
from zope.interface import directlyProvides
+
from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
config = self._makeOne(autocommit=True)
@@ -296,6 +300,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_with_http_cache(self):
import datetime
+
from pyramid.response import Response
response = Response('OK')
@@ -415,9 +420,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(request.__view__.__class__, view)
def test_add_view_context_as_class(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
+ from pyramid.renderers import null_renderer
+
view = lambda *arg: 'OK'
class Foo:
@@ -464,9 +470,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_for_as_class(self):
# ``for_`` is older spelling for ``context``
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
+ from pyramid.renderers import null_renderer
+
view = lambda *arg: 'OK'
class Foo:
@@ -505,11 +512,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper, view)
def test_add_view_register_secured_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import ISecuredView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import IRequest, ISecuredView, IViewClassifier
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__call_permissive__ = view
@@ -524,11 +530,14 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper, view)
def test_add_view_exception_register_secured_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IView,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__call_permissive__ = view
@@ -545,13 +554,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper, view)
def test_add_view_same_phash_overrides_existing_single_view(self):
- from pyramid.renderers import null_renderer
from hashlib import md5
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
phash = md5()
phash.update(b'xhr = True')
@@ -573,13 +585,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_exc_same_phash_overrides_existing_single_view(self):
- from pyramid.renderers import null_renderer
from hashlib import md5
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ )
+ from pyramid.renderers import null_renderer
phash = md5()
phash.update(b'xhr = True')
@@ -611,12 +626,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_default_phash_overrides_no_phash(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'NOT OK'
config = self._makeOne(autocommit=True)
@@ -635,12 +653,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_exc_default_phash_overrides_no_phash(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'NOT OK'
config = self._makeOne(autocommit=True)
@@ -666,13 +687,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_default_phash_overrides_default_phash(self):
+ from zope.interface import Interface
+
from pyramid.config.predicates import DEFAULT_PHASH
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
from pyramid.renderers import null_renderer
- from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
view = lambda *arg: 'NOT OK'
view.__phash__ = DEFAULT_PHASH
@@ -692,13 +716,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_exc_default_phash_overrides_default_phash(self):
+ from zope.interface import implementedBy
+
from pyramid.config.predicates import DEFAULT_PHASH
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ )
from pyramid.renderers import null_renderer
- from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IMultiView
view = lambda *arg: 'NOT OK'
view.__phash__ = DEFAULT_PHASH
@@ -725,12 +752,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_multiview_replaces_existing_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__phash__ = 'abc'
@@ -744,13 +774,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK')
def test_add_view_exc_multiview_replaces_existing_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__phash__ = 'abc'
@@ -777,12 +810,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK')
def test_add_view_multiview_replaces_existing_securedview(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import ISecuredView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ ISecuredView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__phash__ = 'abc'
@@ -796,13 +832,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK')
def test_add_view_exc_multiview_replaces_existing_securedview(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import ISecuredView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ ISecuredView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
view.__phash__ = 'abc'
@@ -829,12 +868,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK')
def test_add_view_with_accept_multiview_replaces_existing_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
def view(context, request):
return 'OK'
@@ -905,13 +947,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK3')
def test_add_view_exc_with_accept_multiview_replaces_existing_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
def view(context, request):
return 'OK'
@@ -950,12 +995,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK2')
def test_add_view_multiview_replaces_existing_view_with___accept__(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
def view(context, request):
return 'OK'
@@ -980,13 +1028,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_exc_mulview_replaces_existing_view_with___accept__(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
def view(context, request):
return 'OK'
@@ -1024,11 +1075,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, request), 'OK')
def test_add_view_multiview_replaces_multiview(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import IMultiView, IRequest, IViewClassifier
+ from pyramid.renderers import null_renderer
view = DummyMultiView()
config = self._makeOne(autocommit=True)
@@ -1045,12 +1095,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK1')
def test_add_view_exc_multiview_replaces_multiviews(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
hot_view = DummyMultiView()
exc_view = DummyMultiView()
@@ -1090,12 +1143,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(exc_wrapper(None, None), 'OK1')
def test_add_view_exc_multiview_replaces_only_exc_multiview(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
hot_view = DummyMultiView()
exc_view = DummyMultiView()
@@ -1136,12 +1192,15 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(exc_wrapper(None, None), 'OK1')
def test_add_view_multiview_context_superclass_then_subclass(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
class ISuper(Interface):
pass
@@ -1168,13 +1227,16 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper(None, None), 'OK2')
def test_add_view_multiview_exception_superclass_then_subclass(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
+ from pyramid.renderers import null_renderer
class Super(Exception):
pass
@@ -1212,9 +1274,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(wrapper_exc_view(None, None), 'OK2')
def test_add_view_multiview_call_ordering(self):
- from pyramid.renderers import null_renderer as nr
from zope.interface import directlyProvides
+ from pyramid.renderers import null_renderer as nr
+
def view1(context, request):
return 'view1'
@@ -1423,9 +1486,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(response, 'hello')
def test_add_view_multiview___discriminator__(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
+ from pyramid.renderers import null_renderer
+
class IFoo(Interface):
pass
@@ -1443,10 +1507,12 @@ class TestViewsConfigurationMixin(unittest.TestCase):
foo = Foo()
bar = Bar()
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+ from pyramid.interfaces import (
+ IMultiView,
+ IRequest,
+ IView,
+ IViewClassifier,
+ )
view = lambda *arg: 'OK'
view.__phash__ = 'abc'
@@ -1465,8 +1531,8 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_view_with_template_renderer(self):
- from tests import test_config
from pyramid.interfaces import ISettings
+ from tests import test_config
class view:
def __init__(self, context, request):
@@ -1519,8 +1585,8 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result.body, b'moo')
def test_add_view_with_template_renderer_no_callable(self):
- from tests import test_config
from pyramid.interfaces import ISettings
+ from tests import test_config
config = self._makeOne(autocommit=True)
renderer = self._registerRenderer(config)
@@ -1540,9 +1606,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result.settings, settings)
def test_add_view_with_request_type_as_iface(self):
- from pyramid.renderers import null_renderer
from zope.interface import directlyProvides
+ from pyramid.renderers import null_renderer
+
def view(context, request):
return 'OK'
@@ -1583,9 +1650,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertRaises(ConfigurationExecutionError, config.commit)
def test_add_view_with_route_name_exception(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
+ from pyramid.renderers import null_renderer
+
view = lambda *arg: 'OK'
config = self._makeOne(autocommit=True)
config.add_route('foo', '/a/b')
@@ -1742,6 +1810,46 @@ class TestViewsConfigurationMixin(unittest.TestCase):
request.is_xhr = False
self._assertNotFound(wrapper, None, request)
+ def test_add_view_with_is_authenticated_true_matches(self):
+ from pyramid.renderers import null_renderer as nr
+
+ view = lambda *arg: 'OK'
+ config = self._makeOne(autocommit=True)
+ config.add_view(view=view, is_authenticated=True, renderer=nr)
+ wrapper = self._getViewCallable(config)
+ request = self._makeRequest(config)
+ request.is_authenticated = True
+ self.assertEqual(wrapper(None, request), 'OK')
+
+ def test_add_view_with_is_authenticated_true_no_match(self):
+ view = lambda *arg: 'OK'
+ config = self._makeOne(autocommit=True)
+ config.add_view(view=view, is_authenticated=True)
+ wrapper = self._getViewCallable(config)
+ request = self._makeRequest(config)
+ request.is_authenticated = False
+ self._assertNotFound(wrapper, None, request)
+
+ def test_add_view_with_is_authenticated_false_matches(self):
+ from pyramid.renderers import null_renderer as nr
+
+ view = lambda *arg: 'OK'
+ config = self._makeOne(autocommit=True)
+ config.add_view(view=view, is_authenticated=False, renderer=nr)
+ wrapper = self._getViewCallable(config)
+ request = self._makeRequest(config)
+ request.is_authenticated = False
+ self.assertEqual(wrapper(None, request), 'OK')
+
+ def test_add_view_with_is_authenticated_false_no_match(self):
+ view = lambda *arg: 'OK'
+ config = self._makeOne(autocommit=True)
+ config.add_view(view=view, is_authenticated=False)
+ wrapper = self._getViewCallable(config)
+ request = self._makeRequest(config)
+ request.is_authenticated = True
+ self._assertNotFound(wrapper, None, request)
+
def test_add_view_with_header_badregex(self):
view = lambda *arg: 'OK'
config = self._makeOne()
@@ -1827,9 +1935,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_view_with_containment_true(self):
- from pyramid.renderers import null_renderer
from zope.interface import directlyProvides
+ from pyramid.renderers import null_renderer
+
view = lambda *arg: 'OK'
config = self._makeOne(autocommit=True)
config.add_view(view=view, containment=IDummy, renderer=null_renderer)
@@ -1847,9 +1956,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self._assertNotFound(wrapper, context, None)
def test_add_view_with_containment_dottedname(self):
- from pyramid.renderers import null_renderer
from zope.interface import directlyProvides
+ from pyramid.renderers import null_renderer
+
view = lambda *arg: 'OK'
config = self._makeOne(autocommit=True)
config.add_view(
@@ -1890,6 +2000,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_with_custom_predicates_match(self):
import warnings
+
from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
@@ -1935,6 +2046,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_custom_predicate_bests_standard_predicate(self):
import warnings
+
from pyramid.renderers import null_renderer
view = lambda *arg: 'OK'
@@ -2118,10 +2230,11 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(Mapper.kw['mapper'], Mapper)
def test_add_view_with_view_defaults(self):
- from pyramid.renderers import null_renderer
- from pyramid.exceptions import PredicateMismatch
from zope.interface import directlyProvides
+ from pyramid.exceptions import PredicateMismatch
+ from pyramid.renderers import null_renderer
+
class view:
__view_defaults__ = {'containment': 'tests.test_config.IDummy'}
@@ -2143,10 +2256,11 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertRaises(PredicateMismatch, wrapper, context, request)
def test_add_view_with_view_defaults_viewname_is_dottedname_kwarg(self):
- from pyramid.renderers import null_renderer
- from pyramid.exceptions import PredicateMismatch
from zope.interface import directlyProvides
+ from pyramid.exceptions import PredicateMismatch
+ from pyramid.renderers import null_renderer
+
config = self._makeOne(autocommit=True)
config.add_view(
view='tests.test_config.test_views.DummyViewDefaultsClass',
@@ -2162,10 +2276,11 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertRaises(PredicateMismatch, wrapper, context, request)
def test_add_view_with_view_defaults_viewname_is_dottedname_nonkwarg(self):
- from pyramid.renderers import null_renderer
- from pyramid.exceptions import PredicateMismatch
from zope.interface import directlyProvides
+ from pyramid.exceptions import PredicateMismatch
+ from pyramid.renderers import null_renderer
+
config = self._makeOne(autocommit=True)
config.add_view(
'tests.test_config.test_views.DummyViewDefaultsClass',
@@ -2209,8 +2324,8 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertRaises(ConfigurationConflictError, config.commit)
def test_add_view_class_method_no_attr(self):
- from pyramid.renderers import null_renderer
from pyramid.exceptions import ConfigurationError
+ from pyramid.renderers import null_renderer
config = self._makeOne(autocommit=True)
@@ -2225,6 +2340,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_exception_only_no_regular_view(self):
from zope.interface import implementedBy
+
from pyramid.renderers import null_renderer
view1 = lambda *arg: 'OK'
@@ -2242,6 +2358,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_view_exception_only(self):
from zope.interface import implementedBy
+
from pyramid.renderers import null_renderer
view1 = lambda *arg: 'OK'
@@ -2274,6 +2391,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_exception_view(self):
from zope.interface import implementedBy
+
from pyramid.renderers import null_renderer
view1 = lambda *arg: 'OK'
@@ -2288,6 +2406,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_exception_view_with_subclass(self):
from zope.interface import implementedBy
+
from pyramid.renderers import null_renderer
view1 = lambda *arg: 'OK'
@@ -2348,10 +2467,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_exception_view_with_view_defaults(self):
- from pyramid.renderers import null_renderer
+ from zope.interface import directlyProvides, implementedBy
+
from pyramid.exceptions import PredicateMismatch
- from zope.interface import directlyProvides
- from zope.interface import implementedBy
+ from pyramid.renderers import null_renderer
class view:
__view_defaults__ = {'containment': 'tests.test_config.IDummy'}
@@ -2442,10 +2561,10 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result(None, request).body, b'foo')
def test_add_static_view_here_no_utility_registered(self):
- from pyramid.renderers import null_renderer
from zope.interface import Interface
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import IView, IViewClassifier
+ from pyramid.renderers import null_renderer
config = self._makeOne(autocommit=True)
config.add_static_view('static', 'files', renderer=null_renderer)
@@ -2486,6 +2605,7 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_static_view_absolute(self):
import os
+
from pyramid.interfaces import IStaticURLInfo
info = DummyStaticURLInfo()
@@ -2497,10 +2617,11 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(info.added, [(config, 'static', static_path, {})])
def test_add_forbidden_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPForbidden
+ from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
config = self._makeOne(autocommit=True)
view = lambda *arg: 'OK'
@@ -2516,8 +2637,9 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_forbidden_view_no_view_argument(self):
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPForbidden
+ from pyramid.interfaces import IRequest
config = self._makeOne(autocommit=True)
config.setup_registry()
@@ -2571,12 +2693,12 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_forbidden_view_with_view_defaults(self):
- from pyramid.interfaces import IRequest
- from pyramid.renderers import null_renderer
+ from zope.interface import directlyProvides, implementedBy
+
from pyramid.exceptions import PredicateMismatch
from pyramid.httpexceptions import HTTPForbidden
- from zope.interface import directlyProvides
- from zope.interface import implementedBy
+ from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
class view:
__view_defaults__ = {'containment': 'tests.test_config.IDummy'}
@@ -2603,10 +2725,11 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertRaises(PredicateMismatch, wrapper, context, request)
def test_add_notfound_view(self):
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPNotFound
+ from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
config = self._makeOne(autocommit=True)
view = lambda *arg: arg
@@ -2622,8 +2745,9 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_notfound_view_no_view_argument(self):
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPNotFound
+ from pyramid.interfaces import IRequest
config = self._makeOne(autocommit=True)
config.setup_registry()
@@ -2677,11 +2801,12 @@ class TestViewsConfigurationMixin(unittest.TestCase):
)
def test_add_notfound_view_append_slash(self):
- from pyramid.response import Response
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
+
+ from pyramid.httpexceptions import HTTPNotFound, HTTPTemporaryRedirect
from pyramid.interfaces import IRequest
- from pyramid.httpexceptions import HTTPTemporaryRedirect, HTTPNotFound
+ from pyramid.renderers import null_renderer
+ from pyramid.response import Response
config = self._makeOne(autocommit=True)
config.add_route('foo', '/foo/')
@@ -2706,11 +2831,12 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result.location, '/scriptname/foo/?a=1&b=2')
def test_add_notfound_view_append_slash_custom_response(self):
- from pyramid.response import Response
- from pyramid.renderers import null_renderer
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPMovedPermanently, HTTPNotFound
+ from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
+ from pyramid.response import Response
config = self._makeOne(autocommit=True)
config.add_route('foo', '/foo/')
@@ -2735,12 +2861,12 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result.location, '/scriptname/foo/?a=1&b=2')
def test_add_notfound_view_with_view_defaults(self):
- from pyramid.interfaces import IRequest
- from pyramid.renderers import null_renderer
+ from zope.interface import directlyProvides, implementedBy
+
from pyramid.exceptions import PredicateMismatch
from pyramid.httpexceptions import HTTPNotFound
- from zope.interface import directlyProvides
- from zope.interface import implementedBy
+ from pyramid.interfaces import IRequest
+ from pyramid.renderers import null_renderer
class view:
__view_defaults__ = {'containment': 'tests.test_config.IDummy'}
@@ -2768,8 +2894,9 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_notfound_view_with_renderer(self):
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPNotFound
+ from pyramid.interfaces import IRequest
config = self._makeOne(autocommit=True)
view = lambda *arg: {}
@@ -2786,8 +2913,9 @@ class TestViewsConfigurationMixin(unittest.TestCase):
def test_add_forbidden_view_with_renderer(self):
from zope.interface import implementedBy
- from pyramid.interfaces import IRequest
+
from pyramid.httpexceptions import HTTPForbidden
+ from pyramid.interfaces import IRequest
config = self._makeOne(autocommit=True)
view = lambda *arg: {}
@@ -2822,8 +2950,8 @@ class TestViewsConfigurationMixin(unittest.TestCase):
self.assertEqual(result, test_config)
def test_add_normal_and_exception_view_intr_derived_callable(self):
- from pyramid.renderers import null_renderer
from pyramid.exceptions import BadCSRFToken
+ from pyramid.renderers import null_renderer
config = self._makeOne(autocommit=True)
introspector = DummyIntrospector()
@@ -3074,12 +3202,14 @@ class TestMultiView(unittest.TestCase):
def test_class_implements_ISecuredView(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import ISecuredView
verifyClass(ISecuredView, self._getTargetClass())
def test_instance_implements_ISecuredView(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import ISecuredView
verifyObject(ISecuredView, self._makeOne())
@@ -3732,15 +3862,17 @@ class TestStaticURLInfo(unittest.TestCase):
return request
def test_verifyClass(self):
- from pyramid.interfaces import IStaticURLInfo
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import IStaticURLInfo
+
verifyClass(IStaticURLInfo, self._getTargetClass())
def test_verifyObject(self):
- from pyramid.interfaces import IStaticURLInfo
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IStaticURLInfo
+
verifyObject(IStaticURLInfo, self._makeOne())
def test_generate_missing(self):
diff --git a/tests/test_docs.py b/tests/test_docs.py
index 46c9ed765..952b6ba8c 100644
--- a/tests/test_docs.py
+++ b/tests/test_docs.py
@@ -9,12 +9,12 @@ if 0:
@classmethod
def test_docs(cls):
- import os
- import pkg_resources
- import manuel.testing
- import manuel.codeblock
import manuel.capture
+ import manuel.codeblock
import manuel.ignore
+ import manuel.testing
+ import os
+ import pkg_resources
m = manuel.ignore.Manuel()
m += manuel.codeblock.Manuel()
diff --git a/tests/test_events.py b/tests/test_events.py
index 285a84274..bc35c5207 100644
--- a/tests/test_events.py
+++ b/tests/test_events.py
@@ -13,16 +13,18 @@ class NewRequestEventTests(unittest.TestCase):
return self._getTargetClass()(request)
def test_class_conforms_to_INewRequest(self):
- from pyramid.interfaces import INewRequest
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import INewRequest
+
klass = self._getTargetClass()
verifyClass(INewRequest, klass)
def test_instance_conforms_to_INewRequest(self):
- from pyramid.interfaces import INewRequest
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import INewRequest
+
request = DummyRequest()
inst = self._makeOne(request)
verifyObject(INewRequest, inst)
@@ -43,16 +45,18 @@ class NewResponseEventTests(unittest.TestCase):
return self._getTargetClass()(request, response)
def test_class_conforms_to_INewResponse(self):
- from pyramid.interfaces import INewResponse
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import INewResponse
+
klass = self._getTargetClass()
verifyClass(INewResponse, klass)
def test_instance_conforms_to_INewResponse(self):
- from pyramid.interfaces import INewResponse
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import INewResponse
+
request = DummyRequest()
response = DummyResponse()
inst = self._makeOne(request, response)
@@ -76,15 +80,17 @@ class ApplicationCreatedEventTests(unittest.TestCase):
return self._getTargetClass()(context)
def test_class_conforms_to_IApplicationCreated(self):
- from pyramid.interfaces import IApplicationCreated
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import IApplicationCreated
+
verifyClass(IApplicationCreated, self._getTargetClass())
def test_object_conforms_to_IApplicationCreated(self):
- from pyramid.interfaces import IApplicationCreated
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IApplicationCreated
+
verifyObject(IApplicationCreated, self._makeOne())
@@ -95,15 +101,17 @@ class WSGIApplicationCreatedEventTests(ApplicationCreatedEventTests):
return WSGIApplicationCreatedEvent
def test_class_conforms_to_IWSGIApplicationCreatedEvent(self):
- from pyramid.interfaces import IWSGIApplicationCreatedEvent
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import IWSGIApplicationCreatedEvent
+
verifyClass(IWSGIApplicationCreatedEvent, self._getTargetClass())
def test_object_conforms_to_IWSGIApplicationCreatedEvent(self):
- from pyramid.interfaces import IWSGIApplicationCreatedEvent
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IWSGIApplicationCreatedEvent
+
verifyObject(IWSGIApplicationCreatedEvent, self._makeOne())
@@ -120,12 +128,14 @@ class ContextFoundEventTests(unittest.TestCase):
def test_class_conforms_to_IContextFound(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IContextFound
verifyClass(IContextFound, self._getTargetClass())
def test_instance_conforms_to_IContextFound(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IContextFound
verifyObject(IContextFound, self._makeOne())
@@ -139,12 +149,14 @@ class AfterTraversalEventTests(ContextFoundEventTests):
def test_class_conforms_to_IAfterTraversal(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IAfterTraversal
verifyClass(IAfterTraversal, self._getTargetClass())
def test_instance_conforms_to_IAfterTraversal(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IAfterTraversal
verifyObject(IAfterTraversal, self._makeOne())
@@ -163,12 +175,14 @@ class BeforeTraversalEventTests(unittest.TestCase):
def test_class_conforms_to_IBeforeTraversal(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IBeforeTraversal
verifyClass(IBeforeTraversal, self._getTargetClass())
def test_instance_conforms_to_IBeforeTraversal(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IBeforeTraversal
verifyObject(IBeforeTraversal, self._makeOne())
@@ -312,6 +326,7 @@ class TestBeforeRender(unittest.TestCase):
) # see https://github.com/Pylons/pyramid/issues/3237
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IBeforeRender
event = self._makeOne({})
diff --git a/tests/test_i18n.py b/tests/test_i18n.py
index b8b11830e..206eea290 100644
--- a/tests/test_i18n.py
+++ b/tests/test_i18n.py
@@ -499,8 +499,8 @@ class TestLocalizerRequestMixin(unittest.TestCase):
self.assertEqual(request.localizer, dummy)
def test_localizer_from_mo(self):
- from pyramid.interfaces import ITranslationDirectories
from pyramid.i18n import Localizer
+ from pyramid.interfaces import ITranslationDirectories
localedirs = [localedir]
self.config.registry.registerUtility(
@@ -517,8 +517,8 @@ class TestLocalizerRequestMixin(unittest.TestCase):
self.assertTrue(hasattr(result, 'pluralize'))
def test_localizer_from_mo_bad_mo(self):
- from pyramid.interfaces import ITranslationDirectories
from pyramid.i18n import Localizer
+ from pyramid.interfaces import ITranslationDirectories
localedirs = [localedir]
self.config.registry.registerUtility(
diff --git a/tests/test_integration.py b/tests/test_integration.py
index 638ddb2c5..f671b7c0b 100644
--- a/tests/test_integration.py
+++ b/tests/test_integration.py
@@ -34,8 +34,8 @@ def wsgiapptest(environ, start_response):
class WGSIAppPlusViewConfigTests(unittest.TestCase):
def test_it(self):
- from venusian import ATTACH_ATTR
import types
+ from venusian import ATTACH_ATTR
self.assertTrue(getattr(wsgiapptest, ATTACH_ATTR))
self.assertIsInstance(wsgiapptest, types.FunctionType)
@@ -45,10 +45,9 @@ class WGSIAppPlusViewConfigTests(unittest.TestCase):
self.assertEqual(result, '123')
def test_scanned(self):
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
from pyramid.config import Configurator
+ from pyramid.interfaces import IRequest, IView, IViewClassifier
+
from . import test_integration
config = Configurator()
@@ -281,9 +280,10 @@ class TestStaticAppNoSubpath(unittest.TestCase):
staticapp = static_view(os.path.join(here, 'fixtures'), use_subpath=False)
def _makeRequest(self, extra):
- from pyramid.request import Request
from io import BytesIO
+ from pyramid.request import Request
+
kw = {
'PATH_INFO': '',
'SCRIPT_NAME': '',
diff --git a/tests/test_path.py b/tests/test_path.py
index 384460fb1..479e12e40 100644
--- a/tests/test_path.py
+++ b/tests/test_path.py
@@ -28,6 +28,7 @@ class TestCallerPath(unittest.TestCase):
def test_memoization_has_abspath(self):
import os
+
from . import test_path
test_path.__abspath__ = '/foo/bar'
@@ -36,6 +37,7 @@ class TestCallerPath(unittest.TestCase):
def test_memoization_success(self):
import os
+
from . import test_path
result = self._callFUT('a/b/c')
@@ -166,8 +168,8 @@ class TestPackageOf(unittest.TestCase):
self.assertEqual(result, tests)
def test_it_module(self):
- import tests.test_path
import tests
+ import tests.test_path
package = DummyPackageOrModule(tests.test_path)
result = self._callFUT(package)
@@ -222,8 +224,8 @@ class TestResolver(unittest.TestCase):
return self._getTargetClass()(package)
def test_get_package_caller_package(self):
- import tests
from pyramid.path import CALLER_PACKAGE
+ import tests
self.assertEqual(self._makeOne(CALLER_PACKAGE).get_package(), tests)
@@ -295,8 +297,7 @@ class TestAssetResolver(unittest.TestCase):
self.assertRaises(ValueError, inst.resolve, 'test_asset.py')
def test_resolve_relspec_caller_package(self):
- from pyramid.path import PkgResourcesAssetDescriptor
- from pyramid.path import CALLER_PACKAGE
+ from pyramid.path import CALLER_PACKAGE, PkgResourcesAssetDescriptor
inst = self._makeOne(CALLER_PACKAGE)
r = inst.resolve('test_asset.py')
@@ -314,15 +315,17 @@ class TestPkgResourcesAssetDescriptor(unittest.TestCase):
return self._getTargetClass()(pkg, path)
def test_class_conforms_to_IAssetDescriptor(self):
- from pyramid.interfaces import IAssetDescriptor
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import IAssetDescriptor
+
verifyClass(IAssetDescriptor, self._getTargetClass())
def test_instance_conforms_to_IAssetDescriptor(self):
- from pyramid.interfaces import IAssetDescriptor
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IAssetDescriptor
+
verifyObject(IAssetDescriptor, self._makeOne())
def test_absspec(self):
@@ -369,15 +372,17 @@ class TestFSAssetDescriptor(unittest.TestCase):
return self._getTargetClass()(path)
def test_class_conforms_to_IAssetDescriptor(self):
- from pyramid.interfaces import IAssetDescriptor
from zope.interface.verify import verifyClass
+ from pyramid.interfaces import IAssetDescriptor
+
verifyClass(IAssetDescriptor, self._getTargetClass())
def test_instance_conforms_to_IAssetDescriptor(self):
- from pyramid.interfaces import IAssetDescriptor
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IAssetDescriptor
+
verifyObject(IAssetDescriptor, self._makeOne())
def test_absspec(self):
@@ -611,6 +616,7 @@ class TestDottedNameResolver(unittest.TestCase):
def test_ctor_module(self):
import tests
+
from . import test_path
typ = self._makeOne(test_path)
@@ -649,8 +655,7 @@ class DummyPackageOrModule:
class DummyNamespacePackage:
- """Has no __file__ attribute.
- """
+ """Has no __file__ attribute."""
def __init__(self, real_package_or_module):
self.__name__ = real_package_or_module.__name__
diff --git a/tests/test_predicates.py b/tests/test_predicates.py
index 1cc3f4aa5..848afe387 100644
--- a/tests/test_predicates.py
+++ b/tests/test_predicates.py
@@ -453,8 +453,8 @@ class Test_EffectivePrincipalsPredicate(unittest.TestCase):
return EffectivePrincipalsPredicate(val, config)
def _testing_authn_policy(self, userid, groupids=tuple()):
+ from pyramid.authorization import Authenticated, Everyone
from pyramid.interfaces import IAuthenticationPolicy, ISecurityPolicy
- from pyramid.authorization import Everyone, Authenticated
from pyramid.security import LegacySecurityPolicy
class DummyPolicy:
diff --git a/tests/test_registry.py b/tests/test_registry.py
index 022cc5ba1..125b22a9f 100644
--- a/tests/test_registry.py
+++ b/tests/test_registry.py
@@ -100,8 +100,8 @@ class TestIntrospector(unittest.TestCase):
return self._getTargetClass()()
def test_conformance(self):
- from zope.interface.verify import verifyClass
- from zope.interface.verify import verifyObject
+ from zope.interface.verify import verifyClass, verifyObject
+
from pyramid.interfaces import IIntrospector
verifyClass(IIntrospector, self._getTargetClass())
@@ -346,8 +346,8 @@ class TestIntrospectable(unittest.TestCase):
return self._makeOne('category', 'discrim', 'title', 'type')
def test_conformance(self):
- from zope.interface.verify import verifyClass
- from zope.interface.verify import verifyObject
+ from zope.interface.verify import verifyClass, verifyObject
+
from pyramid.interfaces import IIntrospectable
verifyClass(IIntrospectable, self._getTargetClass())
diff --git a/tests/test_renderers.py b/tests/test_renderers.py
index 7bbf8565c..359a68d38 100644
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -157,6 +157,7 @@ class TestRendererHelper(unittest.TestCase):
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IRendererInfo
helper = self._makeOne()
@@ -419,9 +420,10 @@ class TestRendererHelper(unittest.TestCase):
registry = self.config.registry
settings = {}
registry.settings = settings
- from pyramid.interfaces import IRendererFactory
import os
+ from pyramid.interfaces import IRendererFactory
+
here = os.path.dirname(os.path.abspath(__file__))
fixture = os.path.join(here, 'fixtures/minimal.pt')
@@ -444,9 +446,10 @@ class TestRendererHelper(unittest.TestCase):
registry = self.config.registry
settings = {}
registry.settings = settings
- from pyramid.interfaces import IRendererFactory
import os
+ from pyramid.interfaces import IRendererFactory
+
here = os.path.dirname(os.path.abspath(__file__))
fixture = os.path.join(here, 'fixtures/minimal.pt')
@@ -482,6 +485,7 @@ class TestNullRendererHelper(unittest.TestCase):
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IRendererInfo
helper = self._makeOne()
diff --git a/tests/test_request.py b/tests/test_request.py
index 70ec32529..50531ab17 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -23,9 +23,10 @@ class TestRequest(unittest.TestCase):
return self._getTargetClass()(environ)
def _registerResourceURL(self):
- from pyramid.interfaces import IResourceURL
from zope.interface import Interface
+ from pyramid.interfaces import IResourceURL
+
class DummyResourceURL:
def __init__(self, context, request):
self.physical_path = '/context/'
@@ -37,12 +38,14 @@ class TestRequest(unittest.TestCase):
def test_class_conforms_to_IRequest(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import IRequest
verifyClass(IRequest, self._getTargetClass())
def test_instance_conforms_to_IRequest(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import IRequest
verifyObject(IRequest, self._makeOne())
@@ -555,10 +558,11 @@ class Test_subclassing_Request(unittest.TestCase):
self.assertTrue(hasattr(RequestSub, '__provides__'))
def test_subclass_with_implementer(self):
+ from zope.interface import implementer
+
from pyramid.interfaces import IRequest
from pyramid.request import Request
from pyramid.util import InstancePropertyHelper
- from zope.interface import implementer
@implementer(IRequest)
class RequestSub(Request):
diff --git a/tests/test_response.py b/tests/test_response.py
index 07456818f..abfbbc4f1 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -75,6 +75,7 @@ class TestFileResponse(unittest.TestCase):
# version of Python. See https://github.com/Pylons/pyramid/issues/1360
# for more information.
import mimetypes as old_mimetypes
+
from pyramid import response
from pyramid.util import text_
diff --git a/tests/test_router.py b/tests/test_router.py
index 63d9b4238..0f00ea531 100644
--- a/tests/test_router.py
+++ b/tests/test_router.py
@@ -161,11 +161,9 @@ class TestRouter(unittest.TestCase):
self.assertEqual(router.request_factory, DummyRequestFactory)
def test_tween_factories(self):
- from pyramid.interfaces import ITweens
from pyramid.config.tweens import Tweens
+ from pyramid.interfaces import IResponse, ITweens, IViewClassifier
from pyramid.response import Response
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IResponse
tweens = Tweens()
self.registry.registerUtility(tweens, ITweens)
@@ -346,9 +344,8 @@ class TestRouter(unittest.TestCase):
self.assertRaises(ValueError, router, environ, start_response)
def test_call_view_returns_adapted_response(self):
+ from pyramid.interfaces import IResponse, IViewClassifier
from pyramid.response import Response
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IResponse
context = DummyContext()
self._registerTraverserFactory(context)
@@ -369,9 +366,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(start_response.status, '200 OK')
def test_call_with_request_extensions(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequestExtensions
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IRequest,
+ IRequestExtensions,
+ IViewClassifier,
+ )
from pyramid.request import Request
from pyramid.util import InstancePropertyHelper
@@ -461,14 +460,12 @@ class TestRouter(unittest.TestCase):
self.assertEqual(request.root, context)
def test_call_view_registered_specific_success(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -492,8 +489,8 @@ class TestRouter(unittest.TestCase):
self.assertEqual(request.root, context)
def test_call_view_registered_specific_fail(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
+
from pyramid.httpexceptions import HTTPNotFound
from pyramid.interfaces import IViewClassifier
@@ -517,15 +514,14 @@ class TestRouter(unittest.TestCase):
self.assertRaises(HTTPNotFound, router, environ, start_response)
def test_call_view_raises_forbidden(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
+
from pyramid.httpexceptions import HTTPForbidden
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -542,15 +538,13 @@ class TestRouter(unittest.TestCase):
self.assertEqual(why.args[0], 'unauthorized')
def test_call_view_raises_notfound(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
from pyramid.httpexceptions import HTTPNotFound
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -565,15 +559,14 @@ class TestRouter(unittest.TestCase):
self.assertEqual(why.args[0], 'notfound')
def test_call_view_raises_response_cleared(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
+
from pyramid.interfaces import IExceptionViewClassifier
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -599,14 +592,12 @@ class TestRouter(unittest.TestCase):
self.assertEqual(itera, [b'OK'])
def test_call_request_has_response_callbacks(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -628,14 +619,12 @@ class TestRouter(unittest.TestCase):
self.assertEqual(response.called_back, True)
def test_call_request_has_finished_callbacks_when_view_succeeds(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -657,14 +646,12 @@ class TestRouter(unittest.TestCase):
self.assertEqual(environ['called_back'], True)
def test_call_request_has_finished_callbacks_when_view_raises(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import IRequest, IViewClassifier
context = DummyContext()
directlyProvides(context, IContext)
@@ -697,11 +684,13 @@ class TestRouter(unittest.TestCase):
exc_raised(NotImplementedError, router, environ, start_response)
def test_call_eventsends(self):
- from pyramid.interfaces import INewRequest
- from pyramid.interfaces import INewResponse
- from pyramid.interfaces import IBeforeTraversal
- from pyramid.interfaces import IContextFound
- from pyramid.interfaces import IViewClassifier
+ from pyramid.interfaces import (
+ IBeforeTraversal,
+ IContextFound,
+ INewRequest,
+ INewResponse,
+ IViewClassifier,
+ )
context = DummyContext()
self._registerTraverserFactory(context)
@@ -730,9 +719,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, response.app_iter)
def test_call_newrequest_evllist_exc_can_be_caught_by_exceptionview(self):
- from pyramid.interfaces import INewRequest
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ INewRequest,
+ IRequest,
+ )
context = DummyContext()
self._registerTraverserFactory(context)
@@ -822,10 +813,9 @@ class TestRouter(unittest.TestCase):
)
def test_call_route_matches_doesnt_overwrite_subscriber_iface(self):
- from pyramid.interfaces import INewRequest
- from pyramid.interfaces import IViewClassifier
- from zope.interface import alsoProvides
- from zope.interface import Interface
+ from zope.interface import Interface, alsoProvides
+
+ from pyramid.interfaces import INewRequest, IViewClassifier
self._registerRouteRequest('foo')
@@ -867,10 +857,10 @@ class TestRouter(unittest.TestCase):
self.assertTrue(IFoo.providedBy(request))
def test_root_factory_raises_notfound(self):
- from pyramid.interfaces import IRootFactory
+ from zope.interface import Interface, directlyProvides
+
from pyramid.httpexceptions import HTTPNotFound
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from pyramid.interfaces import IRootFactory
def rootfactory(request):
raise HTTPNotFound('from root factory')
@@ -889,10 +879,10 @@ class TestRouter(unittest.TestCase):
self.assertTrue('from root factory' in why.args[0])
def test_root_factory_raises_forbidden(self):
- from pyramid.interfaces import IRootFactory
+ from zope.interface import Interface, directlyProvides
+
from pyramid.httpexceptions import HTTPForbidden
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from pyramid.interfaces import IRootFactory
def rootfactory(request):
raise HTTPForbidden('from root factory')
@@ -911,9 +901,9 @@ class TestRouter(unittest.TestCase):
self.assertTrue('from root factory' in why.args[0])
def test_root_factory_exception_propagating(self):
+ from zope.interface import Interface, directlyProvides
+
from pyramid.interfaces import IRootFactory
- from zope.interface import Interface
- from zope.interface import directlyProvides
def rootfactory(request):
raise RuntimeError()
@@ -939,16 +929,17 @@ class TestRouter(unittest.TestCase):
self.assertRaises(RuntimeError, router, environ, start_response)
def test_call_view_exception_propagating(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
class IContext(Interface):
pass
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequestFactory
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IRequestFactory,
+ IViewClassifier,
+ )
def rfactory(environ):
return request
@@ -989,9 +980,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(request.exc_info[:2], (RuntimeError, error))
def test_call_view_raises_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
response = DummyResponse()
exception_response = DummyResponse()
@@ -1017,9 +1010,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_call_view_raises_super_exception_sub_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class SuperException(Exception):
pass
@@ -1046,9 +1041,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(SuperException, router, environ, start_response)
def test_call_view_raises_sub_exception_super_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class SuperException(Exception):
pass
@@ -1076,9 +1073,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_call_view_raises_exception_another_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class MyException(Exception):
pass
@@ -1105,9 +1104,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(MyException, router, environ, start_response)
def test_root_factory_raises_exception_view(self):
- from pyramid.interfaces import IRootFactory
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IRootFactory,
+ )
def rootfactory(request):
raise RuntimeError()
@@ -1130,8 +1131,7 @@ class TestRouter(unittest.TestCase):
self.assertEqual(app_iter, ["Hello, world"])
def test_traverser_raises_exception_view(self):
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import IExceptionViewClassifier, IRequest
environ = self._makeEnviron()
context = DummyContext()
@@ -1152,9 +1152,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_exception_view_returns_non_iresponse(self):
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
environ = self._makeEnviron()
response = DummyResponse()
@@ -1176,8 +1178,10 @@ class TestRouter(unittest.TestCase):
self.assertRaises(ValueError, router, environ, start_response)
def test_call_route_raises_route_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
self._connectRoute('foo', 'archives/:action/:article', None)
@@ -1200,9 +1204,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_call_view_raises_exception_route_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
self._connectRoute('foo', 'archives/:action/:article', None)
@@ -1224,9 +1230,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(RuntimeError, router, environ, start_response)
def test_call_route_raises_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
self._connectRoute('foo', 'archives/:action/:article', None)
@@ -1249,9 +1257,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_call_route_raises_super_exception_sub_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class SuperException(Exception):
pass
@@ -1279,9 +1289,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(SuperException, router, environ, start_response)
def test_call_route_raises_sub_exception_super_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class SuperException(Exception):
pass
@@ -1310,9 +1322,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, world"])
def test_call_route_raises_exception_another_exception_view(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class MyException(Exception):
pass
@@ -1340,9 +1354,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(MyException, router, environ, start_response)
def test_call_route_raises_exception_view_specializing(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
self._connectRoute('foo', 'archives/:action/:article', None)
@@ -1375,8 +1391,10 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result, ["Hello, special world"])
def test_call_route_raises_exception_view_another_route(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
another_req_iface = self._registerRouteRequest('bar')
@@ -1399,9 +1417,11 @@ class TestRouter(unittest.TestCase):
self.assertRaises(RuntimeError, router, environ, start_response)
def test_call_view_raises_exception_view_route(self):
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
req_iface = self._registerRouteRequest('foo')
response = DummyResponse()
@@ -1424,8 +1444,7 @@ class TestRouter(unittest.TestCase):
def test_call_view_raises_predicate_mismatch(self):
from pyramid.exceptions import PredicateMismatch
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import IRequest, IViewClassifier
view = DummyView(DummyResponse(), raise_exception=PredicateMismatch)
self._registerView(view, '', IViewClassifier, IRequest, None)
@@ -1436,8 +1455,7 @@ class TestRouter(unittest.TestCase):
def test_call_view_predicate_mismatch_doesnt_hide_views(self):
from pyramid.exceptions import PredicateMismatch
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequest, IResponse
+ from pyramid.interfaces import IRequest, IResponse, IViewClassifier
from pyramid.response import Response
class BaseContext:
@@ -1470,11 +1488,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(app_iter, [b'abc'])
def test_call_view_multiple_predicate_mismatches_dont_hide_views(self):
+ from zope.interface import Interface, implementer
+
from pyramid.exceptions import PredicateMismatch
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequest, IResponse
+ from pyramid.interfaces import IRequest, IResponse, IViewClassifier
from pyramid.response import Response
- from zope.interface import Interface, implementer
class IBaseContext(Interface):
pass
@@ -1512,11 +1530,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(app_iter, [b'abc'])
def test_call_view_predicate_mismatch_doesnt_find_unrelated_views(self):
- from pyramid.exceptions import PredicateMismatch
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IRequest
from zope.interface import Interface, implementer
+ from pyramid.exceptions import PredicateMismatch
+ from pyramid.interfaces import IRequest, IViewClassifier
+
class IContext(Interface):
pass
@@ -1562,9 +1580,11 @@ class TestRouter(unittest.TestCase):
self.assertEqual(resp.body, b'foo')
def test_execution_policy_bubbles_exception(self):
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IExceptionViewClassifier
- from pyramid.interfaces import IRequest
+ from pyramid.interfaces import (
+ IExceptionViewClassifier,
+ IRequest,
+ IViewClassifier,
+ )
class Exception1(Exception):
pass
@@ -1594,10 +1614,10 @@ class TestRouter(unittest.TestCase):
self.assertRaises(Exception2, lambda: router(environ, start_response))
def test_request_context_with_statement(self):
- from pyramid.threadlocal import get_current_request
from pyramid.interfaces import IExecutionPolicy
from pyramid.request import Request
from pyramid.response import Response
+ from pyramid.threadlocal import get_current_request
registry = self.config.registry
result = []
@@ -1617,10 +1637,10 @@ class TestRouter(unittest.TestCase):
self.assertEqual(result[1], None)
def test_request_context_manually(self):
- from pyramid.threadlocal import get_current_request
from pyramid.interfaces import IExecutionPolicy
from pyramid.request import Request
from pyramid.response import Response
+ from pyramid.threadlocal import get_current_request
registry = self.config.registry
result = []
diff --git a/tests/test_scripts/test_proutes.py b/tests/test_scripts/test_proutes.py
index a585a02aa..8ac5d0fd1 100644
--- a/tests/test_scripts/test_proutes.py
+++ b/tests/test_scripts/test_proutes.py
@@ -118,6 +118,7 @@ class TestPRoutesCommand(unittest.TestCase):
def test_single_route_no_views_registered(self):
from zope.interface import Interface
+
from pyramid.interfaces import IRouteRequest
registry = self._makeRegistry()
@@ -143,9 +144,8 @@ class TestPRoutesCommand(unittest.TestCase):
def test_single_route_one_view_registered(self):
from zope.interface import Interface
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
+
+ from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
@@ -176,9 +176,8 @@ class TestPRoutesCommand(unittest.TestCase):
def test_one_route_with_long_name_one_view_registered(self):
from zope.interface import Interface
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
+
+ from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
@@ -249,9 +248,8 @@ class TestPRoutesCommand(unittest.TestCase):
def test_single_route_one_view_registered_with_factory(self):
from zope.interface import Interface
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
+
+ from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
registry = self._makeRegistry()
@@ -286,9 +284,12 @@ class TestPRoutesCommand(unittest.TestCase):
def test_single_route_multiview_registered(self):
from zope.interface import Interface
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRouteRequest,
+ IViewClassifier,
+ )
registry = self._makeRegistry()
@@ -526,8 +527,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(compare_to, expected)
def test_route_is_get_view_request_method_not_post(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -558,8 +559,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(compare_to, expected)
def test_view_request_method_not_post(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -590,8 +591,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(compare_to, expected)
def test_view_glob(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -635,8 +636,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(compare_to, expected)
def test_good_format(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -666,8 +667,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_bad_format(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -696,8 +697,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(L[0], expected)
def test_config_format_ini_newlines(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -730,8 +731,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_config_format_ini_spaces(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
@@ -764,8 +765,8 @@ class TestPRoutesCommand(unittest.TestCase):
self.assertEqual(L[0].split(), ['Method', 'Name'])
def test_config_format_ini_commas(self):
- from pyramid.renderers import null_renderer as nr
from pyramid.config import not_
+ from pyramid.renderers import null_renderer as nr
def view1(context, request): # pragma: no cover
return 'view1'
diff --git a/tests/test_scripts/test_pviews.py b/tests/test_scripts/test_pviews.py
index fb809fdcd..36b63ef99 100644
--- a/tests/test_scripts/test_pviews.py
+++ b/tests/test_scripts/test_pviews.py
@@ -40,13 +40,11 @@ class TestPViewsCommand(unittest.TestCase):
self.assertEqual(result, None)
def test__find_view_no_match_multiview_registered(self):
- from zope.interface import implementer
- from zope.interface import providedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
- from pyramid.traversal import DefaultRootFactory
+ from zope.interface import implementer, providedBy
+
+ from pyramid.interfaces import IMultiView, IRequest, IViewClassifier
from pyramid.registry import Registry
+ from pyramid.traversal import DefaultRootFactory
registry = Registry()
@@ -69,11 +67,10 @@ class TestPViewsCommand(unittest.TestCase):
def test__find_view_traversal(self):
from zope.interface import providedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
- from pyramid.traversal import DefaultRootFactory
+
+ from pyramid.interfaces import IRequest, IView, IViewClassifier
from pyramid.registry import Registry
+ from pyramid.traversal import DefaultRootFactory
registry = Registry()
@@ -94,13 +91,11 @@ class TestPViewsCommand(unittest.TestCase):
self.assertEqual(result, view1)
def test__find_view_traversal_multiview(self):
- from zope.interface import implementer
- from zope.interface import providedBy
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IMultiView
- from pyramid.traversal import DefaultRootFactory
+ from zope.interface import implementer, providedBy
+
+ from pyramid.interfaces import IMultiView, IRequest, IViewClassifier
from pyramid.registry import Registry
+ from pyramid.traversal import DefaultRootFactory
registry = Registry()
@@ -123,11 +118,9 @@ class TestPViewsCommand(unittest.TestCase):
self.assertEqual(result, view)
def test__find_view_route_no_multiview(self):
- from zope.interface import Interface
- from zope.interface import implementer
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
+ from zope.interface import Interface, implementer
+
+ from pyramid.interfaces import IRouteRequest, IView, IViewClassifier
from pyramid.registry import Registry
registry = Registry()
@@ -162,11 +155,9 @@ class TestPViewsCommand(unittest.TestCase):
self.assertEqual(result, view)
def test__find_view_route_multiview_no_view_registered(self):
- from zope.interface import Interface
- from zope.interface import implementer
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IRootFactory
+ from zope.interface import Interface, implementer
+
+ from pyramid.interfaces import IMultiView, IRootFactory, IRouteRequest
from pyramid.registry import Registry
registry = Registry()
@@ -206,13 +197,15 @@ class TestPViewsCommand(unittest.TestCase):
self.assertTrue(IMultiView.providedBy(result))
def test__find_view_route_multiview(self):
- from zope.interface import Interface
- from zope.interface import implementer
- from pyramid.interfaces import IRouteRequest
- from pyramid.interfaces import IViewClassifier
- from pyramid.interfaces import IView
- from pyramid.interfaces import IMultiView
- from pyramid.interfaces import IRootFactory
+ from zope.interface import Interface, implementer
+
+ from pyramid.interfaces import (
+ IMultiView,
+ IRootFactory,
+ IRouteRequest,
+ IView,
+ IViewClassifier,
+ )
from pyramid.registry import Registry
registry = Registry()
diff --git a/tests/test_security.py b/tests/test_security.py
index bf2908100..efaf9b4bf 100644
--- a/tests/test_security.py
+++ b/tests/test_security.py
@@ -243,10 +243,10 @@ class TestViewExecutionPermitted(unittest.TestCase):
return view_execution_permitted(*arg, **kw)
def _registerSecuredView(self, view_name, allow=True):
- from pyramid.threadlocal import get_current_registry
from zope.interface import Interface
- from pyramid.interfaces import ISecuredView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import ISecuredView, IViewClassifier
+ from pyramid.threadlocal import get_current_registry
class Checker:
def __permitted__(self, context, request):
@@ -266,10 +266,9 @@ class TestViewExecutionPermitted(unittest.TestCase):
def test_no_permission(self):
from zope.interface import Interface
+
+ from pyramid.interfaces import ISettings, IView, IViewClassifier
from pyramid.threadlocal import get_current_registry
- from pyramid.interfaces import ISettings
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
settings = dict(debug_authorization=True)
reg = get_current_registry()
@@ -291,8 +290,8 @@ class TestViewExecutionPermitted(unittest.TestCase):
self.assertEqual(result, True)
def test_no_view_registered(self):
- from pyramid.threadlocal import get_current_registry
from pyramid.interfaces import ISettings
+ from pyramid.threadlocal import get_current_registry
settings = dict(debug_authorization=True)
reg = get_current_registry()
@@ -302,8 +301,8 @@ class TestViewExecutionPermitted(unittest.TestCase):
self.assertRaises(TypeError, self._callFUT, context, request, '')
def test_with_permission(self):
- from zope.interface import Interface
- from zope.interface import directlyProvides
+ from zope.interface import Interface, directlyProvides
+
from pyramid.interfaces import IRequest
class IContext(Interface):
@@ -393,6 +392,29 @@ class TestUnAuthenticatedUserId(unittest.TestCase):
self.assertEqual(request.unauthenticated_userid, 'wat')
+class TestIsAuthenticated(unittest.TestCase):
+ def setUp(self):
+ testing.setUp()
+
+ def tearDown(self):
+ testing.tearDown()
+
+ def test_no_security_policy(self):
+ request = _makeRequest()
+ self.assertIs(request.is_authenticated, False)
+
+ def test_with_security_policy(self):
+ request = _makeRequest()
+ _registerSecurityPolicy(request.registry, '123')
+ self.assertIs(request.is_authenticated, True)
+
+ def test_with_legacy_security_policy(self):
+ request = _makeRequest()
+ _registerAuthenticationPolicy(request.registry, 'yo')
+ _registerLegacySecurityPolicy(request.registry)
+ self.assertEqual(request.authenticated_userid, 'yo')
+
+
class TestEffectivePrincipals(unittest.TestCase):
def setUp(self):
testing.setUp()
@@ -436,8 +458,8 @@ class TestHasPermission(unittest.TestCase):
testing.tearDown()
def _makeOne(self):
- from pyramid.security import SecurityAPIMixin
from pyramid.registry import Registry
+ from pyramid.security import SecurityAPIMixin
mixin = SecurityAPIMixin()
mixin.registry = Registry()
diff --git a/tests/test_session.py b/tests/test_session.py
index 94626a733..b86abe191 100644
--- a/tests/test_session.py
+++ b/tests/test_session.py
@@ -14,6 +14,7 @@ class SharedCookieSessionTests:
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import ISession
request = testing.DummyRequest()
@@ -477,8 +478,8 @@ class TestSignedCookieSession(SharedCookieSessionTests, unittest.TestCase):
self.assertEqual(session['state'], 1)
def test_invalid_data_size(self):
- from hashlib import sha512
import base64
+ from hashlib import sha512
request = testing.DummyRequest()
num_bytes = sha512().digest_size - 1
diff --git a/tests/test_settings.py b/tests/test_settings.py
index e8be490ee..457835663 100644
--- a/tests/test_settings.py
+++ b/tests/test_settings.py
@@ -69,6 +69,14 @@ class Test_aslist(unittest.TestCase):
result = self._callFUT(['abc', 'def'])
self.assertEqual(list(result), ['abc', 'def'])
+ def test_with_integer(self):
+ result = self._callFUT([1])
+ self.assertEqual(result, [1])
+
+ def test_with_integer_no_flatten(self):
+ result = self._callFUT([1], flatten=False)
+ self.assertEqual(result, [1])
+
def test_with_string(self):
result = self._callFUT('abc def')
self.assertEqual(result, ['abc', 'def'])
@@ -84,3 +92,7 @@ class Test_aslist(unittest.TestCase):
def test_with_string_crsep_spacesep_no_flatten(self):
result = self._callFUT(' abc\n def ghi ', flatten=False)
self.assertEqual(result, ['abc', 'def ghi'])
+
+ def test_with_string_crsep_spacesep_and_integer(self):
+ result = self._callFUT([' abc def ghi ', 1])
+ self.assertEqual(result, ['abc', 'def', 'ghi', 1])
diff --git a/tests/test_testing.py b/tests/test_testing.py
index e630eb00b..8f912dbd7 100644
--- a/tests/test_testing.py
+++ b/tests/test_testing.py
@@ -134,8 +134,8 @@ class TestDummyRequest(unittest.TestCase):
self.assertEqual(request.environ['PATH_INFO'], '/foo')
def test_defaults(self):
- from pyramid.threadlocal import get_current_registry
from pyramid.testing import DummySession
+ from pyramid.threadlocal import get_current_registry
request = self._makeOne()
self.assertEqual(request.method, 'GET')
@@ -214,8 +214,8 @@ class TestDummyRequest(unittest.TestCase):
def test_registry_is_config_registry_when_setup_is_called_after_ctor(self):
# see https://github.com/Pylons/pyramid/issues/165
- from pyramid.registry import Registry
from pyramid.config import Configurator
+ from pyramid.registry import Registry
request = self._makeOne()
try:
@@ -233,8 +233,8 @@ class TestDummyRequest(unittest.TestCase):
def test_del_registry(self):
# see https://github.com/Pylons/pyramid/issues/165
- from pyramid.registry import Registry
from pyramid.config import Configurator
+ from pyramid.registry import Registry
request = self._makeOne()
request.registry = 'abc'
@@ -249,8 +249,8 @@ class TestDummyRequest(unittest.TestCase):
config.end()
def test_response_with_responsefactory(self):
- from pyramid.registry import Registry
from pyramid.interfaces import IResponseFactory
+ from pyramid.registry import Registry
registry = Registry('this_test')
@@ -300,7 +300,9 @@ class TestDummyRequest(unittest.TestCase):
class TestDummyTemplateRenderer(unittest.TestCase):
- def _getTargetClass(self,):
+ def _getTargetClass(
+ self,
+ ):
from pyramid.testing import DummyTemplateRenderer
return DummyTemplateRenderer
@@ -351,9 +353,8 @@ class Test_setUp(unittest.TestCase):
self.assertEqual(result, hook)
def test_it_defaults(self):
- from pyramid.threadlocal import manager
- from pyramid.threadlocal import get_current_registry
from pyramid.registry import Registry
+ from pyramid.threadlocal import get_current_registry, manager
old = True
manager.push(old)
@@ -597,6 +598,7 @@ class TestDummySession(unittest.TestCase):
) # see https://github.com/Pylons/pyramid/issues/3237
def test_instance_conforms(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import ISession
session = self._makeOne()
diff --git a/tests/test_traversal.py b/tests/test_traversal.py
index b99862ba0..a8b81c48b 100644
--- a/tests/test_traversal.py
+++ b/tests/test_traversal.py
@@ -119,12 +119,14 @@ class ResourceTreeTraverserTests(unittest.TestCase):
def test_class_conforms_to_ITraverser(self):
from zope.interface.verify import verifyClass
+
from pyramid.interfaces import ITraverser
verifyClass(ITraverser, self._getTargetClass())
def test_instance_conforms_to_ITraverser(self):
from zope.interface.verify import verifyObject
+
from pyramid.interfaces import ITraverser
context = DummyContext()
@@ -494,8 +496,7 @@ class FindInterfaceTests(unittest.TestCase):
bar.__name__ = 'bar'
baz.__parent__ = bar
baz.__name__ = 'baz'
- from zope.interface import directlyProvides
- from zope.interface import Interface
+ from zope.interface import Interface, directlyProvides
class IFoo(Interface):
pass
@@ -552,9 +553,10 @@ class FindResourceTests(unittest.TestCase):
from pyramid.threadlocal import get_current_registry
reg = get_current_registry()
- from pyramid.interfaces import ITraverser
from zope.interface import Interface
+ from pyramid.interfaces import ITraverser
+
reg.registerAdapter(traverser, (Interface,), ITraverser)
def test_list(self):
@@ -888,9 +890,10 @@ class ResourceURLTests(unittest.TestCase):
return ResourceURL
def test_instance_conforms_to_IResourceURL(self):
- from pyramid.interfaces import IResourceURL
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IResourceURL
+
context = DummyContext()
request = DummyRequest()
verifyObject(IResourceURL, self._makeOne(context, request))
@@ -978,9 +981,10 @@ class TestVirtualRoot(unittest.TestCase):
from pyramid.threadlocal import get_current_registry
reg = get_current_registry()
- from pyramid.interfaces import ITraverser
from zope.interface import Interface
+ from pyramid.interfaces import ITraverser
+
reg.registerAdapter(traverser, (Interface,), ITraverser)
def test_virtual_root_no_virtual_root_path(self):
@@ -1051,9 +1055,10 @@ class TraverseTests(unittest.TestCase):
from pyramid.threadlocal import get_current_registry
reg = get_current_registry()
- from pyramid.interfaces import ITraverser
from zope.interface import Interface
+ from pyramid.interfaces import ITraverser
+
reg.registerAdapter(traverser, (Interface,), ITraverser)
def test_request_has_registry(self):
diff --git a/tests/test_tweens.py b/tests/test_tweens.py
index aee1ae7cc..eb6e45118 100644
--- a/tests/test_tweens.py
+++ b/tests/test_tweens.py
@@ -31,8 +31,8 @@ class Test_excview_tween_factory(unittest.TestCase):
self.assertIsNone(request.exc_info)
def test_it_catches_notfound(self):
- from pyramid.request import Request
from pyramid.httpexceptions import HTTPNotFound
+ from pyramid.request import Request
self.config.add_notfound_view(lambda exc, request: exc)
diff --git a/tests/test_url.py b/tests/test_url.py
index 0eacd9c20..0b67f1acf 100644
--- a/tests/test_url.py
+++ b/tests/test_url.py
@@ -31,9 +31,10 @@ class TestURLMethodsMixin(unittest.TestCase):
return request
def _registerResourceURL(self, reg):
- from pyramid.interfaces import IResourceURL
from zope.interface import Interface
+ from pyramid.interfaces import IResourceURL
+
class DummyResourceURL:
physical_path = '/context/'
virtual_path = '/context/'
@@ -684,9 +685,10 @@ class TestURLMethodsMixin(unittest.TestCase):
)
def test_current_route_url_with_request_query(self):
- from pyramid.interfaces import IRoutesMapper
from webob.multidict import GetDict
+ from pyramid.interfaces import IRoutesMapper
+
request = self._makeOne()
request.GET = GetDict([('q', '123')], {})
route = DummyRoute('/1/2/3')
@@ -698,9 +700,10 @@ class TestURLMethodsMixin(unittest.TestCase):
self.assertEqual(result, 'http://example.com:5432/1/2/3?q=123')
def test_current_route_url_with_request_query_duplicate_entries(self):
- from pyramid.interfaces import IRoutesMapper
from webob.multidict import GetDict
+ from pyramid.interfaces import IRoutesMapper
+
request = self._makeOne()
request.GET = GetDict(
[('q', '123'), ('b', '2'), ('b', '2'), ('q', '456')], {}
@@ -716,9 +719,10 @@ class TestURLMethodsMixin(unittest.TestCase):
)
def test_current_route_url_with_query_override(self):
- from pyramid.interfaces import IRoutesMapper
from webob.multidict import GetDict
+ from pyramid.interfaces import IRoutesMapper
+
request = self._makeOne()
request.GET = GetDict([('q', '123')], {})
route = DummyRoute('/1/2/3')
@@ -834,8 +838,8 @@ class TestURLMethodsMixin(unittest.TestCase):
self.assertEqual(info.args, ('tests:static/foo.css', request, {}))
def test_static_url_abspath_integration_with_staticurlinfo(self):
- from pyramid.interfaces import IStaticURLInfo
from pyramid.config.views import StaticURLInfo
+ from pyramid.interfaces import IStaticURLInfo
info = StaticURLInfo()
here = os.path.abspath(os.path.dirname(__file__))
@@ -850,8 +854,8 @@ class TestURLMethodsMixin(unittest.TestCase):
)
def test_static_url_noscheme_uses_scheme_from_request(self):
- from pyramid.interfaces import IStaticURLInfo
from pyramid.config.views import StaticURLInfo
+ from pyramid.interfaces import IStaticURLInfo
info = StaticURLInfo()
here = os.path.abspath(os.path.dirname(__file__))
diff --git a/tests/test_urldispatch.py b/tests/test_urldispatch.py
index 13cf31b32..4d58ce66c 100644
--- a/tests/test_urldispatch.py
+++ b/tests/test_urldispatch.py
@@ -14,9 +14,10 @@ class TestRoute(unittest.TestCase):
return self._getTargetClass()(*arg)
def test_provides_IRoute(self):
- from pyramid.interfaces import IRoute
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IRoute
+
verifyObject(IRoute, self._makeOne('name', 'pattern'))
def test_ctor(self):
@@ -75,9 +76,10 @@ class RoutesMapperTests(unittest.TestCase):
return klass()
def test_provides_IRoutesMapper(self):
- from pyramid.interfaces import IRoutesMapper
from zope.interface.verify import verifyObject
+ from pyramid.interfaces import IRoutesMapper
+
verifyObject(IRoutesMapper, self._makeOne())
def test_no_route_matches(self):
diff --git a/tests/test_util.py b/tests/test_util.py
index 0fb975f66..bf4c08988 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -137,7 +137,7 @@ class Test_InstancePropertyHelper(unittest.TestCase):
self.assertEqual(2, foo.x)
def test_reset_reify(self):
- """ This is questionable behavior, but may as well get notified
+ """This is questionable behavior, but may as well get notified
if it changes."""
foo = Dummy()
helper = self._getTargetClass()
@@ -333,7 +333,7 @@ class Test_InstancePropertyMixin(unittest.TestCase):
self.assertEqual(2, foo.x)
def test_reset_reify(self):
- """ This is questionable behavior, but may as well get notified
+ """This is questionable behavior, but may as well get notified
if it changes."""
foo = self._makeOne()
foo.set_property(lambda _: 1, name='x', reify=True)
@@ -630,7 +630,7 @@ class TestTopologicalSorter(unittest.TestCase):
)
def test_sorted_ordering_5(self):
- from pyramid.util import LAST, FIRST
+ from pyramid.util import FIRST, LAST
sorter = self._makeOne()
add = sorter.add
diff --git a/tests/test_view.py b/tests/test_view.py
index 3bfad0732..0b192ed25 100644
--- a/tests/test_view.py
+++ b/tests/test_view.py
@@ -34,8 +34,8 @@ class BaseTest:
return environ
def _makeRequest(self, **environ):
- from pyramid.request import Request
from pyramid.registry import Registry
+ from pyramid.request import Request
environ = self._makeEnviron(**environ)
request = Request(environ)
@@ -412,8 +412,8 @@ class RenderViewToIterableTests(BaseTest, unittest.TestCase):
self.assertEqual(iterable, [b'anotherview'])
def test_verify_output_bytestring(self):
- from pyramid.request import Request
from pyramid.config import Configurator
+ from pyramid.request import Request
from pyramid.view import render_view
config = Configurator(settings={})
@@ -711,8 +711,8 @@ class TestViewConfigDecorator(unittest.TestCase):
self.assertEqual(config.pkg, tests)
def test_call_with_renderer_IRendererInfo(self):
- import tests
from pyramid.interfaces import IRendererInfo
+ import tests
@implementer(IRendererInfo)
class DummyRendererHelper:
diff --git a/tests/test_viewderivers.py b/tests/test_viewderivers.py
index 4e871ad4a..bec016461 100644
--- a/tests/test_viewderivers.py
+++ b/tests/test_viewderivers.py
@@ -877,9 +877,8 @@ class TestDeriveView(unittest.TestCase):
self.assertEqual(predicates, [True, True])
def test_with_wrapper_viewname(self):
+ from pyramid.interfaces import IView, IViewClassifier
from pyramid.response import Response
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
inner_response = Response('OK')
@@ -1192,6 +1191,7 @@ class TestDeriveView(unittest.TestCase):
def test_http_cached_view_integer(self):
import datetime
+
from pyramid.response import Response
response = Response('OK')
@@ -1214,6 +1214,7 @@ class TestDeriveView(unittest.TestCase):
def test_http_cached_view_timedelta(self):
import datetime
+
from pyramid.response import Response
response = Response('OK')
@@ -1238,6 +1239,7 @@ class TestDeriveView(unittest.TestCase):
def test_http_cached_view_tuple(self):
import datetime
+
from pyramid.response import Response
response = Response('OK')
@@ -1984,9 +1986,8 @@ class TestDeriverIntegration(unittest.TestCase):
self, config, ctx_iface=None, request_iface=None, name=''
):
from zope.interface import Interface
- from pyramid.interfaces import IRequest
- from pyramid.interfaces import IView
- from pyramid.interfaces import IViewClassifier
+
+ from pyramid.interfaces import IRequest, IView, IViewClassifier
classifier = IViewClassifier
if ctx_iface is None:
diff --git a/tox.ini b/tox.ini
index 91baa42db..99aeb67d2 100644
--- a/tox.ini
+++ b/tox.ini
@@ -23,7 +23,7 @@ commands =
skip_install = true
commands =
flake8 src/pyramid tests setup.py
- isort --check -rc src/pyramid tests setup.py
+ isort --check-only --df src/pyramid tests setup.py
black --check --diff src/pyramid tests setup.py
python setup.py check -r -s -m
check-manifest
@@ -63,7 +63,7 @@ depends = py38-cover
[testenv:format]
skip_install = true
commands =
- isort -rc src/pyramid tests setup.py
+ isort src/pyramid tests setup.py
black src/pyramid tests setup.py
deps =
black