Merge branch 'beckn-onix-v1.0-develop' of https://github.com/beckn/beckn-onix into feature/core

This commit is contained in:
MohitKatare-protean
2025-03-28 22:18:39 +05:30
29 changed files with 3473 additions and 323 deletions

View File

@@ -3,14 +3,22 @@ package definition
import (
"context"
"net/url"
"github.com/beckn/beckn-onix/pkg/model"
)
type Router interface {
Route(ctx context.Context, url *url.URL, body []byte) (*model.Route, error)
// Route defines the structure for the Route returned.
type Route struct {
TargetType string // "url" or "msgq" or "bap" or "bpp"
PublisherID string // For message queues
URL *url.URL // For API calls
}
// RouterProvider initializes the a new Router instance with the given config.
type RouterProvider interface {
New(ctx context.Context, cfg map[string]string) (Router, error)
New(ctx context.Context, config map[string]string) (Router, func() error, error)
}
// Router defines the interface for routing requests.
type Router interface {
// Route determines the routing destination based on the request context.
Route(ctx context.Context, url *url.URL, body []byte) (*Route, error)
}

View File

@@ -7,7 +7,7 @@ import (
// SchemaValidator interface for schema validation.
type SchemaValidator interface {
Validate(ctx context.Context, url *url.URL, reqBody []byte) error
Validate(ctx context.Context, url *url.URL, payload []byte) error
}
// SchemaValidatorProvider interface for creating validators.

View File

@@ -0,0 +1,21 @@
package main
import (
"context"
"net/http"
"strings"
requestpreprocessor "github.com/beckn/beckn-onix/pkg/plugin/implementation/requestPreProcessor"
)
type provider struct{}
func (p provider) New(ctx context.Context, c map[string]string) (func(http.Handler) http.Handler, error) {
config := &requestpreprocessor.Config{}
if contextKeysStr, ok := c["ContextKeys"]; ok {
config.ContextKeys = strings.Split(contextKeysStr, ",")
}
return requestpreprocessor.NewUUIDSetter(config)
}
var Provider = provider{}

View File

@@ -0,0 +1,85 @@
package main
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TODO: Will Split this into success and fail (two test cases)
func TestProviderNew(t *testing.T) {
testCases := []struct {
name string
config map[string]string
expectedError bool
expectedStatus int
prepareRequest func(req *http.Request)
}{
{
name: "No Config",
config: map[string]string{},
expectedError: true,
expectedStatus: http.StatusOK,
prepareRequest: func(req *http.Request) {
// Add minimal required headers.
req.Header.Set("context", "test-context")
req.Header.Set("transaction_id", "test-transaction")
},
},
{
name: "With Check Keys",
config: map[string]string{
"ContextKeys": "message_id,transaction_id",
},
expectedError: false,
expectedStatus: http.StatusOK,
prepareRequest: func(req *http.Request) {
// Add headers matching the check keys.
req.Header.Set("context", "test-context")
req.Header.Set("transaction_id", "test-transaction")
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
requestBody := `{
"context": {
"transaction_id": "abc"
}
}`
p := provider{}
middleware, err := p.New(context.Background(), tc.config)
if tc.expectedError {
assert.Error(t, err)
return
}
require.NoError(t, err)
assert.NotNil(t, middleware)
testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
req := httptest.NewRequest("POST", "/", strings.NewReader(requestBody))
req.Header.Set("Content-Type", "application/json")
if tc.prepareRequest != nil {
tc.prepareRequest(req)
}
w := httptest.NewRecorder()
middlewaredHandler := middleware(testHandler)
middlewaredHandler.ServeHTTP(w, req)
assert.Equal(t, tc.expectedStatus, w.Code, "Unexpected response status")
responseBody := w.Body.String()
t.Logf("Response Body: %s", responseBody)
})
}
}

View File

@@ -0,0 +1,105 @@
package requestpreprocessor
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"github.com/google/uuid"
)
type Config struct {
ContextKeys []string
Role string
}
type becknRequest struct {
Context map[string]any `json:"context"`
}
type contextKeyType string
const contextKey = "context"
const subscriberIDKey contextKeyType = "subscriber_id"
func NewUUIDSetter(cfg *Config) (func(http.Handler) http.Handler, error) {
if err := validateConfig(cfg); err != nil {
return nil, err
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
var req becknRequest
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
return
}
if req.Context == nil {
http.Error(w, fmt.Sprintf("%s field not found.", contextKey), http.StatusBadRequest)
return
}
var subID any
switch cfg.Role {
case "bap":
subID = req.Context["bap_id"]
case "bpp":
subID = req.Context["bpp_id"]
}
ctx := context.WithValue(r.Context(), subscriberIDKey, subID)
for _, key := range cfg.ContextKeys {
value := uuid.NewString()
updatedValue := update(req.Context, key, value)
ctx = context.WithValue(ctx, contextKeyType(key), updatedValue)
}
reqData := map[string]any{"context": req.Context}
updatedBody, _ := json.Marshal(reqData)
r.Body = io.NopCloser(bytes.NewBuffer(updatedBody))
r.ContentLength = int64(len(updatedBody))
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}, nil
}
func update(wrapper map[string]any, key string, value any) any {
field, exists := wrapper[key]
if !exists || isEmpty(field) {
wrapper[key] = value
return value
}
return field
}
func isEmpty(v any) bool {
switch v := v.(type) {
case string:
return v == ""
case nil:
return true
default:
return false
}
}
func validateConfig(cfg *Config) error {
if cfg == nil {
return errors.New("config cannot be nil")
}
// Check if ContextKeys is empty.
if len(cfg.ContextKeys) == 0 {
return errors.New("ContextKeys cannot be empty")
}
// Validate that ContextKeys does not contain empty strings.
for _, key := range cfg.ContextKeys {
if key == "" {
return errors.New("ContextKeys cannot contain empty strings")
}
}
return nil
}

