def test_middleware_called_if_routed_to_sub_app(route: str, origin: str,
                                                expected: str,
                                                expected_body: str):
    app = App(
        enable_cors=True,
        cors_config={
            "allow_origins": ["example.com", "localhost:8001", "ietf.org"]
        },
    )

    @app.route("/")
    async def index(req, res):
        res.text = "Hello"

    sub = App()

    @sub.route("/")
    class SubApp:
        async def get(self, req, res):
            res.text = "OK"

    app.mount("/sub", sub)

    client = create_client(app)
    res = client.get(route, headers={"origin": origin})

    assert res.text == expected_body

    if not expected:  # unknown origin -> no allow-origin header
        assert "access-control-allow-origin" not in res.headers
    else:  # allowed origin -> allow-origin header"
        assert "access-control-allow-origin" in res.headers
        assert res.headers.get("access-control-allow-origin") == expected
Beispiel #2
0
def test_if_origin_not_in_allow_origins_then_400():
    app = App(enable_cors=True, cors_config={"allow_origins": ["foobar.com"]})

    @app.route("/")
    async def index(req, res):
        pass

    client = create_client(app)
    response = client.options(
        "/",
        headers={
            "origin": "foobar.com",
            "access-control-request-method": "GET",
        },
    )
    assert response.status_code == 200

    response = client.options(
        "/",
        headers={
            "origin": "example.com",
            "access-control-request-method": "GET",
        },
    )
    assert response.status_code == 400
Beispiel #3
0
def test_if_static_dir_is_none_then_no_assets_served(tmpdir_factory):
    static_dir = tmpdir_factory.mktemp("static")
    _create_asset(static_dir)

    app = App(static_dir=None)
    client = create_client(app)

    assert client.get(f"/static/{FILE_DIR}/{FILE_NAME}").status_code == 404
Beispiel #4
0
def test_if_not_debug_then_no_debug_info_returned(app: App):
    @app.route("/")
    async def index(req, res):
        raise ValueError("Oops")

    client = create_client(app, raise_server_exceptions=False)
    r = client.get("/")
    assert r.status_code == 500
    assert r.text == "500 Internal Server Error"
Beispiel #5
0
def test_static_root_defaults_to_static_dir(tmpdir_factory):
    static_dir = tmpdir_factory.mktemp("foo")
    _create_asset(static_dir)

    app = App(static_dir=str(static_dir), static_root=None)
    client = create_client(app)

    response = client.get(f"{static_dir}/{FILE_DIR}/{FILE_NAME}")
    assert response.status_code == 200
Beispiel #6
0
def test_if_host_not_allowed_then_400():
    app = App(allowed_hosts=["example.com"])
    client = create_client(app)

    @app.route("/")
    async def index(req, res):
        pass

    response = client.get("/")
    assert response.status_code == 400
Beispiel #7
0
def test_assets_are_served_at_static_by_default(tmpdir_factory):
    static_dir = tmpdir_factory.mktemp("static")
    _create_asset(static_dir)

    app = App(static_dir=str(static_dir))
    client = create_client(app)

    response = client.get(f"/static/{FILE_DIR}/{FILE_NAME}")
    assert response.status_code == 200
    assert response.text == FILE_CONTENTS
Beispiel #8
0
def test_customize_static_root(tmpdir_factory):
    static_dir = tmpdir_factory.mktemp("static")
    _create_asset(static_dir)

    app = App(static_dir=str(static_dir), static_root="assets")
    client = create_client(app)

    assert client.get(f"/static/{FILE_DIR}/{FILE_NAME}").status_code == 404
    response = client.get(f"/assets/{FILE_DIR}/{FILE_NAME}")
    assert response.status_code == 200
    assert response.text == FILE_CONTENTS
Beispiel #9
0
def test_if_gzip_enabled_then_response_is_compressed():
    app = App(enable_gzip=True, gzip_min_size=0)

    @app.route("/")
    async def index(req, res):
        pass

    client = create_client(app)
    response = client.get("/", headers={"Accept-Encoding": "gzip"})
    assert response.status_code == 200
    assert response.headers["content-encoding"] == "gzip"
