Exemplo n.º 1
0
    def tearDown(self):
        from pyramid.threadlocal import manager

        manager.clear()
        getSiteManager = self._getSM()
        if getSiteManager is not None:
            getSiteManager.reset()
Exemplo n.º 2
0
def tearDown(unhook_zca=True):
    """Undo the effects :func:`pyramid.testing.setUp`.  Use this
    function in the ``tearDown`` method of a unit test that uses
    :func:`pyramid.testing.setUp` in its ``setUp`` method.

    If the ``unhook_zca`` argument is ``True`` (the default), call
    :func:`zope.component.getSiteManager.reset`.  This undoes the
    action of :func:`pyramid.testing.setUp` called with the
    argument ``hook_zca=True``.  If :mod:`zope.component` cannot be
    imported, ignore the argument.
    """
    global have_zca
    if unhook_zca and have_zca:
        try:
            from zope.component import getSiteManager
            getSiteManager.reset()
        except ImportError:  # pragma: no cover
            have_zca = False
    info = manager.pop()
    manager.clear()
    if info is not None:
        registry = info['registry']
        if hasattr(registry, '__init__') and hasattr(registry, '__name__'):
            try:
                registry.__init__(registry.__name__)
            except TypeError:
                # calling __init__ is largely for the benefit of
                # people who want to use the global ZCA registry;
                # however maybe somebody's using a registry we don't
                # understand, let's not blow up
                pass
Exemplo n.º 3
0
def tearDown(unhook_zca=True):
    """Undo the effects of :func:`pyramid.testing.setUp`.  Use this
    function in the ``tearDown`` method of a unit test that uses
    :func:`pyramid.testing.setUp` in its ``setUp`` method.

    If the ``unhook_zca`` argument is ``True`` (the default), call
    :func:`zope.component.getSiteManager.reset`.  This undoes the
    action of :func:`pyramid.testing.setUp` when called with the
    argument ``hook_zca=True``.  If :mod:`zope.component` cannot be
    imported, ``unhook_zca`` is set to ``False``.
    """
    global have_zca
    if unhook_zca and have_zca:
        try:
            from zope.component import getSiteManager
            getSiteManager.reset()
        except ImportError: # pragma: no cover
            have_zca = False
    info = manager.pop()
    manager.clear()
    if info is not None:
        registry = info['registry']
        if hasattr(registry, '__init__') and hasattr(registry, '__name__'):
            try:
                registry.__init__(registry.__name__)
            except TypeError:
                # calling __init__ is largely for the benefit of
                # people who want to use the global ZCA registry;
                # however maybe somebody's using a registry we don't
                # understand, let's not blow up
                pass
Exemplo n.º 4
0
 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()
