def request_context(self, environ): """ Create a new request context from a WSGI environ. The request context is used to push/pop the threadlocals required when processing the request. It also contains an initialized :class:`pyramid.interfaces.IRequest` instance using the registered :class:`pyramid.interfaces.IRequestFactory`. The context may be used as a context manager to control the threadlocal lifecycle: .. code-block:: python with router.request_context(environ) as request: ... Alternatively, the context may be used without the ``with`` statement by manually invoking its ``begin()`` and ``end()`` methods. .. code-block:: python ctx = router.request_context(environ) request = ctx.begin() try: ... finally: ctx.end() """ request = self.request_factory(environ) request.registry = self.registry request.invoke_subrequest = self.invoke_subrequest extensions = self.request_extensions if extensions is not None: apply_request_extensions(request, extensions=extensions) return RequestContext(request)
def test_delete_404(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.delete('/api/1/collections/3/cards/404', status=404)
def set_snapshot(xmin, snapshot_id): global current_xmin_snapshot_id if current_xmin_snapshot_id == (xmin, snapshot_id): return clear_snapshot() current_xmin_snapshot_id = (xmin, snapshot_id) while True: txn = transaction.begin() txn.doom() if snapshot_id is not None: txn.setExtendedInfo('snapshot_id', snapshot_id) session = app.registry[DBSESSION]() connection = session.connection() db_xmin = connection.execute( "SELECT txid_snapshot_xmin(txid_current_snapshot());").scalar() if db_xmin >= xmin: break transaction.abort() log.info('Waiting for xmin %r to reach %r', db_xmin, xmin) time.sleep(0.1) registry = app.registry request = app.request_factory.blank('/_indexing_pool') request.registry = registry request.datastore = 'database' apply_request_extensions(request) request.invoke_subrequest = app.invoke_subrequest request.root = app.root_factory(request) request._stats = {} manager.push({'request': request, 'registry': registry})
def pyramid_config(pyramid_request): """ Return a test Pyramid config (Configurator) object. The returned Configurator uses the dummy request from the pyramid_request fixture above. """ # Settings that will end up in pyramid_request.registry.settings. settings = { 'lti_server': 'http://TEST_LTI_SERVER.com', 'sqlalchemy.url': TEST_DATABASE_URL, 'client_origin': 'http://TEST_H_SERVER.is', 'via_url': 'http://TEST_VIA_SERVER.is', } with testing.testConfig(request=pyramid_request, settings=settings) as config: config.include('pyramid_services') config.include('lti.db') apply_request_extensions(pyramid_request) # auth_data_svc = mock.create_autospec(auth_data.AuthDataService, instance=True) # auth_data_svc.get_canvas_server.return_value = 'https://TEST_CANVAS_SERVER.com' # auth_data_svc.get_lti_secret.return_value = 'TEST_CLIENT_SECRET' # auth_data_svc.get_lti_token.return_value = 'TEST_OAUTH_ACCESS_TOKEN' # auth_data_svc.get_lti_refresh_token.return_value = 'TEST_OAUTH_REFRESH_TOKEN' # config.register_service(auth_data_svc, name='auth_data') yield config
def invoke_request(self, request, _use_tweens=True, _apply_extensions=False): registry = self.registry has_listeners = self.registry.has_listeners notify = self.registry.notify threadlocals = {'registry': registry, 'request': request} manager = self.threadlocal_manager manager.push(threadlocals) if _use_tweens: handle_request = self.handle_request else: handle_request = self.orig_handle_request try: try: extensions = self.request_extensions if _apply_extensions and extensions is not None: apply_request_extensions(request, extensions=extensions) response = handle_request(request) if request.response_callbacks: request._process_response_callbacks(response) has_listeners and notify(NewResponse(request, response)) return response finally: if request.finished_callbacks: request._process_finished_callbacks() finally: manager.pop()
def pyramid_config(self, pyramid_config, pyramid_request): pyramid_config.add_request_method(FeatureRequestProperty, name="feature", reify=True) apply_request_extensions(pyramid_request) return pyramid_config
def __init__(self, *args, **kwargs): super(PyramidWebTestRequest, self).__init__(*args, **kwargs) manager.push({'request': self, 'registry': self.registry}) self._base_pyramid_request = self._pyramid_app.request_factory( self.environ) self._base_pyramid_request.registry = self.registry apply_request_extensions(self)
def pyramid_config(self, pyramid_config, pyramid_request): from pyramid.request import apply_request_extensions pyramid_config.add_request_method(FeatureRequestProperty, name='feature', reify=True) apply_request_extensions(pyramid_request) return pyramid_config
def test_collection_get_404(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.get('/api/1/walls/404/collections', status=404)
def pyramid_config(pyramid_request): """ Return a test Pyramid config (Configurator) object. The returned Configurator uses the dummy request from the pyramid_request fixture above. """ with testing.testConfig(request=pyramid_request, settings=TEST_SETTINGS) as config: config.include("pyramid_jinja2") config.include("pyramid_services") config.include("pyramid_tm") config.include("lms.sentry") config.include("lms.models") config.include("lms.db") config.include("lms.routes") config.add_static_view(name="export", path="lms:static/export") config.add_static_view(name="static", path="lms:static") config.action(None, configure_jinja2_assets, args=(config, )) apply_request_extensions(pyramid_request) yield config
def test_log(self): # Logger logger = logging.getLogger(__name__) logger.level = logging.INFO stream = StringIO() stream_handler = logging.StreamHandler(stream) logger.addHandler(stream_handler) # Actual test request = testing.DummyRequest() apply_request_extensions(request) self.assertTrue(request.authenticated_userid, 'jane') obj = self._cut(request) # Patch logger obj.logger = logger obj.add('uid', 'darth', [ROLE_VIEWER], [ROLE_OWNER]) payload = obj.prepare() formatted = obj.format(payload) try: obj.log(formatted) stream.seek(0) output = stream.read() finally: logger.removeHandler(stream_handler) self.assertIn('"+": ["role:Viewer"]', output) self.assertIn('"-": ["role:Owner"]', output) self.assertIn('"jane"', output) # Make sure json can read this json_row = loads(output) self.assertIn('contexts', json_row)
def test_openapi_view() -> None: """Test registration a an openapi view.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(MINIMAL_DOCUMENT) document.seek(0) config.pyramid_openapi3_spec(document.name, route="/foo.yaml", route_name="foo_api_spec") config.add_route("foo", "/foo") view_func = lambda *arg: "bar" # noqa: E731 config.add_view(openapi=True, renderer="json", view=view_func, route_name="foo") request_interface = config.registry.queryUtility(IRouteRequest, name="foo") view = config.registry.adapters.registered( (IViewClassifier, request_interface, Interface), IView, name="") request = DummyRequest(config=config, content_type="text/html") apply_request_extensions(request) request.matched_route = DummyRoute(name="foo", pattern="/foo") context = None response = view(context, request) assert response.json == "bar"
def test_feature(self, feature_flags, pyramid_config, pyramid_request): includeme(pyramid_config) apply_request_extensions(pyramid_request) pyramid_request.feature("test_feature") feature_flags.flag_is_active.assert_called_once_with( pyramid_request, "test_feature")
def make_request(self, environ): request = self.request_factory(environ) request.registry = self.registry request.invoke_subrequest = self.invoke_subrequest extensions = self.request_extensions if extensions is not None: apply_request_extensions(request, extensions=extensions) return request
def test_get_json_appstruct_bad_payload(self): request = Request.blank('/', body=b'Hello world!') request.errors = Errors() request.registry = self.config.registry apply_request_extensions(request) view = self._cut(request) view.get_json_appstruct() self.assertEqual(len(request.errors), 1)
def test_get_json_appstruct_no_payload(self): request = testing.DummyRequest() request.errors = Errors() request.registry = self.config.registry apply_request_extensions(request) view = self._cut(request) view.get_json_appstruct() self.assertEqual(len(request.errors), 1)
def _fixture(self): from arche.api import Root request = testing.DummyRequest() apply_request_extensions(request) request.root = root = Root() self.config.begin(request) return {'closer': object, 'root': root, 'registry': self.config.registry, 'request': request}
def test_integration(self): from arche_celery.authentication import worker_auth worker_auth(self.config.registry) request = testing.DummyRequest() apply_request_extensions(request) request._celery_userid = 'hello' self.assertEqual(request.unauthenticated_userid, 'hello') self.assertEqual(request.authenticated_userid, 'hello')
def test_auth_methods(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.get("/api/1/auth/methods") self.assertIn('google', response.json_body)
def make_faux_request(self): """In the case we can't use real request object, make a new request from registry given to Celery.""" # Real request has been already committed in this point, # so create a faux request to satisfy the presence of dbsession et. al. registry = self.app.registry request = _make_request("/", registry) apply_request_extensions(request) return request
def dummy_request(root, registry, app): request = app.request_factory.blank('/dummy') request.root = root request.registry = registry request._stats = {} request.invoke_subrequest = app.invoke_subrequest apply_request_extensions(request) return request
def test_delete(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.delete('/api/1/walls/2/collections/3', status=200) self.assertEqual({"removed": 3}, response.json_body)
def test_get_404(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) response = app.get('/api/1/users/404', status=404) self.assertEqual(response.json_body.get('status', None), 'error')
def test_get(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) root, cred = self._fixture(request) response = app.get('/api/1/users/10', status=200, headers={'Authorization': cred.header()}) self.assertEqual(response.json_body, {'data': {'first_name': 'Jeff'}, 'rid': 10, 'type_name': 'User'})
def setUp(self): self.config = testing.setUp() self.config.include('arche.testing') self.config.include('voteit.debate.schemas') self.config.include('voteit.debate.models') self.request = testing.DummyRequest() apply_request_extensions(self.request) self.config.begin(self.request)
def test_header_parameters() -> None: """Test parameters in header are validated correctly.""" with testConfig() as config: config.include("pyramid_openapi3") with tempfile.NamedTemporaryFile() as document: document.write(b'openapi: "3.0.0"\n' b"info:\n" b' version: "1.0.0"\n' b" title: Foo API\n" b"paths:\n" b" /foo:\n" b" get:\n" b" parameters:\n" b" - name: foo\n" b" in: header\n" b" required: true\n" b" schema:\n" b" type: integer\n" b" responses:\n" b" 200:\n" b" description: A foo\n") document.seek(0) config.pyramid_openapi3_spec(document.name, route="/foo.yaml", route_name="foo_api_spec") config.add_route("foo", "/foo") view_func = lambda *arg: "foo" # noqa: E731 # pragma: no branch config.add_view(openapi=True, renderer="json", view=view_func, route_name="foo") request_interface = config.registry.queryUtility(IRouteRequest, name="foo") view = config.registry.adapters.registered( (IViewClassifier, request_interface, Interface), IView, name="") # Test validation fails request = DummyRequest(config=config, content_type="text/html") apply_request_extensions(request) request.matched_route = DummyRoute(name="foo", pattern="/foo") context = None with pytest.raises(RequestValidationError, match="Missing required parameter: foo"): response = view(context, request) # Test validation succeeds request = DummyRequest(config=config, headers={"foo": "1"}, content_type="text/html") apply_request_extensions(request) request.matched_route = DummyRoute(name="foo", pattern="/foo") context = None response = view(context, request) assert response.json == "foo"
def __init__(self, client_id): self.client_id = client_id self.terminated = False self.filter = mock.MagicMock() self.send = mock.MagicMock() # Each fake socket needs its own request, so can't use the # pyramid_request fixture. self.request = DummyRequest(db=mock.sentinel.db_session) apply_request_extensions(self.request)
def test_collection_post_bad_data(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.post('/api/1/walls/2/relations', params=dumps({'members': "Johan och ett par till"}), status=400)
def test_put_bad_data(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.put('/api/1/walls/2/relations/1', params=dumps({'members': 'Jeff & Stanley'}), status=400)
def pyramid_config(pyramid_settings, pyramid_request): """Pyramid configurator object.""" with testing.testConfig(request=pyramid_request, settings=pyramid_settings) as config: # Include pyramid_services so it's easy to set up fake services in tests config.include('pyramid_services') apply_request_extensions(pyramid_request) yield config
def _fixture(self): from arche.resources import User root = barebone_fixture(self.config) root['users']['jane'] = User(email = '*****@*****.**') request = testing.DummyRequest() apply_request_extensions(request) self.config.begin(request) request.root = root return root, request
def test_collection_options(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) headers = (('Access-Control-Request-Method', 'POST'), ('Origin', 'http://localhost')) app.options('/api/1/walls/2/collections', status=200, headers=headers)
def test_prepare_was_not_really_removed(self): request = testing.DummyRequest() apply_request_extensions(request) self.assertTrue(request.authenticated_userid, 'jane') obj = self._cut(request) # Removing and adding (which shouldn't happen...) should not generate an entry. obj.add('uid', 'darth', [ROLE_VIEWER], []) obj.add('uid', 'darth', [], [ROLE_VIEWER]) self.assertEqual(obj.prepare(), {})
def dummy_request(root, registry, app): from pyramid.request import apply_request_extensions request = app.request_factory.blank('/dummy') request.root = root request.registry = registry request._stats = {} request.invoke_subrequest = app.invoke_subrequest apply_request_extensions(request) return request
def test_collection_get(self): root = self._fixture() request = testing.DummyRequest() request.matchdict['rid'] = 2 apply_request_extensions(request) inst = self._cut(request, context=root) response = inst.collection_get() self.assertIsInstance(response, list) self.assertIn(root['wall']['collection'], response)
def test_collection_post_bad_data(self): wsgiapp = self.config.make_wsgi_app() app = TestApp(wsgiapp) request = testing.DummyRequest() apply_request_extensions(request) self._fixture(request) app.post('/api/1/walls/2/collections', params=dumps({'title': 123}), status=400)
def test_format(self): request = testing.DummyRequest() apply_request_extensions(request) self.assertTrue(request.authenticated_userid, 'jane') obj = self._cut(request) obj.add('uid', 'darth', ['Sith', 'Dark', ROLE_VIEWER], ['Puppies']) payload = obj.prepare() formatted = obj.format(payload) self.assertIn('{"+": ["Sith", "Dark", "role:Viewer"]', formatted)
def test_get(self): root = self._fixture() request = testing.DummyRequest() apply_request_extensions(request) request.matchdict['rid'] = 2 request.matchdict['subrid'] = 3 inst = self._cut(request, context=root) response = inst.get() self.assertIsInstance(response, Collection)
def prepare(request=None, registry=None): """ This function pushes data onto the Pyramid threadlocal stack (request and registry), making those objects 'current'. It returns a dictionary useful for bootstrapping a Pyramid application in a scripting environment. ``request`` is passed to the :app:`Pyramid` application root factory to compute the root. If ``request`` is None, a default will be constructed using the registry's :term:`Request Factory` via the :meth:`pyramid.interfaces.IRequestFactory.blank` method. If ``registry`` is not supplied, the last registry loaded from :attr:`pyramid.config.global_registries` will be used. If you have loaded more than one :app:`Pyramid` application in the current process, you may not want to use the last registry loaded, thus you can search the ``global_registries`` and supply the appropriate one based on your own criteria. The function returns a dictionary composed of ``root``, ``closer``, ``registry``, ``request`` and ``root_factory``. The ``root`` returned is the application's root resource object. The ``closer`` returned is a callable (accepting no arguments) that should be called when your scripting application is finished using the root. ``registry`` is the registry object passed or the last registry loaded into :attr:`pyramid.config.global_registries` if no registry is passed. ``request`` is the request object passed or the constructed request if no request is passed. ``root_factory`` is the root factory used to construct the root. """ if registry is None: registry = getattr(request, 'registry', global_registries.last) if registry is None: raise ConfigurationError('No valid Pyramid applications could be ' 'found, make sure one has been created ' 'before trying to activate it.') if request is None: request = _make_request('/', registry) # NB: even though _make_request might have already set registry on # request, we reset it in case someone has passed in their own # request. request.registry = registry threadlocals = {'registry':registry, 'request':request} threadlocal_manager.push(threadlocals) apply_request_extensions(request) def closer(): threadlocal_manager.pop() root_factory = registry.queryUtility(IRootFactory, default=DefaultRootFactory) root = root_factory(request) if getattr(request, 'context', None) is None: request.context = root return {'root':root, 'closer':closer, 'registry':registry, 'request':request, 'root_factory':root_factory}
def test_get_read_count(self): request = testing.DummyRequest() self.config.include('voteit.core.helpers') apply_request_extensions(request) obj = self._cut(testing.DummyModel(uid='hi'), request) obj.change('Dummy', 1, 'robin') self.assertEqual(obj.get_read_count('Dummy', 'robin'), 1) obj.change('Dummy', -2, 'robin') self.assertEqual(obj.get_read_count('Dummy', 'robin'), -1) obj.change('Dummy', +3, 'robin') self.assertEqual(obj.get_read_count('Dummy', 'robin'), 2)
def dummy_request(dbsession): from webob.multidict import MultiDict from pyramid.request import apply_request_extensions req = testing.DummyRequest(base_url="http://testscaffold.com", dbsession=dbsession) req.route_url = mock.Mock(return_value="/") req.POST = MultiDict() req.GET = MultiDict() req.params = MultiDict() req.session = mock.Mock() apply_request_extensions(req) return req
def _fixture(self): from arche.resources import Document root = barebone_fixture(self.config) root['source'] = source = Document() source['a'] = Document() source['a']['b'] = Document() root['target'] = Document() request = testing.DummyRequest() request.root = root apply_request_extensions(request) self.config.begin(request) return root, request
def test_add(self): request = testing.DummyRequest() apply_request_extensions(request) self.assertTrue(request.authenticated_userid, 'jane') obj = self._cut(request) obj.add('uid', 'darth', ['Sith', 'Dark', ROLE_VIEWER], ['Puppies']) expected = { 'uid': { 'darth': {'new': frozenset(['Dark', 'Sith', 'role:Viewer']), 'old': frozenset(['Puppies'])}, } } self.assertEqual(obj.entries, expected)
def test_render_result(self): poll = _setup_poll_fixture(self.config) poll.set_field_value('poll_plugin', 'schulze_pr') _add_votes(poll) poll.close_poll() plugin = poll.get_poll_plugin() request = testing.DummyRequest() request.root = find_root(poll) request.meeting = request.root['m'] apply_request_extensions(request) view = BaseView(poll, request) result = plugin.render_result(view) self.assertTrue('first proposal' in result) self.assertTrue('third proposal' in result)
def _fixture(self): self.config.include('arche.testing.catalog') self.config.include('voteit.core.models.catalog') self.config.include('voteit.core.testing_helpers.register_workflows') self.config.include('voteit.core.helpers') self.config.include('voteit.core.models.read_names') from voteit.core.models.meeting import Meeting request = testing.DummyRequest() root = barebone_fixture(self.config) request.root = root apply_request_extensions(request) self.config.begin(request) root['m'] = request.meeting = Meeting() return root['m'], request
def test_render_result(self): poll = self._fixture() _add_votes(poll) poll.poll_settings['winners'] = 2 poll.close_poll() plugin = poll.get_poll_plugin() request = testing.DummyRequest() request.root = find_root(poll) request.meeting = request.root['m'] apply_request_extensions(request) view = BaseView(poll, request) result = plugin.render_result(view) self.assertTrue('first proposal' in result) self.assertTrue('second proposal' in result)
def test_get_current_average_en(self): root = self._fixture() section = _fixture_section_responses(root) request = testing.DummyRequest() apply_request_extensions(request) request.root = root obj = self._cut(root["ruleset"], request) result = tuple(obj.get_current_average(section)) # part_1 self.assertEqual(result[0][:2], [5, 4]) # part_2 self.assertEqual(result[1][:2], [5, 5]) # part_3 self.assertEqual(result[2][:2], [5, 0])
def build_request(original, dict_obj): """ Transform a dict object into a ``pyramid.request.Request`` object. It sets a ``parent`` attribute on the resulting request assigned with the `original` request specified. :param original: the original request. :param dict_obj: a dict object with the sub-request specifications. """ api_prefix = '/%s' % original.upath_info.split('/')[1] path = dict_obj['path'] if not path.startswith(api_prefix): path = api_prefix + path path = path.encode('utf-8') method = dict_obj.get('method') or 'GET' headers = dict(original.headers) headers.update(**dict_obj.get('headers') or {}) # Body can have different length, do not use original header. headers.pop('Content-Length', None) payload = dict_obj.get('body') or '' # Payload is always a dict (from ``BatchRequestSchema.body``). # Send it as JSON for subrequests. if isinstance(payload, dict): headers['Content-Type'] = encode_header( 'application/json; charset=utf-8') payload = json.dumps(payload) if six.PY3: # pragma: no cover path = path.decode('latin-1') request = Request.blank(path=path, headers=headers, POST=payload, method=method) request.registry = original.registry apply_request_extensions(request) # This is used to distinguish subrequests from direct incoming requests. # See :func:`kinto.core.initialization.setup_logging()` request.parent = original return request
def test_get_current_average_sv(self): root = self._fixture() section = _fixture_section_responses(root) self.config.registry.settings["default_locale_name"] = "sv" request = testing.DummyRequest() self.assertEqual(request.locale_name, "sv") apply_request_extensions(request) request.root = root obj = self._cut(root["ruleset"], request) result = tuple(obj.get_current_average(section)) # part_1 self.assertEqual(result[0][:2], [17, 12]) # part_2 self.assertEqual(result[1][:2], [17, 14]) # part_3 self.assertEqual(result[2][:2], [17, 0])
def test_get_guarded_objects_catalog_result(self): from arche.resources import Document root = self._fixture() request = testing.DummyRequest() apply_request_extensions(request) request.root = root root['doc1'] = doc1 = Document() root['doc2'] = doc2 = Document() def _checker(*args): return root.catalog.query("type_name == 'Document'") obj = self._cut(_checker, catalog_result=True) self.assertEqual(set(obj.get_guarded_objects(request, root)), set([doc1, doc2])) self.assertIsInstance(obj.get_guarded_objects(request, root), collections.Iterable)
def invoke_subrequest(self, request, use_tweens=False): """Obtain a response object from the Pyramid application based on information in the ``request`` object provided. The ``request`` object must be an object that implements the Pyramid request interface (such as a :class:`pyramid.request.Request` instance). If ``use_tweens`` is ``True``, the request will be sent to the :term:`tween` in the tween stack closest to the request ingress. If ``use_tweens`` is ``False``, the request will be sent to the main router handler, and no tweens will be invoked. See the API for pyramid.request for complete documentation. """ registry = self.registry has_listeners = self.registry.has_listeners notify = self.registry.notify threadlocals = {'registry':registry, 'request':request} manager = self.threadlocal_manager manager.push(threadlocals) request.registry = registry request.invoke_subrequest = self.invoke_subrequest if use_tweens: handle_request = self.handle_request else: handle_request = self.orig_handle_request try: try: extensions = self.request_extensions if extensions is not None: apply_request_extensions(request, extensions=extensions) response = handle_request(request) if request.response_callbacks: request._process_response_callbacks(response) has_listeners and notify(NewResponse(request, response)) return response finally: if request.finished_callbacks: request._process_finished_callbacks() finally: manager.pop()
def setUp(self): import tempfile import os.path self.tmpdir = tempfile.mkdtemp() dbpath = os.path.join( self.tmpdir, 'test.db') uri = 'file://' + dbpath settings = {'zodbconn.uri': uri, 'substanced.secret': 'sosecret', 'substanced.initial_login': '******', 'substanced.initial_password': '******', 'pyramid.includes': [ 'pyramid_tm', 'substanced', 'dace', ]} app = main({}, **settings) self.db = app.registry._zodb_databases[''] self.request = request = DummyRequest() self.request.test = True self.config = testing.setUp(registry=app.registry, request=request) # set extensions (add_request_method, so the request.user works) extensions = app.registry.queryUtility(IRequestExtensions) if extensions is not None: if getattr(request, '_set_extensions', None) is not None: # pyramid 1.5.7 request._set_extensions(extensions) else: from pyramid.request import apply_request_extensions apply_request_extensions(request, extensions=extensions) self.registry = self.config.registry self.app = root_factory(request) request.root = request.context = self.app # request.user execute substanced.sdi.user which get request.context to find objectmap self.users = self.app['principals']['users'] self.app['principals'].add_user('alice', password='******', email='*****@*****.**') self.app['principals'].add_user('bob', password='******', email='*****@*****.**') login('admin') # request.user is the admin user, but if you do later login('system'), you will still have admin in request.user #request.user = self.users['admin'] self.def_container = self.app['process_definition_container']
def init_request_methods(request): """ Request methods addded via config.add_request_method isn't enalbed by default during testing. This method will add them. DEPRECATED b/c method. Use: pyramid.request.apply_request_extensions It was introduced in Pyramid 1.6 and does the same thing """ try: from pyramid.request import apply_request_extensions apply_request_extensions(request) except ImportError: #Prior to Pyramid 1.6 extensions = request.registry.queryUtility(IRequestExtensions) if extensions is not None: request._set_extensions(extensions)