def test_async_depth(self):
     resource = DummyResource("root", None)
     resource.add_child("cat", DummyResource)
     out = self.loop.run_until_complete(spawn_greenlet(traverse, resource, ["cat"]))
     out["context"].add_child("dog", DummyResource)
     out = self.loop.run_until_complete(spawn_greenlet(traverse, resource, ["cat", "dog"]))
     self.assertListEqual(list(out["traversed"]), ["cat", "dog"])
Beispiel #2
0
 def test_async_depth(self):
     resource = DummyResource('root', None)
     resource.add_child('cat', DummyResource)
     out = self.loop.run_until_complete(
         spawn_greenlet(traverse, resource, ['cat']), )
     out['context'].add_child('dog', DummyResource)
     out = self.loop.run_until_complete(
         spawn_greenlet(traverse, resource, ['cat', 'dog']), )
     self.assertListEqual(list(out['traversed']), ['cat', 'dog'])
Beispiel #3
0
 def test_async_depth(self):
     with testing.testConfig() as config:
         config.add_traverser(AsyncioTraverser)
         resource = DummyResource('root', None)
         resource.add_child('cat', DummyResource)
         out = self.loop.run_until_complete(
             spawn_greenlet(traverse, resource, ['cat']),
         )
         out['context'].add_child('dog', DummyResource)
         out = self.loop.run_until_complete(
             spawn_greenlet(traverse, resource, ['cat', 'dog']),
         )
         self.assertListEqual(list(out['traversed']), ['cat', 'dog'])
Beispiel #4
0
 def test_wrapper_in_coroutine(self, wrapped_policy, web_request):
     loop = asyncio.get_event_loop()
     loop.run_until_complete(spawn_greenlet(
         synchronize(self.yield_from_authn_policy_methods),
         wrapped_policy,
         web_request,
     ))
Beispiel #5
0
 def test_sync_tween_below(self):
     tweens = self._make_tweens()
     tweens.add_implicit('sync', self._dummy_tween_factory)
     tweens.add_implicit('async', self._async_tween_factory)
     chain = tweens(None, None)
     out = self.loop.run_until_complete(spawn_greenlet(chain, None))
     self.assertEqual(out, 12)
Beispiel #6
0
    def handle_request(self, message, payload):
        """ Patched from aiohttp. """
        now = time.time()

        if self.readpayload:
            wsgiinput = io.BytesIO()
            wsgiinput.write((yield from payload.read()))
            wsgiinput.seek(0)
            payload = wsgiinput

        environ = self.create_wsgi_environ(message, payload)
        # add a reference to this for switching protocols
        environ['async.protocol'] = self

        response = self.create_wsgi_response(message)

        riter = yield from spawn_greenlet(self.wsgi, environ,
                                          response.start_response)

        resp = response.response
        try:
            for item in riter:
                if isinstance(item, asyncio.Future):
                    item = yield from item
                yield from resp.write(item)

            yield from resp.write_eof()
        finally:
            if hasattr(riter, 'close'):
                riter.close()

        if resp.keep_alive():
            self.keep_alive(True)

        self.log_access(message, environ, response.response, time.time() - now)
Beispiel #7
0
    def test_result_chain(self):
        from aiopyramid.helpers import spawn_greenlet
        from aiopyramid.helpers import run_in_greenlet

        @asyncio.coroutine
        def _sample(pass_back):
            return pass_back

        @asyncio.coroutine
        def _chain(pass_back):
            out = yield from _sample(pass_back)
            self.assertEqual(out, pass_back)
            return out - 1

        def _greenlet():
            this = greenlet.getcurrent()
            future = asyncio.Future()
            message = 12
            sub_task = asyncio.async(run_in_greenlet(
                this,
                future,
                _chain,
                message,
            ))
            this.parent.switch(sub_task)
            self.assertEqual(future.result(), message - 1)
            return message + 1

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_greenlet),
        )
        self.assertEqual(13, out)
