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" })))
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
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(BadRequest): await parameter.get_value(request)
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
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_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
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