View File

@@ -0,0 +1,178 @@
package requestpreprocessor
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestNewUUIDSetterSuccessCases(t *testing.T) {
tests := []struct {
name string
config *Config
requestBody map[string]any
expectedKeys []string
role string
}{
{
name: "Valid keys, update missing keys with bap role",
config: &Config{
ContextKeys: []string{"transaction_id", "message_id"},
Role: "bap",
},
requestBody: map[string]any{
"context": map[string]any{
"transaction_id": "",
"message_id": nil,
"bap_id": "bap-123",
},
},
expectedKeys: []string{"transaction_id", "message_id", "bap_id"},
role: "bap",
},
{
name: "Valid keys, do not update existing keys with bpp role",
config: &Config{
ContextKeys: []string{"transaction_id", "message_id"},
Role: "bpp",
},
requestBody: map[string]any{
"context": map[string]any{
"transaction_id": "existing-transaction",
"message_id": "existing-message",
"bpp_id": "bpp-456",
},
},
expectedKeys: []string{"transaction_id", "message_id", "bpp_id"},
role: "bpp",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
middleware, err := NewUUIDSetter(tt.config)
if err != nil {
t.Fatalf("Unexpected error while creating middleware: %v", err)
}
bodyBytes, _ := json.Marshal(tt.requestBody)
req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
w.WriteHeader(http.StatusOK)
subID, ok := ctx.Value(subscriberIDKey).(string)
if !ok {
http.Error(w, "Subscriber ID not found", http.StatusInternalServerError)
return
}
response := map[string]any{"subscriber_id": subID}
if err := json.NewEncoder(w).Encode(response); err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
})
middleware(dummyHandler).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("Expected status code 200, but got %d", rec.Code)
return
}
var responseBody map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &responseBody); err != nil {
t.Fatal("Failed to unmarshal response body:", err)
}
expectedSubIDKey := "bap_id"
if tt.role == "bpp" {
expectedSubIDKey = "bpp_id"
}
subID, ok := responseBody["subscriber_id"].(string)
if !ok {
t.Error("subscriber_id not found in response")
return
}
expectedSubID := tt.requestBody["context"].(map[string]any)[expectedSubIDKey]
if subID != expectedSubID {
t.Errorf("Expected subscriber_id %v, but got %v", expectedSubID, subID)
}
})
}
}
func TestNewUUIDSetterErrorCases(t *testing.T) {
tests := []struct {
name string
config *Config
requestBody map[string]any
expectedCode int
}{
{
name: "Missing context key",
config: &Config{
ContextKeys: []string{"transaction_id"},
},
requestBody: map[string]any{
"otherKey": "value",
},
expectedCode: http.StatusBadRequest,
},
{
name: "Invalid context type",
config: &Config{
ContextKeys: []string{"transaction_id"},
},
requestBody: map[string]any{
"context": "not-a-map",
},
expectedCode: http.StatusBadRequest,
},
{
name: "Nil config",
config: nil,
requestBody: map[string]any{},
expectedCode: http.StatusInternalServerError,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
middleware, err := NewUUIDSetter(tt.config)
if tt.config == nil {
if err == nil {
t.Error("Expected an error for nil config, but got none")
}
return
}
if err != nil {
t.Fatalf("Unexpected error while creating middleware: %v", err)
}
bodyBytes, _ := json.Marshal(tt.requestBody)
req := httptest.NewRequest(http.MethodPost, "/test", bytes.NewReader(bodyBytes))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
dummyHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
middleware(dummyHandler).ServeHTTP(rec, req)
if rec.Code != tt.expectedCode {
t.Errorf("Expected status code %d, but got %d", tt.expectedCode, rec.Code)
}
})
}
}

