Removed unused files
This commit is contained in:
@@ -1,16 +0,0 @@
|
|||||||
package definition
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/url"
|
|
||||||
)
|
|
||||||
|
|
||||||
// SchemaValidator interface for schema validation.
|
|
||||||
type SchemaValidator interface {
|
|
||||||
Validate(ctx context.Context, url *url.URL, payload []byte) error
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaValidatorProvider interface for creating validators.
|
|
||||||
type SchemaValidatorProvider interface {
|
|
||||||
New(ctx context.Context, config map[string]string) (SchemaValidator, func() error, error)
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
|
|
||||||
schemaValidator "github.com/beckn/beckn-onix/pkg/plugin/implementation/schemaValidator"
|
|
||||||
)
|
|
||||||
|
|
||||||
// schemaValidatorProvider provides instances of schemaValidator.
|
|
||||||
type schemaValidatorProvider struct{}
|
|
||||||
|
|
||||||
// New initializes a new Verifier instance.
|
|
||||||
func (vp schemaValidatorProvider) New(ctx context.Context, config map[string]string) (definition.SchemaValidator, func() error, error) {
|
|
||||||
if ctx == nil {
|
|
||||||
return nil, nil, errors.New("context cannot be nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract schema_dir from the config map
|
|
||||||
schemaDir, ok := config["schema_dir"]
|
|
||||||
if !ok || schemaDir == "" {
|
|
||||||
return nil, nil, errors.New("config must contain 'schema_dir'")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new schemaValidator instance with the provided configuration
|
|
||||||
return schemaValidator.New(ctx, &schemaValidator.Config{
|
|
||||||
SchemaDir: schemaDir,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Provider is the exported symbol that the plugin manager will look for.
|
|
||||||
var Provider definition.SchemaValidatorProvider = schemaValidatorProvider{}
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupTestSchema creates a temporary directory and writes a sample schema file.
|
|
||||||
func setupTestSchema(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
// Create a temporary directory for the schema
|
|
||||||
schemaDir, err := os.MkdirTemp("", "schemas")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create temp directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the directory structure for the schema file
|
|
||||||
schemaFilePath := filepath.Join(schemaDir, "example", "1.0", "test_schema.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(schemaFilePath), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create schema directory structure: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Define a sample schema
|
|
||||||
schemaContent := `{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"context": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"domain": {"type": "string"},
|
|
||||||
"version": {"type": "string"}
|
|
||||||
},
|
|
||||||
"required": ["domain", "version"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["context"]
|
|
||||||
}`
|
|
||||||
|
|
||||||
// Write the schema to the file
|
|
||||||
if err := os.WriteFile(schemaFilePath, []byte(schemaContent), 0644); err != nil {
|
|
||||||
t.Fatalf("Failed to write schema file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return schemaDir
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestValidatorProviderSuccess tests successful ValidatorProvider implementation.
|
|
||||||
func TestValidatorProviderSuccess(t *testing.T) {
|
|
||||||
schemaDir := setupTestSchema(t)
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
// Define test cases.
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
ctx context.Context
|
|
||||||
config map[string]string
|
|
||||||
expectedError string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Valid schema directory",
|
|
||||||
ctx: context.Background(), // Valid context
|
|
||||||
config: map[string]string{"schema_dir": schemaDir},
|
|
||||||
expectedError: "",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test using table-driven tests
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
vp := schemaValidatorProvider{}
|
|
||||||
schemaValidator, close, err := vp.New(tt.ctx, tt.config)
|
|
||||||
|
|
||||||
// Ensure no error occurred
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure the schemaValidator is not nil
|
|
||||||
if schemaValidator == nil {
|
|
||||||
t.Error("expected a non-nil schemaValidator, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure the close function is not nil
|
|
||||||
if close == nil {
|
|
||||||
t.Error("expected a non-nil close function, got nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test the close function
|
|
||||||
if err := close(); err != nil {
|
|
||||||
t.Errorf("close function returned an error: %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestValidatorProviderSuccess tests cases where ValidatorProvider creation should fail.
|
|
||||||
func TestValidatorProviderFailure(t *testing.T) {
|
|
||||||
schemaDir := setupTestSchema(t)
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
// Define test cases.
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
ctx context.Context
|
|
||||||
config map[string]string
|
|
||||||
expectedError string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Config is empty",
|
|
||||||
ctx: context.Background(),
|
|
||||||
config: map[string]string{},
|
|
||||||
expectedError: "config must contain 'schema_dir'",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "schema_dir is empty",
|
|
||||||
ctx: context.Background(),
|
|
||||||
config: map[string]string{"schema_dir": ""},
|
|
||||||
expectedError: "config must contain 'schema_dir'",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Invalid schema directory",
|
|
||||||
ctx: context.Background(), // Valid context
|
|
||||||
config: map[string]string{"schema_dir": "/invalid/dir"},
|
|
||||||
expectedError: "failed to initialise schemaValidator: schema directory does not exist: /invalid/dir",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Nil context",
|
|
||||||
ctx: nil, // Nil context
|
|
||||||
config: map[string]string{"schema_dir": schemaDir},
|
|
||||||
expectedError: "context cannot be nil",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test using table-driven tests
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
vp := schemaValidatorProvider{}
|
|
||||||
_, _, err := vp.New(tt.ctx, tt.config)
|
|
||||||
|
|
||||||
// Check for expected error
|
|
||||||
if tt.expectedError != "" {
|
|
||||||
if err == nil || !strings.Contains(err.Error(), tt.expectedError) {
|
|
||||||
t.Errorf("expected error %q, got %v", tt.expectedError, err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure no error occurred
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("unexpected error: %v", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,202 +0,0 @@
|
|||||||
package schemaValidator
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
response "github.com/beckn/beckn-onix/pkg/response"
|
|
||||||
|
|
||||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Payload represents the structure of the data payload with context information.
|
|
||||||
type payload struct {
|
|
||||||
Context struct {
|
|
||||||
Domain string `json:"domain"`
|
|
||||||
Version string `json:"version"`
|
|
||||||
} `json:"context"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// SchemaValidator implements the Validator interface.
|
|
||||||
type SchemaValidator struct {
|
|
||||||
config *Config
|
|
||||||
schemaCache map[string]*jsonschema.Schema
|
|
||||||
}
|
|
||||||
|
|
||||||
// Config struct for SchemaValidator.
|
|
||||||
type Config struct {
|
|
||||||
SchemaDir string
|
|
||||||
}
|
|
||||||
|
|
||||||
// New creates a new ValidatorProvider instance.
|
|
||||||
func New(ctx context.Context, config *Config) (*SchemaValidator, func() error, error) {
|
|
||||||
// Check if config is nil
|
|
||||||
if config == nil {
|
|
||||||
return nil, nil, fmt.Errorf("config cannot be nil")
|
|
||||||
}
|
|
||||||
v := &SchemaValidator{
|
|
||||||
config: config,
|
|
||||||
schemaCache: make(map[string]*jsonschema.Schema),
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call Initialise function to load schemas and get validators
|
|
||||||
if err := v.initialise(); err != nil {
|
|
||||||
return nil, nil, fmt.Errorf("failed to initialise schemaValidator: %v", err)
|
|
||||||
}
|
|
||||||
return v, v.Close, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate validates the given data against the schema.
|
|
||||||
func (v *SchemaValidator) Validate(ctx context.Context, url *url.URL, data []byte) error {
|
|
||||||
var payloadData payload
|
|
||||||
err := json.Unmarshal(data, &payloadData)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to parse JSON payload: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract domain, version, and endpoint from the payload and uri.
|
|
||||||
cxt_domain := payloadData.Context.Domain
|
|
||||||
version := payloadData.Context.Version
|
|
||||||
version = fmt.Sprintf("v%s", version)
|
|
||||||
|
|
||||||
endpoint := path.Base(url.String())
|
|
||||||
// ToDo Add debug log here
|
|
||||||
fmt.Println("Handling request for endpoint:", endpoint)
|
|
||||||
domain := strings.ToLower(cxt_domain)
|
|
||||||
domain = strings.ReplaceAll(domain, ":", "_")
|
|
||||||
|
|
||||||
// Construct the schema file name.
|
|
||||||
schemaFileName := fmt.Sprintf("%s_%s_%s", domain, version, endpoint)
|
|
||||||
|
|
||||||
// Retrieve the schema from the cache.
|
|
||||||
schema, exists := v.schemaCache[schemaFileName]
|
|
||||||
if !exists {
|
|
||||||
return fmt.Errorf("schema not found for domain: %s", schemaFileName)
|
|
||||||
}
|
|
||||||
|
|
||||||
var jsonData any
|
|
||||||
if err := json.Unmarshal(data, &jsonData); err != nil {
|
|
||||||
return fmt.Errorf("failed to parse JSON data: %v", err)
|
|
||||||
}
|
|
||||||
err = schema.Validate(jsonData)
|
|
||||||
if err != nil {
|
|
||||||
// Handle schema validation errors
|
|
||||||
if validationErr, ok := err.(*jsonschema.ValidationError); ok {
|
|
||||||
// Convert validation errors into an array of SchemaValError
|
|
||||||
var schemaErrors []response.Error
|
|
||||||
for _, cause := range validationErr.Causes {
|
|
||||||
// Extract the path and message from the validation error
|
|
||||||
path := strings.Join(cause.InstanceLocation, ".") // JSON path to the invalid field
|
|
||||||
message := cause.Error() // Validation error message
|
|
||||||
|
|
||||||
// Append the error to the schemaErrors array
|
|
||||||
schemaErrors = append(schemaErrors, response.Error{
|
|
||||||
Paths: path,
|
|
||||||
Message: message,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
// Return the array of schema validation errors
|
|
||||||
return &response.SchemaValidationErr{Errors: schemaErrors}
|
|
||||||
}
|
|
||||||
// Return a generic error for non-validation errors
|
|
||||||
return fmt.Errorf("validation failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return nil if validation succeeds
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidatorProvider provides instances of Validator.
|
|
||||||
type ValidatorProvider struct{}
|
|
||||||
|
|
||||||
// Initialise initialises the validator provider by compiling all the JSON schema files
|
|
||||||
// from the specified directory and storing them in a cache indexed by their schema filenames.
|
|
||||||
func (v *SchemaValidator) initialise() error {
|
|
||||||
schemaDir := v.config.SchemaDir
|
|
||||||
// Check if the directory exists and is accessible.
|
|
||||||
info, err := os.Stat(schemaDir)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return fmt.Errorf("schema directory does not exist: %s", schemaDir)
|
|
||||||
}
|
|
||||||
return fmt.Errorf("failed to access schema directory: %v", err)
|
|
||||||
}
|
|
||||||
if !info.IsDir() {
|
|
||||||
return fmt.Errorf("provided schema path is not a directory: %s", schemaDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
compiler := jsonschema.NewCompiler()
|
|
||||||
|
|
||||||
// Helper function to process directories recursively.
|
|
||||||
var processDir func(dir string) error
|
|
||||||
processDir = func(dir string) error {
|
|
||||||
entries, err := os.ReadDir(dir)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to read directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, entry := range entries {
|
|
||||||
path := filepath.Join(dir, entry.Name())
|
|
||||||
if entry.IsDir() {
|
|
||||||
// Recursively process subdirectories.
|
|
||||||
if err := processDir(path); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else if filepath.Ext(entry.Name()) == ".json" {
|
|
||||||
// Process JSON files.
|
|
||||||
compiledSchema, err := compiler.Compile(path)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to compile JSON schema from file %s: %v", entry.Name(), err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use relative path from schemaDir to avoid absolute paths and make schema keys domain/version specific.
|
|
||||||
relativePath, err := filepath.Rel(schemaDir, path)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to get relative path for file %s: %v", entry.Name(), err)
|
|
||||||
}
|
|
||||||
// Split the relative path to get domain, version, and schema.
|
|
||||||
parts := strings.Split(relativePath, string(os.PathSeparator))
|
|
||||||
|
|
||||||
// Ensure that the file path has at least 3 parts: domain, version, and schema file.
|
|
||||||
if len(parts) < 3 {
|
|
||||||
return fmt.Errorf("invalid schema file structure, expected domain/version/schema.json but got: %s", relativePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract domain, version, and schema filename from the parts.
|
|
||||||
// Validate that the extracted parts are non-empty.
|
|
||||||
domain := strings.TrimSpace(parts[0])
|
|
||||||
version := strings.TrimSpace(parts[1])
|
|
||||||
schemaFileName := strings.TrimSpace(parts[2])
|
|
||||||
schemaFileName = strings.TrimSuffix(schemaFileName, ".json")
|
|
||||||
|
|
||||||
if domain == "" || version == "" || schemaFileName == "" {
|
|
||||||
return fmt.Errorf("invalid schema file structure, one or more components are empty. Relative path: %s", relativePath)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Construct a unique key combining domain, version, and schema name (e.g., ondc_trv10_v2.0.0_schema).
|
|
||||||
uniqueKey := fmt.Sprintf("%s_%s_%s", domain, version, schemaFileName)
|
|
||||||
// Store the compiled schema in the SchemaCache using the unique key.
|
|
||||||
v.schemaCache[uniqueKey] = compiledSchema
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start processing from the root schema directory.
|
|
||||||
if err := processDir(schemaDir); err != nil {
|
|
||||||
return fmt.Errorf("failed to read schema directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Close releases resources (mock implementation returning nil).
|
|
||||||
func (v *SchemaValidator) Close() error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,369 +0,0 @@
|
|||||||
package schemaValidator
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
|
||||||
)
|
|
||||||
|
|
||||||
// setupTestSchema creates a temporary directory and writes a sample schema file.
|
|
||||||
func setupTestSchema(t *testing.T) string {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
// Create a temporary directory for the schema
|
|
||||||
schemaDir, err := os.MkdirTemp("", "schemas")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create temp directory: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create the directory structure for the schema file
|
|
||||||
schemaFilePath := filepath.Join(schemaDir, "example", "v1.0", "endpoint.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(schemaFilePath), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create schema directory structure: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Define a sample schema
|
|
||||||
schemaContent := `{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"context": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"domain": {"type": "string"},
|
|
||||||
"version": {"type": "string"},
|
|
||||||
"action": {"type": "string"}
|
|
||||||
},
|
|
||||||
"required": ["domain", "version", "action"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["context"]
|
|
||||||
}`
|
|
||||||
|
|
||||||
// Write the schema to the file
|
|
||||||
if err := os.WriteFile(schemaFilePath, []byte(schemaContent), 0644); err != nil {
|
|
||||||
t.Fatalf("Failed to write schema file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return schemaDir
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidator_Validate_Success(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
url string
|
|
||||||
payload string
|
|
||||||
wantErr bool
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Valid payload",
|
|
||||||
url: "http://example.com/endpoint",
|
|
||||||
payload: `{"context": {"domain": "example", "version": "1.0", "action": "endpoint"}}`,
|
|
||||||
wantErr: false,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Setup a temporary schema directory for testing
|
|
||||||
schemaDir := setupTestSchema(t)
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
config := &Config{SchemaDir: schemaDir}
|
|
||||||
v, _, err := New(context.Background(), config)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create validator: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
u, _ := url.Parse(tt.url)
|
|
||||||
err := v.Validate(context.Background(), u, []byte(tt.payload))
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("Unexpected error: %v", err)
|
|
||||||
} else {
|
|
||||||
t.Logf("Test %s passed with no errors", tt.name)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidator_Validate_Failure(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
url string
|
|
||||||
payload string
|
|
||||||
wantErr string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Invalid JSON payload",
|
|
||||||
url: "http://example.com/endpoint",
|
|
||||||
payload: `{"context": {"domain": "example", "version": "1.0"`,
|
|
||||||
wantErr: "failed to parse JSON payload",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Schema validation failure",
|
|
||||||
url: "http://example.com/endpoint",
|
|
||||||
payload: `{"context": {"domain": "example", "version": "1.0"}}`,
|
|
||||||
wantErr: "context: at '/context': missing property 'action'",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Schema not found",
|
|
||||||
url: "http://example.com/unknown_endpoint",
|
|
||||||
payload: `{"context": {"domain": "example", "version": "1.0"}}`,
|
|
||||||
wantErr: "schema not found for domain",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Setup a temporary schema directory for testing
|
|
||||||
schemaDir := setupTestSchema(t)
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
config := &Config{SchemaDir: schemaDir}
|
|
||||||
v, _, err := New(context.Background(), config)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Failed to create validator: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
u, _ := url.Parse(tt.url)
|
|
||||||
err := v.Validate(context.Background(), u, []byte(tt.payload))
|
|
||||||
if tt.wantErr != "" {
|
|
||||||
if err == nil {
|
|
||||||
t.Errorf("Expected error containing '%s', but got nil", tt.wantErr)
|
|
||||||
} else if !strings.Contains(err.Error(), tt.wantErr) {
|
|
||||||
t.Errorf("Expected error containing '%s', but got '%v'", tt.wantErr, err)
|
|
||||||
} else {
|
|
||||||
t.Logf("Test %s passed with expected error: %v", tt.name, err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("Unexpected error: %v", err)
|
|
||||||
} else {
|
|
||||||
t.Logf("Test %s passed with no errors", tt.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidator_Initialise(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
setupFunc func(schemaDir string) error
|
|
||||||
wantErr string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Schema directory does not exist",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Do not create the schema directory
|
|
||||||
return nil
|
|
||||||
|
|
||||||
},
|
|
||||||
wantErr: "schema directory does not exist",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Schema path is not a directory",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create a file instead of a directory
|
|
||||||
return os.WriteFile(schemaDir, []byte{}, 0644)
|
|
||||||
},
|
|
||||||
wantErr: "provided schema path is not a directory",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Invalid schema file structure",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create an invalid schema file structure
|
|
||||||
invalidSchemaFile := filepath.Join(schemaDir, "invalid_schema.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
return os.WriteFile(invalidSchemaFile, []byte(`{}`), 0644)
|
|
||||||
},
|
|
||||||
wantErr: "invalid schema file structure",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Failed to compile JSON schema",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create a schema file with invalid JSON
|
|
||||||
invalidSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
return os.WriteFile(invalidSchemaFile, []byte(`{invalid json}`), 0644)
|
|
||||||
},
|
|
||||||
wantErr: "failed to compile JSON schema",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Invalid schema file structure with empty components",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create a schema file with empty domain, version, or schema name
|
|
||||||
invalidSchemaFile := filepath.Join(schemaDir, "", "1.0", "endpoint.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
return os.WriteFile(invalidSchemaFile, []byte(`{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"context": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"domain": {"type": "string"},
|
|
||||||
"version": {"type": "string"}
|
|
||||||
},
|
|
||||||
"required": ["domain", "version"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["context"]
|
|
||||||
}`), 0644)
|
|
||||||
},
|
|
||||||
wantErr: "failed to read schema directory: invalid schema file structure, expected domain/version/schema.json but got: 1.0/endpoint.json",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Failed to read directory",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create a directory and remove read permissions
|
|
||||||
if err := os.MkdirAll(schemaDir, 0000); err != nil {
|
|
||||||
t.Fatalf("Failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
wantErr: "failed to read directory",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "Valid schema directory",
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Create a valid schema file
|
|
||||||
validSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json")
|
|
||||||
if err := os.MkdirAll(filepath.Dir(validSchemaFile), 0755); err != nil {
|
|
||||||
t.Fatalf("Failed to create directory: %v", err)
|
|
||||||
}
|
|
||||||
return os.WriteFile(validSchemaFile, []byte(`{
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"context": {
|
|
||||||
"type": "object",
|
|
||||||
"properties": {
|
|
||||||
"domain": {"type": "string"},
|
|
||||||
"version": {"type": "string"}
|
|
||||||
},
|
|
||||||
"required": ["domain", "version"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"required": ["context"]
|
|
||||||
}`), 0644)
|
|
||||||
},
|
|
||||||
wantErr: "",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
// Setup a temporary schema directory for testing
|
|
||||||
schemaDir := filepath.Join(os.TempDir(), "schemas")
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
// Run the setup function to prepare the test case
|
|
||||||
if err := tt.setupFunc(schemaDir); err != nil {
|
|
||||||
t.Fatalf("setupFunc() error = %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
config := &Config{SchemaDir: schemaDir}
|
|
||||||
v := &SchemaValidator{
|
|
||||||
config: config,
|
|
||||||
schemaCache: make(map[string]*jsonschema.Schema),
|
|
||||||
}
|
|
||||||
|
|
||||||
err := v.initialise()
|
|
||||||
if (err != nil && !strings.Contains(err.Error(), tt.wantErr)) || (err == nil && tt.wantErr != "") {
|
|
||||||
t.Errorf("Error: initialise() returned error = %v, expected error = %v", err, tt.wantErr)
|
|
||||||
} else if err == nil {
|
|
||||||
t.Logf("Test %s passed: validator initialized successfully", tt.name)
|
|
||||||
} else {
|
|
||||||
t.Logf("Test %s passed with expected error: %v", tt.name, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidator_New_Success(t *testing.T) {
|
|
||||||
schemaDir := setupTestSchema(t)
|
|
||||||
defer os.RemoveAll(schemaDir)
|
|
||||||
|
|
||||||
config := &Config{SchemaDir: schemaDir}
|
|
||||||
_, _, err := New(context.Background(), config)
|
|
||||||
if err != nil {
|
|
||||||
t.Errorf("Unexpected error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidator_New_Failure(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
config *Config
|
|
||||||
setupFunc func(schemaDir string) error
|
|
||||||
wantErr string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "Config is nil",
|
|
||||||
config: nil,
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
wantErr: "config cannot be nil",
|
|
||||||
},
|
|
||||||
// {
|
|
||||||
// name: "Config is empty",
|
|
||||||
// config: &Config{},
|
|
||||||
// setupFunc: func(schemaDir string) error {
|
|
||||||
// return nil
|
|
||||||
// },
|
|
||||||
// wantErr: "config must contain 'schema_dir'",
|
|
||||||
// },
|
|
||||||
// {
|
|
||||||
// name: "schema_dir is empty",
|
|
||||||
// config: &Config{SchemaDir: ""},
|
|
||||||
// setupFunc: func(schemaDir string) error {
|
|
||||||
// return nil
|
|
||||||
// },
|
|
||||||
// wantErr: "config must contain 'schema_dir'",
|
|
||||||
// },
|
|
||||||
{
|
|
||||||
name: "Failed to initialise validators",
|
|
||||||
config: &Config{
|
|
||||||
SchemaDir: "/invalid/path",
|
|
||||||
},
|
|
||||||
setupFunc: func(schemaDir string) error {
|
|
||||||
// Do not create the schema directory
|
|
||||||
return nil
|
|
||||||
},
|
|
||||||
wantErr: "ailed to initialise schemaValidator: schema directory does not exist: /invalid/path",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
// Run the setup function if provided
|
|
||||||
if tt.setupFunc != nil {
|
|
||||||
schemaDir := ""
|
|
||||||
if tt.config != nil {
|
|
||||||
schemaDir = tt.config.SchemaDir
|
|
||||||
}
|
|
||||||
if err := tt.setupFunc(schemaDir); err != nil {
|
|
||||||
t.Fatalf("Setup function failed: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call the New function with the test config
|
|
||||||
_, _, err := New(context.Background(), tt.config)
|
|
||||||
if (err != nil && !strings.Contains(err.Error(), tt.wantErr)) || (err == nil && tt.wantErr != "") {
|
|
||||||
t.Errorf("Error: New() returned error = %v, expected error = %v", err, tt.wantErr)
|
|
||||||
} else {
|
|
||||||
t.Logf("Test %s passed with expected error: %v", tt.name, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,7 +18,6 @@ type Config struct {
|
|||||||
Decrypter PluginConfig `yaml:"decrypter"`
|
Decrypter PluginConfig `yaml:"decrypter"`
|
||||||
Encrypter PluginConfig `yaml:"encrypter"`
|
Encrypter PluginConfig `yaml:"encrypter"`
|
||||||
Publisher PluginConfig `yaml:"publisher"`
|
Publisher PluginConfig `yaml:"publisher"`
|
||||||
SchemaValidator PluginConfig `yaml:"schemaValidator"`
|
|
||||||
Router PluginConfig `yaml:"router"`
|
Router PluginConfig `yaml:"router"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -28,11 +27,6 @@ type PluginConfig struct {
|
|||||||
Config map[string]string `yaml:"config"`
|
Config map[string]string `yaml:"config"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SchemaDetails contains information about the plugin schema directory.
|
|
||||||
type SchemaDetails struct {
|
|
||||||
SchemaDir string `yaml:"schemaDir"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Manager handles dynamic plugin loading and management.
|
// Manager handles dynamic plugin loading and management.
|
||||||
type Manager struct {
|
type Manager struct {
|
||||||
sp definition.SignerProvider
|
sp definition.SignerProvider
|
||||||
@@ -40,7 +34,6 @@ type Manager struct {
|
|||||||
dp definition.DecrypterProvider
|
dp definition.DecrypterProvider
|
||||||
ep definition.EncrypterProvider
|
ep definition.EncrypterProvider
|
||||||
pb definition.PublisherProvider
|
pb definition.PublisherProvider
|
||||||
svp definition.SchemaValidatorProvider
|
|
||||||
rp definition.RouterProvider
|
rp definition.RouterProvider
|
||||||
cfg *Config
|
cfg *Config
|
||||||
}
|
}
|
||||||
@@ -87,13 +80,7 @@ func NewManager(ctx context.Context, cfg *Config) (*Manager, error) {
|
|||||||
return nil, fmt.Errorf("failed to load encryption plugin: %w", err)
|
return nil, fmt.Errorf("failed to load encryption plugin: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load schema validator plugin
|
return &Manager{sp: sp, vp: vp, pb: pb, ep: ep, dp: dp, rp: rp, cfg: cfg}, nil
|
||||||
svp, err := provider[definition.SchemaValidatorProvider](cfg.Root, cfg.SchemaValidator.ID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to load validator plugin: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return &Manager{sp: sp, vp: vp, pb: pb, ep: ep, dp: dp, rp: rp, svp: svp, cfg: cfg}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// provider loads a plugin dynamically and retrieves its provider instance.
|
// provider loads a plugin dynamically and retrieves its provider instance.
|
||||||
@@ -191,20 +178,6 @@ func (m *Manager) Publisher(ctx context.Context) (definition.Publisher, error) {
|
|||||||
return publisher, nil
|
return publisher, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SchemaValidator retrieves the validation plugin instances.
|
|
||||||
func (m *Manager) SchemaValidator(ctx context.Context) (definition.SchemaValidator, func() error, error) {
|
|
||||||
if m.svp == nil {
|
|
||||||
return nil, nil, fmt.Errorf("schema validator plugin provider not loaded")
|
|
||||||
|
|
||||||
}
|
|
||||||
schemaValidator, close, err := m.svp.New(ctx, m.cfg.SchemaValidator.Config)
|
|
||||||
if err != nil {
|
|
||||||
|
|
||||||
return nil, nil, fmt.Errorf("failed to initialize schema validator: %v", err)
|
|
||||||
}
|
|
||||||
return schemaValidator, close, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Router retrieves the router plugin instances.
|
// Router retrieves the router plugin instances.
|
||||||
func (m *Manager) Router(ctx context.Context) (definition.Router, func() error, error) {
|
func (m *Manager) Router(ctx context.Context) (definition.Router, func() error, error) {
|
||||||
if m.rp == nil {
|
if m.rp == nil {
|
||||||
|
|||||||
Reference in New Issue
Block a user