Beispiel #1
0
def test_small_request_headers_add_through_higher_api_many():
    request = Request("GET", b"https://hello-world", None)

    request.headers.add_many({b"Hello": b"World", b"X-Foo": b"Foo"})

    raw_bytes = write_small_request(request)

    assert b"Hello: World\r\n" in raw_bytes
    assert b"X-Foo: Foo\r\n" in raw_bytes
Beispiel #2
0
def test_request_pyi():
    request = Request("GET", b"/", [(b"cookie", b"foo=aaa")])

    request.cookies["foo"] == "aaa"
    request.get_cookie("foo") == "aaa"
    request.get_first_header(b"cookie") == b"foo=aaa"

    request.set_cookie("lorem", "ipsum")
    request.get_cookie("lorem") == "ipsum"
Beispiel #3
0
async def test_invalid_range_request_range_not_satisfiable(range_value):
    file_path = get_file_path("example.txt")
    with pytest.raises(RangeNotSatisfiable):
        get_response_for_file(
            FilesHandler(),
            Request("GET", b"/example", [(b"Range", range_value)]),
            file_path,
            1200,
        )
Beispiel #4
0
async def test_get_response_for_file_returns_cache_control_header(cache_time):
    response = get_response_for_file(FilesHandler(),
                                     Request("GET", b"/example", None),
                                     TEST_FILES[0], cache_time)

    assert response.status == 200
    header = response.get_single_header(b"cache-control")

    assert header == f"max-age={cache_time}".encode()
Beispiel #5
0
async def test_if_read_json_fails_content_type_header_is_checked_non_json_gives_invalid_operation():
    request = Request('POST', b'/', [
        (b'Content-Type', b'text/html')
    ])

    request.with_content(Content(b'application/json', b'{"hello":'))  # broken json

    with pytest.raises(InvalidOperation):
        await request.json()
Beispiel #6
0
async def test_get_response_for_file_with_head_method_returns_empty_body_with_info(
    file_path, ):
    response = get_response_for_file(FilesHandler(),
                                     Request("HEAD", b"/example", None),
                                     file_path, 1200)

    assert response.status == 200
    data = await response.read()
    assert data is None
def test_check_permanent_redirects():
    client = ClientSession()
    client._permanent_redirects_urls._cache[b"/foo"] = URL(b"https://somewhere.org")

    request = Request("GET", b"/foo", None)
    assert request.url == URL(b"/foo")

    client.check_permanent_redirects(request)
    assert request.url == URL(b"https://somewhere.org")
Beispiel #8
0
def test_request_supports_dynamic_attributes():
    request = Request(b'GET', b'/', Headers(), None)
    foo = object()

    assert hasattr(
        request, 'foo'
    ) is False, 'This test makes sense if such attribute is not defined'
    request.foo = foo
    assert request.foo is foo
async def test_from_query_binding(expected_type, query_value, expected_value):
    request = Request("GET", b"/?foo=" + query_value, None)

    parameter = QueryBinder(expected_type, "foo")

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_value
Beispiel #10
0
async def test_if_read_json_fails_content_type_header_is_checked_json_gives_bad_request_format(
):
    request = Request("POST", b"/", [(b"Content-Type", b"application/json")])

    request.with_content(Content(b"application/json",
                                 b'{"hello":'))  # broken json

    with pytest.raises(BadRequestFormat):
        await request.json()
async def test_from_header_binding_name_ci(expected_type, header_value, expected_value):
    request = Request("GET", b"/", [(b"X-Foo", header_value)])

    parameter = HeaderBinder(expected_type, "x-foo")

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_value
Beispiel #12
0
async def test_from_body_json_binding_request_missing_content_type():

    request = Request('POST', b'/', [])

    parameter = FromJson(ExampleOne)

    value = await parameter.get_value(request)

    assert value is None
Beispiel #13
0
async def test_get_response_for_static_content_handles_304():
    response = get_response_for_static_content(
        Request("GET", b"/", None),
        b"text/plain",
        b"Lorem ipsum dolor sit amet\n",
        datetime(2020, 10, 24).timestamp(),
    )

    assert response.status == 200

    response = get_response_for_static_content(
        Request("GET", b"/", [(b"If-None-Match", response.get_first_header(b"etag"))]),
        b"text/plain",
        b"Lorem ipsum dolor sit amet\n",
        datetime(2020, 10, 24).timestamp(),
    )

    assert response.status == 304
Beispiel #14
0
async def test_if_read_json_fails_content_type_header_is_checked_non_json_gives_invalid_operation(
):
    request = Request("POST", b"/", [])

    request.with_content(Content(
        b"text/html", b'{"hello":'))  # broken json; broken content-type

    with pytest.raises(BadRequestFormat):
        await request.json()