View File

@@ -0,0 +1,31 @@
package main
import (
"context"
"errors"
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
router "github.com/beckn/beckn-onix/pkg/plugin/implementation/router"
)
// RouterProvider provides instances of Router.
type RouterProvider struct{}
// New initializes a new Router instance.
func (rp RouterProvider) New(ctx context.Context, config map[string]string) (definition.Router, func() error, error) {
if ctx == nil {
return nil, nil, errors.New("context cannot be nil")
}
// Parse the routingConfig key from the config map
routingConfig, ok := config["routingConfig"]
if !ok {
return nil, nil, errors.New("routingConfig is required in the configuration")
}
return router.New(ctx, &router.Config{
RoutingConfig: routingConfig,
})
}
// Provider is the exported symbol that the plugin manager will look for.
var Provider = RouterProvider{}

View File

@@ -0,0 +1,101 @@
package main
import (
"context"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)
// setupTestConfig creates a temporary directory and writes a sample routing rules file.
func setupTestConfig(t *testing.T) string {
t.Helper()
// Get project root (assuming testData is in project root)
_, filename, _, _ := runtime.Caller(0) // Path to plugin_test.go
projectRoot := filepath.Dir(filepath.Dir(filename)) // Move up from cmd/
yamlPath := filepath.Join(projectRoot, "testData", "bap_receiver.yaml")
// Copy to temp file (to test file loading logic)
tempDir := t.TempDir()
tempPath := filepath.Join(tempDir, "routingRules.yaml")
content, err := os.ReadFile(yamlPath)
if err != nil {
t.Fatalf("Failed to read test file: %v", err)
}
if err := os.WriteFile(tempPath, content, 0644); err != nil {
t.Fatalf("Failed to create temp config: %v", err)
}
return tempPath
}
// TestRouterProviderSuccess tests successful router creation.
func TestRouterProviderSuccess(t *testing.T) {
rulesFilePath := setupTestConfig(t)
defer os.RemoveAll(filepath.Dir(rulesFilePath))
provider := RouterProvider{}
router, _, err := provider.New(context.Background(), map[string]string{
"routingConfig": rulesFilePath,
})
if err != nil {
t.Fatalf("New() unexpected error: %v", err)
}
if router == nil {
t.Error("New() returned nil router, want non-nil")
}
}
// TestRouterProviderFailure tests the RouterProvider implementation for failure cases.
func TestRouterProviderFailure(t *testing.T) {
rulesFilePath := setupTestConfig(t)
defer os.RemoveAll(filepath.Dir(rulesFilePath))
// Define test cases
tests := []struct {
name string
ctx context.Context
config map[string]string
wantErr string
}{
{
name: "Empty routing config path",
ctx: context.Background(),
config: map[string]string{
"routingConfig": "",
},
wantErr: "failed to load routing rules: routingConfig path is empty",
},
{
name: "Missing routing config key",
ctx: context.Background(),
config: map[string]string{},
wantErr: "routingConfig is required in the configuration",
},
{
name: "Nil context",
ctx: nil,
config: map[string]string{"routingConfig": rulesFilePath},
wantErr: "context cannot be nil",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
provider := RouterProvider{}
_, _, err := provider.New(tt.ctx, tt.config)
// Check for expected error
if err == nil {
t.Fatalf("New(%v, %v) = nil error, want error containing %q", tt.ctx, tt.config, tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("New(%v, %v) = %v, want error containing %q", tt.ctx, tt.config, err, tt.wantErr)
}
})
}
}

View File

