Example #1
0
async def test_wsgi_not_supported():
    with pytest.raises(falcon.CompatibilityError):
        async with testing.TestClient(falcon.App()):
            pass

    with pytest.raises(falcon.CompatibilityError):
        async with testing.ASGIConductor(falcon.App()):
            pass
Example #2
0
    def test_add_invalid_middleware(self):
        """Test than an invalid class can not be added as middleware"""
        class InvalidMiddleware():
            def process_request(self, *args):
                pass

        mw_list = [RequestTimeMiddleware(), InvalidMiddleware]
        with pytest.raises(AttributeError):
            falcon.App(middleware=mw_list)
        mw_list = [RequestTimeMiddleware(), 'InvalidMiddleware']
        with pytest.raises(TypeError):
            falcon.App(middleware=mw_list)
        mw_list = [{'process_request': 90}]
        with pytest.raises(TypeError):
            falcon.App(middleware=mw_list)
Example #3
0
    def __init__(self, port, hab: habbing.Habitat, mbx: exchanging.Mailboxer,
                 **kwa):
        """

        :param port:
        :param hab:
        :param kwa:
        """
        self.hab = hab
        self.mbx = mbx
        self.port = port
        self.rxbs = bytearray()

        self.app = falcon.App()

        self.app.add_route("/mbx", self)

        self.server = http.Server(port=self.port, app=self.app)
        serdoer = http.ServerDoer(server=self.server)

        doers = [serdoer]

        super(MailboxServer, self).__init__(doers=doers, **kwa)
        if self.tymth:
            self.server.wind(self.tymth)
Example #4
0
def server_process(port, mode, **kwargs):
    import json
    import falcon
    from distutils.version import StrictVersion
    from wsgiref import simple_server

    class HelloWorldResource(object):
        def on_get(self, req, resp):
            resp.body = json.dumps({'text': 'Hello World!!!'})

    if StrictVersion(falcon.__version__) < StrictVersion('3.0.0'):
        app = falcon.API()
    else:
        app = falcon.App()

    app.add_route('/hello/world', HelloWorldResource())

    if mode == 'auto':
        from swagger_ui import api_doc
        api_doc(app, **kwargs)
    else:
        from swagger_ui import falcon_api_doc
        falcon_api_doc(app, **kwargs)

    httpd = simple_server.make_server('localhost', port, app)
    httpd.serve_forever()
Example #5
0
def client():
    app = falcon.App()

    resource = RedirectingResource()
    app.add_route('/', resource)

    return testing.TestClient(app)
Example #6
0
def client_exercising_headers():
    app = falcon.App()

    resource = RedirectingResourceWithHeaders()
    app.add_route('/', resource)

    return testing.TestClient(app)
Example #7
0
    def test_noncoroutine_required(self):
        wsgi_app = falcon.App()

        with pytest.raises(TypeError) as exinfo:
            wsgi_app.add_route('/', PartialCoroutineResource())

        assert 'responder must be a regular synchronous method' in str(exinfo.value)
Example #8
0
 def test_api_initialization_with_cors_enabled_and_middleware_param(
         self, mw):
     app = falcon.App(middleware=mw, cors_enable=True)
     app.add_route('/', TestCorsResource())
     client = testing.TestClient(app)
     result = client.simulate_get()
     assert result.headers['Access-Control-Allow-Origin'] == '*'
Example #9
0
    def test_order_independent_mw_executed_when_exception_in_rsrc(self):
        """Test that error in inner middleware leaves"""
        global context

        class RaiseErrorMiddleware:
            def process_resource(self, req, resp, resource):
                raise Exception('Always fail')

        app = falcon.App(independent_middleware=True,
                         middleware=[
                             ExecutedFirstMiddleware(),
                             RaiseErrorMiddleware(),
                             ExecutedLastMiddleware()
                         ])

        def handler(req, resp, ex, params):
            pass

        app.add_error_handler(Exception, handler)

        app.add_route(TEST_ROUTE, MiddlewareClassResource())
        client = testing.TestClient(app)

        client.simulate_request(path=TEST_ROUTE)

        # Any mw is executed now...
        expectedExecutedMethods = [
            'ExecutedFirstMiddleware.process_request',
            'ExecutedLastMiddleware.process_request',
            'ExecutedFirstMiddleware.process_resource',
            'ExecutedLastMiddleware.process_response',
            'ExecutedFirstMiddleware.process_response'
        ]
        assert expectedExecutedMethods == context['executed_methods']
