"""Tests for json_schema decorators.""" import json import os import flask import flexmock from availability import config from availability.constants import error from availability.validation import json_schema REQUIRED_HEADER = 'Example-Header' HEADER_SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Request Header Schema', 'type': 'object', 'properties': { REQUIRED_HEADER: { 'type': 'string' } }, 'required': [REQUIRED_HEADER], 'additionalProperties': True} REQUIRED_BODY_ATTR = 'example_attribute' BODY_SCHEMA = { '$schema': 'http://json-schema.org/draft-04/schema#', 'title': 'Request Body Schema', 'type': 'object', 'properties': { REQUIRED_BODY_ATTR: { 'type': 'string' } }, 'required': [REQUIRED_BODY_ATTR], 'additionalProperties': True} VALID_RESPONSE = 'successful response' def test_validate_headers_fail(): """Assert headers validation fails when required field is missing.""" request = flexmock.flexmock(headers={}) @json_schema.validate_headers(request, HEADER_SCHEMA) def mock_handler(): pass response = mock_handler() assert isinstance(response, flask.Response) assert response.status_code == 400 response_payload = json.loads(response.data.decode()) assert response_payload['code'] == error.HEADER_VALIDATION_ERROR expected_error = "'{}' is a required property".format(REQUIRED_HEADER) assert expected_error in response_payload['message'] def test_validate_headers_success(): """Assert validation decorator calls original function if headers valid.""" valid_headers = {REQUIRED_HEADER: 'anything'} request = flexmock.flexmock(headers=valid_headers) @json_schema.validate_headers(request, HEADER_SCHEMA) def mock_handler(): return VALID_RESPONSE assert mock_handler() == VALID_RESPONSE def test_validate_body_fail(): """Assert body validation fails when required field is missing.""" fake_request = flexmock.flexmock(get_json=lambda: {}) @json_schema.validate_body(fake_request, BODY_SCHEMA) def mock_handler(): pass response = mock_handler() assert isinstance(response, flask.Response) assert response.status_code == 400 response_payload = json.loads(response.data.decode()) assert response_payload['code'] == error.BODY_VALIDATION_ERROR expected_error = "'{}' is a required property".format(REQUIRED_BODY_ATTR) assert expected_error in response_payload['message'] def test_validate_body_success(): """Assert validation decorator calls original function if body is valid.""" fake_request = flexmock.flexmock( get_json=lambda: {REQUIRED_BODY_ATTR: 'anything'}) @json_schema.validate_body(fake_request, BODY_SCHEMA) def mock_handler(): return VALID_RESPONSE assert mock_handler() == VALID_RESPONSE def test_load_schema(): """Assert can load schema by name.""" schema_name = 'header.schema.json' schema_path = os.path.join( config.BASE_DIR, '..', 'spec', schema_name) with open(schema_path) as schema_file: expected_schema = json.load(schema_file) actual_schema = json_schema.load_schema('header.schema.json') assert actual_schema == expected_schema