"""Test JSON schema.""" import copy from jsonschema import Draft3Validator import pytest from backend.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 our example. Returns: data (dict) """ data = { 'correlation_id': '123456678786485', 'account_type': 'vendor', 'account_id': '24', 'code': 'ABC123' } return data def test_json_schema_validate_success( monkeypatch, example_schema, example_data_to_validate): """Test general use case successful validation returns correct format.""" response = json_schema.validate( data=example_data_to_validate, validator=Draft3Validator(example_schema)) assert response.status == 200 def test_json_schema_validate_error( monkeypatch, example_schema, example_data_to_validate): """Test that the general use case 'fail' validation response is delivered. Our desired response.Response message format { field_name: error_message }. """ 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' response = json_schema.validate( data=mutated_data, validator=Draft3Validator(example_schema)) errors = response.errors.get('message') assert response.status == 400 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')