"""Validator Tests. Testing generic validator methods. """ from jsonschema import Draft3Validator import pytest from images.validation import json_schema @pytest.fixture def schema(): """Sample schema to validate against. Returns: dict: Validation schema. """ return { 'type': 'object', 'properties': { 'string-property': {'type': 'string'}, 'numeric-property': {'type': 'number'} } } @pytest.fixture def validator(schema): """Validator instance that uses our test schema. Returns: Draft3Validator: Validator instance. """ return Draft3Validator(schema) @pytest.fixture def valid_data(): """Data that will pass validation against the test schema. Returns: dict: Valid data. """ return { 'string-property': 'this is a string', 'numeric-property': 123 } @pytest.fixture def invalid_data(): """Data that will fail validation against the test schema. Returns: dict: Invalid data. """ return { 'string-property': 79.3, 'numeric-property': 'i am a number, i swear' } @pytest.fixture def teapot_status(): """Non-success status code to use when testing validation failure. Returns: int: Status code. """ return 418 def test_validate_success(valid_data, validator): """Test status and message when data is valid.""" response = json_schema.validate(valid_data, validator) assert response.status == 200 assert response.message == {'status': 'ok'} def test_validate_failure_pass_status(invalid_data, validator, teapot_status): """Test status and errors when data is invalid and status is passed.""" response = json_schema.validate(invalid_data, validator, teapot_status) message = response.errors.get('message') assert response.status == teapot_status assert 'string-property' in message assert 'numeric-property' in message def test_validate_failure(invalid_data, validator): """Test status and errors when data is invalid and no status is passed.""" response = json_schema.validate(invalid_data, validator) message = response.errors.get('message') assert response.status == 400 assert 'string-property' in message assert 'numeric-property' in message def test_filter_strips_whitespace(): """Test that the _filter method strips whitespace from values.""" filtered_data = json_schema._filter({'thing': ' something '}) assert filtered_data == {'thing': 'something'} def test_filter_sets_empty_string_to_none(): """Test that the _filter method converts an empty string to 'none'.""" filtered_data = json_schema._filter({'thing': ''}) assert filtered_data == {'thing': None}