@@ -0,0 +1,275 @@
package router
import (
"context"
"encoding/json"
"fmt"
"net/url"
"os"
"path"
"strings"
definition "github.com/beckn/beckn-onix/pkg/plugin/definition"
"gopkg.in/yaml.v3"
)
// Config holds the configuration for the Router plugin.
type Config struct {
RoutingConfig string `json:"routingConfig"`
}
// RoutingConfig represents the structure of the routing configuration file.
type routingConfig struct {
RoutingRules []routingRule `yaml:"routingRules"`
}
// Router implements Router interface.
type Router struct {
rules map[string]map[string]map[string]*definition.Route // domain -> version -> endpoint -> route
}
// RoutingRule represents a single routing rule.
type routingRule struct {
Domain string `yaml:"domain"`
Version string `yaml:"version"`
TargetType string `yaml:"targetType"` // "url", "publisher", "bpp", or "bap"
Target target `yaml:"target,omitempty"`
Endpoints []string `yaml:"endpoints"`
}
// Target contains destination-specific details.
type target struct {
URL string `yaml:"url,omitempty"` // URL for "url" or gateway endpoint for "bpp"/"bap"
PublisherID string `yaml:"publisherId,omitempty"` // For "msgq" type
}
// TargetType defines possible target destinations.
const (
targetTypeURL = "url" // Route to a specific URL
targetTypePublisher = "publisher" // Route to a publisher
targetTypeBPP = "bpp" // Route to a BPP endpoint
targetTypeBAP = "bap" // Route to a BAP endpoint
)
// New initializes a new Router instance with the provided configuration.
// It loads and validates the routing rules from the specified YAML file.
// Returns an error if the configuration is invalid or the rules cannot be loaded.
func New(ctx context.Context, config *Config) (*Router, func() error, error) {
// Check if config is nil
if config == nil {
return nil, nil, fmt.Errorf("config cannot be nil")
}
router := &Router{
rules: make(map[string]map[string]map[string]*definition.Route),
}
// Load rules at bootup
if err := router.loadRules(config.RoutingConfig); err != nil {
return nil, nil, fmt.Errorf("failed to load routing rules: %w", err)
}
return router, nil, nil
}
// parseTargetURL parses a URL string into a url.URL object with strict validation
func parseTargetURL(urlStr string) (*url.URL, error) {
if urlStr == "" {
return nil, nil
}
parsed, err := url.Parse(urlStr)
if err != nil {
return nil, fmt.Errorf("invalid URL '%s': %w", urlStr, err)
}
// Enforce scheme requirement
if parsed.Scheme == "" {
return nil, fmt.Errorf("URL '%s' must include a scheme (http/https)", urlStr)
}
// Optionally validate scheme is http or https
if parsed.Scheme != "https" {
return nil, fmt.Errorf("URL '%s' must use https scheme", urlStr)
}
return parsed, nil
}
// LoadRules reads and parses routing rules from the YAML configuration file.
func (r *Router) loadRules(configPath string) error {
if configPath == "" {
return fmt.Errorf("routingConfig path is empty")
}
data, err := os.ReadFile(configPath)
if err != nil {
return fmt.Errorf("error reading config file at %s: %w", configPath, err)
}
var config routingConfig
if err := yaml.Unmarshal(data, &config); err != nil {
return fmt.Errorf("error parsing YAML: %w", err)
}
// Validate rules
if err := validateRules(config.RoutingRules); err != nil {
return fmt.Errorf("invalid routing rules: %w", err)
}
// Build the optimized rule map
for _, rule := range config.RoutingRules {
// Initialize domain map if not exists
if _, ok := r.rules[rule.Domain]; !ok {
r.rules[rule.Domain] = make(map[string]map[string]*definition.Route)
}
// Initialize version map if not exists
if _, ok := r.rules[rule.Domain][rule.Version]; !ok {
r.rules[rule.Domain][rule.Version] = make(map[string]*definition.Route)
}
// Add all endpoints for this rule
for _, endpoint := range rule.Endpoints {
var route *definition.Route
switch rule.TargetType {
case targetTypePublisher:
route = &definition.Route{
TargetType: rule.TargetType,
PublisherID: rule.Target.PublisherID,
}
case targetTypeURL:
parsedURL, err := parseTargetURL(rule.Target.URL)
if err != nil {
return fmt.Errorf("invalid URL in rule: %w", err)
}
route = &definition.Route{
TargetType: rule.TargetType,
URL: parsedURL,
}
case targetTypeBPP, targetTypeBAP:
var parsedURL *url.URL
if rule.Target.URL != "" {
parsedURL, err = parseTargetURL(rule.Target.URL)
if err != nil {
return fmt.Errorf("invalid URL in rule: %w", err)
}
}
route = &definition.Route{
TargetType: rule.TargetType,
URL: parsedURL,
}
}
r.rules[rule.Domain][rule.Version][endpoint] = route
}
}
return nil
}
// validateRules performs basic validation on the loaded routing rules.
func validateRules(rules []routingRule) error {
for _, rule := range rules {
// Ensure domain, version, and TargetType are present
if rule.Domain == "" || rule.Version == "" || rule.TargetType == "" {
return fmt.Errorf("invalid rule: domain, version, and targetType are required")
}
// Validate based on TargetType
switch rule.TargetType {
case targetTypeURL:
if rule.Target.URL == "" {
return fmt.Errorf("invalid rule: url is required for targetType 'url'")
}
if _, err := parseTargetURL(rule.Target.URL); err != nil {
return fmt.Errorf("invalid URL - %s: %w", rule.Target.URL, err)
}
case targetTypePublisher:
if rule.Target.PublisherID == "" {
return fmt.Errorf("invalid rule: publisherID is required for targetType 'publisher'")
}
case targetTypeBPP, targetTypeBAP:
if rule.Target.URL != "" {
if _, err := parseTargetURL(rule.Target.URL); err != nil {
return fmt.Errorf("invalid URL - %s defined in routing config for target type %s: %w", rule.Target.URL, rule.TargetType, err)
}
}
continue
default:
return fmt.Errorf("invalid rule: unknown targetType '%s'", rule.TargetType)
}
}
return nil
}
// Route determines the routing destination based on the request context.
func (r *Router) Route(ctx context.Context, url *url.URL, body []byte) (*definition.Route, error) {
// Parse the body to extract domain and version
var requestBody struct {
Context struct {
Domain string `json:"domain"`
Version string `json:"version"`
BPPURI string `json:"bpp_uri,omitempty"`
BAPURI string `json:"bap_uri,omitempty"`
} `json:"context"`
}
if err := json.Unmarshal(body, &requestBody); err != nil {
return nil, fmt.Errorf("error parsing request body: %w", err)
}
// Extract the endpoint from the URL
endpoint := path.Base(url.Path)
// Lookup route in the optimized map
domainRules, ok := r.rules[requestBody.Context.Domain]
if !ok {
return nil, fmt.Errorf("no routing rules found for domain %s", requestBody.Context.Domain)
}
versionRules, ok := domainRules[requestBody.Context.Version]
if !ok {
return nil, fmt.Errorf("no routing rules found for domain %s version %s", requestBody.Context.Domain, requestBody.Context.Version)
}
route, ok := versionRules[endpoint]
if !ok {
return nil, fmt.Errorf("endpoint '%s' is not supported for domain %s and version %s in routing config",
endpoint, requestBody.Context.Domain, requestBody.Context.Version)
}
// Handle BPP/BAP routing with request URIs
switch route.TargetType {
case targetTypeBPP:
return handleProtocolMapping(route, requestBody.Context.BPPURI, endpoint)
case targetTypeBAP:
return handleProtocolMapping(route, requestBody.Context.BAPURI, endpoint)
}
return route, nil
}
// handleProtocolMapping handles both BPP and BAP routing with proper URL construction
func handleProtocolMapping(route *definition.Route, requestURI, endpoint string) (*definition.Route, error) {
uri := strings.TrimSpace(requestURI)
var targetURL *url.URL
if len(uri) != 0 {
parsedURL, err := parseTargetURL(uri)
if err != nil {
return nil, fmt.Errorf("invalid %s URI - %s in request body for %s: %w", strings.ToUpper(route.TargetType), uri, endpoint, err)
}
targetURL = parsedURL
}
// If no request URI, fall back to configured URL with endpoint appended
if targetURL == nil {
if route.URL == nil {
return nil, fmt.Errorf("could not determine destination for endpoint '%s': neither request contained a %s URI nor was a default URL configured in routing rules", endpoint, strings.ToUpper(route.TargetType))
}
targetURL = &url.URL{
Scheme: route.URL.Scheme,
Host: route.URL.Host,
Path: path.Join(route.URL.Path, endpoint),
}
}
return &definition.Route{
TargetType: targetTypeURL,
URL: targetURL,
}, nil
}

