update the file structure update Initialise function , update interface and update code and write table test cases

This commit is contained in:
AshwiniK-protean
2025-03-13 07:55:54 +05:30
parent ced64648f6
commit 0488eccc3b
27 changed files with 708 additions and 808 deletions

View File

@@ -0,0 +1,31 @@
package main
import (
"context"
"beckn-onix/shared/plugin/definition"
"beckn-onix/shared/plugin/implementations/validator"
)
// ValidatorProvider provides instances of Validator.
type ValidatorProvider struct{}
// New initializes a new Verifier instance.
func (vp ValidatorProvider) New(ctx context.Context, config map[string]string) (map[string]definition.Validator, error) {
// Create a new Validator instance with the provided configuration
validators, err := validator.New(ctx, config)
if err != nil {
return nil, err
}
// Convert the map to the expected type
result := make(map[string]definition.Validator)
for key, val := range validators {
result[key] = val
}
return result, nil
}
// Provider is the exported symbol that the plugin manager will look for.
var Provider definition.ValidatorProvider = ValidatorProvider{}

View File

@@ -0,0 +1,85 @@
package main
import (
"context"
"errors"
"net/url"
"testing"
"beckn-onix/shared/plugin/definition"
)
// MockValidator is a mock implementation of the Validator interface for testing.
type MockValidator struct{}
func (m *MockValidator) Validate(ctx context.Context, u url.URL, data []byte) (bool, error) {
return true, nil
}
// Mock New function for testing
func MockNew(ctx context.Context, config map[string]string) (map[string]definition.Validator, error) {
if config["error"] == "true" {
return nil, errors.New("mock error")
}
return map[string]definition.Validator{
"validator1": &MockValidator{},
"validator2": &MockValidator{},
}, nil
}
func TestValidatorProvider_New(t *testing.T) {
tests := []struct {
name string
config map[string]string
expectedError string
expectedCount int
}{
{
name: "Successful initialization",
config: map[string]string{"some_key": "some_value"},
expectedError: "",
expectedCount: 2, // Expecting 2 mock validators
},
{
name: "Error during initialization (mock error)",
config: map[string]string{"error": "true"},
expectedError: "mock error",
expectedCount: 0,
},
{
name: "Empty config map",
config: map[string]string{},
expectedError: "",
expectedCount: 2, // Expecting 2 mock validators
},
{
name: "Non-empty config with invalid key",
config: map[string]string{"invalid_key": "invalid_value"},
expectedError: "",
expectedCount: 2, // Expecting 2 mock validators
},
}
// Using the mock New function directly for testing
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a ValidatorProvider with the mock New function
vp := &ValidatorProvider{}
validators, err := vp.New(context.Background(), tt.config)
// Check for expected error
if tt.expectedError != "" {
if err == nil || err.Error() != tt.expectedError {
t.Errorf("expected error %q, got %v", tt.expectedError, err)
}
return
}
// Check for expected number of validators
if len(validators) != tt.expectedCount {
t.Errorf("expected %d validators, got %d", tt.expectedCount, len(validators))
}
})
}
}

View File

@@ -0,0 +1,165 @@
package validator
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// Validator implements the Validator interface.
type Validator struct {
config map[string]string
schema *jsonschema.Schema
SchemaCache map[string]*jsonschema.Schema
}
// New creates a new Verifier instance.
func New(ctx context.Context, config map[string]string) (map[string]*Validator, error) {
v := &Validator{config: config}
// Call Initialise function to load schemas and get validators
validators, err := v.Initialise()
if err != nil {
return nil, fmt.Errorf("failed to initialise validators: %v", err)
}
return validators, nil
}
// 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"`
}
// ValidatorProvider provides instances of Validator.
type ValidatorProvider struct{}
// Validate validates the given data against the schema.
func (v *Validator) Validate(ctx context.Context, url url.URL, payload []byte) (bool, error) {
var payloadData Payload
err := json.Unmarshal(payload, &payloadData)
if err != nil {
return false, fmt.Errorf("failed to parse JSON payload: %v", err)
}
// Extract domain, version, and endpoint from the payload and uri
domain := payloadData.Context.Domain
version := payloadData.Context.Version
version = fmt.Sprintf("v%s", version)
endpoint := path.Base(url.String())
fmt.Println("Handling request for endpoint:", endpoint)
domain = strings.ToLower(domain)
domain = strings.ReplaceAll(domain, ":", "_")
//schemaFileName := fmt.Sprintf("%s_%s_%s", domain, version, endpoint)
var jsonData interface{}
if err := json.Unmarshal(payload, &jsonData); err != nil {
return false, err
}
err = v.schema.Validate(jsonData)
if err != nil {
// TODO: Integrate with the logging module once it is ready
return false, fmt.Errorf("Validation failed: %v", err)
}
return true, nil
}
// Initialise initialises the validator provider by compiling all the JSON schema files
// from the specified directory and storing them in a cache. It returns a map of validators
// indexed by their schema filenames.
func (v *Validator) Initialise() (map[string]*Validator, error) {
// Initialize SchemaCache as an empty Map if it's nil
if v.SchemaCache == nil {
v.SchemaCache = make(map[string]*jsonschema.Schema)
}
schemaDir := v.config["schema_dir"]
// Check if the directory exists and is accessible
info, err := os.Stat(schemaDir)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("schema directory does not exist: %s", schemaDir)
}
return nil, fmt.Errorf("failed to access schema directory: %v", err)
}
if !info.IsDir() {
return nil, fmt.Errorf("provided schema path is not a directory: %s", schemaDir)
}
// Initialize the validatorCache map to store the Validator instances associated with each schema.
validatorCache := make(map[string]*Validator)
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
// Store the corresponding validator in the validatorCache using the same unique key.
validatorCache[uniqueKey] = &Validator{schema: compiledSchema}
}
}
return nil
}
// Start processing from the root schema directory
if err := processDir(schemaDir); err != nil {
return nil, fmt.Errorf("failed to read schema directory: %v", err)
}
return validatorCache, nil
}

