Chris McDonough
2012-09-10 dcbe7d5e36a15010915366cd74680574ca1f518f
Merge branch 'feature.14removedeprecations'
4 files deleted
21 files modified
1546 ■■■■ changed files
CHANGES.txt 85 ●●●●● patch | view | raw | blame | history
TODO.txt 13 ●●●●● patch | view | raw | blame | history
docs/api.rst 2 ●●●●● patch | view | raw | blame | history
docs/api/chameleon_text.rst 31 ●●●●● patch | view | raw | blame | history
docs/api/chameleon_zpt.rst 28 ●●●●● patch | view | raw | blame | history
docs/api/settings.rst 2 ●●●●● patch | view | raw | blame | history
pyramid/chameleon_text.py 92 ●●●●● patch | view | raw | blame | history
pyramid/chameleon_zpt.py 91 ●●●●● patch | view | raw | blame | history
pyramid/configuration.py 60 ●●●●● patch | view | raw | blame | history
pyramid/paster.py 10 ●●●●● patch | view | raw | blame | history
pyramid/request.py 9 ●●●●● patch | view | raw | blame | history
pyramid/router.py 10 ●●●● patch | view | raw | blame | history
pyramid/settings.py 26 ●●●●● patch | view | raw | blame | history
pyramid/testing.py 373 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_chameleon_text.py 83 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_chameleon_zpt.py 86 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_configuration.py 31 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_path.py 6 ●●●● patch | view | raw | blame | history
pyramid/tests/test_request.py 12 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_router.py 4 ●●●● patch | view | raw | blame | history
pyramid/tests/test_settings.py 26 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_testing.py 281 ●●●●● patch | view | raw | blame | history
pyramid/tests/test_traversal.py 155 ●●●● patch | view | raw | blame | history
pyramid/traversal.py 28 ●●●●● patch | view | raw | blame | history
setup.py 2 ●●● patch | view | raw | blame | history
CHANGES.txt
@@ -152,3 +152,88 @@
  featureful ``pyramid.config.Configurator.set_request_method`` should be
  used in its place (it has all of the same capabilities but can also extend
  the request object with methods).
Backwards Incompatibilities
---------------------------
- The Pyramid router no longer adds the values ``bfg.routes.route`` or
  ``bfg.routes.matchdict`` to the request's WSGI environment dictionary.
  These values were docs-deprecated in ``repoze.bfg`` 1.0 (effectively seven
  minor releases ago).  If your code depended on these values, use
  request.matched_route and request.matchdict instead.
- It is no longer possible to pass an environ dictionary directly to
  ``pyramid.traversal.ResourceTreeTraverser.__call__`` (aka
  ``ModelGraphTraverser.__call__``).  Instead, you must pass a request
  object.  Passing an environment instead of a request has generated a
  deprecation warning since Pyramid 1.1.
- Pyramid will no longer work properly if you use the
  ``webob.request.LegacyRequest`` as a request factory.  Instances of the
  LegacyRequest class have a ``request.path_info`` which return a string.
  This Pyramid release assumes that ``request.path_info`` will
  unconditionally be Unicode.
- The functions from ``pyramid.chameleon_zpt`` and ``pyramid.chameleon_text``
  named ``get_renderer``, ``get_template``, ``render_template``, and
  ``render_template_to_response`` have been removed.  These have issued a
  deprecation warning upon import since Pyramid 1.0.  Use
  ``pyramid.renderers.get_renderer()``,
  ``pyramid.renderers.get_renderer().implementation()``,
  ``pyramid.renderers.render()`` or ``pyramid.renderers.render_to_response``
  respectively instead of these functions.
- The ``pyramid.configuration`` module was removed.  It had been deprecated
  since Pyramid 1.0 and printed a deprecation warning upon its use.  Use
  ``pyramid.config`` instead.
- The ``pyramid.paster.PyramidTemplate`` API was removed.  It had been
  deprecated since Pyramid 1.1 and issued a warning on import.  If your code
  depended on this, adjust your code to import
  ``pyramid.scaffolds.PyramidTemplate`` instead.
- The ``pyramid.settings.get_settings()`` API was removed.  It had been
  printing a deprecation warning since Pyramid 1.0.  If your code depended on
  this API, use ``pyramid.threadlocal.get_current_registry().settings``
  instead or use the ``settings`` attribute of the registry available from
  the request (``request.registry.settings``).