Example #10
0
    def test_outer_mw_with_ex_handler_throw_exception(self):
        """Test that error in inner middleware leaves"""
        global context

        class RaiseErrorMiddleware:
            def process_request(self, req, resp):
                raise Exception('Always fail')

        app = falcon.App(middleware=[
            TransactionIdMiddleware(),
            RaiseErrorMiddleware(),
            RequestTimeMiddleware()
        ])

        def handler(req, resp, ex, params):
            context['error_handler'] = True

        app.add_error_handler(Exception, handler)

        app.add_route(TEST_ROUTE, MiddlewareClassResource())
        client = testing.TestClient(app)

        client.simulate_request(path=TEST_ROUTE)

        # Any mw is executed now...
        assert 'transaction_id' in context
        assert 'start_time' not in context
        assert 'mid_time' not in context
        assert 'end_time' in context
        assert 'error_handler' in context
Example #11
0
    def test_inner_mw_throw_exception(self):
        """Test that error in inner middleware leaves"""
        global context

        class RaiseErrorMiddleware:
            def process_request(self, req, resp):
                raise Exception('Always fail')

        app = falcon.App(middleware=[
            TransactionIdMiddleware(),
            RequestTimeMiddleware(),
            RaiseErrorMiddleware()
        ])

        app.add_route(TEST_ROUTE, MiddlewareClassResource())
        client = testing.TestClient(app)

        result = client.simulate_request(path=TEST_ROUTE)
        assert result.status_code == 500

        # RequestTimeMiddleware process_response should be executed
        assert 'transaction_id' in context
        assert 'start_time' in context
        assert 'mid_time' not in context
        assert 'end_time' in context
Example #12
0
def create(body, headers):
    queue_collection = queues.CollectionResource()
    queue_item = queues.ItemResource()

    stats_endpoint = stats.Resource()

    msg_collection = messages.CollectionResource()
    msg_item = messages.ItemResource()

    claim_collection = claims.CollectionResource()
    claim_item = claims.ItemResource()

    middleware = [
        RequestIDComponent(),
        CannedResponseComponent(body, headers),
    ]

    api = falcon.App(middleware=middleware)
    api.add_route('/v1/{tenant_id}/queues', queue_collection)
    api.add_route('/v1/{tenant_id}/queues/{queue_name}', queue_item)
    api.add_route('/v1/{tenant_id}/queues/{queue_name}'
                  '/stats', stats_endpoint)
    api.add_route('/v1/{tenant_id}/queues/{queue_name}'
                  '/messages', msg_collection)
    api.add_route(
        '/v1/{tenant_id}/queues/{queue_name}'
        '/messages/{message_id}', msg_item)
    api.add_route('/v1/{tenant_id}/queues/{queue_name}'
                  '/claims', claim_collection)
    api.add_route('/v1/{tenant_id}/queues/{queue_name}'
                  '/claims/{claim_id}', claim_item)

    return api
Example #13
0
    def test_cached_text_in_result(self):
        app = falcon.App()
        app.add_route('/', testing.SimpleTestResource(body='test'))
        client = testing.TestClient(app)

        result = client.simulate_get()
        assert result.text == result.text
Example #14
0
def adminInterface(controller, hab, adminHttpPort=5623, adminTcpPort=5624):

    rotateHandler = agenting.RotateHandler(hab=hab)
    issueHandler = agenting.IssueCredentialHandler(hab=hab)
    handlers = [rotateHandler, issueHandler]

    exchanger = exchanging.Exchanger(hab=hab,
                                     controller=controller,
                                     handlers=handlers)

    server = tcpServing.Server(host="", port=adminTcpPort)
    tcpServerDoer = tcpServing.ServerDoer(server=server)
    directant = directing.Directant(hab=hab, server=server)

    app = falcon.App()
    exnServer = httping.AgentExnServer(exc=exchanger, app=app)
    httpKelServer = httping.AgentKelServer(hab=hab, app=app)

    server = http.Server(port=adminHttpPort, app=exnServer.app)
    httpServerDoer = http.ServerDoer(server=server)

    doers = [
        exnServer, exchanger, tcpServerDoer, directant, httpKelServer,
        httpServerDoer
    ]

    return doers
Example #15
0
def test_non_ascii_json_serialization(document):
    app = falcon.App()
    app.add_route('/', SimpleMediaResource(document))
    client = testing.TestClient(app)

    resp = client.simulate_get('/')
    assert resp.json == document