View File

@@ -0,0 +1,486 @@
package router
import (
"context"
"embed"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
)
//go:embed testData/*
var testData embed.FS
func setupTestConfig(t *testing.T, yamlFileName string) string {
t.Helper()
configDir := t.TempDir()
content, err := testData.ReadFile("testData/" + yamlFileName)
if err != nil {
t.Fatalf("ReadFile() err = %v, want nil", err)
}
rulesPath := filepath.Join(configDir, "routing_rules.yaml")
if err := os.WriteFile(rulesPath, content, 0644); err != nil {
t.Fatalf("WriteFile() err = %v, want nil", err)
}
return rulesPath
}
// setupRouter is a helper function to create router instance.
func setupRouter(t *testing.T, configFile string) (*Router, func() error, string) {
rulesFilePath := setupTestConfig(t, configFile)
config := &Config{
RoutingConfig: rulesFilePath,
}
router, _, err := New(context.Background(), config)
if err != nil {
t.Fatalf("New failed: %v", err)
}
return router, nil, rulesFilePath
}
// TestNew tests the New function.
func TestNew(t *testing.T) {
ctx := context.Background()
// List of YAML files in the testData directory
yamlFiles := []string{
"bap_caller.yaml",
"bap_receiver.yaml",
"bpp_caller.yaml",
"bpp_receiver.yaml",
}
for _, yamlFile := range yamlFiles {
t.Run(yamlFile, func(t *testing.T) {
rulesFilePath := setupTestConfig(t, yamlFile)
defer os.RemoveAll(filepath.Dir(rulesFilePath))
// Define test cases
tests := []struct {
name string
config *Config
wantErr string
}{
{
name: "Valid configuration",
config: &Config{
RoutingConfig: rulesFilePath,
},
wantErr: "",
},
{
name: "Empty config",
config: nil,
wantErr: "config cannot be nil",
},
{
name: "Empty routing config path",
config: &Config{
RoutingConfig: "",
},
wantErr: "routingConfig path is empty",
},
{
name: "Routing config file does not exist",
config: &Config{
RoutingConfig: "/nonexistent/path/to/rules.yaml",
},
wantErr: "error reading config file",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router, _, err := New(ctx, tt.config)
// Check for expected error
if tt.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("New(%v) = %v, want error containing %q", tt.config, err, tt.wantErr)
}
return
}
// Ensure no error occurred
if err != nil {
t.Errorf("New(%v) = %v, want nil error", tt.config, err)
return
}
// Ensure the router and close function are not nil
if router == nil {
t.Errorf("New(%v, %v) = nil router, want non-nil", ctx, tt.config)
}
})
}
})
}
}
// TestValidateRulesSuccess tests the validate function for success cases.
func TestValidateRulesSuccess(t *testing.T) {
tests := []struct {
name string
rules []routingRule
}{
{
name: "Valid rules with url routing",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "url",
Target: target{
URL: "https://example.com/api",
},
Endpoints: []string{"on_search", "on_select"},
},
},
},
{
name: "Valid rules with publisher routing",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "publisher",
Target: target{
PublisherID: "example_topic",
},
Endpoints: []string{"on_search", "on_select"},
},
},
},
{
name: "Valid rules with bpp routing to gateway",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "bpp",
Target: target{
URL: "https://mock_gateway.com/api",
},
Endpoints: []string{"search"},
},
},
},
{
name: "Valid rules with bpp routing",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "bpp",
Endpoints: []string{"select"},
},
},
},
{
name: "Valid rules with bap routing",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "bap",
Endpoints: []string{"select"},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateRules(tt.rules)
if err != nil {
t.Errorf("validateRules(%v) = %v, want nil error", tt.rules, err)
}
})
}
}
// TestValidateRulesFailure tests the validate function for failure cases.
func TestValidateRulesFailure(t *testing.T) {
tests := []struct {
name string
rules []routingRule
wantErr string
}{
{
name: "Missing domain",
rules: []routingRule{
{
Version: "1.0.0",
TargetType: "url",
Target: target{
URL: "https://example.com/api",
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: domain, version, and targetType are required",
},
{
name: "Missing version",
rules: []routingRule{
{
Domain: "retail",
TargetType: "url",
Target: target{
URL: "https://example.com/api",
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: domain, version, and targetType are required",
},
{
name: "Missing targetType",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
Target: target{
URL: "https://example.com/api",
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: domain, version, and targetType are required",
},
{
name: "Invalid targetType",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "invalid",
Target: target{
URL: "https://example.com/api",
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: unknown targetType 'invalid'",
},
{
name: "Missing url for targetType: url",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "url",
Target: target{
// URL is missing
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: url is required for targetType 'url'",
},
{
name: "Invalid URL format for targetType: url",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "url",
Target: target{
URL: "htp://invalid-url.com", // Invalid scheme
},
Endpoints: []string{"search"},
},
},
wantErr: "invalid URL - htp://invalid-url.com: URL 'htp://invalid-url.com' must use https scheme",
},
{
name: "Missing topic_id for targetType: publisher",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "publisher",
Target: target{
// PublisherID is missing
},
Endpoints: []string{"search", "select"},
},
},
wantErr: "invalid rule: publisherID is required for targetType 'publisher'",
},
{
name: "Invalid URL for BPP targetType",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "bpp",
Target: target{
URL: "htp://invalid-url.com", // Invalid URL
},
Endpoints: []string{"search"},
},
},
wantErr: "invalid URL - htp://invalid-url.com defined in routing config for target type bpp",
},
{
name: "Invalid URL for BAP targetType",
rules: []routingRule{
{
Domain: "retail",
Version: "1.0.0",
TargetType: "bap",
Target: target{
URL: "http://[invalid].com", // Invalid host
},
Endpoints: []string{"search"},
},
},
wantErr: "invalid URL - http://[invalid].com defined in routing config for target type bap",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateRules(tt.rules)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("validateRules(%v) = %v, want error containing %q", tt.rules, err, tt.wantErr)
}
})
}
}
// TestRouteSuccess tests the Route function for success cases.
func TestRouteSuccess(t *testing.T) {
ctx := context.Background()
// Define success test cases
tests := []struct {
name string
configFile string
url string
body string
}{
{
name: "Valid domain, version, and endpoint (bpp routing with gateway URL)",
configFile: "bap_caller.yaml",
url: "https://example.com/v1/ondc/search",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`,
},
{
name: "Valid domain, version, and endpoint (bpp routing with bpp_uri)",
configFile: "bap_caller.yaml",
url: "https://example.com/v1/ondc/select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "https://bpp1.example.com"}}`,
},
{
name: "Valid domain, version, and endpoint (url routing)",
configFile: "bpp_receiver.yaml",
url: "https://example.com/v1/ondc/select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`,
},
{
name: "Valid domain, version, and endpoint (publisher routing)",
configFile: "bpp_receiver.yaml",
url: "https://example.com/v1/ondc/search",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`,
},
{
name: "Valid domain, version, and endpoint (bap routing with bap_uri)",
configFile: "bpp_caller.yaml",
url: "https://example.com/v1/ondc/on_select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bap_uri": "https://bap1.example.com"}}`,
},
{
name: "Valid domain, version, and endpoint (bpp routing with bpp_uri)",
configFile: "bap_receiver.yaml",
url: "https://example.com/v1/ondc/on_select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "https://bpp1.example.com"}}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router, _, rulesFilePath := setupRouter(t, tt.configFile)
defer os.RemoveAll(filepath.Dir(rulesFilePath))
parsedURL, _ := url.Parse(tt.url)
_, err := router.Route(ctx, parsedURL, []byte(tt.body))
// Ensure no error occurred
if err != nil {
t.Errorf("router.Route(%v, %v, %v) = %v, want nil error", ctx, parsedURL, []byte(tt.body), err)
}
})
}
}
// TestRouteFailure tests the Route function for failure cases.
func TestRouteFailure(t *testing.T) {
ctx := context.Background()
// Define failure test cases
tests := []struct {
name string
configFile string
url string
body string
wantErr string
}{
{
name: "Unsupported endpoint",
configFile: "bpp_receiver.yaml",
url: "https://example.com/v1/ondc/unsupported",
body: `{"context": {"domain": "ONDC:TRV11", "version": "2.0.0"}}`,
wantErr: "endpoint 'unsupported' is not supported for domain ONDC:TRV11 and version 2.0.0",
},
{
name: "No matching rule",
configFile: "bpp_receiver.yaml",
url: "https://example.com/v1/ondc/select",
body: `{"context": {"domain": "ONDC:SRV11", "version": "2.0.0"}}`,
wantErr: "no routing rules found for domain ONDC:SRV11",
},
{
name: "Missing bap_uri for bap routing",
configFile: "bpp_caller.yaml",
url: "https://example.com/v1/ondc/on_search",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`,
wantErr: "could not determine destination for endpoint 'on_search': neither request contained a BAP URI nor was a default URL configured in routing rules",
},
{
name: "Missing bpp_uri for bpp routing",
configFile: "bap_caller.yaml",
url: "https://example.com/v1/ondc/select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0"}}`,
wantErr: "could not determine destination for endpoint 'select': neither request contained a BPP URI nor was a default URL configured in routing rules",
},
{
name: "Invalid bpp_uri format in request",
configFile: "bap_caller.yaml",
url: "https://example.com/v1/ondc/select",
body: `{"context": {"domain": "ONDC:TRV10", "version": "2.0.0", "bpp_uri": "htp://invalid-url"}}`, // Invalid scheme (htp instead of http)
wantErr: "invalid BPP URI - htp://invalid-url in request body for select: URL 'htp://invalid-url' must use https scheme",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
router, _, rulesFilePath := setupRouter(t, tt.configFile)
defer os.RemoveAll(filepath.Dir(rulesFilePath))
parsedURL, _ := url.Parse(tt.url)
_, err := router.Route(ctx, parsedURL, []byte(tt.body))
// Check for expected error
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("Route(%q, %q) = %v, want error containing %q", tt.url, tt.body, err, tt.wantErr)
}
})
}
}

