summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--docs/tutorials/wiki2/authentication.rst15
-rw-r--r--docs/tutorials/wiki2/authorization.rst4
-rw-r--r--docs/tutorials/wiki2/src/authentication/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/src/authentication/tutorial/security.py2
-rw-r--r--docs/tutorials/wiki2/src/authentication/tutorial/templates/layout.jinja24
-rw-r--r--docs/tutorials/wiki2/src/authentication/tutorial/views/auth.py2
-rw-r--r--docs/tutorials/wiki2/src/authentication/tutorial/views/default.py6
-rw-r--r--docs/tutorials/wiki2/src/authorization/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/src/authorization/tutorial/security.py2
-rw-r--r--docs/tutorials/wiki2/src/authorization/tutorial/templates/layout.jinja24
-rw-r--r--docs/tutorials/wiki2/src/authorization/tutorial/views/auth.py2
-rw-r--r--docs/tutorials/wiki2/src/authorization/tutorial/views/default.py2
-rw-r--r--docs/tutorials/wiki2/src/basiclayout/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/src/installation/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/src/models/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/src/tests/tests/conftest.py42
-rw-r--r--docs/tutorials/wiki2/src/tests/tests/test_views.py48
-rw-r--r--docs/tutorials/wiki2/src/tests/tutorial/security.py2
-rw-r--r--docs/tutorials/wiki2/src/tests/tutorial/templates/layout.jinja24
-rw-r--r--docs/tutorials/wiki2/src/tests/tutorial/views/auth.py2
-rw-r--r--docs/tutorials/wiki2/src/tests/tutorial/views/default.py2
-rw-r--r--docs/tutorials/wiki2/src/views/tests/conftest.py43
-rw-r--r--docs/tutorials/wiki2/tests.rst7
23 files changed, 241 insertions, 167 deletions
diff --git a/docs/tutorials/wiki2/authentication.rst b/docs/tutorials/wiki2/authentication.rst
index 4d8723176..414d6c879 100644
--- a/docs/tutorials/wiki2/authentication.rst
+++ b/docs/tutorials/wiki2/authentication.rst
@@ -10,8 +10,7 @@ APIs to add login and logout functionality to our wiki.
We will implement authentication with the following steps:
-* Add a :term:`security policy` and a ``request.user`` computed property
- (``security.py``).
+* Add a :term:`security policy` (``security.py``).
* Add routes for ``/login`` and ``/logout`` (``routes.py``).
* Add login and logout views (``views/auth.py``).
* Add a login template (``login.jinja2``).
@@ -41,10 +40,8 @@ Update ``tutorial/security.py`` with the following content:
:linenos:
:language: python
-Here we've defined:
-
-* A new security policy named ``MySecurityPolicy``, which is implementing most of the :class:`pyramid.interfaces.ISecurityPolicy` interface by tracking a :term:`identity` using a signed cookie implemented by :class:`pyramid.authentication.AuthTktCookieHelper` (lines 8-34).
-* The ``request.user`` computed property is registered for use throughout our application as the authenticated ``tutorial.models.User`` object for the logged-in user (line 42-44).
+Here we've defined a new security policy named ``MySecurityPolicy``, which is implementing most of the :class:`pyramid.interfaces.ISecurityPolicy` interface by tracking a :term:`identity` using a signed cookie implemented by :class:`pyramid.authentication.AuthTktCookieHelper` (lines 8-34).
+The security policy outputs the authenticated ``tutorial.models.User`` object for the logged-in user as the :term:`identity`, which is available as ``request.identity``.
Our new :term:`security policy` defines how our application will remember, forget, and identify users.
It also handles authorization, which we'll cover in the next chapter (if you're wondering why we didn't implement the ``permits`` method yet).
@@ -64,7 +61,7 @@ Identifying the current user is done in a few steps:
#. The result is stored in the ``identity_cache`` which ensures that subsequent invocations return the same identity object for the request.
-Finally, :attr:`pyramid.request.Request.identity` contains either ``None`` or a ``tutorial.models.User`` instance and that value is aliased to ``request.user`` for convenience in our application.
+Finally, :attr:`pyramid.request.Request.identity` contains either ``None`` or a ``tutorial.models.User`` instance.
Note the usage of the ``identity_cache`` is optional, but it has several advantages in most scenarios:
@@ -156,7 +153,7 @@ Only the highlighted lines need to be changed.
If the user either is not logged in or is not in the ``basic`` or ``editor`` roles, then we raise ``HTTPForbidden``, which will trigger our forbidden view to compute a response.
However, we will hook this later to redirect to the login page.
-Also, now that we have ``request.user``, we no longer have to hard-code the creator as the ``editor`` user, so we can finally drop that hack.
+Also, now that we have ``request.identity``, we no longer have to hard-code the creator as the ``editor`` user, so we can finally drop that hack.
These simple checks should protect our views.
@@ -266,7 +263,7 @@ indicated by the highlighted lines.
:emphasize-lines: 2-12
:language: html
-The ``request.user`` will be ``None`` if the user is not authenticated, or a
+The ``request.identity`` will be ``None`` if the user is not authenticated, or a
``tutorial.models.User`` object if the user is authenticated. This check will
make the logout link shown only when the user is logged in, and conversely the
login link is only shown when the user is logged out.
diff --git a/docs/tutorials/wiki2/authorization.rst b/docs/tutorials/wiki2/authorization.rst
index 38b9b7373..be3a09664 100644
--- a/docs/tutorials/wiki2/authorization.rst
+++ b/docs/tutorials/wiki2/authorization.rst
@@ -5,7 +5,7 @@ Adding authorization
====================
In the last chapter we built :term:`authentication` into our wiki. We also
-went one step further and used the ``request.user`` object to perform some
+went one step further and used the ``request.identity`` object to perform some
explicit :term:`authorization` checks. This is fine for a lot of applications,
but :app:`Pyramid` provides some facilities for cleaning this up and decoupling
the constraints from the view function itself.
@@ -24,7 +24,7 @@ We will implement access control with the following steps:
Add ACL support
---------------
-A :term:`principal` is a level of abstraction on top of the raw :term:`userid`
+A :term:`principal` is a level of abstraction on top of the raw :term:`identity`
that describes the user in terms of its capabilities, roles, or other
identifiers that are easier to generalize. The permissions are then written
against the principals without focusing on the exact user involved.
diff --git a/docs/tutorials/wiki2/src/authentication/tests/conftest.py b/docs/tutorials/wiki2/src/authentication/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/authentication/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/authentication/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/authentication/tutorial/security.py b/docs/tutorials/wiki2/src/authentication/tutorial/security.py
index a4843f286..e0d8ed965 100644
--- a/docs/tutorials/wiki2/src/authentication/tutorial/security.py
+++ b/docs/tutorials/wiki2/src/authentication/tutorial/security.py
@@ -40,5 +40,3 @@ def includeme(config):
config.set_default_csrf_options(require_csrf=True)
config.set_security_policy(MySecurityPolicy(settings['auth.secret']))
- config.add_request_method(
- lambda request: request.identity, 'user', property=True)
diff --git a/docs/tutorials/wiki2/src/authentication/tutorial/templates/layout.jinja2 b/docs/tutorials/wiki2/src/authentication/tutorial/templates/layout.jinja2
index 64a1db0c5..55f4a85dc 100644
--- a/docs/tutorials/wiki2/src/authentication/tutorial/templates/layout.jinja2
+++ b/docs/tutorials/wiki2/src/authentication/tutorial/templates/layout.jinja2
@@ -33,13 +33,13 @@
</div>
<div class="col-md-10">
<div class="content">
- {% if request.user is none %}
+ {% if not request.is_authenticated %}
<p class="pull-right">
<a href="{{ request.route_url('login') }}">Login</a>
</p>
{% else %}
<form class="pull-right" action="{{ request.route_url('logout') }}" method="post">
- {{request.user.name}}
+ {{request.identity.name}}
<input type="hidden" name="csrf_token" value="{{ get_csrf_token() }}">
<button class="btn btn-link" type="submit">Logout</button>
</form>
diff --git a/docs/tutorials/wiki2/src/authentication/tutorial/views/auth.py b/docs/tutorials/wiki2/src/authentication/tutorial/views/auth.py
index e1a564415..807ff3464 100644
--- a/docs/tutorials/wiki2/src/authentication/tutorial/views/auth.py
+++ b/docs/tutorials/wiki2/src/authentication/tutorial/views/auth.py
@@ -53,7 +53,7 @@ def logout(request):
@forbidden_view_config(renderer='tutorial:templates/403.jinja2')
def forbidden_view(exc, request):
- if request.user is None:
+ if not request.is_authenticated:
next_url = request.route_url('login', _query={'next': request.url})
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/authentication/tutorial/views/default.py b/docs/tutorials/wiki2/src/authentication/tutorial/views/default.py
index 378ce0ae9..4fb715737 100644
--- a/docs/tutorials/wiki2/src/authentication/tutorial/views/default.py
+++ b/docs/tutorials/wiki2/src/authentication/tutorial/views/default.py
@@ -45,7 +45,7 @@ def view_page(request):
def edit_page(request):
pagename = request.matchdict['pagename']
page = request.dbsession.query(models.Page).filter_by(name=pagename).one()
- user = request.user
+ user = request.identity
if user is None or (user.role != 'editor' and page.creator != user):
raise HTTPForbidden
if request.method == 'POST':
@@ -60,7 +60,7 @@ def edit_page(request):
@view_config(route_name='add_page', renderer='tutorial:templates/edit.jinja2')
def add_page(request):
- user = request.user
+ user = request.identity
if user is None or user.role not in ('editor', 'basic'):
raise HTTPForbidden
pagename = request.matchdict['pagename']
@@ -70,7 +70,7 @@ def add_page(request):
if request.method == 'POST':
body = request.params['body']
page = models.Page(name=pagename, data=body)
- page.creator = request.user
+ page.creator = request.identity
request.dbsession.add(page)
next_url = request.route_url('view_page', pagename=pagename)
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/authorization/tests/conftest.py b/docs/tutorials/wiki2/src/authorization/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/authorization/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/authorization/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/authorization/tutorial/security.py b/docs/tutorials/wiki2/src/authorization/tutorial/security.py
index 4f79195ef..18f0bd4c7 100644
--- a/docs/tutorials/wiki2/src/authorization/tutorial/security.py
+++ b/docs/tutorials/wiki2/src/authorization/tutorial/security.py
@@ -59,5 +59,3 @@ def includeme(config):
config.set_default_csrf_options(require_csrf=True)
config.set_security_policy(MySecurityPolicy(settings['auth.secret']))
- config.add_request_method(
- lambda request: request.identity, 'user', property=True)
diff --git a/docs/tutorials/wiki2/src/authorization/tutorial/templates/layout.jinja2 b/docs/tutorials/wiki2/src/authorization/tutorial/templates/layout.jinja2
index 64a1db0c5..55f4a85dc 100644
--- a/docs/tutorials/wiki2/src/authorization/tutorial/templates/layout.jinja2
+++ b/docs/tutorials/wiki2/src/authorization/tutorial/templates/layout.jinja2
@@ -33,13 +33,13 @@
</div>
<div class="col-md-10">
<div class="content">
- {% if request.user is none %}
+ {% if not request.is_authenticated %}
<p class="pull-right">
<a href="{{ request.route_url('login') }}">Login</a>
</p>
{% else %}
<form class="pull-right" action="{{ request.route_url('logout') }}" method="post">
- {{request.user.name}}
+ {{request.identity.name}}
<input type="hidden" name="csrf_token" value="{{ get_csrf_token() }}">
<button class="btn btn-link" type="submit">Logout</button>
</form>
diff --git a/docs/tutorials/wiki2/src/authorization/tutorial/views/auth.py b/docs/tutorials/wiki2/src/authorization/tutorial/views/auth.py
index e1a564415..807ff3464 100644
--- a/docs/tutorials/wiki2/src/authorization/tutorial/views/auth.py
+++ b/docs/tutorials/wiki2/src/authorization/tutorial/views/auth.py
@@ -53,7 +53,7 @@ def logout(request):
@forbidden_view_config(renderer='tutorial:templates/403.jinja2')
def forbidden_view(exc, request):
- if request.user is None:
+ if not request.is_authenticated:
next_url = request.route_url('login', _query={'next': request.url})
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/authorization/tutorial/views/default.py b/docs/tutorials/wiki2/src/authorization/tutorial/views/default.py
index 214788357..4a2a66c84 100644
--- a/docs/tutorials/wiki2/src/authorization/tutorial/views/default.py
+++ b/docs/tutorials/wiki2/src/authorization/tutorial/views/default.py
@@ -56,7 +56,7 @@ def add_page(request):
if request.method == 'POST':
body = request.params['body']
page = models.Page(name=pagename, data=body)
- page.creator = request.user
+ page.creator = request.identity
request.dbsession.add(page)
next_url = request.route_url('view_page', pagename=pagename)
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/basiclayout/tests/conftest.py b/docs/tutorials/wiki2/src/basiclayout/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/basiclayout/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/basiclayout/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/installation/tests/conftest.py b/docs/tutorials/wiki2/src/installation/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/installation/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/installation/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/models/tests/conftest.py b/docs/tutorials/wiki2/src/models/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/models/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/models/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/tests/tests/conftest.py b/docs/tutorials/wiki2/src/tests/tests/conftest.py
index 1c8fb16d0..5ef28acd1 100644
--- a/docs/tutorials/wiki2/src/tests/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/tests/tests/conftest.py
@@ -4,7 +4,7 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
from webob.cookies import Cookie
@@ -130,37 +130,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/src/tests/tests/test_views.py b/docs/tutorials/wiki2/src/tests/tests/test_views.py
index 007184af8..e93b04b3c 100644
--- a/docs/tutorials/wiki2/src/tests/tests/test_views.py
+++ b/docs/tutorials/wiki2/src/tests/tests/test_views.py
@@ -1,9 +1,17 @@
+from pyramid.testing import DummySecurityPolicy
+
from tutorial import models
def makeUser(name, role):
return models.User(name=name, role=role)
+
+def setUser(config, user):
+ config.set_security_policy(
+ DummySecurityPolicy(identity=user)
+ )
+
def makePage(name, data, creator):
return models.Page(name=name, data=data, creator=creator)
@@ -12,7 +20,11 @@ class Test_view_wiki:
from tutorial.views.default import view_wiki
return view_wiki(request)
- def test_it(self, dummy_request):
+ def _addRoutes(self, config):
+ config.add_route('view_page', '/{pagename}')
+
+ def test_it(self, dummy_config, dummy_request):
+ self._addRoutes(dummy_config)
response = self._callFUT(dummy_request)
assert response.location == 'http://example.com/FrontPage'
@@ -25,13 +37,19 @@ class Test_view_page:
from tutorial.routes import PageResource
return PageResource(page)
- def test_it(self, dummy_request, dbsession):
+ def _addRoutes(self, config):
+ config.add_route('edit_page', '/{pagename}/edit_page')
+ config.add_route('add_page', '/add_page/{pagename}')
+ config.add_route('view_page', '/{pagename}')
+
+ def test_it(self, dummy_config, dummy_request, dbsession):
# add a page to the db
user = makeUser('foo', 'editor')
page = makePage('IDoExist', 'Hello CruelWorld IDoExist', user)
dbsession.add_all([page, user])
# create a request asking for the page we've created
+ self._addRoutes(dummy_config)
dummy_request.context = self._makeContext(page)
# call the view we're testing and check its behavior
@@ -56,18 +74,24 @@ class Test_add_page:
from tutorial.routes import NewPage
return NewPage(pagename)
- def test_get(self, dummy_request, dbsession):
- dummy_request.user = makeUser('foo', 'editor')
+ def _addRoutes(self, config):
+ config.add_route('add_page', '/add_page/{pagename}')
+ config.add_route('view_page', '/{pagename}')
+
+ def test_get(self, dummy_config, dummy_request, dbsession):
+ setUser(dummy_config, makeUser('foo', 'editor'))
+ self._addRoutes(dummy_config)
dummy_request.context = self._makeContext('AnotherPage')
info = self._callFUT(dummy_request)
assert info['pagedata'] == ''
assert info['save_url'] == 'http://example.com/add_page/AnotherPage'
- def test_submit_works(self, dummy_request, dbsession):
+ def test_submit_works(self, dummy_config, dummy_request, dbsession):
dummy_request.method = 'POST'
dummy_request.POST['body'] = 'Hello yo!'
dummy_request.context = self._makeContext('AnotherPage')
- dummy_request.user = makeUser('foo', 'editor')
+ setUser(dummy_config, makeUser('foo', 'editor'))
+ self._addRoutes(dummy_config)
self._callFUT(dummy_request)
page = (
dbsession.query(models.Page)
@@ -85,24 +109,30 @@ class Test_edit_page:
from tutorial.routes import PageResource
return PageResource(page)
- def test_get(self, dummy_request, dbsession):
+ def _addRoutes(self, config):
+ config.add_route('edit_page', '/{pagename}/edit_page')
+ config.add_route('view_page', '/{pagename}')
+
+ def test_get(self, dummy_config, dummy_request, dbsession):
user = makeUser('foo', 'editor')
page = makePage('abc', 'hello', user)
dbsession.add_all([page, user])
+ self._addRoutes(dummy_config)
dummy_request.context = self._makeContext(page)
info = self._callFUT(dummy_request)
assert info['pagename'] == 'abc'
assert info['save_url'] == 'http://example.com/abc/edit_page'
- def test_submit_works(self, dummy_request, dbsession):
+ def test_submit_works(self, dummy_config, dummy_request, dbsession):
user = makeUser('foo', 'editor')
page = makePage('abc', 'hello', user)
dbsession.add_all([page, user])
+ self._addRoutes(dummy_config)
dummy_request.method = 'POST'
dummy_request.POST['body'] = 'Hello yo!'
- dummy_request.user = user
+ setUser(dummy_config, user)
dummy_request.context = self._makeContext(page)
response = self._callFUT(dummy_request)
assert response.location == 'http://example.com/abc'
diff --git a/docs/tutorials/wiki2/src/tests/tutorial/security.py b/docs/tutorials/wiki2/src/tests/tutorial/security.py
index 4f79195ef..18f0bd4c7 100644
--- a/docs/tutorials/wiki2/src/tests/tutorial/security.py
+++ b/docs/tutorials/wiki2/src/tests/tutorial/security.py
@@ -59,5 +59,3 @@ def includeme(config):
config.set_default_csrf_options(require_csrf=True)
config.set_security_policy(MySecurityPolicy(settings['auth.secret']))
- config.add_request_method(
- lambda request: request.identity, 'user', property=True)
diff --git a/docs/tutorials/wiki2/src/tests/tutorial/templates/layout.jinja2 b/docs/tutorials/wiki2/src/tests/tutorial/templates/layout.jinja2
index 64a1db0c5..55f4a85dc 100644
--- a/docs/tutorials/wiki2/src/tests/tutorial/templates/layout.jinja2
+++ b/docs/tutorials/wiki2/src/tests/tutorial/templates/layout.jinja2
@@ -33,13 +33,13 @@
</div>
<div class="col-md-10">
<div class="content">
- {% if request.user is none %}
+ {% if not request.is_authenticated %}
<p class="pull-right">
<a href="{{ request.route_url('login') }}">Login</a>
</p>
{% else %}
<form class="pull-right" action="{{ request.route_url('logout') }}" method="post">
- {{request.user.name}}
+ {{request.identity.name}}
<input type="hidden" name="csrf_token" value="{{ get_csrf_token() }}">
<button class="btn btn-link" type="submit">Logout</button>
</form>
diff --git a/docs/tutorials/wiki2/src/tests/tutorial/views/auth.py b/docs/tutorials/wiki2/src/tests/tutorial/views/auth.py
index e1a564415..807ff3464 100644
--- a/docs/tutorials/wiki2/src/tests/tutorial/views/auth.py
+++ b/docs/tutorials/wiki2/src/tests/tutorial/views/auth.py
@@ -53,7 +53,7 @@ def logout(request):
@forbidden_view_config(renderer='tutorial:templates/403.jinja2')
def forbidden_view(exc, request):
- if request.user is None:
+ if not request.is_authenticated:
next_url = request.route_url('login', _query={'next': request.url})
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/tests/tutorial/views/default.py b/docs/tutorials/wiki2/src/tests/tutorial/views/default.py
index 214788357..4a2a66c84 100644
--- a/docs/tutorials/wiki2/src/tests/tutorial/views/default.py
+++ b/docs/tutorials/wiki2/src/tests/tutorial/views/default.py
@@ -56,7 +56,7 @@ def add_page(request):
if request.method == 'POST':
body = request.params['body']
page = models.Page(name=pagename, data=body)
- page.creator = request.user
+ page.creator = request.identity
request.dbsession.add(page)
next_url = request.route_url('view_page', pagename=pagename)
return HTTPSeeOther(location=next_url)
diff --git a/docs/tutorials/wiki2/src/views/tests/conftest.py b/docs/tutorials/wiki2/src/views/tests/conftest.py
index 2db65f887..4ac4c60a8 100644
--- a/docs/tutorials/wiki2/src/views/tests/conftest.py
+++ b/docs/tutorials/wiki2/src/views/tests/conftest.py
@@ -4,10 +4,9 @@ import alembic.command
import os
from pyramid.paster import get_appsettings
from pyramid.scripting import prepare
-from pyramid.testing import DummyRequest
+from pyramid.testing import DummyRequest, testConfig
import pytest
import transaction
-from webob.cookies import Cookie
import webtest
from tutorial import main
@@ -89,37 +88,45 @@ def app_request(app, tm, dbsession):
drawbacks in tests as it's harder to mock data and is heavier.
"""
- env = prepare(registry=app.registry)
- request = env['request']
- request.host = 'example.com'
+ with prepare(registry=app.registry) as env:
+ request = env['request']
+ request.host = 'example.com'
- # without this, request.dbsession will be joined to the same transaction
- # manager but it will be using a different sqlalchemy.orm.Session using
- # a separate database transaction
- request.dbsession = dbsession
- request.tm = tm
+ # without this, request.dbsession will be joined to the same transaction
+ # manager but it will be using a different sqlalchemy.orm.Session using
+ # a separate database transaction
+ request.dbsession = dbsession
+ request.tm = tm
- yield request
- env['closer']()
+ yield request
@pytest.fixture
-def dummy_request(app, tm, dbsession):
+def dummy_request(tm, dbsession):
"""
A lightweight dummy request.
- This request is ultra-lightweight and should be used only when the
- request itself is not a large focus in the call-stack.
-
- It is way easier to mock and control side-effects using this object.
+ This request is ultra-lightweight and should be used only when the request
+ itself is not a large focus in the call-stack. It is much easier to mock
+ and control side-effects using this object, however:
- It does not have request extensions applied.
- Threadlocals are not properly pushed.
"""
request = DummyRequest()
- request.registry = app.registry
request.host = 'example.com'
request.dbsession = dbsession
request.tm = tm
return request
+
+@pytest.fixture
+def dummy_config(dummy_request):
+ """
+ A dummy :class:`pyramid.config.Configurator` object. This allows for
+ mock configuration, including configuration for ``dummy_request``, as well
+ as pushing the appropriate threadlocals.
+
+ """
+ with testConfig(request=dummy_request) as config:
+ yield config
diff --git a/docs/tutorials/wiki2/tests.rst b/docs/tutorials/wiki2/tests.rst
index 1bf38d988..dce14cf9b 100644
--- a/docs/tutorials/wiki2/tests.rst
+++ b/docs/tutorials/wiki2/tests.rst
@@ -69,6 +69,9 @@ Per-test fixtures
- ``dummy_request`` - a :class:`pyramid.testing.DummyRequest` object that is very lightweight.
This is a great object to pass to view functions that have minimal side-effects as it'll be fast and simple.
+- ``dummy_config`` — a :class:`pyramid.config.Configurator` object used as configuration by ``dummy_request``.
+ Useful for mocking configuration like routes and security policies.
+
Modifying the fixtures
----------------------
@@ -109,8 +112,8 @@ Integration tests
=================
We can directly execute the view code, bypassing :app:`Pyramid` and testing just the code that we've written.
-These tests use dummy requests that we'll prepare appropriately to set the conditions each view expects.
-For example, setting ``request.user``, or adding some dummy data to the session.
+These tests use dummy requests that we'll prepare appropriately to set the conditions each view expects, such as adding dummy data to the session.
+We'll be using ``dummy_config`` to configure the necessary routes, as well as setting the security policy as :class:`pyramid.testing.DummySecurityPolicy` to mock ``dummy_request.identity``.
Update ``tests/test_views.py`` such that it appears as follows: