コード例 #1
0
def test_cookies_jar():
    class Foo:
        def on_get(self, req, resp):
            # NOTE(myuz): In the future we shouldn't change the cookie
            #             a test depends on the input.
            # NOTE(kgriffs): This is the only test that uses a single
            #   cookie (vs. multiple) as input; if this input ever changes,
            #   a separate test will need to be added to explicitly verify
            #   this use case.
            resp.set_cookie('has_permission', 'true')

        def on_post(self, req, resp):
            if req.cookies['has_permission'] == 'true':
                resp.status = falcon.HTTP_200
            else:
                resp.status = falcon.HTTP_403

    app = App()
    app.add_route('/jars', Foo())

    client = testing.TestClient(app)

    response_one = client.simulate_get('/jars')
    response_two = client.simulate_post('/jars', cookies=response_one.cookies)

    assert response_two.status == falcon.HTTP_200
コード例 #2
0
ファイル: test_testing.py プロジェクト: wsz/falcon
def test_simulate_request_content_type():
    class Foo:
        def on_post(self, req, resp):
            resp.text = req.content_type

    app = App()
    app.add_route('/', Foo())

    headers = {'Content-Type': falcon.MEDIA_TEXT}

    result = testing.simulate_post(app, '/', headers=headers)
    assert result.text == falcon.MEDIA_TEXT

    result = testing.simulate_post(app, '/', content_type=falcon.MEDIA_HTML)
    assert result.text == falcon.MEDIA_HTML

    result = testing.simulate_post(
        app, '/', content_type=falcon.MEDIA_HTML, headers=headers
    )
    assert result.text == falcon.MEDIA_HTML

    result = testing.simulate_post(app, '/', json={})
    assert result.text == falcon.MEDIA_JSON

    result = testing.simulate_post(app, '/', json={}, content_type=falcon.MEDIA_HTML)
    assert result.text == falcon.MEDIA_JSON

    result = testing.simulate_post(app, '/', json={}, headers=headers)
    assert result.text == falcon.MEDIA_JSON

    result = testing.simulate_post(
        app, '/', json={}, headers=headers, content_type=falcon.MEDIA_HTML
    )
    assert result.text == falcon.MEDIA_JSON
コード例 #3
0
def api_server():
    """
    spawn a run forever api server instance and add routing information
    """
    app = App()
    app.add_route("/gateway", GatewayDepositServer())
    print(it("red", "INITIALIZING DEPOSIT SERVER"))
    print("serving http at")
    call(["hostname", "-I"])
    with make_server("", 8000, app) as httpd:
        httpd.serve_forever()
コード例 #4
0
ファイル: test_inspect.py プロジェクト: hzdwang/falcon-1
def get_app(asgi, cors=True, **kw):
    if asgi:
        from falcon.asgi import App as AsyncApp
        return AsyncApp(cors_enable=cors, **kw)
    else:
        from falcon import App
        return App(cors_enable=cors, **kw)
コード例 #5
0
def test_simulate_request_http_version(version, valid):
    app = App()

    if valid:
        testing.simulate_request(app, http_version=version)
    else:
        with pytest.raises(ValueError):
            testing.simulate_request(app, http_version=version)
コード例 #6
0
def create_signs_routes(api: falcon.App, context: Context):
    signs_search = SignsSearch(context.sign_repository)
    signs = SignsResource(context.sign_repository)
    signs_images = SignsImageResource(
        AnnotationImageExtractor(
            context.fragment_repository,
            context.annotations_repository,
            context.photo_repository,
        ))
    api.add_route("/signs", signs_search)
    api.add_route("/signs/{sign_name}", signs)
    api.add_route("/signs/{sign_name}/images", signs_images)
コード例 #7
0
from falcon.cmd import print_routes
from falcon.testing import redirected

try:
    import cython
except ImportError:
    cython = None


class DummyResource:
    def on_get(self, req, resp):
        resp.body = 'Test\n'
        resp.status = '200 OK'


_api = App()
_api.add_route('/test', DummyResource())


def test_traverse_with_verbose():
    """Ensure traverse() finds the proper routes and outputs verbose info."""

    output = io.StringIO()
    with redirected(stdout=output):
        print_routes.traverse(_api._router._roots, verbose=True)

    route, get_info, options_info = output.getvalue().strip().split('\n')
    assert '-> /test' == route

    # NOTE(kgriffs) We might receive these in either order, since the
    # method map is not ordered, so check and swap if necessary.
コード例 #8
0
def create_cdli_routes(api: falcon.App):
    cdli = CdliResource()

    api.add_route("/cdli/{cdli_number}", cdli)
コード例 #9
0
ファイル: routes.py プロジェクト: lynncyrin/json-api-template
def setup_routes(app: falcon.App, user_views: UserViews) -> falcon.App:
    app.add_route("/users", user_views, suffix="users")
    app.add_route("/users/{user_id}", user_views, suffix="user")
    return app
コード例 #10
0
ファイル: __main__.py プロジェクト: p1c2u/openapi-core
from falcon import App
from falconproject.openapi import openapi_middleware
from falconproject.pets.resources import PetDetailResource
from falconproject.pets.resources import PetListResource

app = App(middleware=[openapi_middleware])

pet_list_resource = PetListResource()
pet_detail_resource = PetDetailResource()

app.add_route("/v1/pets", pet_list_resource)
app.add_route("/v1/pets/{petId}", pet_detail_resource)
コード例 #11
0
 def app(self, middleware):
     return App(middleware=[middleware])
