-
-
Save disktnk/980d1efc3238e55581d5fad885f1ad92 to your computer and use it in GitHub Desktop.
tagged unit validation check script, this files are created by Copilot Agent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| JSON Schema validation script for shape objects. | |
| This script validates JSON objects against a JSON Schema that defines | |
| circle and square shapes using discriminated unions (oneOf). | |
| """ | |
| import json | |
| import sys | |
| from typing import Dict, Any, List, Tuple | |
| try: | |
| import jsonschema | |
| except ImportError: | |
| print("Error: jsonschema library not found. Please install it with: pip install jsonschema") | |
| sys.exit(1) | |
| def validate_json_schema_shape(data: Dict[str, Any], schema: Dict[str, Any]) -> Tuple[bool, str]: | |
| """ | |
| Validate a JSON object against the JSON Schema shape schema. | |
| Args: | |
| data: The JSON object to validate | |
| schema: The JSON Schema definition | |
| Returns: | |
| Tuple of (is_valid, error_message) | |
| """ | |
| try: | |
| # Use jsonschema library for validation | |
| jsonschema.validate(data, schema) | |
| return True, "Valid" | |
| except jsonschema.ValidationError as e: | |
| # Format the validation error for user-friendly output | |
| error_path = ".".join(str(part) for part in e.absolute_path) if e.absolute_path else "root" | |
| return False, f"Validation error at {error_path}: {e.message}" | |
| except jsonschema.SchemaError as e: | |
| return False, f"Schema error: {e.message}" | |
| except Exception as e: | |
| return False, f"Validation failed with exception: {str(e)}" | |
| def main(): | |
| """Main function to run JSON Schema validation tests.""" | |
| # JSON Schema definition (equivalent to the JTD schema) | |
| schema = { | |
| "$schema": "https://json-schema.org/draft/2020-12/schema", | |
| "type": "object", | |
| "properties": { | |
| "shape": { | |
| "type": "object", | |
| "properties": { | |
| "type": { | |
| "type": "string", | |
| "enum": ["circle", "square"] | |
| } | |
| }, | |
| "required": ["type"], | |
| "oneOf": [ | |
| { | |
| "properties": { | |
| "type": {"const": "circle"}, | |
| "radius": {"type": "number"} | |
| }, | |
| "required": ["type", "radius"], | |
| "additionalProperties": False | |
| }, | |
| { | |
| "properties": { | |
| "type": {"const": "square"}, | |
| "sideLength": {"type": "number"} | |
| }, | |
| "required": ["type", "sideLength"], | |
| "additionalProperties": False | |
| } | |
| ] | |
| } | |
| }, | |
| "required": ["shape"], | |
| "additionalProperties": False | |
| } | |
| # Test cases (same as JTD version) | |
| test_cases = [ | |
| # Valid cases | |
| ({"shape": {"type": "circle", "radius": 5}}, True, "Valid circle"), | |
| ({"shape": {"type": "square", "sideLength": 10}}, True, "Valid square"), | |
| ({"shape": {"type": "circle", "radius": 3.14}}, True, "Valid circle with float radius"), | |
| ({"shape": {"type": "square", "sideLength": 0}}, True, "Valid square with zero side length"), | |
| # Invalid cases | |
| ({"shape": {"type": "equilateral_triangle", "length": 3}}, False, "Unknown shape type"), | |
| ({"shape": {"type": "circle"}}, False, "Missing required radius"), | |
| ({"shape": {"type": "square"}}, False, "Missing required sideLength"), | |
| ({"shape": {"type": "circle", "radius": "5"}}, False, "Invalid radius type (string)"), | |
| ({"shape": {"type": "square", "sideLength": "ten"}}, False, "Invalid sideLength type (string)"), | |
| ({}, False, "Missing shape property"), | |
| ({"shape": {}}, False, "Missing type discriminator"), | |
| ({"shape": {"radius": 5}}, False, "Missing type discriminator with radius"), | |
| # Additional JSON Schema specific test cases | |
| ({"shape": {"type": "circle", "radius": 5}, "extra": "field"}, False, "Additional property not allowed"), | |
| ({"shape": {"type": "circle", "radius": 5, "extra": "field"}}, False, "Additional property in shape not allowed"), | |
| ] | |
| print("JSON Schema Shape Validation Test Results") | |
| print("=" * 55) | |
| passed = 0 | |
| failed = 0 | |
| for i, (test_data, expected_valid, description) in enumerate(test_cases, 1): | |
| is_valid, error_msg = validate_json_schema_shape(test_data, schema) | |
| # Check if the result matches expectation | |
| test_passed = (is_valid == expected_valid) | |
| status = "PASS" if test_passed else "FAIL" | |
| result_icon = "✓" if test_passed else "✗" | |
| print(f"{result_icon} Test {i:2d}: {status} - {description}") | |
| print(f" Data: {json.dumps(test_data)}") | |
| print(f" Expected: {'Valid' if expected_valid else 'Invalid'}") | |
| print(f" Result: {'Valid' if is_valid else 'Invalid'}") | |
| if not is_valid: | |
| print(f" Error: {error_msg}") | |
| print() | |
| if test_passed: | |
| passed += 1 | |
| else: | |
| failed += 1 | |
| print("=" * 55) | |
| print(f"Summary: {passed} passed, {failed} failed out of {len(test_cases)} tests") | |
| # Show schema comparison | |
| print("\n" + "=" * 55) | |
| print("Schema Comparison:") | |
| print("=" * 55) | |
| print("This JSON Schema is equivalent to the following JTD schema:") | |
| print(json.dumps({ | |
| "type": "object", | |
| "properties": { | |
| "shape": { | |
| "discriminator": "type", | |
| "mapping": { | |
| "circle": { | |
| "properties": { | |
| "radius": {"type": "number"} | |
| }, | |
| "required": ["radius"] | |
| }, | |
| "square": { | |
| "properties": { | |
| "sideLength": {"type": "number"} | |
| }, | |
| "required": ["sideLength"] | |
| } | |
| } | |
| } | |
| }, | |
| "required": ["shape"] | |
| }, indent=2)) | |
| if failed > 0: | |
| sys.exit(1) | |
| else: | |
| print("\nAll tests passed! ✓") | |
| if __name__ == "__main__": | |
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| """ | |
| JSON Type Definition (JTD) validation script for shape objects. | |
| This script validates JSON objects against a JTD schema that defines | |
| circle and square shapes using discriminated unions. | |
| """ | |
| import json | |
| import sys | |
| from typing import Dict, Any, List, Tuple | |
| try: | |
| import jtd | |
| except ImportError: | |
| print("Error: jtd library not found. Please install it with: pip install jtd") | |
| sys.exit(1) | |
| def validate_jtd_shape(data: Dict[str, Any], schema: Dict[str, Any]) -> Tuple[bool, str]: | |
| """ | |
| Validate a JSON object against the JTD shape schema using the jtd library. | |
| Args: | |
| data: The JSON object to validate | |
| schema: The JTD schema definition | |
| Returns: | |
| Tuple of (is_valid, error_message) | |
| """ | |
| try: | |
| # Use JTD library for validation | |
| errors = jtd.validate(schema, data) | |
| if errors: | |
| # Format the first error for user-friendly output | |
| error = errors[0] | |
| error_path = ".".join(str(part) for part in error.instance_path) if error.instance_path else "root" | |
| return False, f"Validation error at {error_path}: {error.message}" | |
| return True, "Valid" | |
| except Exception as e: | |
| return False, f"Validation failed with exception: {str(e)}" | |
| def main(): | |
| """Main function to run JTD validation tests.""" | |
| # JTD Schema definition | |
| schema = { | |
| "type": "object", | |
| "properties": { | |
| "shape": { | |
| "discriminator": "type", | |
| "mapping": { | |
| "circle": { | |
| "properties": { | |
| "radius": {"type": "number"} | |
| }, | |
| "required": ["radius"] | |
| }, | |
| "square": { | |
| "properties": { | |
| "sideLength": {"type": "number"} | |
| }, | |
| "required": ["sideLength"] | |
| } | |
| } | |
| } | |
| }, | |
| "required": ["shape"] | |
| } | |
| # Test cases | |
| test_cases = [ | |
| # Valid cases | |
| ({"shape": {"type": "circle", "radius": 5}}, True, "Valid circle"), | |
| ({"shape": {"type": "square", "sideLength": 10}}, True, "Valid square"), | |
| ({"shape": {"type": "circle", "radius": 3.14}}, True, "Valid circle with float radius"), | |
| ({"shape": {"type": "square", "sideLength": 0}}, True, "Valid square with zero side length"), | |
| # Invalid cases | |
| ({"shape": {"type": "equilateral_triangle", "length": 3}}, False, "Unknown shape type"), | |
| ({"shape": {"type": "circle"}}, False, "Missing required radius"), | |
| ({"shape": {"type": "square"}}, False, "Missing required sideLength"), | |
| ({"shape": {"type": "circle", "radius": "5"}}, False, "Invalid radius type (string)"), | |
| ({"shape": {"type": "square", "sideLength": "ten"}}, False, "Invalid sideLength type (string)"), | |
| ({}, False, "Missing shape property"), | |
| ({"shape": {}}, False, "Missing type discriminator"), | |
| ({"shape": {"radius": 5}}, False, "Missing type discriminator with radius"), | |
| ] | |
| print("JTD Shape Validation Test Results") | |
| print("=" * 50) | |
| passed = 0 | |
| failed = 0 | |
| for i, (test_data, expected_valid, description) in enumerate(test_cases, 1): | |
| is_valid, error_msg = validate_jtd_shape(test_data, schema) | |
| # Check if the result matches expectation | |
| test_passed = (is_valid == expected_valid) | |
| status = "PASS" if test_passed else "FAIL" | |
| result_icon = "✓" if test_passed else "✗" | |
| print(f"{result_icon} Test {i:2d}: {status} - {description}") | |
| print(f" Data: {json.dumps(test_data)}") | |
| print(f" Expected: {'Valid' if expected_valid else 'Invalid'}") | |
| print(f" Result: {'Valid' if is_valid else 'Invalid'}") | |
| if not is_valid: | |
| print(f" Error: {error_msg}") | |
| print() | |
| if test_passed: | |
| passed += 1 | |
| else: | |
| failed += 1 | |
| print("=" * 50) | |
| print(f"Summary: {passed} passed, {failed} failed out of {len(test_cases)} tests") | |
| if failed > 0: | |
| sys.exit(1) | |
| else: | |
| print("All tests passed! ✓") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment