slfs1991slfs's picture
Add files using upload-large-folder tool
24db4f6 verified
Raw History Blame Contribute Delete
20.9 kB
#!/bin/bash
# Oracle solution: API Contract Validator CLI Tool
set -e
echo "=== Creating API Contract Validator CLI Tool ==="
cat > /app/apivalidator << 'PYTHON_EOF'
#!/usr/bin/env python3
"""
API Contract Validator CLI Tool
Validates API endpoints against OpenAPI/Swagger specifications.
"""
import argparse
import json
import sys
import time
from pathlib import Path
from typing import Dict, List, Any, Optional
from urllib.parse import urljoin
try:
import requests
except ImportError:
print("Error: 'requests' library is required. Install with: pip install requests", file=sys.stderr)
sys.exit(1)
try:
import yaml
except ImportError:
print("Error: 'pyyaml' library is required. Install with: pip install pyyaml", file=sys.stderr)
sys.exit(1)
try:
import jsonschema
from jsonschema import validate, ValidationError
except ImportError:
print("Error: 'jsonschema' library is required. Install with: pip install jsonschema", file=sys.stderr)
sys.exit(1)
class APIContractValidator:
"""Main API contract validator class."""
def __init__(self, spec_file: Path, base_url: str, output_file: Path,
format_type: str = "json", endpoints: List[str] = None,
methods: List[str] = None, timeout: int = 10,
auth_token: Optional[str] = None,
validate_request: bool = False,
validate_response: bool = True,
generate_tests: bool = False,
verbose: bool = False):
self.spec_file = Path(spec_file)
self.base_url = base_url.rstrip('/')
self.output_file = Path(output_file)
self.format_type = format_type
self.endpoints = endpoints or []
self.methods = methods or []
self.timeout = timeout
self.auth_token = auth_token
self.validate_request = validate_request
self.validate_response = validate_response
self.generate_tests = generate_tests
self.verbose = verbose
self.spec = None
self.results = {
"summary": {
"total_endpoints": 0,
"tested_endpoints": 0,
"passed": 0,
"failed": 0,
"errors": 0,
"validation_errors": []
},
"endpoints": [],
"test_cases": []
}
def load_specification(self):
"""Load and parse OpenAPI/Swagger specification."""
if not self.spec_file.exists():
print(f"Error: Specification file '{self.spec_file}' does not exist", file=sys.stderr)
sys.exit(1)
try:
content = self.spec_file.read_text()
if self.spec_file.suffix.lower() in ['.yaml', '.yml']:
self.spec = yaml.safe_load(content)
else:
self.spec = json.loads(content)
except yaml.YAMLError as e:
print(f"Error: Invalid YAML in specification file: {e}", file=sys.stderr)
sys.exit(1)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON in specification file: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"Error: Failed to read specification file: {e}", file=sys.stderr)
sys.exit(1)
# Check OpenAPI version
if 'openapi' in self.spec:
version = self.spec['openapi']
if not version.startswith('3.0') and not version.startswith('3.1'):
print(f"Warning: OpenAPI version {version} may not be fully supported", file=sys.stderr)
elif 'swagger' in self.spec:
version = self.spec['swagger']
if not version.startswith('2.0'):
print(f"Warning: Swagger version {version} may not be fully supported", file=sys.stderr)
else:
print("Warning: Specification does not appear to be OpenAPI or Swagger", file=sys.stderr)
def get_paths(self) -> Dict[str, Dict]:
"""Extract paths from specification."""
if not self.spec or 'paths' not in self.spec:
return {}
paths = self.spec['paths']
# Filter by endpoints if specified
if self.endpoints:
filtered_paths = {}
for endpoint in self.endpoints:
if endpoint in paths:
filtered_paths[endpoint] = paths[endpoint]
return filtered_paths
return paths
def get_methods_for_path(self, path_spec: Dict) -> List[str]:
"""Get HTTP methods for a path."""
methods = []
for method in ['get', 'post', 'put', 'patch', 'delete', 'head', 'options']:
if method in path_spec:
methods.append(method.upper())
# Filter by methods if specified
if self.methods:
methods = [m for m in methods if m in [meth.upper() for meth in self.methods]]
return methods
def generate_sample_data(self, schema: Dict) -> Any:
"""Generate sample data based on JSON schema."""
if 'type' not in schema:
return None
schema_type = schema['type']
if schema_type == 'string':
if 'enum' in schema:
return schema['enum'][0]
if 'format' == 'email':
return 'test@example.com'
if 'format' == 'date':
return '2024-01-01'
return 'sample_string'
elif schema_type == 'integer':
return 42
elif schema_type == 'number':
return 3.14
elif schema_type == 'boolean':
return True
elif schema_type == 'array':
items_schema = schema.get('items', {})
return [self.generate_sample_data(items_schema)]
elif schema_type == 'object':
obj = {}
if 'properties' in schema:
for prop_name, prop_schema in schema['properties'].items():
if prop_name not in schema.get('required', []):
continue # Skip optional for simplicity
obj[prop_name] = self.generate_sample_data(prop_schema)
return obj
elif schema_type == 'null':
return None
return None
def validate_schema(self, data: Any, schema: Dict) -> List[str]:
"""Validate data against JSON schema."""
errors = []
try:
validate(instance=data, schema=schema)
except ValidationError as e:
errors.append(f"Schema validation error: {e.message}")
except Exception as e:
errors.append(f"Validation error: {str(e)}")
return errors
def test_endpoint(self, path: str, method: str, operation: Dict) -> Dict[str, Any]:
"""Test a single endpoint."""
result = {
"path": path,
"method": method,
"status": "unknown",
"status_code": None,
"response_time_ms": None,
"validations": {
"status_code": False,
"response_schema": False,
"headers": False
},
"errors": []
}
# Build URL
url = urljoin(self.base_url, path)
# Prepare request
headers = {'Content-Type': 'application/json'}
if self.auth_token:
headers['Authorization'] = f'Bearer {self.auth_token}'
# Prepare request body if needed
data = None
if method in ['POST', 'PUT', 'PATCH']:
request_body = operation.get('requestBody', {})
if request_body:
content = request_body.get('content', {})
json_content = content.get('application/json', {})
if json_content and 'schema' in json_content:
data = self.generate_sample_data(json_content['schema'])
# Make request
try:
start_time = time.time()
response = requests.request(
method=method,
url=url,
headers=headers,
json=data,
timeout=self.timeout
)
response_time = (time.time() - start_time) * 1000
result["status_code"] = response.status_code
result["response_time_ms"] = int(response_time)
# Check expected status codes
expected_statuses = list(operation.get('responses', {}).keys())
if str(response.status_code) in expected_statuses:
result["validations"]["status_code"] = True
result["status"] = "passed"
else:
result["validations"]["status_code"] = False
result["status"] = "failed"
result["errors"].append(
f"Unexpected status code {response.status_code}, expected one of: {expected_statuses}"
)
# Validate response schema if enabled
if self.validate_response and response.status_code < 400:
response_spec = operation.get('responses', {}).get(str(response.status_code), {})
content = response_spec.get('content', {})
json_content = content.get('application/json', {})
if json_content and 'schema' in json_content:
try:
response_data = response.json()
schema_errors = self.validate_schema(response_data, json_content['schema'])
if not schema_errors:
result["validations"]["response_schema"] = True
else:
result["validations"]["response_schema"] = False
result["errors"].extend(schema_errors)
except json.JSONDecodeError:
result["errors"].append("Response is not valid JSON")
except Exception as e:
result["errors"].append(f"Schema validation error: {str(e)}")
except requests.exceptions.Timeout:
result["status"] = "error"
result["errors"].append(f"Request timeout after {self.timeout} seconds")
except requests.exceptions.ConnectionError:
result["status"] = "error"
result["errors"].append("Connection error - could not reach server")
except Exception as e:
result["status"] = "error"
result["errors"].append(f"Request error: {str(e)}")
return result
def validate_contracts(self):
"""Validate all API contracts."""
paths = self.get_paths()
self.results["summary"]["total_endpoints"] = sum(
len(self.get_methods_for_path(path_spec))
for path_spec in paths.values()
)
for path, path_spec in paths.items():
methods = self.get_methods_for_path(path_spec)
for method in methods:
operation = path_spec[method.lower()]
result = self.test_endpoint(path, method, operation)
self.results["endpoints"].append(result)
self.results["summary"]["tested_endpoints"] += 1
if result["status"] == "passed":
self.results["summary"]["passed"] += 1
elif result["status"] == "failed":
self.results["summary"]["failed"] += 1
self.results["summary"]["validation_errors"].append({
"endpoint": path,
"method": method,
"status_code": result["status_code"],
"error_type": "validation",
"message": "; ".join(result["errors"]) if result["errors"] else "Validation failed"
})
else:
self.results["summary"]["errors"] += 1
# Generate test cases if requested
if self.generate_tests:
self.generate_test_cases()
def generate_test_cases(self):
"""Generate test cases for endpoints."""
paths = self.get_paths()
for path, path_spec in paths.items():
methods = self.get_methods_for_path(path_spec)
for method in methods:
operation = path_spec[method.lower()]
test_case = {
"endpoint": path,
"method": method,
"url": urljoin(self.base_url, path),
"expected_status": list(operation.get('responses', {}).keys())[0] if operation.get('responses') else "200",
"request_body": None,
"headers": {}
}
if method in ['POST', 'PUT', 'PATCH']:
request_body = operation.get('requestBody', {})
if request_body:
content = request_body.get('content', {})
json_content = content.get('application/json', {})
if json_content and 'schema' in json_content:
test_case["request_body"] = self.generate_sample_data(json_content['schema'])
if self.auth_token:
test_case["headers"]["Authorization"] = f"Bearer {self.auth_token}"
self.results["test_cases"].append(test_case)
def generate_json_output(self):
"""Generate JSON output."""
with open(self.output_file, 'w') as f:
json.dump(self.results, f, indent=2)
def generate_markdown_output(self):
"""Generate Markdown output."""
lines = ["# API Contract Validation Report\n\n"]
# Summary
summary = self.results["summary"]
lines.append("## Summary\n\n")
lines.append(f"- **Total Endpoints**: {summary['total_endpoints']}\n")
lines.append(f"- **Tested Endpoints**: {summary['tested_endpoints']}\n")
lines.append(f"- **Passed**: {summary['passed']}\n")
lines.append(f"- **Failed**: {summary['failed']}\n")
lines.append(f"- **Errors**: {summary['errors']}\n\n")
# Endpoints
if self.results["endpoints"]:
lines.append("## Endpoint Results\n\n")
for endpoint in self.results["endpoints"]:
status_icon = "✅" if endpoint["status"] == "passed" else "❌"
lines.append(f"### {status_icon} {endpoint['method']} {endpoint['path']}\n\n")
lines.append(f"- **Status**: {endpoint['status']}\n")
if endpoint["status_code"]:
lines.append(f"- **Status Code**: {endpoint['status_code']}\n")
if endpoint["response_time_ms"]:
lines.append(f"- **Response Time**: {endpoint['response_time_ms']} ms\n")
if endpoint["errors"]:
lines.append("- **Errors**:\n")
for error in endpoint["errors"]:
lines.append(f" - {error}\n")
lines.append("\n")
with open(self.output_file, 'w') as f:
f.writelines(lines)
def generate_html_output(self):
"""Generate HTML output."""
summary = self.results["summary"]
html = f"""<!DOCTYPE html>
<html>
<head>
<title>API Contract Validation Report</title>
<style>
body {{ font-family: Arial, sans-serif; margin: 20px; }}
.summary {{ background: #f5f5f5; padding: 15px; border-radius: 5px; }}
.endpoint {{ margin: 10px 0; padding: 10px; border-left: 3px solid #ccc; }}
.passed {{ border-color: #4caf50; }}
.failed {{ border-color: #f44336; }}
.error {{ border-color: #ff9800; }}
</style>
</head>
<body>
<h1>API Contract Validation Report</h1>
<div class="summary">
<h2>Summary</h2>
<p><strong>Total Endpoints:</strong> {summary['total_endpoints']}</p>
<p><strong>Tested:</strong> {summary['tested_endpoints']}</p>
<p><strong>Passed:</strong> {summary['passed']}</p>
<p><strong>Failed:</strong> {summary['failed']}</p>
<p><strong>Errors:</strong> {summary['errors']}</p>
</div>
<h2>Endpoint Results</h2>
"""
for endpoint in self.results["endpoints"]:
status_class = endpoint["status"]
html += f""" <div class="endpoint {status_class}">
<strong>{endpoint['method']} {endpoint['path']}</strong><br>
Status: {endpoint['status']}<br>
"""
if endpoint["status_code"]:
html += f" Status Code: {endpoint['status_code']}<br>\n"
if endpoint["errors"]:
html += " Errors:<ul>\n"
for error in endpoint["errors"]:
html += f" <li>{error}</li>\n"
html += " </ul>\n"
html += " </div>\n"
html += """</body>
</html>"""
with open(self.output_file, 'w') as f:
f.write(html)
def generate_output(self):
"""Generate output in specified format."""
if self.format_type == "json":
self.generate_json_output()
elif self.format_type == "markdown":
self.generate_markdown_output()
elif self.format_type == "html":
self.generate_html_output()
else:
print(f"Error: Unknown format '{self.format_type}'", file=sys.stderr)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(
description="API Contract Validator CLI Tool",
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("--spec", required=True, help="Path to OpenAPI/Swagger specification file")
parser.add_argument("--base-url", required=True, help="Base URL of the API to test")
parser.add_argument("--output", required=True, help="Output file path")
parser.add_argument("--format", choices=["json", "markdown", "html"], default="json",
help="Output format (default: json)")
parser.add_argument("--endpoints", help="Comma-separated list of endpoint paths to test")
parser.add_argument("--methods", help="Comma-separated list of HTTP methods to test")
parser.add_argument("--timeout", type=int, default=10, help="Request timeout in seconds (default: 10)")
parser.add_argument("--auth", help="Bearer token for authentication")
parser.add_argument("--validate-request", action="store_true", help="Validate request payloads")
parser.add_argument("--validate-response", action="store_true", default=True, help="Validate response payloads (default: true)")
parser.add_argument("--no-validate-response", dest="validate_response", action="store_false",
help="Disable response validation")
parser.add_argument("--generate-tests", action="store_true", help="Generate test cases")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
args = parser.parse_args()
endpoints = args.endpoints.split(',') if args.endpoints else None
methods = args.methods.split(',') if args.methods else None
validator = APIContractValidator(
spec_file=args.spec,
base_url=args.base_url,
output_file=args.output,
format_type=args.format,
endpoints=endpoints,
methods=methods,
timeout=args.timeout,
auth_token=args.auth,
validate_request=args.validate_request,
validate_response=args.validate_response,
generate_tests=args.generate_tests,
verbose=args.verbose
)
validator.load_specification()
validator.validate_contracts()
validator.generate_output()
if validator.verbose:
summary = validator.results["summary"]
print(f"Validated {summary['tested_endpoints']} endpoints", file=sys.stderr)
print(f"Passed: {summary['passed']}, Failed: {summary['failed']}, Errors: {summary['errors']}", file=sys.stderr)
print(f"Report written to {args.output}", file=sys.stderr)
# Exit with error code if there are failures
if validator.results["summary"]["failed"] > 0 or validator.results["summary"]["errors"] > 0:
sys.exit(1)
if __name__ == "__main__":
main()
PYTHON_EOF
chmod +x /app/apivalidator
echo "✓ apivalidator script created and made executable"
echo ""
echo "=== Solution complete ==="