Example #16
0
def client():
    app = falcon.App()

    resource = WrappedRespondersResource()
    app.add_route('/', resource)

    return testing.TestClient(app)
Example #17
0
def create_app(mgr: Manager):
    logging.basicConfig(filename="/var/tmp/webservices_api.log",
                        level=logging.INFO)
    logging.info("Service initialized")
    print("Service initialized", file=sys.stderr)

    manager = mgr
    app = application = falcon.App(middleware=[MultipartMiddleware()])

    # Provided for backwards compatibility
    #scNetViz = ScNetVizHandler(mgr)
    #api.add_route('/scnetviz/api/v1/umap', scNetViz)
    #api.add_route('/scnetviz/api/v1/tsne', scNetViz)
    #api.add_route('/scnetviz/api/v1/drawgraph', scNetViz)
    #api.add_route('/scnetviz/api/v1/louvain', scNetViz)
    #api.add_route('/scnetviz/api/v1/leiden', scNetViz)

    # New API
    jobs = Jobs(mgr)
    app.add_route('/status/{job_id}', jobs)
    app.add_route('/fetch/{job_id}', jobs)
    app.add_route('/terminate/{job_id}', jobs)
    algorithms = Algorithms(jobs)
    app.add_route('/services', algorithms)
    for algorithm in algorithms.get_algorithms():
        app.add_route('/service/' + algorithm,
                      algorithms.get_algorithm(algorithm))

    # ChimeraX web services
    from . import cxservices
    cxservices.add_routes(app)

    return application
Example #18
0
    def test_override_default_media_type(self, client, content_type, body):
        client.app = falcon.App(media_type=content_type)
        client.app.add_route('/', testing.SimpleTestResource(body=body))
        result = client.simulate_get()

        assert result.text == body
        assert result.headers['Content-Type'] == content_type
Example #19
0
def create():
    api = falcon.App(cors_enable=True)
    api.add_route('/analyze', Analyze())
    api.add_route('/crawl', Crawl())
    api.add_route('/status', Status())
    logger.info('falcon initialized')
    return api
Example #20
0
def run():
    """
    Use hio http server
    """
    tymist = tyming.Tymist(tyme=0.0)

    app = falcon.App()  # falcon.API instances are callable WSGI apps

    WEB_DIR_PATH = os.path.dirname(
        os.path.abspath(sys.modules.get(__name__).__file__))
    STATIC_DIR_PATH = os.path.join(WEB_DIR_PATH, 'static')

    sink = serving.StaticSink(staticDirPath=STATIC_DIR_PATH)
    app.add_sink(sink, prefix=sink.DefaultStaticSinkBasePath)

    try:
        server = http.Server(name='test',
                             port=8080,
                             tymeout=0.5,
                             app=app,
                             tymth=tymist.tymen())
        server.reopen()

        while True:
            try:
                server.service()
                time.sleep(0.0625)
                tymist.tick(tock=0.0625)

            except KeyboardInterrupt:  # use CNTL-C to shutdown from shell
                break

    finally:
        server.close()
Example #21
0
    def test_generate_trans_id_and_time_with_request(self,
                                                     independent_middleware):
        # NOTE(kgriffs): We test both so that we can cover the code paths
        # where only a single middleware method is implemented by a
        # component.
        creq = CaptureRequestMiddleware()
        cresp = CaptureResponseMiddleware()

        global context
        app = falcon.App(independent_middleware=independent_middleware,
                         middleware=[
                             TransactionIdMiddleware(),
                             RequestTimeMiddleware(), creq, cresp
                         ])

        app.add_route(TEST_ROUTE, MiddlewareClassResource())
        client = testing.TestClient(app)

        response = client.simulate_request(path=TEST_ROUTE)
        assert _EXPECTED_BODY == response.json
        assert response.status == falcon.HTTP_200
        assert 'transaction_id' in context
        assert 'unique-req-id' == context['transaction_id']
        assert 'start_time' in context
        assert 'mid_time' in context
        assert 'end_time' in context
        assert context['mid_time'] >= context['start_time'], \
            'process_resource not executed after request'
        assert context['end_time'] >= context['start_time'], \
            'process_response not executed after request'