Beispiel #10
0
def test_mount_extra_static_files_dirs(tmpdir_factory):
    static_dir = tmpdir_factory.mktemp("staticfiles")
    _create_asset(static_dir)

    app = App(static_dir=None)
    app.mount("assets", static(str(static_dir)))
    client = create_client(app)

    response = client.get(f"/assets/{FILE_DIR}/{FILE_NAME}")
    assert response.status_code == 200
    assert response.text == FILE_CONTENTS
Beispiel #11
0
def test_if_hsts_enabled_and_request_is_on_http_then_redirects_to_https():
    app = App(enable_hsts=True)

    @app.route("/")
    async def index(req, res):
        pass

    client = create_client(app)
    response = client.get("/", allow_redirects=False)
    assert response.status_code == 301
    assert response.headers["location"] == "https://testserver/"
Beispiel #12
0
def test_debug_response(app: App, accept: str, content_type: str):
    app.debug = True

    @app.route("/")
    async def index(req, res):
        raise ValueError("Oops")

    client = create_client(app, raise_server_exceptions=False)
    r = client.get("/", headers={"accept": accept})
    assert r.status_code == 500
    assert r.headers["content-type"] == content_type
    assert 'raise ValueError("Oops")' in r.text
Beispiel #13
0
def test_if_invalid_route_parameter_then_error_response(
    app,
    setup,
    setup_error_handler,
    check_status,
    annotation: Type,
    string_value: str,
):
    setup_error_handler(app)
    setup(app, annotation)
    client = create_client(app, raise_server_exceptions=False)
    r = check_status(client, f"/{string_value}")
    if r is not None:
        assert "value" in r.json()["detail"]
Beispiel #14
0
def test_no_allowed_origins_by_default():
    app = App(enable_cors=True)

    @app.route("/")
    async def index(req, res):
        pass

    client = create_client(app)
    response = client.options(
        "/",
        headers={
            "origin": "foobar.com",
            "access-control-request-method": "GET",
        },
    )
    assert response.status_code == 400
Beispiel #15
0
def test_sessions_enabled_secret_key_present(ctx, config):
    with ctx:
        app = App(enable_sessions=True, sessions_config=config)

        @app.route("/set")
        @view(methods=["post"])
        async def set_session(req, res):
            req.session["data"] = "something"
            res.text = "Saved"

        @app.route("/")
        async def index(req, res):
            data = req.session["data"]
            res.text = f"Hello {data}"

        client = create_client(app)
        client.post("/set")
        response = client.get("/")
        assert "something" in response.text
        assert "session" in response.cookies
Beispiel #16
0
def test_sessions_enabled_secret_key_present():
    with override_env("SECRET_KEY", "not-so-secret"):
        app = App(enable_sessions=True)

        @app.route("/set")
        @view(methods=["post"])
        async def set_session(req, res):
            req.session["data"] = "something"
            res.text = "Saved"

        @app.route("/")
        async def index(req, res):
            data = req.session["data"]
            res.text = f"Hello {data}"

        client = create_client(app)
        client.post("/set")
        response = client.get("/")
        assert "something" in response.text
        assert "session" in response.cookies
Beispiel #17
0
def test_custom_error_handler(app: App, exception_cls):
    called = False

    @app.error_handler(KeyError)
    def on_key_error(req, res, exc):
        nonlocal called
        res.text = "Oops!"
        called = True

    @app.route("/")
    async def index(req, res):
        raise exception_cls("foo")

    client = create_client(app, raise_server_exceptions=False)

    if exception_cls == KeyError:
        response = client.get("/")
        assert called
        assert response.status_code == 200
        assert response.text == "Oops!"
    else:
        response = client.get("/")
        assert response.status_code == 500
        assert not called
Beispiel #18
0
def client():
    return create_client(app)