- These APIs from the ``pyramid.testing`` module were removed.  They have
  been printing deprecation warnings since Pyramid 1.0:
  * ``registerDummySecurityPolicy``, use
    ``pyramid.config.Configurator.testing_securitypolicy`` instead.
  * ``registerResources`` (aka ``registerModels``, use
    ``pyramid.config.Configurator.testing_resources`` instead.
  * ``registerEventListener``, use
    ``pyramid.config.Configurator.testing_add_subscriber`` instead.
  * ``registerTemplateRenderer`` (aka `registerDummyRenderer``), use
    ``pyramid.config.Configurator.testing_add_template`` instead.
  * ``registerView``, use ``pyramid.config.Configurator.add_view`` instead.
  * ``registerUtility``, use
    ``pyramid.config.Configurator.registry.registerUtility`` instead.
  * ``registerAdapter``, use
    ``pyramid.config.Configurator.registry.registerAdapter`` instead.
  * ``registerSubscriber``, use
    ``pyramid.config.Configurator.add_subscriber`` instead.
  * ``registerRoute``, use
    ``pyramid.config.Configurator.add_route`` instead.
  * ``registerSettings``, use
    ``pyramid.config.Configurator.add_settings`` instead.
Dependencies
------------
- Pyramid now requires WebOb 1.2b3+ (the prior Pyramid release only relied on
  1.2dev+).  This is to ensure that we obtain a version of WebOb that returns
  ``request.path_info`` as text.
TODO.txt
@@ -98,18 +98,7 @@
Future
------
- 1.4: Kill off ``bfg.routes`` envvars in router.
- 1.4: Remove ``chameleon_text`` / ``chameleon_zpt`` deprecated functions
  (render_*)
- 1.4: Remove ``pyramid.configuration`` (deprecated).
- 1.4: Remove ``pyramid.paster.PyramidTemplate`` (deprecated).
- 1.4: Remove ``pyramid.settings.get_settings`` (deprecated).
- 1.5: Remove all deprecated ``pyramid.testing`` functions.
- 1.5: remove ``pyramid.view.static`` and ``pyramid.view.is_response``.
- 1.5: turn ``pyramid.settings.Settings`` into a function that returns the
  original dict (after ``__getattr__`` deprecation period, it was deprecated
docs/api.rst
@@ -10,8 +10,6 @@
   api/authorization
   api/authentication
   api/chameleon_text
   api/chameleon_zpt
   api/compat
   api/config
   api/events
docs/api/chameleon_text.rst
File was deleted
docs/api/chameleon_zpt.rst
File was deleted
docs/api/settings.rst
@@ -5,8 +5,6 @@
.. automodule:: pyramid.settings
  .. autofunction:: get_settings
  .. autofunction:: asbool
  .. autofunction:: aslist
pyramid/chameleon_text.py
@@ -1,6 +1,5 @@
import sys
from zope.deprecation import deprecated
from zope.interface import implementer
from pyramid.compat import reraise
@@ -20,7 +19,6 @@
from pyramid.decorator import reify
from pyramid import renderers
from pyramid.path import caller_package
def renderer_factory(info):
    return renderers.template_renderer_factory(info, TextTemplateRenderer)
@@ -51,94 +49,4 @@
            raise ValueError('renderer was passed non-dictionary as value')
        result = self.template(**system)
        return result
def get_renderer(path):
    """ Return a callable object which can be used to render a
    :term:`Chameleon` text template using the template implied by the
    ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
    factory = renderers.RendererHelper(path, package=package)
    return factory.get_renderer()
deprecated(
    'get_renderer',
    '(pyramid.chameleon_text.get_renderer is deprecated '
    'as of Pyramid 1.0; instead use pyramid.renderers.get_renderer)')
def get_template(path):
    """ Return the underyling object representing a :term:`Chameleon`
    text template using the template implied by the ``path`` argument.
    The ``path`` argument may be a package-relative path, an absolute
    path, or a :term:`asset specification`.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       the ``implementation()`` method of a template renderer retrieved via
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
    factory = renderers.RendererHelper(path, package=package)
    return factory.get_renderer().implementation()
deprecated(
    'get_template',
    '(pyramid.chameleon_text.get_template is deprecated '
    'as of Pyramid 1.0; instead use '
    'pyramid.renderers.get_renderer().implementation())')
def render_template(path, **kw):
    """ Render a :term:`Chameleon` text template using the template
    implied by the ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.  The arguments in ``*kw`` are passed as top-level
    names to the template, and so may be used within the template
    itself.  Returns a string.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.render` instead.
    """
    package = caller_package()
    request = kw.pop('request', None)
    renderer = renderers.RendererHelper(path, package=package)
    return renderer.render(kw, None, request=request)
deprecated(
    'render_template',
    '(pyramid.chameleon_text.render_template is deprecated '
    'as of Pyramid 1.0; instead use pyramid.renderers.render)')
def render_template_to_response(path, **kw):
    """ Render a :term:`Chameleon` text template using the template
    implied by the ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.  The arguments in ``*kw`` are passed as top-level
    names to the template, and so may be used within the template
    itself.  Returns a :term:`Response` object with the body as the
    template result.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.render_to_response` instead.
    """
    package = caller_package()
    request = kw.pop('request', None)
    renderer = renderers.RendererHelper(path, package=package)
    return renderer.render_to_response(kw, None, request=request)
deprecated(
    'render_template_to_response',
    '(pyramid.chameleon_text.render_template_to_response is deprecated '
    'as of Pyramid 1.0; instead use pyramid.renderers.render_to_response)')
pyramid/chameleon_zpt.py
@@ -1,6 +1,5 @@
import sys
from zope.deprecation import deprecated
from zope.interface import implementer
from pyramid.compat import reraise
@@ -18,7 +17,6 @@
from pyramid.interfaces import ITemplateRenderer
from pyramid.decorator import reify
from pyramid.path import caller_package
from pyramid import renderers
def renderer_factory(info):
@@ -58,92 +56,3 @@
        result = self.template(**system)
        return result
def get_renderer(path):
    """ Return a callable object which can be used to render a
    :term:`Chameleon` ZPT template using the template implied by the
    ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
    factory = renderers.RendererHelper(name=path, package=package)
    return factory.get_renderer()
deprecated(
    'get_renderer',
    '(pyramid.chameleon_zpt.get_renderer is deprecated '
    'as of Pyramid 1.0; instead use pyramid.renderers.get_renderer)')
def get_template(path):
    """ Return the underyling object representing a :term:`Chameleon`
    ZPT template using the template implied by the ``path`` argument.
    The ``path`` argument may be a package-relative path, an absolute
    path, or a :term:`asset specification`.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       the ``implementation()`` method of a template renderer retrieved via
       :func:`pyramid.renderers.get_renderer` instead.
    """
    package = caller_package()
    factory = renderers.RendererHelper(name=path, package=package)
    return factory.get_renderer().implementation()
deprecated(
    'get_template',
    '(pyramid.chameleon_zpt.get_template is deprecated '
    'as of Pyramid 1.0; instead use '
    'pyramid.renderers.get_renderer().implementation())')
def render_template(path, **kw):
    """ Render a :term:`Chameleon` ZPT template using the template
    implied by the ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.  The arguments in ``*kw`` are passed as top-level
    names to the template, and so may be used within the template
    itself.  Returns a string.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.render` instead.
    """
    package = caller_package()
    request = kw.pop('request', None)
    renderer = renderers.RendererHelper(name=path, package=package)
    return renderer.render(kw, None, request=request)
deprecated(
    'render_template',
    '(pyramid.chameleon_zpt.render_template is deprecated as of Pyramid 1.0; '
    'instead use pyramid.renderers.render)')
def render_template_to_response(path, **kw):
    """ Render a :term:`Chameleon` ZPT template using the template
    implied by the ``path`` argument.  The ``path`` argument may be a
    package-relative path, an absolute path, or a :term:`asset
    specification`.  The arguments in ``*kw`` are passed as top-level
    names to the template, and so may be used within the template
    itself.  Returns a :term:`Response` object with the body as the
    template result.
    .. warning::
       This API is deprecated in :app:`Pyramid` 1.0.  Use
       :func:`pyramid.renderers.render_to_response` instead.
    """
    package = caller_package()
    request = kw.pop('request', None)
    renderer = renderers.RendererHelper(name=path, package=package)
    return renderer.render_to_response(kw, None, request=request)
deprecated(
    'render_template_to_response',
    '(pyramid.chameleon_zpt.render_template_to_response is deprecated; as of '
    'Pyramid 1.0, instead use pyramid.renderers.render_to_response)')
pyramid/configuration.py
File was deleted
pyramid/paster.py
@@ -1,7 +1,5 @@
import os
import zope.deprecation
from paste.deploy import (
    loadapp,
    appconfig,
@@ -10,14 +8,6 @@
from pyramid.compat import configparser
from logging.config import fileConfig
from pyramid.scripting import prepare
from pyramid.scaffolds import PyramidTemplate # bw compat
PyramidTemplate = PyramidTemplate # pyflakes
zope.deprecation.deprecated(
    'PyramidTemplate', ('pyramid.paster.PyramidTemplate was moved to '
                        'pyramid.scaffolds.PyramidTemplate in Pyramid 1.1'),
)
def get_app(config_uri, name=None, loadapp=loadapp):
    """ Return the WSGI application named ``name`` in the PasteDeploy
pyramid/request.py
@@ -454,13 +454,4 @@
    new_request.environ['SCRIPT_NAME'] = new_script_name
    new_request.environ['PATH_INFO'] = new_path_info
    # In case downstream WSGI app is a Pyramid app, hack around existence of
    # these envars until we can safely remove them (see router.py); in any
    # case, even if these get removed, it might be better to not copy the
    # existing environ but to create a new one instead.
    if 'bfg.routes.route' in new_request.environ:
        del new_request.environ['bfg.routes.route']
    if 'bfg.routes.matchdict' in new_request.environ:
        del new_request.environ['bfg.routes.matchdict']
    return new_request.get_response(app)
pyramid/router.py
@@ -84,13 +84,6 @@
                           request.url)
                    logger and logger.debug(msg)
            else:
                # TODO: kill off bfg.routes.* environ keys
                # when traverser requires request arg, and
                # cant cope with environ anymore (they are
                # docs-deprecated as of BFG 1.3)
                environ = request.environ
                environ['bfg.routes.route'] = route
                environ['bfg.routes.matchdict'] = match
                attrs['matchdict'] = match
                attrs['matched_route'] = route
@@ -105,7 +98,8 @@
                            request.url,
                            route.name,
                            request.path_info,
                            route.pattern, match,
                            route.pattern,
                            match,
                            ', '.join([p.__text__ for p in route.predicates]))
                        )
                    logger and logger.debug(msg)
pyramid/settings.py
@@ -1,30 +1,4 @@
from zope.deprecation import deprecated
from pyramid.threadlocal import get_current_registry
from pyramid.compat import string_types
def get_settings():
    """
    Return a :term:`deployment settings` object for the current application.
    The object is a dictionary-like object that contains key/value pairs
    based on the dictionary passed as the ``settings`` argument to the
    :class:`pyramid.config.Configurator` constructor or the
    :func:`pyramid.router.make_app` API.
    .. warning:: This method is deprecated as of Pyramid 1.0.  Use
       ``pyramid.threadlocal.get_current_registry().settings`` instead or use
       the ``settings`` attribute of the registry available from the request
       (``request.registry.settings``).
    """
    reg = get_current_registry()
    return reg.settings
