"""Tests for Handler utils.""" import json from typing import Any import marshmallow import pytest from marshmallow.exceptions import ValidationError import application from vectororder.exceptions import RequestError from vectororder.utils import handlers as handlers_utils class _TestSchema(marshmallow.Schema): name = marshmallow.fields.Str(required=True) def test_parse_request_json(client_headers: dict[str, str]) -> None: """Test parsing and validating request JSON.""" request_data = {"name": "Snowball"} with application.app.test_request_context( headers=client_headers, data=json.dumps(request_data) ): data = handlers_utils.parse_request_json(schema=_TestSchema) assert data == request_data def test_parse_request_json_with_request_data(client_headers: dict[str, str]) -> None: """Test parsing and validating request JSON with explicit request_data.""" request_data = {"name": "Baseball"} explicitly_passed_data = {"name": "Plankton"} with application.app.test_request_context( headers=client_headers, data=json.dumps(request_data) ): data = handlers_utils.parse_request_json( schema=_TestSchema, request_data=explicitly_passed_data ) assert data == explicitly_passed_data @pytest.mark.parametrize("data", [b"true", b"null", b'""', b"[]", b"", b'{"items": [}']) def test_parse_request_json_invalid_data( client_headers: dict[str, str], data: Any ) -> None: """Test non-dict values returns a bad request.""" with application.app.test_request_context(headers=client_headers, data=data): with pytest.raises(RequestError): handlers_utils.parse_request_json(schema=_TestSchema) def test_parse_request_json_invalid_headers() -> None: """Test missing header data returns a bad request.""" request_data = {"name": "Snowball"} with application.app.test_request_context(data=json.dumps(request_data)): with pytest.raises(RequestError): handlers_utils.parse_request_json(schema=_TestSchema) def test_parse_request_json_missing_required_field( client_headers: dict[str, str], ) -> None: """Test schema validator returns error.""" with application.app.test_request_context( headers=client_headers, data=json.dumps({}) ): with pytest.raises(ValidationError): handlers_utils.parse_request_json(schema=_TestSchema) @pytest.mark.parametrize( "order_by_str, expected_result", ( ("", []), ("foo", ["foo"]), ("FOO", ["FOO"]), ("-foo", ["-foo"]), ("foo,bar_buzz", ["foo", "bar_buzz"]), ("foo, bar_buzz", ["foo", "bar_buzz"]), ("foo1,-bar", ["foo1", "-bar"]), ), ) def test_get_order_by_success(order_by_str: str, expected_result: list[str]) -> None: """Test get_order_by helper successfully parsing incoming parameter.""" assert handlers_utils.get_order_by(order_by_str) == expected_result @pytest.mark.parametrize( "order_by_str", ( "-", "9", "foo^", "--foo", "foo,bar*", "99, foo", ), ) def test_get_order_by_failure(order_by_str: str) -> None: """Test get_order_by helper raising exception.""" with pytest.raises(ValidationError): handlers_utils.get_order_by(order_by_str)