Ejemplo n.º 1
0
    def get_app(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.finish('Hello world')

            def post(self):
                self.finish('Hello world')

        class LargeHandler(RequestHandler):
            def get(self):
                # 512KB should be bigger than the socket buffers so it will
                # be written out in chunks.
                self.write(''.join(chr(i % 256) * 1024 for i in range(512)))

        class FinishOnCloseHandler(RequestHandler):
            @asynchronous
            def get(self):
                self.flush()

            def on_connection_close(self):
                # This is not very realistic, but finishing the request
                # from the close callback has the right timing to mimic
                # some errors seen in the wild.
                self.finish('closed')

        return Application([('/', HelloHandler), ('/large', LargeHandler),
                            ('/finish_on_close', FinishOnCloseHandler)])
Ejemplo n.º 2
0
 def get_app(self):
     self.close_future = Future()
     return Application([
         ('/echo', EchoHandler,
          dict(close_future=self.close_future,
               compression_options=self.get_server_compression_options())),
     ])
Ejemplo n.º 3
0
    def get_app(self):
        class BufferedHandler(RequestHandler):
            def put(self):
                self.write(str(len(self.request.body)))

        @stream_request_body
        class StreamingHandler(RequestHandler):
            def initialize(self):
                self.bytes_read = 0

            def prepare(self):
                if 'expected_size' in self.request.arguments:
                    self.request.connection.set_max_body_size(
                        int(self.get_argument('expected_size')))
                if 'body_timeout' in self.request.arguments:
                    self.request.connection.set_body_timeout(
                        float(self.get_argument('body_timeout')))

            def data_received(self, data):
                self.bytes_read += len(data)

            def put(self):
                self.write(str(self.bytes_read))

        return Application([('/buffered', BufferedHandler),
                            ('/streaming', StreamingHandler)])
Ejemplo n.º 4
0
    def test_missing_key(self):
        """A missing SSL key should cause an immediate exception."""

        application = Application()
        module_dir = os.path.dirname(__file__)
        existing_certificate = os.path.join(module_dir, 'test.crt')
        existing_key = os.path.join(module_dir, 'test.key')

        self.assertRaises((ValueError, IOError),
                          HTTPServer,
                          application,
                          ssl_options={
                              "certfile": "/__mising__.crt",
                          })
        self.assertRaises((ValueError, IOError),
                          HTTPServer,
                          application,
                          ssl_options={
                              "certfile": existing_certificate,
                              "keyfile": "/__missing__.key"
                          })

        # This actually works because both files exist
        HTTPServer(application,
                   ssl_options={
                       "certfile": existing_certificate,
                       "keyfile": existing_key,
                   })
Ejemplo n.º 5
0
 def get_app(self):
     self.close_future = Future()
     return Application([
         ('/echo', EchoHandler, dict(close_future=self.close_future)),
         ('/non_ws', NonWebSocketHandler),
         ('/header', HeaderHandler, dict(close_future=self.close_future)),
         ('/header_echo', HeaderEchoHandler,
          dict(close_future=self.close_future)),
         ('/close_reason', CloseReasonHandler,
          dict(close_future=self.close_future)),
         ('/error_in_on_message', ErrorInOnMessageHandler,
          dict(close_future=self.close_future)),
         ('/async_prepare', AsyncPrepareHandler,
          dict(close_future=self.close_future)),
         ('/path_args/(.*)', PathArgsHandler,
          dict(close_future=self.close_future)),
         ('/coroutine', CoroutineOnMessageHandler,
          dict(close_future=self.close_future)),
         ('/render', RenderMessageHandler,
          dict(close_future=self.close_future)),
     ],
                        template_loader=DictLoader({
                            'message.html':
                            '<b>{{ message }}</b>',
                        }))
Ejemplo n.º 6
0
 def test_missing_arguments(self):
     application = Application()
     self.assertRaises(KeyError,
                       HTTPServer,
                       application,
                       ssl_options={
                           "keyfile": "/__missing__.crt",
                       })
Ejemplo n.º 7
0
    def get_app(self):
        class ChunkedWithContentLength(RequestHandler):
            def get(self):
                # Add an invalid Transfer-Encoding to the response
                self.set_header('Transfer-Encoding', 'chunked')
                self.write("Hello world")

        return Application([('/chunkwithcl', ChunkedWithContentLength)])
Ejemplo n.º 8
0
    def start_tornado_server(self):
        class HelloHandler(RequestHandler):
            def get(self):
                self.write("Hello from salt.ext.tornado!")

        app = Application([('/', HelloHandler)], log_function=lambda x: None)
        server = HTTPServer(app, io_loop=self.io_loop)
        sock, self.tornado_port = bind_unused_port()
        server.add_sockets([sock])
Ejemplo n.º 9
0
    def get_app(self):
        class PingHandler(TestWebSocketHandler):
            def on_ping(self, data):
                self.write_message("got ping")

        self.close_future = Future()
        return Application([
            ('/', PingHandler, dict(close_future=self.close_future)),
        ])
Ejemplo n.º 10
0
    def get_app(self):
        class SmallBody(RequestHandler):
            def get(self):
                self.write("a" * 1024 * 64)

        class LargeBody(RequestHandler):
            def get(self):
                self.write("a" * 1024 * 100)

        return Application([('/small', SmallBody), ('/large', LargeBody)])
Ejemplo n.º 11
0
    def get_app(self):
        return Application(
            [
                # test endpoints
                ('/openid/client/login', OpenIdClientLoginHandler,
                 dict(test=self)),
                ('/oauth10/client/login', OAuth1ClientLoginHandler,
                 dict(test=self, version='1.0')),
                ('/oauth10/client/request_params',
                 OAuth1ClientRequestParametersHandler, dict(version='1.0')),
                ('/oauth10a/client/login', OAuth1ClientLoginHandler,
                 dict(test=self, version='1.0a')),
                ('/oauth10a/client/login_coroutine',
                 OAuth1ClientLoginCoroutineHandler,
                 dict(test=self, version='1.0a')),
                ('/oauth10a/client/request_params',
                 OAuth1ClientRequestParametersHandler, dict(version='1.0a')),
                ('/oauth2/client/login', OAuth2ClientLoginHandler,
                 dict(test=self)),
                ('/facebook/client/login', FacebookClientLoginHandler,
                 dict(test=self)),
                ('/twitter/client/login', TwitterClientLoginHandler,
                 dict(test=self)),
                ('/twitter/client/login_gen_engine',
                 TwitterClientLoginGenEngineHandler, dict(test=self)),
                ('/twitter/client/login_gen_coroutine',
                 TwitterClientLoginGenCoroutineHandler, dict(test=self)),
                ('/twitter/client/show_user', TwitterClientShowUserHandler,
                 dict(test=self)),
                ('/twitter/client/show_user_future',
                 TwitterClientShowUserFutureHandler, dict(test=self)),

                # simulated servers
                ('/openid/server/authenticate', OpenIdServerAuthenticateHandler
                 ),
                ('/oauth1/server/request_token',
                 OAuth1ServerRequestTokenHandler),
                ('/oauth1/server/access_token',
                 OAuth1ServerAccessTokenHandler),
                ('/facebook/server/access_token',
                 FacebookServerAccessTokenHandler),
                ('/facebook/server/me', FacebookServerMeHandler),
                ('/twitter/server/access_token',
                 TwitterServerAccessTokenHandler),
                (r'/twitter/api/users/show/(.*)\.json',
                 TwitterServerShowUserHandler),
                (r'/twitter/api/account/verify_credentials\.json',
                 TwitterServerVerifyCredentialsHandler),
            ],
            http_client=self.http_client,
            twitter_consumer_key='test_twitter_consumer_key',
            twitter_consumer_secret='test_twitter_consumer_secret',
            facebook_api_key='test_facebook_api_key',
            facebook_secret='test_facebook_secret')
Ejemplo n.º 12
0
    def get_app(self):
        app = Application()

        def request_callable(request):
            request.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
            request.finish()

        app.add_handlers(
            ".*", [(HostMatches("www.example.com"), [
                (PathMatches("/first_handler"),
                 "tornado.test.routing_test.SecondHandler", {},
                 "second_handler")
            ]),
                   Rule(PathMatches("/first_handler"),
                        FirstHandler,
                        name="first_handler"),
                   Rule(PathMatches("/request_callable"), request_callable),
                   ("/connection_delegate", ConnectionDelegate())])

        return app
Ejemplo n.º 13
0
 def setUp(self):
     super(UnixSocketTest, self).setUp()
     self.tmpdir = tempfile.mkdtemp()
     self.sockfile = os.path.join(self.tmpdir, "test.sock")
     sock = netutil.bind_unix_socket(self.sockfile)
     app = Application([("/hello", HelloWorldRequestHandler)])
     self.server = HTTPServer(app, io_loop=self.io_loop)
     self.server.add_socket(sock)
     self.stream = IOStream(socket.socket(socket.AF_UNIX),
                            io_loop=self.io_loop)
     self.stream.connect(self.sockfile, self.stop)
     self.wait()
Ejemplo n.º 14
0
    def get_app(self):
        wsgi_app = WSGIContainer(self.wsgi_app)

        class Handler(RequestHandler):
            def get(self, *args, **kwargs):
                self.finish(self.reverse_url("tornado"))

        return RuleRouter([
            (PathMatches("/tornado.*"),
             Application([(r"/tornado/test", Handler, {}, "tornado")])),
            (PathMatches("/wsgi"), wsgi_app),
        ])
Ejemplo n.º 15
0
    def get_app(self):
        class ProcessHandler(RequestHandler):
            def get(self):
                if self.get_argument("exit", None):
                    # must use os._exit instead of sys.exit so unittest's
                    # exception handler doesn't catch it
                    os._exit(int(self.get_argument("exit")))
                if self.get_argument("signal", None):
                    os.kill(os.getpid(), int(self.get_argument("signal")))
                self.write(str(os.getpid()))

        return Application([("/", ProcessHandler)])
Ejemplo n.º 16
0
    def get_app(self):
        class SmallHeaders(RequestHandler):
            def get(self):
                self.set_header("X-Filler", "a" * 100)
                self.write("ok")

        class LargeHeaders(RequestHandler):
            def get(self):
                self.set_header("X-Filler", "a" * 1000)
                self.write("ok")

        return Application([('/small', SmallHeaders),
                            ('/large', LargeHeaders)])
Ejemplo n.º 17
0
 def get_app(self):
     return Application([
         ('/sequence', GenSequenceHandler),
         ('/coroutine_sequence', GenCoroutineSequenceHandler),
         ('/coroutine_unfinished_sequence',
          GenCoroutineUnfinishedSequenceHandler),
         ('/task', GenTaskHandler),
         ('/exception', GenExceptionHandler),
         ('/coroutine_exception', GenCoroutineExceptionHandler),
         ('/yield_exception', GenYieldExceptionHandler),
         ('/undecorated_coroutine', UndecoratedCoroutinesHandler),
         ('/async_prepare_error', AsyncPrepareErrorHandler),
         ('/native_coroutine', NativeCoroutineHandler),
     ])
Ejemplo n.º 18
0
    def get_app(self):
        return Application(
            [
                # test endpoints
                ('/client/login', GoogleLoginHandler, dict(test=self)),

                # simulated google authorization server endpoints
                ('/google/oauth2/authorize', GoogleOAuth2AuthorizeHandler),
                ('/google/oauth2/token', GoogleOAuth2TokenHandler),
                ('/google/oauth2/userinfo', GoogleOAuth2UserinfoHandler),
            ],
            google_oauth={
                "key": 'fake_google_client_id',
                "secret": 'fake_google_client_secret'
            })
Ejemplo n.º 19
0
 def get_app(self):
     return Application([
         url("/hello", HelloWorldHandler),
         url("/post", PostHandler),
         url("/put", PutHandler),
         url("/redirect", RedirectHandler),
         url("/chunk", ChunkHandler),
         url("/auth", AuthHandler),
         url("/countdown/([0-9]+)", CountdownHandler, name="countdown"),
         url("/echopost", EchoPostHandler),
         url("/user_agent", UserAgentHandler),
         url("/304_with_content_length", ContentLength304Handler),
         url("/all_methods", AllMethodsHandler),
         url('/patch', PatchHandler),
         url('/set_header', SetHeaderHandler),
     ],
                        gzip=True)
Ejemplo n.º 20
0
    def setUp(self):
        if IOLoop.configured_class().__name__ in ('TwistedIOLoop',
                                                  'AsyncIOMainLoop'):
            # TwistedIOLoop only supports the global reactor, so we can't have
            # separate IOLoops for client and server threads.
            # AsyncIOMainLoop doesn't work with the default policy
            # (although it could with some tweaks to this test and a
            # policy that created loops for non-main threads).
            raise unittest.SkipTest(
                'Sync HTTPClient not compatible with TwistedIOLoop or '
                'AsyncIOMainLoop')
        self.server_ioloop = IOLoop()

        sock, self.port = bind_unused_port()
        app = Application([('/', HelloWorldHandler)])
        self.server = HTTPServer(app, io_loop=self.server_ioloop)
        self.server.add_socket(sock)

        self.server_thread = threading.Thread(target=self.server_ioloop.start)
        self.server_thread.start()

        self.http_client = HTTPClient()
Ejemplo n.º 21
0
 def get_app(self):
     # callable objects to finish pending /trigger requests
     self.triggers = collections.deque()
     return Application([
         url("/trigger", TriggerHandler,
             dict(queue=self.triggers, wake_callback=self.stop)),
         url("/chunk", ChunkHandler),
         url("/countdown/([0-9]+)", CountdownHandler, name="countdown"),
         url("/hang", HangHandler),
         url("/hello", HelloWorldHandler),
         url("/content_length", ContentLengthHandler),
         url("/head", HeadHandler),
         url("/options", OptionsHandler),
         url("/no_content", NoContentHandler),
         url("/see_other_post", SeeOtherPostHandler),
         url("/see_other_get", SeeOtherGetHandler),
         url("/host_echo", HostEchoHandler),
         url("/no_content_length", NoContentLengthHandler),
         url("/echo_post", EchoPostHandler),
         url("/respond_in_prepare", RespondInPrepareHandler),
         url("/redirect", RedirectHandler),
     ],
                        gzip=True)
Ejemplo n.º 22
0
 def get_app(self):
     self.close_future = Future()
     return Application([
         ('/', EchoHandler, dict(close_future=self.close_future)),
     ],
                        websocket_max_message_size=1024)
Ejemplo n.º 23
0
 def get_app(self):
     return Application([('/', HelloWorldRequestHandler)])
Ejemplo n.º 24
0
 def get_app(self):
     return Application([
         url("/hello", HelloWorldHandler),
     ])
Ejemplo n.º 25
0
 def get_app(self):
     return Application([('/', TestRequestHandler,
                          dict(io_loop=self.io_loop))])
Ejemplo n.º 26
0
 def get_app(self):
     return Application([
         ('/digest', DigestAuthHandler),
         ('/custom_reason', CustomReasonHandler),
         ('/custom_fail_reason', CustomFailReasonHandler),
     ])
Ejemplo n.º 27
0
 def get_app(self):
     self.close_future = Future()
     return Application([('/native', NativeCoroutineOnMessageHandler,
                          dict(close_future=self.close_future))])
Ejemplo n.º 28
0
 def get_app(self):
     return HTTPMethodRouter(Application())
Ejemplo n.º 29
0
 def get_app(self):
     return Application([('/', EchoHandler)])
Ejemplo n.º 30
0
 def get_app(self):
     self.app = Application(self.get_handlers(),
                            **self.get_app_kwargs())
     return WSGIContainer(validator(WSGIAdapter(self.app)))