"""Tests for Handler utils.""" import json import application import marshmallow import pytest from product_digital_marketing.exceptions import RequestError from product_digital_marketing.exceptions import ValidationError from product_digital_marketing.utils import handlers as handlers_utils class _TestSchema(marshmallow.Schema): name = marshmallow.fields.Str(required=True) def test_parse_request_json(client_headers): """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 @pytest.mark.parametrize('data', [ b'true', b'null', b'\'\'', b'[]', b'', b'{"items": [}']) def test_parse_request_json_invalid_data(client_headers, data): """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(): """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): """Test schema validator returns error.""" request_data = {} with application.app.test_request_context( headers=client_headers, data=json.dumps(request_data)): with pytest.raises(ValidationError): handlers_utils.parse_request_json(schema=_TestSchema) def test_parse_request_no_schema(client_headers): """Test schema validator pass with no schema specified.""" request_data = {} with application.app.test_request_context( headers=client_headers, data=json.dumps(request_data)): handlers_utils.parse_request_json()