Exemple #1
0
    async def get_value(self, request: Request) -> T:
        if request.declares_json(
        ) and request.method not in self._excluded_methods:
            data = await request.json()

            if not data:
                raise MissingBodyError()

            return self.parse_value(data)

        if self.required:
            if not request.has_body():
                raise MissingBodyError()

            raise InvalidRequestBody('Expected JSON payload')

        return None
Exemple #2
0
def test_small_request_headers_add_through_higher_api():
    request = Request("GET", b"https://hello-world", None)

    request.headers.add(b"Hello", b"World")

    raw_bytes = write_small_request(request)

    assert b"Hello: World\r\n" in raw_bytes
async def test_from_query_raises_for_invalid_parameter(expected_type,
                                                       invalid_value: bytes):
    request = Request("GET", b"/?foo=" + invalid_value, None)

    parameter = QueryBinder(expected_type, "foo", required=True)

    with raises(BadRequest):
        await parameter.get_value(request)
Exemple #4
0
async def test_request_binder():
    request = Request('GET', b'/', None)

    parameter = RequestBinder()

    value = await parameter.get_value(request)

    assert value is request
Exemple #5
0
 async def options(self,
                   url: URLType,
                   content: Content = None,
                   headers: Optional[List[Header]] = None,
                   params=None):
     return await self.send(
         Request('OPTIONS', self.get_url(url, params),
                 headers).with_content(content))
Exemple #6
0
def test_small_request_headers_add_through_higher_api():
    request = Request('GET', b'https://hello-world', None)

    request.headers.add(b'Hello', b'World')

    raw_bytes = write_small_request(request)

    assert b'Hello: World\r\n' in raw_bytes
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
Exemple #8
0
 def _validate_request_url(self, request: Request):
     if not request.url.is_absolute:
         if self.base_url:
             request.url = URL(self._get_url_without_params(request.url))
         else:
             raise ValueError(
                 'request.url must be a complete, absolute URL. Either provide a base_url '
                 'for the client, or specify a full URL for the request.')
Exemple #9
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,
        )
Exemple #10
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()
Exemple #11
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
Exemple #12
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
Exemple #13
0
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"/", []))
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")
Exemple #15
0
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
Exemple #16
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
Exemple #17
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
Exemple #18
0
async def test_get_response_for_file_returns_cache_control_header(cache_time):
    response = get_response_for_file(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()
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
Exemple #20
0
 def _validate_request_url(self, request: Request):
     if not request.url.is_absolute:
         if self.base_url:
             request.url = URL(self.get_url_value(request.url))
         else:
             raise ValueError(
                 "request.url must be a complete, absolute URL. "
                 "Either provide a base_url "
                 "for the client, or specify a full URL for the request.")
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)
Exemple #22
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
Exemple #23
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
Exemple #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;",
    }
Exemple #25
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;'
    }
Exemple #26
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
Exemple #27
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
Exemple #28
0
async def test_get_response_for_file_returns_not_modified_handling_if_none_match_header(file_path, method):
    info = FileInfo.from_path(file_path)

    response = get_response_for_file(Request(method, b'/example',
                                             [(b'If-None-Match', info.etag.encode())]),
                                     file_path,
                                     1200)

    assert response.status == 304
    data = await response.read()
    assert data is None
Exemple #29
0
async def test_text_file_range_request_single_part(range_value, expected_bytes, expected_content_range):
    file_path = _get_file_path('example.txt')
    response = get_response_for_file(Request('GET', b'/example',
                                             [(b'Range', range_value)]),
                                     file_path,
                                     1200)
    assert response.status == 206
    body = await response.read()
    assert body == expected_bytes

    assert response.get_single_header(b'content-range') == expected_content_range
async def test_from_services():
    request = Request("GET", b"/", [])

    service_instance = ExampleOne(1, 2)
    container = Container()
    container.add_instance(service_instance)

    parameter = ServiceBinder(ExampleOne, "service", False, container.build_provider())
    value = await parameter.get_value(request)

    assert value is service_instance