deprecated(
    'get_settings',
    '(pyramid.settings.get_settings is deprecated as of Pyramid 1.0.  Use'
    '``pyramid.threadlocal.get_current_registry().settings`` instead or use '
    'the ``settings`` attribute of the registry available from the request '
    '(``request.registry.settings``)).')
truthy = frozenset(('t', 'true', 'y', 'yes', 'on', '1'))
pyramid/testing.py
@@ -1,20 +1,14 @@
import copy
import os
from zope.deprecation import deprecated
from zope.interface import (
    implementer,
    Interface,
    alsoProvides,
    )
from pyramid.interfaces import (
    IRequest,
    IResponseFactory,
    ISecuredView,
    IView,
    IViewClassifier,
    ISession,
    )
@@ -26,14 +20,12 @@
from pyramid.config import Configurator
from pyramid.decorator import reify
from pyramid.httpexceptions import HTTPForbidden
from pyramid.response import Response
from pyramid.registry import Registry
from pyramid.security import (
    Authenticated,
    Everyone,
    has_permission,
    )
from pyramid.threadlocal import (
@@ -49,371 +41,6 @@
from pyramid.url import URLMethodsMixin
_marker = object()
def registerDummySecurityPolicy(userid=None, groupids=(), permissive=True):
    """ Registers a pair of faux :app:`Pyramid` security policies:
    a :term:`authentication policy` and a :term:`authorization
    policy`.
    The behavior of the registered :term:`authorization policy`
    depends on the ``permissive`` argument.  If ``permissive`` is
    true, a permissive :term:`authorization policy` is registered;
    this policy allows all access.  If ``permissive`` is false, a
    nonpermissive :term:`authorization policy` is registered; this
    policy denies all access.
    The behavior of the registered :term:`authentication policy`
    depends on the values provided for the ``userid`` and ``groupids``
    argument.  The authentication policy will return the userid
    identifier implied by the ``userid`` argument and the group ids
    implied by the ``groupids`` argument when the
    :func:`pyramid.security.authenticated_userid` or
    :func:`pyramid.security.effective_principals` APIs are used.
    This function is most useful when testing code that uses the APIs named
    :func:`pyramid.security.has_permission`,
    :func:`pyramid.security.authenticated_userid`,
    :func:`pyramid.security.unauthenticated_userid`,
    :func:`pyramid.security.effective_principals`, and
    :func:`pyramid.security.principals_allowed_by_permission`.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_securitypolicy`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_securitypolicy(userid=userid, groupids=groupids,
                                           permissive=permissive)
    config.commit()
    return result
deprecated('registerDummySecurityPolicy',
           'The testing.registerDummySecurityPolicy API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_securitypolicy '
           'method in your unit and integration tests.')
def registerResources(resources):
    """ Registers a dictionary of :term:`resource` objects that can be
    resolved via the :func:`pyramid.traversal.find_resource` API.
    The :func:`pyramid.traversal.find_resource` API is called with a
    path as one of its arguments.  If the dictionary you register when
    calling this method contains that path as a string key
    (e.g. ``/foo/bar`` or ``foo/bar``), the corresponding value will
    be returned to ``find_resource`` (and thus to your code) when
    :func:`pyramid.traversal.find_resource` is called with an
    equivalent path string or tuple.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_resources`
       method in your unit and integration tests.
    .. note:: For ancient backward compatibility purposes, this API can also
       be accessed as :func:`pyramid.testing.registerModels`.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_resources(resources)
    config.commit()
    return result
deprecated('registerResources',
           'The testing.registerResources API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_resources '
           'method in your unit and integration tests.')
registerModels = registerResources
deprecated('registerModels',
           'The testing.registerModels API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_resources '
           'method in your unit and integration tests.')
def registerEventListener(event_iface=None):
    """ Registers an :term:`event` listener (aka :term:`subscriber`)
    listening for events of the type ``event_iface``.  This method
    returns a list object which is appended to by the subscriber
    whenever an event is captured.
    When an event is dispatched that matches ``event_iface``, that
    event will be appended to the list.  You can then compare the
    values in the list to expected event notifications.  This method
    is useful when testing code that wants to call
    :meth:`pyramid.registry.Registry.notify`.
    The default value of ``event_iface`` (``None``) implies a
    subscriber registered for *any* kind of event.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_add_subscriber`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_add_subscriber(event_iface)
    config.commit()
    return result
deprecated('registerEventListener',
           'The testing.registerEventListener API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_add_subscriber '
           'method in your unit and integration tests.')
def registerTemplateRenderer(path, renderer=None):
    """ Register a template renderer at ``path`` (usually a relative
    filename ala ``templates/foo.pt``) and return the renderer object.
    If the ``renderer`` argument is None, a 'dummy' renderer will be
    used.  This function is useful when testing code that calls the
    :func:`pyramid.renderers.render` function or
    :func:`pyramid.renderers.render_to_response` function or any
    other ``render_*`` or ``get_*`` API of the
    :mod:`pyramid.renderers` module.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.testing_add_renderer`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    result = config.testing_add_template(path, renderer)
    config.commit()
    return result
deprecated('registerTemplateRenderer',
           'The testing.registerTemplateRenderer API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_add_renderer '
           'method in your unit and integration tests.')
# registerDummyRenderer is a deprecated alias that should never be removed
# (too much usage in the wild)
registerDummyRenderer = registerTemplateRenderer
deprecated('registerDummyRenderer',
           'The testing.registerDummyRenderer API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.testing_add_renderer '
           'method in your unit and integration tests.')
def registerView(name, result='', view=None, for_=(Interface, Interface),
                 permission=None):
    """ Registers a :app:`Pyramid` :term:`view callable` under the
    name implied by the ``name`` argument.  The view will return a
    :term:`WebOb` :term:`Response` object with the value implied by
    the ``result`` argument as its ``body`` attribute.  To gain more
    control, if you pass in a non-``None`` ``view`` argument, this
    value will be used as a view callable instead of an automatically
    generated view callable (and ``result`` is not used).
    To protect the view using a :term:`permission`, pass in a
    non-``None`` value as ``permission``.  This permission will be
    checked by any active :term:`authorization policy` when view
    execution is attempted.
    This function is useful when testing code which calls
    :func:`pyramid.view.render_view_to_response`.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.add_view`
       method in your unit and integration tests.
    """
    for_ = (IViewClassifier, ) + for_
    if view is None:
        def view(context, request):
            return Response(result)
    if permission is None:
        return registerAdapter(view, for_, IView, name)
    else:
        def _secure(context, request):
            if not has_permission(permission, context, request):
                raise HTTPForbidden('no permission')
            else:
                return view(context, request)
        _secure.__call_permissive__ = view
        def permitted(context, request):
            return has_permission(permission, context, request)
        _secure.__permitted__ = permitted
        return registerAdapter(_secure, for_, ISecuredView, name)
deprecated('registerView',
           'The registerView API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.add_view '
           'method in your unit and integration tests.')
def registerUtility(impl, iface=Interface, name=''):
    """ Register a ZCA utility component.
    The ``impl`` argument specifies the implementation of the utility.
    The ``iface`` argument specifies the :term:`interface` which will
    be later required to look up the utility
    (:class:`zope.interface.Interface`, by default).  The ``name``
    argument implies the utility name; it is the empty string by
    default.
    See `The ZCA book <http://www.muthukadan.net/docs/zca.html>`_ for
    more information about ZCA utilities.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the :meth:`pyramid.Registry.registerUtility`
       method.  The ``registry`` attribute of a :term:`Configurator`
       in your unit and integration tests is an instance of the
       :class:`pyramid.Registry` class.
    """
    reg = get_current_registry()
    reg.registerUtility(impl, iface, name=name)
    return impl
deprecated('registerUtility',
           'The registerUtility API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.registry.registerUtility method (via '
           'e.g. "config.registry.registerUtility(..)" '
           'method in your unit and integration tests.')
def registerAdapter(impl, for_=Interface, provides=Interface, name=''):
    """ Register a ZCA adapter component.
    The ``impl`` argument specifies the implementation of the
    component (often a class).  The ``for_`` argument implies the
    ``for`` interface type used for this registration; it is
    :class:`zope.interface.Interface` by default.  If ``for`` is not a
    tuple or list, it will be converted to a one-tuple before being
    passed to underlying :meth:`pyramid.registry.registerAdapter`
    API.
    The ``provides`` argument specifies the ZCA 'provides' interface,
    :class:`zope.interface.Interface` by default.
    The ``name`` argument is the empty string by default; it implies
    the name under which the adapter is registered.
    See `The ZCA book <http://www.muthukadan.net/docs/zca.html>`_ for
    more information about ZCA adapters.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the :meth:`pyramid.Registry.registerAdapter`
       method.  The ``registry`` attribute of a :term:`Configurator`
       in your unit and integration tests is an instance of the
       :class:`pyramid.Registry` class.
    """
    reg = get_current_registry()
    if not isinstance(for_, (tuple, list)):
        for_ = (for_,)
    reg.registerAdapter(impl, for_, provides, name=name)
    return impl
deprecated('registerAdapter',
           'The registerAdapter API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.registry.registerAdapter method (via '
           'e.g. "config.registry.registerAdapter(..)" '
           'method in your unit and integration tests.')
def registerSubscriber(subscriber, iface=Interface):
    """ Register a ZCA subscriber component.
    The ``subscriber`` argument specifies the implementation of the
    subscriber component (often a function).
    The ``iface`` argument is the interface type for which the
    subscriber will be registered (:class:`zope.interface.Interface`
    by default). If ``iface`` is not a tuple or list, it will be
    converted to a one-tuple before being passed to the underlying ZCA
    :meth:`pyramid.registry.registerHandler` method.
    See `The ZCA book <http://www.muthukadan.net/docs/zca.html>`_ for
    more information about ZCA subscribers.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.add_subscriber`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry)
    result = config.add_subscriber(subscriber, iface=iface)
    config.commit()
    return result
deprecated('registerSubscriber',
           'The testing.registerSubscriber API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.add_subscriber '
           'method in your unit and integration tests.')
def registerRoute(pattern, name, factory=None):
    """ Register a new :term:`route` using a pattern
    (e.g. ``:pagename``), a name (e.g. ``home``), and an optional root
    factory.
    The ``pattern`` argument implies the route pattern.  The ``name``
    argument implies the route name.  The ``factory`` argument implies
    a :term:`root factory` associated with the route.
    This API is useful for testing code that calls
    e.g. :func:`pyramid.url.route_url`.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.add_route`
       method in your unit and integration tests.
    """
    reg = get_current_registry()
    config = Configurator(registry=reg)
    config.setup_registry()
    result = config.add_route(name, pattern, factory=factory)
    config.commit()
    return result
deprecated('registerRoute',
           'The testing.registerRoute API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.add_route '
           'method in your unit and integration tests.')
def registerSettings(dictarg=None, **kw):
    """Register one or more 'setting' key/value pairs.  A setting is
    a single key/value pair in the dictionary-ish object returned from
    the API :attr:`pyramid.registry.Registry.settings`.
    You may pass a dictionary::
       registerSettings({'external_uri':'http://example.com'})
    Or a set of key/value pairs::
       registerSettings(external_uri='http://example.com')
    Use of this function is required when you need to test code that calls
    the :attr:`pyramid.registry.Registry.settings` API and which uses return
    values from that API.
    .. warning:: This API is deprecated as of :app:`Pyramid` 1.0.
       Instead use the
       :meth:`pyramid.config.Configurator.add_settings`
       method in your unit and integration tests.
    """
    registry = get_current_registry()
    config = Configurator(registry=registry)
    config.add_settings(dictarg, **kw)
deprecated('registerSettings',
           'The testing.registerSettings API is deprecated as of '
           'Pyramid 1.0. Instead use the '
           'pyramid.config.Configurator.add_settings '
           'method in your unit and integration tests.')
class DummyRootFactory(object):
    __parent__ = None
pyramid/tests/test_chameleon_text.py
@@ -7,22 +7,14 @@
class Base:
    def setUp(self):
        self.config = testing.setUp()
        from zope.deprecation import __show__
        __show__.off()
    def tearDown(self):
        testing.tearDown()
        from zope.deprecation import __show__
        __show__.on()
    def _getTemplatePath(self, name):
        import os
        here = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(here, 'fixtures', name)
    def _registerUtility(self, utility, iface, name=''):
        reg = self.config.registry
        reg.registerUtility(utility, iface, name=name)
class TextTemplateRendererTests(Base, unittest.TestCase):
    def _getTargetClass(self):
@@ -126,81 +118,6 @@
        result = instance.implementation()()
        self.assertTrue(isinstance(result, binary_type))
        self.assertEqual(result, b'Hello.\n')
class RenderTemplateTests(Base, unittest.TestCase):
    def _callFUT(self, name, **kw):
        from pyramid.chameleon_text import render_template
        return render_template(name, **kw)
    @skip_on('java')
    def test_it(self):
        minimal = self._getTemplatePath('minimal.txt')
        result = self._callFUT(minimal)
        self.assertTrue(isinstance(result, binary_type))
        self.assertEqual(result, b'Hello.\n')
class RenderTemplateToResponseTests(Base, unittest.TestCase):
    def _callFUT(self, name, **kw):
        from pyramid.chameleon_text import render_template_to_response
        return render_template_to_response(name, **kw)
    @skip_on('java')
    def test_minimal(self):
        minimal = self._getTemplatePath('minimal.txt')
        result = self._callFUT(minimal)
        from webob import Response
        self.assertTrue(isinstance(result, Response))
        self.assertEqual(result.app_iter, [b'Hello.\n'])
        self.assertEqual(result.status, '200 OK')
        self.assertEqual(len(result.headerlist), 2)
    @skip_on('java')
    def test_iresponsefactory_override(self):
        from webob import Response
        class Response2(Response):
            pass
        from pyramid.interfaces import IResponseFactory
        self._registerUtility(Response2, IResponseFactory)
        minimal = self._getTemplatePath('minimal.txt')
        result = self._callFUT(minimal)
        self.assertTrue(isinstance(result, Response2))
class GetRendererTests(Base, unittest.TestCase):
    def _callFUT(self, name):
        from pyramid.chameleon_text import get_renderer
        return get_renderer(name)
    @skip_on('java')
    def test_it(self):
        from pyramid.interfaces import IRendererFactory
        class Dummy:
            template = object()
            def implementation(self): pass
        renderer = Dummy()
        def rf(spec):
            return renderer
        self._registerUtility(rf, IRendererFactory, name='foo')
        result = self._callFUT('foo')
        self.assertTrue(result is renderer)
class GetTemplateTests(Base, unittest.TestCase):
    def _callFUT(self, name):
        from pyramid.chameleon_text import get_template
        return get_template(name)
    @skip_on('java')
    def test_it(self):
        from pyramid.interfaces import IRendererFactory
        class Dummy:
            template = object()
            def implementation(self):
                return self.template
        renderer = Dummy()
        def rf(spec):
            return renderer
        self._registerUtility(rf, IRendererFactory, name='foo')
        result = self._callFUT('foo')
        self.assertTrue(result is renderer.template)
class DummyLookup(object):
    auto_reload=True
pyramid/tests/test_chameleon_zpt.py
@@ -7,24 +7,15 @@
class Base(object):
    def setUp(self):
        self.config = testing.setUp()
        from zope.deprecation import __show__
        __show__.off()
    def tearDown(self):
        testing.tearDown()
        from zope.deprecation import __show__
        __show__.on()
    def _getTemplatePath(self, name):
        import os
        here = os.path.abspath(os.path.dirname(__file__))
        return os.path.join(here, 'fixtures', name)
    def _registerUtility(self, utility, iface, name=''):
        reg = self.config.registry
        reg.registerUtility(utility, iface, name=name)
        return reg
class ZPTTemplateRendererTests(Base, unittest.TestCase):
    def _getTargetClass(self):
        from pyramid.chameleon_zpt import ZPTTemplateRenderer
@@ -131,83 +122,6 @@
        self.assertEqual(result.rstrip('\n'),
                     '<div xmlns="http://www.w3.org/1999/xhtml">\n</div>')
        
class RenderTemplateTests(Base, unittest.TestCase):
    def _callFUT(self, name, **kw):
        from pyramid.chameleon_zpt import render_template
        return render_template(name, **kw)
    @skip_on('java')
    def test_it(self):
        minimal = self._getTemplatePath('minimal.pt')
        result = self._callFUT(minimal)
        self.assertTrue(isinstance(result, text_type))
        self.assertEqual(result.rstrip('\n'),
                     '<div xmlns="http://www.w3.org/1999/xhtml">\n</div>')
class RenderTemplateToResponseTests(Base, unittest.TestCase):
    def _callFUT(self, name, **kw):
        from pyramid.chameleon_zpt import render_template_to_response
        return render_template_to_response(name, **kw)
    @skip_on('java')
    def test_it(self):
        minimal = self._getTemplatePath('minimal.pt')
        result = self._callFUT(minimal)
        from webob import Response
        self.assertTrue(isinstance(result, Response))
        self.assertEqual(result.app_iter[0].rstrip(b'\n'),
                     b'<div xmlns="http://www.w3.org/1999/xhtml">\n</div>')
        self.assertEqual(result.status, '200 OK')
        self.assertEqual(len(result.headerlist), 2)
    @skip_on('java')
    def test_iresponsefactory_override(self):
        from webob import Response
        class Response2(Response):
            pass
        from pyramid.interfaces import IResponseFactory
        self._registerUtility(Response2, IResponseFactory)
        minimal = self._getTemplatePath('minimal.pt')
        result = self._callFUT(minimal)
        self.assertTrue(isinstance(result, Response2))
class GetRendererTests(Base, unittest.TestCase):
    def _callFUT(self, name):
        from pyramid.chameleon_zpt import get_renderer
        return get_renderer(name)
    @skip_on('java')
    def test_it(self):
        from pyramid.interfaces import IRendererFactory
        class Dummy:
            template = object()
            def implementation(self): pass
        renderer = Dummy()
        def rf(spec):
            return renderer
        self._registerUtility(rf, IRendererFactory, name='foo')
        result = self._callFUT('foo')
        self.assertTrue(result is renderer)
class GetTemplateTests(Base, unittest.TestCase):
    def _callFUT(self, name):
        from pyramid.chameleon_zpt import get_template
        return get_template(name)
    @skip_on('java')
    def test_it(self):
        from pyramid.interfaces import IRendererFactory
        class Dummy:
            template = object()
            def implementation(self):
                return self.template
        renderer = Dummy()
        def rf(spec):
            return renderer
        self._registerUtility(rf, IRendererFactory, name='foo')
        result = self._callFUT('foo')
        self.assertTrue(result is renderer.template)
class DummyLookup(object):
    auto_reload=True
pyramid/tests/test_configuration.py
File was deleted
pyramid/tests/test_path.py
@@ -138,9 +138,9 @@
        self.assertEqual(result, tests)
    def test_it_module(self):
        import pyramid.tests.test_configuration
        import pyramid.tests.test_path
        from pyramid import tests
        package = DummyPackageOrModule(pyramid.tests.test_configuration)
        package = DummyPackageOrModule(pyramid.tests.test_path)
        result = self._callFUT(package)
        self.assertEqual(result, tests)
@@ -395,7 +395,7 @@
        self.assertEqual(result, self.__class__)
    def test__zope_dottedname_style_resolve_relative_leading_dots(self):
        import pyramid.tests.test_configuration
        import pyramid.tests.test_path
        typ = self._makeOne()
        result = typ._zope_dottedname_style(
            '..tests.test_path.TestDottedNameResolver', pyramid.tests)
pyramid/tests/test_request.py
@@ -549,18 +549,6 @@
        self.assertEqual(request.environ['SCRIPT_NAME'], '/' + encoded)
        self.assertEqual(request.environ['PATH_INFO'], '/' + encoded)
    def test_it_removes_bfg_routes_info(self):
        request = DummyRequest({})
        request.environ['bfg.routes.route'] = True
        request.environ['bfg.routes.matchdict'] = True
        response = self._callFUT(request, 'app')
        self.assertTrue(request.copied)
        self.assertEqual(response, 'app')
        self.assertEqual(request.environ['SCRIPT_NAME'], '')
        self.assertEqual(request.environ['PATH_INFO'], '/')
        self.assertFalse('bfg.routes.route' in request.environ)
        self.assertFalse('bfg.routes.matchdict' in request.environ)
class DummyRequest:
    def __init__(self, environ=None):
        if environ is None:
pyramid/tests/test_router.py
@@ -646,8 +646,6 @@
        self.assertEqual(request.context, context)
        self.assertEqual(request.root, root)
        matchdict = {'action':'action1', 'article':'article1'}
        self.assertEqual(environ['bfg.routes.matchdict'], matchdict)
        self.assertEqual(environ['bfg.routes.route'].name, 'foo')
        self.assertEqual(request.matchdict, matchdict)
        self.assertEqual(request.matched_route.name, 'foo')
        self.assertEqual(len(logger.messages), 1)
@@ -712,8 +710,6 @@
        self.assertEqual(request.context, context)
        self.assertEqual(request.root, root)
        matchdict = {'action':'action1', 'article':'article1'}
        self.assertEqual(environ['bfg.routes.matchdict'], matchdict)
        self.assertEqual(environ['bfg.routes.route'].name, 'foo')
        self.assertEqual(request.matchdict, matchdict)
        self.assertEqual(request.matched_route.name, 'foo')
        self.assertTrue(IFoo.providedBy(request))
pyramid/tests/test_settings.py
@@ -1,30 +1,4 @@
import unittest
from pyramid import testing
class TestGetSettings(unittest.TestCase):
    def setUp(self):
        from pyramid.registry import Registry
        registry = Registry('testing')
        self.config = testing.setUp(registry=registry)
        from zope.deprecation import __show__
        __show__.off()
    def tearDown(self):
        self.config.end()
        from zope.deprecation import __show__
        __show__.on()
    def _callFUT(self):
        from pyramid.settings import get_settings
        return get_settings()
    def test_it_nosettings(self):
        self.assertEqual(self._callFUT()['reload_templates'], False)
    def test_it_withsettings(self):
        settings = {'a':1}
        self.config.registry.settings = settings
        self.assertEqual(self._callFUT(), settings)
class Test_asbool(unittest.TestCase):
    def _callFUT(self, s):
pyramid/tests/test_testing.py
@@ -1,285 +1,4 @@
import unittest
from pyramid.compat import text_
class TestBase(unittest.TestCase):
    def setUp(self):
        from pyramid.threadlocal import manager
        from pyramid.registry import Registry
        manager.clear()
        registry = Registry('testing')
        self.registry = registry
        manager.push({'registry':registry, 'request':None})
        from zope.deprecation import __show__
        __show__.off()
    def tearDown(self):
        from pyramid.threadlocal import manager
        manager.clear()
        from zope.deprecation import __show__
        __show__.on()
class Test_registerDummySecurityPolicy(TestBase):
    def test_registerDummySecurityPolicy(self):
        from pyramid import testing
        testing.registerDummySecurityPolicy('user', ('group1', 'group2'),
                                            permissive=False)
        from pyramid.interfaces import IAuthenticationPolicy
        from pyramid.interfaces import IAuthorizationPolicy
        ut = self.registry.getUtility(IAuthenticationPolicy)
        from pyramid.testing import DummySecurityPolicy
        self.assertTrue(isinstance(ut, DummySecurityPolicy))
        ut = self.registry.getUtility(IAuthorizationPolicy)
        self.assertEqual(ut.userid, 'user')
        self.assertEqual(ut.groupids, ('group1', 'group2'))
        self.assertEqual(ut.permissive, False)
class Test_registerResources(TestBase):
    def test_it(self):
        class Dummy:
            pass
        ob1 = Dummy()
        ob2 = Dummy()
        resources = {'/ob1':ob1, '/ob2':ob2}
        from pyramid import testing
        testing.registerResources(resources)
        from pyramid.interfaces import ITraverser
        adapter = self.registry.getAdapter(None, ITraverser)
        result = adapter(DummyRequest({'PATH_INFO':'/ob1'}))
        self.assertEqual(result['context'], ob1)
        self.assertEqual(result['view_name'], '')
        self.assertEqual(result['subpath'], ())
        self.assertEqual(result['traversed'], (text_('ob1'),))
        self.assertEqual(result['virtual_root'], ob1)
        self.assertEqual(result['virtual_root_path'], ())
        result = adapter(DummyRequest({'PATH_INFO':'/ob2'}))
        self.assertEqual(result['context'], ob2)
        self.assertEqual(result['view_name'], '')
        self.assertEqual(result['subpath'], ())
        self.assertEqual(result['traversed'], (text_('ob2'),))
        self.assertEqual(result['virtual_root'], ob2)
        self.assertEqual(result['virtual_root_path'], ())
        self.assertRaises(KeyError, adapter, DummyRequest({'PATH_INFO':'/ob3'}))
        from pyramid.traversal import find_resource
        self.assertEqual(find_resource(None, '/ob1'), ob1)
class Test_registerTemplateRenderer(TestBase):
    def test_registerTemplateRenderer(self):
        from pyramid import testing
        renderer = testing.registerTemplateRenderer('templates/foo')
        from pyramid.testing import DummyTemplateRenderer
        self.assertTrue(isinstance(renderer, DummyTemplateRenderer))
        from pyramid.renderers import render_to_response
        render_to_response('templates/foo', dict(foo=1, bar=2))
        renderer.assert_(foo=1)
        renderer.assert_(bar=2)
    def test_registerTemplateRenderer_explicitrenderer(self):
        from pyramid import testing
        def renderer(kw, system):
            self.assertEqual(kw, {'foo':1, 'bar':2})
        renderer = testing.registerTemplateRenderer('templates/foo', renderer)
        from pyramid.renderers import render_to_response
        render_to_response('templates/foo', dict(foo=1, bar=2))
class Test_registerEventListener(TestBase):
    def test_registerEventListener_single(self):
        from pyramid import testing
        L = testing.registerEventListener(IDummy)
        event = DummyEvent()
        self.registry.notify(event)
        self.assertEqual(len(L), 1)
        self.assertEqual(L[0], event)
        self.registry.notify(object())
        self.assertEqual(len(L), 1)
    def test_registerEventListener_multiple(self):
        from pyramid import testing
        L = testing.registerEventListener((Interface, IDummy))
        event = DummyEvent()
        event.object = 'foo'
        # the below is the equivalent of z.c.event.objectEventNotify(event)
        self.registry.subscribers((event.object, event), None)
        self.assertEqual(len(L), 2)
        self.assertEqual(L[0], 'foo')
        self.assertEqual(L[1], event)
    def test_registerEventListener_defaults(self):
        from pyramid import testing
        L = testing.registerEventListener()
        event = object()
        self.registry.notify(event)
        self.assertEqual(L[-1], event)
        event2 = object()
        self.registry.notify(event2)
        self.assertEqual(L[-1], event2)
class Test_registerView(TestBase):
    def test_registerView_defaults(self):
        from pyramid import testing
        view = testing.registerView('moo.html')
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        from pyramid.view import render_view_to_response
        request = DummyRequest()
        request.registry = self.registry
        response = render_view_to_response(None, request, 'moo.html')
        self.assertEqual(view(None, None).body, response.body)
    def test_registerView_withresult(self):
        from pyramid import testing
        view = testing.registerView('moo.html', 'yo')
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        from pyramid.view import render_view_to_response
        request = DummyRequest()
        request.registry = self.registry
        response = render_view_to_response(None, request, 'moo.html')
        self.assertEqual(response.body, b'yo')
    def test_registerView_custom(self):
        from pyramid import testing
        def view(context, request):
            from webob import Response
            return Response('123')
        view = testing.registerView('moo.html', view=view)
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        from pyramid.view import render_view_to_response
        request = DummyRequest()
        request.registry = self.registry
        response = render_view_to_response(None, request, 'moo.html')
        self.assertEqual(response.body, b'123')
    def test_registerView_with_permission_denying(self):
        from pyramid import testing
        from pyramid.httpexceptions import HTTPForbidden
        def view(context, request):
            """ """
        view = testing.registerView('moo.html', view=view, permission='bar')
        testing.registerDummySecurityPolicy(permissive=False)
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        from pyramid.view import render_view_to_response
        request = DummyRequest()
        request.registry = self.registry
        self.assertRaises(HTTPForbidden, render_view_to_response,
                          None, request, 'moo.html')
    def test_registerView_with_permission_denying2(self):
        from pyramid import testing
        from pyramid.security import view_execution_permitted
        def view(context, request):
            """ """
        view = testing.registerView('moo.html', view=view, permission='bar')
        testing.registerDummySecurityPolicy(permissive=False)
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        result = view_execution_permitted(None, None, 'moo.html')
        self.assertEqual(result, False)
    def test_registerView_with_permission_allowing(self):
        from pyramid import testing
        def view(context, request):
            from webob import Response
            return Response('123')
        view = testing.registerView('moo.html', view=view, permission='bar')
        testing.registerDummySecurityPolicy(permissive=True)
        import types
        self.assertTrue(isinstance(view, types.FunctionType))
        from pyramid.view import render_view_to_response
        request = DummyRequest()
        request.registry = self.registry
        result = render_view_to_response(None, request, 'moo.html')
        self.assertEqual(result.app_iter, [b'123'])
class Test_registerAdapter(TestBase):
    def test_registerAdapter(self):
        from zope.interface import Interface
        class provides(Interface):
            pass
        class Provider:
            pass
        class for_(Interface):
            pass
        from pyramid import testing
        testing.registerAdapter(Provider, (for_, for_), provides, name='foo')
        adapter = self.registry.adapters.lookup(
            (for_, for_), provides, name='foo')
        self.assertEqual(adapter, Provider)
    def test_registerAdapter_notlist(self):
        from zope.interface import Interface
        class provides(Interface):
            pass
        class Provider:
            pass
        class for_(Interface):
            pass
        from pyramid import testing
        testing.registerAdapter(Provider, for_, provides, name='foo')
        adapter = self.registry.adapters.lookup(
            (for_,), provides, name='foo')
        self.assertEqual(adapter, Provider)
class Test_registerUtility(TestBase):
    def test_registerUtility(self):
        from zope.interface import implementer
        from zope.interface import Interface
        class iface(Interface):
            pass
        @implementer(iface)
        class impl:
            def __call__(self):
                return 'foo'
        utility = impl()
        from pyramid import testing
        testing.registerUtility(utility, iface, name='mudge')
        self.assertEqual(self.registry.getUtility(iface, name='mudge')(), 'foo')
class Test_registerSubscriber(TestBase):
    def test_it(self):
        from pyramid import testing
        L = []
        def subscriber(event):
            L.append(event)
        testing.registerSubscriber(subscriber, iface=IDummy)
        event = DummyEvent()
        self.registry.notify(event)
        self.assertEqual(len(L), 1)
        self.assertEqual(L[0], event)
        self.registry.notify(object())
        self.assertEqual(len(L), 1)
class Test_registerRoute(TestBase):
    def test_registerRoute(self):
        from pyramid.config import Configurator
        from pyramid.request import Request
        from pyramid.interfaces import IRoutesMapper
        from pyramid.testing import registerRoute
        registerRoute(':pagename', 'home', DummyFactory)
        mapper = self.registry.getUtility(IRoutesMapper)
        self.assertEqual(len(mapper.routelist), 1)
        request = Request.blank('/')
        request.registry = self.registry
        config = Configurator(registry=self.registry)
        config.setup_registry()
        self.assertEqual(request.route_url('home', pagename='abc'),
                         'http://localhost/abc')
class Test_registerSettings(TestBase):
    def test_registerSettings(self):
        from pyramid.interfaces import ISettings
        from pyramid.testing import registerSettings
        registerSettings({'a':1, 'b':2})
        settings = self.registry.getUtility(ISettings)
        self.assertEqual(settings['a'], 1)
        self.assertEqual(settings['b'], 2)
        registerSettings(b=3, c=4)
        settings = self.registry.getUtility(ISettings)
        self.assertEqual(settings['a'], 1)
        self.assertEqual(settings['b'], 3)
        self.assertEqual(settings['c'], 4)
class TestDummyRootFactory(unittest.TestCase):
    def _makeOne(self, environ):
pyramid/tests/test_traversal.py
@@ -142,31 +142,25 @@
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_with_pathinfo_highorder(self):
        foo = DummyContext(None, text_(b'Qu\xc3\xa9bec', 'utf-8'))
        path = text_(b'/Qu\xc3\xa9bec', 'utf-8')
        foo = DummyContext(None, path)
        root = DummyContext(foo, 'root')
        policy = self._makeOne(root)
        if PY3: # pragma: no cover
            path_info = b'/Qu\xc3\xa9bec'.decode('latin-1')
        else:
            path_info = b'/Qu\xc3\xa9bec'
        environ = self._getEnviron(PATH_INFO=path_info)
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=path)
        result = policy(request)
        self.assertEqual(result['context'], foo)
        self.assertEqual(result['view_name'], '')
        self.assertEqual(result['subpath'], ())
        self.assertEqual(
            result['traversed'],
            (text_(b'Qu\xc3\xa9bec', 'utf-8'),)
            )
        self.assertEqual(result['traversed'], (path[1:],))
        self.assertEqual(result['root'], policy.root)
        self.assertEqual(result['virtual_root'], policy.root)
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_pathel_with_no_getitem(self):
        policy = self._makeOne(None)
        environ = self._getEnviron(PATH_INFO='/foo/bar')
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=text_('/foo/bar'))
        result = policy(request)
        self.assertEqual(result['context'], None)
        self.assertEqual(result['view_name'], 'foo')
@@ -179,8 +173,8 @@
    def test_call_withconn_getitem_emptypath_nosubpath(self):
        root = DummyContext()
        policy = self._makeOne(root)
        environ = self._getEnviron(PATH_INFO='')
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=text_(''))
        result = policy(request)
        self.assertEqual(result['context'], root)
        self.assertEqual(result['view_name'], '')
@@ -194,8 +188,8 @@
        foo = DummyContext()
        root = DummyContext(foo)
        policy = self._makeOne(root)
        environ = self._getEnviron(PATH_INFO='/foo/bar')
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=text_('/foo/bar'))
        result = policy(request)
        self.assertEqual(result['context'], foo)
        self.assertEqual(result['view_name'], 'bar')
@@ -209,8 +203,8 @@
        foo = DummyContext()
        root = DummyContext(foo)
        policy = self._makeOne(root)
        environ = self._getEnviron(PATH_INFO='/foo/bar/baz/buz')
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=text_('/foo/bar/baz/buz'))
        result = policy(request)
        self.assertEqual(result['context'], foo)
        self.assertEqual(result['view_name'], 'bar')
@@ -224,8 +218,8 @@
        foo = DummyContext()
        root = DummyContext(foo)
        policy = self._makeOne(root)
        environ = self._getEnviron(PATH_INFO='/@@foo')
        request = DummyRequest(environ)
        environ = self._getEnviron()
        request = DummyRequest(environ, path_info=text_('/@@foo'))
        result = policy(request)
        self.assertEqual(result['context'], root)
        self.assertEqual(result['view_name'], 'foo')
@@ -236,14 +230,13 @@
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_with_vh_root(self):
        environ = self._getEnviron(PATH_INFO='/baz',
                                   HTTP_X_VHM_ROOT='/foo/bar')
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/foo/bar')
        baz = DummyContext(None, 'baz')
        bar = DummyContext(baz, 'bar')
        foo = DummyContext(bar, 'foo')
        root = DummyContext(foo, 'root')
        policy = self._makeOne(root)
        request = DummyRequest(environ)
        request = DummyRequest(environ, path_info=text_('/baz'))
        result = policy(request)
        self.assertEqual(result['context'], baz)
        self.assertEqual(result['view_name'], '')
@@ -256,14 +249,13 @@
                         (text_('foo'), text_('bar')))
    def test_call_with_vh_root2(self):
        environ = self._getEnviron(PATH_INFO='/bar/baz',
                                   HTTP_X_VHM_ROOT='/foo')
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/foo')
        baz = DummyContext(None, 'baz')
        bar = DummyContext(baz, 'bar')
        foo = DummyContext(bar, 'foo')
        root = DummyContext(foo, 'root')
        policy = self._makeOne(root)
        request = DummyRequest(environ)
        request = DummyRequest(environ, path_info=text_('/bar/baz'))
        result = policy(request)
        self.assertEqual(result['context'], baz)
        self.assertEqual(result['view_name'], '')
@@ -275,14 +267,13 @@
        self.assertEqual(result['virtual_root_path'], (text_('foo'),))
    def test_call_with_vh_root3(self):
        environ = self._getEnviron(PATH_INFO='/foo/bar/baz',
                                   HTTP_X_VHM_ROOT='/')
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/')
        baz = DummyContext()
        bar = DummyContext(baz)
        foo = DummyContext(bar)
        root = DummyContext(foo)
        policy = self._makeOne(root)
        request = DummyRequest(environ)
        request = DummyRequest(environ, path_info=text_('/foo/bar/baz'))
        result = policy(request)
        self.assertEqual(result['context'], baz)
        self.assertEqual(result['view_name'], '')
@@ -294,14 +285,13 @@
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_with_vh_root4(self):
        environ = self._getEnviron(PATH_INFO='/',
                                   HTTP_X_VHM_ROOT='/foo/bar/baz')
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/foo/bar/baz')
        baz = DummyContext(None, 'baz')
        bar = DummyContext(baz, 'bar')
        foo = DummyContext(bar, 'foo')
        root = DummyContext(foo, 'root')
        policy = self._makeOne(root)
        request = DummyRequest(environ)
        request = DummyRequest(environ, path_info=text_('/'))
        result = policy(request)
        self.assertEqual(result['context'], baz)
        self.assertEqual(result['view_name'], '')
@@ -315,9 +305,8 @@
    def test_call_with_vh_root_path_root(self):
        policy = self._makeOne(None)
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/',
                                   PATH_INFO='/')
        request = DummyRequest(environ)
        environ = self._getEnviron(HTTP_X_VHM_ROOT='/')
        request = DummyRequest(environ, path_info=text_('/'))
        result = policy(request)
        self.assertEqual(result['context'], None)
        self.assertEqual(result['view_name'], '')
@@ -328,57 +317,48 @@
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_with_vh_root_highorder(self):
        path = text_(b'Qu\xc3\xa9bec', 'utf-8')
        bar = DummyContext(None, 'bar')
        foo = DummyContext(bar, text_(b'Qu\xc3\xa9bec', 'utf-8'))
        foo = DummyContext(bar, path)
        root = DummyContext(foo, 'root')
        policy = self._makeOne(root)
        if PY3: # pragma: no cover
            vhm_root = b'/Qu\xc3\xa9bec'.decode('latin-1')
        else:
            vhm_root = b'/Qu\xc3\xa9bec'
        environ = self._getEnviron(HTTP_X_VHM_ROOT=vhm_root,
                                   PATH_INFO='/bar')
        request = DummyRequest(environ)
        environ = self._getEnviron(HTTP_X_VHM_ROOT=vhm_root)
        request = DummyRequest(environ, path_info=text_('/bar'))
        result = policy(request)
        self.assertEqual(result['context'], bar)
        self.assertEqual(result['view_name'], '')
        self.assertEqual(result['subpath'], ())
        self.assertEqual(
            result['traversed'],
            (text_(b'Qu\xc3\xa9bec', 'utf-8'), text_('bar'))
            (path, text_('bar'))
            )
        self.assertEqual(result['root'], policy.root)
        self.assertEqual(result['virtual_root'], foo)
        self.assertEqual(
            result['virtual_root_path'],
            (text_(b'Qu\xc3\xa9bec', 'utf-8'),)
            (path,)
            )
    def test_non_utf8_path_segment_unicode_path_segments_fails(self):
    def test_path_info_raises_unicodedecodeerror(self):
        from pyramid.exceptions import URLDecodeError
        foo = DummyContext()
        root = DummyContext(foo)
        policy = self._makeOne(root)
        segment = native_(text_(b'LaPe\xc3\xb1a', 'utf-8'), 'utf-16')
        environ = self._getEnviron(PATH_INFO='/%s' % segment)
        request = DummyRequest(environ)
        self.assertRaises(URLDecodeError, policy, request)
    def test_non_utf8_path_segment_settings_unicode_path_segments_fails(self):
        from pyramid.exceptions import URLDecodeError
        foo = DummyContext()
        root = DummyContext(foo)
        policy = self._makeOne(root)
        segment = native_(text_(b'LaPe\xc3\xb1a', 'utf-8'), 'utf-16')
        environ = self._getEnviron(PATH_INFO='/%s' % segment)
        request = DummyRequest(environ)
        environ = self._getEnviron()
        toraise = UnicodeDecodeError('ascii', b'a', 2, 3, '5')
        request = DummyRequest(environ, toraise=toraise)
        request.matchdict = None
        self.assertRaises(URLDecodeError, policy, request)
    def test_withroute_nothingfancy(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {}}
        request = DummyRequest(environ)
        request = DummyRequest({})
        request.matchdict = {}
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], '')
@@ -391,8 +371,9 @@
    def test_withroute_with_subpath_string(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {'subpath':'/a/b/c'}}
        request = DummyRequest(environ)
        matchdict = {'subpath':'/a/b/c'}
        request = DummyRequest({})
        request.matchdict = matchdict
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], '')
@@ -405,8 +386,9 @@
    def test_withroute_with_subpath_tuple(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {'subpath':('a', 'b', 'c')}}
        request = DummyRequest(environ)
        matchdict = {'subpath':('a', 'b', 'c')}
        request = DummyRequest({})
        request.matchdict = matchdict
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], '')
@@ -419,8 +401,9 @@
    def test_withroute_and_traverse_string(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {'traverse':'foo/bar'}}
        request = DummyRequest(environ)
        matchdict =  {'traverse':text_('foo/bar')}
        request = DummyRequest({})
        request.matchdict = matchdict
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], 'foo')
@@ -433,8 +416,9 @@
    def test_withroute_and_traverse_tuple(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {'traverse':('foo', 'bar')}}
        request = DummyRequest(environ)
        matchdict = {'traverse':('foo', 'bar')}
        request = DummyRequest({})
        request.matchdict = matchdict
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], 'foo')
@@ -447,8 +431,9 @@
    def test_withroute_and_traverse_empty(self):
        resource = DummyContext()
        traverser = self._makeOne(resource)
        environ = {'bfg.routes.matchdict': {'traverse':''}}
        request = DummyRequest(environ)
        matchdict = {'traverse':''}
        request = DummyRequest({})
        request.matchdict = matchdict
        result = traverser(request)
        self.assertEqual(result['context'], resource)
        self.assertEqual(result['view_name'], '')
@@ -457,21 +442,6 @@
        self.assertEqual(result['root'], resource)
        self.assertEqual(result['virtual_root'], resource)
        self.assertEqual(result['virtual_root_path'], ())
    def test_call_with_environ(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always')
            policy = self._makeOne(None)
            environ = self._getEnviron()
            result = policy(environ)
            self.assertEqual(result['context'], None)
            self.assertEqual(result['view_name'], '')
            self.assertEqual(result['subpath'], ())
            self.assertEqual(result['traversed'], ())
            self.assertEqual(result['root'], policy.root)
            self.assertEqual(result['virtual_root'], policy.root)
            self.assertEqual(result['virtual_root_path'], ())
            self.assertEqual(len(w), 1)
class FindInterfaceTests(unittest.TestCase):
    def _callFUT(self, context, iface):
@@ -1310,11 +1280,28 @@
        return '<DummyContext with name %s at id %s>'%(self.__name__, id(self))
class DummyRequest:
    application_url = 'http://example.com:5432' # app_url never ends with slash
    def __init__(self, environ=None):
    matchdict = None
    matched_route = None
    def __init__(self, environ=None, path_info=text_('/'), toraise=None):
        if environ is None:
            environ = {}
        self.environ = environ
        self._set_path_info(path_info)
        self.toraise = toraise
    def _get_path_info(self):
        if self.toraise:
            raise self.toraise
        return self._path_info
    def _set_path_info(self, v):
        self._path_info = v
    path_info = property(_get_path_info, _set_path_info)
class DummyContextURL:
    def __init__(self, context, request):
pyramid/traversal.py
@@ -614,6 +614,7 @@
            _segment_cache[(segment, safe)] = result
            return result
    
slash = text_('/')
@implementer(ITraverser)
class ResourceTreeTraverser(object):
@@ -629,27 +630,17 @@
        self.root = root
    def __call__(self, request):
        try:
            environ = request.environ
        except AttributeError:
            # In BFG 1.0 and before, this API expected an environ
            # rather than a request; some bit of code may still be
            # passing us an environ.  If so, deal.
            environ = request
            depwarn = ('Passing an environ dictionary directly to a traverser '
                       'is deprecated in Pyramid 1.1.  Pass a request object '
                       'instead.')
            warnings.warn(depwarn, DeprecationWarning, 2)
        environ = request.environ
        matchdict = request.matchdict
        if 'bfg.routes.matchdict' in environ:
            matchdict = environ['bfg.routes.matchdict']
        if matchdict is not None:
            path = matchdict.get('traverse', '/') or '/'
            path = matchdict.get('traverse', slash) or slash
            if is_nonstr_iter(path):
                # this is a *traverse stararg (not a {traverse})
                # routing has already decoded these elements, so we just
                # need to join them
                path = '/'.join(path) or '/'
                path = slash.join(path) or slash
            subpath = matchdict.get('subpath', ())
            if not is_nonstr_iter(subpath):
@@ -663,9 +654,10 @@
            subpath = ()
            try:
                # empty if mounted under a path in mod_wsgi, for example
                path = decode_path_info(environ['PATH_INFO'] or '/')
                path = request.path_info or slash
            except KeyError:
                path = '/'
                # if environ['PATH_INFO'] is just not there
                path = slash
            except UnicodeDecodeError as e:
                raise URLDecodeError(e.encoding, e.object, e.start, e.end,
                                     e.reason)
@@ -684,7 +676,7 @@
        root = self.root
        ob = vroot = root
        if vpath == '/': # invariant: vpath must not be empty
        if vpath == slash: # invariant: vpath must not be empty
            # prevent a call to traversal_path if we know it's going
            # to return the empty tuple
            vpath_tuple = ()
setup.py
@@ -39,7 +39,7 @@
    'setuptools',
    'Chameleon >= 1.2.3',
    'Mako >= 0.3.6', # strict_undefined
    'WebOb >= 1.2dev', # response.text / py3 compat
    'WebOb >= 1.2b3', # request.path_info is unicode
    'repoze.lru >= 0.4', # py3 compat
    'zope.interface >= 3.8.0',  # has zope.interface.registry
    'zope.deprecation >= 3.5.0', # py3 compat