Exemplo n.º 5
0
 def test_it_with_settings_passed_implicit_registry(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     try:
         config = self._callFUT(hook_zca=False, settings=dict(a=1))
         self.assertEqual(config.registry.settings['a'], 1)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 6
0
 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()
Exemplo n.º 7
0
 def test_it_with_settings_passed_implicit_registry(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     try:
         config = self._callFUT(hook_zca=False,
                                settings=dict(a=1))
         self.assertEqual(config.registry.settings['a'], 1)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 8
0
 def test_it_with_request(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     request = object()
     try:
         self._callFUT(request=request)
         current = manager.get()
         self.assertEqual(current['request'], request)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 9
0
 def test_it_with_request(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     request = object()
     try:
         self._callFUT(request=request)
         current = manager.get()
         self.assertEqual(current['request'], request)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 10
0
 def test_it_with_hook_zca_false(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     registry = object()
     try:
         self._callFUT(registry=registry, hook_zca=False)
         sm = getSiteManager()
         self.failIf(sm is registry)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 11
0
 def test_it_with_hook_zca_false(self):
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     from pyramid.registry import Registry
     registry = Registry()
     try:
         self._callFUT(registry=registry, hook_zca=False)
         sm = getSiteManager()
         self.failIf(sm is registry)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 12
0
 def test_it_with_registry(self):
     from pyramid.registry import Registry
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     registry = Registry()
     try:
         self._callFUT(registry=registry)
         current = manager.get()
         self.assertEqual(current['registry'], registry)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 13
0
 def test_unhook_zc_false(self):
     from pyramid.threadlocal import manager
     from zope.component import getSiteManager
     hook = lambda *arg: None
     try:
         getSiteManager.sethook(hook)
         self._callFUT(unhook_zca=False)
     finally:
         result = getSiteManager.sethook(None)
         self.assertEqual(result, hook)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 14
0
 def test_unhook_zc_false(self):
     from pyramid.threadlocal import manager
     from zope.component import getSiteManager
     hook = lambda *arg: None
     try:
         getSiteManager.sethook(hook)
         self._callFUT(unhook_zca=False)
     finally:
         result = getSiteManager.sethook(None)
         self.assertEqual(result, hook)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 15
0
 def test_it_with_registry(self):
     from pyramid.registry import Registry
     from zope.component import getSiteManager
     from pyramid.threadlocal import manager
     registry = Registry()
     try:
         self._callFUT(registry=registry)
         current = manager.get()
         self.assertEqual(current['registry'], registry)
     finally:
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 16
0
def new_test_request(login,
                     password,
                     method='basic',
                     context=None,
                     registry=None):
    """Create test request with HTTP authorization header"""
    auth = base64.b64encode('{}:{}'.format(login, password).encode()).decode()
    request = DummyRequest(
        headers={'Authorization': '{} {}'.format(method, auth)},
        context=context)
    if registry is not None:
        manager.clear()
        manager.push({'registry': registry, 'request': request})
    return request
Exemplo n.º 17
0
 def test_registry_cannot_be_inited(self):
     from pyramid.threadlocal import manager
     registry = DummyRegistry()
     def raiseit(name):
         raise TypeError
     registry.__init__ = raiseit
     old = {'registry':registry}
     try:
         manager.push(old)
         self._callFUT() # doesn't blow up
         current = manager.get()
         self.assertNotEqual(current, old)
         self.assertEqual(registry.inited, 1)
     finally:
         manager.clear()
Exemplo n.º 18
0
 def test_registry_cannot_be_inited(self):
     from pyramid.threadlocal import manager
     registry = DummyRegistry()
     def raiseit(name):
         raise TypeError
     registry.__init__ = raiseit
     old = {'registry':registry}
     try:
         manager.push(old)
         self._callFUT() # doesn't blow up
         current = manager.get()
         self.assertNotEqual(current, old)
         self.assertEqual(registry.inited, 1)
     finally:
         manager.clear()
Exemplo n.º 19
0
 def test_defaults(self):
     from pyramid.threadlocal import manager
     from zope.component import getSiteManager
     registry = DummyRegistry()
     old = {'registry':registry}
     hook = lambda *arg: None
     try:
         getSiteManager.sethook(hook)
         manager.push(old)
         self._callFUT()
         current = manager.get()
         self.assertNotEqual(current, old)
         self.assertEqual(registry.inited, 2)
     finally:
         result = getSiteManager.sethook(None)
         self.assertNotEqual(result, hook)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 20
0
 def test_defaults(self):
     from pyramid.threadlocal import manager
     from zope.component import getSiteManager
     registry = DummyRegistry()
     old = {'registry': registry}
     hook = lambda *arg: None
     try:
         getSiteManager.sethook(hook)
         manager.push(old)
         self._callFUT()
         current = manager.get()
         self.assertNotEqual(current, old)
         self.assertEqual(registry.inited, 2)
     finally:
         result = getSiteManager.sethook(None)
         self.assertNotEqual(result, hook)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 21
0
 def test_it_defaults(self):
     from pyramid.threadlocal import manager
     from pyramid.threadlocal import get_current_registry
     from pyramid.registry import Registry
     from zope.component import getSiteManager
     old = True
     manager.push(old)
     try:
         config = self._callFUT()
         current = manager.get()
         self.failIf(current is old)
         self.assertEqual(config.registry, current['registry'])
         self.assertEqual(current['registry'].__class__, Registry)
         self.assertEqual(current['request'], None)
     finally:
         result = getSiteManager.sethook(None)
         self.assertEqual(result, get_current_registry)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 22
0
 def test_it_defaults(self):
     from pyramid.threadlocal import manager
     from pyramid.threadlocal import get_current_registry
     from pyramid.registry import Registry
     from zope.component import getSiteManager
     old = True
     manager.push(old)
     try:
         config = self._callFUT()
         current = manager.get()
         self.failIf(current is old)
         self.assertEqual(config.registry, current['registry'])
         self.assertEqual(current['registry'].__class__, Registry)
         self.assertEqual(current['request'], None)
     finally:
         result = getSiteManager.sethook(None)
         self.assertEqual(result, get_current_registry)
         getSiteManager.reset()
         manager.clear()
Exemplo n.º 23
0
def tearDown(unhook_zca=True):
    """Undo the effects :func:`pyramid.testing.setUp`.  Use this
    function in the ``tearDown`` method of a unit test that uses
    :func:`pyramid.testing.setUp` in its ``setUp`` method.

    If the ``unhook_zca`` argument is ``True`` (the default), call
    :func:`zope.component.getSiteManager.reset`.  This undoes the
    action of :func:`pyramid.testing.setUp` called with the
    argument ``hook_zca=True``.  If :mod:`zope.component` cannot be
    imported, ignore the argument.

    .. warning:: Although this method of tearing a test setup down
                 will never disappear, after :app:`Pyramid` 1.0,
                 using the ``begin`` and ``end`` methods of a
                 ``Configurator`` are preferred to using
                 ``pyramid.testing.setUp`` and
                 ``pyramid.testing.tearDown``.  See
                 :ref:`unittesting_chapter` for more information.

    """
    if unhook_zca:
        try:
            from zope.component import getSiteManager

            getSiteManager.reset()
        except ImportError:  # pragma: no cover
            pass
    info = manager.pop()
    manager.clear()
    if info is not None:
        registry = info["registry"]
        if hasattr(registry, "__init__") and hasattr(registry, "__name__"):
            try:
                registry.__init__(registry.__name__)
            except TypeError:
                # calling __init__ is largely for the benefit of
                # people who want to use the global ZCA registry;
                # however maybe somebody's using a registry we don't
                # understand, let's not blow up
                pass
    _clearContext()  # XXX why?
Exemplo n.º 24
0
def setUp(registry=None,
          request=None,
          hook_zca=True,
          autocommit=True,
          settings=None):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``get_current_*`` functions (or call :app:`Pyramid` code
    that uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a *global*
    :term:`application registry`, which may cause unit tests to not be
    isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_request` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    If ``settings`` is not None, it must be a dictionary representing the
    values passed to a Configurator as its ``settings=`` argument.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    config = Configurator(registry=registry, autocommit=autocommit)
    if settings is None:
        settings = {}
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        from pyramid.config import DEFAULT_RENDERERS
        for name, renderer in DEFAULT_RENDERERS:
            # Cause the default renderers to be registered because
            # in-the-wild test code relies on being able to call
            # e.g. ``pyramid.chameleon_zpt.render_template``
            # without registering a .pt renderer, expecting the "real"
            # template to be rendered.  This is a holdover from when
            # individual template system renderers weren't indirected
            # by the ``pyramid.renderers`` machinery, and
            # ``render_template`` and friends went behind the back of
            # any existing renderer factory lookup system.
            config.add_renderer(name, renderer)
        config.add_default_view_predicates()
        config.add_default_route_predicates()
    config.commit()
    global have_zca
    try:
        have_zca and hook_zca and config.hook_zca()
    except ImportError:  # pragma: no cover
        # (dont choke on not being able to import z.component)
        have_zca = False
    config.begin(request=request)
    return config
Exemplo n.º 25
0
    def tearDown(self):
        from pyramid.threadlocal import manager

        manager.clear()
        getSiteManager.reset()
Exemplo n.º 26
0
def setUp(
    registry=None,
    request=None,
    hook_zca=True,
    autocommit=True,
    settings=None,
    package=None,
):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``get_current_*`` functions (or call :app:`Pyramid` code
    that uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a *global*
    :term:`application registry`, which may cause unit tests to not be
    isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_registry` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    If ``settings`` is not ``None``, it must be a dictionary representing the
    values passed to a Configurator as its ``settings=`` argument.

    If ``package`` is ``None`` it will be set to the caller's package. The
    ``package`` setting in the :class:`pyramid.config.Configurator` will
    affect any relative imports made via
    :meth:`pyramid.config.Configurator.include` or
    :meth:`pyramid.config.Configurator.maybe_dotted`.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    if package is None:
        package = caller_package()
    config = Configurator(
        registry=registry, autocommit=autocommit, package=package
    )
    if settings is None:
        settings = {}
    config._fix_registry()
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        config.add_default_response_adapters()
        config.add_default_renderers()
        config.add_default_accept_view_order()
        config.add_default_view_predicates()
        config.add_default_view_derivers()
        config.add_default_route_predicates()
        config.add_default_tweens()
        config.add_default_security()
    config.commit()
    global have_zca
    try:
        have_zca and hook_zca and config.hook_zca()
    except ImportError:  # pragma: no cover
        # (dont choke on not being able to import z.component)
        have_zca = False
    config.begin(request=request)
    return config
Exemplo n.º 27
0
def setUp(registry=None, request=None, hook_zca=True, autocommit=True):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any of the ``register*`` functions in :mod:`pyramid.testing`
      (such as :func:`pyramid.testing.registerResources`)

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``testing.register*`` APIs, or the
    ``get_current_*`` functions (or call :app:`Pyramid` code that
    uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a
    *global* :term:`application registry`, which may cause unit tests
    to not be isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_request` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.

    .. warning:: Although this method of setting up a test registry
                 will never disappear, after :app:`Pyramid` 1.0,
                 using the ``begin`` and ``end`` methods of a
                 ``Configurator`` are preferred to using
                 ``pyramid.testing.setUp`` and
                 ``pyramid.testing.tearDown``.  See
                 :ref:`testing_chapter` for more information.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    config = Configurator(registry=registry, autocommit=autocommit)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        from pyramid.config import DEFAULT_RENDERERS
        for name, renderer in DEFAULT_RENDERERS:
            # Cause the default renderers to be registered because
            # in-the-wild test code relies on being able to call
            # e.g. ``pyramid.chameleon_zpt.render_template``
            # without registering a .pt renderer, expecting the "real"
            # template to be rendered.  This is a holdover from when
            # individual template system renderers weren't indirected
            # by the ``pyramid.renderers`` machinery, and
            # ``render_template`` and friends went behind the back of
            # any existing renderer factory lookup system.
            config.add_renderer(name, renderer)
    config.commit()
    hook_zca and config.hook_zca()
    config.begin(request=request)
    return config
Exemplo n.º 28
0
 def tearDown(self):
     from pyramid.threadlocal import manager
     manager.clear()
     getSiteManager = self._getSM()
     if getSiteManager is not None:
         getSiteManager.reset()
Exemplo n.º 29
0
 def tearDown(self):
     from pyramid.threadlocal import manager
     manager.clear()
     from zope.deprecation import __show__
     __show__.on()
Exemplo n.º 30
0
    def setUp(self):
        from pyramid.threadlocal import manager
        manager.clear()

        import os
        import tempfile
        config = {
            'dbname': os.environ.get('KARLWEBTEST_PGDBNAME', 'karlwebtest'),
            'user': os.environ.get('KARLWEBTEST_PGUSER', 'karlwebtest'),
            'host': os.environ.get('KARLWEBTEST_PGHOST', 'localhost'),
            'password': os.environ.get('KARLWEBTEST_PGPASSWORD', 'test'),
            'port': os.environ.get('KARLWEBTEST_PGPORT', '5432'),
        }
        self.tmp = tmp = tempfile.mkdtemp('.karl-webtest')
        instances_ini = os.path.join(tmp, 'instances.ini')
        with open(instances_ini, 'w') as out:
            out.write(instances_ini_tmpl % config)
        karlserve_ini = os.path.join(tmp, 'karlserve.ini')
        with open(karlserve_ini, 'w') as out:
            out.write(karlserve_ini_tmpl)
        postoffice_ini = os.path.join(tmp, 'postoffice.ini')
        with open(postoffice_ini, 'w') as out:
            out.write(postoffice_ini_tmpl)
        var = os.path.join(tmp, 'var')
        os.mkdir(var)

        import pkg_resources
        import sys
        initdb = pkg_resources.resource_filename(__name__, 'initdb.py')
        binpath = os.path.dirname(os.path.abspath(sys.argv[0]))
        karlserve = os.path.join(binpath, 'karlserve')
        shell('dropdb %s' % config['dbname'], check=False)
        shell('createdb -O %s %s' % (config['user'], config['dbname']))
        shell('%s -C %s debug -S %s test' % (karlserve, karlserve_ini, initdb))
        postoffice = os.path.join(binpath, 'postoffice')
        shell('%s -C %s' % (postoffice, postoffice_ini))

        from karlserve.application import make_app
        from webtest import TestApp
        settings = {
            'var': var, 'instances_config': instances_ini,
            'who_secret': 'wackadoo', 'who_cookie': 'macadamia',
            'postoffice.zodb_uri':
            'file://%s/po.db?blobstorage_dir=%s/poblobs' % (var, var)}

        from relstorage.adapters import postgresql
        self.Psycopg2Connection = postgresql.Psycopg2Connection
        import psycopg2
        self.connect = psycopg2.connect
        self.connections = []
        def sneaky_connect(connect):
            def wrapper(*args, **kw):
                c = connect(*args, **kw)
                self.connections.append(c)
                return c
            return wrapper
        postgresql.Psycopg2Connection = sneaky_connect(
            postgresql.Psycopg2Connection)
        psycopg2.connect = sneaky_connect(psycopg2.connect)

        self.app = TestApp(browserid(make_app(settings), None, 'sshwabbits'))
Exemplo n.º 31
0
def setUp(registry=None, request=None, hook_zca=True, autocommit=True,
          settings=None, package=None):
    """
    Set :app:`Pyramid` registry and request thread locals for the
    duration of a single unit test.

    Use this function in the ``setUp`` method of a unittest test case
    which directly or indirectly uses:

    - any method of the :class:`pyramid.config.Configurator`
      object returned by this function.

    - the :func:`pyramid.threadlocal.get_current_registry` or
      :func:`pyramid.threadlocal.get_current_request` functions.

    If you use the ``get_current_*`` functions (or call :app:`Pyramid` code
    that uses these functions) without calling ``setUp``,
    :func:`pyramid.threadlocal.get_current_registry` will return a *global*
    :term:`application registry`, which may cause unit tests to not be
    isolated with respect to registrations they perform.

    If the ``registry`` argument is ``None``, a new empty
    :term:`application registry` will be created (an instance of the
    :class:`pyramid.registry.Registry` class).  If the ``registry``
    argument is not ``None``, the value passed in should be an
    instance of the :class:`pyramid.registry.Registry` class or a
    suitable testing analogue.

    After ``setUp`` is finished, the registry returned by the
    :func:`pyramid.threadlocal.get_current_registry` function will
    be the passed (or constructed) registry until
    :func:`pyramid.testing.tearDown` is called (or
    :func:`pyramid.testing.setUp` is called again) .

    If the ``hook_zca`` argument is ``True``, ``setUp`` will attempt
    to perform the operation ``zope.component.getSiteManager.sethook(
    pyramid.threadlocal.get_current_registry)``, which will cause
    the :term:`Zope Component Architecture` global API
    (e.g. :func:`zope.component.getSiteManager`,
    :func:`zope.component.getAdapter`, and so on) to use the registry
    constructed by ``setUp`` as the value it returns from
    :func:`zope.component.getSiteManager`.  If the
    :mod:`zope.component` package cannot be imported, or if
    ``hook_zca`` is ``False``, the hook will not be set.

    If ``settings`` is not ``None``, it must be a dictionary representing the
    values passed to a Configurator as its ``settings=`` argument.

    If ``package`` is ``None`` it will be set to the caller's package. The
    ``package`` setting in the :class:`pyramid.config.Configurator` will
    affect any relative imports made via
    :meth:`pyramid.config.Configurator.include` or
    :meth:`pyramid.config.Configurator.maybe_dotted`.

    This function returns an instance of the
    :class:`pyramid.config.Configurator` class, which can be
    used for further configuration to set up an environment suitable
    for a unit or integration test.  The ``registry`` attribute
    attached to the Configurator instance represents the 'current'
    :term:`application registry`; the same registry will be returned
    by :func:`pyramid.threadlocal.get_current_registry` during the
    execution of the test.
    """
    manager.clear()
    if registry is None:
        registry = Registry('testing')
    if package is None:
        package = caller_package()
    config = Configurator(registry=registry, autocommit=autocommit,
                          package=package)
    if settings is None:
        settings = {}
    if getattr(registry, 'settings', None) is None:
        config._set_settings(settings)
    if hasattr(registry, 'registerUtility'):
        # Sometimes nose calls us with a non-registry object because
        # it thinks this function is module test setup.  Likewise,
        # someone may be passing us an esoteric "dummy" registry, and
        # the below won't succeed if it doesn't have a registerUtility
        # method.
        config.add_default_renderers()
        config.add_default_view_predicates()
        config.add_default_route_predicates()
    config.commit()
    global have_zca
    try:
        have_zca and hook_zca and config.hook_zca()
    except ImportError: # pragma: no cover
        # (dont choke on not being able to import z.component)
        have_zca = False
    config.begin(request=request)
    return config
Exemplo n.º 32
0
 def tearDown(self):
     from pyramid.threadlocal import manager
     manager.clear()
     from zope.deprecation import __show__
     __show__.on()
Exemplo n.º 33
0
    def setUp(self):
        from pyramid.threadlocal import manager
        manager.clear()

        import os
        import tempfile
        config = {
            'dbname': os.environ.get('KARLWEBTEST_PGDBNAME', 'karlwebtest'),
            'user': os.environ.get('KARLWEBTEST_PGUSER', 'karlwebtest'),
            'host': os.environ.get('KARLWEBTEST_PGHOST', 'localhost'),
            'password': os.environ.get('KARLWEBTEST_PGPASSWORD', 'test'),
            'port': os.environ.get('KARLWEBTEST_PGPORT', '5432'),
        }
        self.tmp = tmp = tempfile.mkdtemp('.karl-webtest')
        instances_ini = os.path.join(tmp, 'instances.ini')
        with open(instances_ini, 'w') as out:
            out.write(instances_ini_tmpl % config)
        karlserve_ini = os.path.join(tmp, 'karlserve.ini')
        with open(karlserve_ini, 'w') as out:
            out.write(karlserve_ini_tmpl)
        postoffice_ini = os.path.join(tmp, 'postoffice.ini')
        with open(postoffice_ini, 'w') as out:
            out.write(postoffice_ini_tmpl)
        var = os.path.join(tmp, 'var')
        os.mkdir(var)

        import pkg_resources
        import sys
        initdb = pkg_resources.resource_filename(__name__, 'initdb.py')
        binpath = os.path.dirname(os.path.abspath(sys.argv[0]))
        karlserve = os.path.join(binpath, 'karlserve')
        shell('dropdb %s' % config['dbname'], check=False)
        shell('createdb -O %s %s' % (config['user'], config['dbname']))
        shell('%s -C %s debug -S %s test' % (karlserve, karlserve_ini, initdb))
        postoffice = os.path.join(binpath, 'postoffice')
        shell('%s -C %s' % (postoffice, postoffice_ini))

        from karlserve.application import make_app
        from webtest import TestApp
        settings = {
            'var':
            var,
            'instances_config':
            instances_ini,
            'who_secret':
            'wackadoo',
            'who_cookie':
            'macadamia',
            'postoffice.zodb_uri':
            'file://%s/po.db?blobstorage_dir=%s/poblobs' % (var, var)
        }

        from relstorage.adapters import postgresql
        self.Psycopg2Connection = postgresql.Psycopg2Connection
        import psycopg2
        self.connect = psycopg2.connect
        self.connections = []

        def sneaky_connect(connect):
            def wrapper(*args, **kw):
                c = connect(*args, **kw)
                self.connections.append(c)
                return c

            return wrapper

        postgresql.Psycopg2Connection = sneaky_connect(
            postgresql.Psycopg2Connection)
        psycopg2.connect = sneaky_connect(psycopg2.connect)

        self.app = TestApp(browserid(make_app(settings), None, 'sshwabbits'))
Exemplo n.º 34
0
 def tearDown(self):
     from pyramid.threadlocal import manager
     manager.clear()
     getSiteManager.reset()