Beispiel #8
0
 def test_sync_tween_below(self):
     tweens = self._make_tweens()
     tweens.add_implicit('sync', self._dummy_tween_factory)
     tweens.add_implicit('async', self._async_tween_factory)
     chain = tweens(None, None)
     out = self.loop.run_until_complete(spawn_greenlet(chain, None))
     self.assertEqual(out, 12)
Beispiel #9
0
 def test_wrapper_in_sync(self, wrapped_policy, web_request):
     loop = asyncio.get_event_loop()
     loop.run_until_complete(spawn_greenlet(
         self.call_authn_policy_methods,
         wrapped_policy,
         web_request,
     ))
Beispiel #10
0
 def test_async_view_name(self):
     resource = DummyResource('root', None)
     resource.add_child('cat', DummyResource)
     out = self.loop.run_until_complete(
         spawn_greenlet(traverse, resource, ['cat', 'mouse']), )
     self.assertListEqual(list(out['traversed']), ['cat'])
     self.assertEqual(out['view_name'], 'mouse')
Beispiel #11
0
 def handle_request(self, request):
     # Check for body size overflow.
     if (request.content_length is not None
             and request.content_length > self._max_request_body_size):
         raise HTTPRequestEntityTooLarge()
     # Buffer the body.
     content_length = 0
     with SpooledTemporaryFile(max_size=self._inbuf_overflow) as body:
         while True:
             block = yield from request.content.readany()
             if not block:
                 break
             content_length += len(block)
             if content_length > self._max_request_body_size:
                 raise HTTPRequestEntityTooLarge()
             body.write(block)
         body.seek(0)
         # Get the environ.
         environ = self._get_environ(request, body, content_length)
         environ['async.writer'] = request.writer
         environ['async.protocol'] = request.protocol
         status, reason, headers, body = yield from spawn_greenlet(
             _run_application,
             self._application,
             environ,
         )
         # All done!
         return Response(
             status=status,
             reason=reason,
             headers=headers,
             body=body,
         )
Beispiel #12
0
 def test_wrapper_in_coroutine(self, wrapped_policy, web_request):
     loop = asyncio.get_event_loop()
     loop.run_until_complete(
         spawn_greenlet(
             synchronize(self.yield_from_authn_policy_methods),
             wrapped_policy,
             web_request,
         ))
Beispiel #13
0
 def test_async_traversed_length(self):
     with testing.testConfig() as config:
         config.add_traverser(AsyncioTraverser)
         resource = DummyResource('root', None)
         resource.add_child('cat', DummyResource)
         out = self.loop.run_until_complete(
             spawn_greenlet(traverse, resource, ['cat']), )
         self.assertEqual(len(out['traversed']), 1)
Beispiel #14
0
 def test_wrapper_in_sync(self, wrapped_policy, web_request):
     loop = asyncio.get_event_loop()
     loop.run_until_complete(
         spawn_greenlet(
             self.call_authn_policy_methods,
             wrapped_policy,
             web_request,
         ))
Beispiel #15
0
 def test_async_root(self):
     with testing.testConfig() as config:
         config.add_traverser(AsyncioTraverser)
         resource = DummyResource('root', None)
         resource.add_child('cat', DummyResource)
         out = self.loop.run_until_complete(
             spawn_greenlet(traverse, resource, ['']), )
         self.assertTrue(out.get('root') == out.get('context'))
Beispiel #16
0
    def test_return_direct_result(self):
        from aiopyramid.helpers import spawn_greenlet

        def _return_4():
            return 4

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_return_4), )
        self.assertEqual(out, 4)
Beispiel #17
0
 def test_async_root(self):
     with testing.testConfig() as config:
         config.add_traverser(AsyncioTraverser)
         resource = DummyResource('root', None)
         resource.add_child('cat', DummyResource)
         out = self.loop.run_until_complete(
             spawn_greenlet(traverse, resource, ['']),
         )
         self.assertTrue(out.get('root') == out.get('context'))
