File size: 20,889 Bytes
24db4f6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 | #!/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 ==="
|