View File

@@ -0,0 +1,25 @@
routingRules:
- domain: ONDC:TRV10
version: 2.0.0
targetType: bpp
target:
url: https://gateway.example.com
endpoints:
- search
- domain: ONDC:TRV10
version: 2.0.0
targetType: bpp
endpoints:
- select
- init
- confirm
- status
- cancel
- domain: ONDC:TRV12
version: 2.0.0
targetType: bpp
endpoints:
- select
- init
- confirm
- status

View File

@@ -0,0 +1,20 @@
routingRules:
- domain: ONDC:TRV10
version: 2.0.0
targetType: url
target:
url: https://services-backend/trv/v1
endpoints:
- on_select
- on_init
- on_confirm
- on_status
- on_update
- on_cancel
- domain: ONDC:TRV10
version: 2.0.0
targetType: publisher
target:
publisherId: trv_topic_id1
endpoints:
- on_search

View File

@@ -0,0 +1,23 @@
routingRules:
- domain: ONDC:TRV10
version: 2.0.0
targetType: bap
endpoints:
- on_search
- on_select
- on_init
- on_confirm
- on_status
- on_update
- on_cancel
- domain: ONDC:TRV11
version: 2.0.0
targetType: bap
endpoints:
- on_search
- on_select
- on_init
- on_confirm
- on_status
- on_update
- on_cancel