Beispiel #18
0
    def test_return_direct_result(self):
        from aiopyramid.helpers import spawn_greenlet

        def _return_4():
            return 4

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_return_4),
        )
        self.assertEqual(out, 4)
Beispiel #19
0
 def test_example_tween(self):
     from aiopyramid.tweens import coroutine_logger_tween_factory
     out = self.loop.run_until_complete(
         spawn_greenlet(
             coroutine_logger_tween_factory(
                 lambda x: x,
                 None,
             ),
             None,
         ))
     self.assertEqual(None, out)
Beispiel #20
0
    def test_switch_direct_result(self):
        from aiopyramid.helpers import spawn_greenlet

        def _switch_4_return_5():
            this = greenlet.getcurrent()
            this.parent.switch(4)
            return 5

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_switch_4_return_5), )
        self.assertEqual(out, 4)
Beispiel #21
0
 def test_example_tween(self):
     from aiopyramid.tweens import coroutine_logger_tween_factory
     out = self.loop.run_until_complete(
         spawn_greenlet(
             coroutine_logger_tween_factory(
                 lambda x: x,
                 None,
             ),
             None,
         )
     )
     self.assertEqual(None, out)
Beispiel #22
0
    def test_switch_direct_result(self):
        from aiopyramid.helpers import spawn_greenlet

        def _switch_4_return_5():
            this = greenlet.getcurrent()
            this.parent.switch(4)
            return 5

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_switch_4_return_5),
        )
        self.assertEqual(out, 4)
Beispiel #23
0
    def test_scope_error(self):
        from aiopyramid.exceptions import ScopeError
        from aiopyramid.helpers import synchronize, spawn_greenlet

        synced = synchronize(self._sample)
        self.assertRaises(ScopeError, synced, 'val')

        five = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(synced, 5), )
        self.assertEqual(five, 5)

        synced = synchronize(self._sample, strict=False)
        self.assertTrue(asyncio.iscoroutine(synced('val')))
Beispiel #24
0
    def test_as_decorator(self):
        from aiopyramid.helpers import synchronize, spawn_greenlet
        from aiopyramid.exceptions import ScopeError

        @synchronize
        @asyncio.coroutine
        def _synced(pass_back):
            yield
            return pass_back

        self.assertRaises(ScopeError, _synced, 'val')
        twelve = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_synced, 12), )
        self.assertEqual(twelve, 12)
Beispiel #25
0
    def test_scope_error(self):
        from aiopyramid.exceptions import ScopeError
        from aiopyramid.helpers import synchronize, spawn_greenlet

        synced = synchronize(self._sample)
        self.assertRaises(ScopeError, synced, 'val')

        five = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(synced, 5),
        )
        self.assertEqual(five, 5)

        synced = synchronize(self._sample, strict=False)
        self.assertTrue(asyncio.iscoroutine(synced('val')))
Beispiel #26
0
    def test_as_decorator(self):
        from aiopyramid.helpers import synchronize, spawn_greenlet
        from aiopyramid.exceptions import ScopeError

        @synchronize
        @asyncio.coroutine
        def _synced(pass_back):
            yield
            return pass_back

        self.assertRaises(ScopeError, _synced, 'val')
        twelve = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_synced, 12),
        )
        self.assertEqual(twelve, 12)
Beispiel #27
0
    def test_wait_on_future(self):
        from aiopyramid.helpers import spawn_greenlet

        future = asyncio.Future()

        def _switch_future():
            this = greenlet.getcurrent()
            this.parent.switch(future)
            return 5  # This should never get returned

        # the result is already set, but
        # spawn_greenlet will still need to yield from it
        future.set_result(4)
        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_switch_future), )
        self.assertEqual(out, 4)
