summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGES.txt159
-rw-r--r--TODO.txt6
-rw-r--r--docs/api/paster.rst2
-rw-r--r--docs/conf.py2
-rw-r--r--docs/narr/install.rst15
-rw-r--r--docs/narr/introspector.rst17
-rw-r--r--docs/whatsnew-1.4.rst17
-rw-r--r--pyramid/config/adapters.py78
-rw-r--r--pyramid/config/util.py50
-rw-r--r--pyramid/config/views.py46
-rw-r--r--pyramid/paster.py22
-rw-r--r--pyramid/scripts/__init__.py1
-rw-r--r--pyramid/scripts/common.py15
-rw-r--r--pyramid/scripts/prequest.py5
-rw-r--r--pyramid/scripts/proutes.py5
-rw-r--r--pyramid/scripts/pserve.py47
-rw-r--r--pyramid/scripts/pshell.py4
-rw-r--r--pyramid/scripts/ptweens.py3
-rw-r--r--pyramid/scripts/pviews.py7
-rw-r--r--pyramid/tests/pkgs/eventonly/__init__.py64
-rw-r--r--pyramid/tests/test_config/test_adapters.py9
-rw-r--r--pyramid/tests/test_config/test_util.py186
-rw-r--r--pyramid/tests/test_config/test_views.py190
-rw-r--r--pyramid/tests/test_integration.py12
-rw-r--r--pyramid/tests/test_paster.py35
-rw-r--r--pyramid/tests/test_scripts/test_common.py13
-rw-r--r--pyramid/tests/test_scripts/test_prequest.py4
-rw-r--r--pyramid/tests/test_scripts/test_proutes.py22
-rw-r--r--pyramid/tests/test_scripts/test_pserve.py43
-rw-r--r--setup.py2
30 files changed, 783 insertions, 298 deletions
diff --git a/CHANGES.txt b/CHANGES.txt
index 51266d15f..841d2ebec 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,5 +1,5 @@
-Next release
-============
+1.4b1 (2012-11-21)
+==================
Features
--------
@@ -10,6 +10,161 @@ Features
class. A similar microoptimization was done to
``pyramid.request.Request.is_response``.
+- Make it possible to use variable arguments on ``p*`` commands (``pserve``,
+ ``pshell``, ``pviews``, etc) in the form ``a=1 b=2`` so you can fill in
+ values in parameterized ``.ini`` file, e.g. ``pshell etc/development.ini
+ http_port=8080``. See https://github.com/Pylons/pyramid/pull/714
+
+- A somewhat advanced and obscure feature of Pyramid event handlers is their
+ ability to handle "multi-interface" notifications. These notifications have
+ traditionally presented multiple objects to the subscriber callable. For
+ instance, if an event was sent by code like this::
+
+ registry.notify(event, context)
+
+ In the past, in order to catch such an event, you were obligated to write and
+ register an event subscriber that mentioned both the event and the context in
+ its argument list::
+
+ @subscriber([SomeEvent, SomeContextType])
+ def asubscriber(event, context):
+ pass
+
+ In many subscriber callables registered this way, it was common for the logic
+ in the subscriber callable to completely ignore the second and following
+ arguments (e.g. ``context`` in the above example might be ignored), because
+ they usually existed as attributes of the event anyway. You could usually
+ get the same value by doing ``event.context`` or similar.
+
+ The fact that you needed to put an extra argument which you usually ignored
+ in the subscriber callable body was only a minor annoyance until we added
+ "subscriber predicates", used to narrow the set of circumstances under which
+ a subscriber will be executed, in a prior 1.4 alpha release. Once those were
+ added, the annoyance was escalated, because subscriber predicates needed to
+ accept the same argument list and arity as the subscriber callables that they
+ were configured against. So, for example, if you had these two subscriber
+ registrations in your code::
+
+ @subscriber([SomeEvent, SomeContextType])
+ def asubscriber(event, context):
+ pass
+
+ @subscriber(SomeOtherEvent)
+ def asubscriber(event):
+ pass
+
+ And you wanted to use a subscriber predicate::
+
+ @subscriber([SomeEvent, SomeContextType], mypredicate=True)
+ def asubscriber1(event, context):
+ pass
+
+ @subscriber(SomeOtherEvent, mypredicate=True)
+ def asubscriber2(event):
+ pass
+
+ If an existing ``mypredicate`` subscriber predicate had been written in such
+ a way that it accepted only one argument in its ``__call__``, you could not
+ use it against a subscription which named more than one interface in its
+ subscriber interface list. Similarly, if you had written a subscriber
+ predicate that accepted two arguments, you couldn't use it against a
+ registration that named only a single interface type.
+
+ For example, if you created this predicate::
+
+ class MyPredicate(object):
+ # portions elided...
+ def __call__(self, event):
+ return self.val == event.context.foo
+
+ It would not work against a multi-interface-registered subscription, so in
+ the above example, when you attempted to use it against ``asubscriber1``, it
+ would fail at runtime with a TypeError, claiming something was attempting to
+ call it with too many arguments.
+
+ To hack around this limitation, you were obligated to design the
+ ``mypredicate`` predicate to expect to receive in its ``__call__`` either a
+ single ``event`` argument (a SomeOtherEvent object) *or* a pair of arguments
+ (a SomeEvent object and a SomeContextType object), presumably by doing
+ something like this::
+
+ class MyPredicate(object):
+ # portions elided...
+ def __call__(self, event, context=None):
+ return self.val == event.context.foo
+
+ This was confusing and bad.
+
+ In order to allow people to ignore unused arguments to subscriber callables
+ and to normalize the relationship between event subscribers and subscriber
+ predicates, we now allow both subscribers and subscriber predicates to accept
+ only a single ``event`` argument even if they've been subscribed for
+ notifications that involve multiple interfaces. Subscribers and subscriber
+ predicates that accept only one argument will receive the first object passed
+ to ``notify``; this is typically (but not always) the event object. The
+ other objects involved in the subscription lookup will be discarded. You can
+ now write an event subscriber that accepts only ``event`` even if it
+ subscribes to multiple interfaces::
+
+ @subscriber([SomeEvent, SomeContextType])
+ def asubscriber(event):
+ # this will work!
+
+ This prevents you from needing to match the subscriber callable parameters to
+ the subscription type unnecessarily, especially when you don't make use of
+ any argument in your subscribers except for the event object itself.
+
+ Note, however, that if the event object is not the first
+ object in the call to ``notify``, you'll run into trouble. For example, if
+ notify is called with the context argument first::
+
+ registry.notify(context, event)
+
+ You won't be able to take advantage of the event-only feature. It will
+ "work", but the object received by your event handler won't be the event
+ object, it will be the context object, which won't be very useful::
+
+ @subscriber([SomeContextType, SomeEvent])
+ def asubscriber(event):
+ # bzzt! you'll be getting the context here as ``event``, and it'll
+ # be useless
+
+ Existing multiple-argument subscribers continue to work without issue, so you
+ should continue use those if your system notifies using multiple interfaces
+ and the first interface is not the event interface. For example::
+
+ @subscriber([SomeContextType, SomeEvent])
+ def asubscriber(context, event):
+ # this will still work!
+
+ The event-only feature makes it possible to use a subscriber predicate that
+ accepts only a request argument within both multiple-interface subscriber
+ registrations and single-interface subscriber registrations. You needn't
+ make slightly different variations of predicates depending on the
+ subscription type arguments. Instead, just write all your subscriber
+ predicates so they only accept ``event`` in their ``__call__`` and they'll be
+ useful across all registrations for subscriptions that use an event as their
+ first argument, even ones which accept more than just ``event``.
+
+ However, the same caveat applies to predicates as to subscriber callables: if
+ you're subscribing to a multi-interface event, and the first interface is not
+ the event interface, the predicate won't work properly. In such a case,
+ you'll need to match the predicate ``__call__`` argument ordering and
+ composition to the ordering of the interfaces. For example, if the
+ registration for the subscription uses ``[SomeContext, SomeEvent]``, you'll
+ need to reflect that in the ordering of the parameters of the predicate's
+ ``__call__`` method::
+
+ def __call__(self, context, event):
+ return event.request.path.startswith(self.val)
+
+ tl;dr: 1) When using multi-interface subscriptions, always use the event type
+ as the first subscription registration argument and 2) When 1 is true, use
+ only ``event`` in your subscriber and subscriber predicate parameter lists,
+ no matter how many interfaces the subscriber is notified with. This
+ combination will result in the maximum amount of reusability of subscriber
+ predicates and the least amount of thought on your part. Drink responsibly.
+
Bug Fixes
---------
diff --git a/TODO.txt b/TODO.txt
index 46edd8c6b..7a3561494 100644
--- a/TODO.txt
+++ b/TODO.txt
@@ -4,6 +4,9 @@ Pyramid TODOs
Nice-to-Have
------------
+- config.set_registry_attr with conflict detection... make sure the attr is
+ added before a commit, but register an action so a conflict can be detected.
+
- Provide the presumed renderer name to the called view as an attribute of
the request.
@@ -175,6 +178,3 @@ Probably Bad Ideas
- _fix_registry should dictify the registry being fixed.
-- config.set_registry_attr (with conflict detection)... bad idea because it
- won't take effect until after a commit and folks will be confused by that.
-
diff --git a/docs/api/paster.rst b/docs/api/paster.rst
index 3f7a1c364..bde128e05 100644
--- a/docs/api/paster.rst
+++ b/docs/api/paster.rst
@@ -7,7 +7,7 @@
.. autofunction:: bootstrap
- .. autofunction:: get_app(config_uri, name=None)
+ .. autofunction:: get_app(config_uri, name=None, options=None)
.. autofunction:: get_appsettings(config_uri, name=None)
diff --git a/docs/conf.py b/docs/conf.py
index 5e17de18a..3dc09d95d 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -81,7 +81,7 @@ copyright = '%s, Agendaless Consulting' % datetime.datetime.now().year
# other places throughout the built documents.
#
# The short X.Y version.
-version = '1.4a4'
+version = '1.4b1'
# The full version, including alpha/beta/rc tags.
release = version
diff --git a/docs/narr/install.rst b/docs/narr/install.rst
index e8482a289..882e76f11 100644
--- a/docs/narr/install.rst
+++ b/docs/narr/install.rst
@@ -243,6 +243,21 @@ Once you've got setuptools or distribute installed, you should install the
:term:`virtualenv` package. To install the :term:`virtualenv` package into
your setuptools-enabled Python interpreter, use the ``easy_install`` command.
+.. warning::
+
+ Even though Python 3.3 and better comes with ``pyvenv`` out of the box,
+ which is similar to ``virtualenv``, we suggest using ``virtualenv`` instead.
+ ``virtualenv`` works on well Python 3.3. This isn't a recommendation made
+ for technical reasons, it's one made because it's not feasible for the
+ authors of this guide to explain setup using multiple virtual environment
+ systems. We are aiming to not need to make the installation documentation
+ Turing-complete.
+
+ ``pyvenv`` will work fine. However, if you use ``pyvenv`` instead of
+ ``virtualenv``, you'll need to understand how to install software such as
+ ``distribute`` into the virtual environment manually, which this guide does
+ not cover.
+
.. code-block:: text
$ easy_install virtualenv
diff --git a/docs/narr/introspector.rst b/docs/narr/introspector.rst
index b88f3f0c8..bd81fb56a 100644
--- a/docs/narr/introspector.rst
+++ b/docs/narr/introspector.rst
@@ -130,6 +130,23 @@ introspectables in categories not described here.
A sequence of interfaces (or classes) that are subscribed to (the
resolution of the ``ifaces`` argument passed to ``add_subscriber``).
+ ``derived_subscriber``
+
+ A wrapper around the subscriber used internally by the system so it can
+ call it with more than one argument if your original subscriber accepts
+ only one.
+
+ ``predicates``
+
+ The predicate objects created as the result of passing predicate arguments
+ to ``add_susbcriber``
+
+ ``derived_predicates``
+
+ Wrappers around the predicate objects created as the result of passing
+ predicate arguments to ``add_susbcriber`` (to be used when predicates take
+ only one value but must be passed more than one).
+
``response adapters``
Each introspectable in the ``response adapters`` category represents a call
diff --git a/docs/whatsnew-1.4.rst b/docs/whatsnew-1.4.rst
index 5da28bb03..34fda5f37 100644
--- a/docs/whatsnew-1.4.rst
+++ b/docs/whatsnew-1.4.rst
@@ -225,6 +225,23 @@ Minor Feature Additions
as it doesn't make sense to assert that a nonexistent view is
execution-permitted. See https://github.com/Pylons/pyramid/issues/299.
+- Small microspeed enhancement which anticipates that a
+ :class:`pyramid.response.Response` object is likely to be returned from a
+ view. Some code is shortcut if the class of the object returned by a view is
+ this class. A similar microoptimization was done to
+ :func:`pyramid.request.Request.is_response`.
+
+- Make it possible to use variable arguments on all ``p*`` commands
+ (``pserve``, ``pshell``, ``pviews``, etc) in the form ``a=1 b=2`` so you can
+ fill in values in parameterized ``.ini`` file, e.g. ``pshell
+ etc/development.ini http_port=8080``.
+
+- In order to allow people to ignore unused arguments to subscriber callables
+ and to normalize the relationship between event subscribers and subscriber
+ predicates, we now allow both subscribers and subscriber predicates to accept
+ only a single ``event`` argument even if they've been subscribed for
+ notifications that involve multiple interfaces.
+
Backwards Incompatibilities
---------------------------
diff --git a/pyramid/config/adapters.py b/pyramid/config/adapters.py
index 12c4de660..dad60660a 100644
--- a/pyramid/config/adapters.py
+++ b/pyramid/config/adapters.py
@@ -10,6 +10,7 @@ from pyramid.interfaces import (
from pyramid.config.util import (
action_method,
+ takes_one_arg,
)
@@ -51,8 +52,22 @@ class AdaptersConfiguratorMixin(object):
def register():
predlist = self.get_predlist('subscriber')
order, preds, phash = predlist.make(self, **predicates)
- intr.update({'phash':phash, 'order':order, 'predicates':preds})
- derived_subscriber = self._derive_subscriber(subscriber, preds)
+
+ derived_predicates = [ self._derive_predicate(p) for p in preds ]
+ derived_subscriber = self._derive_subscriber(
+ subscriber,
+ derived_predicates,
+ )
+
+ intr.update(
+ {'phash':phash,
+ 'order':order,
+ 'predicates':preds,
+ 'derived_predicates':derived_predicates,
+ 'derived_subscriber':derived_subscriber,
+ }
+ )
+
self.registry.registerHandler(derived_subscriber, iface)
intr = self.introspectable(
@@ -68,25 +83,54 @@ class AdaptersConfiguratorMixin(object):
self.action(None, register, introspectables=(intr,))
return subscriber
+ def _derive_predicate(self, predicate):
+ derived_predicate = predicate
+
+ if eventonly(predicate):
+ def derived_predicate(*arg):
+ return predicate(arg[0])
+ # seems pointless to try to fix __doc__, __module__, etc as
+ # predicate will invariably be an instance
+
+ return derived_predicate
+
def _derive_subscriber(self, subscriber, predicates):
+ derived_subscriber = subscriber
+
+ if eventonly(subscriber):
+ def derived_subscriber(*arg):
+ return subscriber(arg[0])
+ if hasattr(subscriber, '__name__'):
+ update_wrapper(derived_subscriber, subscriber)
+
if not predicates:
- return subscriber
+ return derived_subscriber
+
def subscriber_wrapper(*arg):
- # We need to accept *arg and pass it along because zope
- # subscribers are designed poorly. Notification will always call
- # an associated subscriber with all of the objects involved in
- # the subscription lookup, despite the fact that the event sender
- # always has the option to attach those objects to the event
- # object itself (and usually does). It would be much saner if the
- # registry just used extra args passed to notify to do the lookup
- # but only called event subscribers with the actual event object,
- # or if we had been smart enough early on to always wrap
- # subscribers in something that threw away the extra args, but
- # c'est la vie.
+ # We need to accept *arg and pass it along because zope subscribers
+ # are designed awkwardly. Notification via
+ # registry.adapter.subscribers will always call an associated
+ # subscriber with all of the objects involved in the subscription
+ # lookup, despite the fact that the event sender always has the
+ # option to attach those objects to the event object itself, and
+ # almost always does.
+ #
+ # The "eventonly" jazz sprinkled in this function and related
+ # functions allows users to define subscribers and predicates which
+ # accept only an event argument without needing to accept the rest
+ # of the adaptation arguments. Had I been smart enough early on to
+ # use .subscriptions to find the subscriber functions in order to
+ # call them manually with a single "event" argument instead of
+ # relying on .subscribers to both find and call them implicitly
+ # with all args, the eventonly hack would not have been required.
+ # At this point, though, using .subscriptions and manual execution
+ # is not possible without badly breaking backwards compatibility.
if all((predicate(*arg) for predicate in predicates)):
- return subscriber(*arg)
+ return derived_subscriber(*arg)
+
if hasattr(subscriber, '__name__'):
update_wrapper(subscriber_wrapper, subscriber)
+
return subscriber_wrapper
@action_method
@@ -266,7 +310,7 @@ class AdaptersConfiguratorMixin(object):
if resource_iface is None:
resource_iface = Interface
self.registry.registerAdapter(
- adapter,
+ adapter,
(resource_iface, Interface),
IResourceURL,
)
@@ -281,3 +325,5 @@ class AdaptersConfiguratorMixin(object):
intr['resource_iface'] = resource_iface
self.action(discriminator, register, introspectables=(intr,))
+def eventonly(callee):
+ return takes_one_arg(callee, argname='event')
diff --git a/pyramid/config/util.py b/pyramid/config/util.py
index a83e23798..af0dd1641 100644
--- a/pyramid/config/util.py
+++ b/pyramid/config/util.py
@@ -1,10 +1,12 @@
from hashlib import md5
+import inspect
from pyramid.compat import (
bytes_,
is_nonstr_iter,
)
+from pyramid.compat import im_func
from pyramid.exceptions import ConfigurationError
from pyramid.registry import predvalseq
@@ -110,3 +112,51 @@ class PredicateList(object):
order = (MAX_ORDER - score) / (len(preds) + 1)
return order, preds, phash.hexdigest()
+def takes_one_arg(callee, attr=None, argname=None):
+ ismethod = False
+ if attr is None:
+ attr = '__call__'
+ if inspect.isroutine(callee):
+ fn = callee
+ elif inspect.isclass(callee):
+ try:
+ fn = callee.__init__
+ except AttributeError:
+ return False
+ ismethod = hasattr(fn, '__call__')
+ else:
+ try:
+ fn = getattr(callee, attr)
+ except AttributeError:
+ return False
+
+ try:
+ argspec = inspect.getargspec(fn)
+ except TypeError:
+ return False
+
+ args = argspec[0]
+
+ if hasattr(fn, im_func) or ismethod:
+ # it's an instance method (or unbound method on py2)
+ if not args:
+ return False
+ args = args[1:]
+
+ if not args:
+ return False
+
+ if len(args) == 1:
+ return True
+
+ if argname:
+
+ defaults = argspec[3]
+ if defaults is None:
+ defaults = ()
+
+ if args[0] == argname:
+ if len(args) - len(defaults) == 1:
+ return True
+
+ return False
diff --git a/pyramid/config/views.py b/pyramid/config/views.py
index 4e5af480d..d1b69566b 100644
--- a/pyramid/config/views.py
+++ b/pyramid/config/views.py
@@ -81,6 +81,7 @@ import pyramid.config.predicates
from pyramid.config.util import (
DEFAULT_PHASH,
MAX_ORDER,
+ takes_one_arg,
)
urljoin = urlparse.urljoin
@@ -503,50 +504,7 @@ class DefaultViewMapper(object):
return _attr_view
def requestonly(view, attr=None):
- ismethod = False
- if attr is None:
- attr = '__call__'
- if inspect.isroutine(view):
- fn = view
- elif inspect.isclass(view):
- try:
- fn = view.__init__
- except AttributeError:
- return False
- ismethod = hasattr(fn, '__call__')
- else:
- try:
- fn = getattr(view, attr)
- except AttributeError:
- return False
-
- try:
- argspec = inspect.getargspec(fn)
- except TypeError:
- return False
-
- args = argspec[0]
-
- if hasattr(fn, im_func) or ismethod:
- # it's an instance method (or unbound method on py2)
- if not args:
- return False
- args = args[1:]
- if not args:
- return False
-
- if len(args) == 1:
- return True
-
- defaults = argspec[3]
- if defaults is None:
- defaults = ()
-
- if args[0] == 'request':
- if len(args) - len(defaults) == 1:
- return True
-
- return False
+ return takes_one_arg(view, attr=attr, argname='request')
@implementer(IMultiView)
class MultiView(object):
diff --git a/pyramid/paster.py b/pyramid/paster.py
index b0e4d7933..ce07d1fe0 100644
--- a/pyramid/paster.py
+++ b/pyramid/paster.py
@@ -9,17 +9,27 @@ from pyramid.compat import configparser
from logging.config import fileConfig
from pyramid.scripting import prepare
-def get_app(config_uri, name=None, loadapp=loadapp):
+def get_app(config_uri, name=None, options=None, loadapp=loadapp):
""" Return the WSGI application named ``name`` in the PasteDeploy
config file specified by ``config_uri``.
+ ``options``, if passed, should be a dictionary used as variable assignments
+ like ``{'http_port': 8080}``. This is useful if e.g. ``%(http_port)s`` is
+ used in the config file.
+
If the ``name`` is None, this will attempt to parse the name from
the ``config_uri`` string expecting the format ``inifile#name``.
If no name is found, the name will default to "main"."""
path, section = _getpathsec(config_uri, name)
config_name = 'config:%s' % path
here_dir = os.getcwd()
- app = loadapp(config_name, name=section, relative_to=here_dir)
+ if options:
+ kw = {'global_conf': options}
+ else:
+ kw = {}
+
+ app = loadapp(config_name, name=section, relative_to=here_dir, **kw)
+
return app
def get_appsettings(config_uri, name=None, appconfig=appconfig):
@@ -63,7 +73,7 @@ def _getpathsec(config_uri, name):
section = name
return path, section
-def bootstrap(config_uri, request=None):
+def bootstrap(config_uri, request=None, options=None):
""" Load a WSGI application from the PasteDeploy config file specified
by ``config_uri``. The environment will be configured as if it is
currently serving ``request``, leaving a natural environment in place
@@ -103,10 +113,14 @@ def bootstrap(config_uri, request=None):
for you if none is provided. You can mutate the request's ``environ``
later to setup a specific host/port/scheme/etc.
+ ``options`` Is passed to get_app for use as variable assignments like
+ {'http_port': 8080} and then use %(http_port)s in the
+ config file.
+
See :ref:`writing_a_script` for more information about how to use this
function.
"""
- app = get_app(config_uri)
+ app = get_app(config_uri, options=options)
env = prepare(request)
env['app'] = app
return env
diff --git a/pyramid/scripts/__init__.py b/pyramid/scripts/__init__.py
index ed88d78b4..5bb534f79 100644
--- a/pyramid/scripts/__init__.py
+++ b/pyramid/scripts/__init__.py
@@ -1,2 +1 @@
# package
-
diff --git a/pyramid/scripts/common.py b/pyramid/scripts/common.py
index dfff26449..cbc172e9b 100644
--- a/pyramid/scripts/common.py
+++ b/pyramid/scripts/common.py
@@ -2,6 +2,21 @@ import os
from pyramid.compat import configparser
from logging.config import fileConfig
+def parse_vars(args):
+ """
+ Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
+ 'b', 'c': 'd'}``
+ """
+ result = {}
+ for arg in args:
+ if '=' not in arg:
+ raise ValueError(
+ 'Variable assignment %r invalid (no "=")'
+ % arg)
+ name, value = arg.split('=', 1)
+ result[name] = value
+ return result
+
def logging_file_config(config_file, fileConfig=fileConfig,
configparser=configparser):
"""
diff --git a/pyramid/scripts/prequest.py b/pyramid/scripts/prequest.py
index 13406372a..da6b8cc14 100644
--- a/pyramid/scripts/prequest.py
+++ b/pyramid/scripts/prequest.py
@@ -5,6 +5,7 @@ import textwrap
from pyramid.compat import url_unquote
from pyramid.request import Request
from pyramid.paster import get_app
+from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
command = PRequestCommand(argv, quiet)
@@ -101,7 +102,9 @@ class PRequestCommand(object):
name, value = item.split(':', 1)
headers[name] = value.strip()
- app = self.get_app(app_spec, self.options.app_name)
+ app = self.get_app(app_spec, self.options.app_name,
+ options=parse_vars(self.args[2:]))
+
request_method = (self.options.method or 'GET').upper()
environ = {
diff --git a/pyramid/scripts/proutes.py b/pyramid/scripts/proutes.py
index f64107d2b..49e19deca 100644
--- a/pyramid/scripts/proutes.py
+++ b/pyramid/scripts/proutes.py
@@ -3,6 +3,7 @@ import sys
import textwrap
from pyramid.paster import bootstrap
+from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
command = PRoutesCommand(argv, quiet)
@@ -47,12 +48,14 @@ class PRoutesCommand(object):
if not self.args:
self.out('requires a config file argument')
return 2
+
from pyramid.interfaces import IRouteRequest
from pyramid.interfaces import IViewClassifier
from pyramid.interfaces import IView
from zope.interface import Interface
config_uri = self.args[0]
- env = self.bootstrap[0](config_uri)
+
+ env = self.bootstrap[0](config_uri, options=parse_vars(self.args[1:]))
registry = env['registry']
mapper = self._get_mapper(registry)
if mapper is not None:
diff --git a/pyramid/scripts/pserve.py b/pyramid/scripts/pserve.py
index 9fbf0729a..6c7e1d654 100644
--- a/pyramid/scripts/pserve.py
+++ b/pyramid/scripts/pserve.py
@@ -22,12 +22,15 @@ import threading
import time
import traceback
-from paste.deploy import loadapp, loadserver
+from paste.deploy import loadserver
+from paste.deploy import loadapp
from pyramid.compat import WIN
from pyramid.paster import setup_logging
+from pyramid.scripts.common import parse_vars
+
MAXFD = 1024
if WIN and not hasattr(os, 'kill'): # pragma: no cover
@@ -160,6 +163,15 @@ class PServeCommand(object):
if not self.quiet:
print(msg)
+ def get_options(self):
+ if (len(self.args) > 1
+ and self.args[1] in self.possible_subcommands):
+ restvars = self.args[2:]
+ else:
+ restvars = self.args[1:]
+
+ return parse_vars(restvars)
+
def run(self): # pragma: no cover
if self.options.stop_daemon:
return self.stop_daemon()
@@ -176,13 +188,12 @@ class PServeCommand(object):
self.out('You must give a config file')
return 2
app_spec = self.args[0]
+
if (len(self.args) > 1
and self.args[1] in self.possible_subcommands):
cmd = self.args[1]
- restvars = self.args[2:]
else:
cmd = None
- restvars = self.args[1:]
if self.options.reload:
if os.environ.get(self._reloader_environ_key):
@@ -218,7 +229,9 @@ class PServeCommand(object):
self.options.daemon = True
app_name = self.options.app_name
- vars = self.parse_vars(restvars)
+
+ vars = self.get_options()
+
if not self._scheme_re.search(app_spec):
app_spec = 'config:' + app_spec
server_name = self.options.server_name
@@ -286,8 +299,9 @@ class PServeCommand(object):
server = self.loadserver(server_spec, name=server_name,
relative_to=base, global_conf=vars)
- app = self.loadapp(app_spec, name=app_name,
- relative_to=base, global_conf=vars)
+
+ app = self.loadapp(app_spec, name=app_name, relative_to=base,
+ global_conf=vars)
if self.verbose > 0:
if hasattr(os, 'getpid'):
@@ -310,27 +324,12 @@ class PServeCommand(object):
serve()
- def loadserver(self, server_spec, name, relative_to, **kw):# pragma:no cover
- return loadserver(
- server_spec, name=name, relative_to=relative_to, **kw)
-
def loadapp(self, app_spec, name, relative_to, **kw): # pragma: no cover
return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
- def parse_vars(self, args):
- """
- Given variables like ``['a=b', 'c=d']`` turns it into ``{'a':
- 'b', 'c': 'd'}``
- """
- result = {}
- for arg in args:
- if '=' not in arg:
- raise ValueError(
- 'Variable assignment %r invalid (no "=")'
- % arg)
- name, value = arg.split('=', 1)
- result[name] = value
- return result
+ def loadserver(self, server_spec, name, relative_to, **kw):# pragma:no cover
+ return loadserver(
+ server_spec, name=name, relative_to=relative_to, **kw)
def quote_first_command_arg(self, arg): # pragma: no cover
"""
diff --git a/pyramid/scripts/pshell.py b/pyramid/scripts/pshell.py
index 7a21eaf98..f74402928 100644
--- a/pyramid/scripts/pshell.py
+++ b/pyramid/scripts/pshell.py
@@ -9,6 +9,8 @@ from pyramid.paster import bootstrap
from pyramid.paster import setup_logging
+from pyramid.scripts.common import parse_vars
+
def main(argv=sys.argv, quiet=False):
command = PShellCommand(argv, quiet)
return command.run()
@@ -87,7 +89,7 @@ class PShellCommand(object):
self.pshell_file_config(config_file)
# bootstrap the environ
- env = self.bootstrap[0](config_uri)
+ env = self.bootstrap[0](config_uri, options=parse_vars(self.args[1:]))
# remove the closer from the env
closer = env.pop('closer')
diff --git a/pyramid/scripts/ptweens.py b/pyramid/scripts/ptweens.py
index d3e17db58..5fe2fa120 100644
--- a/pyramid/scripts/ptweens.py
+++ b/pyramid/scripts/ptweens.py
@@ -7,6 +7,7 @@ from pyramid.interfaces import ITweens
from pyramid.tweens import MAIN
from pyramid.tweens import INGRESS
from pyramid.paster import bootstrap
+from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
command = PTweensCommand(argv, quiet)
@@ -62,7 +63,7 @@ class PTweensCommand(object):
self.out('Requires a config file argument')
return 2
config_uri = self.args[0]
- env = self.bootstrap[0](config_uri)
+ env = self.bootstrap[0](config_uri, options=parse_vars(self.args[1:]))
registry = env['registry']
tweens = self._get_tweens(registry)
if tweens is not None:
diff --git a/pyramid/scripts/pviews.py b/pyramid/scripts/pviews.py
index 60aecb9bb..081c13e9d 100644
--- a/pyramid/scripts/pviews.py
+++ b/pyramid/scripts/pviews.py
@@ -4,6 +4,7 @@ import textwrap
from pyramid.interfaces import IMultiView
from pyramid.paster import bootstrap
+from pyramid.scripts.common import parse_vars
def main(argv=sys.argv, quiet=False):
command = PViewsCommand(argv, quiet)
@@ -230,10 +231,12 @@ class PViewsCommand(object):
if len(self.args) < 2:
self.out('Command requires a config file arg and a url arg')
return 2
- config_uri, url = self.args
+ config_uri = self.args[0]
+ url = self.args[1]
+
if not url.startswith('/'):
url = '/%s' % url
- env = self.bootstrap[0](config_uri)
+ env = self.bootstrap[0](config_uri, options=parse_vars(self.args[2:]))
registry = env['registry']
view = self._find_view(url, registry)
self.out('')
diff --git a/pyramid/tests/pkgs/eventonly/__init__.py b/pyramid/tests/pkgs/eventonly/__init__.py
new file mode 100644
index 000000000..7ae93ada6
--- /dev/null
+++ b/pyramid/tests/pkgs/eventonly/__init__.py
@@ -0,0 +1,64 @@
+from pyramid.view import view_config
+from pyramid.events import subscriber
+
+class Yup(object):
+ def __init__(self, val, config):
+ self.val = val
+
+ def text(self):
+ return 'path_startswith = %s' % (self.val,)
+
+ phash = text
+
+ def __call__(self, event):
+ return getattr(event.response, 'yup', False)
+
+class Foo(object):
+ def __init__(self, response):
+ self.response = response
+
+class Bar(object):
+ pass
+
+@subscriber(Foo)
+def foo(event):
+ event.response.text += 'foo '
+
+@subscriber(Foo, yup=True)
+def fooyup(event):
+ event.response.text += 'fooyup '
+
+@subscriber([Foo, Bar])
+def foobar(event):
+ event.response.text += 'foobar '
+
+@subscriber([Foo, Bar])
+def foobar2(event, context):
+ event.response.text += 'foobar2 '
+
+@subscriber([Foo, Bar], yup=True)
+def foobaryup(event):
+ event.response.text += 'foobaryup '
+
+@subscriber([Foo, Bar], yup=True)
+def foobaryup2(event, context):
+ event.response.text += 'foobaryup2 '
+
+@view_config(name='sendfoo')
+def sendfoo(request):
+ response = request.response
+ response.yup = True
+ request.registry.notify(Foo(response))
+ return response
+
+@view_config(name='sendfoobar')
+def sendfoobar(request):
+ response = request.response
+ response.yup = True
+ request.registry.notify(Foo(response), Bar())
+ return response
+
+def includeme(config):
+ config.add_subscriber_predicate('yup', Yup)
+ config.scan('pyramid.tests.pkgs.eventonly')
+
diff --git a/pyramid/tests/test_config/test_adapters.py b/pyramid/tests/test_config/test_adapters.py
index d47e012dc..4cbb1bf80 100644
--- a/pyramid/tests/test_config/test_adapters.py
+++ b/pyramid/tests/test_config/test_adapters.py
@@ -331,6 +331,15 @@ class AdaptersConfiguratorMixinTests(unittest.TestCase):
self.assertEqual(intr['adapter'], DummyResourceURL)
self.assertEqual(intr['resource_iface'], DummyIface)
+class Test_eventonly(unittest.TestCase):
+ def _callFUT(self, callee):
+ from pyramid.config.adapters import eventonly
+ return eventonly(callee)
+
+ def test_defaults(self):
+ def acallable(event, a=1, b=2): pass
+ self.assertTrue(self._callFUT(acallable))
+
class DummyTraverser(object):
def __init__(self, root):
self.root = root
diff --git a/pyramid/tests/test_config/test_util.py b/pyramid/tests/test_config/test_util.py
index b32f9c6ef..a984acfd0 100644
--- a/pyramid/tests/test_config/test_util.py
+++ b/pyramid/tests/test_config/test_util.py
@@ -365,6 +365,192 @@ class TestPredicateList(unittest.TestCase):
from pyramid.exceptions import ConfigurationError
self.assertRaises(ConfigurationError, self._callFUT, unknown=1)
+class Test_takes_one_arg(unittest.TestCase):
+ def _callFUT(self, view, attr=None, argname=None):
+ from pyramid.config.util import takes_one_arg
+ return takes_one_arg(view, attr=attr, argname=argname)
+
+ def test_requestonly_newstyle_class_no_init(self):
+ class foo(object):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_requestonly_newstyle_class_init_toomanyargs(self):
+ class foo(object):
+ def __init__(self, context, request):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_requestonly_newstyle_class_init_onearg_named_request(self):
+ class foo(object):
+ def __init__(self, request):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_newstyle_class_init_onearg_named_somethingelse(self):
+ class foo(object):
+ def __init__(self, req):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_newstyle_class_init_defaultargs_firstname_not_request(self):
+ class foo(object):
+ def __init__(self, context, request=None):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_newstyle_class_init_defaultargs_firstname_request(self):
+ class foo(object):
+ def __init__(self, request, foo=1, bar=2):
+ """ """
+ self.assertTrue(self._callFUT(foo, argname='request'))
+
+ def test_newstyle_class_init_firstname_request_with_secondname(self):
+ class foo(object):
+ def __init__(self, request, two):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_newstyle_class_init_noargs(self):
+ class foo(object):
+ def __init__():
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_oldstyle_class_no_init(self):
+ class foo:
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_oldstyle_class_init_toomanyargs(self):
+ class foo:
+ def __init__(self, context, request):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_oldstyle_class_init_onearg_named_request(self):
+ class foo:
+ def __init__(self, request):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_oldstyle_class_init_onearg_named_somethingelse(self):
+ class foo:
+ def __init__(self, req):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_oldstyle_class_init_defaultargs_firstname_not_request(self):
+ class foo:
+ def __init__(self, context, request=None):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_oldstyle_class_init_defaultargs_firstname_request(self):
+ class foo:
+ def __init__(self, request, foo=1, bar=2):
+ """ """
+ self.assertTrue(self._callFUT(foo, argname='request'), True)
+
+ def test_oldstyle_class_init_noargs(self):
+ class foo:
+ def __init__():
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_function_toomanyargs(self):
+ def foo(context, request):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_function_with_attr_false(self):
+ def bar(context, request):
+ """ """
+ def foo(context, request):
+ """ """
+ foo.bar = bar
+ self.assertFalse(self._callFUT(foo, 'bar'))
+
+ def test_function_with_attr_true(self):
+ def bar(context, request):
+ """ """
+ def foo(request):
+ """ """
+ foo.bar = bar
+ self.assertTrue(self._callFUT(foo, 'bar'))
+
+ def test_function_onearg_named_request(self):
+ def foo(request):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_function_onearg_named_somethingelse(self):
+ def foo(req):
+ """ """
+ self.assertTrue(self._callFUT(foo))
+
+ def test_function_defaultargs_firstname_not_request(self):
+ def foo(context, request=None):
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_function_defaultargs_firstname_request(self):
+ def foo(request, foo=1, bar=2):
+ """ """
+ self.assertTrue(self._callFUT(foo, argname='request'))
+
+ def test_function_noargs(self):
+ def foo():
+ """ """
+ self.assertFalse(self._callFUT(foo))
+
+ def test_instance_toomanyargs(self):
+ class Foo:
+ def __call__(self, context, request):
+ """ """
+ foo = Foo()
+ self.assertFalse(self._callFUT(foo))
+
+ def test_instance_defaultargs_onearg_named_request(self):
+ class Foo:
+ def __call__(self, request):
+ """ """
+ foo = Foo()
+ self.assertTrue(self._callFUT(foo))
+
+ def test_instance_defaultargs_onearg_named_somethingelse(self):
+ class Foo:
+ def __call__(self, req):
+ """ """
+ foo = Foo()
+ self.assertTrue(self._callFUT(foo))
+
+ def test_instance_defaultargs_firstname_not_request(self):
+ class Foo:
+ def __call__(self, context, request=None):
+ """ """
+ foo = Foo()
+ self.assertFalse(self._callFUT(foo))
+
+ def test_instance_defaultargs_firstname_request(self):
+ class Foo:
+ def __call__(self, request, foo=1, bar=2):
+ """ """
+ foo = Foo()
+ self.assertTrue(self._callFUT(foo, argname='request'), True)
+
+ def test_instance_nocall(self):
+ class Foo: pass
+ foo = Foo()
+ self.assertFalse(self._callFUT(foo))
+
+ def test_method_onearg_named_request(self):
+ class Foo:
+ def method(self, request):
+ """ """
+ foo = Foo()
+ self.assertTrue(self._callFUT(foo.method))
+
class DummyCustomPredicate(object):
def __init__(self):
diff --git a/pyramid/tests/test_config/test_views.py b/pyramid/tests/test_config/test_views.py
index bb4c5d519..4cebdce8a 100644
--- a/pyramid/tests/test_config/test_views.py
+++ b/pyramid/tests/test_config/test_views.py
@@ -1896,192 +1896,20 @@ class TestViewsConfigurationMixin(unittest.TestCase):
from pyramid.tests import test_config
self.assertEqual(result, test_config)
-
class Test_requestonly(unittest.TestCase):
def _callFUT(self, view, attr=None):
from pyramid.config.views import requestonly
- return requestonly(view, attr)
-
- def test_requestonly_newstyle_class_no_init(self):
- class foo(object):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_requestonly_newstyle_class_init_toomanyargs(self):
- class foo(object):
- def __init__(self, context, request):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_requestonly_newstyle_class_init_onearg_named_request(self):
- class foo(object):
- def __init__(self, request):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_newstyle_class_init_onearg_named_somethingelse(self):
- class foo(object):
- def __init__(self, req):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_newstyle_class_init_defaultargs_firstname_not_request(self):
- class foo(object):
- def __init__(self, context, request=None):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_newstyle_class_init_defaultargs_firstname_request(self):
- class foo(object):
- def __init__(self, request, foo=1, bar=2):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_newstyle_class_init_firstname_request_with_secondname(self):
- class foo(object):
- def __init__(self, request, two):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_newstyle_class_init_noargs(self):
- class foo(object):
- def __init__():
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_oldstyle_class_no_init(self):
- class foo:
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_oldstyle_class_init_toomanyargs(self):
- class foo:
- def __init__(self, context, request):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_oldstyle_class_init_onearg_named_request(self):
- class foo:
- def __init__(self, request):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_oldstyle_class_init_onearg_named_somethingelse(self):
- class foo:
- def __init__(self, req):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_oldstyle_class_init_defaultargs_firstname_not_request(self):
- class foo:
- def __init__(self, context, request=None):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_oldstyle_class_init_defaultargs_firstname_request(self):
- class foo:
- def __init__(self, request, foo=1, bar=2):
- """ """
- self.assertTrue(self._callFUT(foo), True)
-
- def test_oldstyle_class_init_noargs(self):
- class foo:
- def __init__():
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_function_toomanyargs(self):
- def foo(context, request):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_function_with_attr_false(self):
- def bar(context, request):
- """ """
- def foo(context, request):
- """ """
- foo.bar = bar
- self.assertFalse(self._callFUT(foo, 'bar'))
-
- def test_function_with_attr_true(self):
- def bar(context, request):
- """ """
- def foo(request):
- """ """
- foo.bar = bar
- self.assertTrue(self._callFUT(foo, 'bar'))
-
- def test_function_onearg_named_request(self):
- def foo(request):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_function_onearg_named_somethingelse(self):
- def foo(req):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_function_defaultargs_firstname_not_request(self):
- def foo(context, request=None):
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_function_defaultargs_firstname_request(self):
- def foo(request, foo=1, bar=2):
- """ """
- self.assertTrue(self._callFUT(foo))
-
- def test_function_noargs(self):
- def foo():
- """ """
- self.assertFalse(self._callFUT(foo))
-
- def test_instance_toomanyargs(self):
- class Foo:
- def __call__(self, context, request):
- """ """
- foo = Foo()
- self.assertFalse(self._callFUT(foo))
+ return requestonly(view, attr=attr)
- def test_instance_defaultargs_onearg_named_request(self):
- class Foo:
- def __call__(self, request):
- """ """
- foo = Foo()
- self.assertTrue(self._callFUT(foo))
-
- def test_instance_defaultargs_onearg_named_somethingelse(self):
- class Foo:
- def __call__(self, req):
- """ """
- foo = Foo()
- self.assertTrue(self._callFUT(foo))
-
- def test_instance_defaultargs_firstname_not_request(self):
- class Foo:
- def __call__(self, context, request=None):
- """ """
- foo = Foo()
- self.assertFalse(self._callFUT(foo))
-
- def test_instance_defaultargs_firstname_request(self):
- class Foo:
- def __call__(self, request, foo=1, bar=2):
- """ """
- foo = Foo()
- self.assertTrue(self._callFUT(foo), True)
+ def test_defaults(self):
+ def aview(request, a=1, b=2): pass
+ self.assertTrue(self._callFUT(aview))
- def test_instance_nocall(self):
- class Foo: pass
- foo = Foo()
- self.assertFalse(self._callFUT(foo))
-
- def test_method_onearg_named_request(self):
- class Foo:
- def method(self, request):
- """ """
- foo = Foo()
- self.assertTrue(self._callFUT(foo.method))
+ def test_otherattr(self):
+ class AView(object):
+ def __init__(self, request, a=1, b=2): pass
+ def bleh(self): pass
+ self.assertTrue(self._callFUT(AView, 'bleh'))
class Test_isexception(unittest.TestCase):
def _callFUT(self, ob):
diff --git a/pyramid/tests/test_integration.py b/pyramid/tests/test_integration.py
index 9a8f842aa..bf3960b2d 100644
--- a/pyramid/tests/test_integration.py
+++ b/pyramid/tests/test_integration.py
@@ -174,6 +174,18 @@ class TestStaticAppBase(IntegrationBase):
def test_oob_slash(self):
self.testapp.get('/%2F/test_integration.py', status=404)
+class TestEventOnlySubscribers(IntegrationBase, unittest.TestCase):
+ package = 'pyramid.tests.pkgs.eventonly'
+
+ def test_sendfoo(self):
+ res = self.testapp.get('/sendfoo', status=200)
+ self.assertEqual(sorted(res.body.split()), [b'foo', b'fooyup'])
+
+ def test_sendfoobar(self):
+ res = self.testapp.get('/sendfoobar', status=200)
+ self.assertEqual(sorted(res.body.split()),
+ [b'foobar', b'foobar2', b'foobaryup', b'foobaryup2'])
+
class TestStaticAppUsingAbsPath(TestStaticAppBase, unittest.TestCase):
package = 'pyramid.tests.pkgs.static_abspath'
diff --git a/pyramid/tests/test_paster.py b/pyramid/tests/test_paster.py
index d94b46a9f..b72e0e6b6 100644
--- a/pyramid/tests/test_paster.py
+++ b/pyramid/tests/test_paster.py
@@ -2,14 +2,16 @@ import os
import unittest
class Test_get_app(unittest.TestCase):
- def _callFUT(self, config_file, section_name, loadapp):
+ def _callFUT(self, config_file, section_name, options=None, loadapp=None):
from pyramid.paster import get_app
- return get_app(config_file, section_name, loadapp)
+ return get_app(
+ config_file, section_name, options=options, loadapp=loadapp
+ )
def test_it(self):
app = DummyApp()
loadapp = DummyLoadWSGI(app)
- result = self._callFUT('/foo/bar/myapp.ini', 'myapp', loadapp)
+ result = self._callFUT('/foo/bar/myapp.ini', 'myapp', loadapp=loadapp)
self.assertEqual(loadapp.config_name, 'config:/foo/bar/myapp.ini')
self.assertEqual(loadapp.section_name, 'myapp')
self.assertEqual(loadapp.relative_to, os.getcwd())
@@ -18,7 +20,9 @@ class Test_get_app(unittest.TestCase):
def test_it_with_hash(self):
app = DummyApp()
loadapp = DummyLoadWSGI(app)
- result = self._callFUT('/foo/bar/myapp.ini#myapp', None, loadapp)
+ result = self._callFUT(
+ '/foo/bar/myapp.ini#myapp', None, loadapp=loadapp
+ )
self.assertEqual(loadapp.config_name, 'config:/foo/bar/myapp.ini')
self.assertEqual(loadapp.section_name, 'myapp')
self.assertEqual(loadapp.relative_to, os.getcwd())
@@ -27,12 +31,30 @@ class Test_get_app(unittest.TestCase):
def test_it_with_hash_and_name_override(self):
app = DummyApp()
loadapp = DummyLoadWSGI(app)
- result = self._callFUT('/foo/bar/myapp.ini#myapp', 'yourapp', loadapp)
+ result = self._callFUT(
+ '/foo/bar/myapp.ini#myapp', 'yourapp', loadapp=loadapp
+ )
self.assertEqual(loadapp.config_name, 'config:/foo/bar/myapp.ini')
self.assertEqual(loadapp.section_name, 'yourapp')
self.assertEqual(loadapp.relative_to, os.getcwd())
self.assertEqual(result, app)
+ def test_it_with_options(self):
+ app = DummyApp()
+ loadapp = DummyLoadWSGI(app)
+ options = {'a':1}
+ result = self._callFUT(
+ '/foo/bar/myapp.ini#myapp',
+ 'yourapp',
+ loadapp=loadapp,
+ options=options,
+ )
+ self.assertEqual(loadapp.config_name, 'config:/foo/bar/myapp.ini')
+ self.assertEqual(loadapp.section_name, 'yourapp')
+ self.assertEqual(loadapp.relative_to, os.getcwd())
+ self.assertEqual(loadapp.kw, {'global_conf':options})
+ self.assertEqual(result, app)
+
class Test_get_appsettings(unittest.TestCase):
def _callFUT(self, config_file, section_name, appconfig):
from pyramid.paster import get_appsettings
@@ -132,10 +154,11 @@ class DummyLoadWSGI:
def __init__(self, result):
self.result = result
- def __call__(self, config_name, name=None, relative_to=None):
+ def __call__(self, config_name, name=None, relative_to=None, **kw):
self.config_name = config_name
self.section_name = name
self.relative_to = relative_to
+ self.kw = kw
return self.result
class DummyApp:
diff --git a/pyramid/tests/test_scripts/test_common.py b/pyramid/tests/test_scripts/test_common.py
index c3c792ca4..13ab0ae6a 100644
--- a/pyramid/tests/test_scripts/test_common.py
+++ b/pyramid/tests/test_scripts/test_common.py
@@ -17,6 +17,19 @@ class Test_logging_file_config(unittest.TestCase):
def fileConfig(self, config_file, dict):
return config_file, dict
+class TestParseVars(unittest.TestCase):
+ def test_parse_vars_good(self):
+ from pyramid.scripts.common import parse_vars
+ vars = ['a=1', 'b=2']
+ result = parse_vars(vars)
+ self.assertEqual(result, {'a': '1', 'b': '2'})
+
+ def test_parse_vars_bad(self):
+ from pyramid.scripts.common import parse_vars
+ vars = ['a']
+ self.assertRaises(ValueError, parse_vars, vars)
+
+
class DummyConfigParser(object):
def read(self, x):
pass
diff --git a/pyramid/tests/test_scripts/test_prequest.py b/pyramid/tests/test_scripts/test_prequest.py
index cf7af4218..91d2b322a 100644
--- a/pyramid/tests/test_scripts/test_prequest.py
+++ b/pyramid/tests/test_scripts/test_prequest.py
@@ -13,9 +13,11 @@ class TestPRequestCommand(unittest.TestCase):
cmd.out = self.out
return cmd
- def get_app(self, spec, app_name=None):
+ def get_app(self, spec, app_name=None, options=None):
self._spec = spec
self._app_name = app_name
+ self._options = options or {}
+
def helloworld(environ, start_request):
self._environ = environ
self._path_info = environ['PATH_INFO']
diff --git a/pyramid/tests/test_scripts/test_proutes.py b/pyramid/tests/test_scripts/test_proutes.py
index fad8c1895..25a3cd2e3 100644
--- a/pyramid/tests/test_scripts/test_proutes.py
+++ b/pyramid/tests/test_scripts/test_proutes.py
@@ -12,6 +12,28 @@ class TestPRoutesCommand(unittest.TestCase):
cmd.args = ('/foo/bar/myapp.ini#myapp',)
return cmd
+ def test_good_args(self):
+ cmd = self._getTargetClass()([])
+ cmd.bootstrap = (dummy.DummyBootstrap(),)
+ cmd.args = ('/foo/bar/myapp.ini#myapp', 'a=1')
+ route = dummy.DummyRoute('a', '/a')
+ mapper = dummy.DummyMapper(route)
+ cmd._get_mapper = lambda *arg: mapper
+ L = []
+ cmd.out = lambda msg: L.append(msg)
+ cmd.run()
+ self.assertTrue('<unknown>' in ''.join(L))
+
+ def test_bad_args(self):
+ cmd = self._getTargetClass()([])
+ cmd.bootstrap = (dummy.DummyBootstrap(),)
+ cmd.args = ('/foo/bar/myapp.ini#myapp', 'a')
+ route = dummy.DummyRoute('a', '/a')
+ mapper = dummy.DummyMapper(route)
+ cmd._get_mapper = lambda *arg: mapper
+
+ self.assertRaises(ValueError, cmd.run)
+
def test_no_routes(self):
command = self._makeOne()
mapper = dummy.DummyMapper()
diff --git a/pyramid/tests/test_scripts/test_pserve.py b/pyramid/tests/test_scripts/test_pserve.py
index d7b252d92..6e4b0f17d 100644
--- a/pyramid/tests/test_scripts/test_pserve.py
+++ b/pyramid/tests/test_scripts/test_pserve.py
@@ -22,6 +22,12 @@ class TestPServeCommand(unittest.TestCase):
def out(self, msg):
self.out_.write(msg)
+ def _get_server(*args, **kwargs):
+ def server(app):
+ return ''
+
+ return server
+
def _getTargetClass(self):
from pyramid.scripts.pserve import PServeCommand
return PServeCommand
@@ -193,16 +199,39 @@ class TestPServeCommand(unittest.TestCase):
msg = 'PID in %s is not valid (deleting)' % fn
self.assertEqual(self.out_.getvalue(), msg)
- def test_parse_vars_good(self):
- vars = ['a=1', 'b=2']
- inst = self._makeOne('development.ini')
- result = inst.parse_vars(vars)
+ def test_get_options_with_command(self):
+ inst = self._makeOne()
+ inst.args = ['foo', 'stop', 'a=1', 'b=2']
+ result = inst.get_options()
self.assertEqual(result, {'a': '1', 'b': '2'})
+ def test_get_options_no_command(self):
+ inst = self._makeOne()
+ inst.args = ['foo', 'a=1', 'b=2']
+ result = inst.get_options()
+ self.assertEqual(result, {'a': '1', 'b': '2'})
+
+ def test_parse_vars_good(self):
+ from pyramid.tests.test_scripts.dummy import DummyApp
+
+ inst = self._makeOne('development.ini', 'a=1', 'b=2')
+ inst.loadserver = self._get_server
+
+
+ app = DummyApp()
+
+ def get_app(*args, **kwargs):
+ app.global_conf = kwargs.get('global_conf', None)
+
+ inst.loadapp = get_app
+ inst.run()
+
+ self.assertEqual(app.global_conf, {'a': '1', 'b': '2'})
+
def test_parse_vars_bad(self):
- vars = ['a']
- inst = self._makeOne('development.ini')
- self.assertRaises(ValueError, inst.parse_vars, vars)
+ inst = self._makeOne('development.ini', 'a')
+ inst.loadserver = self._get_server
+ self.assertRaises(ValueError, inst.run)
class Test_read_pidfile(unittest.TestCase):
def _callFUT(self, filename):
diff --git a/setup.py b/setup.py
index 2356e76ac..55da3378d 100644
--- a/setup.py
+++ b/setup.py
@@ -68,7 +68,7 @@ testing_extras = tests_require + [
]
setup(name='pyramid',
- version='1.4a4',
+ version='1.4b1',
description=('The Pyramid web application development framework, a '
'Pylons project'),
long_description=README + '\n\n' + CHANGES,