diff --git a/go.mod b/go.mod index 0128ed4..fc5402a 100644 --- a/go.mod +++ b/go.mod @@ -3,20 +3,30 @@ module github.com/beckn/beckn-onix go 1.24.1 require ( + github.com/kr/pretty v0.3.1 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 golang.org/x/crypto v0.36.0 + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect ) toolchain go1.23.7 require ( github.com/rs/zerolog v1.33.0 + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/google/uuid v1.6.0 + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/stretchr/testify v1.10.0 github.com/zenazn/pkcs7pad v0.0.0-20170308005700-253a5b1f0e03 golang.org/x/text v0.23.0 // indirect golang.org/x/crypto v0.36.0 gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gopkg.in/yaml.v3 v3.0.1 ) +require golang.org/x/text v0.23.0 // indirect + require golang.org/x/sys v0.31.0 // indirect require ( github.com/mattn/go-colorable v0.1.13 // indirect diff --git a/go.sum b/go.sum index 8e52285..ec6094b 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,27 @@ +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/santhosh-tekuri/jsonschema/v6 v6.0.1 h1:PKK9DyHxif4LZo+uQSgXNqs0jj5+xZwwfKHgph2lxBw= github.com/santhosh-tekuri/jsonschema/v6 v6.0.1/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= @@ -24,5 +44,10 @@ golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= diff --git a/pkg/plugin/definition/router.go b/pkg/plugin/definition/router.go new file mode 100644 index 0000000..05e2e30 --- /dev/null +++ b/pkg/plugin/definition/router.go @@ -0,0 +1,24 @@ +package definition + +import ( + "context" + "net/url" +) + +// 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, 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) +} diff --git a/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go new file mode 100644 index 0000000..4a05ecc --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin.go @@ -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{} diff --git a/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go new file mode 100644 index 0000000..0890dbc --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/cmd/plugin_test.go @@ -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) + + }) + } +} diff --git a/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go new file mode 100644 index 0000000..13d4da0 --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor.go @@ -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 +} diff --git a/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go new file mode 100644 index 0000000..307a7e7 --- /dev/null +++ b/pkg/plugin/implementation/requestPreProcessor/reqpreprocessor_test.go @@ -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) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/cmd/plugin.go b/pkg/plugin/implementation/router/cmd/plugin.go new file mode 100644 index 0000000..556f129 --- /dev/null +++ b/pkg/plugin/implementation/router/cmd/plugin.go @@ -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{} diff --git a/pkg/plugin/implementation/router/cmd/plugin_test.go b/pkg/plugin/implementation/router/cmd/plugin_test.go new file mode 100644 index 0000000..c5ffe8e --- /dev/null +++ b/pkg/plugin/implementation/router/cmd/plugin_test.go @@ -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) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/router.go b/pkg/plugin/implementation/router/router.go new file mode 100644 index 0000000..9d16767 --- /dev/null +++ b/pkg/plugin/implementation/router/router.go @@ -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 +} diff --git a/pkg/plugin/implementation/router/router_test.go b/pkg/plugin/implementation/router/router_test.go new file mode 100644 index 0000000..7937ca5 --- /dev/null +++ b/pkg/plugin/implementation/router/router_test.go @@ -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) + } + }) + } +} diff --git a/pkg/plugin/implementation/router/testData/bap_caller.yaml b/pkg/plugin/implementation/router/testData/bap_caller.yaml new file mode 100644 index 0000000..6a40a0f --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bap_caller.yaml @@ -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 \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bap_receiver.yaml b/pkg/plugin/implementation/router/testData/bap_receiver.yaml new file mode 100644 index 0000000..17432db --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bap_receiver.yaml @@ -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 \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bpp_caller.yaml b/pkg/plugin/implementation/router/testData/bpp_caller.yaml new file mode 100644 index 0000000..339b92d --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bpp_caller.yaml @@ -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 \ No newline at end of file diff --git a/pkg/plugin/implementation/router/testData/bpp_receiver.yaml b/pkg/plugin/implementation/router/testData/bpp_receiver.yaml new file mode 100644 index 0000000..7355592 --- /dev/null +++ b/pkg/plugin/implementation/router/testData/bpp_receiver.yaml @@ -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 \ No newline at end of file diff --git a/pkg/response/response_test.go b/pkg/response/response_test.go index 242fa72..73dcb6a 100644 --- a/pkg/response/response_test.go +++ b/pkg/response/response_test.go @@ -301,3 +301,17 @@ func compareContexts(c1, c2 map[string]interface{}) bool { return reflect.DeepEqual(c1, c2) } + +func TestSchemaValidationErr_Error(t *testing.T) { + validationErrors := []Error{ + {Paths: "name", Message: "Name is required"}, + {Paths: "email", Message: "Invalid email format"}, + } + err := SchemaValidationErr{Errors: validationErrors} + expected := "name: Name is required; email: Invalid email format" + if err.Error() != expected { + t.Errorf("err.Error() = %s, want %s", + err.Error(), expected) + + } +}