async def test_body_binder_throws_bad_request_for_missing_body():
    class CustomBodyBinder(BodyBinder):
        def matches_content_type(self, request: Request) -> bool:
            return True

        async def read_data(self, request: Request) -> Any:
            return None

    body_binder = CustomBodyBinder(dict)

    with pytest.raises(MissingBodyError):
        await body_binder.get_value(
            Request("POST", b"/", [(b"content-type", b"application/json")]))

    body_binder = JSONBinder(dict, required=True)

    with pytest.raises(MissingBodyError):
        await body_binder.get_value(Request("POST", b"/", []))
async def test_identity_binder():
    request = Request("GET", b"/", None)
    request.identity = Identity({})

    parameter = IdentityBinder(Identity)

    value = await parameter.get_value(request)

    assert value is request.identity
async def test_from_route_raises_for_invalid_parameter(expected_type,
                                                       invalid_value):
    request = Request("GET", b"/", None)
    request.route_values = {"name": invalid_value}

    parameter = RouteBinder(expected_type, "name")

    with raises(BadRequest):
        await parameter.get_value(request)
async def test_from_body_json_binding_request_missing_content_type():

    request = Request("POST", b"/", [])

    parameter = JsonBinder(ExampleOne)

    value = await parameter.get_value(request)

    assert value is None
Beispiel #19
0
async def test_from_services():
    request = Request(b'GET', b'/', Headers(), None)

    service_instance = ExampleOne(1, 2)
    request.services = {ExampleOne: service_instance}

    parameter = FromServices(ExampleOne)
    value = await parameter.get_value(request)

    assert value is service_instance
Beispiel #20
0
def test_cookie_parsing():
    request = Request('POST', b'/', [
        (b'Cookie', b'ai=something; hello=world; foo=Hello%20World%3B;')
    ])

    assert request.cookies == {
        'ai': 'something',
        'hello': 'world',
        'foo': 'Hello World;'
    }
async def test_from_body_json_binding_invalid_input():

    request = Request("POST", b"/", [JsonContentType]).with_content(
        JsonContent({"c": 1, "d": 2})
    )

    parameter = JsonBinder(ExampleOne)

    with raises(InvalidRequestBody):
        await parameter.get_value(request)
Beispiel #22
0
async def test_from_route_raises_for_invalid_parameter(expected_type,
                                                       invalid_value):

    request = Request('GET', b'/', None)
    request.route_values = {'name': invalid_value}

    parameter = FromRoute(expected_type, 'name')

    with raises(BadRequest):
        await parameter.get_value(request)
Beispiel #23
0
async def test_from_route_binding(expected_type, route_value, expected_value):
    request = Request("GET", b"/", None)
    request.route_values = {"name": route_value}

    parameter = RouteBinder(expected_type, "name")

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_value
Beispiel #24
0
def test_cookie_parsing():
    request = Request(
        "POST", b"/",
        [(b"Cookie", b"ai=something; hello=world; foo=Hello%20World%3B;")])

    assert request.cookies == {
        "ai": "something",
        "hello": "world",
        "foo": "Hello World;",
    }
Beispiel #25
0
async def test_from_query_binding(expected_type, query_value, expected_value):

    request = Request('GET', b'/?foo=' + query_value, None)

    parameter = FromQuery(expected_type, 'foo')

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_value
Beispiel #26
0
async def test_if_read_json_fails_content_type_header_is_checked_non_json_gives_invalid_operation(
):
    request = Request(b'POST', b'/',
                      Headers([Header(b'Content-Type', b'text/html')]), None)

    request.extend_body(b'{"hello":')  # broken json
    request.complete.set()

    with pytest.raises(InvalidOperation):
        await request.json()
Beispiel #27
0
async def test_from_services():
    request = Request('GET', b'/', [])

    service_instance = ExampleOne(1, 2)
    services = {ExampleOne: service_instance}

    parameter = FromServices(ExampleOne, services)
    value = await parameter.get_value(request)

    assert value is service_instance
Beispiel #28
0
async def test_from_header_binding(expected_type, header_value, expected_value):

    request = Request('GET', b'/', [(b'X-Foo', header_value)])

    parameter = FromHeader(expected_type, 'X-Foo')

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_value
Beispiel #29
0
 async def options(
     self,
     url: URLType,
     content: Content = None,
     headers: Optional[List[Header]] = None,
     params=None,
 ) -> Response:
     request = Request("OPTIONS", self.get_url(url, params), headers)
     return await self.send(
         request.with_content(content) if content is not None else request)
Beispiel #30
0
async def test_from_header_binding_iterables(declared_type, expected_type,
                                             header_values, expected_values):
    request = Request("GET", b"/",
                      [(b"X-Foo", value) for value in header_values])

    parameter = HeaderBinder(declared_type, "X-Foo")

    value = await parameter.get_value(request)

    assert isinstance(value, expected_type)
    assert value == expected_values