Example #22
0
def client():
    app = falcon.App()
    app.add_route('/', CookieResource())
    app.add_route('/test-convert', CookieResourceMaxAgeFloatString())
    app.add_route('/same-site', CookieResourceSameSite())

    return testing.TestClient(app)
Example #23
0
def client():
    app = falcon.App()

    resource = FaultyResource()
    app.add_route('/fail', resource)

    return testing.TestClient(app)
Example #24
0
    def test_status(self):
        app = falcon.App()
        resource = testing.SimpleTestResource(status=falcon.HTTP_702)
        app.add_route('/', resource)
        client = testing.TestClient(app)

        result = client.simulate_get()
        assert result.status == falcon.HTTP_702
Example #25
0
def test_parser_sync(body, doc):
    app = falcon.App()

    resource = WrappedRespondersBodyParserResource()
    app.add_route('/', resource)

    testing.simulate_get(app, '/', body=body)
    assert resource.doc == doc
Example #26
0
    def setUp(self):
        super(TestCase, self).setUp()

        app = falcon.App()

        # NOTE(kgriffs): Don't use super() to avoid triggering
        # unittest.TestCase.__init__()
        TestClient.__init__(self, app)
Example #27
0
    def test_raise_status_empty_body(self):
        """ Make sure passing None to body results in empty body """
        app = falcon.App()
        app.add_route('/status', TestStatusResource())
        client = testing.TestClient(app)

        response = client.simulate_request(path='/status', method='PATCH')
        assert response.text == ''
Example #28
0
def create_app(testing: bool = False):
    middlewares = (Filter(), CORS(), Translate())
    app = falcon.App(middleware=middlewares)
    # setup logger
    setup_logger(level=config.LOG_LEVEL)
    # register routes
    register_routes(app)
    return app
Example #29
0
def runAgent(controller,
             name="agent",
             httpPort=5620,
             tcp=5621,
             adminHttpPort=5623,
             adminTcpPort=5624,
             expire=0.0):
    """
    Setup and run one agent
    """
    logger = help.ogler.getLogger()

    ks = keeping.Keeper(name=name,
                        temp=False)  # not opened by default, doer opens
    ksDoer = keeping.KeeperDoer(
        keeper=ks)  # doer do reopens if not opened and closes
    db = basing.Baser(name=name, temp=False,
                      reload=True)  # not opened by default, doer opens
    dbDoer = basing.BaserDoer(
        baser=db)  # doer do reopens if not opened and closes

    # setup habitat
    hab = habbing.Habitat(name=name, ks=ks, db=db, temp=False, create=False)
    habDoer = habbing.HabitatDoer(habitat=hab)  # setup doer

    # kvy = eventing.Kevery(db=hab.db, local=False)
    # setup doers
    server = tcpServing.Server(host="", port=tcp)
    tcpServerDoer = tcpServing.ServerDoer(server=server)
    directant = directing.Directant(hab=hab, server=server)

    wallet = walleting.Wallet(hab=hab, name=name)

    jsonSchema = scheming.JSONSchema(resolver=scheming.jsonSchemaCache)
    issueHandler = handling.IssueHandler(wallet=wallet, typ=jsonSchema)
    requestHandler = handling.RequestHandler(wallet=wallet, typ=jsonSchema)
    exchanger = exchanging.Exchanger(hab=hab,
                                     handlers=[issueHandler, requestHandler])

    app = falcon.App()
    exnServer = httping.AgentExnServer(exc=exchanger, app=app)
    httpKelServer = httping.AgentKelServer(hab=hab, app=app)

    server = http.Server(port=httpPort, app=exnServer.app)
    httpServerDoer = http.ServerDoer(server=server)

    doers = [
        ksDoer, dbDoer, habDoer, exchanger, directant, tcpServerDoer,
        exnServer, httpServerDoer, httpKelServer
    ]
    doers.extend(adminInterface(controller, hab, adminHttpPort, adminTcpPort))

    try:
        tock = 0.03125
        doist = doing.Doist(limit=expire, tock=tock, real=True)
        doist.do(doers=doers)
    except kering.ConfigurationError:
        print(f"prefix for {name} does not exist, incept must be run first", )
Example #30
0
    def test_dont_need_params_in_signature(self):
        """
        Verify that we don't need parameters in the process_* signatures (for
        side-effect-only middlewares, mostly). Makes no difference on py27
        but does affect py36.

        https://github.com/falconry/falcon/issues/1254
        """
        falcon.App(middleware=EmptySignatureMiddleware())