Beispiel #28
0
    def test_wait_on_future(self):
        from aiopyramid.helpers import spawn_greenlet

        future = asyncio.Future()

        def _switch_future():
            this = greenlet.getcurrent()
            this.parent.switch(future)
            return 5  # This should never get returned

        # the result is already set, but
        # spawn_greenlet will still need to yield from it
        future.set_result(4)
        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_switch_future),
        )
        self.assertEqual(out, 4)
Beispiel #29
0
    def test_exception(self):
        from aiopyramid.helpers import spawn_greenlet
        from aiopyramid.helpers import run_in_greenlet

        @asyncio.coroutine
        def _sample():
            raise KeyError

        def _greenlet():
            this = greenlet.getcurrent()
            future = asyncio.Future()
            sub_task = asyncio.ensure_future(
                run_in_greenlet(this, future, _sample), )
            this.parent.switch(sub_task)
            self.assertRaises(KeyError, future.result)

        asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_greenlet), )
Beispiel #30
0
    def handle_request(self, message, payload):
        """ Patched from aiohttp. """
        now = time.time()

        if self.readpayload:
            wsgiinput = io.BytesIO()
            wsgiinput.write((yield from payload.read()))
            wsgiinput.seek(0)
            payload = wsgiinput
        else:
            # allow read to be called from a synchronous context
            payload.read = synchronize(payload.read)
            payload.read = spawn_greenlet_on_scope_error(payload.read)

        environ = self.create_wsgi_environ(message, payload)
        # add a reference to this for switching protocols
        environ['async.protocol'] = self

        response = self.create_wsgi_response(message)

        riter = yield from spawn_greenlet(
            self.wsgi,
            environ,
            response.start_response
        )

        resp = response.response
        try:
            for item in riter:
                if isinstance(item, asyncio.Future):
                    item = yield from item
                yield from resp.write(item)

            yield from resp.write_eof()
        finally:
            if hasattr(riter, 'close'):
                riter.close()

        if resp.keep_alive():
            self.keep_alive(True)

        self.log_access(
            message, environ, response.response, time.time() - now)
Beispiel #31
0
    def test_exception(self):
        from aiopyramid.helpers import spawn_greenlet
        from aiopyramid.helpers import run_in_greenlet

        @asyncio.coroutine
        def _sample():
            raise KeyError

        def _greenlet():
            this = greenlet.getcurrent()
            future = asyncio.Future()
            sub_task = asyncio.async(
                run_in_greenlet(this, future, _sample),
            )
            this.parent.switch(sub_task)
            self.assertRaises(KeyError, future.result)

        asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_greenlet),
        )
Beispiel #32
0
    def test_result(self):
        from aiopyramid.helpers import spawn_greenlet
        from aiopyramid.helpers import run_in_greenlet

        @asyncio.coroutine
        def _sample(pass_back):
            return pass_back

        def _greenlet():
            this = greenlet.getcurrent()
            future = asyncio.Future()
            message = 12
            sub_task = asyncio.ensure_future(
                run_in_greenlet(this, future, _sample, message), )
            this.parent.switch(sub_task)
            self.assertEqual(future.result(), message)
            return message + 1

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_greenlet), )
        self.assertEqual(13, out)
Beispiel #33
0
    def handle_request(self, request):
        # Check for body size overflow.
        if (
                request.content_length is not None and
                request.content_length > self._max_request_body_size):
            raise HTTPRequestEntityTooLarge()
        # Buffer the body.
        body_buffer = ReadBuffer(
            self._inbuf_overflow,
            self._max_request_body_size,
            self._loop,
            self._executor)

        try:
            while True:
                block = yield from request.content.readany()
                if not block:
                    break
                yield from body_buffer.write(block)
            # Seek the body.
            body, content_length = yield from body_buffer.get_body()
            # Get the environ.
            environ = self._get_environ(request, body, content_length)
            environ['async.writer'] = request.writer
            environ['async.protocol'] = request.protocol
            status, reason, headers, body = yield from spawn_greenlet(
                _run_application,
                self._application,
                environ,
            )
            # All done!
            return Response(
                status=status,
                reason=reason,
                headers=headers,
                body=body,
            )

        finally:
            yield from body_buffer.close()