View File

@@ -0,0 +1,28 @@
routingRules:
- domain: ONDC:TRV10
version: 2.0.0
targetType: url
target:
url: https://services-backend/trv/v1
endpoints:
- select
- init
- confirm
- status
- cancel
- domain: ONDC:TRV10
version: 2.0.0
targetType: publisher
target:
publisherId: trv_topic_id1
endpoints:
- search
- domain: ONDC:TRV11
version: 2.0.0
targetType: url
target:
url: https://services-backend/trv/v1
endpoints:
- select
- init
- confirm

View File

@@ -0,0 +1,33 @@
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 schemaDir from the config map
schemaDir, ok := config["schemaDir"]
if !ok || schemaDir == "" {
return nil, nil, errors.New("config must contain 'schemaDir'")
}
// 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{}

View File

@@ -0,0 +1,150 @@
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{"schemaDir": schemaDir},
expectedError: "",
},
}
// Test using table-driven tests
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
vp := schemaValidatorProvider{}
schemaValidator, _, 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")
}
})
}
}
// 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 'schemaDir'",
},
{
name: "schemaDir is empty",
ctx: context.Background(),
config: map[string]string{"schemaDir": ""},
expectedError: "config must contain 'schemaDir'",
},
{
name: "Invalid schema directory",
ctx: context.Background(), // Valid context
config: map[string]string{"schemaDir": "/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{"schemaDir": 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
}
})
}
}

View File

@@ -0,0 +1,197 @@
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, nil, 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
}

View File

@@ -0,0 +1,353 @@
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 TestValidatorNew_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 TestValidatorNewFailure(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: "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)
}
})
}
}