You can add the property of request with the directive add_request_method of pyramid. (In the past, there was a directive called add_request_property, but it became deprecated in haste)
document: http://docs.pylonsproject.org/projects/pyramid/en/latest/api/config.html#pyramid.config.Configurator.add_request_method
There are two options to keep in mind:
--reify --Add an attribute to request. The added attributes are cached --property --Add an attribute to request. The added attribute is calculated each time
If nothing is added, it will be added as a method. (Also, if verify = True, it is automatically added as property)
## configuration
def includeme(config):
## request.get_foo()Can be called as
config.add_request_method(get_foo, "get_foo")
## request.Can be accessed as foo
config.add_request_method(get_foo2, "foo", reify=True)
config.add_request_method(get_foo2, "foo", property=True)
test. If it's a unit test, you can use mock for text. Somehow it can be done by using dummy. A story about what to do during an integration test.
Let's look at the pyramid code. The answer is in pyramid / router.py. Roughly speaking, we can see the following.
--add_request_method stores an interface called IRequestExtensions in the key --Set with pyramid.request.Request._set_extensions ()
An example of how to write an integration test with reference to the above This time, set request.foo. Just check if you can get it with request.foo.
# -*- coding:utf-8 -*-
import unittest
## definition
foo = object()
def get_foo(request):
return foo
def includeme(config):
config.add_request_method(get_foo, "foo", reify=True)
## test
class Tests(unittest.TestCase):
def _makeOne(self, config, path="/"):
from pyramid.request import Request
from pyramid.interfaces import IRequestExtensions
request = Request.blank(path)
extensions = config.registry.getUtility(IRequestExtensions)
request.registry = config.registry
request._set_extensions(extensions)
return request
def test_it(self):
from pyramid.testing import testConfig
with testConfig() as config:
config.include(includeme)
### request time
request = self._makeOne(config, path="/")
self.assertEqual(request.foo, foo)
Recommended Posts