예제 #1
0
def status_code(status: int = 200, message: MessageType = None):
    """Returns a plain response with given status, with optional message; sent as plain text or JSON."""
    if not message:
        return Response(status)
    if isinstance(message, str):
        content = TextContent(message)
    else:
        content = JsonContent(message)
    return Response(status, content=content)
예제 #2
0
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)
예제 #3
0
    async def create_cat(request):
        nonlocal called_times
        called_times += 1
        assert request is not None

        content = await request.read()
        assert b'{"name":"Celine","kind":"Persian"}' == content

        data = await request.json()
        assert {"name": "Celine", "kind": "Persian"} == data

        return Response(201, [(b'Server', b'Python/3.7')], JsonContent({'id': '123'}))
예제 #4
0
async def test_from_body_json_binding_invalid_input():

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

    parameter = FromJson(ExampleOne)

    with raises(InvalidRequestBody):
        await parameter.get_value(request)
예제 #5
0
async def test_from_body_json_binding():

    request = Request("POST", b"/", [JsonContentType]).with_content(
        JsonContent({"a": "world", "b": 9000})
    )

    parameter = JsonBinder(ExampleOne)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleOne)
    assert value.a == "world"
    assert value.b == 9000
예제 #6
0
async def test_from_body_json_binding_request_missing_content_type():

    request = Request(b'POST', b'/', Headers(),
                      JsonContent({
                          'a': 'world',
                          'b': 9000
                      }))

    parameter = FromJson(ExampleOne)

    value = await parameter.get_value(request)

    assert value is None
예제 #7
0
async def test_body_binder_throws_bad_request_for_value_error():
    body_binder = JsonBinder(dict, required=True)

    def example_converter(value):
        raise ValueError("Invalid value")

    body_binder.converter = example_converter

    with pytest.raises(InvalidRequestBody):
        await body_binder.get_value(
            Request(
                "POST", b"/", [(b"content-type", b"application/json")]
            ).with_content(JsonContent({"id": "1", "name": "foo"}))
        )
예제 #8
0
async def test_from_body_json_binding():

    request = Request('POST', b'/', [JsonContentType]).with_content(
        JsonContent({
            'a': 'world',
            'b': 9000
        }))

    parameter = FromJson(ExampleOne)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleOne)
    assert value.a == 'world'
    assert value.b == 9000
예제 #9
0
async def test_from_body_json_binding_extra_parameters_strategy():

    request = Request('POST', b'/', [
        JsonContentType
    ]).with_content(JsonContent({
        'a': 'world',
        'b': 9000,
        'c': 'This is an extra parameter, accepted by constructor explicitly'
    }))

    parameter = FromJson(ExampleTwo)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleTwo)
    assert value.a == 'world'
    assert value.b == 9000
예제 #10
0
async def test_from_body_json_binding_extra_parameters_strategy():

    request = Request("POST", b"/", [JsonContentType]).with_content(
        JsonContent({
            "a":
            "world",
            "b":
            9000,
            "c":
            "This is an extra parameter, accepted by constructor explicitly",
        }))

    parameter = JsonBinder(ExampleTwo)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleTwo)
    assert value.a == "world"
    assert value.b == 9000
예제 #11
0
async def test_from_body_json_with_converter():

    request = Request('POST', b'/', [
        JsonContentType
    ]).with_content(JsonContent({
        'a': 'world',
        'b': 9000,
        'c': 'This is an extra parameter, accepted by constructor explicitly'
    }))

    def convert(data):
        return ExampleOne(data.get('a'), data.get('b'))

    parameter = FromJson(ExampleOne, converter=convert)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleOne)
    assert value.a == 'world'
    assert value.b == 9000
예제 #12
0
async def test_from_body_json_with_converter():

    request = Request("POST", b"/", [JsonContentType]).with_content(
        JsonContent({
            "a":
            "world",
            "b":
            9000,
            "c":
            "This is an extra parameter, accepted by constructor explicitly",
        }))

    def convert(data):
        return ExampleOne(data.get("a"), data.get("b"))

    parameter = JsonBinder(ExampleOne, converter=convert)

    value = await parameter.get_value(request)

    assert isinstance(value, ExampleOne)
    assert value.a == "world"
    assert value.b == 9000
예제 #13
0
async def test_connection_handle_expect_100_continue_and_1xx(
    connection: ClientConnection, ):
    # Arrange
    connection.open = True
    connection.headers = get_example_headers()
    connection.parser = FakeParser(100)
    connection.transport = FakeTransport()

    request = Request(
        "POST",
        b"/",
        headers=[(b"content-type", b"application/json"),
                 (b"expect", b"100-continue")],
    ).with_content(JsonContent({
        "id": "1",
        "name": "foo"
    }))

    # Arrange future response...
    connection.headers = get_example_headers()
    connection.parser = FakeParser(100)
    # trick: simulate a complete response before the request is sent;
    # here is legit because we are simulating a proper scenario
    connection.on_headers_complete()

    try:
        await asyncio.wait_for(connection.send(request), 0.01)
    except TimeoutError:
        pass

    # The first message must include only headers without body,
    # the second the body (received after the 100 response arrived)

    assert (
        connection.transport.messages[0] ==
        b"POST / HTTP/1.1\r\ncontent-type: application/json\r\nexpect: 100-continue\r\n\r\n"
    )
    assert connection.transport.messages[1] == b'{"id": "1", "name": "foo"}'
예제 #14
0
def created(location: Union[bytes, str], value: Any = None):
    """Returns an HTTP 201 Created response, to the given location and with optional JSON content."""
    return Response(201,
                    Headers([Header(b'Location', _ensure_bytes(location))]),
                    JsonContent(value) if value else None)
예제 #15
0
async def test_post_json(session, data):
    response = await session.post("/echo-posted-json", JsonContent(data))
    ensure_success(response)

    assert await response.json() == data
예제 #16
0
def json(value: Any, status: int = 200):
    """Returns a response with application/json content, and given status (default HTTP 200 OK)."""
    return Response(status, content=JsonContent(value))
예제 #17
0
    assert content.body == text.encode("utf8")


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "req,expected_chunks",
    [
        (
            Request(
                "POST",
                b"/",
                headers=[
                    (b"content-type", b"application/json"),
                    (b"expect", b"100-continue"),
                ],
            ).with_content(JsonContent({"id": "1", "name": "foo"})),
            [b'{"id": "1", "name": "foo"}'],
        ),
        (
            Request(
                "POST",
                b"/",
                headers=[
                    (b"content-type", b"text/plain"),
                    (b"expect", b"100-continue"),
                ],
            ).with_content(TextContent("Hello World")),
            [b"Hello World"],
        ),
    ],
)
예제 #18
0
def created(location: BytesOrStr, value: Any = None):
    """Returns an HTTP 201 Created response, to the given location and with optional JSON content."""
    return Response(201,
                    [(b'Location', _ensure_bytes(location))],
                    JsonContent(value) if value else None)
예제 #19
0
 async def example(request):
     nonlocal calls
     calls.append(5)
     return Response(200,
                     [(b'Server', b'Python/3.7')],
                     JsonContent({'id': '123'}))