"""Tests for json schema.""" import copy from unittest.mock import MagicMock from jsonschema import Draft3Validator import pytest from deliveryhistory.validation import json_schema @pytest.fixture def example_schema(): """Return a JSON Draft3 Schema to use in our validator tests. Returns: schema (dict): JSON Draft3 Validation Schema """ schema = { 'properties': { 'account_type': { 'required': True, 'example': 'vendor', 'description': 'vendor | subaccount', 'type': 'string', 'pattern': '(vendor)|(subaccount)'}, 'account_id': { 'required': True, 'type': 'string', 'pattern': r'^\d+$', 'description': 'vendor_id | subaccount_id'}, 'correlation_id': { 'required': True, 'type': 'string', 'description': 'UUID'}, 'code': { 'type': 'string', 'required': True, 'maxLength': 10} }, 'additionalProperties': False, 'required': True, 'type': 'object', '$schema': 'http://json-schema.org/draft-03/schema' } return schema @pytest.fixture def example_data_to_validate(): """Return a dict that will successfully validate against example schema. Returns: data (dict) """ data = { 'correlation_id': '123456678786485', 'account_type': 'vendor', 'account_id': '24', 'code': 'ABC123' } return data @pytest.mark.parametrize('data,expected', [ ('', ''), ('\n\t ', ''), (' strip whitespace \n\t ', 'strip whitespace') ]) def test_json_schema_filter_input(data, expected): """Test json_schema.filter_input filters as expected.""" cleaned = json_schema.filter_input({'value': data}) assert cleaned['value'] == expected def test_json_schema_validate_success( monkeypatch, example_schema, example_data_to_validate): """Test general use case successful validation returns valid format.""" monkeypatch.setattr( json_schema, 'filter_input', value=MagicMock( return_value=example_data_to_validate)) response = json_schema.validate( data=example_data_to_validate, validator=Draft3Validator(example_schema)) assert response assert json_schema.filter_input.called def test_json_schema_validate_error( monkeypatch, example_schema, example_data_to_validate): """Test "fail" validation response is delivered in our desired format. Response - { field_name: error_message } pairs. """ mutated_data = copy.copy(example_data_to_validate) mutated_data.pop('correlation_id') mutated_data['account_type'] = 'banana' mutated_data['code'] = '12345678901' mutated_data['unknown_field'] = 'unknown_field_value' monkeypatch.setattr( json_schema, 'filter_input', value=MagicMock( return_value=mutated_data)) response = json_schema.validate( data=mutated_data, validator=Draft3Validator(example_schema)) errors = response.errors.get('message') assert response.status == 400 assert json_schema.filter_input.called assert 'required' in errors.get('correlation_id') assert 'match' in errors.get('account_type') assert 'long' in errors.get('code') assert 'unknown_field' in errors.get('additionalProperties')