コード例 #12
0
        resp.media = {"name": name}

    @api.validate(
        resp=Response(HTTP_200=Resp, HTTP_401=None),
        tags=[api_tag, "test"],
    )
    def on_post(self, req, resp, name, query: Query, json: JSON,
                cookies: Cookies):
        score = [randint(0, req.context.json.limit) for _ in range(5)]
        score.sort(reverse=req.context.query.order)
        assert req.context.cookies.pub == "abcdefg"
        assert req.cookies["pub"] == "abcdefg"
        resp.media = {"name": req.context.json.name, "score": score}


app = App()
app.add_route("/ping", Ping())
app.add_route("/api/user/{name}", UserScore())
app.add_route("/api/user_annotated/{name}", UserScoreAnnotated())
api.register(app)


@pytest.fixture
def client():
    return testing.TestClient(app)


def test_falcon_validate(client):
    resp = client.simulate_request("GET",
                                   "/ping",
                                   headers={"Content-Type": "text/plain"})
コード例 #13
0
def create_dictionary_routes(api: falcon.App, context: Context):
    dictionary = Dictionary(context.word_repository, context.changelog)
    words = WordsResource(dictionary)
    word_search = WordSearch(dictionary)
    api.add_route("/words", word_search)
    api.add_route("/words/{object_id}", words)
コード例 #14
0
def create_fragmentarium_routes(api: falcon.App, context: Context):
    context.fragment_repository.create_indexes()
    fragmentarium = Fragmentarium(context.fragment_repository)
    finder = FragmentFinder(
        context.get_bibliography(),
        context.fragment_repository,
        Dictionary(context.word_repository, context.changelog),
        context.photo_repository,
        context.folio_repository,
        context.parallel_line_injector,
    )
    updater = context.get_fragment_updater()
    annotations_service = AnnotationsService(
        context.ebl_ai_client,
        context.annotations_repository,
        context.photo_repository,
        context.changelog,
    )

    statistics = make_statistics_resource(context.cache, fragmentarium)
    fragments = FragmentsResource(finder)
    fragment_genre = FragmentGenreResource(updater)

    fragment_matcher = FragmentMatcherResource(
        FragmentMatcher(context.fragment_repository)
    )
    fragment_search = FragmentSearch(
        fragmentarium,
        finder,
        context.get_transliteration_query_factory(),
        context.cache,
    )
    genres = GenresResource()
    lemmatization = LemmatizationResource(updater)
    references = ReferencesResource(updater)
    transliteration = TransliterationResource(
        updater, context.get_transliteration_update_factory()
    )
    annotations = AnnotationResource(annotations_service)
    fragment_pager = make_fragment_pager_resource(finder, context.cache)
    folio_pager = FolioPagerResource(finder)
    photo = PhotoResource(finder)
    folios = FoliosResource(finder)

    api.add_route("/fragments", fragment_search)
    api.add_route("/fragments/{number}/match", fragment_matcher)
    api.add_route("/fragments/{number}/genres", fragment_genre)
    api.add_route("/fragments/{number}", fragments)
    api.add_route("/fragments/{number}/pager", fragment_pager)
    api.add_route("/fragments/{number}/lemmatization", lemmatization)
    api.add_route("/fragments/{number}/references", references)
    api.add_route("/fragments/{number}/transliteration", transliteration)
    api.add_route("/fragments/{number}/annotations", annotations)
    api.add_route("/fragments/{number}/photo", photo)
    api.add_route("/genres", genres)
    api.add_route("/statistics", statistics)
    api.add_route("/fragments/{number}/pager/{folio_name}/{folio_number}", folio_pager)
    api.add_route("/folios/{name}/{number}", folios)
コード例 #15
0
def create_files_route(api: falcon.App, context: Context):
    files = PublicFilesResource(context.public_file_repository)
    api.add_route("/images/{file_name}", files)
コード例 #16
0
ファイル: app.py プロジェクト: williamkibira/account-service
 def initialize_routes(self, app: falcon.App) -> None:
     app.add_route('/health-check', Readiness())
     app.add_route('/liveness', Liveness())
     app.add_route('/ping', Ping())
     # ACCOUNT RESOURCES
     app.add_route('/api/v1/account-service/accounts/register',
                   AccountCreationResource(service=self._account_service))
     app.add_route('/api/v1/account-service/accounts/update',
                   AccountUpdateResource(service=self._account_service))
     app.add_route(
         '/api/v1/account-service/accounts/request-reset',
         ReceivePasswordResetRequest(service=self._account_service))
     app.add_route('/api/v1/account-service/accounts/reset',
                   ResetAccountPassword(service=self._account_service))
     # USER RESOURCES
     app.add_route('/api/v1/account-service/users/details',
                   UserFetchResource(service=self._user_service))
コード例 #17
0
def create_lemmatization_routes(api: falcon.App, context: Context):
    dictionary = Dictionary(context.word_repository, context.changelog)
    finder = SuggestionFinder(dictionary, context.lemma_repository)
    lemma_search = LemmaSearch(finder)

    api.add_route("/lemmas", lemma_search)
コード例 #18
0
def create_bibliography_routes(api: falcon.App, context: Context):
    bibliography = context.get_bibliography()
    bibliography_resource = BibliographyResource(bibliography)
    bibliography_entries = BibliographyEntriesResource(bibliography)
    api.add_route("/bibliography", bibliography_resource)
    api.add_route("/bibliography/{id_}", bibliography_entries)