View File

@@ -0,0 +1,291 @@
package validator
import (
"context"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
func TestValidator_Validate(t *testing.T) {
tests := []struct {
name string
url string
payload string
wantValid bool
wantErr string
}{
{
name: "Valid payload",
url: "http://example.com/endpoint",
payload: `{"context": {"domain": "example", "version": "1.0"}}`,
wantValid: true,
wantErr: "",
},
{
name: "Invalid JSON payload",
url: "http://example.com/endpoint",
payload: `{"context": {"domain": "example", "version": "1.0"`,
wantValid: false,
wantErr: "failed to parse JSON payload",
},
{
name: "Schema validation failure",
url: "http://example.com/endpoint",
payload: `{"context": {"domain": "invalid", "version": "1.0"}}`,
wantValid: false,
wantErr: "Validation failed",
},
}
// Setup a temporary schema directory for testing
schemaDir := filepath.Join(os.TempDir(), "schemas")
defer os.RemoveAll(schemaDir)
os.MkdirAll(schemaDir, 0755)
// Create a sample schema file
schemaContent := `{
"type": "object",
"properties": {
"context": {
"type": "object",
"properties": {
"domain": {"type": "string"},
"version": {"type": "string"}
},
"required": ["domain", "version"]
}
},
"required": ["context"]
}`
schemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json")
os.MkdirAll(filepath.Dir(schemaFile), 0755)
os.WriteFile(schemaFile, []byte(schemaContent), 0644)
config := map[string]string{"schema_dir": 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)
valid, err := v["example_1.0_endpoint"].Validate(context.Background(), *u, []byte(tt.payload))
if (err != nil && !strings.Contains(err.Error(), tt.wantErr)) || (err == nil && tt.wantErr != "") {
t.Errorf("Error: Validate() returned error = %v, expected error = %v", err, tt.wantErr)
return
}
if valid != tt.wantValid {
t.Errorf("Error: Validate() returned valid = %v, expected valid = %v", valid, tt.wantValid)
} else {
t.Logf("Test %s passed: valid = %v", tt.name, valid)
}
})
}
}
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")
os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755)
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")
os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755)
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")
os.MkdirAll(filepath.Dir(invalidSchemaFile), 0755)
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: "invalid schema file structure, one or more components are empty",
},
{
name: "Failed to read directory",
setupFunc: func(schemaDir string) error {
// Create a directory and remove read permissions
os.MkdirAll(schemaDir, 0000)
return nil
},
wantErr: "failed to read directory",
},
{
name: "Failed to access schema directory",
setupFunc: func(schemaDir string) error {
// Create a directory and remove access permissions
os.MkdirAll(schemaDir, 0000)
return nil
},
wantErr: "failed to access schema directory",
},
{
name: "Valid schema directory",
setupFunc: func(schemaDir string) error {
// Create a valid schema file
validSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json")
os.MkdirAll(filepath.Dir(validSchemaFile), 0755)
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 := map[string]string{"schema_dir": schemaDir}
v := &Validator{config: config}
_, 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(t *testing.T) {
tests := []struct {
name string
config map[string]string
setupFunc func(schemaDir string) error
wantErr string
}{
{
name: "Failed to initialise validators",
config: map[string]string{
"schema_dir": "/invalid/path",
},
setupFunc: func(schemaDir string) error {
// Do not create the schema directory
return nil
},
wantErr: "failed to initialise validators",
},
{
name: "Valid initialisation",
config: map[string]string{
"schema_dir": "/valid/path",
},
setupFunc: func(schemaDir string) error {
// Create a valid schema directory and file
validSchemaFile := filepath.Join(schemaDir, "example", "1.0", "endpoint.json")
os.MkdirAll(filepath.Dir(validSchemaFile), 0755)
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 := tt.config["schema_dir"]
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)
}
_, 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 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)
}
})
}
}