Documentation
¶
Overview ¶
Package validator provides OpenAPI response validation functionality
Index ¶
- type DiffType
- type FieldDiff
- type OpenAPIValidator
- func (v *OpenAPIValidator) CompareResponses(previous, current *Response) ([]FieldDiff, error)
- func (v *OpenAPIValidator) GetValidationMode() ValidationMode
- func (v *OpenAPIValidator) LoadSpec(specFile string) (*spec.Swagger, error)
- func (v *OpenAPIValidator) SetValidationMode(mode ValidationMode)
- func (v *OpenAPIValidator) ValidateResponse(response *Response, operation *spec.Operation) (*ValidationResult, error)
- type Response
- type Severity
- type ValidationError
- type ValidationMode
- type ValidationResult
- type ValidationWarning
- type Validator
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type FieldDiff ¶
type FieldDiff struct {
Path string `json:"path"`
Type DiffType `json:"type"`
OldValue interface{} `json:"old_value,omitempty"`
NewValue interface{} `json:"new_value,omitempty"`
Severity Severity `json:"severity"`
}
FieldDiff represents a difference in a field
type OpenAPIValidator ¶
type OpenAPIValidator struct {
// contains filtered or unexported fields
}
OpenAPIValidator implements the Validator interface
func (*OpenAPIValidator) CompareResponses ¶
func (v *OpenAPIValidator) CompareResponses(previous, current *Response) ([]FieldDiff, error)
CompareResponses compares two responses and detects differences
func (*OpenAPIValidator) GetValidationMode ¶
func (v *OpenAPIValidator) GetValidationMode() ValidationMode
GetValidationMode returns the current validation mode
func (*OpenAPIValidator) LoadSpec ¶
func (v *OpenAPIValidator) LoadSpec(specFile string) (*spec.Swagger, error)
LoadSpec loads an OpenAPI specification from a file
func (*OpenAPIValidator) SetValidationMode ¶
func (v *OpenAPIValidator) SetValidationMode(mode ValidationMode)
SetValidationMode sets the validation mode (strict or lenient)
func (*OpenAPIValidator) ValidateResponse ¶
func (v *OpenAPIValidator) ValidateResponse(response *Response, operation *spec.Operation) (*ValidationResult, error)
ValidateResponse validates an HTTP response against an OpenAPI operation
type Response ¶
type Response struct {
Headers http.Header `json:"headers"`
Body []byte `json:"body"`
StatusCode int `json:"status_code"`
}
Response represents an HTTP response for validation
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"`
Message string `json:"message"`
Type string `json:"type"`
Path string `json:"path"`
}
ValidationError represents a validation error
type ValidationMode ¶
type ValidationMode string
ValidationMode defines the validation strictness
const ( ValidationModeStrict ValidationMode = "strict" ValidationModeLenient ValidationMode = "lenient" )
type ValidationResult ¶
type ValidationResult struct {
Errors []ValidationError `json:"errors,omitempty"`
Warnings []ValidationWarning `json:"warnings,omitempty"`
FieldDiffs []FieldDiff `json:"field_diffs,omitempty"`
Valid bool `json:"valid"`
}
ValidationResult represents the result of response validation
type ValidationWarning ¶
type ValidationWarning struct {
Field string `json:"field"`
Message string `json:"message"`
Type string `json:"type"`
Path string `json:"path"`
}
ValidationWarning represents a validation warning
type Validator ¶
type Validator interface {
ValidateResponse(response *Response, operation *spec.Operation) (*ValidationResult, error)
LoadSpec(specFile string) (*spec.Swagger, error)
SetValidationMode(mode ValidationMode)
GetValidationMode() ValidationMode
CompareResponses(previous, current *Response) ([]FieldDiff, error)
}
Validator defines the interface for response validation
Example (Basic) ¶
// Create a new validator
validator := NewValidator()
// Load an OpenAPI specification
specPath := filepath.Join("testdata", "simple-api.json")
swagger, err := validator.LoadSpec(specPath)
if err != nil {
fmt.Printf("Error loading spec: %v\n", err)
return
}
// Get an operation from the spec
operation := swagger.Paths.Paths["/users"].Get
// Create a response to validate
response := &Response{
StatusCode: 200,
Headers: http.Header{},
Body: []byte(`[{"id": 1, "name": "John Doe", "email": "john@example.com"}]`),
}
// Validate the response
result, err := validator.ValidateResponse(response, operation)
if err != nil {
fmt.Printf("Validation error: %v\n", err)
return
}
fmt.Printf("Valid: %t\n", result.Valid)
fmt.Printf("Errors: %d\n", len(result.Errors))
fmt.Printf("Warnings: %d\n", len(result.Warnings))
Output: Valid: true Errors: 0 Warnings: 0
Example (CompareResponses) ¶
validator := NewValidator()
// Previous API response
previous := &Response{
StatusCode: 200,
Body: []byte(`{"id": 1, "name": "John", "age": 30}`),
}
// Current API response with changes
current := &Response{
StatusCode: 200,
Body: []byte(`{"id": 1, "name": "Jane", "email": "jane@example.com"}`),
}
diffs, _ := validator.CompareResponses(previous, current)
fmt.Printf("Found %d differences\n", len(diffs))
// Count different types of changes
var modified, removed, added int
for _, diff := range diffs {
switch diff.Type {
case DiffTypeModified:
modified++
case DiffTypeRemoved:
removed++
case DiffTypeAdded:
added++
}
}
fmt.Printf("Modified: %d, Removed: %d, Added: %d\n", modified, removed, added)
Output: Found 3 differences Modified: 1, Removed: 1, Added: 1
Example (LenientMode) ¶
validator := NewValidator()
validator.SetValidationMode(ValidationModeLenient)
// Load spec and get operation
specPath := filepath.Join("testdata", "simple-api.json")
swagger, _ := validator.LoadSpec(specPath)
operation := swagger.Paths.Paths["/users"].Get
// Response with additional fields not in spec
response := &Response{
StatusCode: 200,
Headers: http.Header{},
Body: []byte(`[{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"phone": "+1234567890",
"address": "123 Main St"
}]`),
}
result, _ := validator.ValidateResponse(response, operation)
fmt.Printf("Valid: %t\n", result.Valid)
fmt.Printf("Field diffs: %d\n", len(result.FieldDiffs))
// Count additional fields detected
additionalFields := 0
for _, diff := range result.FieldDiffs {
if diff.Type == DiffTypeAdded {
additionalFields++
}
}
fmt.Printf("Additional fields detected: %d\n", additionalFields)
Output: Valid: true Field diffs: 2 Additional fields detected: 2
Example (StrictMode) ¶
validator := NewValidator()
validator.SetValidationMode(ValidationModeStrict)
// Create a simple operation that only defines 200 response
operation := &spec.Operation{
OperationProps: spec.OperationProps{
Responses: &spec.Responses{
ResponsesProps: spec.ResponsesProps{
StatusCodeResponses: map[int]spec.Response{
200: {
ResponseProps: spec.ResponseProps{
Description: "Success",
},
},
},
},
},
},
}
// Response with undefined status code
response := &Response{
StatusCode: 404,
Headers: http.Header{},
Body: []byte(`{"error": "Not found"}`),
}
result, _ := validator.ValidateResponse(response, operation)
fmt.Printf("Valid: %t\n", result.Valid)
fmt.Printf("Has errors: %t\n", len(result.Errors) > 0)
if len(result.Errors) > 0 {
fmt.Printf("Error type: %s\n", result.Errors[0].Type)
}
Output: Valid: false Has errors: true Error type: undefined_status_code