Beispiel #34
0
    def test_result(self):
        from aiopyramid.helpers import spawn_greenlet
        from aiopyramid.helpers import run_in_greenlet

        @asyncio.coroutine
        def _sample(pass_back):
            return pass_back

        def _greenlet():
            this = greenlet.getcurrent()
            future = asyncio.Future()
            message = 12
            sub_task = asyncio.ensure_future(
                run_in_greenlet(this, future, _sample, message),
            )
            this.parent.switch(sub_task)
            self.assertEqual(future.result(), message)
            return message + 1

        out = asyncio.get_event_loop().run_until_complete(
            spawn_greenlet(_greenlet),
        )
        self.assertEqual(13, out)
Beispiel #35
0
    def handle_request(self, request):
        # Check for body size overflow.
        if (request.content_length is not None
                and request.content_length > self._max_request_body_size):
            raise HTTPRequestEntityTooLarge()
        # Buffer the body.
        body_buffer = ReadBuffer(self._inbuf_overflow,
                                 self._max_request_body_size, self._loop,
                                 self._executor)

        try:
            while True:
                block = yield from request.content.readany()
                if not block:
                    break
                yield from body_buffer.write(block)
            # Seek the body.
            body, content_length = yield from body_buffer.get_body()
            # Get the environ.
            environ = self._get_environ(request, body, content_length)
            environ['async.writer'] = request.writer
            environ['async.protocol'] = request.protocol
            status, reason, headers, body = yield from spawn_greenlet(
                _run_application,
                self._application,
                environ,
            )
            # All done!
            return Response(
                status=status,
                reason=reason,
                headers=headers,
                body=body,
            )

        finally:
            yield from body_buffer.close()
Beispiel #36
0
 def test_async_root(self):
     resource = DummyResource('root', None)
     resource.add_child('cat', DummyResource)
     out = self.loop.run_until_complete(
         spawn_greenlet(traverse, resource, ['']), )
     self.assertTrue(out.get('root') == out.get('context'))
Beispiel #37
0
 def test_async_tween(self):
     out = self.loop.run_until_complete(
         spawn_greenlet(self._async_tween_factory(None, None), None),
     )
     self.assertEqual(out, 12)
Beispiel #38
0
 def test_async_tween(self):
     out = self.loop.run_until_complete(
         spawn_greenlet(self._async_tween_factory(None, None), None), )
     self.assertEqual(out, 12)
 def test_async_traversed_length(self):
     resource = DummyResource("root", None)
     resource.add_child("cat", DummyResource)
     out = self.loop.run_until_complete(spawn_greenlet(traverse, resource, ["cat"]))
     self.assertEqual(len(out["traversed"]), 1)
Beispiel #40
0
 def test_async_traversed_length(self):
     resource = DummyResource('root', None)
     resource.add_child('cat', DummyResource)
     out = self.loop.run_until_complete(
         spawn_greenlet(traverse, resource, ['cat']), )
     self.assertEqual(len(out['traversed']), 1)
 def test_async_root(self):
     resource = DummyResource("root", None)
     resource.add_child("cat", DummyResource)
     out = self.loop.run_until_complete(spawn_greenlet(traverse, resource, [""]))
     self.assertTrue(out.get("root") == out.get("context"))
 def test_async_view_name(self):
     resource = DummyResource("root", None)
     resource.add_child("cat", DummyResource)
     out = self.loop.run_until_complete(spawn_greenlet(traverse, resource, ["cat", "mouse"]))
     self.assertListEqual(list(out["traversed"]), ["cat"])
     self.assertEqual(out["view_name"], "mouse")