From 9276bb7c58672268caaf274d452dccc91fd08c9c Mon Sep 17 00:00:00 2001 From: Yaroslav Grebnov Date: Sun, 11 Oct 2026 15:40:22 +0200 Subject: [PATCH 1/4] Refactor request and response models in specs --- Makefile | 1 + api/service_run_test.go | 6 +- execute/call/grpc.go | 3 +- execute/evaluate/calls.go | 153 ++++ execute/evaluate/calls_test.go | 768 +++++++++++++++++++++ execute/evaluate/evaluator.go | 8 +- execute/evaluate/evaluator_test.go | 30 +- execute/runtime/environment_test.go | 12 +- execute/runtime/router/grpc/router.go | 14 +- execute/runtime/router/grpc/router_test.go | 97 ++- execute/runtime/service/grpc/mock.go | 188 ++++- execute/runtime/service/grpc/mock_test.go | 434 +++++++++++- execute/runtime/service/http/mock.go | 137 ++-- execute/runtime/service/http/mock_test.go | 368 +++++++--- execute/worker/grpc/evaluate.go | 72 +- execute/worker/grpc/evaluate_test.go | 244 +++++-- execute/worker/grpc/executor_test.go | 44 +- execute/worker/http/evaluate.go | 153 ++-- execute/worker/http/evaluate_test.go | 314 +++++++-- execute/worker/http/executor.go | 13 +- execute/worker/http/executor_test.go | 83 ++- execute/worker/summary.go | 81 +-- execute/worker/summary_test.go | 316 +++++---- execute/worker/worker.go | 33 +- execute/worker/worker_test.go | 585 +++++++++++++++- mock/Execute.go | 56 ++ model/environment.go | 79 +-- model/grpc.go | 22 + model/http.go | 96 +++ model/test.go | 96 +-- model/testexecution.go | 76 +- pkg/keys/keys.go | 3 +- tests/test_test.go | 6 +- tests/testexecution_test.go | 4 +- 34 files changed, 3703 insertions(+), 892 deletions(-) create mode 100644 execute/evaluate/calls.go create mode 100644 execute/evaluate/calls_test.go create mode 100644 mock/Execute.go create mode 100644 model/grpc.go create mode 100644 model/http.go diff --git a/Makefile b/Makefile index 32101be..d680e92 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,7 @@ mockgen: install-mockgen @mkdir -p mock $(MOCKGEN) -destination=mock/Repository.go -package=mock github.com/e2engine/core/repository EntityRepository,ResourceRepository,TestRepository,TestExecutionRepository,TestSuiteExecutionRepository $(MOCKGEN) -destination=mock/Runtime.go -package=mock github.com/e2engine/core/execute/runtime Service,ServiceProvider,Router,RouterProvider + $(MOCKGEN) -destination=mock/Execute.go -package=mock github.com/e2engine/core/execute ProtocolExecutor .PHONY: lint lint: install-golangci-lint diff --git a/api/service_run_test.go b/api/service_run_test.go index 1d1dc97..f7c5c69 100644 --- a/api/service_run_test.go +++ b/api/service_run_test.go @@ -714,14 +714,14 @@ func validTestSpec() model.TestSpec { return model.TestSpec{ Tags: []string{"smoke"}, Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{ + HTTP: &model.HTTPRequest{ Method: "GET", URL: "http://localhost:8080/health", }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{ - Status: 200, + HTTP: &model.HTTPResponse{ + StatusCode: 200, }, }, } diff --git a/execute/call/grpc.go b/execute/call/grpc.go index 3633d3b..cde121d 100644 --- a/execute/call/grpc.go +++ b/execute/call/grpc.go @@ -6,7 +6,8 @@ type GRPCCall struct { } type GRPCRequest struct { - RPC string + Service string + Method string Metadata map[string][]string Message []byte } diff --git a/execute/evaluate/calls.go b/execute/evaluate/calls.go new file mode 100644 index 0000000..934c786 --- /dev/null +++ b/execute/evaluate/calls.go @@ -0,0 +1,153 @@ +package evaluate + +import ( + "sort" + + "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/model" +) + +type httpObservedCallKey struct { + ServiceID string + Method string + Path string + ResponseStatusCode int +} + +type grpcObservedCallKey struct { + ServiceID string + Service string + Method string + ResponseStatus string +} + +func SummarizeCalls( + executionID string, + calls call.Reader, +) []model.ServiceObservedCalls { + actualCalls := calls.Get( + call.Filter{ + TestExecutionID: executionID, + }, + ) + + if len(actualCalls) == 0 { + return nil + } + + httpCalls := make(map[httpObservedCallKey]int) + grpcCalls := make(map[grpcObservedCallKey]int) + + for _, actual := range actualCalls { + switch { + case actual.HTTP != nil: + key := httpObservedCallKey{ + ServiceID: actual.ServiceID, + Method: actual.HTTP.Request.Method, + Path: actual.HTTP.Request.Path, + ResponseStatusCode: actual.HTTP.Response.StatusCode, + } + + httpCalls[key]++ + + case actual.GRPC != nil: + key := grpcObservedCallKey{ + ServiceID: actual.ServiceID, + Service: actual.GRPC.Request.Service, + Method: actual.GRPC.Request.Method, + ResponseStatus: actual.GRPC.Response.Status, + } + + grpcCalls[key]++ + } + } + + result := make( + []model.ServiceObservedCalls, + 0, + len(httpCalls)+len(grpcCalls), + ) + + for key, count := range httpCalls { + statusCode := key.ResponseStatusCode + + result = append( + result, + model.ServiceObservedCalls{ + ServiceID: key.ServiceID, + Count: count, + HTTP: &model.HTTPServiceObservedCall{ + Method: key.Method, + Path: key.Path, + ResponseStatusCode: &statusCode, + }, + }, + ) + } + + for key, count := range grpcCalls { + result = append( + result, + model.ServiceObservedCalls{ + ServiceID: key.ServiceID, + Count: count, + GRPC: &model.GRPCServiceObservedCall{ + Service: key.Service, + Method: key.Method, + ResponseStatus: key.ResponseStatus, + }, + }, + ) + } + + sort.Slice(result, func(i, j int) bool { + left := result[i] + right := result[j] + + if left.ServiceID != right.ServiceID { + return left.ServiceID < right.ServiceID + } + + if left.HTTP != nil && right.GRPC != nil { + return true + } + + if left.GRPC != nil && right.HTTP != nil { + return false + } + + if left.HTTP != nil { + if left.HTTP.Method != right.HTTP.Method { + return left.HTTP.Method < right.HTTP.Method + } + if left.HTTP.Path != right.HTTP.Path { + return left.HTTP.Path < right.HTTP.Path + } + + return observedHTTPStatus(left.HTTP) < + observedHTTPStatus(right.HTTP) + } + + if left.GRPC.Service != right.GRPC.Service { + return left.GRPC.Service < right.GRPC.Service + } + if left.GRPC.Method != right.GRPC.Method { + return left.GRPC.Method < right.GRPC.Method + } + + return left.GRPC.ResponseStatus < + right.GRPC.ResponseStatus + }) + + return result +} + +func observedHTTPStatus( + c *model.HTTPServiceObservedCall, +) int { + if c.ResponseStatusCode == nil { + return 0 + } + + return *c.ResponseStatusCode +} diff --git a/execute/evaluate/calls_test.go b/execute/evaluate/calls_test.go new file mode 100644 index 0000000..1f3a1c8 --- /dev/null +++ b/execute/evaluate/calls_test.go @@ -0,0 +1,768 @@ +package evaluate + +import ( + "testing" + + "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/model" +) + +func TestSummarizeCalls(t *testing.T) { + tests := []struct { + name string + + calls []call.Call + + expected []model.ServiceObservedCalls + }{ + { + name: "no calls", + }, + { + name: "aggregates identical HTTP calls", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 2, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/users", + ResponseStatusCode: intPtrObserved(200), + }, + }, + }, + }, + { + name: "separates HTTP calls by response status", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 500, + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/users", + ResponseStatusCode: intPtrObserved(200), + }, + }, + { + ServiceID: "users", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/users", + ResponseStatusCode: intPtrObserved(500), + }, + }, + }, + }, + { + name: "separates HTTP calls by request identity", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "POST", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/health", + ResponseStatusCode: intPtrObserved(200), + }, + }, + { + ServiceID: "users", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/users", + ResponseStatusCode: intPtrObserved(200), + }, + }, + { + ServiceID: "users", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "POST", + Path: "/users", + ResponseStatusCode: intPtrObserved(200), + }, + }, + }, + }, + { + name: "aggregates identical gRPC calls", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 2, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "OK", + }, + }, + }, + }, + { + name: "separates gRPC calls by response status", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "Internal", + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "Internal", + }, + }, + { + ServiceID: "users", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "OK", + }, + }, + }, + }, + { + name: "separates gRPC calls by request identity", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Get", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "users", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.AdminService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "users", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.AdminService", + Method: "Create", + ResponseStatus: "OK", + }, + }, + { + ServiceID: "users", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "OK", + }, + }, + { + ServiceID: "users", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Get", + ResponseStatus: "OK", + }, + }, + }, + }, + { + name: "separates calls by service ID", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "service-b", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "service-a", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "service-a", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/health", + ResponseStatusCode: intPtrObserved(200), + }, + }, + { + ServiceID: "service-b", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/health", + ResponseStatusCode: intPtrObserved(200), + }, + }, + }, + }, + { + name: "HTTP sorts before gRPC for same service", + calls: []call.Call{ + { + TestExecutionID: "execution-1", + ServiceID: "service-1", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + }, + Response: call.GRPCResponse{ + Status: "OK", + }, + }, + }, + { + TestExecutionID: "execution-1", + ServiceID: "service-1", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + }, + expected: []model.ServiceObservedCalls{ + { + ServiceID: "service-1", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "GET", + Path: "/health", + ResponseStatusCode: intPtrObserved(200), + }, + }, + { + ServiceID: "service-1", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "OK", + }, + }, + }, + }, + { + name: "ignores calls from another execution", + calls: []call.Call{ + { + TestExecutionID: "execution-2", + ServiceID: "users", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "GET", + Path: "/users", + }, + Response: call.HTTPResponse{ + StatusCode: 200, + }, + }, + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := &call.Store{} + + for _, actual := range tt.calls { + store.Record(actual) + } + + actual := SummarizeCalls( + "execution-1", + store, + ) + + assertObservedCalls( + t, + actual, + tt.expected, + ) + }) + } +} + +func TestSummarizeCallsDoesNotExposeCapturedData( + t *testing.T, +) { + store := &call.Store{} + + store.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "service-1", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: "POST", + Path: "/events", + Query: map[string][]string{ + "token": {"secret-query"}, + }, + Headers: map[string][]string{ + "Authorization": { + "Bearer secret-token", + }, + }, + Body: []byte(`{"secret":"request"}`), + }, + Response: call.HTTPResponse{ + StatusCode: 204, + Headers: map[string][]string{ + "Set-Cookie": { + "secret-cookie", + }, + }, + Body: []byte(`{"secret":"response"}`), + }, + }, + }) + + actual := SummarizeCalls( + "execution-1", + store, + ) + + expected := []model.ServiceObservedCalls{ + { + ServiceID: "service-1", + Count: 1, + HTTP: &model.HTTPServiceObservedCall{ + Method: "POST", + Path: "/events", + ResponseStatusCode: intPtrObserved(204), + }, + }, + } + + assertObservedCalls( + t, + actual, + expected, + ) +} + +func TestObservedHTTPStatus(t *testing.T) { + status := 404 + + tests := []struct { + name string + + call *model.HTTPServiceObservedCall + + expected int + }{ + { + name: "status", + call: &model.HTTPServiceObservedCall{ + ResponseStatusCode: &status, + }, + expected: 404, + }, + { + name: "nil status", + call: &model.HTTPServiceObservedCall{}, + expected: 0, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := observedHTTPStatus( + tt.call, + ) + + if actual != tt.expected { + t.Errorf( + "expected status %d, got %d", + tt.expected, + actual, + ) + } + }) + } +} + +func assertObservedCalls( + t *testing.T, + actual []model.ServiceObservedCalls, + expected []model.ServiceObservedCalls, +) { + t.Helper() + + if len(actual) != len(expected) { + t.Fatalf( + "expected %d observed calls, got %d: %+v", + len(expected), + len(actual), + actual, + ) + } + + for i := range expected { + if actual[i].ServiceID != expected[i].ServiceID { + t.Errorf( + "call %d: expected service ID %q, got %q", + i, + expected[i].ServiceID, + actual[i].ServiceID, + ) + } + + if actual[i].Count != expected[i].Count { + t.Errorf( + "call %d: expected count %d, got %d", + i, + expected[i].Count, + actual[i].Count, + ) + } + + assertObservedHTTPCall( + t, + i, + actual[i].HTTP, + expected[i].HTTP, + ) + + assertObservedGRPCCall( + t, + i, + actual[i].GRPC, + expected[i].GRPC, + ) + } +} + +func assertObservedHTTPCall( + t *testing.T, + index int, + actual *model.HTTPServiceObservedCall, + expected *model.HTTPServiceObservedCall, +) { + t.Helper() + + if expected == nil { + if actual != nil { + t.Errorf( + "call %d: expected no HTTP call, got %+v", + index, + actual, + ) + } + + return + } + + if actual == nil { + t.Errorf( + "call %d: expected HTTP call %+v, got nil", + index, + expected, + ) + + return + } + + if actual.Method != expected.Method { + t.Errorf( + "call %d: expected HTTP method %q, got %q", + index, + expected.Method, + actual.Method, + ) + } + + if actual.Path != expected.Path { + t.Errorf( + "call %d: expected HTTP path %q, got %q", + index, + expected.Path, + actual.Path, + ) + } + + actualStatus := observedHTTPStatus(actual) + expectedStatus := observedHTTPStatus(expected) + + if actualStatus != expectedStatus { + t.Errorf( + "call %d: expected HTTP status %d, got %d", + index, + expectedStatus, + actualStatus, + ) + } +} + +func assertObservedGRPCCall( + t *testing.T, + index int, + actual *model.GRPCServiceObservedCall, + expected *model.GRPCServiceObservedCall, +) { + t.Helper() + + if expected == nil { + if actual != nil { + t.Errorf( + "call %d: expected no gRPC call, got %+v", + index, + actual, + ) + } + + return + } + + if actual == nil { + t.Errorf( + "call %d: expected gRPC call %+v, got nil", + index, + expected, + ) + + return + } + + if actual.Service != expected.Service { + t.Errorf( + "call %d: expected gRPC service %q, got %q", + index, + expected.Service, + actual.Service, + ) + } + + if actual.Method != expected.Method { + t.Errorf( + "call %d: expected gRPC method %q, got %q", + index, + expected.Method, + actual.Method, + ) + } + + if actual.ResponseStatus != expected.ResponseStatus { + t.Errorf( + "call %d: expected gRPC status %q, got %q", + index, + expected.ResponseStatus, + actual.ResponseStatus, + ) + } +} + +func intPtrObserved(value int) *int { + return &value +} diff --git a/execute/evaluate/evaluator.go b/execute/evaluate/evaluator.go index a826982..727c12f 100644 --- a/execute/evaluate/evaluator.go +++ b/execute/evaluate/evaluator.go @@ -16,7 +16,7 @@ type CallEvaluator interface { ctx context.Context, service *model.ServiceSpec, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) Deviation( @@ -43,7 +43,7 @@ func New( func (e *Evaluator) EvaluateCalls( ctx context.Context, services []model.ServiceSpec, - expectedCalls []model.CallExpectation, + expectedCalls []model.ServiceExpectedCalls, calls call.Reader, result *execute.TestExecutionResult, ) error { @@ -107,7 +107,7 @@ func (e *Evaluator) evaluateActualCalls( func (e *Evaluator) evaluateExpectedCalls( ctx context.Context, services []model.ServiceSpec, - expectedCalls []model.CallExpectation, + expectedCalls []model.ServiceExpectedCalls, calls call.Reader, result *execute.TestExecutionResult, ) error { @@ -177,7 +177,7 @@ func (e *Evaluator) matches( ctx context.Context, service *model.ServiceSpec, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) { switch { case expected.HTTP != nil: diff --git a/execute/evaluate/evaluator_test.go b/execute/evaluate/evaluator_test.go index 2714174..318974b 100644 --- a/execute/evaluate/evaluator_test.go +++ b/execute/evaluate/evaluator_test.go @@ -62,14 +62,14 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { Mode: model.ServiceModeMocked, }, }, - []model.CallExpectation{ + []model.ServiceExpectedCalls{ { ServiceID: "http-service", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, { ServiceID: "grpc-service", - GRPC: &model.GRPCCallExpectation{}, + GRPC: &model.GRPCRequestPattern{}, }, }, calls, @@ -388,10 +388,10 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { Kind: model.ServiceKindHTTP, }, }, - []model.CallExpectation{ + []model.ServiceExpectedCalls{ { ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, Count: tt.count, }, }, @@ -468,10 +468,10 @@ func TestEvaluatorEvaluateExpectedCallsError( Kind: model.ServiceKindHTTP, }, }, - []model.CallExpectation{ + []model.ServiceExpectedCalls{ { ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, }, calls, @@ -491,7 +491,7 @@ func TestEvaluatorMatches(t *testing.T) { tests := []struct { name string - expected model.CallExpectation + expected model.ServiceExpectedCalls expectedHTTPCalls int expectedGRPCCalls int @@ -499,16 +499,16 @@ func TestEvaluatorMatches(t *testing.T) { }{ { name: "HTTP", - expected: model.CallExpectation{ - HTTP: &model.HTTPCallExpectation{}, + expected: model.ServiceExpectedCalls{ + HTTP: &model.HTTPRequestPattern{}, }, expectedHTTPCalls: 1, expectedMatch: true, }, { name: "gRPC", - expected: model.CallExpectation{ - GRPC: &model.GRPCCallExpectation{}, + expected: model.ServiceExpectedCalls{ + GRPC: &model.GRPCRequestPattern{}, }, expectedGRPCCalls: 1, expectedMatch: true, @@ -592,8 +592,8 @@ func TestEvaluatorMatchesError(t *testing.T) { context.Background(), &model.ServiceSpec{}, call.Call{}, - model.CallExpectation{ - HTTP: &model.HTTPCallExpectation{}, + model.ServiceExpectedCalls{ + HTTP: &model.HTTPRequestPattern{}, }, ) @@ -619,7 +619,7 @@ func (e *testCallEvaluator) Matches( _ context.Context, _ *model.ServiceSpec, _ call.Call, - _ model.CallExpectation, + _ model.ServiceExpectedCalls, ) (bool, error) { e.matchesCalls++ diff --git a/execute/runtime/environment_test.go b/execute/runtime/environment_test.go index e3b821e..4c0d9a8 100644 --- a/execute/runtime/environment_test.go +++ b/execute/runtime/environment_test.go @@ -885,14 +885,14 @@ func newTestEnvironment( Fixtures: []model.FixtureSpec{ { When: model.FixtureWhen{ - HTTP: &model.HTTPFixtureWhen{ + HTTP: &model.HTTPRequestPattern{ Method: "GET", Path: "/", }, }, Then: model.FixtureThen{ - HTTP: &model.HTTPFixtureThen{ - Status: 200, + HTTP: &model.HTTPResponse{ + StatusCode: 200, }, }, }, @@ -986,14 +986,14 @@ func validTestEnvironment() *model.Environment { Fixtures: []model.FixtureSpec{ { When: model.FixtureWhen{ - HTTP: &model.HTTPFixtureWhen{ + HTTP: &model.HTTPRequestPattern{ Method: "GET", Path: "/", }, }, Then: model.FixtureThen{ - HTTP: &model.HTTPFixtureThen{ - Status: 200, + HTTP: &model.HTTPResponse{ + StatusCode: 200, }, }, }, diff --git a/execute/runtime/router/grpc/router.go b/execute/runtime/router/grpc/router.go index 0fe4b96..e78e385 100644 --- a/execute/runtime/router/grpc/router.go +++ b/execute/runtime/router/grpc/router.go @@ -5,6 +5,7 @@ import ( nativeerrors "errors" "fmt" "net" + "strings" e2engine "github.com/e2engine/instrumentation-go" e2enginegrpc "github.com/e2engine/instrumentation-go/grpc" @@ -300,13 +301,16 @@ func (r *Router) newHandler( responseStatus := status.Convert(err) + service, method := splitFullMethod(fullMethod) + r.calls.Record( call.Call{ TestExecutionID: testExecutionID, ServiceID: route.ServiceID, GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: fullMethod, + Service: service, + Method: method, Metadata: cloneMetadata( incomingMetadata, ), @@ -350,6 +354,14 @@ func (r *Router) newHandler( } } +func splitFullMethod(fullMethod string) (service, method string) { + fullMethod = strings.TrimPrefix(fullMethod, "/") + + service, method, _ = strings.Cut(fullMethod, "/") + + return service, method +} + func cloneMetadata(source metadata.MD) map[string][]string { source = e2enginegrpc.WithoutTestExecutionID(source) diff --git a/execute/runtime/router/grpc/router_test.go b/execute/runtime/router/grpc/router_test.go index 252179a..982aa3e 100644 --- a/execute/runtime/router/grpc/router_test.go +++ b/execute/runtime/router/grpc/router_test.go @@ -352,10 +352,17 @@ func TestRouter(t *testing.T) { t.Fatal("expected gRPC call") } - if got.GRPC.Request.RPC != "/test.Service/Method" { + if got.GRPC.Request.Service != "test.Service" { t.Errorf( - "unexpected RPC %s", - got.GRPC.Request.RPC, + "unexpected service %s", + got.GRPC.Request.Service, + ) + } + + if got.GRPC.Request.Method != "Method" { + t.Errorf( + "unexpected method %s", + got.GRPC.Request.Method, ) } @@ -686,3 +693,87 @@ func newTestGRPCRouter( store, ) } + +func TestSplitFullMethod(t *testing.T) { + tests := []struct { + name string + + fullMethod string + + expectedService string + expectedMethod string + }{ + { + name: "canonical full method", + fullMethod: "/users.UserService/Create", + expectedService: "users.UserService", + expectedMethod: "Create", + }, + { + name: "without leading slash", + fullMethod: "users.UserService/Create", + expectedService: "users.UserService", + expectedMethod: "Create", + }, + { + name: "service without package", + fullMethod: "/UserService/Create", + expectedService: "UserService", + expectedMethod: "Create", + }, + { + name: "empty method", + fullMethod: "/users.UserService/", + expectedService: "users.UserService", + expectedMethod: "", + }, + { + name: "service only", + fullMethod: "/users.UserService", + expectedService: "users.UserService", + expectedMethod: "", + }, + { + name: "empty", + fullMethod: "", + expectedService: "", + expectedMethod: "", + }, + { + name: "slash only", + fullMethod: "/", + expectedService: "", + expectedMethod: "", + }, + { + name: "additional slash remains in method", + fullMethod: "/users.UserService/Create/extra", + expectedService: "users.UserService", + expectedMethod: "Create/extra", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + service, method := splitFullMethod( + tt.fullMethod, + ) + + if service != tt.expectedService { + t.Errorf( + "expected service %q, got %q", + tt.expectedService, + service, + ) + } + + if method != tt.expectedMethod { + t.Errorf( + "expected method %q, got %q", + tt.expectedMethod, + method, + ) + } + }) + } +} diff --git a/execute/runtime/service/grpc/mock.go b/execute/runtime/service/grpc/mock.go index f76ff87..16491de 100644 --- a/execute/runtime/service/grpc/mock.go +++ b/execute/runtime/service/grpc/mock.go @@ -44,11 +44,14 @@ type MethodResolver interface { } type Fixture struct { - rpc string - message map[string]any - - status codes.Code - response map[string]any + service string + method string + metadata map[string][]string + message map[string]any + + status codes.Code + responseMetadata map[string][]string + response map[string]any } func NewMockGRPCService( @@ -58,9 +61,18 @@ func NewMockGRPCService( ) *MockGRPCService { return &MockGRPCService{ logger: logger.With( - log.String(keys.EnvironmentServiceID, spec.ID), - log.String(keys.EnvironmentServiceKind, string(spec.Kind)), - log.String(keys.EnvironmentServiceMode, string(spec.Mode)), + log.String( + keys.EnvironmentServiceID, + spec.ID, + ), + log.String( + keys.EnvironmentServiceKind, + string(spec.Kind), + ), + log.String( + keys.EnvironmentServiceMode, + string(spec.Mode), + ), ), spec: spec, fixtures: compileFixtures(spec.Fixtures), @@ -68,7 +80,9 @@ func NewMockGRPCService( } } -func (s *MockGRPCService) Mount(ctx context.Context) error { +func (s *MockGRPCService) Mount( + ctx context.Context, +) error { if err := ctx.Err(); err != nil { return err } @@ -93,7 +107,10 @@ func (s *MockGRPCService) Mount(ctx context.Context) error { go func() { err := s.server.Serve(listener) if err != nil && - !nativeerrors.Is(err, ggrpc.ErrServerStopped) { + !nativeerrors.Is( + err, + ggrpc.ErrServerStopped, + ) { s.logger.Error( "gRPC mock service stopped unexpectedly", log.Err(keys.Cause, err), @@ -116,7 +133,9 @@ func (s *MockGRPCService) GetRuntimeAddress() string { return s.runtimeAddress } -func (s *MockGRPCService) Unmount(ctx context.Context) error { +func (s *MockGRPCService) Unmount( + ctx context.Context, +) error { if s.server == nil { return nil } @@ -142,7 +161,9 @@ func (s *MockGRPCService) handle( _ any, stream ggrpc.ServerStream, ) error { - fullMethod, ok := ggrpc.MethodFromServerStream(stream) + fullMethod, ok := ggrpc.MethodFromServerStream( + stream, + ) if !ok { return status.Error( codes.Internal, @@ -164,20 +185,32 @@ func (s *MockGRPCService) handle( ) } - if method.IsStreamingClient() || method.IsStreamingServer() { + if method.IsStreamingClient() || + method.IsStreamingServer() { return status.Error( codes.Unimplemented, "streaming RPCs are not supported", ) } - request := dynamicpb.NewMessage(method.Input()) + request := dynamicpb.NewMessage( + method.Input(), + ) if errRecv := stream.RecvMsg(request); errRecv != nil { return errRecv } - fixture, err := s.match(fullMethod, request, method) + incomingMetadata, _ := metadata.FromIncomingContext( + stream.Context(), + ) + + fixture, err := s.match( + fullMethod, + request, + incomingMetadata, + method, + ) if err != nil { return status.Error( codes.Internal, @@ -192,10 +225,7 @@ func (s *MockGRPCService) handle( ) stream.SetTrailer( - metadata.Pairs( - string(keys.E2EngineMockMissMetadata), - "true", - ), + metadata.Pairs(string(keys.E2EngineMockMissMetadata), "true"), ) return status.Error( @@ -204,6 +234,21 @@ func (s *MockGRPCService) handle( ) } + if len(fixture.responseMetadata) > 0 { + responseMetadata := metadata.MD{} + + for key, values := range fixture.responseMetadata { + responseMetadata[key] = append( + []string(nil), + values..., + ) + } + + if errSetHeader := stream.SetHeader(responseMetadata); errSetHeader != nil { + return errSetHeader + } + } + if fixture.status != codes.OK { return status.Error( fixture.status, @@ -230,7 +275,10 @@ func (s *MockGRPCService) handle( } func methodName(fullMethod string) string { - index := strings.LastIndex(fullMethod, "/") + index := strings.LastIndex( + fullMethod, + "/", + ) if index == -1 { return fullMethod } @@ -241,15 +289,29 @@ func methodName(fullMethod string) string { func (s *MockGRPCService) match( fullMethod string, actual proto.Message, + actualMetadata metadata.MD, method protoreflect.MethodDescriptor, ) (*Fixture, error) { - rpc := methodName(fullMethod) + service, methodName, _ := strings.Cut( + strings.TrimPrefix( + fullMethod, + "/", + ), + "/", + ) for i := range s.fixtures { fixture := &s.fixtures[i] - if fixture.rpc != rpc && - fixture.rpc != fullMethod { + if fixture.service != service || + fixture.method != methodName { + continue + } + + if !areMetadataEqual( + fixture.metadata, + actualMetadata, + ) { continue } @@ -268,11 +330,17 @@ func (s *MockGRPCService) match( keys.Operation, "build fixture request message", ), - errorc.Error(keys.Cause, err), + errorc.Error( + keys.Cause, + err, + ), ) } - if proto.Equal(expected, actual) { + if proto.Equal( + expected, + actual, + ) { return fixture, nil } } @@ -280,11 +348,46 @@ func (s *MockGRPCService) match( return nil, nil } +func areMetadataEqual( + expected map[string][]string, + actual metadata.MD, +) bool { + for key, expectedValues := range expected { + actualValues := actual.Get(key) + + if len(expectedValues) != + len(actualValues) { + return false + } + + expectedCounts := make( + map[string]int, + len(expectedValues), + ) + + for _, value := range expectedValues { + expectedCounts[value]++ + } + + for _, value := range actualValues { + if expectedCounts[value] == 0 { + return false + } + + expectedCounts[value]-- + } + } + + return true +} + func buildMessage( descriptor protoreflect.MessageDescriptor, value map[string]any, ) (*dynamicpb.Message, error) { - message := dynamicpb.NewMessage(descriptor) + message := dynamicpb.NewMessage( + descriptor, + ) if len(value) == 0 { return message, nil @@ -298,18 +401,27 @@ func buildMessage( keys.Operation, "marshal gRPC message value", ), - errorc.Error(keys.Cause, err), + errorc.Error( + keys.Cause, + err, + ), ) } - if err := protojson.Unmarshal(data, message); err != nil { + if err := protojson.Unmarshal( + data, + message, + ); err != nil { return nil, errorc.With( errors.ErrCannotBuildGRPCMessage, errorc.String( keys.Operation, "unmarshal gRPC message", ), - errorc.Error(keys.Cause, err), + errorc.Error( + keys.Cause, + err, + ), ) } @@ -319,7 +431,11 @@ func buildMessage( func compileFixtures( specs []model.FixtureSpec, ) []Fixture { - fixtures := make([]Fixture, 0, len(specs)) + fixtures := make( + []Fixture, + 0, + len(specs), + ) for i := range specs { spec := &specs[i] @@ -332,10 +448,16 @@ func compileFixtures( fixtures = append( fixtures, Fixture{ - rpc: spec.When.GRPC.Method, + service: spec.When.GRPC.Service, + method: spec.When.GRPC.Method, + metadata: spec.When.GRPC.Metadata, message: spec.When.GRPC.Message, - status: grpcCode(spec.Then.GRPC.Status), - response: spec.Then.GRPC.Message, + + status: grpcCode( + spec.Then.GRPC.Status, + ), + responseMetadata: spec.Then.GRPC.Metadata, + response: spec.Then.GRPC.Message, }, ) } diff --git a/execute/runtime/service/grpc/mock_test.go b/execute/runtime/service/grpc/mock_test.go index cd0e2f0..fa1858e 100644 --- a/execute/runtime/service/grpc/mock_test.go +++ b/execute/runtime/service/grpc/mock_test.go @@ -9,6 +9,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/metadata" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protodesc" "google.golang.org/protobuf/reflect/protoreflect" @@ -170,16 +171,29 @@ func TestCompileFixtures(t *testing.T) { specs := []model.FixtureSpec{ { When: model.FixtureWhen{ - GRPC: &model.GRPCFixtureWhen{ - Method: "GetUser", + GRPC: &model.GRPCRequestPattern{ + Service: "users.v1.UserService", + Method: "GetUser", + Metadata: map[string][]string{ + "x-request-id": { + "one", + "two", + }, + }, Message: map[string]any{ "id": "42", }, }, }, Then: model.FixtureThen{ - GRPC: &model.GRPCFixtureThen{ + GRPC: &model.GRPCResponse{ Status: "not_found", + Metadata: map[string][]string{ + "x-response-id": { + "three", + "four", + }, + }, Message: map[string]any{ "message": "not found", }, @@ -189,15 +203,16 @@ func TestCompileFixtures(t *testing.T) { { When: model.FixtureWhen{}, Then: model.FixtureThen{ - GRPC: &model.GRPCFixtureThen{ + GRPC: &model.GRPCResponse{ Status: "ok", }, }, }, { When: model.FixtureWhen{ - GRPC: &model.GRPCFixtureWhen{ - Method: "Ignored", + GRPC: &model.GRPCRequestPattern{ + Service: "users.v1.UserService", + Method: "Ignored", }, }, Then: model.FixtureThen{}, @@ -215,11 +230,19 @@ func TestCompileFixtures(t *testing.T) { fixture := fixtures[0] - if fixture.rpc != "GetUser" { + if fixture.service != "users.v1.UserService" { t.Errorf( - "expected rpc %q, got %q", + "expected service %q, got %q", + "users.v1.UserService", + fixture.service, + ) + } + + if fixture.method != "GetUser" { + t.Errorf( + "expected method %q, got %q", "GetUser", - fixture.rpc, + fixture.method, ) } @@ -246,6 +269,26 @@ func TestCompileFixtures(t *testing.T) { fixture.response["message"], ) } + + requestMetadata := fixture.metadata["x-request-id"] + if len(requestMetadata) != 2 || + requestMetadata[0] != "one" || + requestMetadata[1] != "two" { + t.Errorf( + "expected request metadata [one two], got %v", + requestMetadata, + ) + } + + responseMetadata := fixture.responseMetadata["x-response-id"] + if len(responseMetadata) != 2 || + responseMetadata[0] != "three" || + responseMetadata[1] != "four" { + t.Errorf( + "expected response metadata [three four], got %v", + responseMetadata, + ) + } } func TestBuildMessage(t *testing.T) { @@ -297,7 +340,9 @@ func TestBuildMessage(t *testing.T) { } if actual := message.Get(active).Bool(); !actual { - t.Error("expected active to be true") + t.Error( + "expected active to be true", + ) } }, }, @@ -315,7 +360,9 @@ func TestBuildMessage(t *testing.T) { ) { t.Helper() - tags := descriptor.Fields().ByName("tags") + tags := descriptor.Fields().ByName( + "tags", + ) list := message.Get(tags).List() if list.Len() != 2 { @@ -357,7 +404,10 @@ func TestBuildMessage(t *testing.T) { ) } - tt.expected(t, message) + tt.expected( + t, + message, + ) }) } } @@ -387,6 +437,109 @@ func TestBuildMessageInvalidField(t *testing.T) { } } +func TestAreMetadataEqual(t *testing.T) { + tests := []struct { + name string + expected map[string][]string + actual metadata.MD + want bool + }{ + { + name: "nil expected", + expected: nil, + actual: metadata.MD{ + "additional": {"value"}, + }, + want: true, + }, + { + name: "matching value", + expected: map[string][]string{ + "x-request-id": {"one"}, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + }, + want: true, + }, + { + name: "matching repeated values", + expected: map[string][]string{ + "x-request-id": { + "one", + "two", + }, + }, + actual: metadata.MD{ + "x-request-id": { + "two", + "one", + }, + }, + want: true, + }, + { + name: "additional actual key ignored", + expected: map[string][]string{ + "x-request-id": {"one"}, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + "additional": {"value"}, + }, + want: true, + }, + { + name: "missing expected key", + expected: map[string][]string{ + "x-request-id": {"one"}, + }, + actual: metadata.MD{}, + want: false, + }, + { + name: "different value", + expected: map[string][]string{ + "x-request-id": {"one"}, + }, + actual: metadata.MD{ + "x-request-id": {"two"}, + }, + want: false, + }, + { + name: "additional value for expected key", + expected: map[string][]string{ + "x-request-id": {"one"}, + }, + actual: metadata.MD{ + "x-request-id": { + "one", + "two", + }, + }, + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := areMetadataEqual( + tt.expected, + tt.actual, + ) + + if actual != tt.want { + t.Errorf( + "expected %v, got %v", + tt.want, + actual, + ) + } + }) + } +} + func TestMockGRPCServiceMatch(t *testing.T) { method := testMethodDescriptor(t) @@ -397,21 +550,26 @@ func TestMockGRPCServiceMatch(t *testing.T) { }, ) if err != nil { - t.Fatalf("cannot build request: %v", err) + t.Fatalf( + "cannot build request: %v", + err, + ) } tests := []struct { name string fullMethod string + metadata metadata.MD fixtures []Fixture expected bool }{ { - name: "short rpc", + name: "service method and message", fullMethod: "/users.v1.UserService/GetUser", fixtures: []Fixture{ { - rpc: "GetUser", + service: "users.v1.UserService", + method: "GetUser", message: map[string]any{ "id": "42", }, @@ -420,11 +578,24 @@ func TestMockGRPCServiceMatch(t *testing.T) { expected: true, }, { - name: "full method", + name: "metadata", fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": { + "two", + "one", + }, + }, fixtures: []Fixture{ { - rpc: "/users.v1.UserService/GetUser", + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": { + "one", + "two", + }, + }, message: map[string]any{ "id": "42", }, @@ -433,11 +604,47 @@ func TestMockGRPCServiceMatch(t *testing.T) { expected: true, }, { - name: "different rpc", + name: "additional metadata ignored", fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": {"one"}, + "additional": {"value"}, + }, fixtures: []Fixture{ { - rpc: "CreateUser", + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": {"one"}, + }, + message: map[string]any{ + "id": "42", + }, + }, + }, + expected: true, + }, + { + name: "different service", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.AdminService", + method: "GetUser", + message: map[string]any{ + "id": "42", + }, + }, + }, + expected: false, + }, + { + name: "different method", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "CreateUser", message: map[string]any{ "id": "42", }, @@ -450,7 +657,8 @@ func TestMockGRPCServiceMatch(t *testing.T) { fullMethod: "/users.v1.UserService/GetUser", fixtures: []Fixture{ { - rpc: "GetUser", + service: "users.v1.UserService", + method: "GetUser", message: map[string]any{ "id": "43", }, @@ -458,6 +666,66 @@ func TestMockGRPCServiceMatch(t *testing.T) { }, expected: false, }, + { + name: "missing metadata", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": {"one"}, + }, + message: map[string]any{ + "id": "42", + }, + }, + }, + expected: false, + }, + { + name: "different metadata", + fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": {"two"}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": {"one"}, + }, + message: map[string]any{ + "id": "42", + }, + }, + }, + expected: false, + }, + { + name: "additional value for specified metadata key", + fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": { + "one", + "two", + }, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": {"one"}, + }, + message: map[string]any{ + "id": "42", + }, + }, + }, + expected: false, + }, } for _, tt := range tests { @@ -469,10 +737,14 @@ func TestMockGRPCServiceMatch(t *testing.T) { fixture, err := service.match( tt.fullMethod, request, + tt.metadata, method, ) if err != nil { - t.Fatalf("match() error = %v", err) + t.Fatalf( + "match() error = %v", + err, + ) } if tt.expected && fixture == nil { @@ -501,13 +773,17 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( }, ) if err != nil { - t.Fatalf("cannot build request: %v", err) + t.Fatalf( + "cannot build request: %v", + err, + ) } service := &MockGRPCService{ fixtures: []Fixture{ { - rpc: "GetUser", + service: "users.v1.UserService", + method: "GetUser", message: map[string]any{ "unknown": "value", }, @@ -518,6 +794,7 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( _, err = service.match( "/users.v1.UserService/GetUser", request, + nil, method, ) if err == nil { @@ -536,7 +813,9 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( } } -func TestMockGRPCServiceMountCanceledContext(t *testing.T) { +func TestMockGRPCServiceMountCanceledContext( + t *testing.T, +) { service := &MockGRPCService{} ctx, cancel := context.WithCancel( @@ -546,7 +825,10 @@ func TestMockGRPCServiceMountCanceledContext(t *testing.T) { err := service.Mount(ctx) - if !nativeerrors.Is(err, context.Canceled) { + if !nativeerrors.Is( + err, + context.Canceled, + ) { t.Errorf( "expected %v, got %v", context.Canceled, @@ -555,15 +837,21 @@ func TestMockGRPCServiceMountCanceledContext(t *testing.T) { } if service.listener != nil { - t.Error("expected listener not to be created") + t.Error( + "expected listener not to be created", + ) } if service.server != nil { - t.Error("expected server not to be created") + t.Error( + "expected server not to be created", + ) } } -func TestMockGRPCServiceUnmountBeforeMount(t *testing.T) { +func TestMockGRPCServiceUnmountBeforeMount( + t *testing.T, +) { service := &MockGRPCService{} if err := service.Unmount( @@ -609,9 +897,13 @@ func testMethodDescriptor( ) } - method := service.Methods().ByName("GetUser") + method := service.Methods().ByName( + "GetUser", + ) if method == nil { - t.Fatal("GetUser method not found") + t.Fatal( + "GetUser method not found", + ) } return method @@ -731,7 +1023,10 @@ func (r *testMethodResolver) ResolveMethod( func TestMockGRPCServiceHandle(t *testing.T) { logger, err := log.NewSilentLogger() if err != nil { - t.Fatalf("Unexpected NewSilentLogger error: %q", err) + t.Fatalf( + "Unexpected NewSilentLogger error: %q", + err, + ) } method := testMethodDescriptor(t) @@ -743,11 +1038,24 @@ func TestMockGRPCServiceHandle(t *testing.T) { }, fixtures: []Fixture{ { - rpc: "GetUser", + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]string{ + "x-request-id": { + "one", + "two", + }, + }, message: map[string]any{ "id": "42", }, status: codes.OK, + responseMetadata: map[string][]string{ + "x-response-id": { + "three", + "four", + }, + }, response: map[string]any{ "name": "Yaroslav", }, @@ -813,15 +1121,28 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } + ctx = metadata.NewOutgoingContext( + ctx, + metadata.MD{ + "x-request-id": { + "one", + "two", + }, + }, + ) + response := dynamicpb.NewMessage( method.Output(), ) + var header metadata.MD + if err := conn.Invoke( ctx, "/users.v1.UserService/GetUser", request, response, + grpc.Header(&header), ); err != nil { t.Fatalf( "Invoke() error = %v", @@ -829,12 +1150,46 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } + responseMetadata := header.Get( + "x-response-id", + ) + if len(responseMetadata) != 2 { + t.Fatalf( + "expected 2 response metadata values, got %v", + responseMetadata, + ) + } + + if !containsString( + responseMetadata, + "three", + ) { + t.Errorf( + "expected response metadata to contain %q, got %v", + "three", + responseMetadata, + ) + } + + if !containsString( + responseMetadata, + "four", + ) { + t.Errorf( + "expected response metadata to contain %q, got %v", + "four", + responseMetadata, + ) + } + name := method.Output(). Fields(). ByName("name") if name == nil { - t.Fatal("name field not found") + t.Fatal( + "name field not found", + ) } if actual := response.Get(name).String(); actual != "Yaroslav" { @@ -845,3 +1200,16 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } } + +func containsString( + values []string, + expected string, +) bool { + for _, value := range values { + if value == expected { + return true + } + } + + return false +} diff --git a/execute/runtime/service/http/mock.go b/execute/runtime/service/http/mock.go index 29f6159..aa5fda1 100644 --- a/execute/runtime/service/http/mock.go +++ b/execute/runtime/service/http/mock.go @@ -139,35 +139,56 @@ func (s *MockHTTPService) match(r *http.Request) (*Fixture, error) { ) } - for _, fixture := range s.fixtures { - if fixture.method == r.Method && - fixture.path == r.URL.Path && - areQueryParamsEqual(fixture.query, r.URL.Query()) && - areHeadersEqual(fixture.headers, r.Header) && - isBodyEqual(fixture.body, body) { - return &fixture, nil + for i := range s.fixtures { + if s.fixtures[i].method == r.Method && + s.fixtures[i].path == r.URL.Path && + areQueryParamsEqual(s.fixtures[i].query, r.URL.Query()) && + areHeadersEqual(s.fixtures[i].headers, r.Header) && + isBodyEqual( + s.fixtures[i].body, + s.fixtures[i].bodyJSON, + body, + ) { + return &s.fixtures[i], nil } } return nil, nil } -func isBodyEqual(expected, actual []byte) bool { - if len(expected) == 0 || len(actual) == 0 { - return len(expected) == len(actual) +func isBodyEqual( + expectedBody string, + expectedBodyJSON string, + actual []byte, +) bool { + if expectedBody != "" { + return expectedBody == string(actual) } - var expectedValue any - if err := json.Unmarshal(expected, &expectedValue); err != nil { - return false - } + if expectedBodyJSON != "" { + var expectedValue any + if err := json.Unmarshal( + []byte(expectedBodyJSON), + &expectedValue, + ); err != nil { + return false + } - var actualValue any - if err := json.Unmarshal(actual, &actualValue); err != nil { - return false + var actualValue any + if err := json.Unmarshal( + actual, + &actualValue, + ); err != nil { + return false + } + + return reflect.DeepEqual( + expectedValue, + actualValue, + ) } - return reflect.DeepEqual(expectedValue, actualValue) + return len(actual) == 0 } func areHeadersEqual(expected, actual http.Header) bool { @@ -197,7 +218,10 @@ func areQueryParamsEqual( return reflect.DeepEqual(expected, actual) } -func (s *MockHTTPService) respond(w http.ResponseWriter, fixture *Fixture) { +func (s *MockHTTPService) respond( + w http.ResponseWriter, + fixture *Fixture, +) { for k, values := range fixture.responseHeaders { for _, v := range values { w.Header().Add(k, v) @@ -205,23 +229,15 @@ func (s *MockHTTPService) respond(w http.ResponseWriter, fixture *Fixture) { } var body []byte - if len(fixture.responseBody) > 0 { - var err error - body, err = json.Marshal(fixture.responseBody) - if err != nil { - s.logger.Error( - errors.ErrFailedToMarshalResponseBody.Error(), - log.String(keys.RequestMethod, fixture.method), - log.String(keys.RequestURLPath, fixture.path), - log.Err(keys.Cause, err), - ) - http.Error( - w, - errors.ErrFailedToMarshalResponseBody.Error(), - http.StatusInternalServerError, - ) - return - } + + if fixture.responseBody != "" { + body = []byte( + fixture.responseBody, + ) + } else if fixture.responseBodyJSON != "" { + body = []byte( + fixture.responseBodyJSON, + ) } w.WriteHeader(fixture.status) @@ -230,10 +246,17 @@ func (s *MockHTTPService) respond(w http.ResponseWriter, fixture *Fixture) { if _, err := w.Write(body); err != nil { s.logger.Error( errors.ErrFailedToWriteResponseBody.Error(), - log.String(keys.RequestMethod, fixture.method), - log.String(keys.RequestURLPath, fixture.path), + log.String( + keys.RequestMethod, + fixture.method, + ), + log.String( + keys.RequestURLPath, + fixture.path, + ), log.Err(keys.Cause, err), ) + return } } @@ -244,32 +267,48 @@ type Fixture struct { path string query url.Values headers map[string][]string - body json.RawMessage + + body string + bodyJSON string status int responseHeaders map[string][]string - responseBody json.RawMessage + + responseBody string + responseBodyJSON string } -func compileFixtures(specs []model.FixtureSpec) []Fixture { - fixtures := make([]Fixture, len(specs)) +func compileFixtures( + specs []model.FixtureSpec, +) []Fixture { + fixtures := make( + []Fixture, + len(specs), + ) + for i, spec := range specs { // Path is validated by ServiceSpec.Validate. - u, _ := url.ParseRequestURI(spec.When.HTTP.Path) + u, _ := url.ParseRequestURI( + spec.When.HTTP.Path, + ) - fixture := Fixture{ + fixtures[i] = Fixture{ method: spec.When.HTTP.Method, path: u.Path, query: u.Query(), headers: spec.When.HTTP.Headers, - body: json.RawMessage(spec.When.HTTP.Body), - status: spec.Then.HTTP.Status, + body: spec.When.HTTP.Body, + bodyJSON: spec.When.HTTP.BodyJSON, + + status: spec.Then.HTTP.StatusCode, + responseHeaders: spec.Then.HTTP.Headers, - responseBody: json.RawMessage(spec.Then.HTTP.Body), - } - fixtures[i] = fixture + responseBody: spec.Then.HTTP.Body, + responseBodyJSON: spec.Then.HTTP.BodyJSON, + } } + return fixtures } diff --git a/execute/runtime/service/http/mock_test.go b/execute/runtime/service/http/mock_test.go index 6737e86..2d01e73 100644 --- a/execute/runtime/service/http/mock_test.go +++ b/execute/runtime/service/http/mock_test.go @@ -25,11 +25,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss bool }{ { - name: "method path and body match", + name: "JSON object body matches semantically", fixture: newHTTPFixture( "POST", "/users", nil, + "", `{"name":"Alice","age":42}`, http.StatusCreated, ), @@ -40,11 +41,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusCreated, }, { - name: "array body", + name: "JSON array body", fixture: newHTTPFixture( "POST", "/values", nil, + "", `[1,2,3]`, http.StatusOK, ), @@ -55,11 +57,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "scalar body", + name: "JSON scalar body", fixture: newHTTPFixture( "POST", "/value", nil, + "", `42`, http.StatusOK, ), @@ -70,11 +73,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "string body", + name: "JSON string body", fixture: newHTTPFixture( "POST", "/value", nil, + "", `"hello"`, http.StatusOK, ), @@ -85,11 +89,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "boolean body", + name: "JSON boolean body", fixture: newHTTPFixture( "POST", "/value", nil, + "", `true`, http.StatusOK, ), @@ -100,11 +105,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "null body", + name: "JSON null body", fixture: newHTTPFixture( "POST", "/value", nil, + "", `null`, http.StatusOK, ), @@ -114,6 +120,55 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, + { + name: "exact text body", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + "hello world", + "", + http.StatusOK, + ), + method: "POST", + path: "/text", + body: "hello world", + + expectedStatus: http.StatusOK, + }, + { + name: "arbitrary non-JSON text body", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + "this is not JSON: {", + "", + http.StatusOK, + ), + method: "POST", + path: "/text", + body: "this is not JSON: {", + + expectedStatus: http.StatusOK, + }, + { + name: "text body uses exact semantics", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + `{"name":"Alice","age":42}`, + "", + http.StatusOK, + ), + method: "POST", + path: "/users", + body: `{"age":42,"name":"Alice"}`, + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, { name: "empty body", fixture: newHTTPFixture( @@ -121,6 +176,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users", nil, "", + "", http.StatusOK, ), method: "GET", @@ -135,6 +191,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users?status=active&page=2", nil, "", + "", http.StatusOK, ), method: "GET", @@ -149,6 +206,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users?role=admin&role=operator", nil, "", + "", http.StatusOK, ), method: "GET", @@ -165,6 +223,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"one", "two"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -184,6 +243,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"expected"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -204,6 +264,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"expected"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -221,6 +282,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users", nil, "", + "", http.StatusOK, ), method: "POST", @@ -236,6 +298,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users", nil, "", + "", http.StatusOK, ), method: "GET", @@ -251,6 +314,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users?page=1", nil, "", + "", http.StatusOK, ), method: "GET", @@ -266,6 +330,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users", nil, "", + "", http.StatusOK, ), method: "GET", @@ -283,6 +348,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"expected"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -300,6 +366,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"expected"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -320,6 +387,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "X-Test": {"expected"}, }, "", + "", http.StatusOK, ), method: "GET", @@ -332,11 +400,12 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss: true, }, { - name: "body miss", + name: "JSON body miss", fixture: newHTTPFixture( "POST", "/users", nil, + "", `{"name":"Alice"}`, http.StatusOK, ), @@ -347,6 +416,23 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusNotImplemented, expectedMiss: true, }, + { + name: "text body miss", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + "expected", + "", + http.StatusOK, + ), + method: "POST", + path: "/text", + body: "actual", + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, { name: "expected empty body actual non-empty body is miss", fixture: newHTTPFixture( @@ -354,6 +440,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { "/users", nil, "", + "", http.StatusOK, ), method: "POST", @@ -364,17 +451,34 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss: true, }, { - name: "expected body actual empty body is miss", + name: "expected JSON body actual empty body is miss", fixture: newHTTPFixture( "POST", "/users", nil, + "", `{}`, http.StatusOK, ), method: "POST", path: "/users", + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, + { + name: "expected text body actual empty body is miss", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + "expected", + "", + http.StatusOK, + ), + method: "POST", + path: "/text", + expectedStatus: http.StatusNotImplemented, expectedMiss: true, }, @@ -387,34 +491,56 @@ func TestMockHTTPServiceMatch(t *testing.T) { []model.FixtureSpec{tt.fixture}, ) - if err := service.Mount(context.Background()); err != nil { - t.Fatalf("Mount() error = %v", err) + if err := service.Mount( + context.Background(), + ); err != nil { + t.Fatalf( + "Mount() error = %v", + err, + ) } + t.Cleanup(func() { - if err := service.Unmount(context.Background()); err != nil { - t.Errorf("Unmount() error = %v", err) + if err := service.Unmount( + context.Background(), + ); err != nil { + t.Errorf( + "Unmount() error = %v", + err, + ) } }) req, err := http.NewRequestWithContext( t.Context(), tt.method, - "http://"+service.GetRuntimeAddress()+tt.path, + "http://"+ + service.GetRuntimeAddress()+ + tt.path, strings.NewReader(tt.body), ) if err != nil { - t.Fatalf("cannot create request: %v", err) + t.Fatalf( + "cannot create request: %v", + err, + ) } for key, values := range tt.headers { for _, value := range values { - req.Header.Add(key, value) + req.Header.Add( + key, + value, + ) } } resp, err := http.DefaultClient.Do(req) if err != nil { - t.Fatalf("request error = %v", err) + t.Fatalf( + "request error = %v", + err, + ) } defer resp.Body.Close() @@ -427,7 +553,9 @@ func TestMockHTTPServiceMatch(t *testing.T) { } gotMiss := resp.Header.Get( - string(keys.E2EngineMockMissHeader), + string( + keys.E2EngineMockMissHeader, + ), ) == "true" if gotMiss != tt.expectedMiss { @@ -442,83 +570,137 @@ func TestMockHTTPServiceMatch(t *testing.T) { } func TestMockHTTPServiceResponse(t *testing.T) { - service := newTestMockHTTPService( - t, - []model.FixtureSpec{ - { - When: model.FixtureWhen{ - HTTP: &model.HTTPFixtureWhen{ - Method: "GET", - Path: "/users", - }, + tests := []struct { + name string + response *model.HTTPResponse + expectedBody string + }{ + { + name: "text body", + response: &model.HTTPResponse{ + StatusCode: http.StatusCreated, + Headers: map[string][]string{ + "X-Test": {"one", "two"}, }, - Then: model.FixtureThen{ - HTTP: &model.HTTPFixtureThen{ - Status: http.StatusCreated, - Headers: map[string][]string{ - "X-Test": {"one", "two"}, - }, - Body: `{"id":42}`, - }, + Body: "plain text response", + }, + expectedBody: "plain text response", + }, + { + name: "JSON body preserves authored representation", + response: &model.HTTPResponse{ + StatusCode: http.StatusCreated, + Headers: map[string][]string{ + "X-Test": {"one", "two"}, }, + BodyJSON: "{\n \"id\": 42\n}", }, + expectedBody: "{\n \"id\": 42\n}", }, - ) - - if err := service.Mount(context.Background()); err != nil { - t.Fatalf("Mount() error = %v", err) - } - t.Cleanup(func() { - if err := service.Unmount(context.Background()); err != nil { - t.Errorf("Unmount() error = %v", err) - } - }) - - req, err := http.NewRequestWithContext( - t.Context(), - http.MethodGet, - "http://"+service.GetRuntimeAddress()+"/users", - nil, - ) - if err != nil { - t.Fatalf("cannot create request: %v", err) } - resp, err := http.DefaultClient.Do(req) - if err != nil { - t.Fatalf("request error = %v", err) - } - defer resp.Body.Close() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + service := newTestMockHTTPService( + t, + []model.FixtureSpec{ + { + When: model.FixtureWhen{ + HTTP: &model.HTTPRequestPattern{ + Method: "GET", + Path: "/users", + }, + }, + Then: model.FixtureThen{ + HTTP: tt.response, + }, + }, + }, + ) - if resp.StatusCode != http.StatusCreated { - t.Errorf( - "expected status %d, got %d", - http.StatusCreated, - resp.StatusCode, - ) - } + if err := service.Mount( + context.Background(), + ); err != nil { + t.Fatalf( + "Mount() error = %v", + err, + ) + } - values := resp.Header.Values("X-Test") - if len(values) != 2 || - values[0] != "one" || - values[1] != "two" { - t.Errorf( - "expected X-Test headers [one two], got %v", - values, - ) - } + t.Cleanup(func() { + if err := service.Unmount( + context.Background(), + ); err != nil { + t.Errorf( + "Unmount() error = %v", + err, + ) + } + }) - body, err := io.ReadAll(resp.Body) - if err != nil { - t.Fatalf("cannot read response body: %v", err) - } + req, err := http.NewRequestWithContext( + t.Context(), + http.MethodGet, + "http://"+ + service.GetRuntimeAddress()+ + "/users", + nil, + ) + if err != nil { + t.Fatalf( + "cannot create request: %v", + err, + ) + } - if string(body) != `{"id":42}` { - t.Errorf( - "expected response body %q, got %q", - `{"id":42}`, - string(body), - ) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf( + "request error = %v", + err, + ) + } + defer resp.Body.Close() + + if resp.StatusCode != + http.StatusCreated { + t.Errorf( + "expected status %d, got %d", + http.StatusCreated, + resp.StatusCode, + ) + } + + values := resp.Header.Values( + "X-Test", + ) + if len(values) != 2 || + values[0] != "one" || + values[1] != "two" { + t.Errorf( + "expected X-Test headers [one two], got %v", + values, + ) + } + + body, err := io.ReadAll( + resp.Body, + ) + if err != nil { + t.Fatalf( + "cannot read response body: %v", + err, + ) + } + + if string(body) != tt.expectedBody { + t.Errorf( + "expected response body %q, got %q", + tt.expectedBody, + string(body), + ) + } + }) } } @@ -552,21 +734,23 @@ func newHTTPFixture( method, path string, headers map[string][]string, - body string, + body, + bodyJSON string, status int, ) model.FixtureSpec { return model.FixtureSpec{ When: model.FixtureWhen{ - HTTP: &model.HTTPFixtureWhen{ - Method: method, - Path: path, - Headers: headers, - Body: body, + HTTP: &model.HTTPRequestPattern{ + Method: method, + Path: path, + Headers: headers, + Body: body, + BodyJSON: bodyJSON, }, }, Then: model.FixtureThen{ - HTTP: &model.HTTPFixtureThen{ - Status: status, + HTTP: &model.HTTPResponse{ + StatusCode: status, }, }, } diff --git a/execute/worker/grpc/evaluate.go b/execute/worker/grpc/evaluate.go index e741653..90444c8 100644 --- a/execute/worker/grpc/evaluate.go +++ b/execute/worker/grpc/evaluate.go @@ -3,6 +3,7 @@ package grpc import ( "context" "encoding/json" + "strings" "github.com/ygrebnov/errorc" "google.golang.org/grpc/codes" @@ -46,7 +47,7 @@ func (e *Evaluator) EvaluateResponse( response *dynamicpb.Message, header metadata.MD, trailer metadata.MD, - expect *model.GRPCExpectSpec, + expect *model.GRPCResponse, result *execute.TestExecutionResult, ) error { if err := ctx.Err(); err != nil { @@ -54,7 +55,7 @@ func (e *Evaluator) EvaluateResponse( } result.Summary.Response = &model.TestExecutionResponseSummary{ - GRPC: &model.TestExecutionGRPCResponseSummary{}, + GRPC: &model.GRPCResponse{}, } actualStatus := status.Code(callErr) @@ -62,8 +63,10 @@ func (e *Evaluator) EvaluateResponse( result.Summary.Response.GRPC.Status = actualStatus.String() + actualMetadata := mergeMetadata(header, trailer) + result.Summary.Response.GRPC.Metadata = - mergeMetadata(header, trailer) + selectMetadata(actualMetadata, expect.Metadata) expectedStatus, err := grpcCode( expect.Status, @@ -83,6 +86,25 @@ func (e *Evaluator) EvaluateResponse( ) } + for key, expectedValues := range expect.Metadata { + actualValues, ok := actualMetadata[key] + if ok && util.IsStringSlicesEqual( + actualValues, + expectedValues, + ) { + continue + } + + result.Summary.Deviations = append( + result.Summary.Deviations, + model.TestExecutionDeviation{ + Field: "metadata." + key, + Expected: strings.Join(expectedValues, ","), + Actual: strings.Join(actualValues, ","), + }, + ) + } + responseMap, err := messageToMap(response) if err != nil { return err @@ -139,11 +161,37 @@ func (e *Evaluator) EvaluateResponse( return nil } +func selectMetadata( + actual map[string][]string, + expected map[string][]string, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for key := range expected { + if values, ok := actual[key]; ok { + result[key] = util.CloneStringSlice(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + func (e *Evaluator) Matches( ctx context.Context, service *model.ServiceSpec, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) { if actual.ServiceID != expected.ServiceID { return false, nil @@ -154,13 +202,8 @@ func (e *Evaluator) Matches( return false, nil } - expectedRPC := - "/" + - expected.GRPC.Service + - "/" + - expected.GRPC.Method - - if actual.GRPC.Request.RPC != expectedRPC { + if actual.GRPC.Request.Service != expected.GRPC.Service || + actual.GRPC.Request.Method != expected.GRPC.Method { return false, nil } @@ -237,9 +280,14 @@ func (e *Evaluator) Deviation( return nil } + actualRPC := "/" + + actual.GRPC.Request.Service + + "/" + + actual.GRPC.Request.Method + return &model.TestExecutionDeviation{ Field: "calls." + service.ID, - Actual: actual.GRPC.Request.RPC, + Actual: actualRPC, Message: "mocked service received a request " + "that did not match any fixture", } diff --git a/execute/worker/grpc/evaluate_test.go b/execute/worker/grpc/evaluate_test.go index 22f09c5..a36315f 100644 --- a/execute/worker/grpc/evaluate_test.go +++ b/execute/worker/grpc/evaluate_test.go @@ -31,7 +31,7 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { header metadata.MD trailer metadata.MD message map[string]any - expect model.GRPCExpectSpec + expect model.GRPCResponse expectedStatus string expectedMetadata map[string][]string @@ -41,28 +41,130 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { { name: "matching response", header: metadata.MD{ - "x-header": {"header-value"}, + "x-header": { + "header-value", + }, + "x-ignored": { + "ignored-value", + }, }, trailer: metadata.MD{ - "x-trailer": {"trailer-value"}, + "x-trailer": { + "trailer-value", + }, }, message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponse{ Status: "OK", + Metadata: map[string][]string{ + "x-header": { + "header-value", + }, + "x-trailer": { + "trailer-value", + }, + }, Message: map[string]any{ "name": "actual", }, }, expectedStatus: "OK", expectedMetadata: map[string][]string{ - "x-header": {"header-value"}, - "x-trailer": {"trailer-value"}, + "x-header": { + "header-value", + }, + "x-trailer": { + "trailer-value", + }, + }, + expectedMessage: map[string]any{ + "name": "actual", + }, + }, + { + name: "unrelated metadata is not persisted", + header: metadata.MD{ + "x-header": { + "header-value", + }, + }, + trailer: metadata.MD{ + "x-trailer": { + "trailer-value", + }, + }, + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponse{ + Status: "OK", + }, + expectedStatus: "OK", + expectedMessage: map[string]any{ + "name": "actual", + }, + }, + { + name: "metadata mismatch", + header: metadata.MD{ + "x-header": { + "actual", + }, + }, + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "x-header": { + "expected", + }, + }, + }, + expectedStatus: "OK", + expectedMetadata: map[string][]string{ + "x-header": { + "actual", + }, }, expectedMessage: map[string]any{ "name": "actual", }, + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "expected", + Actual: "actual", + }, + }, + }, + { + name: "expected metadata missing", + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "x-header": { + "expected", + }, + }, + }, + expectedStatus: "OK", + expectedMessage: map[string]any{ + "name": "actual", + }, + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "expected", + Actual: "", + }, + }, }, { name: "status mismatch", @@ -73,11 +175,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponse{ Status: "OK", }, - expectedStatus: "NotFound", - expectedMetadata: map[string][]string{}, + expectedStatus: "NotFound", expectedMessage: map[string]any{ "name": "actual", }, @@ -94,14 +195,13 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponse{ Status: "OK", Message: map[string]any{ "name": "expected", }, }, - expectedStatus: "OK", - expectedMetadata: map[string][]string{}, + expectedStatus: "OK", expectedMessage: map[string]any{ "name": "actual", }, @@ -118,11 +218,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponse{ Status: "OK", }, - expectedStatus: "OK", - expectedMetadata: map[string][]string{}, + expectedStatus: "OK", expectedMessage: map[string]any{ "name": "actual", }, @@ -160,7 +259,9 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { actual := result.Summary.Response.GRPC if actual == nil { - t.Fatal("expected gRPC response summary") + t.Fatal( + "expected gRPC response summary", + ) } if actual.Status != tt.expectedStatus { @@ -225,7 +326,7 @@ func TestEvaluatorEvaluateResponseCancelledContext( ), nil, nil, - &model.GRPCExpectSpec{ + &model.GRPCResponse{ Status: "OK", }, result, @@ -257,7 +358,7 @@ func TestEvaluatorEvaluateResponseUnknownStatus( ), nil, nil, - &model.GRPCExpectSpec{ + &model.GRPCResponse{ Status: "invalid", }, result, @@ -311,9 +412,12 @@ func TestEvaluatorMatches(t *testing.T) { ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Create", + Service: "users.UserService", + Method: "Create", Metadata: map[string][]string{ - "x-request-id": {"request-1"}, + "x-request-id": { + "request-1", + }, }, Message: messageBytes, }, @@ -324,20 +428,22 @@ func TestEvaluatorMatches(t *testing.T) { name string actual call.Call - expected model.CallExpectation + expected model.ServiceExpectedCalls match bool }{ { name: "matches", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", Metadata: map[string][]string{ - "x-request-id": {"request-1"}, + "x-request-id": { + "request-1", + }, }, Message: map[string]any{ "name": "Yaroslav", @@ -349,9 +455,9 @@ func TestEvaluatorMatches(t *testing.T) { { name: "different service", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-2", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", }, @@ -362,9 +468,9 @@ func TestEvaluatorMatches(t *testing.T) { actual: call.Call{ ServiceID: "service-1", }, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", }, @@ -373,16 +479,16 @@ func TestEvaluatorMatches(t *testing.T) { { name: "expectation is not gRPC", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", }, }, { name: "RPC mismatch", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Get", }, @@ -391,13 +497,15 @@ func TestEvaluatorMatches(t *testing.T) { { name: "metadata missing", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", Metadata: map[string][]string{ - "x-missing": {"value"}, + "x-missing": { + "value", + }, }, }, }, @@ -405,13 +513,15 @@ func TestEvaluatorMatches(t *testing.T) { { name: "metadata mismatch", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", Metadata: map[string][]string{ - "x-request-id": {"different"}, + "x-request-id": { + "different", + }, }, }, }, @@ -419,9 +529,9 @@ func TestEvaluatorMatches(t *testing.T) { { name: "message mismatch", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", Message: map[string]any{ @@ -433,9 +543,9 @@ func TestEvaluatorMatches(t *testing.T) { { name: "no message expectation", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", }, @@ -480,14 +590,15 @@ func TestEvaluatorMatchesMissingMethod( ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Missing", + Service: "users.UserService", + Method: "Missing", }, }, } - expected := model.CallExpectation{ + expected := model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Missing", Message: map[string]any{ @@ -522,15 +633,16 @@ func TestEvaluatorMatchesInvalidCapturedMessage( ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Create", + Service: "users.UserService", + Method: "Create", Message: []byte{0xff}, }, }, } - expected := model.CallExpectation{ + expected := model.ServiceExpectedCalls{ ServiceID: "service-1", - GRPC: &model.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", Message: map[string]any{ @@ -580,7 +692,8 @@ func TestEvaluatorDeviation(t *testing.T) { ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Create", + Service: "users.UserService", + Method: "Create", }, Response: call.GRPCResponse{ Metadata: map[string][]string{}, @@ -594,7 +707,8 @@ func TestEvaluatorDeviation(t *testing.T) { ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Create", + Service: "users.UserService", + Method: "Create", }, Response: call.GRPCResponse{ Metadata: map[string][]string{ @@ -614,7 +728,8 @@ func TestEvaluatorDeviation(t *testing.T) { ServiceID: "service-1", GRPC: &call.GRPCCall{ Request: call.GRPCRequest{ - RPC: "/users.UserService/Create", + Service: "users.UserService", + Method: "Create", }, Response: call.GRPCResponse{ Metadata: map[string][]string{ @@ -703,13 +818,21 @@ func TestMessageToMap(t *testing.T) { func TestMergeMetadata(t *testing.T) { header := metadata.MD{ - "x-header": {"one"}, - "x-shared": {"header"}, + "x-header": { + "one", + }, + "x-shared": { + "header", + }, } trailer := metadata.MD{ - "x-trailer": {"two"}, - "x-shared": {"trailer"}, + "x-trailer": { + "two", + }, + "x-shared": { + "trailer", + }, } actual := mergeMetadata( @@ -718,9 +841,16 @@ func TestMergeMetadata(t *testing.T) { ) expected := map[string][]string{ - "x-header": {"one"}, - "x-trailer": {"two"}, - "x-shared": {"header", "trailer"}, + "x-header": { + "one", + }, + "x-trailer": { + "two", + }, + "x-shared": { + "header", + "trailer", + }, } if !reflect.DeepEqual( diff --git a/execute/worker/grpc/executor_test.go b/execute/worker/grpc/executor_test.go index 83a1137..e515fa8 100644 --- a/execute/worker/grpc/executor_test.go +++ b/execute/worker/grpc/executor_test.go @@ -322,10 +322,14 @@ func TestExecutorExecute(t *testing.T) { stream.Context(), ) if !ok { - t.Error("expected request metadata") + t.Error( + "expected request metadata", + ) } - if id := e2enginegrpc.TestExecutionID(md); id != "execution-123" { + if id := e2enginegrpc.TestExecutionID( + md, + ); id != "execution-123" { t.Errorf( "unexpected execution ID metadata: %s", id, @@ -336,7 +340,9 @@ func TestExecutorExecute(t *testing.T) { method.Input(), ) - if err := stream.RecvMsg(request); err != nil { + if err := stream.RecvMsg( + request, + ); err != nil { return err } @@ -383,7 +389,9 @@ func TestExecutorExecute(t *testing.T) { ), ) - return stream.SendMsg(response) + return stream.SendMsg( + response, + ) }, ), ) @@ -412,7 +420,7 @@ func TestExecutorExecute(t *testing.T) { Test: model.Test{ Spec: model.TestSpec{ Request: model.RequestSpec{ - GRPC: &model.GRPCRequestSpec{ + GRPC: &model.GRPCRequest{ Target: service.Address, Service: "users.UserService", Method: "Create", @@ -427,7 +435,7 @@ func TestExecutorExecute(t *testing.T) { }, }, Expect: model.ExpectSpec{ - GRPC: &model.GRPCExpectSpec{ + GRPC: &model.GRPCResponse{ Status: "OK", Message: map[string]any{ "id": "user-123", @@ -455,7 +463,9 @@ func TestExecutorExecute(t *testing.T) { } if result.Summary.Response.GRPC == nil { - t.Fatal("expected gRPC response summary") + t.Fatal( + "expected gRPC response summary", + ) } response := result.Summary.Response.GRPC @@ -483,25 +493,9 @@ func TestExecutorExecute(t *testing.T) { ) } - expectedMetadata := map[string][]string{ - "content-type": { - "application/grpc", - }, - "x-header": { - "header-value", - }, - "x-trailer": { - "trailer-value", - }, - } - - if !reflect.DeepEqual( - response.Metadata, - expectedMetadata, - ) { + if response.Metadata != nil { t.Errorf( - "expected metadata %#v, got %#v", - expectedMetadata, + "expected nil metadata, got %#v", response.Metadata, ) } diff --git a/execute/worker/http/evaluate.go b/execute/worker/http/evaluate.go index 6735dac..a5e3107 100644 --- a/execute/worker/http/evaluate.go +++ b/execute/worker/http/evaluate.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "strconv" + "strings" "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" @@ -26,63 +27,79 @@ func NewEvaluator() *Evaluator { func (e *Evaluator) EvaluateResponse( _ context.Context, resp *http.Response, - expect *model.HTTPExpectSpec, + expect *model.HTTPResponse, result *execute.TestExecutionResult, ) error { result.Summary.Response = &model.TestExecutionResponseSummary{ - HTTP: &model.TestExecutionHTTPResponseSummary{StatusCode: resp.StatusCode}, + HTTP: &model.HTTPResponse{ + StatusCode: resp.StatusCode, + Headers: selectHeaders(resp.Header, expect.Headers), + }, } - if resp.StatusCode != expect.Status { + if resp.StatusCode != expect.StatusCode { result.Summary.Deviations = append( result.Summary.Deviations, model.TestExecutionDeviation{ Field: "status_code", - Expected: strconv.Itoa(expect.Status), + Expected: strconv.Itoa(expect.StatusCode), Actual: strconv.Itoa(resp.StatusCode), }, ) } - if expect.Body != "" { - actualBody, err := io.ReadAll(resp.Body) - if err != nil { - return err + for key, expectedValues := range expect.Headers { + actualValues := resp.Header.Values(key) + + if len(actualValues) > 0 && + util.IsStringSlicesEqual(actualValues, expectedValues) { + continue } - if json.Valid(actualBody) { - result.Summary.Response.HTTP.BodyJSON = util.CompactJSON(actualBody) + result.Summary.Deviations = append( + result.Summary.Deviations, + model.TestExecutionDeviation{ + Field: "headers." + key, + Expected: strings.Join(expectedValues, ","), + Actual: strings.Join(actualValues, ","), + }, + ) + } + + if expect.Body == "" && expect.BodyJSON == "" { + return nil + } + + actualBody, err := io.ReadAll(resp.Body) + if err != nil { + return err + } - equal, err := util.IsJSONEqual( - []byte(expect.Body), - actualBody, + if expect.Body != "" { + result.Summary.Response.HTTP.Body = string(actualBody) + + if string(actualBody) != expect.Body { + result.Summary.Deviations = append( + result.Summary.Deviations, + model.TestExecutionDeviation{ + Field: string(keys.FieldBody), + Expected: expect.Body, + Actual: string(actualBody), + }, ) - if err != nil { - // Expected JSON should already have been validated. - return err - } - - if !equal { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: string(keys.FieldBody), - Expected: util.CompactJSON([]byte(expect.Body)), - Actual: util.CompactJSON(actualBody), - }, - ) - } - - return nil } - result.Summary.Response.HTTP.BodyText = string(actualBody) + return nil + } + + if !json.Valid(actualBody) { + result.Summary.Response.HTTP.Body = string(actualBody) result.Summary.Deviations = append( result.Summary.Deviations, model.TestExecutionDeviation{ - Field: string(keys.FieldBody), - Expected: util.CompactJSON([]byte(expect.Body)), + Field: string(keys.FieldBodyJSON), + Expected: util.CompactJSON([]byte(expect.BodyJSON)), Actual: string(actualBody), Message: "response body is not valid JSON", }, @@ -91,14 +108,66 @@ func (e *Evaluator) EvaluateResponse( return nil } + result.Summary.Response.HTTP.BodyJSON = + util.CompactJSON(actualBody) + + equal, err := util.IsJSONEqual( + []byte(expect.BodyJSON), + actualBody, + ) + if err != nil { + // Expected JSON should already have been validated. + return err + } + + if !equal { + result.Summary.Deviations = append( + result.Summary.Deviations, + model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: util.CompactJSON( + []byte(expect.BodyJSON), + ), + Actual: util.CompactJSON(actualBody), + }, + ) + } + return nil } +func selectHeaders( + actual http.Header, + expected map[string][]string, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for key := range expected { + values := actual.Values(key) + if len(values) > 0 { + result[key] = util.CloneStringSlice(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + func (e *Evaluator) Matches( _ context.Context, _ *model.ServiceSpec, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) { if actual.ServiceID != expected.ServiceID { return false, nil @@ -116,7 +185,7 @@ func (e *Evaluator) Matches( func httpCallMatchesExpectation( actual call.HTTPRequest, - expected *model.HTTPCallExpectation, + expected *model.HTTPRequestPattern, ) bool { if expected.Method != "" && actual.Method != expected.Method { return false @@ -134,15 +203,21 @@ func httpCallMatchesExpectation( } for key, expectedValues := range expected.Headers { - actualValues, ok := actual.Headers[key] - if !ok || !util.IsStringSlicesEqual(actualValues, expectedValues) { + actualValues := actual.Headers.Values(key) + + if len(actualValues) == 0 || + !util.IsStringSlicesEqual(actualValues, expectedValues) { return false } } - if expected.Body != "" { + if expected.Body != "" && string(actual.Body) != expected.Body { + return false + } + + if expected.BodyJSON != "" { equal, err := util.IsJSONEqual( - []byte(expected.Body), + []byte(expected.BodyJSON), actual.Body, ) if err != nil || !equal { diff --git a/execute/worker/http/evaluate_test.go b/execute/worker/http/evaluate_test.go index 075ce15..92ba0a4 100644 --- a/execute/worker/http/evaluate_test.go +++ b/execute/worker/http/evaluate_test.go @@ -18,27 +18,29 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { tests := []struct { name string - status int - body string - expect model.HTTPExpectSpec + status int + body string + headers nethttp.Header + expect model.HTTPResponse expectedBodyJSON string expectedBodyText string + expectedHeaders map[string][]string expected []model.TestExecutionDeviation }{ { name: "matching status without body expectation", status: nethttp.StatusOK, body: `{"ignored":true}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, }, }, { name: "status mismatch", status: nethttp.StatusNotFound, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, }, expected: []model.TestExecutionDeviation{ { @@ -52,9 +54,9 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "matching JSON body", status: nethttp.StatusOK, body: `{"name":"test","count":1}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"count":1,"name":"test"}`, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{"count":1,"name":"test"}`, }, expectedBodyJSON: `{"name":"test","count":1}`, }, @@ -62,14 +64,14 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "JSON body mismatch", status: nethttp.StatusOK, body: `{"name":"actual"}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"name":"expected"}`, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{"name":"expected"}`, }, expectedBodyJSON: `{"name":"actual"}`, expected: []model.TestExecutionDeviation{ { - Field: "body", + Field: string(keys.FieldBodyJSON), Expected: `{"name":"expected"}`, Actual: `{"name":"actual"}`, }, @@ -79,14 +81,14 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "response body is not JSON", status: nethttp.StatusOK, body: "hello", - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"message":"hello"}`, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{"message":"hello"}`, }, expectedBodyText: "hello", expected: []model.TestExecutionDeviation{ { - Field: "body", + Field: string(keys.FieldBodyJSON), Expected: `{"message":"hello"}`, Actual: "hello", Message: "response body is not valid JSON", @@ -97,9 +99,9 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "status and body mismatch", status: nethttp.StatusBadRequest, body: `{"actual":true}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"expected":true}`, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{"expected":true}`, }, expectedBodyJSON: `{"actual":true}`, expected: []model.TestExecutionDeviation{ @@ -109,12 +111,131 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { Actual: "400", }, { - Field: "body", + Field: string(keys.FieldBodyJSON), Expected: `{"expected":true}`, Actual: `{"actual":true}`, }, }, }, + { + name: "matching exact text body", + status: nethttp.StatusOK, + body: "plain text body", + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Body: "plain text body", + }, + expectedBodyText: "plain text body", + }, + { + name: "mismatched exact text body", + status: nethttp.StatusOK, + body: "actual text body", + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Body: "expected text body", + }, + expectedBodyText: "actual text body", + expected: []model.TestExecutionDeviation{ + { + Field: string(keys.FieldBody), + Expected: "expected text body", + Actual: "actual text body", + }, + }, + }, + { + name: "expected header is persisted", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"value"}, + }, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]string{ + "X-Test": {"value"}, + }, + }, + expectedHeaders: map[string][]string{ + "X-Test": {"value"}, + }, + }, + { + name: "unexpected header is not persisted", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "Authorization": {"secret"}, + "X-Test": {"value"}, + }, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]string{ + "X-Test": {"value"}, + }, + }, + expectedHeaders: map[string][]string{ + "X-Test": {"value"}, + }, + }, + { + name: "header name is case insensitive", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"value"}, + }, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]string{ + "x-test": {"value"}, + }, + }, + expectedHeaders: map[string][]string{ + "x-test": {"value"}, + }, + }, + { + name: "header mismatch", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"actual"}, + }, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]string{ + "X-Test": {"expected"}, + }, + }, + expectedHeaders: map[string][]string{ + "X-Test": {"actual"}, + }, + expected: []model.TestExecutionDeviation{ + { + Field: "headers.X-Test", + Expected: "expected", + Actual: "actual", + }, + }, + }, + { + name: "expected header is missing", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Other": {"value"}, + }, + expect: model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]string{ + "X-Test": {"expected"}, + }, + }, + expected: []model.TestExecutionDeviation{ + { + Field: "headers.X-Test", + Expected: "expected", + Actual: "", + }, + }, + }, } for _, tt := range tests { @@ -123,6 +244,7 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { response := &nethttp.Response{ StatusCode: tt.status, + Header: tt.headers, Body: io.NopCloser( strings.NewReader(tt.body), ), @@ -164,14 +286,58 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { ) } - if actual.BodyText != tt.expectedBodyText { + if actual.Body != tt.expectedBodyText { t.Errorf( "expected text body %q, got %q", tt.expectedBodyText, - actual.BodyText, + actual.Body, + ) + } + + if len(actual.Headers) != len(tt.expectedHeaders) { + t.Errorf( + "expected %d headers, got %d: %+v", + len(tt.expectedHeaders), + len(actual.Headers), + actual.Headers, ) } + for key, expectedValues := range tt.expectedHeaders { + actualValues, ok := actual.Headers[key] + if !ok { + t.Errorf( + "expected header %q, got %+v", + key, + actual.Headers, + ) + + continue + } + + if len(actualValues) != len(expectedValues) { + t.Errorf( + "expected header %q values %v, got %v", + key, + expectedValues, + actualValues, + ) + + continue + } + + for i := range expectedValues { + if actualValues[i] != expectedValues[i] { + t.Errorf( + "expected header %q value %q, got %q", + key, + expectedValues[i], + actualValues[i], + ) + } + } + } + assertDeviations( t, result.Summary.Deviations, @@ -200,9 +366,9 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { err := evaluator.EvaluateResponse( context.Background(), response, - &model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"result":"ok"}`, + &model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{"result":"ok"}`, }, result, ) @@ -233,18 +399,18 @@ func TestEvaluatorMatches(t *testing.T) { tests := []struct { name string actual call.Call - expected model.CallExpectation + expected model.ServiceExpectedCalls match bool }{ { name: "matches", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{ - Method: "POST", - Path: "/users", - Body: `{"name":"Yaroslav"}`, + HTTP: &model.HTTPRequestPattern{ + Method: "POST", + Path: "/users", + BodyJSON: `{"name":"Yaroslav"}`, }, }, match: true, @@ -252,9 +418,9 @@ func TestEvaluatorMatches(t *testing.T) { { name: "different service", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-2", - HTTP: &model.HTTPCallExpectation{ + HTTP: &model.HTTPRequestPattern{ Method: "POST", }, }, @@ -264,9 +430,9 @@ func TestEvaluatorMatches(t *testing.T) { actual: call.Call{ ServiceID: "service-1", }, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{ + HTTP: &model.HTTPRequestPattern{ Method: "POST", }, }, @@ -274,16 +440,16 @@ func TestEvaluatorMatches(t *testing.T) { { name: "expectation is not HTTP", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", }, }, { name: "HTTP expectation does not match", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{ + HTTP: &model.HTTPRequestPattern{ Method: "GET", }, }, @@ -330,7 +496,8 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { tests := []struct { name string - expected model.HTTPCallExpectation + expected model.HTTPRequestPattern + body []byte match bool }{ { @@ -339,7 +506,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "all fields match", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Method: "POST", Path: "/users", Query: map[string][]string{ @@ -350,25 +517,25 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { "Content-Type": {"application/json"}, "X-Test": {"one", "two"}, }, - Body: `{"active":true,"name":"Yaroslav"}`, + BodyJSON: `{"active":true,"name":"Yaroslav"}`, }, match: true, }, { name: "method mismatch", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Method: "GET", }, }, { name: "path mismatch", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Path: "/orders", }, }, { name: "query missing", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "missing": {"value"}, }, @@ -376,7 +543,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "query mismatch", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "active": {"false"}, }, @@ -384,7 +551,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "header missing", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Headers: map[string][]string{ "X-Missing": {"value"}, }, @@ -392,28 +559,52 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "header mismatch", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Headers: map[string][]string{ "Content-Type": {"text/plain"}, }, }, }, + { + name: "header name is case insensitive", + expected: model.HTTPRequestPattern{ + Headers: map[string][]string{ + "x-test": {"one", "two"}, + }, + }, + match: true, + }, { name: "JSON body mismatch", - expected: model.HTTPCallExpectation{ - Body: `{"name":"Other"}`, + expected: model.HTTPRequestPattern{ + BodyJSON: `{"name":"Other"}`, }, }, { name: "actual body is invalid JSON", - expected: model.HTTPCallExpectation{ - Body: `{"name":"Yaroslav"}`, + expected: model.HTTPRequestPattern{ + BodyJSON: `{"name":"Yaroslav"}`, + }, + body: []byte("not-json"), + match: false, + }, + { + name: "exact text body matches", + expected: model.HTTPRequestPattern{ + Body: `{"name":"Yaroslav","active":true}`, + }, + match: true, + }, + { + name: "exact text body mismatch", + expected: model.HTTPRequestPattern{ + Body: `{"active":true,"name":"Yaroslav"}`, }, match: false, }, { name: "query subset matches", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "active": {"true"}, }, @@ -422,7 +613,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "headers subset matches", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Headers: map[string][]string{ "Content-Type": {"application/json"}, }, @@ -431,7 +622,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "query values match regardless of order", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "role": {"user", "admin"}, }, @@ -440,7 +631,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "header values match regardless of order", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Headers: map[string][]string{ "X-Test": {"two", "one"}, }, @@ -453,8 +644,8 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { t.Run(tt.name, func(t *testing.T) { request := actual - if tt.name == "actual body is invalid JSON" { - request.Body = []byte("not-json") + if tt.body != nil { + request.Body = tt.body } match := httpCallMatchesExpectation( @@ -518,7 +709,10 @@ func TestEvaluatorDeviation(t *testing.T) { Response: call.HTTPResponse{ Headers: func() nethttp.Header { headers := make(nethttp.Header) - headers.Set(string(keys.E2EngineMockMissHeader), "true") + headers.Set( + string(keys.E2EngineMockMissHeader), + "true", + ) return headers }(), }, diff --git a/execute/worker/http/executor.go b/execute/worker/http/executor.go index e62a915..917cda2 100644 --- a/execute/worker/http/executor.go +++ b/execute/worker/http/executor.go @@ -64,13 +64,15 @@ func (e *TestExecutor) Execute( func buildHTTPRequest( ctx context.Context, - spec *model.HTTPRequestSpec, + spec *model.HTTPRequest, testExecutionID string, ) (*http.Request, error) { var body io.Reader if spec.Body != "" { body = bytes.NewReader([]byte(spec.Body)) + } else if spec.BodyJSON != "" { + body = bytes.NewReader([]byte(spec.BodyJSON)) } req, err := http.NewRequestWithContext( @@ -84,9 +86,12 @@ func buildHTTPRequest( } query := req.URL.Query() - for key, value := range spec.Query { - query.Set(key, value) + for key, values := range spec.Query { + for _, value := range values { + query.Add(key, value) + } } + req.URL.RawQuery = query.Encode() for key, values := range spec.Headers { @@ -97,7 +102,7 @@ func buildHTTPRequest( req.Header = e2enginehttp.WithTestExecutionID(req.Header, testExecutionID) - if spec.Body != "" && + if spec.BodyJSON != "" && req.Header.Get("Content-Type") == "" { req.Header.Set( "Content-Type", diff --git a/execute/worker/http/executor_test.go b/execute/worker/http/executor_test.go index 5865670..aa7c5ff 100644 --- a/execute/worker/http/executor_test.go +++ b/execute/worker/http/executor_test.go @@ -20,7 +20,7 @@ func TestBuildHTTPRequest(t *testing.T) { tests := []struct { name string - spec *model.HTTPRequestSpec + spec *model.HTTPRequest expectedMethod string expectedURL string @@ -29,7 +29,7 @@ func TestBuildHTTPRequest(t *testing.T) { }{ { name: "basic request", - spec: &model.HTTPRequestSpec{ + spec: &model.HTTPRequest{ Method: nethttp.MethodGet, URL: "https://example.com/users", }, @@ -37,26 +37,37 @@ func TestBuildHTTPRequest(t *testing.T) { expectedURL: "https://example.com/users", }, { - name: "body gets default content type", - spec: &model.HTTPRequestSpec{ + name: "body does not get default content type", + spec: &model.HTTPRequest{ Method: nethttp.MethodPost, URL: "https://example.com/users", Body: `{"id":42}`, }, + expectedMethod: nethttp.MethodPost, + expectedURL: "https://example.com/users", + expectedBody: `{"id":42}`, + }, + { + name: "body JSON gets default content type", + spec: &model.HTTPRequest{ + Method: nethttp.MethodPost, + URL: "https://example.com/users", + BodyJSON: `{"id":42}`, + }, expectedMethod: nethttp.MethodPost, expectedURL: "https://example.com/users", expectedBody: `{"id":42}`, expectedContentType: "application/json", }, { - name: "explicit content type is preserved", - spec: &model.HTTPRequestSpec{ + name: "body JSON explicit content type is preserved", + spec: &model.HTTPRequest{ Method: nethttp.MethodPost, URL: "https://example.com/users", Headers: nethttp.Header{ "Content-Type": {"application/problem+json"}, }, - Body: `{"id":42}`, + BodyJSON: `{"id":42}`, }, expectedMethod: nethttp.MethodPost, expectedURL: "https://example.com/users", @@ -65,7 +76,7 @@ func TestBuildHTTPRequest(t *testing.T) { }, { name: "empty body does not get content type", - spec: &model.HTTPRequestSpec{ + spec: &model.HTTPRequest{ Method: nethttp.MethodPost, URL: "https://example.com/users", }, @@ -113,7 +124,9 @@ func TestBuildHTTPRequest(t *testing.T) { ) } - if id := e2enginehttp.TestExecutionID(req.Header); id != "execution-123" { + if id := e2enginehttp.TestExecutionID( + req.Header, + ); id != "execution-123" { t.Errorf( "expected execution ID header %q, got %q", "execution-123", @@ -122,7 +135,9 @@ func TestBuildHTTPRequest(t *testing.T) { } if req.Context() != ctx { - t.Error("expected request to use provided context") + t.Error( + "expected request to use provided context", + ) } if tt.expectedBody == "" { @@ -166,13 +181,13 @@ func TestBuildHTTPRequest(t *testing.T) { } func TestBuildHTTPRequestQuery(t *testing.T) { - spec := &model.HTTPRequestSpec{ + spec := &model.HTTPRequest{ Method: nethttp.MethodGet, URL: "https://example.com/users?" + "existing=value&override=old", - Query: map[string]string{ - "added": "new", - "override": "new", + Query: map[string][]string{ + "added": {"new"}, + "override": {"new"}, }, } @@ -198,25 +213,29 @@ func TestBuildHTTPRequestQuery(t *testing.T) { ) } - if query.Get("added") != "new" { + if !reflect.DeepEqual( + query["added"], + []string{"new"}, + ) { t.Errorf( - "expected added query parameter %q, got %q", - "new", - query.Get("added"), + "unexpected added query parameters: %#v", + query["added"], ) } - if query.Get("override") != "new" { + if !reflect.DeepEqual( + query["override"], + []string{"old", "new"}, + ) { t.Errorf( - "expected overridden query parameter %q, got %q", - "new", - query.Get("override"), + "unexpected override query parameters: %#v", + query["override"], ) } } func TestBuildHTTPRequestHeaders(t *testing.T) { - spec := &model.HTTPRequestSpec{ + spec := &model.HTTPRequest{ Method: nethttp.MethodGet, URL: "https://example.com/users", Headers: e2enginehttp.WithTestExecutionID( @@ -252,7 +271,9 @@ func TestBuildHTTPRequestHeaders(t *testing.T) { ) } - if id := e2enginehttp.TestExecutionID(req.Header); id != "execution-123" { + if id := e2enginehttp.TestExecutionID( + req.Header, + ); id != "execution-123" { t.Errorf( "expected execution header to be overridden, got %s", id, @@ -268,7 +289,7 @@ func TestBuildHTTPRequestCanceledContext(t *testing.T) { req, err := buildHTTPRequest( ctx, - &model.HTTPRequestSpec{ + &model.HTTPRequest{ Method: nethttp.MethodGet, URL: "https://example.com", }, @@ -403,7 +424,9 @@ func TestExecutorExecute(t *testing.T) { w nethttp.ResponseWriter, r *nethttp.Request, ) { - if id := e2enginehttp.TestExecutionID(r.Header); id != "execution-123" { + if id := e2enginehttp.TestExecutionID( + r.Header, + ); id != "execution-123" { t.Errorf( "expected execution ID %q, got %q", "execution-123", @@ -435,15 +458,15 @@ func TestExecutorExecute(t *testing.T) { Test: model.Test{ Spec: model.TestSpec{ Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{ + HTTP: &model.HTTPRequest{ Method: nethttp.MethodGet, URL: server.URL, }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{ + HTTP: &model.HTTPResponse{ + StatusCode: nethttp.StatusOK, + BodyJSON: `{ "name": "test", "id": 42 }`, diff --git a/execute/worker/summary.go b/execute/worker/summary.go index 4e799f3..909fd32 100644 --- a/execute/worker/summary.go +++ b/execute/worker/summary.go @@ -8,77 +8,30 @@ import ( ) func newSummary(spec *model.TestSpec) *model.TestExecutionSummary { - summary := &model.TestExecutionSummary{ - ExpectedCalls: newExpectedCallsSummary(spec.Expect.Calls), - } - - switch { - case spec.Request.HTTP != nil: - summary.Request = &model.TestExecutionRequestSummary{ - HTTP: &model.TestExecutionHTTPRequestSummary{ - Method: spec.Request.HTTP.Method, - URL: spec.Request.HTTP.URL, - Headers: util.CloneHTTPHeader(spec.Request.HTTP.Headers), - BodyJSON: util.CompactJSON(json.RawMessage(spec.Request.HTTP.Body)), + if spec.Request.HTTP != nil { + return &model.TestExecutionSummary{ + Request: &model.TestExecutionRequestSummary{ + HTTP: &model.HTTPRequest{ + Method: spec.Request.HTTP.Method, + URL: spec.Request.HTTP.URL, + Query: util.CloneStringSliceMap(spec.Request.HTTP.Query), + Headers: util.CloneHTTPHeader(spec.Request.HTTP.Headers), + Body: spec.Request.HTTP.Body, + BodyJSON: util.CompactJSON(json.RawMessage(spec.Request.HTTP.BodyJSON)), + }, }, } + } - case spec.Request.GRPC != nil: - summary.Request = &model.TestExecutionRequestSummary{ - GRPC: &model.TestExecutionGRPCRequestSummary{ + return &model.TestExecutionSummary{ + Request: &model.TestExecutionRequestSummary{ + GRPC: &model.GRPCRequest{ + Target: spec.Request.GRPC.Target, Service: spec.Request.GRPC.Service, Method: spec.Request.GRPC.Method, Metadata: util.CloneStringSliceMap(spec.Request.GRPC.Metadata), Message: util.CloneMap(spec.Request.GRPC.Message), }, - } - } - - return summary -} - -func newExpectedCallsSummary( - expectedCalls []model.CallExpectation, -) []model.TestExecutionCallExpectationSummary { - if len(expectedCalls) == 0 { - return nil - } - - result := make( - []model.TestExecutionCallExpectationSummary, - 0, - len(expectedCalls), - ) - - for _, expected := range expectedCalls { - summary := model.TestExecutionCallExpectationSummary{ - ServiceID: expected.ServiceID, - Count: expected.Count, - } - - if expected.HTTP != nil { - summary.HTTP = &model.TestExecutionHTTPCallExpectationSummary{ - Method: expected.HTTP.Method, - Path: expected.HTTP.Path, - Query: util.CloneQuery(expected.HTTP.Query), - Headers: util.CloneHTTPHeader(expected.HTTP.Headers), - BodyJSON: util.CompactJSON( - json.RawMessage(expected.HTTP.Body), - ), - } - } - - if expected.GRPC != nil { - summary.GRPC = &model.TestExecutionGRPCCallExpectationSummary{ - Service: expected.GRPC.Service, - Method: expected.GRPC.Method, - Metadata: util.CloneStringSliceMap(expected.GRPC.Metadata), - Message: util.CloneMap(expected.GRPC.Message), - } - } - - result = append(result, summary) + }, } - - return result } diff --git a/execute/worker/summary_test.go b/execute/worker/summary_test.go index 7a3c876..c2514e1 100644 --- a/execute/worker/summary_test.go +++ b/execute/worker/summary_test.go @@ -2,105 +2,135 @@ package worker import ( "net/http" - "net/url" "testing" "github.com/e2engine/core/model" ) -func TestNewSummaryHTTP(t *testing.T) { +func TestNewSummaryHTTPBody(t *testing.T) { spec := &model.TestSpec{ Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{ + HTTP: &model.HTTPRequest{ Method: http.MethodPost, URL: "https://example.com/users", + Query: map[string][]string{ + "active": {"true"}, + }, Headers: http.Header{ - "Content-Type": {"application/json"}, + "Content-Type": { + "text/plain", + }, }, Body: `{ "id": 42 }`, }, }, - Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{ - Status: http.StatusCreated, - Body: `{ - "status": "created" - }`, - }, - }, } summary := newSummary(spec) if summary.Request == nil { - t.Fatal("expected non-nil request summary") + t.Fatal( + "expected non-nil request summary", + ) } if summary.Request.HTTP == nil { - t.Fatal("expected HTTP request summary") + t.Fatal( + "expected HTTP request summary", + ) } if summary.Request.GRPC != nil { - t.Fatal("expected nil gRPC request summary") + t.Fatal( + "expected nil gRPC request summary", + ) } - if summary.ExpectedCalls != nil { - t.Fatal("expected nil expected calls summary") - } + actual := summary.Request.HTTP - if summary.Request.HTTP.Method != http.MethodPost { + if actual.Method != http.MethodPost { t.Errorf( "expected method %q, got %q", http.MethodPost, - summary.Request.HTTP.Method, + actual.Method, ) } - if summary.Request.HTTP.URL != "https://example.com/users" { + if actual.URL != "https://example.com/users" { t.Errorf( "unexpected URL %q", - summary.Request.HTTP.URL, + actual.URL, ) } - if summary.Request.HTTP.BodyJSON != `{"id":42}` { + if actual.Query["active"][0] != "true" { t.Errorf( - "expected compact body %q, got %q", - `{"id":42}`, - summary.Request.HTTP.BodyJSON, + "unexpected query %#v", + actual.Query, + ) + } + + if actual.Headers["Content-Type"][0] != + "text/plain" { + t.Errorf( + "unexpected headers %#v", + actual.Headers, + ) + } + + if actual.Body != `{ + "id": 42 + }` { + t.Errorf( + "unexpected body %q", + actual.Body, + ) + } + + if actual.BodyJSON != "" { + t.Errorf( + "expected empty JSON body, got %q", + actual.BodyJSON, + ) + } + + spec.Request.HTTP.Query["active"][0] = "false" + spec.Request.HTTP.Headers["Content-Type"][0] = + "application/json" + spec.Request.HTTP.Body = "changed" + + if actual.Query["active"][0] != "true" { + t.Error( + "expected request query to be cloned", ) } - spec.Request.HTTP.Headers["Content-Type"][0] = "text/plain" + if actual.Headers["Content-Type"][0] != + "text/plain" { + t.Error( + "expected request headers to be cloned", + ) + } - if summary.Request.HTTP.Headers["Content-Type"][0] != - "application/json" { - t.Error("expected request headers to be cloned") + if actual.Body == "changed" { + t.Error( + "expected request body snapshot to be independent", + ) } } -func TestNewSummaryGRPC(t *testing.T) { +func TestNewSummaryHTTPBodyJSON(t *testing.T) { spec := &model.TestSpec{ Request: model.RequestSpec{ - GRPC: &model.GRPCRequestSpec{ - Service: "users.v1.UserService", - Method: "GetUser", - Metadata: map[string][]string{ - "x-request-id": {"123"}, - }, - Message: map[string]any{ - "id": "42", - }, - }, - }, - Expect: model.ExpectSpec{ - GRPC: &model.GRPCExpectSpec{ - Status: "OK", - Message: map[string]any{ - "name": "Yaroslav", - }, + HTTP: &model.HTTPRequest{ + Method: http.MethodPost, + URL: "https://example.com/users", + BodyJSON: `{ + "id": 42, + "name": "Yaroslav" + }`, }, }, } @@ -108,84 +138,56 @@ func TestNewSummaryGRPC(t *testing.T) { summary := newSummary(spec) if summary.Request == nil { - t.Fatal("expected non-nil request summary") - } - - if summary.Request.GRPC == nil { - t.Fatal("expected gRPC request summary") + t.Fatal( + "expected non-nil request summary", + ) } - if summary.Request.HTTP != nil { - t.Fatal("expected nil HTTP request summary") + if summary.Request.HTTP == nil { + t.Fatal( + "expected HTTP request summary", + ) } - if summary.ExpectedCalls != nil { - t.Fatal("expected nil expected calls summary") - } + actual := summary.Request.HTTP - if summary.Request.GRPC.Service != "users.v1.UserService" { + if actual.Body != "" { t.Errorf( - "unexpected service %q", - summary.Request.GRPC.Service, + "expected empty body, got %q", + actual.Body, ) } - if summary.Request.GRPC.Method != "GetUser" { + if actual.BodyJSON != + `{"id":42,"name":"Yaroslav"}` { t.Errorf( - "unexpected method %q", - summary.Request.GRPC.Method, + "expected compact JSON body %q, got %q", + `{"id":42,"name":"Yaroslav"}`, + actual.BodyJSON, ) } - spec.Request.GRPC.Metadata["x-request-id"][0] = "changed" - spec.Request.GRPC.Message["id"] = "changed" + spec.Request.HTTP.BodyJSON = `{"changed":true}` - if actual := summary.Request.GRPC.Metadata["x-request-id"][0]; actual != "123" { - t.Error("expected request metadata to be cloned") - } - - if actual := summary.Request.GRPC.Message["id"]; actual != "42" { - t.Error("expected request message to be cloned") - } -} - -func TestNewExpectedCallsSummaryEmpty(t *testing.T) { - if actual := newExpectedCallsSummary(nil); actual != nil { - t.Errorf( - "expected nil, got %#v", - actual, + if actual.BodyJSON != + `{"id":42,"name":"Yaroslav"}` { + t.Error( + "expected request JSON body snapshot to be independent", ) } } -func TestNewExpectedCallsSummary(t *testing.T) { - count := 2 - - expected := []model.CallExpectation{ - { - ServiceID: "http-service", - Count: &count, - HTTP: &model.HTTPCallExpectation{ - Method: http.MethodPost, - Path: "/users", - Query: url.Values{ - "active": {"true"}, - }, - Headers: http.Header{ - "Content-Type": {"application/json"}, - }, - Body: `{ - "id": 42 - }`, - }, - }, - { - ServiceID: "grpc-service", - GRPC: &model.GRPCCallExpectation{ +func TestNewSummaryGRPC(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + GRPC: &model.GRPCRequest{ + Target: "127.0.0.1:50051", Service: "users.v1.UserService", Method: "GetUser", Metadata: map[string][]string{ - "x-request-id": {"123"}, + "x-request-id": { + "123", + }, }, Message: map[string]any{ "id": "42", @@ -194,75 +196,101 @@ func TestNewExpectedCallsSummary(t *testing.T) { }, } - summary := newExpectedCallsSummary(expected) + summary := newSummary(spec) - if len(summary) != 2 { - t.Fatalf( - "expected 2 summaries, got %d", - len(summary), + if summary.Request == nil { + t.Fatal( + "expected non-nil request summary", ) } - httpSummary := summary[0] + if summary.Request.GRPC == nil { + t.Fatal( + "expected gRPC request summary", + ) + } - if httpSummary.ServiceID != "http-service" { - t.Errorf( - "unexpected service ID %q", - httpSummary.ServiceID, + if summary.Request.HTTP != nil { + t.Fatal( + "expected nil HTTP request summary", ) } - if httpSummary.Count != &count && - (httpSummary.Count == nil || *httpSummary.Count != count) { + actual := summary.Request.GRPC + + if actual.Target != "127.0.0.1:50051" { t.Errorf( - "unexpected count %#v", - httpSummary.Count, + "unexpected target %q", + actual.Target, ) } - if httpSummary.HTTP == nil { - t.Fatal("expected HTTP call expectation summary") + if actual.Service != + "users.v1.UserService" { + t.Errorf( + "unexpected service %q", + actual.Service, + ) } - if httpSummary.HTTP.BodyJSON != `{"id":42}` { + if actual.Method != "GetUser" { t.Errorf( - "unexpected HTTP body %q", - httpSummary.HTTP.BodyJSON, + "unexpected method %q", + actual.Method, ) } - grpcSummary := summary[1] - - if grpcSummary.GRPC == nil { - t.Fatal("expected gRPC call expectation summary") + if actual.Metadata["x-request-id"][0] != + "123" { + t.Errorf( + "unexpected metadata %#v", + actual.Metadata, + ) } - if grpcSummary.GRPC.Service != "users.v1.UserService" { + if actual.Message["id"] != "42" { t.Errorf( - "unexpected service %q", - grpcSummary.GRPC.Service, + "unexpected message %#v", + actual.Message, ) } - expected[0].HTTP.Query["active"][0] = "false" - expected[0].HTTP.Headers["Content-Type"][0] = "text/plain" - expected[1].GRPC.Metadata["x-request-id"][0] = "changed" - expected[1].GRPC.Message["id"] = "changed" + spec.Request.GRPC.Target = "changed:50051" + spec.Request.GRPC.Service = "changed.Service" + spec.Request.GRPC.Method = "Changed" + spec.Request.GRPC.Metadata["x-request-id"][0] = + "changed" + spec.Request.GRPC.Message["id"] = "changed" + + if actual.Target != "127.0.0.1:50051" { + t.Error( + "expected target snapshot to be independent", + ) + } - if httpSummary.HTTP.Query["active"][0] != "true" { - t.Error("expected query to be cloned") + if actual.Service != + "users.v1.UserService" { + t.Error( + "expected service snapshot to be independent", + ) } - if httpSummary.HTTP.Headers["Content-Type"][0] != - "application/json" { - t.Error("expected headers to be cloned") + if actual.Method != "GetUser" { + t.Error( + "expected method snapshot to be independent", + ) } - if grpcSummary.GRPC.Metadata["x-request-id"][0] != "123" { - t.Error("expected metadata to be cloned") + if actual.Metadata["x-request-id"][0] != + "123" { + t.Error( + "expected request metadata to be cloned", + ) } - if grpcSummary.GRPC.Message["id"] != "42" { - t.Error("expected message to be cloned") + if actual.Message["id"] != "42" { + t.Error( + "expected request message to be cloned", + ) } } diff --git a/execute/worker/worker.go b/execute/worker/worker.go index 9936635..de9c4df 100644 --- a/execute/worker/worker.go +++ b/execute/worker/worker.go @@ -8,6 +8,7 @@ import ( "github.com/ygrebnov/errorc" "github.com/e2engine/core/execute" + "github.com/e2engine/core/execute/call" "github.com/e2engine/core/execute/evaluate" grpcservice "github.com/e2engine/core/execute/runtime/service/grpc" grpcworker "github.com/e2engine/core/execute/worker/grpc" @@ -79,6 +80,11 @@ func (w *Worker) Execute( ) defer cancel() + executor, err := w.getExecutor(&job.Test.Spec) + if err != nil { + return nil, err + } + callStore := job.Runtime.Calls result := &execute.TestExecutionResult{ @@ -87,25 +93,21 @@ func (w *Worker) Execute( Summary: newSummary(&job.Test.Spec), } - if err := validateExpectedCalls( + if errValidate := validateExpectedCalls( job.Environment.Spec.Services, job.Test.Spec.Expect.Calls, - ); err != nil { - setExecutionError(result, err) + ); errValidate != nil { + setExecutionError(result, errValidate) return result, nil } - executor, err := w.getExecutor(&job.Test.Spec) - if err != nil { - return nil, err - } - if err := executor.Execute( runCtx, &job, result, ); err != nil { + summarizeCalls(result, callStore) setExecutionError(result, err) return result, nil @@ -118,11 +120,14 @@ func (w *Worker) Execute( callStore, result, ); err != nil { + summarizeCalls(result, callStore) setExecutionError(result, err) return result, nil } + summarizeCalls(result, callStore) + if len(result.Summary.Deviations) == 0 { result.Status = model.ExecutionStatusPassed } else { @@ -134,6 +139,16 @@ func (w *Worker) Execute( return result, nil } +func summarizeCalls( + result *execute.TestExecutionResult, + callStore call.Reader, +) { + result.Summary.Calls = evaluate.SummarizeCalls( + result.ExecutionID, + callStore, + ) +} + func (w *Worker) getExecutor( spec *model.TestSpec, ) (execute.ProtocolExecutor, error) { @@ -151,7 +166,7 @@ func (w *Worker) getExecutor( func validateExpectedCalls( services []model.ServiceSpec, - expected []model.CallExpectation, + expected []model.ServiceExpectedCalls, ) error { byID := make(map[string]model.ServiceSpec, len(services)) for i := range services { diff --git a/execute/worker/worker_test.go b/execute/worker/worker_test.go index f2fb01d..ef5164e 100644 --- a/execute/worker/worker_test.go +++ b/execute/worker/worker_test.go @@ -3,31 +3,68 @@ package worker import ( "context" nativeerrors "errors" + "net/http" "testing" "time" + "go.uber.org/mock/gomock" + "github.com/e2engine/core/execute" + "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/execute/evaluate" + "github.com/e2engine/core/mock" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" ) -type testProtocolExecutor struct { - err error +type testCallEvaluator struct { + matches bool + matchesErr error + deviation *model.TestExecutionDeviation } -func (e *testProtocolExecutor) Execute( +func (e *testCallEvaluator) Matches( _ context.Context, - _ *execute.TestJob, - _ *execute.TestExecutionResult, -) error { - return e.err + _ *model.ServiceSpec, + _ call.Call, + _ model.ServiceExpectedCalls, +) (bool, error) { + return e.matches, e.matchesErr +} + +func (e *testCallEvaluator) Deviation( + _ *model.ServiceSpec, + _ call.Call, +) *model.TestExecutionDeviation { + return e.deviation +} + +func newHTTPTestJob( + callStore *call.Store, +) execute.TestJob { + return execute.TestJob{ + ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: callStore, + }, + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponse{}, + }, + }, + }, + } } func TestValidateExpectedCalls(t *testing.T) { tests := []struct { name string services []model.ServiceSpec - expected []model.CallExpectation + expected []model.ServiceExpectedCalls wantErr bool }{ { @@ -38,10 +75,10 @@ func TestValidateExpectedCalls(t *testing.T) { Kind: model.ServiceKindHTTP, }, }, - expected: []model.CallExpectation{ + expected: []model.ServiceExpectedCalls{ { ServiceID: "http-service", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, }, }, @@ -53,10 +90,10 @@ func TestValidateExpectedCalls(t *testing.T) { Kind: model.ServiceKindGRPC, }, }, - expected: []model.CallExpectation{ + expected: []model.ServiceExpectedCalls{ { ServiceID: "grpc-service", - GRPC: &model.GRPCCallExpectation{}, + GRPC: &model.GRPCRequestPattern{}, }, }, }, @@ -68,10 +105,10 @@ func TestValidateExpectedCalls(t *testing.T) { Kind: model.ServiceKindHTTP, }, }, - expected: []model.CallExpectation{ + expected: []model.ServiceExpectedCalls{ { ServiceID: "unknown", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, }, wantErr: true, @@ -84,10 +121,10 @@ func TestValidateExpectedCalls(t *testing.T) { Kind: model.ServiceKindGRPC, }, }, - expected: []model.CallExpectation{ + expected: []model.ServiceExpectedCalls{ { ServiceID: "service", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, }, wantErr: true, @@ -100,10 +137,10 @@ func TestValidateExpectedCalls(t *testing.T) { Kind: model.ServiceKindHTTP, }, }, - expected: []model.CallExpectation{ + expected: []model.ServiceExpectedCalls{ { ServiceID: "service", - GRPC: &model.GRPCCallExpectation{}, + GRPC: &model.GRPCRequestPattern{}, }, }, wantErr: true, @@ -147,8 +184,10 @@ func TestValidateExpectedCalls(t *testing.T) { } func TestWorkerGetExecutor(t *testing.T) { - httpExecutor := &testProtocolExecutor{} - grpcExecutor := &testProtocolExecutor{} + ctrl := gomock.NewController(t) + + httpExecutor := mock.NewMockProtocolExecutor(ctrl) + grpcExecutor := mock.NewMockProtocolExecutor(ctrl) w := &Worker{ httpExecutor: httpExecutor, @@ -165,7 +204,7 @@ func TestWorkerGetExecutor(t *testing.T) { name: "HTTP", spec: &model.TestSpec{ Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{}, + HTTP: &model.HTTPRequest{}, }, }, expected: httpExecutor, @@ -174,7 +213,7 @@ func TestWorkerGetExecutor(t *testing.T) { name: "gRPC", spec: &model.TestSpec{ Request: model.RequestSpec{ - GRPC: &model.GRPCRequestSpec{}, + GRPC: &model.GRPCRequest{}, }, }, expected: grpcExecutor, @@ -191,7 +230,10 @@ func TestWorkerGetExecutor(t *testing.T) { actual, err := w.getExecutor(tt.spec) if tt.wantErr != nil { - if !nativeerrors.Is(err, tt.wantErr) { + if !nativeerrors.Is( + err, + tt.wantErr, + ) { t.Errorf( "expected error %v, got %v", tt.wantErr, @@ -265,27 +307,330 @@ func TestSetExecutionError(t *testing.T) { func TestWorkerExecuteExecutorError(t *testing.T) { executionErr := nativeerrors.New( + "execution failed", ) + ctrl := gomock.NewController(t) + executor := mock.NewMockProtocolExecutor(ctrl) + executor.EXPECT(). + Execute( + gomock.Any(), + gomock.Any(), + gomock.Any(), + ). + Return(executionErr) + w := &Worker{ + cfg: &Config{ + TestTimeout: time.Second, + }, + httpExecutor: executor, + } + callStore := &call.Store{} + job := newHTTPTestJob(callStore) + + result, err := w.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } + + if result == nil { + t.Fatal("expected result") + } + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusError, + result.Status, + ) + } + + if result.Summary.Error != executionErr.Error() { + t.Errorf( + "expected summary error %q, got %q", + executionErr.Error(), + result.Summary.Error, + ) + } + + if result.FinishedAt.IsZero() { + t.Error("expected FinishedAt") + } +} + +func TestWorkerExecutePassed(t *testing.T) { + ctrl := gomock.NewController(t) + executor := mock.NewMockProtocolExecutor(ctrl) + callStore := &call.Store{} + + executor.EXPECT(). + Execute( + gomock.Any(), + gomock.Any(), + gomock.Any(), + ). + DoAndReturn(func( + _ context.Context, + job *execute.TestJob, + _ *execute.TestExecutionResult, + ) error { + job.Runtime.Calls.Record(call.Call{ + TestExecutionID: job.ExecutionID, + ServiceID: "service-1", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: http.MethodGet, + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: http.StatusOK, + }, + }, + }) + + return nil + }) + + w := &Worker{ + cfg: &Config{ + TestTimeout: time.Second, + }, + httpExecutor: executor, + evaluator: evaluate.New( + &testCallEvaluator{}, + &testCallEvaluator{}, + ), + } + + job := newHTTPTestJob(callStore) + + result, err := w.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } + + if result.Status != model.ExecutionStatusPassed { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusPassed, + result.Status, + ) + } + + if len(result.Summary.Calls) != 1 { + t.Fatalf( + "expected 1 summarized call, got %d", + len(result.Summary.Calls), + ) + } + + actual := result.Summary.Calls[0] + + if actual.ServiceID != "service-1" { + t.Errorf( + "expected service ID %q, got %q", + "service-1", + actual.ServiceID, + ) + } + + if actual.Count != 1 { + t.Errorf( + "expected count 1, got %d", + actual.Count, + ) + } + + if actual.HTTP == nil { + t.Fatal( + "expected HTTP call summary", + ) + } + + if actual.HTTP.Method != http.MethodGet { + t.Errorf( + "expected method %q, got %q", + http.MethodGet, + actual.HTTP.Method, + ) + } + + if actual.HTTP.Path != "/health" { + t.Errorf( + "expected path %q, got %q", + "/health", + actual.HTTP.Path, + ) + } + + if actual.HTTP.ResponseStatusCode == nil || + *actual.HTTP.ResponseStatusCode != + http.StatusOK { + t.Errorf( + "expected status code %d, got %#v", + http.StatusOK, + actual.HTTP.ResponseStatusCode, + ) + } + + if result.FinishedAt.IsZero() { + t.Error( + "expected FinishedAt", + ) + } +} + +func TestWorkerExecuteFailed(t *testing.T) { + ctrl := gomock.NewController(t) + executor := mock.NewMockProtocolExecutor(ctrl) + + executor.EXPECT(). + Execute( + gomock.Any(), + gomock.Any(), + gomock.Any(), + ). + DoAndReturn(func( + _ context.Context, + job *execute.TestJob, + result *execute.TestExecutionResult, + ) error { + job.Runtime.Calls.Record(call.Call{ + TestExecutionID: job.ExecutionID, + ServiceID: "service-1", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: http.MethodGet, + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: http.StatusOK, + }, + }, + }) + + result.Summary.Deviations = append( + result.Summary.Deviations, + model.TestExecutionDeviation{ + Field: "status_code", + Expected: "204", + Actual: "200", + }, + ) + + return nil + }) w := &Worker{ cfg: &Config{ TestTimeout: time.Second, }, - httpExecutor: &testProtocolExecutor{ - err: executionErr, + httpExecutor: executor, + evaluator: evaluate.New( + &testCallEvaluator{}, + &testCallEvaluator{}, + ), + } + + callStore := &call.Store{} + job := newHTTPTestJob(callStore) + + result, err := w.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } + + if result.Status != model.ExecutionStatusFailed { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusFailed, + result.Status, + ) + } + + if len(result.Summary.Deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(result.Summary.Deviations), + ) + } + + if len(result.Summary.Calls) != 1 { + t.Fatalf( + "expected 1 summarized call, got %d", + len(result.Summary.Calls), + ) + } + + if result.FinishedAt.IsZero() { + t.Error( + "expected FinishedAt", + ) + } +} + +func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { + ctrl := gomock.NewController(t) + executor := mock.NewMockProtocolExecutor(ctrl) + + w := &Worker{ + cfg: &Config{ + TestTimeout: time.Second, }, + httpExecutor: executor, } + callStore := &call.Store{} + job := execute.TestJob{ ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: callStore, + }, + Environment: model.Environment{ + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{ + { + ID: "service-1", + Kind: model.ServiceKindHTTP, + }, + }, + }, + }, Test: model.Test{ Spec: model.TestSpec{ Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{}, + HTTP: &model.HTTPRequest{}, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{}, + HTTP: &model.HTTPResponse{}, + Calls: []model.ServiceExpectedCalls{ + { + ServiceID: "unknown", + HTTP: &model.HTTPRequestPattern{ + Method: http.MethodGet, + Path: "/health", + }, + }, + }, }, }, }, @@ -302,8 +647,132 @@ func TestWorkerExecuteExecutorError(t *testing.T) { ) } - if result == nil { - t.Fatal("expected result") + if result.Status != model.ExecutionStatusError { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusError, + result.Status, + ) + } + + if result.Summary.Error == "" { + t.Error( + "expected summary error", + ) + } + + if result.Summary.Calls != nil { + t.Errorf( + "expected no summarized calls, got %+v", + result.Summary.Calls, + ) + } + + if result.FinishedAt.IsZero() { + t.Error( + "expected FinishedAt", + ) + } +} + +func TestWorkerExecuteEvaluateCallsError(t *testing.T) { + ctrl := gomock.NewController(t) + executor := mock.NewMockProtocolExecutor(ctrl) + + executor.EXPECT(). + Execute( + gomock.Any(), + gomock.Any(), + gomock.Any(), + ). + DoAndReturn(func( + _ context.Context, + job *execute.TestJob, + _ *execute.TestExecutionResult, + ) error { + job.Runtime.Calls.Record(call.Call{ + TestExecutionID: job.ExecutionID, + ServiceID: "service-1", + HTTP: &call.HTTPCall{ + Request: call.HTTPRequest{ + Method: http.MethodGet, + Path: "/health", + }, + Response: call.HTTPResponse{ + StatusCode: http.StatusOK, + }, + }, + }) + + return nil + }) + + evaluationErr := nativeerrors.New( + "evaluation failed", + ) + + w := &Worker{ + cfg: &Config{ + TestTimeout: time.Second, + }, + httpExecutor: executor, + evaluator: evaluate.New( + &testCallEvaluator{ + matchesErr: evaluationErr, + }, + &testCallEvaluator{}, + ), + } + + count := 1 + + job := execute.TestJob{ + ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: &call.Store{}, + }, + Environment: model.Environment{ + Spec: model.EnvironmentSpec{ + Services: []model.ServiceSpec{ + { + ID: "service-1", + Kind: model.ServiceKindHTTP, + Mode: model.ServiceModeReal, + }, + }, + }, + }, + Test: model.Test{ + Spec: model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponse{}, + Calls: []model.ServiceExpectedCalls{ + { + ServiceID: "service-1", + Count: &count, + HTTP: &model.HTTPRequestPattern{ + Method: http.MethodGet, + Path: "/health", + }, + }, + }, + }, + }, + }, + } + + result, err := w.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) } if result.Status != model.ExecutionStatusError { @@ -314,22 +783,66 @@ func TestWorkerExecuteExecutorError(t *testing.T) { ) } - if result.Summary.Error != executionErr.Error() { + if result.Summary.Error != + evaluationErr.Error() { t.Errorf( "expected summary error %q, got %q", - executionErr.Error(), + evaluationErr.Error(), result.Summary.Error, ) } - if result.Summary.ExpectedCalls != nil { - t.Errorf( - "expected no expected calls, got %#v", - result.Summary.ExpectedCalls, + if len(result.Summary.Calls) != 1 { + t.Fatalf( + "expected 1 summarized call, got %d", + len(result.Summary.Calls), ) } if result.FinishedAt.IsZero() { - t.Error("expected FinishedAt") + t.Error( + "expected FinishedAt", + ) + } +} + +func TestWorkerExecuteUnsupportedProtocol(t *testing.T) { + w := &Worker{ + cfg: &Config{ + TestTimeout: time.Second, + }, + } + + job := execute.TestJob{ + ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: &call.Store{}, + }, + Test: model.Test{ + Spec: model.TestSpec{}, + }, + } + + result, err := w.Execute( + context.Background(), + job, + ) + + if !nativeerrors.Is( + err, + errors.ErrUnsupportedTestProtocol, + ) { + t.Fatalf( + "expected error %v, got %v", + errors.ErrUnsupportedTestProtocol, + err, + ) + } + + if result != nil { + t.Errorf( + "expected nil result, got %+v", + result, + ) } } diff --git a/mock/Execute.go b/mock/Execute.go new file mode 100644 index 0000000..40b2906 --- /dev/null +++ b/mock/Execute.go @@ -0,0 +1,56 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/e2engine/core/execute (interfaces: ProtocolExecutor) +// +// Generated by this command: +// +// mockgen-darwin-arm64-v0.6.0 -destination=mock/Execute.go -package=mock github.com/e2engine/core/execute ProtocolExecutor +// + +// Package mock is a generated GoMock package. +package mock + +import ( + context "context" + reflect "reflect" + + execute "github.com/e2engine/core/execute" + gomock "go.uber.org/mock/gomock" +) + +// MockProtocolExecutor is a mock of ProtocolExecutor interface. +type MockProtocolExecutor struct { + ctrl *gomock.Controller + recorder *MockProtocolExecutorMockRecorder + isgomock struct{} +} + +// MockProtocolExecutorMockRecorder is the mock recorder for MockProtocolExecutor. +type MockProtocolExecutorMockRecorder struct { + mock *MockProtocolExecutor +} + +// NewMockProtocolExecutor creates a new mock instance. +func NewMockProtocolExecutor(ctrl *gomock.Controller) *MockProtocolExecutor { + mock := &MockProtocolExecutor{ctrl: ctrl} + mock.recorder = &MockProtocolExecutorMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockProtocolExecutor) EXPECT() *MockProtocolExecutorMockRecorder { + return m.recorder +} + +// Execute mocks base method. +func (m *MockProtocolExecutor) Execute(ctx context.Context, job *execute.TestJob, result *execute.TestExecutionResult) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Execute", ctx, job, result) + ret0, _ := ret[0].(error) + return ret0 +} + +// Execute indicates an expected call of Execute. +func (mr *MockProtocolExecutorMockRecorder) Execute(ctx, job, result any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockProtocolExecutor)(nil).Execute), ctx, job, result) +} diff --git a/model/environment.go b/model/environment.go index 6918c19..18c2a11 100644 --- a/model/environment.go +++ b/model/environment.go @@ -3,8 +3,6 @@ package model import ( "context" nativeerrors "errors" - "net/url" - "strings" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -108,7 +106,7 @@ type ServiceSpec struct { HTTPTarget string `json:"http_target,omitempty" yaml:"http_target,omitempty" validate:"omitempty,httpurl"` GRPCTarget string `json:"grpc_target,omitempty" yaml:"grpc_target,omitempty" validate:"omitempty,networkaddress"` - RequestDefaults *ServiceDefaults `json:"request_defaults,omitempty" yaml:"request_defaults,omitempty" validateElem:"omitempty,dive"` + RequestDefaults *RequestDefaults `json:"request_defaults,omitempty" yaml:"request_defaults,omitempty" validateElem:"omitempty,dive"` Fixtures []FixtureSpec `json:"fixtures,omitempty" yaml:"fixtures,omitempty" validateElem:"dive"` @@ -122,12 +120,27 @@ func (s *ServiceSpec) Validate() error { return errorc.With( errors.ErrInvalidSpec, errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "proto spec not allowed for HTTP service"), + errorc.String(keys.Validation, "proto spec is not allowed for HTTP service"), + ) + } + if s.RequestDefaults != nil && len(s.RequestDefaults.Metadata) > 0 { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String(keys.Validation, "metadata is not allowed for HTTP service"), ) } } if s.Kind == ServiceKindGRPC { + if s.RequestDefaults != nil && len(s.RequestDefaults.Headers) > 0 { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + errorc.String(keys.Validation, "headers are not allowed for GRPC service"), + ) + } + if s.Proto == nil { return errorc.With( errors.ErrInvalidSpec, @@ -260,12 +273,22 @@ func (s *ServiceSpec) Validate() error { ) } - u, err := url.ParseRequestURI(fixture.When.HTTP.Path) - if err != nil || u.Path == "" || !strings.HasPrefix(u.Path, "/") { - return errorc.With( - errors.ErrInvalidSpec, - errorc.String(keys.SpecKind, string(EntityKindEnvironment)), - errorc.String(keys.Validation, "invalid HTTP fixture path"), + if err := fixture.When.HTTP.Validate(); err != nil { + return nativeerrors.Join( + errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + ), + err, + ) + } + if err := fixture.Then.HTTP.Validate(); err != nil { + return nativeerrors.Join( + errorc.With( + errors.ErrInvalidSpec, + errorc.String(keys.SpecKind, string(EntityKindEnvironment)), + ), + err, ) } @@ -290,8 +313,9 @@ func (s *ServiceSpec) Validate() error { return nil } -type ServiceDefaults struct { - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` +type RequestDefaults struct { + Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` + Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` } type GRPCProtoSpec struct { @@ -347,36 +371,13 @@ type FixtureSpec struct { } type FixtureWhen struct { - HTTP *HTTPFixtureWhen `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCFixtureWhen `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` + HTTP *HTTPRequestPattern `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCRequestPattern `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` } type FixtureThen struct { - HTTP *HTTPFixtureThen `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCFixtureThen `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` -} - -type HTTPFixtureWhen struct { - Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - Path string `json:"path" yaml:"path" validate:"min(1)"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty" validate:"omitempty,validjson"` -} - -type HTTPFixtureThen struct { - Status int `json:"status" yaml:"status" validate:"min(100),max(599)"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty" validate:"omitempty,validjson"` -} - -type GRPCFixtureWhen struct { - Method string `json:"method" yaml:"method" validate:"min(1)"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} - -type GRPCFixtureThen struct { - Status string `json:"status,omitempty" yaml:"status,omitempty" validate:"omitempty,oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + HTTP *HTTPResponse `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCResponse `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` } type EnvironmentsPage = Page[Environment] diff --git a/model/grpc.go b/model/grpc.go new file mode 100644 index 0000000..e53d4ae --- /dev/null +++ b/model/grpc.go @@ -0,0 +1,22 @@ +package model + +type GRPCRequest struct { + Target string `json:"target" yaml:"target" validate:"networkaddress"` + Service string `json:"service" yaml:"service" validate:"min(1)"` + Method string `json:"method" yaml:"method" validate:"min(1)"` + Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` + Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` +} + +type GRPCRequestPattern struct { + Service string `json:"service" yaml:"service" validate:"min(1)"` + Method string `json:"method" yaml:"method" validate:"min(1)"` + Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` + Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` +} + +type GRPCResponse struct { + Status string `json:"status" yaml:"status" validate:"oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` + Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` + Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` +} diff --git a/model/http.go b/model/http.go new file mode 100644 index 0000000..9cb97dc --- /dev/null +++ b/model/http.go @@ -0,0 +1,96 @@ +package model + +import ( + "net/url" + "strings" + + "github.com/ygrebnov/errorc" + + "github.com/e2engine/core/pkg/keys" +) + +type HTTPRequest struct { + Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` + URL string `json:"url" yaml:"url" validate:"min(1)"` + Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` + Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` + Body string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` +} + +func (h *HTTPRequest) Validate() error { + u, err := url.Parse(h.URL) + if err != nil { + return errorc.With( + errorc.New("invalid HTTP request URL"), + errorc.Error(keys.Cause, err), + ) + } + + if u.Scheme != "http" && + u.Scheme != "https" { + return errorc.New( + "HTTP request URL scheme must be http or https", + ) + } + + if strings.TrimSpace(u.Host) == "" { + return errorc.New( + "HTTP request URL must contain a host", + ) + } + + if h.Body != "" && h.BodyJSON != "" { + return errorc.New( + "HTTP request cannot have both body and body_json set", + ) + } + + return nil +} + +// HTTPRequestPattern is used to match an HTTP request against a pattern. +// Unlike HTTPRequest, it does not describe an outgoing request. +type HTTPRequestPattern struct { + Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` + Path string `json:"path" yaml:"path" validate:"min(1)"` + Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` + Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` + Body string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` +} + +func (h *HTTPRequestPattern) Validate() error { + u, err := url.ParseRequestURI(h.Path) + if err != nil || + u.Path == "" || + !strings.HasPrefix(u.Path, "/") || + u.RawQuery != "" { + return errorc.New("invalid HTTP request path") + } + + if h.Body != "" && h.BodyJSON != "" { + return errorc.New( + "HTTP request pattern cannot have both body and body_json set", + ) + } + + return nil +} + +type HTTPResponse struct { + StatusCode int `json:"status_code" yaml:"status_code" validate:"min(100),max(599)"` + Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` + Body string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` +} + +func (h *HTTPResponse) Validate() error { + if h.Body != "" && h.BodyJSON != "" { + return errorc.New( + "HTTP response cannot have both body and body_json set", + ) + } + + return nil +} diff --git a/model/test.go b/model/test.go index 9674374..86006ec 100644 --- a/model/test.go +++ b/model/test.go @@ -3,8 +3,6 @@ package model import ( "context" nativeerrors "errors" - "net/url" - "strings" "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" @@ -50,6 +48,12 @@ func (t *Test) Validate(ctx context.Context) error { } } + if t.Spec.Expect.HTTP != nil { + if err := t.Spec.Expect.HTTP.Validate(); err != nil { + return invalidTestSpec(err) + } + } + for i := range t.Spec.Expect.Calls { if err := t.Spec.Expect.Calls[i].Validate(); err != nil { return invalidTestSpec(err) @@ -124,24 +128,24 @@ func invalidTestSpec(validation error) error { } type RequestSpec struct { - HTTP *HTTPRequestSpec `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCRequestSpec `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` + HTTP *HTTPRequest `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCRequest `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` } type ExpectSpec struct { - HTTP *HTTPExpectSpec `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCExpectSpec `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` - Calls []CallExpectation `json:"calls,omitempty" yaml:"calls,omitempty" validateElem:"dive"` + HTTP *HTTPResponse `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCResponse `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` + Calls []ServiceExpectedCalls `json:"calls,omitempty" yaml:"calls,omitempty" validateElem:"dive"` } -type CallExpectation struct { - ServiceID string `json:"service_id" yaml:"service_id" validate:"min(3),max(200)"` - Count *int `json:"count,omitempty" yaml:"count,omitempty" validate:"omitempty,min(0)"` - HTTP *HTTPCallExpectation `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCCallExpectation `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` +type ServiceExpectedCalls struct { + ServiceID string `json:"service_id" yaml:"service_id" validate:"min(3),max(200)"` + Count *int `json:"count,omitempty" yaml:"count,omitempty" validate:"omitempty,min(0)"` + HTTP *HTTPRequestPattern `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCRequestPattern `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` } -func (c *CallExpectation) Validate() error { +func (c *ServiceExpectedCalls) Validate() error { httpSet := c.HTTP != nil grpcSet := c.GRPC != nil @@ -151,73 +155,11 @@ func (c *CallExpectation) Validate() error { ) } - return nil -} - -type HTTPCallExpectation struct { - Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - Path string `json:"path" yaml:"path" validate:"min(1)"` - Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty" validate:"omitempty,validjson"` -} - -type GRPCCallExpectation struct { - Service string `json:"service" yaml:"service" validate:"min(1)"` - Method string `json:"method" yaml:"method" validate:"min(1)"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} - -type HTTPRequestSpec struct { - Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - URL string `json:"url" yaml:"url" validate:"min(1)"` - Query map[string]string `json:"query,omitempty" yaml:"query,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty" validate:"omitempty,validjson"` -} - -func (s *HTTPRequestSpec) Validate() error { - u, err := url.Parse(s.URL) - if err != nil { - return errorc.With( - errorc.New("invalid HTTP request URL"), - errorc.Error(keys.Cause, err), - ) - } - - if u.Scheme != "http" && - u.Scheme != "https" { - return errorc.New( - "HTTP request URL scheme must be http or https", - ) - } - - if strings.TrimSpace(u.Host) == "" { - return errorc.New( - "HTTP request URL must contain a host", - ) + if c.HTTP != nil { + return c.HTTP.Validate() } return nil } -type HTTPExpectSpec struct { - Status int `json:"status" yaml:"status" validate:"min(100),max(599)"` - Body string `json:"body,omitempty" yaml:"body,omitempty" validate:"omitempty,validjson"` -} - -type GRPCRequestSpec struct { - Target string `json:"target" yaml:"target" validate:"networkaddress"` - Service string `json:"service" yaml:"service" validate:"min(1)"` - Method string `json:"method" yaml:"method" validate:"min(1)"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} - -type GRPCExpectSpec struct { - Status string `json:"status" yaml:"status" validate:"oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} - type TestsPage = Page[Test] diff --git a/model/testexecution.go b/model/testexecution.go index de403f6..e3b16a6 100644 --- a/model/testexecution.go +++ b/model/testexecution.go @@ -43,8 +43,8 @@ type TestExecutionSummary struct { // Response captures what we observed. Response *TestExecutionResponseSummary `json:"response,omitempty" yaml:"response,omitempty"` - // ExpectedCalls captures the service call expectations that were evaluated. - ExpectedCalls []TestExecutionCallExpectationSummary `json:"expected_calls,omitempty" yaml:"expected_calls,omitempty"` + // Calls captures the actual service calls. + Calls []ServiceObservedCalls `json:"calls,omitempty" yaml:"calls,omitempty"` // Deviations contains assertion failures. // When empty and Error is empty, Status is typically "passed". @@ -52,67 +52,43 @@ type TestExecutionSummary struct { } type TestExecutionRequestSummary struct { - HTTP *TestExecutionHTTPRequestSummary `json:"http,omitempty" yaml:"http,omitempty"` - GRPC *TestExecutionGRPCRequestSummary `json:"grpc,omitempty" yaml:"grpc,omitempty"` + HTTP *HTTPRequest `json:"http,omitempty" yaml:"http,omitempty"` + GRPC *GRPCRequest `json:"grpc,omitempty" yaml:"grpc,omitempty"` } type TestExecutionResponseSummary struct { - HTTP *TestExecutionHTTPResponseSummary `json:"http,omitempty" yaml:"http,omitempty"` - GRPC *TestExecutionGRPCResponseSummary `json:"grpc,omitempty" yaml:"grpc,omitempty"` + HTTP *HTTPResponse `json:"http,omitempty" yaml:"http,omitempty"` + GRPC *GRPCResponse `json:"grpc,omitempty" yaml:"grpc,omitempty"` } -type TestExecutionHTTPRequestSummary struct { - Method string `json:"method,omitempty" yaml:"method,omitempty"` - URL string `json:"url,omitempty" yaml:"url,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty"` -} - -type TestExecutionGRPCRequestSummary struct { - Service string `json:"service,omitempty" yaml:"service,omitempty"` - Method string `json:"method,omitempty" yaml:"method,omitempty"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} - -type TestExecutionHTTPResponseSummary struct { - StatusCode int `json:"status_code,omitempty" yaml:"status_code,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty"` - BodyText string `json:"body_text,omitempty" yaml:"body_text,omitempty"` -} - -type TestExecutionGRPCResponseSummary struct { - Status string `json:"status,omitempty" yaml:"status,omitempty"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` -} +// ServiceObservedCalls is an aggregated, diagnostic view of calls observed +// for a service during test execution. Calls are grouped by request identity +// and response status so dependency outcomes are visible without exposing raw +// request or response data. Response status is diagnostic only and does not +// participate in expected-call assertions, which verify the SUT's outgoing +// requests and call counts independently of dependency behavior. +type ServiceObservedCalls struct { + ServiceID string `json:"service_id" yaml:"service_id"` + Count int `json:"count" yaml:"count"` -type TestExecutionGRPCCallExpectationSummary struct { - Service string `json:"service,omitempty" yaml:"service,omitempty"` - Method string `json:"method,omitempty" yaml:"method,omitempty"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + HTTP *HTTPServiceObservedCall `json:"http,omitempty" yaml:"http,omitempty"` + GRPC *GRPCServiceObservedCall `json:"grpc,omitempty" yaml:"grpc,omitempty"` } -type TestExecutionCallExpectationSummary struct { - ServiceID string `json:"service_id" yaml:"service_id"` - Count *int `json:"count,omitempty" yaml:"count,omitempty"` - - HTTP *TestExecutionHTTPCallExpectationSummary `json:"http,omitempty" yaml:"http,omitempty"` - GRPC *TestExecutionGRPCCallExpectationSummary `json:"grpc,omitempty" yaml:"grpc,omitempty"` +type HTTPServiceObservedCall struct { + Method string `json:"method,omitempty" yaml:"method,omitempty"` + Path string `json:"path,omitempty" yaml:"path,omitempty"` + ResponseStatusCode *int `json:"response_status_code,omitempty" yaml:"response_status_code,omitempty"` } -type TestExecutionHTTPCallExpectationSummary struct { - Method string `json:"method,omitempty" yaml:"method,omitempty"` - Path string `json:"path,omitempty" yaml:"path,omitempty"` - Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty"` +type GRPCServiceObservedCall struct { + Service string `json:"service,omitempty" yaml:"service,omitempty"` + Method string `json:"method,omitempty" yaml:"method,omitempty"` + ResponseStatus string `json:"response_status,omitempty" yaml:"response_status,omitempty"` } type TestExecutionDeviation struct { - Field string `json:"field" yaml:"field"` // e.g. "status_code", "body_json" + Field string `json:"field" yaml:"field"` // e.g. "status_code", "body" Expected string `json:"expected,omitempty" yaml:"expected,omitempty"` Actual string `json:"actual,omitempty" yaml:"actual,omitempty"` Message string `json:"message,omitempty" yaml:"message,omitempty"` diff --git a/pkg/keys/keys.go b/pkg/keys/keys.go index 6327dfd..79c1cc7 100644 --- a/pkg/keys/keys.go +++ b/pkg/keys/keys.go @@ -51,7 +51,8 @@ var ( GRPCFieldType = grpc("field.type") GRPCServiceTargetAddress = grpc("service.target.address") - FieldBody = keys.New("body") + FieldBody = keys.New("body") + FieldBodyJSON = keys.New("body.json") ExecutionID = execution("id") ExecutionStatus = execution("status") diff --git a/tests/test_test.go b/tests/test_test.go index 4ecb004..d03727c 100644 --- a/tests/test_test.go +++ b/tests/test_test.go @@ -470,14 +470,14 @@ func validTestSpec() model.TestSpec { return model.TestSpec{ Tags: []string{"smoke"}, Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{ + HTTP: &model.HTTPRequest{ Method: "GET", URL: "http://localhost:8080/health", }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{ - Status: 200, + HTTP: &model.HTTPResponse{ + StatusCode: 200, }, }, } diff --git a/tests/testexecution_test.go b/tests/testexecution_test.go index 4c9d936..3049267 100644 --- a/tests/testexecution_test.go +++ b/tests/testexecution_test.go @@ -433,13 +433,13 @@ func modelTestExecution() *model.TestExecution { func modelTestExecutionSummary() *model.TestExecutionSummary { return &model.TestExecutionSummary{ Request: &model.TestExecutionRequestSummary{ - HTTP: &model.TestExecutionHTTPRequestSummary{ + HTTP: &model.HTTPRequest{ Method: "GET", URL: "http://localhost:8080/health", }, }, Response: &model.TestExecutionResponseSummary{ - HTTP: &model.TestExecutionHTTPResponseSummary{ + HTTP: &model.HTTPResponse{ StatusCode: 200, BodyJSON: `{"status":"ok"}`, }, From 1c629e194977a40d5be6bea87e49a6a2d942c181 Mon Sep 17 00:00:00 2001 From: Yaroslav Grebnov Date: Mon, 12 Oct 2026 11:12:16 +0200 Subject: [PATCH 2/4] Add reporter --- Makefile | 1 + execute/execute.go | 6 +- execute/runtime/service/grpc/mock.go | 40 +- execute/runtime/service/grpc/mock_test.go | 37 +- execute/runtime/service/http/mock.go | 68 +- execute/runtime/service/http/mock_test.go | 118 ++- .../evaluator}/evaluator.go | 56 +- .../evaluator}/evaluator_test.go | 208 ++-- .../worker/evaluator/mock_reporter_test.go | 53 + execute/worker/evaluator/reporter.go | 11 + execute/worker/grpc/evaluate.go | 126 +-- execute/worker/grpc/evaluate_test.go | 312 +++--- execute/worker/grpc/executor.go | 16 +- execute/worker/grpc/executor_test.go | 169 ++- execute/worker/grpc/mock_reporter_test.go | 113 ++ execute/worker/grpc/reporter.go | 16 + execute/worker/http/evaluate.go | 147 +-- execute/worker/http/evaluate_test.go | 406 +++---- execute/worker/http/executor.go | 8 +- execute/worker/http/executor_test.go | 103 +- execute/worker/http/mock_reporter_test.go | 126 +++ execute/worker/http/reporter.go | 19 + .../{evaluate => worker/reporter}/calls.go | 4 +- .../reporter}/calls_test.go | 41 +- execute/worker/reporter/reporter.go | 288 +++++ execute/worker/reporter/reporter_test.go | 993 ++++++++++++++++++ execute/worker/summary.go | 37 - execute/worker/summary_test.go | 296 ------ execute/worker/worker.go | 167 ++- execute/worker/worker_test.go | 759 +++++-------- go.sum | 4 + mock/Execute.go | 8 +- model/grpc.go | 8 +- model/http.go | 37 +- pkg/keys/keys.go | 7 +- tests/testexecution_test.go | 3 +- 36 files changed, 2979 insertions(+), 1832 deletions(-) rename execute/{evaluate => worker/evaluator}/evaluator.go (79%) rename execute/{evaluate => worker/evaluator}/evaluator_test.go (82%) create mode 100644 execute/worker/evaluator/mock_reporter_test.go create mode 100644 execute/worker/evaluator/reporter.go create mode 100644 execute/worker/grpc/mock_reporter_test.go create mode 100644 execute/worker/grpc/reporter.go create mode 100644 execute/worker/http/mock_reporter_test.go create mode 100644 execute/worker/http/reporter.go rename execute/{evaluate => worker/reporter}/calls.go (98%) rename execute/{evaluate => worker/reporter}/calls_test.go (94%) create mode 100644 execute/worker/reporter/reporter.go create mode 100644 execute/worker/reporter/reporter_test.go delete mode 100644 execute/worker/summary.go delete mode 100644 execute/worker/summary_test.go diff --git a/Makefile b/Makefile index d680e92..6df5802 100644 --- a/Makefile +++ b/Makefile @@ -17,6 +17,7 @@ mockgen: install-mockgen $(MOCKGEN) -destination=mock/Repository.go -package=mock github.com/e2engine/core/repository EntityRepository,ResourceRepository,TestRepository,TestExecutionRepository,TestSuiteExecutionRepository $(MOCKGEN) -destination=mock/Runtime.go -package=mock github.com/e2engine/core/execute/runtime Service,ServiceProvider,Router,RouterProvider $(MOCKGEN) -destination=mock/Execute.go -package=mock github.com/e2engine/core/execute ProtocolExecutor + go generate ./... .PHONY: lint lint: install-golangci-lint diff --git a/execute/execute.go b/execute/execute.go index 5945504..0b06b99 100644 --- a/execute/execute.go +++ b/execute/execute.go @@ -53,11 +53,7 @@ type Worker[J Job, R JobExecutionResult] interface { } type ProtocolExecutor interface { - Execute( - ctx context.Context, - job *TestJob, - result *TestExecutionResult, - ) error + Execute(ctx context.Context, job *TestJob) error } type TestExecutionResult struct { diff --git a/execute/runtime/service/grpc/mock.go b/execute/runtime/service/grpc/mock.go index 16491de..0ca6f42 100644 --- a/execute/runtime/service/grpc/mock.go +++ b/execute/runtime/service/grpc/mock.go @@ -47,7 +47,7 @@ type Fixture struct { service string method string metadata map[string][]string - message map[string]any + message *map[string]any status codes.Code responseMetadata map[string][]string @@ -315,9 +315,13 @@ func (s *MockGRPCService) match( continue } + if fixture.message == nil { + return fixture, nil + } + expected, err := buildMessage( method.Input(), - fixture.message, + *fixture.message, ) if err != nil { return nil, errorc.With( @@ -445,20 +449,28 @@ func compileFixtures( continue } + fixture := Fixture{ + service: spec.When.GRPC.Service, + method: spec.When.GRPC.Method, + metadata: spec.When.GRPC.Metadata, + + status: grpcCode( + spec.Then.GRPC.Status, + ), + responseMetadata: spec.Then.GRPC.Metadata, + } + + if spec.When.GRPC.Message != nil { + fixture.message = spec.When.GRPC.Message + } + + if spec.Then.GRPC.Message != nil { + fixture.response = *spec.Then.GRPC.Message + } + fixtures = append( fixtures, - Fixture{ - service: spec.When.GRPC.Service, - method: spec.When.GRPC.Method, - metadata: spec.When.GRPC.Metadata, - message: spec.When.GRPC.Message, - - status: grpcCode( - spec.Then.GRPC.Status, - ), - responseMetadata: spec.Then.GRPC.Metadata, - response: spec.Then.GRPC.Message, - }, + fixture, ) } diff --git a/execute/runtime/service/grpc/mock_test.go b/execute/runtime/service/grpc/mock_test.go index fa1858e..5cb33cc 100644 --- a/execute/runtime/service/grpc/mock_test.go +++ b/execute/runtime/service/grpc/mock_test.go @@ -168,6 +168,9 @@ func TestGRPCCode(t *testing.T) { } func TestCompileFixtures(t *testing.T) { + m1 := map[string]any{"id": "42"} + m2 := map[string]any{"message": "not found"} + specs := []model.FixtureSpec{ { When: model.FixtureWhen{ @@ -180,9 +183,7 @@ func TestCompileFixtures(t *testing.T) { "two", }, }, - Message: map[string]any{ - "id": "42", - }, + Message: &m1, }, }, Then: model.FixtureThen{ @@ -194,9 +195,7 @@ func TestCompileFixtures(t *testing.T) { "four", }, }, - Message: map[string]any{ - "message": "not found", - }, + Message: &m2, }, }, }, @@ -254,11 +253,11 @@ func TestCompileFixtures(t *testing.T) { ) } - if fixture.message["id"] != "42" { + if (*fixture.message)["id"] != "42" { t.Errorf( "expected request id %q, got %v", "42", - fixture.message["id"], + (*fixture.message)["id"], ) } @@ -570,7 +569,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -596,7 +595,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { "two", }, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -617,7 +616,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { metadata: map[string][]string{ "x-request-id": {"one"}, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -631,7 +630,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.AdminService", method: "GetUser", - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -645,7 +644,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "CreateUser", - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -659,7 +658,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - message: map[string]any{ + message: &map[string]any{ "id": "43", }, }, @@ -676,7 +675,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { metadata: map[string][]string{ "x-request-id": {"one"}, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -696,7 +695,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { metadata: map[string][]string{ "x-request-id": {"one"}, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -719,7 +718,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { metadata: map[string][]string{ "x-request-id": {"one"}, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, }, @@ -784,7 +783,7 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( { service: "users.v1.UserService", method: "GetUser", - message: map[string]any{ + message: &map[string]any{ "unknown": "value", }, }, @@ -1046,7 +1045,7 @@ func TestMockGRPCServiceHandle(t *testing.T) { "two", }, }, - message: map[string]any{ + message: &map[string]any{ "id": "42", }, status: codes.OK, diff --git a/execute/runtime/service/http/mock.go b/execute/runtime/service/http/mock.go index aa5fda1..a2b94f7 100644 --- a/execute/runtime/service/http/mock.go +++ b/execute/runtime/service/http/mock.go @@ -121,7 +121,9 @@ func (s *MockHTTPService) ServeHTTP( s.respond(w, fixture) } -func (s *MockHTTPService) match(r *http.Request) (*Fixture, error) { +func (s *MockHTTPService) match( + r *http.Request, +) (*Fixture, error) { body, err := io.ReadAll(r.Body) if err != nil { s.logger.Error( @@ -140,16 +142,24 @@ func (s *MockHTTPService) match(r *http.Request) (*Fixture, error) { } for i := range s.fixtures { - if s.fixtures[i].method == r.Method && - s.fixtures[i].path == r.URL.Path && - areQueryParamsEqual(s.fixtures[i].query, r.URL.Query()) && - areHeadersEqual(s.fixtures[i].headers, r.Header) && + fixture := &s.fixtures[i] + + if fixture.method == r.Method && + fixture.path == r.URL.Path && + areQueryParamsEqual( + fixture.query, + r.URL.Query(), + ) && + areHeadersEqual( + fixture.headers, + r.Header, + ) && isBodyEqual( - s.fixtures[i].body, - s.fixtures[i].bodyJSON, + fixture.body, + fixture.bodyJSON, body, ) { - return &s.fixtures[i], nil + return fixture, nil } } @@ -157,18 +167,18 @@ func (s *MockHTTPService) match(r *http.Request) (*Fixture, error) { } func isBodyEqual( - expectedBody string, - expectedBodyJSON string, + expectedBody *string, + expectedBodyJSON *string, actual []byte, ) bool { - if expectedBody != "" { - return expectedBody == string(actual) + if expectedBody != nil { + return *expectedBody == string(actual) } - if expectedBodyJSON != "" { + if expectedBodyJSON != nil { var expectedValue any if err := json.Unmarshal( - []byte(expectedBodyJSON), + []byte(*expectedBodyJSON), &expectedValue, ); err != nil { return false @@ -188,7 +198,7 @@ func isBodyEqual( ) } - return len(actual) == 0 + return true } func areHeadersEqual(expected, actual http.Header) bool { @@ -268,8 +278,8 @@ type Fixture struct { query url.Values headers map[string][]string - body string - bodyJSON string + body *string + bodyJSON *string status int responseHeaders map[string][]string @@ -292,22 +302,34 @@ func compileFixtures( spec.When.HTTP.Path, ) - fixtures[i] = Fixture{ + fixture := Fixture{ method: spec.When.HTTP.Method, path: u.Path, query: u.Query(), headers: spec.When.HTTP.Headers, - body: spec.When.HTTP.Body, - bodyJSON: spec.When.HTTP.BodyJSON, - status: spec.Then.HTTP.StatusCode, responseHeaders: spec.Then.HTTP.Headers, + } + + if spec.When.HTTP.Body != nil { + fixture.body = spec.When.HTTP.Body + } - responseBody: spec.Then.HTTP.Body, - responseBodyJSON: spec.Then.HTTP.BodyJSON, + if spec.When.HTTP.BodyJSON != nil { + fixture.bodyJSON = spec.When.HTTP.BodyJSON } + + if spec.Then.HTTP.Body != nil { + fixture.responseBody = *spec.Then.HTTP.Body + } + + if spec.Then.HTTP.BodyJSON != nil { + fixture.responseBodyJSON = *spec.Then.HTTP.BodyJSON + } + + fixtures[i] = fixture } return fixtures diff --git a/execute/runtime/service/http/mock_test.go b/execute/runtime/service/http/mock_test.go index 2d01e73..701540f 100644 --- a/execute/runtime/service/http/mock_test.go +++ b/execute/runtime/service/http/mock_test.go @@ -30,8 +30,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/users", nil, - "", - `{"name":"Alice","age":42}`, + nil, + ptr(`{"name":"Alice","age":42}`), http.StatusCreated, ), method: "POST", @@ -46,8 +46,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/values", nil, - "", - `[1,2,3]`, + nil, + ptr(`[1,2,3]`), http.StatusOK, ), method: "POST", @@ -62,8 +62,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/value", nil, - "", - `42`, + nil, + ptr(`42`), http.StatusOK, ), method: "POST", @@ -78,8 +78,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/value", nil, - "", - `"hello"`, + nil, + ptr(`"hello"`), http.StatusOK, ), method: "POST", @@ -94,8 +94,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/value", nil, - "", - `true`, + nil, + ptr(`true`), http.StatusOK, ), method: "POST", @@ -110,8 +110,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/value", nil, - "", - `null`, + nil, + ptr(`null`), http.StatusOK, ), method: "POST", @@ -126,8 +126,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/text", nil, - "hello world", - "", + ptr("hello world"), + nil, http.StatusOK, ), method: "POST", @@ -142,8 +142,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/text", nil, - "this is not JSON: {", - "", + ptr("this is not JSON: {"), + nil, http.StatusOK, ), method: "POST", @@ -158,8 +158,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/users", nil, - `{"name":"Alice","age":42}`, - "", + ptr(`{"name":"Alice","age":42}`), + nil, http.StatusOK, ), method: "POST", @@ -175,8 +175,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", - "", + ptr(""), + nil, http.StatusOK, ), method: "GET", @@ -190,8 +190,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?status=active&page=2", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -205,8 +205,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?role=admin&role=operator", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -222,8 +222,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"one", "two"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -242,8 +242,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"expected"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -263,8 +263,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"expected"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -281,8 +281,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "POST", @@ -297,8 +297,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -313,8 +313,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?page=1", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -329,8 +329,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -347,8 +347,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"expected"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -365,8 +365,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"expected"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -386,8 +386,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { map[string][]string{ "X-Test": {"expected"}, }, - "", - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -405,8 +405,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/users", nil, - "", - `{"name":"Alice"}`, + nil, + ptr(`{"name":"Alice"}`), http.StatusOK, ), method: "POST", @@ -422,8 +422,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/text", nil, - "expected", - "", + ptr("expected"), + nil, http.StatusOK, ), method: "POST", @@ -439,8 +439,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/users", nil, - "", - "", + ptr(""), + nil, http.StatusOK, ), method: "POST", @@ -456,8 +456,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/users", nil, - "", - `{}`, + nil, + ptr(`{}`), http.StatusOK, ), method: "POST", @@ -472,8 +472,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "POST", "/text", nil, - "expected", - "", + ptr("expected"), + nil, http.StatusOK, ), method: "POST", @@ -582,7 +582,7 @@ func TestMockHTTPServiceResponse(t *testing.T) { Headers: map[string][]string{ "X-Test": {"one", "two"}, }, - Body: "plain text response", + Body: ptr("plain text response"), }, expectedBody: "plain text response", }, @@ -593,7 +593,7 @@ func TestMockHTTPServiceResponse(t *testing.T) { Headers: map[string][]string{ "X-Test": {"one", "two"}, }, - BodyJSON: "{\n \"id\": 42\n}", + BodyJSON: ptr("{\n \"id\": 42\n}"), }, expectedBody: "{\n \"id\": 42\n}", }, @@ -735,7 +735,7 @@ func newHTTPFixture( path string, headers map[string][]string, body, - bodyJSON string, + bodyJSON *string, status int, ) model.FixtureSpec { return model.FixtureSpec{ @@ -755,3 +755,7 @@ func newHTTPFixture( }, } } + +func ptr(s string) *string { + return &s +} diff --git a/execute/evaluate/evaluator.go b/execute/worker/evaluator/evaluator.go similarity index 79% rename from execute/evaluate/evaluator.go rename to execute/worker/evaluator/evaluator.go index 727c12f..7791083 100644 --- a/execute/evaluate/evaluator.go +++ b/execute/worker/evaluator/evaluator.go @@ -1,10 +1,9 @@ -package evaluate +package evaluator import ( "context" "strconv" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" ) @@ -28,15 +27,18 @@ type CallEvaluator interface { type Evaluator struct { httpCallEvaluator CallEvaluator grpcCallEvaluator CallEvaluator + reporter deviationReporter } func New( httpCallEvaluator CallEvaluator, grpcCallEvaluator CallEvaluator, + reporter deviationReporter, ) *Evaluator { return &Evaluator{ httpCallEvaluator: httpCallEvaluator, grpcCallEvaluator: grpcCallEvaluator, + reporter: reporter, } } @@ -45,7 +47,7 @@ func (e *Evaluator) EvaluateCalls( services []model.ServiceSpec, expectedCalls []model.ServiceExpectedCalls, calls call.Reader, - result *execute.TestExecutionResult, + executionID string, ) error { if err := ctx.Err(); err != nil { return err @@ -54,7 +56,7 @@ func (e *Evaluator) EvaluateCalls( e.evaluateActualCalls( services, calls, - result, + executionID, ) return e.evaluateExpectedCalls( @@ -62,14 +64,14 @@ func (e *Evaluator) EvaluateCalls( services, expectedCalls, calls, - result, + executionID, ) } func (e *Evaluator) evaluateActualCalls( services []model.ServiceSpec, calls call.Reader, - result *execute.TestExecutionResult, + executionID string, ) { for i := range services { service := services[i] @@ -79,7 +81,7 @@ func (e *Evaluator) evaluateActualCalls( } filter := call.Filter{ - TestExecutionID: result.ExecutionID, + TestExecutionID: executionID, ServiceID: service.ID, } for _, actual := range calls.Get(filter) { @@ -90,16 +92,16 @@ func (e *Evaluator) evaluateActualCalls( case model.ServiceKindGRPC: deviation = e.grpcCallEvaluator.Deviation(&service, actual) + + default: + panic("invalid service spec: unsupported service kind") } if deviation == nil { continue } - result.Summary.Deviations = append( - result.Summary.Deviations, - *deviation, - ) + e.reporter.AddDeviation(deviation) } } } @@ -109,7 +111,7 @@ func (e *Evaluator) evaluateExpectedCalls( services []model.ServiceSpec, expectedCalls []model.ServiceExpectedCalls, calls call.Reader, - result *execute.TestExecutionResult, + executionID string, ) error { serviceByID := make(map[string]*model.ServiceSpec, len(services)) for i := range services { @@ -120,7 +122,7 @@ func (e *Evaluator) evaluateExpectedCalls( service := serviceByID[expected.ServiceID] filter := call.Filter{ - TestExecutionID: result.ExecutionID, + TestExecutionID: executionID, ServiceID: expected.ServiceID, } actualCalls := calls.Get(filter) @@ -145,28 +147,22 @@ func (e *Evaluator) evaluateExpectedCalls( if expected.Count != nil { if matched != *expected.Count { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "calls." + expected.ServiceID + ".count", - Expected: strconv.Itoa(*expected.Count), - Actual: strconv.Itoa(matched), - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: "calls." + expected.ServiceID + ".count", + Expected: strconv.Itoa(*expected.Count), + Actual: strconv.Itoa(matched), + }) } continue } if matched == 0 { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "calls." + expected.ServiceID + ".count", - Expected: "at least 1", - Actual: "0", - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: "calls." + expected.ServiceID + ".count", + Expected: "at least 1", + Actual: "0", + }) } } @@ -197,6 +193,6 @@ func (e *Evaluator) matches( ) default: - return false, nil + panic("invalid expected call: unsupported protocol") } } diff --git a/execute/evaluate/evaluator_test.go b/execute/worker/evaluator/evaluator_test.go similarity index 82% rename from execute/evaluate/evaluator_test.go rename to execute/worker/evaluator/evaluator_test.go index 318974b..5558527 100644 --- a/execute/evaluate/evaluator_test.go +++ b/execute/worker/evaluator/evaluator_test.go @@ -1,16 +1,21 @@ -package evaluate +package evaluator import ( "context" "errors" "testing" - "github.com/e2engine/core/execute" + "go.uber.org/mock/gomock" + "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" ) func TestEvaluatorEvaluateCalls(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ deviation: &model.TestExecutionDeviation{ Field: "calls.http-service", @@ -30,6 +35,7 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { evaluator := New( httpEvaluator, grpcEvaluator, + reporter, ) calls := &call.Store{} @@ -46,7 +52,10 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { GRPC: &call.GRPCCall{}, }) - result := newTestExecutionResult() + gomock.InOrder( + reporter.EXPECT().AddDeviation(httpEvaluator.deviation), + reporter.EXPECT().AddDeviation(grpcEvaluator.deviation), + ) err := evaluator.EvaluateCalls( context.Background(), @@ -73,7 +82,7 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { }, }, calls, - result, + "execution-1", ) if err != nil { t.Fatalf( @@ -81,29 +90,6 @@ func TestEvaluatorEvaluateCalls(t *testing.T) { err, ) } - - if len(result.Summary.Deviations) != 2 { - t.Fatalf( - "expected 2 deviations, got %d", - len(result.Summary.Deviations), - ) - } - - if result.Summary.Deviations[0].Field != - "calls.http-service" { - t.Errorf( - "expected HTTP deviation, got %+v", - result.Summary.Deviations[0], - ) - } - - if result.Summary.Deviations[1].Field != - "calls.grpc-service" { - t.Errorf( - "expected gRPC deviation, got %+v", - result.Summary.Deviations[1], - ) - } } func TestEvaluatorEvaluateCallsCancelledContext( @@ -114,19 +100,22 @@ func TestEvaluatorEvaluateCallsCancelledContext( ) cancel() + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + evaluator := New( &testCallEvaluator{}, &testCallEvaluator{}, + reporter, ) - result := newTestExecutionResult() - err := evaluator.EvaluateCalls( ctx, nil, nil, &call.Store{}, - result, + "execution-1", ) if !errors.Is(err, context.Canceled) { @@ -138,6 +127,10 @@ func TestEvaluatorEvaluateCallsCancelledContext( } func TestEvaluatorEvaluateActualCalls(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ deviation: &model.TestExecutionDeviation{ Field: "calls.http-service", @@ -155,6 +148,7 @@ func TestEvaluatorEvaluateActualCalls(t *testing.T) { evaluator := New( httpEvaluator, grpcEvaluator, + reporter, ) calls := &call.Store{} @@ -185,7 +179,10 @@ func TestEvaluatorEvaluateActualCalls(t *testing.T) { HTTP: &call.HTTPCall{}, }) - result := newTestExecutionResult() + gomock.InOrder( + reporter.EXPECT().AddDeviation(httpEvaluator.deviation), + reporter.EXPECT().AddDeviation(grpcEvaluator.deviation), + ) evaluator.evaluateActualCalls( []model.ServiceSpec{ @@ -205,16 +202,9 @@ func TestEvaluatorEvaluateActualCalls(t *testing.T) { }, }, calls, - result, + "execution-1", ) - if len(result.Summary.Deviations) != 2 { - t.Fatalf( - "expected 2 deviations, got %d", - len(result.Summary.Deviations), - ) - } - if httpEvaluator.deviationCalls != 1 { t.Errorf( "expected HTTP Deviation() to be called once, got %d", @@ -233,11 +223,16 @@ func TestEvaluatorEvaluateActualCalls(t *testing.T) { func TestEvaluatorEvaluateActualCallsNoDeviation( t *testing.T, ) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{} evaluator := New( httpEvaluator, &testCallEvaluator{}, + reporter, ) calls := &call.Store{} @@ -248,8 +243,6 @@ func TestEvaluatorEvaluateActualCallsNoDeviation( HTTP: &call.HTTPCall{}, }) - result := newTestExecutionResult() - evaluator.evaluateActualCalls( []model.ServiceSpec{ { @@ -259,15 +252,48 @@ func TestEvaluatorEvaluateActualCallsNoDeviation( }, }, calls, - result, + "execution-1", ) +} - if len(result.Summary.Deviations) != 0 { - t.Fatalf( - "expected no deviations, got %+v", - result.Summary.Deviations, - ) - } +func TestEvaluatorEvaluateActualCallsUnsupportedServiceKind( + t *testing.T, +) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + + evaluator := New( + &testCallEvaluator{}, + &testCallEvaluator{}, + reporter, + ) + + calls := &call.Store{} + + calls.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "unsupported-service", + HTTP: &call.HTTPCall{}, + }) + + defer func() { + if recover() == nil { + t.Fatal("expected panic") + } + }() + + evaluator.evaluateActualCalls( + []model.ServiceSpec{ + { + ID: "unsupported-service", + Kind: model.ServiceKind("unsupported"), + Mode: model.ServiceModeMocked, + }, + }, + calls, + "execution-1", + ) } func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { @@ -359,6 +385,10 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ matches: tt.matches, } @@ -366,6 +396,7 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { evaluator := New( httpEvaluator, &testCallEvaluator{}, + reporter, ) calls := &call.Store{} @@ -378,7 +409,10 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { }) } - result := newTestExecutionResult() + if tt.expectedDeviation != nil { + reporter.EXPECT(). + AddDeviation(tt.expectedDeviation) + } err := evaluator.evaluateExpectedCalls( context.Background(), @@ -396,7 +430,7 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { }, }, calls, - result, + "execution-1", ) if err != nil { t.Fatalf( @@ -404,34 +438,6 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { err, ) } - - if tt.expectedDeviation == nil { - if len(result.Summary.Deviations) != 0 { - t.Fatalf( - "expected no deviations, got %+v", - result.Summary.Deviations, - ) - } - - return - } - - if len(result.Summary.Deviations) != 1 { - t.Fatalf( - "expected 1 deviation, got %d", - len(result.Summary.Deviations), - ) - } - - actual := result.Summary.Deviations[0] - - if actual != *tt.expectedDeviation { - t.Errorf( - "expected deviation %+v, got %+v", - *tt.expectedDeviation, - actual, - ) - } }) } } @@ -441,6 +447,10 @@ func TestEvaluatorEvaluateExpectedCallsError( ) { expectedErr := errors.New("match error") + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ matchesErr: expectedErr, } @@ -448,6 +458,7 @@ func TestEvaluatorEvaluateExpectedCallsError( evaluator := New( httpEvaluator, &testCallEvaluator{}, + reporter, ) calls := &call.Store{} @@ -458,8 +469,6 @@ func TestEvaluatorEvaluateExpectedCallsError( HTTP: &call.HTTPCall{}, }) - result := newTestExecutionResult() - err := evaluator.evaluateExpectedCalls( context.Background(), []model.ServiceSpec{ @@ -475,7 +484,7 @@ func TestEvaluatorEvaluateExpectedCallsError( }, }, calls, - result, + "execution-1", ) if !errors.Is(err, expectedErr) { @@ -496,6 +505,7 @@ func TestEvaluatorMatches(t *testing.T) { expectedHTTPCalls int expectedGRPCCalls int expectedMatch bool + expectedPanic bool }{ { name: "HTTP", @@ -515,12 +525,16 @@ func TestEvaluatorMatches(t *testing.T) { }, { name: "no protocol", - expectedMatch: false, + expectedPanic: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ matches: true, } @@ -532,8 +546,26 @@ func TestEvaluatorMatches(t *testing.T) { evaluator := New( httpEvaluator, grpcEvaluator, + reporter, ) + if tt.expectedPanic { + defer func() { + if recover() == nil { + t.Fatal("expected panic") + } + }() + + _, _ = evaluator.matches( + context.Background(), + &model.ServiceSpec{}, + call.Call{}, + tt.expected, + ) + + return + } + match, err := evaluator.matches( context.Background(), &model.ServiceSpec{}, @@ -579,6 +611,10 @@ func TestEvaluatorMatches(t *testing.T) { func TestEvaluatorMatchesError(t *testing.T) { expectedErr := errors.New("match error") + ctrl := gomock.NewController(t) + + reporter := NewMockdeviationReporter(ctrl) + httpEvaluator := &testCallEvaluator{ matchesErr: expectedErr, } @@ -586,6 +622,7 @@ func TestEvaluatorMatchesError(t *testing.T) { evaluator := New( httpEvaluator, &testCallEvaluator{}, + reporter, ) _, err := evaluator.matches( @@ -635,13 +672,6 @@ func (e *testCallEvaluator) Deviation( return e.deviation } -func newTestExecutionResult() *execute.TestExecutionResult { - return &execute.TestExecutionResult{ - ExecutionID: "execution-1", - Summary: &model.TestExecutionSummary{}, - } -} - func intPtr(value int) *int { return &value } diff --git a/execute/worker/evaluator/mock_reporter_test.go b/execute/worker/evaluator/mock_reporter_test.go new file mode 100644 index 0000000..8d3253a --- /dev/null +++ b/execute/worker/evaluator/mock_reporter_test.go @@ -0,0 +1,53 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: reporter.go +// +// Generated by this command: +// +// mockgen -source=reporter.go -destination=mock_reporter_test.go -package=evaluator +// + +// Package evaluator is a generated GoMock package. +package evaluator + +import ( + reflect "reflect" + + model "github.com/e2engine/core/model" + gomock "go.uber.org/mock/gomock" +) + +// MockdeviationReporter is a mock of deviationReporter interface. +type MockdeviationReporter struct { + ctrl *gomock.Controller + recorder *MockdeviationReporterMockRecorder + isgomock struct{} +} + +// MockdeviationReporterMockRecorder is the mock recorder for MockdeviationReporter. +type MockdeviationReporterMockRecorder struct { + mock *MockdeviationReporter +} + +// NewMockdeviationReporter creates a new mock instance. +func NewMockdeviationReporter(ctrl *gomock.Controller) *MockdeviationReporter { + mock := &MockdeviationReporter{ctrl: ctrl} + mock.recorder = &MockdeviationReporterMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockdeviationReporter) EXPECT() *MockdeviationReporterMockRecorder { + return m.recorder +} + +// AddDeviation mocks base method. +func (m *MockdeviationReporter) AddDeviation(deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddDeviation", deviation) +} + +// AddDeviation indicates an expected call of AddDeviation. +func (mr *MockdeviationReporterMockRecorder) AddDeviation(deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeviation", reflect.TypeOf((*MockdeviationReporter)(nil).AddDeviation), deviation) +} diff --git a/execute/worker/evaluator/reporter.go b/execute/worker/evaluator/reporter.go new file mode 100644 index 0000000..2797a14 --- /dev/null +++ b/execute/worker/evaluator/reporter.go @@ -0,0 +1,11 @@ +package evaluator + +import ( + "github.com/e2engine/core/model" +) + +type deviationReporter interface { + AddDeviation(deviation *model.TestExecutionDeviation) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=reporter.go -destination=mock_reporter_test.go -package=evaluator diff --git a/execute/worker/grpc/evaluate.go b/execute/worker/grpc/evaluate.go index 90444c8..c2f0ff0 100644 --- a/execute/worker/grpc/evaluate.go +++ b/execute/worker/grpc/evaluate.go @@ -13,10 +13,9 @@ import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/dynamicpb" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/execute/evaluate" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" + "github.com/e2engine/core/execute/worker/evaluator" "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/keys" @@ -27,46 +26,47 @@ var ( ErrUnknownStatus = errorc.New("unknown gRPC status") ) -var _ evaluate.CallEvaluator = (*Evaluator)(nil) +var _ evaluator.CallEvaluator = (*Evaluator)(nil) type Evaluator struct { resolver servicegrpc.MethodResolver + reporter executionReporter } func NewEvaluator( resolver servicegrpc.MethodResolver, + reporter executionReporter, ) *Evaluator { return &Evaluator{ resolver: resolver, + reporter: reporter, } } func (e *Evaluator) EvaluateResponse( - ctx context.Context, callErr error, response *dynamicpb.Message, header metadata.MD, trailer metadata.MD, expect *model.GRPCResponse, - result *execute.TestExecutionResult, ) error { - if err := ctx.Err(); err != nil { + if err := e.evaluateStatus(callErr, expect); err != nil { return err } - result.Summary.Response = &model.TestExecutionResponseSummary{ - GRPC: &model.GRPCResponse{}, + if err := e.evaluateMetadata(header, trailer, expect); err != nil { + return err } - actualStatus := status.Code(callErr) - - result.Summary.Response.GRPC.Status = - actualStatus.String() - - actualMetadata := mergeMetadata(header, trailer) + return e.evaluateMessage(response, expect) +} - result.Summary.Response.GRPC.Metadata = - selectMetadata(actualMetadata, expect.Metadata) +func (e *Evaluator) evaluateStatus( + callErr error, + expect *model.GRPCResponse, +) error { + actualStatus := status.Code(callErr) + e.reporter.AddGRPCResponseStatus(actualStatus.String()) expectedStatus, err := grpcCode( expect.Status, @@ -76,16 +76,24 @@ func (e *Evaluator) EvaluateResponse( } if actualStatus != expectedStatus { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "status", - Expected: expectedStatus.String(), - Actual: actualStatus.String(), - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldStatus), + Expected: expectedStatus.String(), + Actual: actualStatus.String(), + }) } + return nil +} + +func (e *Evaluator) evaluateMetadata( + header metadata.MD, + trailer metadata.MD, + expect *model.GRPCResponse, +) error { + actualMetadata := mergeMetadata(header, trailer) + e.reporter.AddGRPCResponseMetadata(actualMetadata) + for key, expectedValues := range expect.Metadata { actualValues, ok := actualMetadata[key] if ok && util.IsStringSlicesEqual( @@ -95,25 +103,30 @@ func (e *Evaluator) EvaluateResponse( continue } - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "metadata." + key, - Expected: strings.Join(expectedValues, ","), - Actual: strings.Join(actualValues, ","), - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: "metadata." + key, + Expected: strings.Join(expectedValues, ","), + Actual: strings.Join(actualValues, ","), + }) } + return nil +} + +func (e *Evaluator) evaluateMessage( + response *dynamicpb.Message, + expect *model.GRPCResponse, +) error { responseMap, err := messageToMap(response) if err != nil { return err } - result.Summary.Response.GRPC.Message = - responseMap + e.reporter.AddGRPCResponseMessage(responseMap) if expect.Message == nil { + // An omitted message means that the response message is not evaluated. + // An explicitly empty message (`message: {}`) expects an empty protobuf message. return nil } @@ -122,7 +135,7 @@ func (e *Evaluator) EvaluateResponse( ) if errUnmarshal := unmarshalMap( - expect.Message, + *expect.Message, expectedMessage, ); errUnmarshal != nil { return errUnmarshal @@ -136,7 +149,7 @@ func (e *Evaluator) EvaluateResponse( } expectedJSON, err := json.Marshal( - expect.Message, + *expect.Message, ) if err != nil { return err @@ -149,44 +162,15 @@ func (e *Evaluator) EvaluateResponse( return err } - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "message", - Expected: string(expectedJSON), - Actual: string(actualJSON), - }, - ) + e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldMessage), + Expected: string(expectedJSON), + Actual: string(actualJSON), + }) return nil } -func selectMetadata( - actual map[string][]string, - expected map[string][]string, -) map[string][]string { - if len(expected) == 0 { - return nil - } - - result := make( - map[string][]string, - len(expected), - ) - - for key := range expected { - if values, ok := actual[key]; ok { - result[key] = util.CloneStringSlice(values) - } - } - - if len(result) == 0 { - return nil - } - - return result -} - func (e *Evaluator) Matches( ctx context.Context, service *model.ServiceSpec, @@ -252,7 +236,7 @@ func (e *Evaluator) Matches( ) if err := unmarshalMap( - expected.GRPC.Message, + *expected.GRPC.Message, expectedMessage, ); err != nil { return false, err diff --git a/execute/worker/grpc/evaluate_test.go b/execute/worker/grpc/evaluate_test.go index a36315f..950141e 100644 --- a/execute/worker/grpc/evaluate_test.go +++ b/execute/worker/grpc/evaluate_test.go @@ -6,6 +6,7 @@ import ( "reflect" "testing" + "go.uber.org/mock/gomock" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" @@ -16,7 +17,6 @@ import ( "google.golang.org/protobuf/types/descriptorpb" "google.golang.org/protobuf/types/dynamicpb" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/model" @@ -33,10 +33,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message map[string]any expect model.GRPCResponse - expectedStatus string - expectedMetadata map[string][]string - expectedMessage map[string]any - expectedDeviations []model.TestExecutionDeviation + expectedStatus string + + expectedDeviations []model.TestExecutionDeviation + expectedPayloadDeviations []model.TestExecutionDeviation }{ { name: "matching response", @@ -66,25 +66,16 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "trailer-value", }, }, - Message: map[string]any{ - "name": "actual", - }, + Message: mapPtr( + map[string]any{ + "name": "actual", + }, + ), }, expectedStatus: "OK", - expectedMetadata: map[string][]string{ - "x-header": { - "header-value", - }, - "x-trailer": { - "trailer-value", - }, - }, - expectedMessage: map[string]any{ - "name": "actual", - }, }, { - name: "unrelated metadata is not persisted", + name: "unrelated metadata", header: metadata.MD{ "x-header": { "header-value", @@ -102,9 +93,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { Status: "OK", }, expectedStatus: "OK", - expectedMessage: map[string]any{ - "name": "actual", - }, }, { name: "metadata mismatch", @@ -125,14 +113,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { }, }, expectedStatus: "OK", - expectedMetadata: map[string][]string{ - "x-header": { - "actual", - }, - }, - expectedMessage: map[string]any{ - "name": "actual", - }, expectedDeviations: []model.TestExecutionDeviation{ { Field: "metadata.x-header", @@ -155,9 +135,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { }, }, expectedStatus: "OK", - expectedMessage: map[string]any{ - "name": "actual", - }, expectedDeviations: []model.TestExecutionDeviation{ { Field: "metadata.x-header", @@ -179,9 +156,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { Status: "OK", }, expectedStatus: "NotFound", - expectedMessage: map[string]any{ - "name": "actual", - }, expectedDeviations: []model.TestExecutionDeviation{ { Field: "status", @@ -197,15 +171,14 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { }, expect: model.GRPCResponse{ Status: "OK", - Message: map[string]any{ - "name": "expected", - }, + Message: mapPtr( + map[string]any{ + "name": "expected", + }, + ), }, expectedStatus: "OK", - expectedMessage: map[string]any{ - "name": "actual", - }, - expectedDeviations: []model.TestExecutionDeviation{ + expectedPayloadDeviations: []model.TestExecutionDeviation{ { Field: "message", Expected: `{"name":"expected"}`, @@ -222,33 +195,72 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { Status: "OK", }, expectedStatus: "OK", - expectedMessage: map[string]any{ - "name": "actual", + }, + { + name: "explicit empty message", + message: map[string]any{}, + expect: model.GRPCResponse{ + Status: "OK", + Message: mapPtr( + map[string]any{}, + ), }, + expectedStatus: "OK", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := newTestEvaluator(reporter) + response := newTestMessage( t, tt.message, ) - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, + reporter.EXPECT(). + AddGRPCResponseStatus( + tt.expectedStatus, + ) + + for i := range tt.expectedDeviations { + reporter.EXPECT(). + AddDeviation( + &tt.expectedDeviations[i], + ) } - evaluator := newTestEvaluator() + expectedMetadata := mergeMetadata( + tt.header, + tt.trailer, + ) + + reporter.EXPECT(). + AddGRPCResponseMetadata( + expectedMetadata, + ) + + reporter.EXPECT(). + AddGRPCResponseMessage( + tt.message, + ) + + for i := range tt.expectedPayloadDeviations { + reporter.EXPECT(). + AddPayloadDeviation( + &tt.expectedPayloadDeviations[i], + ) + } err := evaluator.EvaluateResponse( - context.Background(), tt.callErr, response, tt.header, tt.trailer, &tt.expect, - result, ) if err != nil { t.Fatalf( @@ -256,101 +268,22 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { err, ) } - - actual := result.Summary.Response.GRPC - if actual == nil { - t.Fatal( - "expected gRPC response summary", - ) - } - - if actual.Status != tt.expectedStatus { - t.Errorf( - "expected status %q, got %q", - tt.expectedStatus, - actual.Status, - ) - } - - if !reflect.DeepEqual( - actual.Metadata, - tt.expectedMetadata, - ) { - t.Errorf( - "expected metadata %#v, got %#v", - tt.expectedMetadata, - actual.Metadata, - ) - } - - if !reflect.DeepEqual( - actual.Message, - tt.expectedMessage, - ) { - t.Errorf( - "expected message %#v, got %#v", - tt.expectedMessage, - actual.Message, - ) - } - - assertGRPCDeviations( - t, - result.Summary.Deviations, - tt.expectedDeviations, - ) }) } } -func TestEvaluatorEvaluateResponseCancelledContext( - t *testing.T, -) { - ctx, cancel := context.WithCancel( - context.Background(), - ) - cancel() - - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } - - evaluator := newTestEvaluator() - - err := evaluator.EvaluateResponse( - ctx, - nil, - newTestMessage( - t, - map[string]any{}, - ), - nil, - nil, - &model.GRPCResponse{ - Status: "OK", - }, - result, - ) - - if !errors.Is(err, context.Canceled) { - t.Fatalf( - "expected context.Canceled, got %v", - err, - ) - } -} - func TestEvaluatorEvaluateResponseUnknownStatus( t *testing.T, ) { - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := newTestEvaluator(reporter) - evaluator := newTestEvaluator() + reporter.EXPECT(). + AddGRPCResponseStatus("OK") err := evaluator.EvaluateResponse( - context.Background(), nil, newTestMessage( t, @@ -361,7 +294,6 @@ func TestEvaluatorEvaluateResponseUnknownStatus( &model.GRPCResponse{ Status: "invalid", }, - result, ) if !errors.Is(err, ErrUnknownStatus) { @@ -406,8 +338,6 @@ func TestEvaluatorMatches(t *testing.T) { ) } - evaluator := NewEvaluator(resolver) - actual := call.Call{ ServiceID: "service-1", GRPC: &call.GRPCCall{ @@ -445,9 +375,11 @@ func TestEvaluatorMatches(t *testing.T) { "request-1", }, }, - Message: map[string]any{ - "name": "Yaroslav", - }, + Message: mapPtr( + map[string]any{ + "name": "Yaroslav", + }, + ), }, }, match: true, @@ -534,9 +466,11 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Message: map[string]any{ - "name": "Other", - }, + Message: mapPtr( + map[string]any{ + "name": "Other", + }, + ), }, }, }, @@ -552,10 +486,32 @@ func TestEvaluatorMatches(t *testing.T) { }, match: true, }, + { + name: "explicit empty message does not match", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Message: mapPtr( + map[string]any{}, + ), + }, + }, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator( + resolver, + reporter, + ) + match, err := evaluator.Matches( context.Background(), service, @@ -583,8 +539,11 @@ func TestEvaluatorMatches(t *testing.T) { func TestEvaluatorMatchesMissingMethod( t *testing.T, ) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + service := testServiceSpec() - evaluator := newTestEvaluator() + evaluator := newTestEvaluator(reporter) actual := call.Call{ ServiceID: "service-1", @@ -601,9 +560,11 @@ func TestEvaluatorMatchesMissingMethod( GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Missing", - Message: map[string]any{ - "name": "Yaroslav", - }, + Message: mapPtr( + map[string]any{ + "name": "Yaroslav", + }, + ), }, } @@ -626,8 +587,11 @@ func TestEvaluatorMatchesMissingMethod( func TestEvaluatorMatchesInvalidCapturedMessage( t *testing.T, ) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + service := testServiceSpec() - evaluator := newTestEvaluator() + evaluator := newTestEvaluator(reporter) actual := call.Call{ ServiceID: "service-1", @@ -645,9 +609,11 @@ func TestEvaluatorMatchesInvalidCapturedMessage( GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Message: map[string]any{ - "name": "Yaroslav", - }, + Message: mapPtr( + map[string]any{ + "name": "Yaroslav", + }, + ), }, } @@ -670,7 +636,10 @@ func TestEvaluatorMatchesInvalidCapturedMessage( } func TestEvaluatorDeviation(t *testing.T) { - evaluator := newTestEvaluator() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := newTestEvaluator(reporter) service := testServiceSpec() @@ -1011,9 +980,12 @@ func TestGRPCCodeUnknown(t *testing.T) { } } -func newTestEvaluator() *Evaluator { +func newTestEvaluator( + reporter executionReporter, +) *Evaluator { return NewEvaluator( servicegrpc.NewProtoMethodResolver(nil), + reporter, ) } @@ -1153,30 +1125,8 @@ func newMapMessage( return message } -func assertGRPCDeviations( - t *testing.T, - actual []model.TestExecutionDeviation, - expected []model.TestExecutionDeviation, -) { - t.Helper() - - if len(actual) != len(expected) { - t.Fatalf( - "expected %d deviations, got %d: %+v", - len(expected), - len(actual), - actual, - ) - } - - for i := range expected { - if actual[i] != expected[i] { - t.Errorf( - "deviation %d: expected %+v, got %+v", - i, - expected[i], - actual[i], - ) - } - } +func mapPtr( + value map[string]any, +) *map[string]any { + return &value } diff --git a/execute/worker/grpc/executor.go b/execute/worker/grpc/executor.go index 0c0f6ae..dc79ff3 100644 --- a/execute/worker/grpc/executor.go +++ b/execute/worker/grpc/executor.go @@ -22,22 +22,24 @@ import ( type TestExecutor struct { resolver servicegrpc.MethodResolver evaluator *Evaluator + reporter executionReporter } func NewTestExecutor( resolver servicegrpc.MethodResolver, evaluator *Evaluator, + reporter executionReporter, ) *TestExecutor { return &TestExecutor{ resolver: resolver, evaluator: evaluator, + reporter: reporter, } } func (e *TestExecutor) Execute( ctx context.Context, job *execute.TestJob, - result *execute.TestExecutionResult, ) error { spec := job.Test.Spec.Request.GRPC @@ -98,6 +100,16 @@ func (e *TestExecutor) Execute( var header metadata.MD var trailer metadata.MD + r := &model.GRPCRequest{ + Target: spec.Target, + Service: spec.Service, + Method: spec.Method, + Metadata: callMetadata, + Message: spec.Message, + } + + e.reporter.AddGRPCRequest(r) + callErr := connection.Invoke( callCtx, "/"+spec.Service+"/"+spec.Method, @@ -108,13 +120,11 @@ func (e *TestExecutor) Execute( ) return e.evaluator.EvaluateResponse( - ctx, callErr, response, header, trailer, job.Test.Spec.Expect.GRPC, - result, ) } diff --git a/execute/worker/grpc/executor_test.go b/execute/worker/grpc/executor_test.go index e515fa8..da59249 100644 --- a/execute/worker/grpc/executor_test.go +++ b/execute/worker/grpc/executor_test.go @@ -8,6 +8,7 @@ import ( "testing" e2enginegrpc "github.com/e2engine/instrumentation-go/grpc" + "go.uber.org/mock/gomock" ggrpc "google.golang.org/grpc" "google.golang.org/grpc/metadata" "google.golang.org/protobuf/reflect/protodesc" @@ -403,9 +404,18 @@ func TestExecutorExecute(t *testing.T) { service.Address = listener.Addr().String() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator( + resolver, + reporter, + ) + executor := NewTestExecutor( resolver, - NewEvaluator(resolver), + evaluator, + reporter, ) job := &execute.TestJob{ @@ -437,23 +447,117 @@ func TestExecutorExecute(t *testing.T) { Expect: model.ExpectSpec{ GRPC: &model.GRPCResponse{ Status: "OK", - Message: map[string]any{ - "id": "user-123", - }, + Message: mapPtrExecutor( + map[string]any{ + "id": "user-123", + }, + ), }, }, }, }, } - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + reporter.EXPECT(). + AddGRPCRequest(gomock.Any()). + Do(func(req *model.GRPCRequest) { + if req.Target != service.Address { + t.Errorf( + "expected target %q, got %q", + service.Address, + req.Target, + ) + } + + if req.Service != "users.UserService" { + t.Errorf( + "expected service %q, got %q", + "users.UserService", + req.Service, + ) + } + + if req.Method != "Create" { + t.Errorf( + "expected method %q, got %q", + "Create", + req.Method, + ) + } + + if !reflect.DeepEqual( + req.Metadata["x-request-id"], + []string{"request-123"}, + ) { + t.Errorf( + "unexpected request metadata: %#v", + req.Metadata, + ) + } + + if id := e2enginegrpc.TestExecutionID( + metadata.MD(req.Metadata), + ); id != "execution-123" { + t.Errorf( + "expected execution ID %q, got %q", + "execution-123", + id, + ) + } + + expectedMessage := map[string]any{ + "name": "Yaroslav", + } + + if !reflect.DeepEqual( + req.Message, + expectedMessage, + ) { + t.Errorf( + "expected message %#v, got %#v", + expectedMessage, + req.Message, + ) + } + }) + + reporter.EXPECT(). + AddGRPCResponseStatus("OK") + + reporter.EXPECT(). + AddGRPCResponseMetadata(gomock.Any()). + Do(func(md map[string][]string) { + if !reflect.DeepEqual( + md["x-header"], + []string{"header-value"}, + ) { + t.Errorf( + "unexpected header metadata: %#v", + md, + ) + } + + if !reflect.DeepEqual( + md["x-trailer"], + []string{"trailer-value"}, + ) { + t.Errorf( + "unexpected trailer metadata: %#v", + md, + ) + } + }) + + reporter.EXPECT(). + AddGRPCResponseMessage( + map[string]any{ + "id": "user-123", + }, + ) err = executor.Execute( context.Background(), job, - result, ) if err != nil { t.Fatalf( @@ -461,49 +565,10 @@ func TestExecutorExecute(t *testing.T) { err, ) } +} - if result.Summary.Response.GRPC == nil { - t.Fatal( - "expected gRPC response summary", - ) - } - - response := result.Summary.Response.GRPC - - if response.Status != "OK" { - t.Errorf( - "expected status %q, got %q", - "OK", - response.Status, - ) - } - - expectedMessage := map[string]any{ - "id": "user-123", - } - - if !reflect.DeepEqual( - response.Message, - expectedMessage, - ) { - t.Errorf( - "expected message %#v, got %#v", - expectedMessage, - response.Message, - ) - } - - if response.Metadata != nil { - t.Errorf( - "expected nil metadata, got %#v", - response.Metadata, - ) - } - - if len(result.Summary.Deviations) != 0 { - t.Errorf( - "expected no deviations, got %+v", - result.Summary.Deviations, - ) - } +func mapPtrExecutor( + value map[string]any, +) *map[string]any { + return &value } diff --git a/execute/worker/grpc/mock_reporter_test.go b/execute/worker/grpc/mock_reporter_test.go new file mode 100644 index 0000000..93a1db8 --- /dev/null +++ b/execute/worker/grpc/mock_reporter_test.go @@ -0,0 +1,113 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: reporter.go +// +// Generated by this command: +// +// mockgen -source=reporter.go -destination=mock_reporter_test.go -package=grpc +// + +// Package grpc is a generated GoMock package. +package grpc + +import ( + reflect "reflect" + + model "github.com/e2engine/core/model" + gomock "go.uber.org/mock/gomock" +) + +// MockexecutionReporter is a mock of executionReporter interface. +type MockexecutionReporter struct { + ctrl *gomock.Controller + recorder *MockexecutionReporterMockRecorder + isgomock struct{} +} + +// MockexecutionReporterMockRecorder is the mock recorder for MockexecutionReporter. +type MockexecutionReporterMockRecorder struct { + mock *MockexecutionReporter +} + +// NewMockexecutionReporter creates a new mock instance. +func NewMockexecutionReporter(ctrl *gomock.Controller) *MockexecutionReporter { + mock := &MockexecutionReporter{ctrl: ctrl} + mock.recorder = &MockexecutionReporterMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockexecutionReporter) EXPECT() *MockexecutionReporterMockRecorder { + return m.recorder +} + +// AddDeviation mocks base method. +func (m *MockexecutionReporter) AddDeviation(deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddDeviation", deviation) +} + +// AddDeviation indicates an expected call of AddDeviation. +func (mr *MockexecutionReporterMockRecorder) AddDeviation(deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddDeviation), deviation) +} + +// AddGRPCRequest mocks base method. +func (m *MockexecutionReporter) AddGRPCRequest(req *model.GRPCRequest) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGRPCRequest", req) +} + +// AddGRPCRequest indicates an expected call of AddGRPCRequest. +func (mr *MockexecutionReporterMockRecorder) AddGRPCRequest(req any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGRPCRequest", reflect.TypeOf((*MockexecutionReporter)(nil).AddGRPCRequest), req) +} + +// AddGRPCResponseMessage mocks base method. +func (m *MockexecutionReporter) AddGRPCResponseMessage(message map[string]any) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGRPCResponseMessage", message) +} + +// AddGRPCResponseMessage indicates an expected call of AddGRPCResponseMessage. +func (mr *MockexecutionReporterMockRecorder) AddGRPCResponseMessage(message any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGRPCResponseMessage", reflect.TypeOf((*MockexecutionReporter)(nil).AddGRPCResponseMessage), message) +} + +// AddGRPCResponseMetadata mocks base method. +func (m *MockexecutionReporter) AddGRPCResponseMetadata(metadata map[string][]string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGRPCResponseMetadata", metadata) +} + +// AddGRPCResponseMetadata indicates an expected call of AddGRPCResponseMetadata. +func (mr *MockexecutionReporterMockRecorder) AddGRPCResponseMetadata(metadata any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGRPCResponseMetadata", reflect.TypeOf((*MockexecutionReporter)(nil).AddGRPCResponseMetadata), metadata) +} + +// AddGRPCResponseStatus mocks base method. +func (m *MockexecutionReporter) AddGRPCResponseStatus(status string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGRPCResponseStatus", status) +} + +// AddGRPCResponseStatus indicates an expected call of AddGRPCResponseStatus. +func (mr *MockexecutionReporterMockRecorder) AddGRPCResponseStatus(status any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGRPCResponseStatus", reflect.TypeOf((*MockexecutionReporter)(nil).AddGRPCResponseStatus), status) +} + +// AddPayloadDeviation mocks base method. +func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddPayloadDeviation", deviation) +} + +// AddPayloadDeviation indicates an expected call of AddPayloadDeviation. +func (mr *MockexecutionReporterMockRecorder) AddPayloadDeviation(deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddPayloadDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddPayloadDeviation), deviation) +} diff --git a/execute/worker/grpc/reporter.go b/execute/worker/grpc/reporter.go new file mode 100644 index 0000000..dba1e28 --- /dev/null +++ b/execute/worker/grpc/reporter.go @@ -0,0 +1,16 @@ +package grpc + +import ( + "github.com/e2engine/core/model" +) + +type executionReporter interface { + AddDeviation(deviation *model.TestExecutionDeviation) + AddPayloadDeviation(deviation *model.TestExecutionDeviation) + AddGRPCRequest(req *model.GRPCRequest) + AddGRPCResponseStatus(status string) + AddGRPCResponseMetadata(metadata map[string][]string) + AddGRPCResponseMessage(message map[string]any) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=reporter.go -destination=mock_reporter_test.go -package=grpc diff --git a/execute/worker/http/evaluate.go b/execute/worker/http/evaluate.go index a5e3107..aa4a896 100644 --- a/execute/worker/http/evaluate.go +++ b/execute/worker/http/evaluate.go @@ -8,44 +8,40 @@ import ( "strconv" "strings" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/execute/evaluate" + "github.com/e2engine/core/execute/worker/evaluator" "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/keys" ) -var _ evaluate.CallEvaluator = (*Evaluator)(nil) +var _ evaluator.CallEvaluator = (*Evaluator)(nil) -type Evaluator struct{} +type Evaluator struct { + reporter executionReporter +} -func NewEvaluator() *Evaluator { - return &Evaluator{} +func NewEvaluator( + reporter executionReporter, +) *Evaluator { + return &Evaluator{ + reporter: reporter, + } } func (e *Evaluator) EvaluateResponse( - _ context.Context, resp *http.Response, expect *model.HTTPResponse, - result *execute.TestExecutionResult, ) error { - result.Summary.Response = &model.TestExecutionResponseSummary{ - HTTP: &model.HTTPResponse{ - StatusCode: resp.StatusCode, - Headers: selectHeaders(resp.Header, expect.Headers), - }, - } + e.reporter.AddHTTPResponseStatus(resp.StatusCode) + e.reporter.AddHTTPResponseHeaders(resp.Header) if resp.StatusCode != expect.StatusCode { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "status_code", - Expected: strconv.Itoa(expect.StatusCode), - Actual: strconv.Itoa(resp.StatusCode), - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldStatusCode), + Expected: strconv.Itoa(expect.StatusCode), + Actual: strconv.Itoa(resp.StatusCode), + }) } for key, expectedValues := range expect.Headers { @@ -56,17 +52,15 @@ func (e *Evaluator) EvaluateResponse( continue } - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "headers." + key, - Expected: strings.Join(expectedValues, ","), - Actual: strings.Join(actualValues, ","), - }, - ) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: "headers." + key, + Expected: strings.Join(expectedValues, ","), + Actual: strings.Join(actualValues, ","), + }) } - if expect.Body == "" && expect.BodyJSON == "" { + if expect.Body == nil && expect.BodyJSON == nil { + // nil means "do not evaluate body" return nil } @@ -75,44 +69,37 @@ func (e *Evaluator) EvaluateResponse( return err } - if expect.Body != "" { - result.Summary.Response.HTTP.Body = string(actualBody) + if expect.Body != nil { + e.reporter.AddHTTPResponseBody(string(actualBody)) - if string(actualBody) != expect.Body { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: string(keys.FieldBody), - Expected: expect.Body, - Actual: string(actualBody), - }, - ) + if string(actualBody) != *expect.Body { + e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldBody), + Expected: *expect.Body, + Actual: string(actualBody), + }) } return nil } if !json.Valid(actualBody) { - result.Summary.Response.HTTP.Body = string(actualBody) + e.reporter.AddHTTPResponseBody(string(actualBody)) - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: string(keys.FieldBodyJSON), - Expected: util.CompactJSON([]byte(expect.BodyJSON)), - Actual: string(actualBody), - Message: "response body is not valid JSON", - }, - ) + e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: util.CompactJSON([]byte(*expect.BodyJSON)), + Actual: string(actualBody), + Message: "response body is not valid JSON", + }) return nil } - result.Summary.Response.HTTP.BodyJSON = - util.CompactJSON(actualBody) + e.reporter.AddHTTPResponseBodyJSON(util.CompactJSON(actualBody)) equal, err := util.IsJSONEqual( - []byte(expect.BodyJSON), + []byte(*expect.BodyJSON), actualBody, ) if err != nil { @@ -121,48 +108,18 @@ func (e *Evaluator) EvaluateResponse( } if !equal { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: string(keys.FieldBodyJSON), - Expected: util.CompactJSON( - []byte(expect.BodyJSON), - ), - Actual: util.CompactJSON(actualBody), - }, - ) + e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: util.CompactJSON( + []byte(*expect.BodyJSON), + ), + Actual: util.CompactJSON(actualBody), + }) } return nil } -func selectHeaders( - actual http.Header, - expected map[string][]string, -) map[string][]string { - if len(expected) == 0 { - return nil - } - - result := make( - map[string][]string, - len(expected), - ) - - for key := range expected { - values := actual.Values(key) - if len(values) > 0 { - result[key] = util.CloneStringSlice(values) - } - } - - if len(result) == 0 { - return nil - } - - return result -} - func (e *Evaluator) Matches( _ context.Context, _ *model.ServiceSpec, @@ -211,13 +168,13 @@ func httpCallMatchesExpectation( } } - if expected.Body != "" && string(actual.Body) != expected.Body { + if expected.Body != nil && string(actual.Body) != *expected.Body { return false } - if expected.BodyJSON != "" { + if expected.BodyJSON != nil { equal, err := util.IsJSONEqual( - []byte(expected.BodyJSON), + []byte(*expected.BodyJSON), actual.Body, ) if err != nil || !equal { diff --git a/execute/worker/http/evaluate_test.go b/execute/worker/http/evaluate_test.go index 92ba0a4..58f63c9 100644 --- a/execute/worker/http/evaluate_test.go +++ b/execute/worker/http/evaluate_test.go @@ -8,13 +8,24 @@ import ( "strings" "testing" - "github.com/e2engine/core/execute" + "go.uber.org/mock/gomock" + "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/keys" ) func TestEvaluatorEvaluateResponse(t *testing.T) { + type bodyCall struct { + json bool + value string + } + + type deviationCall struct { + payload bool + deviation model.TestExecutionDeviation + } + tests := []struct { name string @@ -23,10 +34,8 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { headers nethttp.Header expect model.HTTPResponse - expectedBodyJSON string - expectedBodyText string - expectedHeaders map[string][]string - expected []model.TestExecutionDeviation + bodyCall *bodyCall + deviations []deviationCall }{ { name: "matching status without body expectation", @@ -42,11 +51,13 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, }, - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: "status_code", - Expected: "200", - Actual: "404", + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldStatusCode), + Expected: "200", + Actual: "404", + }, }, }, }, @@ -56,9 +67,12 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: `{"name":"test","count":1}`, expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{"count":1,"name":"test"}`, + BodyJSON: stringPtr(`{"count":1,"name":"test"}`), + }, + bodyCall: &bodyCall{ + json: true, + value: `{"name":"test","count":1}`, }, - expectedBodyJSON: `{"name":"test","count":1}`, }, { name: "JSON body mismatch", @@ -66,14 +80,20 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: `{"name":"actual"}`, expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{"name":"expected"}`, + BodyJSON: stringPtr(`{"name":"expected"}`), }, - expectedBodyJSON: `{"name":"actual"}`, - expected: []model.TestExecutionDeviation{ + bodyCall: &bodyCall{ + json: true, + value: `{"name":"actual"}`, + }, + deviations: []deviationCall{ { - Field: string(keys.FieldBodyJSON), - Expected: `{"name":"expected"}`, - Actual: `{"name":"actual"}`, + payload: true, + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: `{"name":"expected"}`, + Actual: `{"name":"actual"}`, + }, }, }, }, @@ -83,15 +103,20 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: "hello", expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{"message":"hello"}`, + BodyJSON: stringPtr(`{"message":"hello"}`), }, - expectedBodyText: "hello", - expected: []model.TestExecutionDeviation{ + bodyCall: &bodyCall{ + value: "hello", + }, + deviations: []deviationCall{ { - Field: string(keys.FieldBodyJSON), - Expected: `{"message":"hello"}`, - Actual: "hello", - Message: "response body is not valid JSON", + payload: true, + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: `{"message":"hello"}`, + Actual: "hello", + Message: "response body is not valid JSON", + }, }, }, }, @@ -101,19 +126,27 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: `{"actual":true}`, expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{"expected":true}`, + BodyJSON: stringPtr(`{"expected":true}`), }, - expectedBodyJSON: `{"actual":true}`, - expected: []model.TestExecutionDeviation{ + bodyCall: &bodyCall{ + json: true, + value: `{"actual":true}`, + }, + deviations: []deviationCall{ { - Field: "status_code", - Expected: "200", - Actual: "400", + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldStatusCode), + Expected: "200", + Actual: "400", + }, }, { - Field: string(keys.FieldBodyJSON), - Expected: `{"expected":true}`, - Actual: `{"actual":true}`, + payload: true, + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: `{"expected":true}`, + Actual: `{"actual":true}`, + }, }, }, }, @@ -123,9 +156,11 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: "plain text body", expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - Body: "plain text body", + Body: stringPtr("plain text body"), + }, + bodyCall: &bodyCall{ + value: "plain text body", }, - expectedBodyText: "plain text body", }, { name: "mismatched exact text body", @@ -133,14 +168,19 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { body: "actual text body", expect: model.HTTPResponse{ StatusCode: nethttp.StatusOK, - Body: "expected text body", + Body: stringPtr("expected text body"), + }, + bodyCall: &bodyCall{ + value: "actual text body", }, - expectedBodyText: "actual text body", - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: string(keys.FieldBody), - Expected: "expected text body", - Actual: "actual text body", + payload: true, + deviation: model.TestExecutionDeviation{ + Field: string(keys.FieldBody), + Expected: "expected text body", + Actual: "actual text body", + }, }, }, }, @@ -156,9 +196,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "X-Test": {"value"}, }, }, - expectedHeaders: map[string][]string{ - "X-Test": {"value"}, - }, }, { name: "unexpected header is not persisted", @@ -173,9 +210,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "X-Test": {"value"}, }, }, - expectedHeaders: map[string][]string{ - "X-Test": {"value"}, - }, }, { name: "header name is case insensitive", @@ -189,9 +223,6 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "x-test": {"value"}, }, }, - expectedHeaders: map[string][]string{ - "x-test": {"value"}, - }, }, { name: "header mismatch", @@ -205,14 +236,13 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "X-Test": {"expected"}, }, }, - expectedHeaders: map[string][]string{ - "X-Test": {"actual"}, - }, - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: "headers.X-Test", - Expected: "expected", - Actual: "actual", + deviation: model.TestExecutionDeviation{ + Field: "headers.X-Test", + Expected: "expected", + Actual: "actual", + }, }, }, }, @@ -228,11 +258,13 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { "X-Test": {"expected"}, }, }, - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: "headers.X-Test", - Expected: "expected", - Actual: "", + deviation: model.TestExecutionDeviation{ + Field: "headers.X-Test", + Expected: "expected", + Actual: "", + }, }, }, }, @@ -240,7 +272,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - evaluator := NewEvaluator() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) response := &nethttp.Response{ StatusCode: tt.status, @@ -250,99 +285,46 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { ), } - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + reporter.EXPECT(). + AddHTTPResponseStatus(tt.status) - err := evaluator.EvaluateResponse( - context.Background(), - response, - &tt.expect, - result, - ) - if err != nil { - t.Fatalf("EvaluateResponse() error = %v", err) - } - - if result.Summary.Response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - actual := result.Summary.Response.HTTP - - if actual.StatusCode != tt.status { - t.Errorf( - "expected status code %d, got %d", - tt.status, - actual.StatusCode, - ) - } + reporter.EXPECT(). + AddHTTPResponseHeaders(tt.headers) - if actual.BodyJSON != tt.expectedBodyJSON { - t.Errorf( - "expected JSON body %q, got %q", - tt.expectedBodyJSON, - actual.BodyJSON, - ) - } - - if actual.Body != tt.expectedBodyText { - t.Errorf( - "expected text body %q, got %q", - tt.expectedBodyText, - actual.Body, - ) - } - - if len(actual.Headers) != len(tt.expectedHeaders) { - t.Errorf( - "expected %d headers, got %d: %+v", - len(tt.expectedHeaders), - len(actual.Headers), - actual.Headers, - ) - } - - for key, expectedValues := range tt.expectedHeaders { - actualValues, ok := actual.Headers[key] - if !ok { - t.Errorf( - "expected header %q, got %+v", - key, - actual.Headers, - ) - - continue - } - - if len(actualValues) != len(expectedValues) { - t.Errorf( - "expected header %q values %v, got %v", - key, - expectedValues, - actualValues, - ) - - continue + for _, deviation := range tt.deviations { + if deviation.payload { + reporter.EXPECT(). + AddPayloadDeviation(&deviation.deviation) + } else { + reporter.EXPECT(). + AddDeviation(&deviation.deviation) } + } - for i := range expectedValues { - if actualValues[i] != expectedValues[i] { - t.Errorf( - "expected header %q value %q, got %q", - key, - expectedValues[i], - actualValues[i], + if tt.bodyCall != nil { + if tt.bodyCall.json { + reporter.EXPECT(). + AddHTTPResponseBodyJSON( + tt.bodyCall.value, + ) + } else { + reporter.EXPECT(). + AddHTTPResponseBody( + tt.bodyCall.value, ) - } } } - assertDeviations( - t, - result.Summary.Deviations, - tt.expected, + err := evaluator.EvaluateResponse( + response, + &tt.expect, ) + if err != nil { + t.Fatalf( + "EvaluateResponse() error = %v", + err, + ) + } }) } } @@ -350,7 +332,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { func TestEvaluatorEvaluateResponseReadError(t *testing.T) { expectedErr := errors.New("read error") - evaluator := NewEvaluator() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) response := &nethttp.Response{ StatusCode: nethttp.StatusOK, @@ -359,18 +344,18 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { }, } - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + reporter.EXPECT(). + AddHTTPResponseStatus(nethttp.StatusOK) + + reporter.EXPECT(). + AddHTTPResponseHeaders(nil) err := evaluator.EvaluateResponse( - context.Background(), response, &model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{"result":"ok"}`, + BodyJSON: stringPtr(`{"result":"ok"}`), }, - result, ) if !errors.Is(err, expectedErr) { @@ -383,8 +368,6 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { } func TestEvaluatorMatches(t *testing.T) { - evaluator := NewEvaluator() - actual := call.Call{ ServiceID: "service-1", HTTP: &call.HTTPCall{ @@ -397,10 +380,12 @@ func TestEvaluatorMatches(t *testing.T) { } tests := []struct { - name string + name string + actual call.Call expected model.ServiceExpectedCalls - match bool + + match bool }{ { name: "matches", @@ -410,7 +395,7 @@ func TestEvaluatorMatches(t *testing.T) { HTTP: &model.HTTPRequestPattern{ Method: "POST", Path: "/users", - BodyJSON: `{"name":"Yaroslav"}`, + BodyJSON: stringPtr(`{"name":"Yaroslav"}`), }, }, match: true, @@ -458,6 +443,11 @@ func TestEvaluatorMatches(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) + match, err := evaluator.Matches( context.Background(), &model.ServiceSpec{}, @@ -465,7 +455,10 @@ func TestEvaluatorMatches(t *testing.T) { tt.expected, ) if err != nil { - t.Fatalf("Matches() error = %v", err) + t.Fatalf( + "Matches() error = %v", + err, + ) } if match != tt.match { @@ -495,10 +488,12 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { } tests := []struct { - name string + name string + expected model.HTTPRequestPattern body []byte - match bool + + match bool }{ { name: "empty expectation", @@ -517,7 +512,9 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { "Content-Type": {"application/json"}, "X-Test": {"one", "two"}, }, - BodyJSON: `{"active":true,"name":"Yaroslav"}`, + BodyJSON: stringPtr( + `{"active":true,"name":"Yaroslav"}`, + ), }, match: true, }, @@ -577,30 +574,36 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "JSON body mismatch", expected: model.HTTPRequestPattern{ - BodyJSON: `{"name":"Other"}`, + BodyJSON: stringPtr( + `{"name":"Other"}`, + ), }, }, { name: "actual body is invalid JSON", expected: model.HTTPRequestPattern{ - BodyJSON: `{"name":"Yaroslav"}`, + BodyJSON: stringPtr( + `{"name":"Yaroslav"}`, + ), }, - body: []byte("not-json"), - match: false, + body: []byte("not-json"), }, { name: "exact text body matches", expected: model.HTTPRequestPattern{ - Body: `{"name":"Yaroslav","active":true}`, + Body: stringPtr( + `{"name":"Yaroslav","active":true}`, + ), }, match: true, }, { name: "exact text body mismatch", expected: model.HTTPRequestPattern{ - Body: `{"active":true,"name":"Yaroslav"}`, + Body: stringPtr( + `{"active":true,"name":"Yaroslav"}`, + ), }, - match: false, }, { name: "query subset matches", @@ -638,6 +641,20 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, match: true, }, + { + name: "explicit empty body matches empty body", + expected: model.HTTPRequestPattern{ + Body: stringPtr(""), + }, + body: []byte{}, + match: true, + }, + { + name: "explicit empty body does not match non-empty body", + expected: model.HTTPRequestPattern{ + Body: stringPtr(""), + }, + }, } for _, tt := range tests { @@ -665,15 +682,20 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { } func TestEvaluatorDeviation(t *testing.T) { - evaluator := NewEvaluator() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) service := &model.ServiceSpec{ ID: "service-1", } tests := []struct { - name string - actual call.Call + name string + + actual call.Call + expected *model.TestExecutionDeviation }{ { @@ -710,18 +732,22 @@ func TestEvaluatorDeviation(t *testing.T) { Headers: func() nethttp.Header { headers := make(nethttp.Header) headers.Set( - string(keys.E2EngineMockMissHeader), + string( + keys.E2EngineMockMissHeader, + ), "true", ) + return headers }(), }, }, }, expected: &model.TestExecutionDeviation{ - Field: "calls.service-1", - Actual: "POST /users", - Message: "mocked service received a request that did not match any fixture", + Field: "calls.service-1", + Actual: "POST /users", + Message: "mocked service received a request " + + "that did not match any fixture", }, }, } @@ -773,30 +799,6 @@ func (r *errorReader) Close() error { return nil } -func assertDeviations( - t *testing.T, - actual []model.TestExecutionDeviation, - expected []model.TestExecutionDeviation, -) { - t.Helper() - - if len(actual) != len(expected) { - t.Fatalf( - "expected %d deviations, got %d: %+v", - len(expected), - len(actual), - actual, - ) - } - - for i := range expected { - if actual[i] != expected[i] { - t.Errorf( - "deviation %d: expected %+v, got %+v", - i, - expected[i], - actual[i], - ) - } - } +func stringPtr(value string) *string { + return &value } diff --git a/execute/worker/http/executor.go b/execute/worker/http/executor.go index 917cda2..fcb5afa 100644 --- a/execute/worker/http/executor.go +++ b/execute/worker/http/executor.go @@ -15,22 +15,24 @@ import ( type TestExecutor struct { client *http.Client evaluator *Evaluator + reporter executionReporter } func NewTestExecutor( client *http.Client, evaluator *Evaluator, + reporter executionReporter, ) *TestExecutor { return &TestExecutor{ client: client, evaluator: evaluator, + reporter: reporter, } } func (e *TestExecutor) Execute( ctx context.Context, job *execute.TestJob, - result *execute.TestExecutionResult, ) error { req, err := buildHTTPRequest( ctx, @@ -41,6 +43,8 @@ func (e *TestExecutor) Execute( return err } + e.reporter.AddHTTPRequest(req) + resp, err := doHTTPRequest( e.client, req, @@ -51,10 +55,8 @@ func (e *TestExecutor) Execute( defer resp.Body.Close() if err := e.evaluator.EvaluateResponse( - ctx, resp, job.Test.Spec.Expect.HTTP, - result, ); err != nil { return err } diff --git a/execute/worker/http/executor_test.go b/execute/worker/http/executor_test.go index aa7c5ff..6a52e5f 100644 --- a/execute/worker/http/executor_test.go +++ b/execute/worker/http/executor_test.go @@ -10,6 +10,7 @@ import ( "testing" e2enginehttp "github.com/e2engine/instrumentation-go/http" + "go.uber.org/mock/gomock" "github.com/e2engine/core/execute" "github.com/e2engine/core/model" @@ -448,9 +449,15 @@ func TestExecutorExecute(t *testing.T) { ) defer server.Close() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) + executor := NewTestExecutor( server.Client(), - NewEvaluator(), + evaluator, + reporter, ) job := &execute.TestJob{ @@ -466,24 +473,69 @@ func TestExecutorExecute(t *testing.T) { Expect: model.ExpectSpec{ HTTP: &model.HTTPResponse{ StatusCode: nethttp.StatusOK, - BodyJSON: `{ - "name": "test", - "id": 42 - }`, + BodyJSON: stringPtrExecutor( + `{"name":"test","id":42}`, + ), }, }, }, }, } - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + reporter.EXPECT(). + AddHTTPRequest(gomock.Any()). + Do(func(req *nethttp.Request) { + if req.Method != nethttp.MethodGet { + t.Errorf( + "expected method %q, got %q", + nethttp.MethodGet, + req.Method, + ) + } + + if req.URL.String() != server.URL { + t.Errorf( + "expected URL %q, got %q", + server.URL, + req.URL.String(), + ) + } + + if id := e2enginehttp.TestExecutionID( + req.Header, + ); id != "execution-123" { + t.Errorf( + "expected execution ID header %q, got %q", + "execution-123", + id, + ) + } + }) + + reporter.EXPECT(). + AddHTTPResponseStatus(nethttp.StatusOK) + + reporter.EXPECT(). + AddHTTPResponseHeaders(gomock.Any()). + Do(func(headers nethttp.Header) { + if headers.Get("Content-Type") != + "application/json" { + t.Errorf( + "expected Content-Type %q, got %q", + "application/json", + headers.Get("Content-Type"), + ) + } + }) + + reporter.EXPECT(). + AddHTTPResponseBodyJSON( + `{"id":42,"name":"test"}`, + ) err := executor.Execute( context.Background(), job, - result, ) if err != nil { t.Fatalf( @@ -491,33 +543,10 @@ func TestExecutorExecute(t *testing.T) { err, ) } +} - if result.Summary.Response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - response := result.Summary.Response.HTTP - - if response.StatusCode != nethttp.StatusOK { - t.Errorf( - "expected status %d, got %d", - nethttp.StatusOK, - response.StatusCode, - ) - } - - if response.BodyJSON != - `{"id":42,"name":"test"}` { - t.Errorf( - "unexpected response body %q", - response.BodyJSON, - ) - } - - if len(result.Summary.Deviations) != 0 { - t.Errorf( - "expected no deviations, got %+v", - result.Summary.Deviations, - ) - } +func stringPtrExecutor( + value string, +) *string { + return &value } diff --git a/execute/worker/http/mock_reporter_test.go b/execute/worker/http/mock_reporter_test.go new file mode 100644 index 0000000..e8f0cc5 --- /dev/null +++ b/execute/worker/http/mock_reporter_test.go @@ -0,0 +1,126 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: reporter.go +// +// Generated by this command: +// +// mockgen -source=reporter.go -destination=mock_reporter_test.go -package=http +// + +// Package http is a generated GoMock package. +package http + +import ( + http "net/http" + reflect "reflect" + + model "github.com/e2engine/core/model" + gomock "go.uber.org/mock/gomock" +) + +// MockexecutionReporter is a mock of executionReporter interface. +type MockexecutionReporter struct { + ctrl *gomock.Controller + recorder *MockexecutionReporterMockRecorder + isgomock struct{} +} + +// MockexecutionReporterMockRecorder is the mock recorder for MockexecutionReporter. +type MockexecutionReporterMockRecorder struct { + mock *MockexecutionReporter +} + +// NewMockexecutionReporter creates a new mock instance. +func NewMockexecutionReporter(ctrl *gomock.Controller) *MockexecutionReporter { + mock := &MockexecutionReporter{ctrl: ctrl} + mock.recorder = &MockexecutionReporterMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockexecutionReporter) EXPECT() *MockexecutionReporterMockRecorder { + return m.recorder +} + +// AddDeviation mocks base method. +func (m *MockexecutionReporter) AddDeviation(deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddDeviation", deviation) +} + +// AddDeviation indicates an expected call of AddDeviation. +func (mr *MockexecutionReporterMockRecorder) AddDeviation(deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddDeviation), deviation) +} + +// AddHTTPRequest mocks base method. +func (m *MockexecutionReporter) AddHTTPRequest(req *http.Request) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHTTPRequest", req) +} + +// AddHTTPRequest indicates an expected call of AddHTTPRequest. +func (mr *MockexecutionReporterMockRecorder) AddHTTPRequest(req any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPRequest", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPRequest), req) +} + +// AddHTTPResponseBody mocks base method. +func (m *MockexecutionReporter) AddHTTPResponseBody(body string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHTTPResponseBody", body) +} + +// AddHTTPResponseBody indicates an expected call of AddHTTPResponseBody. +func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseBody(body any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPResponseBody", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPResponseBody), body) +} + +// AddHTTPResponseBodyJSON mocks base method. +func (m *MockexecutionReporter) AddHTTPResponseBodyJSON(body string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHTTPResponseBodyJSON", body) +} + +// AddHTTPResponseBodyJSON indicates an expected call of AddHTTPResponseBodyJSON. +func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseBodyJSON(body any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPResponseBodyJSON", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPResponseBodyJSON), body) +} + +// AddHTTPResponseHeaders mocks base method. +func (m *MockexecutionReporter) AddHTTPResponseHeaders(headers http.Header) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHTTPResponseHeaders", headers) +} + +// AddHTTPResponseHeaders indicates an expected call of AddHTTPResponseHeaders. +func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseHeaders(headers any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPResponseHeaders", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPResponseHeaders), headers) +} + +// AddHTTPResponseStatus mocks base method. +func (m *MockexecutionReporter) AddHTTPResponseStatus(status int) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddHTTPResponseStatus", status) +} + +// AddHTTPResponseStatus indicates an expected call of AddHTTPResponseStatus. +func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseStatus(status any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHTTPResponseStatus", reflect.TypeOf((*MockexecutionReporter)(nil).AddHTTPResponseStatus), status) +} + +// AddPayloadDeviation mocks base method. +func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddPayloadDeviation", deviation) +} + +// AddPayloadDeviation indicates an expected call of AddPayloadDeviation. +func (mr *MockexecutionReporterMockRecorder) AddPayloadDeviation(deviation any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddPayloadDeviation", reflect.TypeOf((*MockexecutionReporter)(nil).AddPayloadDeviation), deviation) +} diff --git a/execute/worker/http/reporter.go b/execute/worker/http/reporter.go new file mode 100644 index 0000000..0674259 --- /dev/null +++ b/execute/worker/http/reporter.go @@ -0,0 +1,19 @@ +package http + +import ( + "net/http" + + "github.com/e2engine/core/model" +) + +type executionReporter interface { + AddDeviation(deviation *model.TestExecutionDeviation) + AddPayloadDeviation(deviation *model.TestExecutionDeviation) + AddHTTPRequest(req *http.Request) + AddHTTPResponseStatus(status int) + AddHTTPResponseHeaders(headers http.Header) + AddHTTPResponseBody(body string) + AddHTTPResponseBodyJSON(body string) +} + +//go:generate go run -mod=mod go.uber.org/mock/mockgen -source=reporter.go -destination=mock_reporter_test.go -package=http diff --git a/execute/evaluate/calls.go b/execute/worker/reporter/calls.go similarity index 98% rename from execute/evaluate/calls.go rename to execute/worker/reporter/calls.go index 934c786..d0b6d3d 100644 --- a/execute/evaluate/calls.go +++ b/execute/worker/reporter/calls.go @@ -1,4 +1,4 @@ -package evaluate +package reporter import ( "sort" @@ -21,7 +21,7 @@ type grpcObservedCallKey struct { ResponseStatus string } -func SummarizeCalls( +func summarizeCalls( executionID string, calls call.Reader, ) []model.ServiceObservedCalls { diff --git a/execute/evaluate/calls_test.go b/execute/worker/reporter/calls_test.go similarity index 94% rename from execute/evaluate/calls_test.go rename to execute/worker/reporter/calls_test.go index 1f3a1c8..fb65cd0 100644 --- a/execute/evaluate/calls_test.go +++ b/execute/worker/reporter/calls_test.go @@ -1,4 +1,4 @@ -package evaluate +package reporter import ( "testing" @@ -480,7 +480,7 @@ func TestSummarizeCalls(t *testing.T) { store.Record(actual) } - actual := SummarizeCalls( + actual := summarizeCalls( "execution-1", store, ) @@ -528,12 +528,47 @@ func TestSummarizeCallsDoesNotExposeCapturedData( }, }) - actual := SummarizeCalls( + store.Record(call.Call{ + TestExecutionID: "execution-1", + ServiceID: "grpc-service", + GRPC: &call.GRPCCall{ + Request: call.GRPCRequest{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]string{ + "authorization": { + "Bearer secret-token", + }, + }, + Message: []byte(`{"secret": "request"}`), + }, + Response: call.GRPCResponse{ + Status: "OK", + Metadata: map[string][]string{ + "set-cookie": { + "secret-cookie", + }, + }, + Message: []byte(`{"secret": "response"}`), + }, + }, + }) + + actual := summarizeCalls( "execution-1", store, ) expected := []model.ServiceObservedCalls{ + { + ServiceID: "grpc-service", + Count: 1, + GRPC: &model.GRPCServiceObservedCall{ + Service: "users.UserService", + Method: "Create", + ResponseStatus: "OK", + }, + }, { ServiceID: "service-1", Count: 1, diff --git a/execute/worker/reporter/reporter.go b/execute/worker/reporter/reporter.go new file mode 100644 index 0000000..66a02ed --- /dev/null +++ b/execute/worker/reporter/reporter.go @@ -0,0 +1,288 @@ +package reporter + +import ( + "encoding/json" + "net/http" + "time" + + "github.com/e2engine/core/execute" + "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/internal/util" + "github.com/e2engine/core/model" +) + +type Reporter struct { + cfg *Config + testSpec *model.TestSpec + report *execute.TestExecutionResult +} + +type Config struct { + DumpPayload bool `json:"dump_payload" yaml:"dump_payload" env:"DUMP_PAYLOAD"` +} + +func New( + cfg *Config, + testSpec *model.TestSpec, + executionID, testSuiteExecutionID string, +) *Reporter { + return &Reporter{ + cfg: cfg, + testSpec: testSpec, + report: &execute.TestExecutionResult{ + ExecutionID: executionID, + TestSuiteExecutionID: testSuiteExecutionID, + Summary: &model.TestExecutionSummary{}, + }, + } +} + +func (r *Reporter) Result() *execute.TestExecutionResult { + return r.report +} + +func (r *Reporter) SetError(err error) { + r.ensureNotFinalized() + + r.report.Status = model.ExecutionStatusError + r.report.FinishedAt = time.Now().UTC() + r.report.Summary.Error = err.Error() +} + +func (r *Reporter) Finalize() { + r.ensureNotFinalized() + + if len(r.report.Summary.Deviations) == 0 { + r.report.Status = model.ExecutionStatusPassed + } else { + r.report.Status = model.ExecutionStatusFailed + } + + r.report.FinishedAt = time.Now().UTC() +} + +func (r *Reporter) ensureNotFinalized() { + if !r.report.FinishedAt.IsZero() { + panic("cannot modify report after it has been finalized") + } +} + +func (r *Reporter) SummarizeCalls(calls call.Reader) { + r.ensureNotFinalized() + + r.report.Summary.Calls = summarizeCalls( + r.report.ExecutionID, + calls, + ) +} + +func (r *Reporter) AddDeviation(deviation *model.TestExecutionDeviation) { + if deviation == nil { + return + } + r.ensureNotFinalized() + r.report.Summary.Deviations = append(r.report.Summary.Deviations, *deviation) +} + +func (r *Reporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { + if deviation == nil { + return + } + + d := &model.TestExecutionDeviation{ + Field: deviation.Field, + Message: deviation.Message, + } + + if r.cfg.DumpPayload { + d.Actual = deviation.Actual + d.Expected = deviation.Expected + } + + r.AddDeviation(d) +} + +func (r *Reporter) AddHTTPRequest(req *http.Request) { + r.ensureNotFinalized() + + request := &model.HTTPRequest{ + Method: req.Method, + URL: req.URL.String(), + Headers: req.Header.Clone(), + } + + if r.cfg.DumpPayload { + request.Body = r.testSpec.Request.HTTP.Body + + if r.testSpec.Request.HTTP.BodyJSON != "" { + request.BodyJSON = util.CompactJSON( + json.RawMessage(r.testSpec.Request.HTTP.BodyJSON), + ) + } + } + + r.report.Summary.Request = &model.TestExecutionRequestSummary{ + HTTP: request, + } +} + +func (r *Reporter) ensureHTTPResponseSummary() { + if r.report.Summary.Response == nil { + r.report.Summary.Response = &model.TestExecutionResponseSummary{} + } + + if r.report.Summary.Response.HTTP == nil { + r.report.Summary.Response.HTTP = &model.HTTPResponse{} + } +} + +func (r *Reporter) AddHTTPResponseStatus(status int) { + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.StatusCode = status +} + +func (r *Reporter) AddHTTPResponseHeaders(headers http.Header) { + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.Headers = selectHeaders( + headers, + r.testSpec.Expect.HTTP.Headers, + ) +} + +func selectHeaders( + actual http.Header, + expected map[string][]string, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for key := range expected { + values := actual.Values(key) + if len(values) > 0 { + result[key] = util.CloneStringSlice(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + +func (r *Reporter) AddHTTPResponseBody(body string) { + if !r.cfg.DumpPayload { + return + } + + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.Body = &body +} + +func (r *Reporter) AddHTTPResponseBodyJSON(body string) { + if !r.cfg.DumpPayload { + return + } + + r.ensureNotFinalized() + + r.ensureHTTPResponseSummary() + r.report.Summary.Response.HTTP.BodyJSON = &body +} + +func (r *Reporter) ensureGRPCResponseSummary() { + if r.report.Summary.Response == nil { + r.report.Summary.Response = &model.TestExecutionResponseSummary{} + } + + if r.report.Summary.Response.GRPC == nil { + r.report.Summary.Response.GRPC = &model.GRPCResponse{} + } +} + +func (r *Reporter) AddGRPCRequest(req *model.GRPCRequest) { + r.ensureNotFinalized() + + request := &model.GRPCRequest{ + Target: req.Target, + Service: req.Service, + Method: req.Method, + Metadata: util.CloneStringSliceMap(req.Metadata), + } + + if r.cfg.DumpPayload { + request.Message = util.CloneMap(req.Message) + } + + r.report.Summary.Request = &model.TestExecutionRequestSummary{ + GRPC: request, + } +} + +func (r *Reporter) AddGRPCResponseStatus(status string) { + r.ensureNotFinalized() + + r.ensureGRPCResponseSummary() + r.report.Summary.Response.GRPC.Status = status +} + +func (r *Reporter) AddGRPCResponseMetadata(metadata map[string][]string) { + r.ensureNotFinalized() + + r.ensureGRPCResponseSummary() + r.report.Summary.Response.GRPC.Metadata = selectMetadata( + metadata, + r.testSpec.Expect.GRPC.Metadata, + ) +} + +func selectMetadata( + actual map[string][]string, + expected map[string][]string, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for key := range expected { + if values, ok := actual[key]; ok { + result[key] = util.CloneStringSlice(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + +func (r *Reporter) AddGRPCResponseMessage(message map[string]any) { + if !r.cfg.DumpPayload { + return + } + + r.ensureNotFinalized() + + r.ensureGRPCResponseSummary() + + m := util.CloneMap(message) + r.report.Summary.Response.GRPC.Message = &m +} diff --git a/execute/worker/reporter/reporter_test.go b/execute/worker/reporter/reporter_test.go new file mode 100644 index 0000000..0223f57 --- /dev/null +++ b/execute/worker/reporter/reporter_test.go @@ -0,0 +1,993 @@ +package reporter + +import ( + "errors" + "net/http" + "net/url" + "reflect" + "testing" + + "github.com/e2engine/core/model" +) + +func TestNew(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + result := r.Result() + + if result.ExecutionID != "execution-1" { + t.Errorf( + "expected execution ID %q, got %q", + "execution-1", + result.ExecutionID, + ) + } + + if result.TestSuiteExecutionID != "suite-execution-1" { + t.Errorf( + "expected test suite execution ID %q, got %q", + "suite-execution-1", + result.TestSuiteExecutionID, + ) + } + + if result.Summary == nil { + t.Fatal("expected summary") + } + + if !result.FinishedAt.IsZero() { + t.Errorf( + "expected zero finished time, got %v", + result.FinishedAt, + ) + } +} + +func TestReporterSetError(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + expectedErr := errors.New("execution failed") + + r.SetError(expectedErr) + + result := r.Result() + + if result.Status != model.ExecutionStatusError { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusError, + result.Status, + ) + } + + if result.Summary.Error != expectedErr.Error() { + t.Errorf( + "expected error %q, got %q", + expectedErr.Error(), + result.Summary.Error, + ) + } + + if result.FinishedAt.IsZero() { + t.Error("expected non-zero finished time") + } + + mustPanic(t, func() { + r.AddDeviation( + &model.TestExecutionDeviation{}, + ) + }) +} + +func TestReporterFinalize(t *testing.T) { + tests := []struct { + name string + + addDeviation bool + expected model.ExecutionStatus + }{ + { + name: "passed", + expected: model.ExecutionStatusPassed, + }, + { + name: "failed", + addDeviation: true, + expected: model.ExecutionStatusFailed, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + if tt.addDeviation { + r.AddDeviation( + &model.TestExecutionDeviation{ + Field: "status", + }, + ) + } + + r.Finalize() + + result := r.Result() + + if result.Status != tt.expected { + t.Errorf( + "expected status %q, got %q", + tt.expected, + result.Status, + ) + } + + if result.FinishedAt.IsZero() { + t.Error("expected non-zero finished time") + } + + mustPanic(t, func() { + r.Finalize() + }) + }) + } +} + +func TestReporterAddDeviation(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddDeviation(nil) + + if len(r.Result().Summary.Deviations) != 0 { + t.Fatal("expected nil deviation to be ignored") + } + + deviation := &model.TestExecutionDeviation{ + Field: "body", + Expected: "expected", + Actual: "actual", + Message: "message", + } + + r.AddDeviation(deviation) + + if len(r.Result().Summary.Deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(r.Result().Summary.Deviations), + ) + } + + actual := r.Result().Summary.Deviations[0] + + if actual != *deviation { + t.Errorf( + "expected deviation %+v, got %+v", + *deviation, + actual, + ) + } + + // Reporter stores the deviation by value. + deviation.Field = "changed" + + if r.Result().Summary.Deviations[0].Field != "body" { + t.Error("stored deviation changed with source") + } +} + +func TestReporterAddPayloadDeviation(t *testing.T) { + deviation := &model.TestExecutionDeviation{ + Field: "body", + Expected: "expected payload", + Actual: "actual payload", + Message: "payload differs", + } + + tests := []struct { + name string + + dumpPayload bool + + expectedExpected string + expectedActual string + }{ + { + name: "payload disabled", + }, + { + name: "payload enabled", + dumpPayload: true, + expectedExpected: deviation.Expected, + expectedActual: deviation.Actual, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddPayloadDeviation(nil) + + r.AddPayloadDeviation(deviation) + + if len(r.Result().Summary.Deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(r.Result().Summary.Deviations), + ) + } + + actual := r.Result().Summary.Deviations[0] + + if actual.Field != deviation.Field { + t.Errorf( + "expected field %q, got %q", + deviation.Field, + actual.Field, + ) + } + + if actual.Message != deviation.Message { + t.Errorf( + "expected message %q, got %q", + deviation.Message, + actual.Message, + ) + } + + if actual.Expected != tt.expectedExpected { + t.Errorf( + "expected Expected %q, got %q", + tt.expectedExpected, + actual.Expected, + ) + } + + if actual.Actual != tt.expectedActual { + t.Errorf( + "expected Actual %q, got %q", + tt.expectedActual, + actual.Actual, + ) + } + }) + } +} + +func TestReporterAddHTTPRequest(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + + expectedBody string + expectedBodyJSON string + }{ + { + name: "payload disabled", + }, + { + name: "payload enabled", + dumpPayload: true, + expectedBody: "request body", + expectedBodyJSON: `{"name":"test"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{ + Body: "request body", + BodyJSON: `{ + "name": "test" + }`, + }, + }, + } + + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + spec, + ) + + u, err := url.Parse( + "http://example.com/resource?a=1", + ) + if err != nil { + t.Fatal(err) + } + + req := &http.Request{ + Method: http.MethodPost, + URL: u, + Header: http.Header{ + "X-Test": {"one", "two"}, + }, + } + + r.AddHTTPRequest(req) + + actual := r.Result().Summary.Request.HTTP + + if actual == nil { + t.Fatal("expected HTTP request summary") + } + + if actual.Method != http.MethodPost { + t.Errorf( + "expected method %q, got %q", + http.MethodPost, + actual.Method, + ) + } + + if actual.URL != u.String() { + t.Errorf( + "expected URL %q, got %q", + u.String(), + actual.URL, + ) + } + + if !reflect.DeepEqual( + actual.Headers, + map[string][]string(req.Header), + ) { + t.Errorf( + "expected headers %#+v, got %#+v", + req.Header, + actual.Headers, + ) + } + + if actual.Body != tt.expectedBody { + t.Errorf( + "expected body %q, got %q", + tt.expectedBody, + actual.Body, + ) + } + + if actual.BodyJSON != tt.expectedBodyJSON { + t.Errorf( + "expected JSON body %q, got %q", + tt.expectedBodyJSON, + actual.BodyJSON, + ) + } + + req.Header["X-Test"][0] = "changed" + + if actual.Headers["X-Test"][0] != "one" { + t.Error( + "stored headers changed with source", + ) + } + }) + } +} + +func TestReporterAddHTTPResponseStatus(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddHTTPResponseStatus(http.StatusCreated) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.StatusCode != http.StatusCreated { + t.Errorf( + "expected status %d, got %d", + http.StatusCreated, + response.HTTP.StatusCode, + ) + } +} + +func TestReporterAddHTTPResponseHeaders(t *testing.T) { + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponse{ + Headers: map[string][]string{ + "X-Included": {"expected"}, + "X-Missing": {"expected"}, + }, + }, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + headers := http.Header{ + "X-Included": {"actual-1", "actual-2"}, + "X-Unrelated": {"secret"}, + } + + r.AddHTTPResponseHeaders(headers) + + actual := r.Result().Summary.Response.HTTP.Headers + + expected := map[string][]string{ + "X-Included": {"actual-1", "actual-2"}, + } + + if !reflect.DeepEqual(actual, expected) { + t.Errorf( + "expected headers %+v, got %+v", + expected, + actual, + ) + } + + headers["X-Included"][0] = "changed" + + if actual["X-Included"][0] != "actual-1" { + t.Error( + "stored headers changed with source", + ) + } +} + +func TestSelectHeaders(t *testing.T) { + tests := []struct { + name string + + actual http.Header + expected map[string][]string + + want map[string][]string + }{ + { + name: "no expected headers", + actual: http.Header{ + "X-Test": {"value"}, + }, + }, + { + name: "expected header absent", + actual: http.Header{ + "X-Test": {"value"}, + }, + expected: map[string][]string{ + "X-Missing": {"expected"}, + }, + }, + { + name: "selected headers", + actual: http.Header{ + "X-One": {"1"}, + "X-Two": {"2"}, + "X-Other": {"other"}, + }, + expected: map[string][]string{ + "X-One": {"expected"}, + "X-Two": {"expected"}, + "X-Missing": {"expected"}, + }, + want: map[string][]string{ + "X-One": {"1"}, + "X-Two": {"2"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := selectHeaders( + tt.actual, + tt.expected, + ) + + if !reflect.DeepEqual(actual, tt.want) { + t.Errorf( + "expected %+v, got %+v", + tt.want, + actual, + ) + } + }) + } +} + +func TestReporterAddHTTPResponseBody(t *testing.T) { + t.Run("payload disabled", func(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBody("body") + + if r.Result().Summary.Response != nil { + t.Fatal( + "expected response summary not to be created", + ) + } + }) + + t.Run("payload enabled", func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: true, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBody("") + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.Body == nil { + t.Fatal( + "expected non-nil body pointer", + ) + } + + if *response.HTTP.Body != "" { + t.Errorf( + "expected empty body, got %q", + *response.HTTP.Body, + ) + } + }) +} + +func TestReporterAddHTTPResponseBodyJSON(t *testing.T) { + t.Run("payload disabled", func(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBodyJSON("{}") + + if r.Result().Summary.Response != nil { + t.Fatal( + "expected response summary not to be created", + ) + } + }) + + t.Run("payload enabled", func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: true, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBodyJSON("") + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.BodyJSON == nil { + t.Fatal( + "expected non-nil JSON body pointer", + ) + } + + if *response.HTTP.BodyJSON != "" { + t.Errorf( + "expected empty JSON body, got %q", + *response.HTTP.BodyJSON, + ) + } + }) +} + +func TestReporterAddGRPCRequest(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + expectMessage bool + }{ + { + name: "payload disabled", + }, + { + name: "payload enabled", + dumpPayload: true, + expectMessage: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + req := &model.GRPCRequest{ + Target: "127.0.0.1:8080", + Service: "example.Service", + Method: "Create", + Metadata: map[string][]string{ + "x-test": {"one", "two"}, + }, + Message: map[string]any{ + "name": "test", + }, + } + + r.AddGRPCRequest(req) + + actual := r.Result().Summary.Request.GRPC + + if actual == nil { + t.Fatal("expected gRPC request summary") + } + + if actual.Target != req.Target { + t.Errorf( + "expected target %q, got %q", + req.Target, + actual.Target, + ) + } + + if actual.Service != req.Service { + t.Errorf( + "expected service %q, got %q", + req.Service, + actual.Service, + ) + } + + if actual.Method != req.Method { + t.Errorf( + "expected method %q, got %q", + req.Method, + actual.Method, + ) + } + + if !reflect.DeepEqual( + actual.Metadata, + req.Metadata, + ) { + t.Errorf( + "expected metadata %+v, got %+v", + req.Metadata, + actual.Metadata, + ) + } + + if tt.expectMessage { + if !reflect.DeepEqual( + actual.Message, + req.Message, + ) { + t.Errorf( + "expected message %+v, got %+v", + req.Message, + actual.Message, + ) + } + } else if actual.Message != nil { + t.Errorf( + "expected nil message, got %+v", + actual.Message, + ) + } + + req.Metadata["x-test"][0] = "changed" + req.Message["name"] = "changed" + + if actual.Metadata["x-test"][0] != "one" { + t.Error( + "stored metadata changed with source", + ) + } + + if tt.expectMessage && + actual.Message["name"] != "test" { + t.Error( + "stored message changed with source", + ) + } + }) + } +} + +func TestReporterAddGRPCResponseStatus(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddGRPCResponseStatus("OK") + + response := r.Result().Summary.Response + + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + if response.GRPC.Status != "OK" { + t.Errorf( + "expected status %q, got %q", + "OK", + response.GRPC.Status, + ) + } +} + +func TestReporterAddGRPCResponseMetadata(t *testing.T) { + spec := &model.TestSpec{ + Expect: model.ExpectSpec{ + GRPC: &model.GRPCResponse{ + Metadata: map[string][]string{ + "x-included": {"expected"}, + "x-missing": {"expected"}, + }, + }, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + metadata := map[string][]string{ + "x-included": {"actual-1", "actual-2"}, + "x-unrelated": {"secret"}, + } + + r.AddGRPCResponseMetadata(metadata) + + actual := r.Result(). + Summary. + Response. + GRPC. + Metadata + + expected := map[string][]string{ + "x-included": {"actual-1", "actual-2"}, + } + + if !reflect.DeepEqual(actual, expected) { + t.Errorf( + "expected metadata %+v, got %+v", + expected, + actual, + ) + } + + metadata["x-included"][0] = "changed" + + if actual["x-included"][0] != "actual-1" { + t.Error( + "stored metadata changed with source", + ) + } +} + +func TestSelectMetadata(t *testing.T) { + tests := []struct { + name string + + actual map[string][]string + expected map[string][]string + + want map[string][]string + }{ + { + name: "no expected metadata", + actual: map[string][]string{ + "x-test": {"value"}, + }, + }, + { + name: "expected metadata absent", + actual: map[string][]string{ + "x-test": {"value"}, + }, + expected: map[string][]string{ + "x-missing": {"expected"}, + }, + }, + { + name: "selected metadata", + actual: map[string][]string{ + "x-one": {"1"}, + "x-two": {"2"}, + "x-other": {"other"}, + }, + expected: map[string][]string{ + "x-one": {"expected"}, + "x-two": {"expected"}, + "x-missing": {"expected"}, + }, + want: map[string][]string{ + "x-one": {"1"}, + "x-two": {"2"}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actual := selectMetadata( + tt.actual, + tt.expected, + ) + + if !reflect.DeepEqual(actual, tt.want) { + t.Errorf( + "expected %+v, got %+v", + tt.want, + actual, + ) + } + }) + } +} + +func TestReporterAddGRPCResponseMessage(t *testing.T) { + t.Run("payload disabled", func(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddGRPCResponseMessage( + map[string]any{ + "name": "test", + }, + ) + + if r.Result().Summary.Response != nil { + t.Fatal( + "expected response summary not to be created", + ) + } + }) + + t.Run("payload enabled", func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: true, + }, + &model.TestSpec{}, + ) + + message := map[string]any{ + "name": "test", + } + + r.AddGRPCResponseMessage(message) + + response := r.Result().Summary.Response + + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + if response.GRPC.Message == nil { + t.Fatal( + "expected non-nil message pointer", + ) + } + + if !reflect.DeepEqual( + *response.GRPC.Message, + message, + ) { + t.Errorf( + "expected message %+v, got %+v", + message, + *response.GRPC.Message, + ) + } + + message["name"] = "changed" + + if (*response.GRPC.Message)["name"] != "test" { + t.Error( + "stored message changed with source", + ) + } + }) + + t.Run("explicit empty message", func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: true, + }, + &model.TestSpec{}, + ) + + r.AddGRPCResponseMessage( + map[string]any{}, + ) + + response := r.Result().Summary.Response + + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } + + if response.GRPC.Message == nil { + t.Fatal( + "expected non-nil message pointer", + ) + } + + if len(*response.GRPC.Message) != 0 { + t.Errorf( + "expected empty message, got %+v", + *response.GRPC.Message, + ) + } + }) +} + +func newReporterForTest( + cfg *Config, + spec *model.TestSpec, +) *Reporter { + return New( + cfg, + spec, + "execution-1", + "suite-execution-1", + ) +} + +func mustPanic( + t *testing.T, + fn func(), +) { + t.Helper() + + defer func() { + if recover() == nil { + t.Fatal("expected panic") + } + }() + + fn() +} diff --git a/execute/worker/summary.go b/execute/worker/summary.go deleted file mode 100644 index 909fd32..0000000 --- a/execute/worker/summary.go +++ /dev/null @@ -1,37 +0,0 @@ -package worker - -import ( - "encoding/json" - - "github.com/e2engine/core/internal/util" - "github.com/e2engine/core/model" -) - -func newSummary(spec *model.TestSpec) *model.TestExecutionSummary { - if spec.Request.HTTP != nil { - return &model.TestExecutionSummary{ - Request: &model.TestExecutionRequestSummary{ - HTTP: &model.HTTPRequest{ - Method: spec.Request.HTTP.Method, - URL: spec.Request.HTTP.URL, - Query: util.CloneStringSliceMap(spec.Request.HTTP.Query), - Headers: util.CloneHTTPHeader(spec.Request.HTTP.Headers), - Body: spec.Request.HTTP.Body, - BodyJSON: util.CompactJSON(json.RawMessage(spec.Request.HTTP.BodyJSON)), - }, - }, - } - } - - return &model.TestExecutionSummary{ - Request: &model.TestExecutionRequestSummary{ - GRPC: &model.GRPCRequest{ - Target: spec.Request.GRPC.Target, - Service: spec.Request.GRPC.Service, - Method: spec.Request.GRPC.Method, - Metadata: util.CloneStringSliceMap(spec.Request.GRPC.Metadata), - Message: util.CloneMap(spec.Request.GRPC.Message), - }, - }, - } -} diff --git a/execute/worker/summary_test.go b/execute/worker/summary_test.go deleted file mode 100644 index c2514e1..0000000 --- a/execute/worker/summary_test.go +++ /dev/null @@ -1,296 +0,0 @@ -package worker - -import ( - "net/http" - "testing" - - "github.com/e2engine/core/model" -) - -func TestNewSummaryHTTPBody(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{ - Method: http.MethodPost, - URL: "https://example.com/users", - Query: map[string][]string{ - "active": {"true"}, - }, - Headers: http.Header{ - "Content-Type": { - "text/plain", - }, - }, - Body: `{ - "id": 42 - }`, - }, - }, - } - - summary := newSummary(spec) - - if summary.Request == nil { - t.Fatal( - "expected non-nil request summary", - ) - } - - if summary.Request.HTTP == nil { - t.Fatal( - "expected HTTP request summary", - ) - } - - if summary.Request.GRPC != nil { - t.Fatal( - "expected nil gRPC request summary", - ) - } - - actual := summary.Request.HTTP - - if actual.Method != http.MethodPost { - t.Errorf( - "expected method %q, got %q", - http.MethodPost, - actual.Method, - ) - } - - if actual.URL != "https://example.com/users" { - t.Errorf( - "unexpected URL %q", - actual.URL, - ) - } - - if actual.Query["active"][0] != "true" { - t.Errorf( - "unexpected query %#v", - actual.Query, - ) - } - - if actual.Headers["Content-Type"][0] != - "text/plain" { - t.Errorf( - "unexpected headers %#v", - actual.Headers, - ) - } - - if actual.Body != `{ - "id": 42 - }` { - t.Errorf( - "unexpected body %q", - actual.Body, - ) - } - - if actual.BodyJSON != "" { - t.Errorf( - "expected empty JSON body, got %q", - actual.BodyJSON, - ) - } - - spec.Request.HTTP.Query["active"][0] = "false" - spec.Request.HTTP.Headers["Content-Type"][0] = - "application/json" - spec.Request.HTTP.Body = "changed" - - if actual.Query["active"][0] != "true" { - t.Error( - "expected request query to be cloned", - ) - } - - if actual.Headers["Content-Type"][0] != - "text/plain" { - t.Error( - "expected request headers to be cloned", - ) - } - - if actual.Body == "changed" { - t.Error( - "expected request body snapshot to be independent", - ) - } -} - -func TestNewSummaryHTTPBodyJSON(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{ - Method: http.MethodPost, - URL: "https://example.com/users", - BodyJSON: `{ - "id": 42, - "name": "Yaroslav" - }`, - }, - }, - } - - summary := newSummary(spec) - - if summary.Request == nil { - t.Fatal( - "expected non-nil request summary", - ) - } - - if summary.Request.HTTP == nil { - t.Fatal( - "expected HTTP request summary", - ) - } - - actual := summary.Request.HTTP - - if actual.Body != "" { - t.Errorf( - "expected empty body, got %q", - actual.Body, - ) - } - - if actual.BodyJSON != - `{"id":42,"name":"Yaroslav"}` { - t.Errorf( - "expected compact JSON body %q, got %q", - `{"id":42,"name":"Yaroslav"}`, - actual.BodyJSON, - ) - } - - spec.Request.HTTP.BodyJSON = `{"changed":true}` - - if actual.BodyJSON != - `{"id":42,"name":"Yaroslav"}` { - t.Error( - "expected request JSON body snapshot to be independent", - ) - } -} - -func TestNewSummaryGRPC(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - GRPC: &model.GRPCRequest{ - Target: "127.0.0.1:50051", - Service: "users.v1.UserService", - Method: "GetUser", - Metadata: map[string][]string{ - "x-request-id": { - "123", - }, - }, - Message: map[string]any{ - "id": "42", - }, - }, - }, - } - - summary := newSummary(spec) - - if summary.Request == nil { - t.Fatal( - "expected non-nil request summary", - ) - } - - if summary.Request.GRPC == nil { - t.Fatal( - "expected gRPC request summary", - ) - } - - if summary.Request.HTTP != nil { - t.Fatal( - "expected nil HTTP request summary", - ) - } - - actual := summary.Request.GRPC - - if actual.Target != "127.0.0.1:50051" { - t.Errorf( - "unexpected target %q", - actual.Target, - ) - } - - if actual.Service != - "users.v1.UserService" { - t.Errorf( - "unexpected service %q", - actual.Service, - ) - } - - if actual.Method != "GetUser" { - t.Errorf( - "unexpected method %q", - actual.Method, - ) - } - - if actual.Metadata["x-request-id"][0] != - "123" { - t.Errorf( - "unexpected metadata %#v", - actual.Metadata, - ) - } - - if actual.Message["id"] != "42" { - t.Errorf( - "unexpected message %#v", - actual.Message, - ) - } - - spec.Request.GRPC.Target = "changed:50051" - spec.Request.GRPC.Service = "changed.Service" - spec.Request.GRPC.Method = "Changed" - spec.Request.GRPC.Metadata["x-request-id"][0] = - "changed" - spec.Request.GRPC.Message["id"] = "changed" - - if actual.Target != "127.0.0.1:50051" { - t.Error( - "expected target snapshot to be independent", - ) - } - - if actual.Service != - "users.v1.UserService" { - t.Error( - "expected service snapshot to be independent", - ) - } - - if actual.Method != "GetUser" { - t.Error( - "expected method snapshot to be independent", - ) - } - - if actual.Metadata["x-request-id"][0] != - "123" { - t.Error( - "expected request metadata to be cloned", - ) - } - - if actual.Message["id"] != "42" { - t.Error( - "expected request message to be cloned", - ) - } -} diff --git a/execute/worker/worker.go b/execute/worker/worker.go index de9c4df..21816c4 100644 --- a/execute/worker/worker.go +++ b/execute/worker/worker.go @@ -8,11 +8,11 @@ import ( "github.com/ygrebnov/errorc" "github.com/e2engine/core/execute" - "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/execute/evaluate" grpcservice "github.com/e2engine/core/execute/runtime/service/grpc" + evaluatorPkg "github.com/e2engine/core/execute/worker/evaluator" grpcworker "github.com/e2engine/core/execute/worker/grpc" httpworker "github.com/e2engine/core/execute/worker/http" + reporterPkg "github.com/e2engine/core/execute/worker/reporter" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" @@ -23,51 +23,29 @@ type Worker struct { cfg *Config logger log.Logger - httpExecutor execute.ProtocolExecutor - grpcExecutor execute.ProtocolExecutor - evaluator *evaluate.Evaluator + client *http.Client + grpcMethodResolver grpcservice.MethodResolver } type Config struct { - TestTimeout time.Duration `json:"test_timeout" yaml:"test_timeout" default:"30s"` // TODO: add validation. + TestTimeout time.Duration `json:"test_timeout" yaml:"test_timeout" default:"30s" validate:"min(1s)"` + Reporter *reporterPkg.Config `json:"reporter" yaml:"reporter" validateElem:"omitempty"` } func NewWorker( cfg *Config, logger log.Logger, grpcMethodResolver grpcservice.MethodResolver, -) (*Worker, error) { +) *Worker { client := http.DefaultClient // TODO: make it configurable. - httpEvaluator := httpworker.NewEvaluator() - - grpcEvaluator := grpcworker.NewEvaluator( - grpcMethodResolver, - ) - - evaluator := evaluate.New( - httpEvaluator, - grpcEvaluator, - ) - - httpExecutor := httpworker.NewTestExecutor( - client, - httpEvaluator, - ) - - grpcExecutor := grpcworker.NewTestExecutor( - grpcMethodResolver, - grpcEvaluator, - ) - return &Worker{ cfg: cfg, logger: logger, - httpExecutor: httpExecutor, - grpcExecutor: grpcExecutor, - evaluator: evaluator, - }, nil + client: client, + grpcMethodResolver: grpcMethodResolver, + } } func (w *Worker) Execute( @@ -80,88 +58,98 @@ func (w *Worker) Execute( ) defer cancel() - executor, err := w.getExecutor(&job.Test.Spec) - if err != nil { - return nil, err + reporterCfg := w.cfg.Reporter + if reporterCfg == nil { + reporterCfg = &reporterPkg.Config{} } + reporter := reporterPkg.New( + reporterCfg, + &job.Test.Spec, + job.ExecutionID, + job.TestSuiteExecutionID, + ) - callStore := job.Runtime.Calls + // In some cases this validation can be the second validation of the test spec, + // but it is better than failing the test execution because of an invalid test spec. + if err := job.Test.Validate(runCtx); err != nil { + reporter.SetError(err) - result := &execute.TestExecutionResult{ - ExecutionID: job.ExecutionID, - TestSuiteExecutionID: job.TestSuiteExecutionID, - Summary: newSummary(&job.Test.Spec), + return reporter.Result(), nil } + httpEvaluator := httpworker.NewEvaluator(reporter) + + grpcEvaluator := grpcworker.NewEvaluator( + w.grpcMethodResolver, + reporter, + ) + + evaluator := evaluatorPkg.New( + httpEvaluator, + grpcEvaluator, + reporter, + ) + + var executor execute.ProtocolExecutor + switch { + case job.Test.Spec.Request.HTTP != nil: + executor = httpworker.NewTestExecutor( + w.client, + httpEvaluator, + reporter, + ) + + case job.Test.Spec.Request.GRPC != nil: + executor = grpcworker.NewTestExecutor( + w.grpcMethodResolver, + grpcEvaluator, + reporter, + ) + + default: + // Test validation guarantees a supported request protocol. + panic("invalid test spec: unsupported test protocol") + } + + callStore := job.Runtime.Calls + if errValidate := validateExpectedCalls( job.Environment.Spec.Services, job.Test.Spec.Expect.Calls, ); errValidate != nil { - setExecutionError(result, errValidate) + reporter.SetError(errValidate) - return result, nil + return reporter.Result(), nil } if err := executor.Execute( runCtx, &job, - result, ); err != nil { - summarizeCalls(result, callStore) - setExecutionError(result, err) + reporter.SummarizeCalls(callStore) + reporter.SetError(err) - return result, nil + return reporter.Result(), nil } - if err := w.evaluator.EvaluateCalls( + if err := evaluator.EvaluateCalls( runCtx, job.Environment.Spec.Services, job.Test.Spec.Expect.Calls, callStore, - result, + job.ExecutionID, ); err != nil { - summarizeCalls(result, callStore) - setExecutionError(result, err) + reporter.SummarizeCalls(callStore) + reporter.SetError(err) - return result, nil + return reporter.Result(), nil } - summarizeCalls(result, callStore) - - if len(result.Summary.Deviations) == 0 { - result.Status = model.ExecutionStatusPassed - } else { - result.Status = model.ExecutionStatusFailed - } + reporter.SummarizeCalls(callStore) - result.FinishedAt = time.Now().UTC() + reporter.Finalize() - return result, nil -} - -func summarizeCalls( - result *execute.TestExecutionResult, - callStore call.Reader, -) { - result.Summary.Calls = evaluate.SummarizeCalls( - result.ExecutionID, - callStore, - ) -} - -func (w *Worker) getExecutor( - spec *model.TestSpec, -) (execute.ProtocolExecutor, error) { - switch { - case spec.Request.HTTP != nil: - return w.httpExecutor, nil - - case spec.Request.GRPC != nil: - return w.grpcExecutor, nil - - default: - return nil, errors.ErrUnsupportedTestProtocol - } + return reporter.Result(), nil } func validateExpectedCalls( @@ -230,12 +218,3 @@ func validateExpectedCalls( return nil } - -func setExecutionError( - result *execute.TestExecutionResult, - err error, -) { - result.Status = model.ExecutionStatusError - result.FinishedAt = time.Now().UTC() - result.Summary.Error = err.Error() -} diff --git a/execute/worker/worker_test.go b/execute/worker/worker_test.go index ef5164e..245189a 100644 --- a/execute/worker/worker_test.go +++ b/execute/worker/worker_test.go @@ -4,62 +4,16 @@ import ( "context" nativeerrors "errors" "net/http" + "net/http/httptest" "testing" "time" - "go.uber.org/mock/gomock" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/execute/evaluate" - "github.com/e2engine/core/mock" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" ) -type testCallEvaluator struct { - matches bool - matchesErr error - deviation *model.TestExecutionDeviation -} - -func (e *testCallEvaluator) Matches( - _ context.Context, - _ *model.ServiceSpec, - _ call.Call, - _ model.ServiceExpectedCalls, -) (bool, error) { - return e.matches, e.matchesErr -} - -func (e *testCallEvaluator) Deviation( - _ *model.ServiceSpec, - _ call.Call, -) *model.TestExecutionDeviation { - return e.deviation -} - -func newHTTPTestJob( - callStore *call.Store, -) execute.TestJob { - return execute.TestJob{ - ExecutionID: "execution-1", - Runtime: execute.TestExecutionRuntime{ - Calls: callStore, - }, - Test: model.Test{ - Spec: model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{}, - }, - Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{}, - }, - }, - }, - } -} - func TestValidateExpectedCalls(t *testing.T) { tests := []struct { name string @@ -183,152 +137,30 @@ func TestValidateExpectedCalls(t *testing.T) { } } -func TestWorkerGetExecutor(t *testing.T) { - ctrl := gomock.NewController(t) - - httpExecutor := mock.NewMockProtocolExecutor(ctrl) - grpcExecutor := mock.NewMockProtocolExecutor(ctrl) - - w := &Worker{ - httpExecutor: httpExecutor, - grpcExecutor: grpcExecutor, - } - - tests := []struct { - name string - spec *model.TestSpec - expected execute.ProtocolExecutor - wantErr error - }{ - { - name: "HTTP", - spec: &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{}, - }, - }, - expected: httpExecutor, - }, - { - name: "gRPC", - spec: &model.TestSpec{ - Request: model.RequestSpec{ - GRPC: &model.GRPCRequest{}, - }, +func TestWorkerExecutePassed(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) }, - expected: grpcExecutor, - }, - { - name: "unsupported", - spec: &model.TestSpec{}, - wantErr: errors.ErrUnsupportedTestProtocol, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actual, err := w.getExecutor(tt.spec) - - if tt.wantErr != nil { - if !nativeerrors.Is( - err, - tt.wantErr, - ) { - t.Errorf( - "expected error %v, got %v", - tt.wantErr, - err, - ) - } - - return - } - - if err != nil { - t.Fatalf( - "getExecutor() error = %v", - err, - ) - } - - if actual != tt.expected { - t.Errorf( - "expected executor %T, got %T", - tt.expected, - actual, - ) - } - }) - } -} - -func TestSetExecutionError(t *testing.T) { - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } - - executionErr := nativeerrors.New( - "execution failed", + ), ) + defer server.Close() - before := time.Now().UTC() - - setExecutionError( - result, - executionErr, + worker := newHTTPTestWorker( + server.Client(), ) - after := time.Now().UTC() - - if result.Status != model.ExecutionStatusError { - t.Errorf( - "expected status %q, got %q", - model.ExecutionStatusError, - result.Status, - ) - } - - if result.Summary.Error != "execution failed" { - t.Errorf( - "expected error %q, got %q", - "execution failed", - result.Summary.Error, - ) - } - - if result.FinishedAt.Before(before) || - result.FinishedAt.After(after) { - t.Errorf( - "unexpected FinishedAt %v", - result.FinishedAt, - ) - } -} - -func TestWorkerExecuteExecutorError(t *testing.T) { - executionErr := nativeerrors.New( - - "execution failed", + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, ) - ctrl := gomock.NewController(t) - executor := mock.NewMockProtocolExecutor(ctrl) - executor.EXPECT(). - Execute( - gomock.Any(), - gomock.Any(), - gomock.Any(), - ). - Return(executionErr) - w := &Worker{ - cfg: &Config{ - TestTimeout: time.Second, - }, - httpExecutor: executor, - } - callStore := &call.Store{} - job := newHTTPTestJob(callStore) - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) @@ -343,18 +175,31 @@ func TestWorkerExecuteExecutorError(t *testing.T) { t.Fatal("expected result") } - if result.Status != model.ExecutionStatusError { + if result.Status != model.ExecutionStatusPassed { t.Errorf( "expected status %q, got %q", - model.ExecutionStatusError, + model.ExecutionStatusPassed, result.Status, ) } - if result.Summary.Error != executionErr.Error() { + if len(result.Summary.Deviations) != 0 { + t.Errorf( + "expected no deviations, got %+v", + result.Summary.Deviations, + ) + } + + if result.Summary.Calls != nil { + t.Errorf( + "expected no summarized calls, got %+v", + result.Summary.Calls, + ) + } + + if result.Summary.Error != "" { t.Errorf( - "expected summary error %q, got %q", - executionErr.Error(), + "expected no summary error, got %q", result.Summary.Error, ) } @@ -364,53 +209,30 @@ func TestWorkerExecuteExecutorError(t *testing.T) { } } -func TestWorkerExecutePassed(t *testing.T) { - ctrl := gomock.NewController(t) - executor := mock.NewMockProtocolExecutor(ctrl) - callStore := &call.Store{} - - executor.EXPECT(). - Execute( - gomock.Any(), - gomock.Any(), - gomock.Any(), - ). - DoAndReturn(func( - _ context.Context, - job *execute.TestJob, - _ *execute.TestExecutionResult, - ) error { - job.Runtime.Calls.Record(call.Call{ - TestExecutionID: job.ExecutionID, - ServiceID: "service-1", - HTTP: &call.HTTPCall{ - Request: call.HTTPRequest{ - Method: http.MethodGet, - Path: "/health", - }, - Response: call.HTTPResponse{ - StatusCode: http.StatusOK, - }, - }, - }) - - return nil - }) - - w := &Worker{ - cfg: &Config{ - TestTimeout: time.Second, - }, - httpExecutor: executor, - evaluator: evaluate.New( - &testCallEvaluator{}, - &testCallEvaluator{}, +func TestWorkerExecuteFailed(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusTeapot) + }, ), - } + ) + defer server.Close() + + worker := newHTTPTestWorker( + server.Client(), + ) - job := newHTTPTestJob(callStore) + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) @@ -421,133 +243,87 @@ func TestWorkerExecutePassed(t *testing.T) { ) } - if result.Status != model.ExecutionStatusPassed { + if result.Status != model.ExecutionStatusFailed { t.Errorf( "expected status %q, got %q", - model.ExecutionStatusPassed, + model.ExecutionStatusFailed, result.Status, ) } - if len(result.Summary.Calls) != 1 { + if len(result.Summary.Deviations) != 1 { t.Fatalf( - "expected 1 summarized call, got %d", - len(result.Summary.Calls), + "expected 1 deviation, got %d", + len(result.Summary.Deviations), ) } - actual := result.Summary.Calls[0] + deviation := result.Summary.Deviations[0] - if actual.ServiceID != "service-1" { + if deviation.Field != "status_code" { t.Errorf( - "expected service ID %q, got %q", - "service-1", - actual.ServiceID, + "expected field %q, got %q", + "status_code", + deviation.Field, ) } - if actual.Count != 1 { + if deviation.Expected != "200" { t.Errorf( - "expected count 1, got %d", - actual.Count, - ) - } - - if actual.HTTP == nil { - t.Fatal( - "expected HTTP call summary", + "expected expected value %q, got %q", + "200", + deviation.Expected, ) } - if actual.HTTP.Method != http.MethodGet { + if deviation.Actual != "418" { t.Errorf( - "expected method %q, got %q", - http.MethodGet, - actual.HTTP.Method, + "expected actual value %q, got %q", + "418", + deviation.Actual, ) } - if actual.HTTP.Path != "/health" { + if result.Summary.Error != "" { t.Errorf( - "expected path %q, got %q", - "/health", - actual.HTTP.Path, - ) - } - - if actual.HTTP.ResponseStatusCode == nil || - *actual.HTTP.ResponseStatusCode != - http.StatusOK { - t.Errorf( - "expected status code %d, got %#v", - http.StatusOK, - actual.HTTP.ResponseStatusCode, + "expected no summary error, got %q", + result.Summary.Error, ) } if result.FinishedAt.IsZero() { - t.Error( - "expected FinishedAt", - ) + t.Error("expected FinishedAt") } } -func TestWorkerExecuteFailed(t *testing.T) { - ctrl := gomock.NewController(t) - executor := mock.NewMockProtocolExecutor(ctrl) - - executor.EXPECT(). - Execute( - gomock.Any(), - gomock.Any(), - gomock.Any(), - ). - DoAndReturn(func( - _ context.Context, - job *execute.TestJob, - result *execute.TestExecutionResult, - ) error { - job.Runtime.Calls.Record(call.Call{ - TestExecutionID: job.ExecutionID, - ServiceID: "service-1", - HTTP: &call.HTTPCall{ - Request: call.HTTPRequest{ - Method: http.MethodGet, - Path: "/health", - }, - Response: call.HTTPResponse{ - StatusCode: http.StatusOK, - }, - }, - }) - - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "status_code", - Expected: "204", - Actual: "200", - }, - ) +func TestWorkerExecuteExecutorError(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), + ) - return nil - }) + client := server.Client() + url := server.URL - w := &Worker{ - cfg: &Config{ - TestTimeout: time.Second, - }, - httpExecutor: executor, - evaluator: evaluate.New( - &testCallEvaluator{}, - &testCallEvaluator{}, - ), - } + server.Close() + + worker := newHTTPTestWorker( + client, + ) - callStore := &call.Store{} - job := newHTTPTestJob(callStore) + job := newHTTPTestJob( + &call.Store{}, + url, + http.StatusOK, + ) - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) @@ -558,85 +334,84 @@ func TestWorkerExecuteFailed(t *testing.T) { ) } - if result.Status != model.ExecutionStatusFailed { + if result == nil { + t.Fatal("expected result") + } + + if result.Status != model.ExecutionStatusError { t.Errorf( "expected status %q, got %q", - model.ExecutionStatusFailed, + model.ExecutionStatusError, result.Status, ) } - if len(result.Summary.Deviations) != 1 { - t.Fatalf( - "expected 1 deviation, got %d", - len(result.Summary.Deviations), + if result.Summary.Error == "" { + t.Error("expected summary error") + } + + if result.Summary.Request == nil || + result.Summary.Request.HTTP == nil { + t.Fatal( + "expected attempted HTTP request in summary", ) } - if len(result.Summary.Calls) != 1 { - t.Fatalf( - "expected 1 summarized call, got %d", - len(result.Summary.Calls), + if result.Summary.Response != nil { + t.Errorf( + "expected no response summary, got %+v", + result.Summary.Response, ) } if result.FinishedAt.IsZero() { - t.Error( - "expected FinishedAt", - ) + t.Error("expected FinishedAt") } } func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { - ctrl := gomock.NewController(t) - executor := mock.NewMockProtocolExecutor(ctrl) + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer server.Close() - w := &Worker{ - cfg: &Config{ - TestTimeout: time.Second, - }, - httpExecutor: executor, - } + worker := newHTTPTestWorker( + server.Client(), + ) - callStore := &call.Store{} + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) - job := execute.TestJob{ - ExecutionID: "execution-1", - Runtime: execute.TestExecutionRuntime{ - Calls: callStore, - }, - Environment: model.Environment{ - Spec: model.EnvironmentSpec{ - Services: []model.ServiceSpec{ - { - ID: "service-1", - Kind: model.ServiceKindHTTP, - }, - }, + job.Environment.Spec.Services = + []model.ServiceSpec{ + { + ID: "service-1", + Kind: model.ServiceKindHTTP, }, - }, - Test: model.Test{ - Spec: model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{}, - }, - Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{}, - Calls: []model.ServiceExpectedCalls{ - { - ServiceID: "unknown", - HTTP: &model.HTTPRequestPattern{ - Method: http.MethodGet, - Path: "/health", - }, - }, - }, + } + + job.Test.Spec.Expect.Calls = + []model.ServiceExpectedCalls{ + { + ServiceID: "unknown", + HTTP: &model.HTTPRequestPattern{ + Method: http.MethodGet, + Path: "/health", }, }, - }, - } + } - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) @@ -656,8 +431,20 @@ func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { } if result.Summary.Error == "" { - t.Error( - "expected summary error", + t.Error("expected summary error") + } + + if result.Summary.Request != nil { + t.Errorf( + "expected no request summary, got %+v", + result.Summary.Request, + ) + } + + if result.Summary.Response != nil { + t.Errorf( + "expected no response summary, got %+v", + result.Summary.Response, ) } @@ -669,112 +456,43 @@ func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { } if result.FinishedAt.IsZero() { - t.Error( - "expected FinishedAt", - ) + t.Error("expected FinishedAt") } } -func TestWorkerExecuteEvaluateCallsError(t *testing.T) { - ctrl := gomock.NewController(t) - executor := mock.NewMockProtocolExecutor(ctrl) - - executor.EXPECT(). - Execute( - gomock.Any(), - gomock.Any(), - gomock.Any(), - ). - DoAndReturn(func( - _ context.Context, - job *execute.TestJob, - _ *execute.TestExecutionResult, - ) error { - job.Runtime.Calls.Record(call.Call{ - TestExecutionID: job.ExecutionID, - ServiceID: "service-1", - HTTP: &call.HTTPCall{ - Request: call.HTTPRequest{ - Method: http.MethodGet, - Path: "/health", - }, - Response: call.HTTPResponse{ - StatusCode: http.StatusOK, - }, - }, - }) - - return nil - }) - - evaluationErr := nativeerrors.New( - "evaluation failed", - ) - - w := &Worker{ +func TestWorkerExecuteInvalidTest(t *testing.T) { + worker := &Worker{ cfg: &Config{ TestTimeout: time.Second, }, - httpExecutor: executor, - evaluator: evaluate.New( - &testCallEvaluator{ - matchesErr: evaluationErr, - }, - &testCallEvaluator{}, - ), + client: http.DefaultClient, } - count := 1 - job := execute.TestJob{ ExecutionID: "execution-1", Runtime: execute.TestExecutionRuntime{ Calls: &call.Store{}, }, - Environment: model.Environment{ - Spec: model.EnvironmentSpec{ - Services: []model.ServiceSpec{ - { - ID: "service-1", - Kind: model.ServiceKindHTTP, - Mode: model.ServiceModeReal, - }, - }, - }, - }, Test: model.Test{ - Spec: model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequest{}, - }, - Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{}, - Calls: []model.ServiceExpectedCalls{ - { - ServiceID: "service-1", - Count: &count, - HTTP: &model.HTTPRequestPattern{ - Method: http.MethodGet, - Path: "/health", - }, - }, - }, - }, - }, + Spec: model.TestSpec{}, }, } - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) if err != nil { t.Fatalf( - "Execute() error = %v", + "expected nil error, got %v", err, ) } + if result == nil { + t.Fatal("expected result") + } + if result.Status != model.ExecutionStatusError { t.Errorf( "expected status %q, got %q", @@ -783,66 +501,107 @@ func TestWorkerExecuteEvaluateCallsError(t *testing.T) { ) } - if result.Summary.Error != - evaluationErr.Error() { - t.Errorf( - "expected summary error %q, got %q", - evaluationErr.Error(), - result.Summary.Error, - ) + if result.Summary.Error == "" { + t.Error("expected summary error") } - if len(result.Summary.Calls) != 1 { - t.Fatalf( - "expected 1 summarized call, got %d", - len(result.Summary.Calls), + if result.Summary.Request != nil { + t.Errorf( + "expected no request summary, got %+v", + result.Summary.Request, ) } if result.FinishedAt.IsZero() { - t.Error( - "expected FinishedAt", - ) + t.Error("expected FinishedAt") } } -func TestWorkerExecuteUnsupportedProtocol(t *testing.T) { - w := &Worker{ +func TestWorkerExecuteNilReporterConfig(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer server.Close() + + worker := &Worker{ cfg: &Config{ TestTimeout: time.Second, + Reporter: nil, }, + client: server.Client(), } - job := execute.TestJob{ - ExecutionID: "execution-1", - Runtime: execute.TestExecutionRuntime{ - Calls: &call.Store{}, - }, - Test: model.Test{ - Spec: model.TestSpec{}, - }, - } + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) - result, err := w.Execute( + result, err := worker.Execute( context.Background(), job, ) - - if !nativeerrors.Is( - err, - errors.ErrUnsupportedTestProtocol, - ) { + if err != nil { t.Fatalf( - "expected error %v, got %v", - errors.ErrUnsupportedTestProtocol, + "Execute() error = %v", err, ) } - if result != nil { + if result.Status != model.ExecutionStatusPassed { t.Errorf( - "expected nil result, got %+v", - result, + "expected status %q, got %q", + model.ExecutionStatusPassed, + result.Status, ) } } + +func newHTTPTestWorker( + client *http.Client, +) *Worker { + return &Worker{ + cfg: &Config{ + TestTimeout: time.Second, + }, + client: client, + } +} + +func newHTTPTestJob( + callStore *call.Store, + url string, + expectedStatus int, +) execute.TestJob { + return execute.TestJob{ + ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: callStore, + }, + Test: model.Test{ + Kind: model.ResourceKindTest, + Name: "test-1", + Version: "1.0.0", + Spec: model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{ + Method: http.MethodGet, + URL: url, + }, + }, + Expect: model.ExpectSpec{ + HTTP: &model.HTTPResponse{ + StatusCode: expectedStatus, + }, + }, + }, + }, + } +} diff --git a/go.sum b/go.sum index 02a5008..fa0381e 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/ygrebnov/model v0.7.5 h1:9i7Xz5vxYQXeJW06gTE9/In49f0lEDhulmsBKhsQxWw= github.com/ygrebnov/model v0.7.5/go.mod h1:qYRz8F/yrt01bPyANAlN0Oqi1fwpgvvl21hjW/NK6N0= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= +golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= @@ -34,6 +36,8 @@ golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= +golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= diff --git a/mock/Execute.go b/mock/Execute.go index 40b2906..d0d9e4f 100644 --- a/mock/Execute.go +++ b/mock/Execute.go @@ -42,15 +42,15 @@ func (m *MockProtocolExecutor) EXPECT() *MockProtocolExecutorMockRecorder { } // Execute mocks base method. -func (m *MockProtocolExecutor) Execute(ctx context.Context, job *execute.TestJob, result *execute.TestExecutionResult) error { +func (m *MockProtocolExecutor) Execute(ctx context.Context, job *execute.TestJob) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Execute", ctx, job, result) + ret := m.ctrl.Call(m, "Execute", ctx, job) ret0, _ := ret[0].(error) return ret0 } // Execute indicates an expected call of Execute. -func (mr *MockProtocolExecutorMockRecorder) Execute(ctx, job, result any) *gomock.Call { +func (mr *MockProtocolExecutorMockRecorder) Execute(ctx, job any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockProtocolExecutor)(nil).Execute), ctx, job, result) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockProtocolExecutor)(nil).Execute), ctx, job) } diff --git a/model/grpc.go b/model/grpc.go index e53d4ae..50975c3 100644 --- a/model/grpc.go +++ b/model/grpc.go @@ -12,11 +12,15 @@ type GRPCRequestPattern struct { Service string `json:"service" yaml:"service" validate:"min(1)"` Method string `json:"method" yaml:"method" validate:"min(1)"` Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + // Message is a pointer to a map to allow distinguishing between an empty message and no message. + // message: {} means "empty message", while no message field means "will be skipped in matching". + Message *map[string]any `json:"message,omitempty" yaml:"message,omitempty"` } type GRPCResponse struct { Status string `json:"status" yaml:"status" validate:"oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + // Message is a pointer to a map to allow distinguishing between an empty message and no message. + // message: {} means "empty message", while no message field means "will be skipped in matching". + Message *map[string]any `json:"message,omitempty" yaml:"message,omitempty"` } diff --git a/model/http.go b/model/http.go index 9cb97dc..c9a1fa4 100644 --- a/model/http.go +++ b/model/http.go @@ -1,6 +1,7 @@ package model import ( + "encoding/json" "net/url" "strings" @@ -52,12 +53,14 @@ func (h *HTTPRequest) Validate() error { // HTTPRequestPattern is used to match an HTTP request against a pattern. // Unlike HTTPRequest, it does not describe an outgoing request. type HTTPRequestPattern struct { - Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - Path string `json:"path" yaml:"path" validate:"min(1)"` - Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty"` - BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` + Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` + Path string `json:"path" yaml:"path" validate:"min(1)"` + Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` + Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` + // Body is pointer to string to distinguish between empty body and no body. + // body: "" means empty body, while no body field means "will be skipped in matching". + Body *string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON *string `json:"body_json,omitempty" yaml:"body_json,omitempty"` } func (h *HTTPRequestPattern) Validate() error { @@ -69,28 +72,42 @@ func (h *HTTPRequestPattern) Validate() error { return errorc.New("invalid HTTP request path") } - if h.Body != "" && h.BodyJSON != "" { + if h.Body != nil && h.BodyJSON != nil { return errorc.New( "HTTP request pattern cannot have both body and body_json set", ) } + if h.BodyJSON != nil && !json.Valid([]byte(*h.BodyJSON)) { + return errorc.New( + "HTTP response body_json is not valid JSON", + ) + } + return nil } type HTTPResponse struct { StatusCode int `json:"status_code" yaml:"status_code" validate:"min(100),max(599)"` Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - Body string `json:"body,omitempty" yaml:"body,omitempty"` - BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` + // Body is pointer to string to distinguish between empty body and no body. + // body: "" means empty body, while no body field means "will be skipped in matching". + Body *string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON *string `json:"body_json,omitempty" yaml:"body_json,omitempty"` } func (h *HTTPResponse) Validate() error { - if h.Body != "" && h.BodyJSON != "" { + if h.Body != nil && h.BodyJSON != nil { return errorc.New( "HTTP response cannot have both body and body_json set", ) } + if h.BodyJSON != nil && !json.Valid([]byte(*h.BodyJSON)) { + return errorc.New( + "HTTP response body_json is not valid JSON", + ) + } + return nil } diff --git a/pkg/keys/keys.go b/pkg/keys/keys.go index 79c1cc7..b32a134 100644 --- a/pkg/keys/keys.go +++ b/pkg/keys/keys.go @@ -51,8 +51,11 @@ var ( GRPCFieldType = grpc("field.type") GRPCServiceTargetAddress = grpc("service.target.address") - FieldBody = keys.New("body") - FieldBodyJSON = keys.New("body.json") + FieldBody = keys.New("body") + FieldBodyJSON = keys.New("body_json") + FieldStatusCode = keys.New("status_code") + FieldStatus = keys.New("status") + FieldMessage = keys.New("message") ExecutionID = execution("id") ExecutionStatus = execution("status") diff --git a/tests/testexecution_test.go b/tests/testexecution_test.go index 3049267..dcf2965 100644 --- a/tests/testexecution_test.go +++ b/tests/testexecution_test.go @@ -431,6 +431,7 @@ func modelTestExecution() *model.TestExecution { } func modelTestExecutionSummary() *model.TestExecutionSummary { + bodyJSON := `{"status":"ok"}` return &model.TestExecutionSummary{ Request: &model.TestExecutionRequestSummary{ HTTP: &model.HTTPRequest{ @@ -441,7 +442,7 @@ func modelTestExecutionSummary() *model.TestExecutionSummary { Response: &model.TestExecutionResponseSummary{ HTTP: &model.HTTPResponse{ StatusCode: 200, - BodyJSON: `{"status":"ok"}`, + BodyJSON: &bodyJSON, }, }, } From af19e6e453b597753d38c61ed2a69d1d09d413a8 Mon Sep 17 00:00:00 2001 From: Yaroslav Grebnov Date: Tue, 13 Oct 2026 16:03:40 +0200 Subject: [PATCH 3/4] Use matchers --- .golangci.yml | 1 + api/service_run_test.go | 2 +- execute/match/match.go | 135 ++++ execute/match/match_test.go | 588 +++++++++++++++ execute/runtime/router/grpc/router.go | 8 +- execute/runtime/router/grpc/router_test.go | 12 +- execute/runtime/router/http/request.go | 12 +- execute/runtime/router/http/request_test.go | 4 +- execute/runtime/router/http/router_test.go | 4 +- execute/runtime/service/grpc/mock.go | 134 +--- execute/runtime/service/grpc/mock_test.go | 649 ++++++++++------- execute/runtime/service/http/mock.go | 112 ++- execute/runtime/service/http/mock_test.go | 262 ++++++- execute/worker/grpc/evaluate.go | 98 ++- execute/worker/grpc/evaluate_test.go | 749 ++++++++++---------- execute/worker/grpc/executor_test.go | 16 +- execute/worker/grpc/mock_reporter_test.go | 2 +- execute/worker/grpc/reporter.go | 2 +- execute/worker/http/evaluate.go | 146 ++-- execute/worker/http/evaluate_test.go | 542 ++++++++++---- execute/worker/http/executor_test.go | 12 +- execute/worker/http/mock_reporter_test.go | 6 +- execute/worker/http/reporter.go | 6 +- execute/worker/reporter/reporter.go | 115 ++- execute/worker/reporter/reporter_test.go | 718 ++++++++++++------- execute/worker/worker_test.go | 2 +- internal/util/clone.go | 13 + internal/util/json.go | 8 +- internal/util/json_test.go | 2 +- model/grpc.go | 32 +- model/http.go | 85 ++- model/matcher/doc.go | 10 + model/matcher/grpc_message.go | 154 ++++ model/matcher/grpc_message_test.go | 487 +++++++++++++ model/matcher/string.go | 200 ++++++ model/matcher/string_test.go | 517 ++++++++++++++ model/test.go | 4 +- model/testexecution.go | 11 + model/validation.go | 27 +- pkg/errors/errors.go | 2 + pkg/keys/keys.go | 2 + tests/test_test.go | 2 +- tests/testexecution_test.go | 2 +- 43 files changed, 4451 insertions(+), 1444 deletions(-) create mode 100644 execute/match/match.go create mode 100644 execute/match/match_test.go create mode 100644 model/matcher/doc.go create mode 100644 model/matcher/grpc_message.go create mode 100644 model/matcher/grpc_message_test.go create mode 100644 model/matcher/string.go create mode 100644 model/matcher/string_test.go diff --git a/.golangci.yml b/.golangci.yml index 76ed832..bf6b1d3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -128,6 +128,7 @@ linters: - gosec - govet - lll + - noctx - revive - staticcheck - unparam diff --git a/api/service_run_test.go b/api/service_run_test.go index f7c5c69..58619a6 100644 --- a/api/service_run_test.go +++ b/api/service_run_test.go @@ -720,7 +720,7 @@ func validTestSpec() model.TestSpec { }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{ + HTTP: &model.HTTPResponsePattern{ StatusCode: 200, }, }, diff --git a/execute/match/match.go b/execute/match/match.go new file mode 100644 index 0000000..3017042 --- /dev/null +++ b/execute/match/match.go @@ -0,0 +1,135 @@ +package match + +import ( + "encoding/json" + + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/types/dynamicpb" + + "github.com/e2engine/core/internal/util" + "github.com/e2engine/core/model/matcher" +) + +func IsStringMatched( + actual []byte, + expected *matcher.String, +) bool { + if expected == nil { + panic("string matcher must not be nil") + } + + switch expected.Operator { + case matcher.StringMatchOperatorExists: + return true + + case matcher.StringMatchOperatorNonEmpty: + return len(actual) > 0 + + case matcher.StringMatchOperatorEquals: + return string(actual) == expected.Value + + default: + // Validation guarantees a supported operator. + panic("invalid string matcher operator") + } +} + +func IsStringSliceMatched( + actual []string, + exists bool, + expected []matcher.String, +) bool { + if len(expected) == 0 { + panic("string matchers must not be empty") + } + + if !exists { + return false + } + + switch expected[0].Operator { + case matcher.StringMatchOperatorExists: + return true + + case matcher.StringMatchOperatorNonEmpty: + for _, value := range actual { + if value != "" { + return true + } + } + return false + + case matcher.StringMatchOperatorEquals: + expectedValues := make([]string, len(expected)) + for i := range expected { + expectedValues[i] = expected[i].Value + } + + return util.IsStringSlicesEqual(actual, expectedValues) + + default: + panic("invalid string matcher operator") + } +} + +func IsJSONMatched( + actual []byte, + expected *matcher.String, +) (bool, error) { + if expected == nil { + panic("JSON matcher must not be nil") + } + + switch expected.Operator { + case matcher.StringMatchOperatorExists: + return json.Valid(actual), nil + + case matcher.StringMatchOperatorNonEmpty: + return len(actual) > 0 && json.Valid(actual), nil + + case matcher.StringMatchOperatorEquals: + return util.IsJSONEqual( + []byte(expected.Value), + actual, + ) + + default: + // Validation guarantees a supported operator. + panic("invalid string matcher operator") + } +} + +func IsGRPCMessageMatched( + actual proto.Message, + expected *matcher.GRPCMessage, +) (bool, error) { + if expected == nil { + panic("gRPC message matcher must not be nil") + } + switch expected.Operator { + case matcher.GRPCMessageMatchOperatorNonEmpty: + nonempty := false + actual.ProtoReflect().Range( + func(_ protoreflect.FieldDescriptor, _ protoreflect.Value) bool { + nonempty = true + return false + }, + ) + return nonempty, nil + case matcher.GRPCMessageMatchOperatorEquals: + expectedMessage := dynamicpb.NewMessage( + actual.ProtoReflect().Descriptor(), + ) + if err := protojson.Unmarshal( + []byte(expected.Value), + expectedMessage, + ); err != nil { + return false, err + } + return proto.Equal(actual, expectedMessage), nil + default: + panic("invalid gRPC message matcher operator") + } +} diff --git a/execute/match/match_test.go b/execute/match/match_test.go new file mode 100644 index 0000000..2ae2371 --- /dev/null +++ b/execute/match/match_test.go @@ -0,0 +1,588 @@ +package match + +import ( + "testing" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/descriptorpb" + + "github.com/e2engine/core/model/matcher" +) + +func TestIsStringMatched(t *testing.T) { + tests := []struct { + name string + actual string + expected matcher.String + want bool + }{ + { + name: "equals", + actual: "hello", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "hello", + }, + want: true, + }, + { + name: "equals mismatch", + actual: "world", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "hello", + }, + }, + { + name: "equals empty", + actual: "", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "", + }, + want: true, + }, + { + name: "equals empty mismatch", + actual: "hello", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "", + }, + }, + { + name: "equals preserves whitespace", + actual: "hello\n", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "hello", + }, + }, + { + name: "exists with content", + actual: "hello", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + want: true, + }, + { + name: "exists with empty content", + actual: "", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + want: true, + }, + { + name: "nonempty with content", + actual: "hello", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty with empty content", + actual: "", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + }, + { + name: "nonempty with whitespace", + actual: " ", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := IsStringMatched( + []byte(tt.actual), + &tt.expected, + ) + + if got != tt.want { + t.Errorf( + "IsStringMatched() = %v, want %v", + got, + tt.want, + ) + } + }) + } +} + +func TestIsStringSliceMatched(t *testing.T) { + eq := func(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } + } + + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + nonempty := matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + } + + tests := []struct { + name string + actual []string + exists bool + expected []matcher.String + want bool + }{ + { + name: "exists with value", + actual: []string{"hello"}, + exists: true, + expected: []matcher.String{exists}, + want: true, + }, + { + name: "exists with empty value", + actual: []string{""}, + exists: true, + expected: []matcher.String{exists}, + want: true, + }, + { + name: "exists with empty slice", + actual: []string{}, + exists: true, + expected: []matcher.String{exists}, + want: true, + }, + { + name: "exists with absent key", + exists: false, + expected: []matcher.String{exists}, + }, + { + name: "nonempty with value", + actual: []string{"hello"}, + exists: true, + expected: []matcher.String{nonempty}, + want: true, + }, + { + name: "nonempty with empty value", + actual: []string{""}, + exists: true, + expected: []matcher.String{nonempty}, + }, + { + name: "nonempty with mixed values", + actual: []string{"", "hello"}, + exists: true, + expected: []matcher.String{nonempty}, + want: true, + }, + { + name: "nonempty with empty slice", + actual: []string{}, + exists: true, + expected: []matcher.String{nonempty}, + }, + { + name: "nonempty with absent key", + actual: []string{"hello"}, + exists: false, + expected: []matcher.String{nonempty}, + }, + { + name: "equals single value", + actual: []string{"hello"}, + exists: true, + expected: []matcher.String{eq("hello")}, + want: true, + }, + { + name: "equals empty value", + actual: []string{""}, + exists: true, + expected: []matcher.String{eq("")}, + want: true, + }, + { + name: "equals mismatch", + actual: []string{"world"}, + exists: true, + expected: []matcher.String{eq("hello")}, + }, + { + name: "equals absent key", + exists: false, + expected: []matcher.String{eq("")}, + }, + { + name: "equals multiple values", + actual: []string{"hello", "world"}, + exists: true, + expected: []matcher.String{eq("hello"), eq("world")}, + want: true, + }, + { + name: "equals multiple values different order", + actual: []string{"world", "hello"}, + exists: true, + expected: []matcher.String{eq("hello"), eq("world")}, + want: true, + }, + { + name: "equals missing value", + actual: []string{"hello"}, + exists: true, + expected: []matcher.String{eq("hello"), eq("world")}, + }, + { + name: "equals extra value", + actual: []string{"hello", "world"}, + exists: true, + expected: []matcher.String{eq("hello")}, + }, + { + name: "equals duplicate values", + actual: []string{"hello", "hello"}, + exists: true, + expected: []matcher.String{eq("hello"), eq("hello")}, + want: true, + }, + { + name: "equals duplicate count mismatch", + actual: []string{"hello", "world"}, + exists: true, + expected: []matcher.String{eq("hello"), eq("hello")}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := IsStringSliceMatched( + tt.actual, + tt.exists, + tt.expected, + ) + + if got != tt.want { + t.Errorf( + "IsStringSliceMatched() = %v, want %v", + got, + tt.want, + ) + } + }) + } +} + +func TestIsJSONMatched(t *testing.T) { + tests := []struct { + name string + actual string + expected matcher.String + want bool + }{ + { + name: "equals objects", + actual: `{"name":"John","age":30}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{"name":"John","age":30}`, + }, + want: true, + }, + { + name: "equals different key order", + actual: `{"age":30,"name":"John"}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{"name":"John","age":30}`, + }, + want: true, + }, + { + name: "equals different whitespace", + actual: "{\n\"name\": \"John\"\n}\n", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{"name":"John"}`, + }, + want: true, + }, + { + name: "equals mismatch", + actual: `{"name":"Jane"}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{"name":"John"}`, + }, + }, + { + name: "equals arrays", + actual: `[1,2,3]`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `[1,2,3]`, + }, + want: true, + }, + { + name: "equals array order mismatch", + actual: `[3,2,1]`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `[1,2,3]`, + }, + }, + { + name: "equals JSON string", + actual: `"hello"`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `"hello"`, + }, + want: true, + }, + { + name: "equals empty object", + actual: `{}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: `{}`, + }, + want: true, + }, + { + name: "exists with object", + actual: `{}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + want: true, + }, + { + name: "exists with null", + actual: `null`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + want: true, + }, + { + name: "exists with empty body", + actual: "", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + }, + { + name: "exists with invalid JSON", + actual: `hello`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + }, + { + name: "nonempty with object", + actual: `{"name":"John"}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty with empty object", + actual: `{}`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty with null", + actual: `null`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty with empty JSON string", + actual: `""`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty with empty body", + actual: "", + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + }, + { + name: "nonempty with invalid JSON", + actual: `hello`, + expected: matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := IsJSONMatched( + []byte(tt.actual), + &tt.expected, + ) + if err != nil { + t.Fatalf("IsJSONMatched() error = %v", err) + } + + if got != tt.want { + t.Errorf( + "IsJSONMatched() = %v, want %v", + got, + tt.want, + ) + } + }) + } +} + +func TestIsGRPCMessageMatched(t *testing.T) { + // FileDescriptorProto is used as a concrete protobuf message. + // Its Name field has explicit presence, allowing us to test + // populated and empty protobuf messages. + tests := []struct { + name string + actual proto.Message + expected matcher.GRPCMessage + want bool + wantErr bool + }{ + { + name: "equals populated message", + actual: &descriptorpb.FileDescriptorProto{ + Name: proto.String("account.proto"), + }, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{"name":"account.proto"}`, + }, + want: true, + }, + { + name: "equals empty message", + actual: &descriptorpb.FileDescriptorProto{}, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + want: true, + }, + { + name: "equals mismatch", + actual: &descriptorpb.FileDescriptorProto{ + Name: proto.String("account.proto"), + }, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{"name":"payment.proto"}`, + }, + }, + { + name: "equals populated vs empty", + actual: &descriptorpb.FileDescriptorProto{ + Name: proto.String("account.proto"), + }, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + }, + { + name: "equals invalid JSON", + actual: &descriptorpb.FileDescriptorProto{}, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{`, + }, + wantErr: true, + }, + { + name: "equals unknown field", + actual: &descriptorpb.FileDescriptorProto{}, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: `{"unknownField":"value"}`, + }, + wantErr: true, + }, + { + name: "nonempty populated message", + actual: &descriptorpb.FileDescriptorProto{ + Name: proto.String("account.proto"), + }, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + want: true, + }, + { + name: "nonempty empty message", + actual: &descriptorpb.FileDescriptorProto{}, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + }, + { + name: "nonempty explicitly set empty string", + actual: &descriptorpb.FileDescriptorProto{ + Name: proto.String(""), + }, + expected: matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := IsGRPCMessageMatched( + tt.actual, + &tt.expected, + ) + + if (err != nil) != tt.wantErr { + t.Fatalf( + "IsGRPCMessageMatched() error = %v, wantErr %v", + err, + tt.wantErr, + ) + } + + if err != nil { + return + } + + if got != tt.want { + t.Errorf( + "IsGRPCMessageMatched() = %v, want %v", + got, + tt.want, + ) + } + }) + } +} diff --git a/execute/runtime/router/grpc/router.go b/execute/runtime/router/grpc/router.go index e78e385..897d135 100644 --- a/execute/runtime/router/grpc/router.go +++ b/execute/runtime/router/grpc/router.go @@ -276,13 +276,9 @@ func (r *Router) newHandler( stream.Context(), ) - outgoingMetadata := e2enginegrpc.WithoutTestExecutionID( - incomingMetadata, - ) - outgoingContext := metadata.NewOutgoingContext( ctx, - outgoingMetadata, + incomingMetadata.Copy(), ) var response rawMessage @@ -363,8 +359,6 @@ func splitFullMethod(fullMethod string) (service, method string) { } func cloneMetadata(source metadata.MD) map[string][]string { - source = e2enginegrpc.WithoutTestExecutionID(source) - result := make( map[string][]string, len(source), diff --git a/execute/runtime/router/grpc/router_test.go b/execute/runtime/router/grpc/router_test.go index 982aa3e..be66547 100644 --- a/execute/runtime/router/grpc/router_test.go +++ b/execute/runtime/router/grpc/router_test.go @@ -105,9 +105,9 @@ func TestCloneMetadata(t *testing.T) { ) } - if len(got) != 1 { + if len(got) != 2 { t.Fatalf( - "expected execution ID metadata to be excluded, got %#v", + "expected execution ID metadata to be present, got %#v", got, ) } @@ -310,9 +310,9 @@ func TestRouter(t *testing.T) { ) } - if id := e2enginegrpc.TestExecutionID(upstreamMetadata); id != "" { + if id := e2enginegrpc.TestExecutionID(upstreamMetadata); id == "" { t.Fatal( - "expected execution ID not to be forwarded upstream", + "expected execution ID to be forwarded upstream", ) } @@ -374,9 +374,9 @@ func TestRouter(t *testing.T) { ) } - if id := e2enginegrpc.TestExecutionID(got.GRPC.Request.Metadata); id != "" { + if id := e2enginegrpc.TestExecutionID(got.GRPC.Request.Metadata); id == "" { t.Fatalf( - "expected execution ID to be excluded from recorded metadata, got %q", + "expected execution ID to be present in recorded metadata, got %q", id, ) } diff --git a/execute/runtime/router/http/request.go b/execute/runtime/router/http/request.go index 123fb37..fa102c2 100644 --- a/execute/runtime/router/http/request.go +++ b/execute/runtime/router/http/request.go @@ -5,19 +5,11 @@ import ( "io" "net/http" - e2enginehttp "github.com/e2engine/instrumentation-go/http" - "github.com/e2engine/core/execute/call" "github.com/e2engine/core/internal/util" ) func captureRequest(req *http.Request) (call.HTTPRequest, error) { - header := e2enginehttp.WithoutTestExecutionID( - req.Header, - ) - - query := util.CloneQuery(req.URL.Query()) - rawBody, err := io.ReadAll(req.Body) if err != nil { return call.HTTPRequest{}, err @@ -32,8 +24,8 @@ func captureRequest(req *http.Request) (call.HTTPRequest, error) { return call.HTTPRequest{ Method: req.Method, Path: req.URL.Path, - Query: query, - Headers: header, + Query: req.URL.Query().Clone(), + Headers: req.Header.Clone(), Body: util.CloneBytes(rawBody), }, nil } diff --git a/execute/runtime/router/http/request_test.go b/execute/runtime/router/http/request_test.go index 5afc91c..9171fe0 100644 --- a/execute/runtime/router/http/request_test.go +++ b/execute/runtime/router/http/request_test.go @@ -59,9 +59,9 @@ func TestCaptureRequest(t *testing.T) { ) } - if id := e2enginehttp.TestExecutionID(got.Headers); id != "" { + if id := e2enginehttp.TestExecutionID(got.Headers); id == "" { t.Errorf( - "expected execution ID header to be removed, got %q", + "expected execution ID header to be present, got %q", id, ) } diff --git a/execute/runtime/router/http/router_test.go b/execute/runtime/router/http/router_test.go index 31ca64f..aaa7893 100644 --- a/execute/runtime/router/http/router_test.go +++ b/execute/runtime/router/http/router_test.go @@ -187,9 +187,9 @@ func TestRouter(t *testing.T) { ) } - if id := e2enginehttp.TestExecutionID(got.HTTP.Request.Headers); id != "" { + if id := e2enginehttp.TestExecutionID(got.HTTP.Request.Headers); id == "" { t.Errorf( - "expected execution ID header to be removed, got %q", + "expected execution ID header to be present, got %q", id, ) } diff --git a/execute/runtime/service/grpc/mock.go b/execute/runtime/service/grpc/mock.go index 0ca6f42..510ad2d 100644 --- a/execute/runtime/service/grpc/mock.go +++ b/execute/runtime/service/grpc/mock.go @@ -17,7 +17,9 @@ import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/dynamicpb" + "github.com/e2engine/core/execute/match" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" "github.com/e2engine/core/pkg/log" @@ -46,8 +48,8 @@ type MethodResolver interface { type Fixture struct { service string method string - metadata map[string][]string - message *map[string]any + metadata map[string][]matcher.String + message *matcher.GRPCMessage status codes.Code responseMetadata map[string][]string @@ -209,7 +211,6 @@ func (s *MockGRPCService) handle( fullMethod, request, incomingMetadata, - method, ) if err != nil { return status.Error( @@ -290,13 +291,9 @@ func (s *MockGRPCService) match( fullMethod string, actual proto.Message, actualMetadata metadata.MD, - method protoreflect.MethodDescriptor, ) (*Fixture, error) { service, methodName, _ := strings.Cut( - strings.TrimPrefix( - fullMethod, - "/", - ), + strings.TrimPrefix(fullMethod, "/"), "/", ) @@ -319,32 +316,20 @@ func (s *MockGRPCService) match( return fixture, nil } - expected, err := buildMessage( - method.Input(), - *fixture.message, + matched, err := match.IsGRPCMessageMatched( + actual, + fixture.message, ) if err != nil { return nil, errorc.With( errors.ErrCannotBuildGRPCMessage, - errorc.String( - keys.GRPCMethod, - fullMethod, - ), - errorc.String( - keys.Operation, - "build fixture request message", - ), - errorc.Error( - keys.Cause, - err, - ), + errorc.String(keys.GRPCMethod, fullMethod), + errorc.String(keys.Operation, "match fixture request message"), + errorc.Error(keys.Cause, err), ) } - if proto.Equal( - expected, - actual, - ) { + if matched { return fixture, nil } } @@ -353,33 +338,19 @@ func (s *MockGRPCService) match( } func areMetadataEqual( - expected map[string][]string, + expected map[string][]matcher.String, actual metadata.MD, ) bool { for key, expectedValues := range expected { - actualValues := actual.Get(key) + actualValues, exists := actual[strings.ToLower(key)] - if len(expectedValues) != - len(actualValues) { + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { return false } - - expectedCounts := make( - map[string]int, - len(expectedValues), - ) - - for _, value := range expectedValues { - expectedCounts[value]++ - } - - for _, value := range actualValues { - if expectedCounts[value] == 0 { - return false - } - - expectedCounts[value]-- - } } return true @@ -444,11 +415,6 @@ func compileFixtures( for i := range specs { spec := &specs[i] - if spec.When.GRPC == nil || - spec.Then.GRPC == nil { - continue - } - fixture := Fixture{ service: spec.When.GRPC.Service, method: spec.When.GRPC.Method, @@ -465,7 +431,7 @@ func compileFixtures( } if spec.Then.GRPC.Message != nil { - fixture.response = *spec.Then.GRPC.Message + fixture.response = spec.Then.GRPC.Message } fixtures = append( @@ -478,59 +444,11 @@ func compileFixtures( } func grpcCode(value string) codes.Code { - switch strings.ToLower(value) { - case "", "ok": - return codes.OK - - case "cancelled": - return codes.Canceled - - case "unknown": - return codes.Unknown - - case "invalid_argument": - return codes.InvalidArgument - - case "deadline_exceeded": - return codes.DeadlineExceeded - - case "not_found": - return codes.NotFound - - case "already_exists": - return codes.AlreadyExists - - case "permission_denied": - return codes.PermissionDenied - - case "resource_exhausted": - return codes.ResourceExhausted - - case "failed_precondition": - return codes.FailedPrecondition - - case "aborted": - return codes.Aborted - - case "out_of_range": - return codes.OutOfRange - - case "unimplemented": - return codes.Unimplemented - - case "internal": - return codes.Internal - - case "unavailable": - return codes.Unavailable - - case "data_loss": - return codes.DataLoss - - case "unauthenticated": - return codes.Unauthenticated - - default: - return codes.Unknown + for code := codes.OK; code <= codes.Unauthenticated; code++ { + if code.String() == value { + return code + } } + + panic("invalid gRPC status") } diff --git a/execute/runtime/service/grpc/mock_test.go b/execute/runtime/service/grpc/mock_test.go index 5cb33cc..a3ea89b 100644 --- a/execute/runtime/service/grpc/mock_test.go +++ b/execute/runtime/service/grpc/mock_test.go @@ -2,6 +2,7 @@ package grpc import ( "context" + "encoding/json" nativeerrors "errors" "testing" "time" @@ -17,6 +18,7 @@ import ( "google.golang.org/protobuf/types/dynamicpb" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/log" ) @@ -69,86 +71,23 @@ func TestGRPCCode(t *testing.T) { value string expected codes.Code }{ - { - value: "", - expected: codes.OK, - }, - { - value: "ok", - expected: codes.OK, - }, - { - value: "OK", - expected: codes.OK, - }, - { - value: "cancelled", - expected: codes.Canceled, - }, - { - value: "unknown", - expected: codes.Unknown, - }, - { - value: "invalid_argument", - expected: codes.InvalidArgument, - }, - { - value: "deadline_exceeded", - expected: codes.DeadlineExceeded, - }, - { - value: "not_found", - expected: codes.NotFound, - }, - { - value: "already_exists", - expected: codes.AlreadyExists, - }, - { - value: "permission_denied", - expected: codes.PermissionDenied, - }, - { - value: "resource_exhausted", - expected: codes.ResourceExhausted, - }, - { - value: "failed_precondition", - expected: codes.FailedPrecondition, - }, - { - value: "aborted", - expected: codes.Aborted, - }, - { - value: "out_of_range", - expected: codes.OutOfRange, - }, - { - value: "unimplemented", - expected: codes.Unimplemented, - }, - { - value: "internal", - expected: codes.Internal, - }, - { - value: "unavailable", - expected: codes.Unavailable, - }, - { - value: "data_loss", - expected: codes.DataLoss, - }, - { - value: "unauthenticated", - expected: codes.Unauthenticated, - }, - { - value: "invalid", - expected: codes.Unknown, - }, + {"OK", codes.OK}, + {"Canceled", codes.Canceled}, + {"Unknown", codes.Unknown}, + {"InvalidArgument", codes.InvalidArgument}, + {"DeadlineExceeded", codes.DeadlineExceeded}, + {"NotFound", codes.NotFound}, + {"AlreadyExists", codes.AlreadyExists}, + {"PermissionDenied", codes.PermissionDenied}, + {"ResourceExhausted", codes.ResourceExhausted}, + {"FailedPrecondition", codes.FailedPrecondition}, + {"Aborted", codes.Aborted}, + {"OutOfRange", codes.OutOfRange}, + {"Unimplemented", codes.Unimplemented}, + {"Internal", codes.Internal}, + {"Unavailable", codes.Unavailable}, + {"DataLoss", codes.DataLoss}, + {"Unauthenticated", codes.Unauthenticated}, } for _, tt := range tests { @@ -167,54 +106,77 @@ func TestGRPCCode(t *testing.T) { } } -func TestCompileFixtures(t *testing.T) { - m1 := map[string]any{"id": "42"} - m2 := map[string]any{"message": "not found"} +func TestGRPCCodeInvalid(t *testing.T) { + tests := []struct { + name string + value string + }{ + { + name: "empty status", + value: "", + }, + { + name: "lowercase status", + value: "ok", + }, + { + name: "snake case status", + value: "not_found", + }, + { + name: "unknown status", + value: "invalid", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + defer func() { + if recover() == nil { + t.Errorf( + "expected grpcCode(%q) to panic", + tt.value, + ) + } + }() + + grpcCode(tt.value) + }) + } +} + +func TestCompileFixtures(t *testing.T) { specs := []model.FixtureSpec{ { When: model.FixtureWhen{ GRPC: &model.GRPCRequestPattern{ Service: "users.v1.UserService", Method: "GetUser", - Metadata: map[string][]string{ + Metadata: map[string][]matcher.String{ "x-request-id": { - "one", - "two", + grpcStringEquals("one"), + grpcStringEquals("two"), }, }, - Message: &m1, + Message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), }, }, Then: model.FixtureThen{ GRPC: &model.GRPCResponse{ - Status: "not_found", + Status: "NotFound", Metadata: map[string][]string{ "x-response-id": { "three", "four", }, }, - Message: &m2, - }, - }, - }, - { - When: model.FixtureWhen{}, - Then: model.FixtureThen{ - GRPC: &model.GRPCResponse{ - Status: "ok", - }, - }, - }, - { - When: model.FixtureWhen{ - GRPC: &model.GRPCRequestPattern{ - Service: "users.v1.UserService", - Method: "Ignored", + Message: map[string]any{ + "message": "not found", + }, }, }, - Then: model.FixtureThen{}, }, } @@ -253,11 +215,22 @@ func TestCompileFixtures(t *testing.T) { ) } - if (*fixture.message)["id"] != "42" { + if fixture.message == nil { + t.Fatal("expected request message matcher") + } + + if fixture.message.Operator != matcher.GRPCMessageMatchOperatorEquals { t.Errorf( - "expected request id %q, got %v", - "42", - (*fixture.message)["id"], + "expected equals operator, got %q", + fixture.message.Operator, + ) + } + + if fixture.message.Value != `{"id":"42"}` { + t.Errorf( + "expected request message %q, got %q", + `{"id":"42"}`, + fixture.message.Value, ) } @@ -270,9 +243,10 @@ func TestCompileFixtures(t *testing.T) { } requestMetadata := fixture.metadata["x-request-id"] + if len(requestMetadata) != 2 || - requestMetadata[0] != "one" || - requestMetadata[1] != "two" { + requestMetadata[0].Value != "one" || + requestMetadata[1].Value != "two" { t.Errorf( "expected request metadata [one two], got %v", requestMetadata, @@ -280,6 +254,7 @@ func TestCompileFixtures(t *testing.T) { } responseMetadata := fixture.responseMetadata["x-response-id"] + if len(responseMetadata) != 2 || responseMetadata[0] != "three" || responseMetadata[1] != "four" { @@ -339,9 +314,7 @@ func TestBuildMessage(t *testing.T) { } if actual := message.Get(active).Bool(); !actual { - t.Error( - "expected active to be true", - ) + t.Error("expected active to be true") } }, }, @@ -359,9 +332,7 @@ func TestBuildMessage(t *testing.T) { ) { t.Helper() - tags := descriptor.Fields().ByName( - "tags", - ) + tags := descriptor.Fields().ByName("tags") list := message.Get(tags).List() if list.Len() != 2 { @@ -403,10 +374,7 @@ func TestBuildMessage(t *testing.T) { ) } - tt.expected( - t, - message, - ) + tt.expected(t, message) }) } } @@ -439,13 +407,12 @@ func TestBuildMessageInvalidField(t *testing.T) { func TestAreMetadataEqual(t *testing.T) { tests := []struct { name string - expected map[string][]string + expected map[string][]matcher.String actual metadata.MD want bool }{ { - name: "nil expected", - expected: nil, + name: "nil expected", actual: metadata.MD{ "additional": {"value"}, }, @@ -453,8 +420,8 @@ func TestAreMetadataEqual(t *testing.T) { }, { name: "matching value", - expected: map[string][]string{ - "x-request-id": {"one"}, + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, actual: metadata.MD{ "x-request-id": {"one"}, @@ -463,10 +430,10 @@ func TestAreMetadataEqual(t *testing.T) { }, { name: "matching repeated values", - expected: map[string][]string{ + expected: map[string][]matcher.String{ "x-request-id": { - "one", - "two", + grpcStringEquals("one"), + grpcStringEquals("two"), }, }, actual: metadata.MD{ @@ -479,8 +446,8 @@ func TestAreMetadataEqual(t *testing.T) { }, { name: "additional actual key ignored", - expected: map[string][]string{ - "x-request-id": {"one"}, + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, actual: metadata.MD{ "x-request-id": {"one"}, @@ -490,26 +457,24 @@ func TestAreMetadataEqual(t *testing.T) { }, { name: "missing expected key", - expected: map[string][]string{ - "x-request-id": {"one"}, + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, actual: metadata.MD{}, - want: false, }, { name: "different value", - expected: map[string][]string{ - "x-request-id": {"one"}, + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, actual: metadata.MD{ "x-request-id": {"two"}, }, - want: false, }, { name: "additional value for expected key", - expected: map[string][]string{ - "x-request-id": {"one"}, + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, actual: metadata.MD{ "x-request-id": { @@ -517,7 +482,84 @@ func TestAreMetadataEqual(t *testing.T) { "two", }, }, - want: false, + }, + { + name: "metadata key case insensitive", + expected: map[string][]matcher.String{ + "X-Request-Id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + }, + want: true, + }, + { + name: "exists with value", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorExists}, + }, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + }, + want: true, + }, + { + name: "exists with empty value", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorExists}, + }, + }, + actual: metadata.MD{ + "x-request-id": {""}, + }, + want: true, + }, + { + name: "exists with missing key", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorExists}, + }, + }, + actual: metadata.MD{}, + }, + { + name: "nonempty with value", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorNonEmpty}, + }, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + }, + want: true, + }, + { + name: "nonempty with empty value", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorNonEmpty}, + }, + }, + actual: metadata.MD{ + "x-request-id": {""}, + }, + }, + { + name: "nonempty with multiple values", + expected: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorNonEmpty}, + }, + }, + actual: metadata.MD{ + "x-request-id": {"", "one"}, + }, + want: true, }, } @@ -549,10 +591,7 @@ func TestMockGRPCServiceMatch(t *testing.T) { }, ) if err != nil { - t.Fatalf( - "cannot build request: %v", - err, - ) + t.Fatalf("cannot build request: %v", err) } tests := []struct { @@ -569,9 +608,9 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, expected: true, @@ -580,24 +619,21 @@ func TestMockGRPCServiceMatch(t *testing.T) { name: "metadata", fullMethod: "/users.v1.UserService/GetUser", metadata: metadata.MD{ - "x-request-id": { - "two", - "one", - }, + "x-request-id": {"two", "one"}, }, fixtures: []Fixture{ { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ + metadata: map[string][]matcher.String{ "x-request-id": { - "one", - "two", + grpcStringEquals("one"), + grpcStringEquals("two"), }, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, expected: true, @@ -613,12 +649,12 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ - "x-request-id": {"one"}, + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, expected: true, @@ -630,12 +666,11 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.AdminService", method: "GetUser", - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, - expected: false, }, { name: "different method", @@ -644,12 +679,11 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "CreateUser", - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, - expected: false, }, { name: "different message", @@ -658,12 +692,11 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "43", - }, + }), }, }, - expected: false, }, { name: "missing metadata", @@ -672,15 +705,14 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ - "x-request-id": {"one"}, + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, - expected: false, }, { name: "different metadata", @@ -692,38 +724,106 @@ func TestMockGRPCServiceMatch(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ - "x-request-id": {"one"}, + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, - expected: false, }, { name: "additional value for specified metadata key", fullMethod: "/users.v1.UserService/GetUser", metadata: metadata.MD{ - "x-request-id": { - "one", - "two", - }, + "x-request-id": {"one", "two"}, }, fixtures: []Fixture{ { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ - "x-request-id": {"one"}, + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", + }), + }, + }, + }, + { + name: "message expectation omitted", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + }, + }, + expected: true, + }, + { + name: "message nonempty matches", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + message: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + }, + }, + expected: true, + }, + { + name: "explicit empty message does not match", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + message: grpcMessageMatcher(map[string]any{}), + }, + }, + }, + { + name: "metadata exists with empty value", + fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": {""}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorExists}, + }, + }, + }, + }, + expected: true, + }, + { + name: "metadata nonempty rejects empty value", + fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": {""}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": { + {Operator: matcher.StringMatchOperatorNonEmpty}, + }, }, }, }, - expected: false, }, } @@ -737,7 +837,6 @@ func TestMockGRPCServiceMatch(t *testing.T) { tt.fullMethod, request, tt.metadata, - method, ) if err != nil { t.Fatalf( @@ -760,6 +859,65 @@ func TestMockGRPCServiceMatch(t *testing.T) { } } +func TestMockGRPCServiceMatchEmptyMessage(t *testing.T) { + method := testMethodDescriptor(t) + + request := dynamicpb.NewMessage(method.Input()) + + tests := []struct { + name string + message *matcher.GRPCMessage + expected bool + }{ + { + name: "equals empty", + message: grpcMessageMatcher(map[string]any{}), + expected: true, + }, + { + name: "nonempty rejects empty message", + message: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + }, + { + name: "no message expectation", + expected: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + service := &MockGRPCService{ + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + message: tt.message, + }, + }, + } + + fixture, err := service.match( + "/users.v1.UserService/GetUser", + request, + nil, + ) + if err != nil { + t.Fatalf("match() error = %v", err) + } + + if (fixture != nil) != tt.expected { + t.Errorf( + "expected match %v, got %v", + tt.expected, + fixture != nil, + ) + } + }) + } +} + func TestMockGRPCServiceMatchInvalidFixtureMessage( t *testing.T, ) { @@ -783,9 +941,9 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( { service: "users.v1.UserService", method: "GetUser", - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "unknown": "value", - }, + }), }, }, } @@ -794,7 +952,6 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( "/users.v1.UserService/GetUser", request, nil, - method, ) if err == nil { t.Fatal("expected error") @@ -836,15 +993,11 @@ func TestMockGRPCServiceMountCanceledContext( } if service.listener != nil { - t.Error( - "expected listener not to be created", - ) + t.Error("expected listener not to be created") } if service.server != nil { - t.Error( - "expected server not to be created", - ) + t.Error("expected server not to be created") } } @@ -896,13 +1049,9 @@ func testMethodDescriptor( ) } - method := service.Methods().ByName( - "GetUser", - ) + method := service.Methods().ByName("GetUser") if method == nil { - t.Fatal( - "GetUser method not found", - ) + t.Fatal("GetUser method not found") } return method @@ -917,15 +1066,11 @@ func testMessageDescriptor( } func testFileDescriptorSet() *descriptorpb.FileDescriptorSet { - optional := - descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL - repeated := - descriptorpb.FieldDescriptorProto_LABEL_REPEATED + optional := descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL + repeated := descriptorpb.FieldDescriptorProto_LABEL_REPEATED - stringType := - descriptorpb.FieldDescriptorProto_TYPE_STRING - boolType := - descriptorpb.FieldDescriptorProto_TYPE_BOOL + stringType := descriptorpb.FieldDescriptorProto_TYPE_STRING + boolType := descriptorpb.FieldDescriptorProto_TYPE_BOOL return &descriptorpb.FileDescriptorSet{ File: []*descriptorpb.FileDescriptorProto{ @@ -935,30 +1080,22 @@ func testFileDescriptorSet() *descriptorpb.FileDescriptorSet { Syntax: proto.String("proto3"), MessageType: []*descriptorpb.DescriptorProto{ { - Name: proto.String( - "GetUserRequest", - ), + Name: proto.String("GetUserRequest"), Field: []*descriptorpb.FieldDescriptorProto{ { - Name: proto.String( - "id", - ), + Name: proto.String("id"), Number: proto.Int32(1), Label: &optional, Type: &stringType, }, { - Name: proto.String( - "active", - ), + Name: proto.String("active"), Number: proto.Int32(2), Label: &optional, Type: &boolType, }, { - Name: proto.String( - "tags", - ), + Name: proto.String("tags"), Number: proto.Int32(3), Label: &repeated, Type: &stringType, @@ -966,14 +1103,10 @@ func testFileDescriptorSet() *descriptorpb.FileDescriptorSet { }, }, { - Name: proto.String( - "GetUserResponse", - ), + Name: proto.String("GetUserResponse"), Field: []*descriptorpb.FieldDescriptorProto{ { - Name: proto.String( - "name", - ), + Name: proto.String("name"), Number: proto.Int32(1), Label: &optional, Type: &stringType, @@ -983,14 +1116,10 @@ func testFileDescriptorSet() *descriptorpb.FileDescriptorSet { }, Service: []*descriptorpb.ServiceDescriptorProto{ { - Name: proto.String( - "UserService", - ), + Name: proto.String("UserService"), Method: []*descriptorpb.MethodDescriptorProto{ { - Name: proto.String( - "GetUser", - ), + Name: proto.String("GetUser"), InputType: proto.String( ".users.v1.GetUserRequest", ), @@ -1039,15 +1168,15 @@ func TestMockGRPCServiceHandle(t *testing.T) { { service: "users.v1.UserService", method: "GetUser", - metadata: map[string][]string{ + metadata: map[string][]matcher.String{ "x-request-id": { - "one", - "two", + grpcStringEquals("one"), + grpcStringEquals("two"), }, }, - message: &map[string]any{ + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), status: codes.OK, responseMetadata: map[string][]string{ "x-response-id": { @@ -1149,9 +1278,8 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } - responseMetadata := header.Get( - "x-response-id", - ) + responseMetadata := header.Get("x-response-id") + if len(responseMetadata) != 2 { t.Fatalf( "expected 2 response metadata values, got %v", @@ -1159,10 +1287,7 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } - if !containsString( - responseMetadata, - "three", - ) { + if !containsString(responseMetadata, "three") { t.Errorf( "expected response metadata to contain %q, got %v", "three", @@ -1170,10 +1295,7 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } - if !containsString( - responseMetadata, - "four", - ) { + if !containsString(responseMetadata, "four") { t.Errorf( "expected response metadata to contain %q, got %v", "four", @@ -1186,9 +1308,7 @@ func TestMockGRPCServiceHandle(t *testing.T) { ByName("name") if name == nil { - t.Fatal( - "name field not found", - ) + t.Fatal("name field not found") } if actual := response.Get(name).String(); actual != "Yaroslav" { @@ -1212,3 +1332,24 @@ func containsString( return false } + +func grpcMessageMatcher( + value map[string]any, +) *matcher.GRPCMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) + } + + return &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: string(data), + } +} + +func grpcStringEquals(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } +} diff --git a/execute/runtime/service/http/mock.go b/execute/runtime/service/http/mock.go index a2b94f7..745966f 100644 --- a/execute/runtime/service/http/mock.go +++ b/execute/runtime/service/http/mock.go @@ -8,11 +8,13 @@ import ( "net" "net/http" "net/url" - "reflect" "github.com/ygrebnov/errorc" + "github.com/e2engine/core/execute/match" + "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" "github.com/e2engine/core/pkg/log" @@ -144,22 +146,20 @@ func (s *MockHTTPService) match( for i := range s.fixtures { fixture := &s.fixtures[i] - if fixture.method == r.Method && - fixture.path == r.URL.Path && - areQueryParamsEqual( - fixture.query, - r.URL.Query(), - ) && - areHeadersEqual( - fixture.headers, - r.Header, - ) && - isBodyEqual( + if fixture.method == r.Method && fixture.path == r.URL.Path && + areQueryParamsEqual(fixture.query, r.URL.Query()) && + areHeadersEqual(fixture.headers, r.Header) { + equalBody, errBodyEqual := isBodyEqual( fixture.body, fixture.bodyJSON, body, - ) { - return fixture, nil + ) + if errBodyEqual != nil { + return nil, errBodyEqual + } + if equalBody { + return fixture, nil + } } } @@ -167,57 +167,42 @@ func (s *MockHTTPService) match( } func isBodyEqual( - expectedBody *string, - expectedBodyJSON *string, + expectedBody *matcher.String, + expectedBodyJSON *matcher.String, actual []byte, -) bool { +) (bool, error) { if expectedBody != nil { - return *expectedBody == string(actual) + return match.IsStringMatched(actual, expectedBody), nil } if expectedBodyJSON != nil { - var expectedValue any - if err := json.Unmarshal( - []byte(*expectedBodyJSON), - &expectedValue, - ); err != nil { - return false + if !json.Valid(actual) { + return false, nil } - var actualValue any - if err := json.Unmarshal( - actual, - &actualValue, - ); err != nil { - return false - } - - return reflect.DeepEqual( - expectedValue, - actualValue, - ) + return match.IsJSONMatched(actual, expectedBodyJSON) } - return true + return true, nil } -func areHeadersEqual(expected, actual http.Header) bool { +func areHeadersEqual( + expected map[string][]matcher.String, + actual http.Header, +) bool { for key, expectedValues := range expected { - actualValues := actual.Values(key) - if len(expectedValues) != len(actualValues) { + canonicalKey := http.CanonicalHeaderKey(key) + actualValues, exists := actual[canonicalKey] + + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { return false } - expectedCounts := make(map[string]int, len(expectedValues)) - for _, value := range expectedValues { - expectedCounts[value]++ - } - for _, value := range actualValues { - if expectedCounts[value] == 0 { - return false - } - expectedCounts[value]-- - } } + return true } @@ -225,7 +210,14 @@ func areQueryParamsEqual( expected, actual url.Values, ) bool { - return reflect.DeepEqual(expected, actual) + for key, expectedValues := range expected { + actualValues, exists := actual[key] + if !exists || !util.IsStringSlicesEqual(actualValues, expectedValues) { + return false + } + } + + return true } func (s *MockHTTPService) respond( @@ -276,10 +268,10 @@ type Fixture struct { method string path string query url.Values - headers map[string][]string + headers map[string][]matcher.String - body *string - bodyJSON *string + body *matcher.String + bodyJSON *matcher.String status int responseHeaders map[string][]string @@ -310,7 +302,9 @@ func compileFixtures( status: spec.Then.HTTP.StatusCode, - responseHeaders: spec.Then.HTTP.Headers, + responseHeaders: spec.Then.HTTP.Headers, + responseBody: spec.Then.HTTP.Body, + responseBodyJSON: spec.Then.HTTP.BodyJSON, } if spec.When.HTTP.Body != nil { @@ -321,14 +315,6 @@ func compileFixtures( fixture.bodyJSON = spec.When.HTTP.BodyJSON } - if spec.Then.HTTP.Body != nil { - fixture.responseBody = *spec.Then.HTTP.Body - } - - if spec.Then.HTTP.BodyJSON != nil { - fixture.responseBodyJSON = *spec.Then.HTTP.BodyJSON - } - fixtures[i] = fixture } diff --git a/execute/runtime/service/http/mock_test.go b/execute/runtime/service/http/mock_test.go index 701540f..9ab3f08 100644 --- a/execute/runtime/service/http/mock_test.go +++ b/execute/runtime/service/http/mock_test.go @@ -9,6 +9,7 @@ import ( httpservice "github.com/e2engine/core/execute/runtime/service/http" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/keys" "github.com/e2engine/core/pkg/log" ) @@ -219,8 +220,16 @@ func TestMockHTTPServiceMatch(t *testing.T) { fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"one", "two"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "one", + }, { + Operator: matcher.StringMatchOperatorEquals, + Value: "two", + }, + }, }, nil, nil, @@ -239,8 +248,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"expected"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, }, nil, nil, @@ -260,8 +274,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"expected"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, }, nil, nil, @@ -324,7 +343,7 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss: true, }, { - name: "unexpected query is miss", + name: "additional query parameters ignored", fixture: newHTTPFixture( "GET", "/users", @@ -336,16 +355,20 @@ func TestMockHTTPServiceMatch(t *testing.T) { method: "GET", path: "/users?page=1", - expectedStatus: http.StatusNotImplemented, - expectedMiss: true, + expectedStatus: http.StatusOK, }, { name: "missing header is miss", fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"expected"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, }, nil, nil, @@ -362,8 +385,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"expected"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, }, nil, nil, @@ -383,8 +411,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { fixture: newHTTPFixture( "GET", "/users", - map[string][]string{ - "X-Test": {"expected"}, + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, }, nil, nil, @@ -479,6 +512,190 @@ func TestMockHTTPServiceMatch(t *testing.T) { method: "POST", path: "/text", + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, + { + name: "header exists with empty value", + fixture: newHTTPFixture( + "GET", + "/users", + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + nil, + nil, + http.StatusOK, + ), + method: "GET", + path: "/users", + headers: map[string][]string{ + "X-Test": {""}, + }, + + expectedStatus: http.StatusOK, + }, + { + name: "header exists but is missing", + fixture: newHTTPFixture( + "GET", + "/users", + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + nil, + nil, + http.StatusOK, + ), + method: "GET", + path: "/users", + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, + { + name: "header nonempty matches", + fixture: newHTTPFixture( + "GET", + "/users", + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorNonEmpty, + }, + }, + }, + nil, + nil, + http.StatusOK, + ), + method: "GET", + path: "/users", + headers: map[string][]string{ + "X-Test": {"value"}, + }, + + expectedStatus: http.StatusOK, + }, + { + name: "header nonempty rejects empty value", + fixture: newHTTPFixture( + "GET", + "/users", + map[string][]matcher.String{ + "X-Test": { + { + Operator: matcher.StringMatchOperatorNonEmpty, + }, + }, + }, + nil, + nil, + http.StatusOK, + ), + method: "GET", + path: "/users", + headers: map[string][]string{ + "X-Test": {""}, + }, + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, + { + name: "body nonempty matches", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + nil, + http.StatusOK, + ), + method: "POST", + path: "/users", + body: "hello", + + expectedStatus: http.StatusOK, + }, + { + name: "body nonempty rejects empty body", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + nil, + http.StatusOK, + ), + method: "POST", + path: "/users", + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, + { + name: "body exists matches empty body", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + &matcher.String{ + Operator: matcher.StringMatchOperatorExists, + }, + nil, + http.StatusOK, + ), + method: "POST", + path: "/users", + + expectedStatus: http.StatusOK, + }, + { + name: "JSON nonempty matches empty object", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + nil, + &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + http.StatusOK, + ), + method: "POST", + path: "/users", + body: `{}`, + + expectedStatus: http.StatusOK, + }, + { + name: "JSON nonempty rejects empty body", + fixture: newHTTPFixture( + "POST", + "/users", + nil, + nil, + &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + http.StatusOK, + ), + method: "POST", + path: "/users", + expectedStatus: http.StatusNotImplemented, expectedMiss: true, }, @@ -582,7 +799,7 @@ func TestMockHTTPServiceResponse(t *testing.T) { Headers: map[string][]string{ "X-Test": {"one", "two"}, }, - Body: ptr("plain text response"), + Body: "plain text response", }, expectedBody: "plain text response", }, @@ -593,7 +810,7 @@ func TestMockHTTPServiceResponse(t *testing.T) { Headers: map[string][]string{ "X-Test": {"one", "two"}, }, - BodyJSON: ptr("{\n \"id\": 42\n}"), + BodyJSON: "{\n \"id\": 42\n}", }, expectedBody: "{\n \"id\": 42\n}", }, @@ -733,9 +950,9 @@ func newTestMockHTTPService( func newHTTPFixture( method, path string, - headers map[string][]string, + headers map[string][]matcher.String, body, - bodyJSON *string, + bodyJSON *matcher.String, status int, ) model.FixtureSpec { return model.FixtureSpec{ @@ -756,6 +973,9 @@ func newHTTPFixture( } } -func ptr(s string) *string { - return &s +func ptr(s string) *matcher.String { + return &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: s, + } } diff --git a/execute/worker/grpc/evaluate.go b/execute/worker/grpc/evaluate.go index c2f0ff0..9f8256e 100644 --- a/execute/worker/grpc/evaluate.go +++ b/execute/worker/grpc/evaluate.go @@ -3,6 +3,7 @@ package grpc import ( "context" "encoding/json" + "slices" "strings" "github.com/ygrebnov/errorc" @@ -14,6 +15,7 @@ import ( "google.golang.org/protobuf/types/dynamicpb" "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/execute/match" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/execute/worker/evaluator" "github.com/e2engine/core/internal/util" @@ -48,7 +50,7 @@ func (e *Evaluator) EvaluateResponse( response *dynamicpb.Message, header metadata.MD, trailer metadata.MD, - expect *model.GRPCResponse, + expect *model.GRPCResponsePattern, ) error { if err := e.evaluateStatus(callErr, expect); err != nil { return err @@ -63,7 +65,7 @@ func (e *Evaluator) EvaluateResponse( func (e *Evaluator) evaluateStatus( callErr error, - expect *model.GRPCResponse, + expect *model.GRPCResponsePattern, ) error { actualStatus := status.Code(callErr) e.reporter.AddGRPCResponseStatus(actualStatus.String()) @@ -89,24 +91,35 @@ func (e *Evaluator) evaluateStatus( func (e *Evaluator) evaluateMetadata( header metadata.MD, trailer metadata.MD, - expect *model.GRPCResponse, + expect *model.GRPCResponsePattern, ) error { actualMetadata := mergeMetadata(header, trailer) e.reporter.AddGRPCResponseMetadata(actualMetadata) for key, expectedValues := range expect.Metadata { - actualValues, ok := actualMetadata[key] - if ok && util.IsStringSlicesEqual( + actualValues, exists := actualMetadata[strings.ToLower(key)] + + if match.IsStringSliceMatched( actualValues, + exists, expectedValues, ) { continue } + sortedActual := slices.Clone(actualValues) + slices.Sort(sortedActual) + + expectedStrings := make([]string, len(expectedValues)) + for i, v := range expectedValues { + expectedStrings[i] = v.String() + } + slices.Sort(expectedStrings) + e.reporter.AddDeviation(&model.TestExecutionDeviation{ Field: "metadata." + key, - Expected: strings.Join(expectedValues, ","), - Actual: strings.Join(actualValues, ","), + Expected: strings.Join(expectedStrings, ","), + Actual: strings.Join(sortedActual, ","), }) } @@ -115,7 +128,7 @@ func (e *Evaluator) evaluateMetadata( func (e *Evaluator) evaluateMessage( response *dynamicpb.Message, - expect *model.GRPCResponse, + expect *model.GRPCResponsePattern, ) error { responseMap, err := messageToMap(response) if err != nil { @@ -125,47 +138,30 @@ func (e *Evaluator) evaluateMessage( e.reporter.AddGRPCResponseMessage(responseMap) if expect.Message == nil { - // An omitted message means that the response message is not evaluated. - // An explicitly empty message (`message: {}`) expects an empty protobuf message. return nil } - expectedMessage := dynamicpb.NewMessage( - response.Descriptor(), - ) - - if errUnmarshal := unmarshalMap( - *expect.Message, - expectedMessage, - ); errUnmarshal != nil { - return errUnmarshal - } - - if proto.Equal( - expectedMessage, + matched, err := match.IsGRPCMessageMatched( response, - ) { - return nil - } - - expectedJSON, err := json.Marshal( - *expect.Message, + expect.Message, ) if err != nil { return err } - actualJSON, err := protojson.Marshal( - response, - ) + if matched { + return nil + } + + actualJSON, err := protojson.Marshal(response) if err != nil { return err } - e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ Field: string(keys.FieldMessage), - Expected: string(expectedJSON), - Actual: string(actualJSON), + Expected: expect.Message, + Actual: actualJSON, }) return nil @@ -192,14 +188,13 @@ func (e *Evaluator) Matches( } for key, expectedValues := range expected.GRPC.Metadata { - actualValues, ok := - actual.GRPC.Request.Metadata[key] - - if !ok || - !util.IsStringSlicesEqual( - actualValues, - expectedValues, - ) { + actualValues, exists := actual.GRPC.Request.Metadata[strings.ToLower(key)] + + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { return false, nil } } @@ -231,21 +226,10 @@ func (e *Evaluator) Matches( ) } - expectedMessage := dynamicpb.NewMessage( - method.Input(), - ) - - if err := unmarshalMap( - *expected.GRPC.Message, - expectedMessage, - ); err != nil { - return false, err - } - - return proto.Equal( + return match.IsGRPCMessageMatched( actualMessage, - expectedMessage, - ), nil + expected.GRPC.Message, + ) } func (e *Evaluator) Deviation( diff --git a/execute/worker/grpc/evaluate_test.go b/execute/worker/grpc/evaluate_test.go index 950141e..83c1536 100644 --- a/execute/worker/grpc/evaluate_test.go +++ b/execute/worker/grpc/evaluate_test.go @@ -2,6 +2,7 @@ package grpc import ( "context" + "encoding/json" "errors" "reflect" "testing" @@ -20,6 +21,7 @@ import ( "github.com/e2engine/core/execute/call" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/keys" ) @@ -31,65 +33,48 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { header metadata.MD trailer metadata.MD message map[string]any - expect model.GRPCResponse - - expectedStatus string + expect model.GRPCResponsePattern + expectedStatus string expectedDeviations []model.TestExecutionDeviation - expectedPayloadDeviations []model.TestExecutionDeviation + expectedPayloadDeviations []model.PayloadDeviation }{ { name: "matching response", header: metadata.MD{ - "x-header": { - "header-value", - }, - "x-ignored": { - "ignored-value", - }, + "x-header": {"header-value"}, + "x-ignored": {"ignored-value"}, }, trailer: metadata.MD{ - "x-trailer": { - "trailer-value", - }, + "x-trailer": {"trailer-value"}, }, message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", - Metadata: map[string][]string{ - "x-header": { - "header-value", - }, - "x-trailer": { - "trailer-value", - }, + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("header-value")}, + "x-trailer": {grpcStringEquals("trailer-value")}, }, - Message: mapPtr( - map[string]any{ - "name": "actual", - }, - ), + Message: mapPtr(map[string]any{ + "name": "actual", + }), }, expectedStatus: "OK", }, { name: "unrelated metadata", header: metadata.MD{ - "x-header": { - "header-value", - }, + "x-header": {"header-value"}, }, trailer: metadata.MD{ - "x-trailer": { - "trailer-value", - }, + "x-trailer": {"trailer-value"}, }, message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", }, expectedStatus: "OK", @@ -97,19 +82,15 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { { name: "metadata mismatch", header: metadata.MD{ - "x-header": { - "actual", - }, + "x-header": {"actual"}, }, message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", - Metadata: map[string][]string{ - "x-header": { - "expected", - }, + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("expected")}, }, }, expectedStatus: "OK", @@ -126,12 +107,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", - Metadata: map[string][]string{ - "x-header": { - "expected", - }, + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("expected")}, }, }, expectedStatus: "OK", @@ -143,6 +122,80 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { }, }, }, + { + name: "metadata exists", + header: metadata.MD{ + "x-header": {""}, + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringOperator(matcher.StringMatchOperatorExists)}, + }, + }, + expectedStatus: "OK", + }, + { + name: "metadata exists but missing", + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringOperator(matcher.StringMatchOperatorExists)}, + }, + }, + expectedStatus: "OK", + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "exists", + }, + }, + }, + { + name: "metadata nonempty", + header: metadata.MD{ + "x-header": {"value"}, + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringOperator(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + expectedStatus: "OK", + }, + { + name: "metadata nonempty rejects empty value", + header: metadata.MD{ + "x-header": {""}, + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringOperator(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + expectedStatus: "OK", + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "nonempty", + }, + }, + }, + { + name: "metadata key is case insensitive", + header: metadata.MD{ + "x-header": {"value"}, + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "X-Header": {grpcStringEquals("value")}, + }, + }, + expectedStatus: "OK", + }, { name: "status mismatch", callErr: status.Error( @@ -152,7 +205,7 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", }, expectedStatus: "NotFound", @@ -164,25 +217,36 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { }, }, }, + { + name: "expected error status", + callErr: status.Error( + codes.NotFound, + "not found", + ), + expect: model.GRPCResponsePattern{ + Status: "NotFound", + }, + expectedStatus: "NotFound", + }, { name: "message mismatch", message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", - Message: mapPtr( - map[string]any{ - "name": "expected", - }, - ), + Message: mapPtr(map[string]any{ + "name": "expected", + }), }, expectedStatus: "OK", - expectedPayloadDeviations: []model.TestExecutionDeviation{ + expectedPayloadDeviations: []model.PayloadDeviation{ { - Field: "message", - Expected: `{"name":"expected"}`, - Actual: `{"name":"actual"}`, + Field: "message", + Expected: mapPtr(map[string]any{ + "name": "expected", + }), + Actual: []byte(`{"name":"actual"}`), }, }, }, @@ -191,7 +255,7 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ Status: "OK", }, expectedStatus: "OK", @@ -199,13 +263,44 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { { name: "explicit empty message", message: map[string]any{}, - expect: model.GRPCResponse{ + expect: model.GRPCResponsePattern{ + Status: "OK", + Message: mapPtr(map[string]any{}), + }, + expectedStatus: "OK", + }, + { + name: "nonempty message matches", + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Message: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + }, + expectedStatus: "OK", + }, + { + name: "nonempty message rejects empty message", + message: map[string]any{}, + expect: model.GRPCResponsePattern{ Status: "OK", - Message: mapPtr( - map[string]any{}, - ), + Message: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, }, expectedStatus: "OK", + expectedPayloadDeviations: []model.PayloadDeviation{ + { + Field: "message", + Expected: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + Actual: []byte(`{}`), + }, + }, }, } @@ -215,22 +310,14 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { reporter := NewMockexecutionReporter(ctrl) evaluator := newTestEvaluator(reporter) - - response := newTestMessage( - t, - tt.message, - ) + response := newTestMessage(t, tt.message) reporter.EXPECT(). - AddGRPCResponseStatus( - tt.expectedStatus, - ) + AddGRPCResponseStatus(tt.expectedStatus) for i := range tt.expectedDeviations { reporter.EXPECT(). - AddDeviation( - &tt.expectedDeviations[i], - ) + AddDeviation(&tt.expectedDeviations[i]) } expectedMetadata := mergeMetadata( @@ -239,14 +326,15 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { ) reporter.EXPECT(). - AddGRPCResponseMetadata( - expectedMetadata, - ) + AddGRPCResponseMetadata(expectedMetadata) + + expectedMessage := tt.message + if expectedMessage == nil { + expectedMessage = map[string]any{} + } reporter.EXPECT(). - AddGRPCResponseMessage( - tt.message, - ) + AddGRPCResponseMessage(expectedMessage) for i := range tt.expectedPayloadDeviations { reporter.EXPECT(). @@ -272,9 +360,7 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { } } -func TestEvaluatorEvaluateResponseUnknownStatus( - t *testing.T, -) { +func TestEvaluatorEvaluateResponseUnknownStatus(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) @@ -285,13 +371,10 @@ func TestEvaluatorEvaluateResponseUnknownStatus( err := evaluator.EvaluateResponse( nil, - newTestMessage( - t, - map[string]any{}, - ), + newTestMessage(t, map[string]any{}), nil, nil, - &model.GRPCResponse{ + &model.GRPCResponsePattern{ Status: "invalid", }, ) @@ -315,15 +398,10 @@ func TestEvaluatorMatches(t *testing.T) { "Create", ) if err != nil { - t.Fatalf( - "ResolveMethod() error = %v", - err, - ) + t.Fatalf("ResolveMethod() error = %v", err) } - message := dynamicpb.NewMessage( - method.Input(), - ) + message := dynamicpb.NewMessage(method.Input()) message.Set( method.Input().Fields().ByName("name"), @@ -332,10 +410,7 @@ func TestEvaluatorMatches(t *testing.T) { messageBytes, err := proto.Marshal(message) if err != nil { - t.Fatalf( - "marshal message: %v", - err, - ) + t.Fatalf("marshal message: %v", err) } actual := call.Call{ @@ -345,9 +420,8 @@ func TestEvaluatorMatches(t *testing.T) { Service: "users.UserService", Method: "Create", Metadata: map[string][]string{ - "x-request-id": { - "request-1", - }, + "x-request-id": {"request-1"}, + "x-empty": {""}, }, Message: messageBytes, }, @@ -359,8 +433,7 @@ func TestEvaluatorMatches(t *testing.T) { actual call.Call expected model.ServiceExpectedCalls - - match bool + match bool }{ { name: "matches", @@ -370,16 +443,12 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Metadata: map[string][]string{ - "x-request-id": { - "request-1", - }, + Metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("request-1")}, }, - Message: mapPtr( - map[string]any{ - "name": "Yaroslav", - }, - ), + Message: mapPtr(map[string]any{ + "name": "Yaroslav", + }), }, }, match: true, @@ -434,10 +503,8 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Metadata: map[string][]string{ - "x-missing": { - "value", - }, + Metadata: map[string][]matcher.String{ + "x-missing": {grpcStringEquals("value")}, }, }, }, @@ -450,13 +517,84 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Metadata: map[string][]string{ - "x-request-id": { - "different", - }, + Metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("different")}, + }, + }, + }, + }, + { + name: "metadata exists", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]matcher.String{ + "x-empty": {grpcStringOperator(matcher.StringMatchOperatorExists)}, + }, + }, + }, + match: true, + }, + { + name: "metadata exists missing", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]matcher.String{ + "x-missing": {grpcStringOperator(matcher.StringMatchOperatorExists)}, + }, + }, + }, + }, + { + name: "metadata nonempty", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringOperator(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + }, + match: true, + }, + { + name: "metadata nonempty rejects empty value", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]matcher.String{ + "x-empty": {grpcStringOperator(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + }, + }, + { + name: "metadata case insensitive", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Metadata: map[string][]matcher.String{ + "X-Request-Id": {grpcStringEquals("request-1")}, }, }, }, + match: true, }, { name: "message mismatch", @@ -466,11 +604,9 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Message: mapPtr( - map[string]any{ - "name": "Other", - }, - ), + Message: mapPtr(map[string]any{ + "name": "Other", + }), }, }, }, @@ -494,11 +630,24 @@ func TestEvaluatorMatches(t *testing.T) { GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Message: mapPtr( - map[string]any{}, - ), + Message: mapPtr(map[string]any{}), + }, + }, + }, + { + name: "nonempty message matches", + actual: actual, + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + Message: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, }, }, + match: true, }, } @@ -507,38 +656,30 @@ func TestEvaluatorMatches(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) - evaluator := NewEvaluator( - resolver, - reporter, - ) + evaluator := NewEvaluator(resolver, reporter) - match, err := evaluator.Matches( + matched, err := evaluator.Matches( context.Background(), service, tt.actual, tt.expected, ) if err != nil { - t.Fatalf( - "Matches() error = %v", - err, - ) + t.Fatalf("Matches() error = %v", err) } - if match != tt.match { + if matched != tt.match { t.Errorf( "expected match %v, got %v", tt.match, - match, + matched, ) } }) } } -func TestEvaluatorMatchesMissingMethod( - t *testing.T, -) { +func TestEvaluatorMatchesMissingMethod(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) @@ -560,15 +701,13 @@ func TestEvaluatorMatchesMissingMethod( GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Missing", - Message: mapPtr( - map[string]any{ - "name": "Yaroslav", - }, - ), + Message: mapPtr(map[string]any{ + "name": "Yaroslav", + }), }, } - match, err := evaluator.Matches( + matched, err := evaluator.Matches( context.Background(), service, actual, @@ -579,14 +718,12 @@ func TestEvaluatorMatchesMissingMethod( t.Fatal("expected error") } - if match { + if matched { t.Fatal("expected no match") } } -func TestEvaluatorMatchesInvalidCapturedMessage( - t *testing.T, -) { +func TestEvaluatorMatchesInvalidCapturedMessage(t *testing.T) { ctrl := gomock.NewController(t) reporter := NewMockexecutionReporter(ctrl) @@ -609,11 +746,9 @@ func TestEvaluatorMatchesInvalidCapturedMessage( GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Message: mapPtr( - map[string]any{ - "name": "Yaroslav", - }, - ), + Message: mapPtr(map[string]any{ + "name": "Yaroslav", + }), }, } @@ -624,10 +759,7 @@ func TestEvaluatorMatchesInvalidCapturedMessage( expected, ) - if !errors.Is( - err, - ErrCannotDecodeCapturedRequest, - ) { + if !errors.Is(err, ErrCannotDecodeCapturedRequest) { t.Fatalf( "expected ErrCannotDecodeCapturedRequest, got %v", err, @@ -640,12 +772,10 @@ func TestEvaluatorDeviation(t *testing.T) { reporter := NewMockexecutionReporter(ctrl) evaluator := newTestEvaluator(reporter) - service := testServiceSpec() tests := []struct { - name string - + name string actual call.Call expected *model.TestExecutionDeviation }{ @@ -681,11 +811,7 @@ func TestEvaluatorDeviation(t *testing.T) { }, Response: call.GRPCResponse{ Metadata: map[string][]string{ - string( - keys.E2EngineMockMissMetadata, - ): { - "false", - }, + string(keys.E2EngineMockMissMetadata): {"false"}, }, }, }, @@ -702,11 +828,7 @@ func TestEvaluatorDeviation(t *testing.T) { }, Response: call.GRPCResponse{ Metadata: map[string][]string{ - string( - keys.E2EngineMockMissMetadata, - ): { - "true", - }, + string(keys.E2EngineMockMissMetadata): {"true"}, }, }, }, @@ -727,26 +849,11 @@ func TestEvaluatorDeviation(t *testing.T) { tt.actual, ) - if tt.expected == nil { - if actual != nil { - t.Fatalf( - "expected no deviation, got %+v", - actual, - ) - } - - return - } - - if actual == nil { - t.Fatal("expected deviation") - } - - if *actual != *tt.expected { + if !reflect.DeepEqual(actual, tt.expected) { t.Errorf( "expected deviation %+v, got %+v", - *tt.expected, - *actual, + tt.expected, + actual, ) } }) @@ -763,20 +870,14 @@ func TestMessageToMap(t *testing.T) { actual, err := messageToMap(message) if err != nil { - t.Fatalf( - "messageToMap() error = %v", - err, - ) + t.Fatalf("messageToMap() error = %v", err) } expected := map[string]any{ "name": "Yaroslav", } - if !reflect.DeepEqual( - actual, - expected, - ) { + if !reflect.DeepEqual(actual, expected) { t.Errorf( "expected %#v, got %#v", expected, @@ -787,45 +888,24 @@ func TestMessageToMap(t *testing.T) { func TestMergeMetadata(t *testing.T) { header := metadata.MD{ - "x-header": { - "one", - }, - "x-shared": { - "header", - }, + "x-header": {"one"}, + "x-shared": {"header"}, } trailer := metadata.MD{ - "x-trailer": { - "two", - }, - "x-shared": { - "trailer", - }, + "x-trailer": {"two"}, + "x-shared": {"trailer"}, } - actual := mergeMetadata( - header, - trailer, - ) + actual := mergeMetadata(header, trailer) expected := map[string][]string{ - "x-header": { - "one", - }, - "x-trailer": { - "two", - }, - "x-shared": { - "header", - "trailer", - }, + "x-header": {"one"}, + "x-trailer": {"two"}, + "x-shared": {"header", "trailer"}, } - if !reflect.DeepEqual( - actual, - expected, - ) { + if !reflect.DeepEqual(actual, expected) { t.Errorf( "expected %#v, got %#v", expected, @@ -836,116 +916,40 @@ func TestMergeMetadata(t *testing.T) { header["x-header"][0] = "changed" if actual["x-header"][0] != "one" { - t.Error( - "expected merged metadata to be independent of header", - ) + t.Error("expected merged metadata to be independent of header") } } func TestGRPCCode(t *testing.T) { tests := []struct { - name string - + name string value string expected codes.Code }{ - { - name: "OK", - value: "OK", - expected: codes.OK, - }, - { - name: "Canceled", - value: "Canceled", - expected: codes.Canceled, - }, - { - name: "Unknown", - value: "Unknown", - expected: codes.Unknown, - }, - { - name: "InvalidArgument", - value: "InvalidArgument", - expected: codes.InvalidArgument, - }, - { - name: "DeadlineExceeded", - value: "DeadlineExceeded", - expected: codes.DeadlineExceeded, - }, - { - name: "NotFound", - value: "NotFound", - expected: codes.NotFound, - }, - { - name: "AlreadyExists", - value: "AlreadyExists", - expected: codes.AlreadyExists, - }, - { - name: "PermissionDenied", - value: "PermissionDenied", - expected: codes.PermissionDenied, - }, - { - name: "ResourceExhausted", - value: "ResourceExhausted", - expected: codes.ResourceExhausted, - }, - { - name: "FailedPrecondition", - value: "FailedPrecondition", - expected: codes.FailedPrecondition, - }, - { - name: "Aborted", - value: "Aborted", - expected: codes.Aborted, - }, - { - name: "OutOfRange", - value: "OutOfRange", - expected: codes.OutOfRange, - }, - { - name: "Unimplemented", - value: "Unimplemented", - expected: codes.Unimplemented, - }, - { - name: "Internal", - value: "Internal", - expected: codes.Internal, - }, - { - name: "Unavailable", - value: "Unavailable", - expected: codes.Unavailable, - }, - { - name: "DataLoss", - value: "DataLoss", - expected: codes.DataLoss, - }, - { - name: "Unauthenticated", - value: "Unauthenticated", - expected: codes.Unauthenticated, - }, + {"OK", "OK", codes.OK}, + {"Canceled", "Canceled", codes.Canceled}, + {"Unknown", "Unknown", codes.Unknown}, + {"InvalidArgument", "InvalidArgument", codes.InvalidArgument}, + {"DeadlineExceeded", "DeadlineExceeded", codes.DeadlineExceeded}, + {"NotFound", "NotFound", codes.NotFound}, + {"AlreadyExists", "AlreadyExists", codes.AlreadyExists}, + {"PermissionDenied", "PermissionDenied", codes.PermissionDenied}, + {"ResourceExhausted", "ResourceExhausted", codes.ResourceExhausted}, + {"FailedPrecondition", "FailedPrecondition", codes.FailedPrecondition}, + {"Aborted", "Aborted", codes.Aborted}, + {"OutOfRange", "OutOfRange", codes.OutOfRange}, + {"Unimplemented", "Unimplemented", codes.Unimplemented}, + {"Internal", "Internal", codes.Internal}, + {"Unavailable", "Unavailable", codes.Unavailable}, + {"DataLoss", "DataLoss", codes.DataLoss}, + {"Unauthenticated", "Unauthenticated", codes.Unauthenticated}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - actual, err := grpcCode( - tt.value, - ) + actual, err := grpcCode(tt.value) if err != nil { - t.Fatalf( - "grpcCode() error = %v", - err, - ) + t.Fatalf("grpcCode() error = %v", err) } if actual != tt.expected { @@ -962,10 +966,7 @@ func TestGRPCCode(t *testing.T) { func TestGRPCCodeUnknown(t *testing.T) { actual, err := grpcCode("invalid") - if !errors.Is( - err, - ErrUnknownStatus, - ) { + if !errors.Is(err, ErrUnknownStatus) { t.Fatalf( "expected ErrUnknownStatus, got %v", err, @@ -1038,17 +1039,13 @@ func newTestMessage( Name: proto.String("Response"), Field: []*descriptorpb.FieldDescriptorProto{ { - Name: proto.String("name"), - JsonName: proto.String( - "name", - ), - Number: proto.Int32(1), + Name: proto.String("name"), + JsonName: proto.String("name"), + Number: proto.Int32(1), Label: descriptorpb. - FieldDescriptorProto_LABEL_OPTIONAL. - Enum(), + FieldDescriptorProto_LABEL_OPTIONAL.Enum(), Type: descriptorpb. - FieldDescriptorProto_TYPE_STRING. - Enum(), + FieldDescriptorProto_TYPE_STRING.Enum(), }, }, }, @@ -1057,43 +1054,22 @@ func newTestMessage( nil, ) if err != nil { - t.Fatalf( - "create file descriptor: %v", - err, - ) + t.Fatalf("create file descriptor: %v", err) } - descriptor := fileDescriptor.Messages().ByName( - "Response", - ) - - message := dynamicpb.NewMessage( - descriptor, - ) + descriptor := fileDescriptor.Messages().ByName("Response") + message := dynamicpb.NewMessage(descriptor) if value != nil { data, err := protojson.Marshal( - newMapMessage( - t, - descriptor, - value, - ), + newMapMessage(t, descriptor, value), ) if err != nil { - t.Fatalf( - "marshal test message: %v", - err, - ) + t.Fatalf("marshal test message: %v", err) } - if err := protojson.Unmarshal( - data, - message, - ); err != nil { - t.Fatalf( - "unmarshal test message: %v", - err, - ) + if err := protojson.Unmarshal(data, message); err != nil { + t.Fatalf("unmarshal test message: %v", err) } } @@ -1107,14 +1083,10 @@ func newMapMessage( ) *dynamicpb.Message { t.Helper() - message := dynamicpb.NewMessage( - descriptor, - ) + message := dynamicpb.NewMessage(descriptor) if name, ok := value["name"].(string); ok { - field := descriptor.Fields().ByName( - "name", - ) + field := descriptor.Fields().ByName("name") message.Set( field, @@ -1125,8 +1097,29 @@ func newMapMessage( return message } -func mapPtr( - value map[string]any, -) *map[string]any { - return &value +func mapPtr(value map[string]any) *matcher.GRPCMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) + } + + return &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: string(data), + } +} + +func grpcStringEquals(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } +} + +func grpcStringOperator( + operator matcher.StringMatchOperator, +) matcher.String { + return matcher.String{ + Operator: operator, + } } diff --git a/execute/worker/grpc/executor_test.go b/execute/worker/grpc/executor_test.go index da59249..c4aa36f 100644 --- a/execute/worker/grpc/executor_test.go +++ b/execute/worker/grpc/executor_test.go @@ -2,6 +2,7 @@ package grpc import ( "context" + "encoding/json" "errors" "net" "reflect" @@ -19,6 +20,7 @@ import ( "github.com/e2engine/core/execute" servicegrpc "github.com/e2engine/core/execute/runtime/service/grpc" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" coreerrors "github.com/e2engine/core/pkg/errors" ) @@ -445,7 +447,7 @@ func TestExecutorExecute(t *testing.T) { }, }, Expect: model.ExpectSpec{ - GRPC: &model.GRPCResponse{ + GRPC: &model.GRPCResponsePattern{ Status: "OK", Message: mapPtrExecutor( map[string]any{ @@ -569,6 +571,14 @@ func TestExecutorExecute(t *testing.T) { func mapPtrExecutor( value map[string]any, -) *map[string]any { - return &value +) *matcher.GRPCMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) + } + + return &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: string(data), + } } diff --git a/execute/worker/grpc/mock_reporter_test.go b/execute/worker/grpc/mock_reporter_test.go index 93a1db8..969d228 100644 --- a/execute/worker/grpc/mock_reporter_test.go +++ b/execute/worker/grpc/mock_reporter_test.go @@ -101,7 +101,7 @@ func (mr *MockexecutionReporterMockRecorder) AddGRPCResponseStatus(status any) * } // AddPayloadDeviation mocks base method. -func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { +func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddPayloadDeviation", deviation) } diff --git a/execute/worker/grpc/reporter.go b/execute/worker/grpc/reporter.go index dba1e28..a2d1fd5 100644 --- a/execute/worker/grpc/reporter.go +++ b/execute/worker/grpc/reporter.go @@ -6,7 +6,7 @@ import ( type executionReporter interface { AddDeviation(deviation *model.TestExecutionDeviation) - AddPayloadDeviation(deviation *model.TestExecutionDeviation) + AddPayloadDeviation(deviation *model.PayloadDeviation) AddGRPCRequest(req *model.GRPCRequest) AddGRPCResponseStatus(status string) AddGRPCResponseMetadata(metadata map[string][]string) diff --git a/execute/worker/http/evaluate.go b/execute/worker/http/evaluate.go index aa4a896..8c5a715 100644 --- a/execute/worker/http/evaluate.go +++ b/execute/worker/http/evaluate.go @@ -5,13 +5,16 @@ import ( "encoding/json" "io" "net/http" + "slices" "strconv" "strings" "github.com/e2engine/core/execute/call" + "github.com/e2engine/core/execute/match" "github.com/e2engine/core/execute/worker/evaluator" "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/keys" ) @@ -31,52 +34,32 @@ func NewEvaluator( func (e *Evaluator) EvaluateResponse( resp *http.Response, - expect *model.HTTPResponse, + expect *model.HTTPResponsePattern, ) error { - e.reporter.AddHTTPResponseStatus(resp.StatusCode) - e.reporter.AddHTTPResponseHeaders(resp.Header) + e.evaluateStatusCode(expect.StatusCode, resp.StatusCode) - if resp.StatusCode != expect.StatusCode { - e.reporter.AddDeviation(&model.TestExecutionDeviation{ - Field: string(keys.FieldStatusCode), - Expected: strconv.Itoa(expect.StatusCode), - Actual: strconv.Itoa(resp.StatusCode), - }) - } - - for key, expectedValues := range expect.Headers { - actualValues := resp.Header.Values(key) + e.evaluateHeaders(expect.Headers, resp.Header) - if len(actualValues) > 0 && - util.IsStringSlicesEqual(actualValues, expectedValues) { - continue - } - - e.reporter.AddDeviation(&model.TestExecutionDeviation{ - Field: "headers." + key, - Expected: strings.Join(expectedValues, ","), - Actual: strings.Join(actualValues, ","), - }) + actualBody, err := io.ReadAll(resp.Body) + if err != nil { + return err } if expect.Body == nil && expect.BodyJSON == nil { // nil means "do not evaluate body" + // we still need to report the body we received + e.reporter.AddHTTPResponseBody(actualBody) return nil } - actualBody, err := io.ReadAll(resp.Body) - if err != nil { - return err - } - if expect.Body != nil { - e.reporter.AddHTTPResponseBody(string(actualBody)) + e.reporter.AddHTTPResponseBody(actualBody) - if string(actualBody) != *expect.Body { - e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + if !match.IsStringMatched(actualBody, expect.Body) { + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ Field: string(keys.FieldBody), - Expected: *expect.Body, - Actual: string(actualBody), + Expected: expect.Body, + Actual: actualBody, }) } @@ -84,42 +67,89 @@ func (e *Evaluator) EvaluateResponse( } if !json.Valid(actualBody) { - e.reporter.AddHTTPResponseBody(string(actualBody)) + e.reporter.AddHTTPResponseBodyJSON(actualBody) - e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ Field: string(keys.FieldBodyJSON), - Expected: util.CompactJSON([]byte(*expect.BodyJSON)), - Actual: string(actualBody), + Expected: expect.BodyJSON, + Actual: actualBody, Message: "response body is not valid JSON", }) return nil } - e.reporter.AddHTTPResponseBodyJSON(util.CompactJSON(actualBody)) + actualJSON := util.CompactJSON(actualBody) - equal, err := util.IsJSONEqual( - []byte(*expect.BodyJSON), + e.reporter.AddHTTPResponseBodyJSON(actualJSON) + + matched, err := match.IsJSONMatched( actualBody, + expect.BodyJSON, ) if err != nil { - // Expected JSON should already have been validated. + // Expected JSON has already been validated. return err } - if !equal { - e.reporter.AddPayloadDeviation(&model.TestExecutionDeviation{ - Field: string(keys.FieldBodyJSON), - Expected: util.CompactJSON( - []byte(*expect.BodyJSON), - ), - Actual: util.CompactJSON(actualBody), + if !matched { + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: expect.BodyJSON, + Actual: actualJSON, }) } return nil } +func (e *Evaluator) evaluateStatusCode(expected, actual int) { + e.reporter.AddHTTPResponseStatus(actual) + + if actual != expected { + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: string(keys.FieldStatusCode), + Expected: strconv.Itoa(expected), + Actual: strconv.Itoa(actual), + }) + } +} + +func (e *Evaluator) evaluateHeaders( + expected map[string][]matcher.String, + actual http.Header, +) { + e.reporter.AddHTTPResponseHeaders(actual) + + for key, expectedValues := range expected { + canonicalKey := http.CanonicalHeaderKey(key) + actualValues, exists := actual[canonicalKey] + + if match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { + continue + } + + sortedActual := slices.Clone(actualValues) + slices.Sort(sortedActual) + + expectedStrings := make([]string, len(expectedValues)) + for i, v := range expectedValues { + expectedStrings[i] = v.String() + } + slices.Sort(expectedStrings) + + e.reporter.AddDeviation(&model.TestExecutionDeviation{ + Field: "headers." + key, + Expected: strings.Join(expectedStrings, ","), + Actual: strings.Join(sortedActual, ","), + }) + } +} + func (e *Evaluator) Matches( _ context.Context, _ *model.ServiceSpec, @@ -160,24 +190,28 @@ func httpCallMatchesExpectation( } for key, expectedValues := range expected.Headers { - actualValues := actual.Headers.Values(key) - - if len(actualValues) == 0 || - !util.IsStringSlicesEqual(actualValues, expectedValues) { + canonicalKey := http.CanonicalHeaderKey(key) + actualValues, exists := actual.Headers[canonicalKey] + + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { return false } } - if expected.Body != nil && string(actual.Body) != *expected.Body { + if expected.Body != nil && !match.IsStringMatched(actual.Body, expected.Body) { return false } if expected.BodyJSON != nil { - equal, err := util.IsJSONEqual( - []byte(*expected.BodyJSON), + matched, err := match.IsJSONMatched( actual.Body, + expected.BodyJSON, ) - if err != nil || !equal { + if err != nil || !matched { return false } } diff --git a/execute/worker/http/evaluate_test.go b/execute/worker/http/evaluate_test.go index 58f63c9..f52b508 100644 --- a/execute/worker/http/evaluate_test.go +++ b/execute/worker/http/evaluate_test.go @@ -5,6 +5,7 @@ import ( "errors" "io" nethttp "net/http" + "reflect" "strings" "testing" @@ -12,6 +13,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/keys" ) @@ -22,8 +24,8 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { } type deviationCall struct { - payload bool - deviation model.TestExecutionDeviation + deviation *model.TestExecutionDeviation + payload *model.PayloadDeviation } tests := []struct { @@ -32,28 +34,31 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { status int body string headers nethttp.Header - expect model.HTTPResponse + expect model.HTTPResponsePattern - bodyCall *bodyCall + bodyCall bodyCall deviations []deviationCall }{ { name: "matching status without body expectation", status: nethttp.StatusOK, body: `{"ignored":true}`, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, }, + bodyCall: bodyCall{ + value: `{"ignored":true}`, + }, }, { name: "status mismatch", status: nethttp.StatusNotFound, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, }, deviations: []deviationCall{ { - deviation: model.TestExecutionDeviation{ + deviation: &model.TestExecutionDeviation{ Field: string(keys.FieldStatusCode), Expected: "200", Actual: "404", @@ -65,34 +70,46 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "matching JSON body", status: nethttp.StatusOK, body: `{"name":"test","count":1}`, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - BodyJSON: stringPtr(`{"count":1,"name":"test"}`), + BodyJSON: stringMatcher(`{"count":1,"name":"test"}`), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ json: true, value: `{"name":"test","count":1}`, }, }, + { + name: "matching JSON body with whitespace", + status: nethttp.StatusOK, + body: "{\n \"name\": \"test\"\n}\n", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"name":"test"}`), + }, + bodyCall: bodyCall{ + json: true, + value: `{"name":"test"}`, + }, + }, { name: "JSON body mismatch", status: nethttp.StatusOK, body: `{"name":"actual"}`, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - BodyJSON: stringPtr(`{"name":"expected"}`), + BodyJSON: stringMatcher(`{"name":"expected"}`), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ json: true, value: `{"name":"actual"}`, }, deviations: []deviationCall{ { - payload: true, - deviation: model.TestExecutionDeviation{ + payload: &model.PayloadDeviation{ Field: string(keys.FieldBodyJSON), - Expected: `{"name":"expected"}`, - Actual: `{"name":"actual"}`, + Expected: stringMatcher(`{"name":"expected"}`), + Actual: []byte(`{"name":"actual"}`), }, }, }, @@ -101,20 +118,20 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "response body is not JSON", status: nethttp.StatusOK, body: "hello", - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - BodyJSON: stringPtr(`{"message":"hello"}`), + BodyJSON: stringMatcher(`{"message":"hello"}`), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ value: "hello", + json: true, }, deviations: []deviationCall{ { - payload: true, - deviation: model.TestExecutionDeviation{ + payload: &model.PayloadDeviation{ Field: string(keys.FieldBodyJSON), - Expected: `{"message":"hello"}`, - Actual: "hello", + Expected: stringMatcher(`{"message":"hello"}`), + Actual: []byte("hello"), Message: "response body is not valid JSON", }, }, @@ -124,28 +141,27 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "status and body mismatch", status: nethttp.StatusBadRequest, body: `{"actual":true}`, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - BodyJSON: stringPtr(`{"expected":true}`), + BodyJSON: stringMatcher(`{"expected":true}`), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ json: true, value: `{"actual":true}`, }, deviations: []deviationCall{ { - deviation: model.TestExecutionDeviation{ + deviation: &model.TestExecutionDeviation{ Field: string(keys.FieldStatusCode), Expected: "200", Actual: "400", }, }, { - payload: true, - deviation: model.TestExecutionDeviation{ + payload: &model.PayloadDeviation{ Field: string(keys.FieldBodyJSON), - Expected: `{"expected":true}`, - Actual: `{"actual":true}`, + Expected: stringMatcher(`{"expected":true}`), + Actual: []byte(`{"actual":true}`), }, }, }, @@ -154,11 +170,11 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "matching exact text body", status: nethttp.StatusOK, body: "plain text body", - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Body: stringPtr("plain text body"), + Body: stringMatcher("plain text body"), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ value: "plain text body", }, }, @@ -166,48 +182,147 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { name: "mismatched exact text body", status: nethttp.StatusOK, body: "actual text body", - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Body: stringPtr("expected text body"), + Body: stringMatcher("expected text body"), }, - bodyCall: &bodyCall{ + bodyCall: bodyCall{ value: "actual text body", }, deviations: []deviationCall{ { - payload: true, - deviation: model.TestExecutionDeviation{ + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBody), + Expected: stringMatcher("expected text body"), + Actual: []byte("actual text body"), + }, + }, + }, + }, + { + name: "exact body preserves trailing newline", + status: nethttp.StatusOK, + body: "hello\n", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcher("hello"), + }, + bodyCall: bodyCall{ + value: "hello\n", + }, + deviations: []deviationCall{ + { + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBody), + Expected: stringMatcher("hello"), + Actual: []byte("hello\n"), + }, + }, + }, + }, + { + name: "matching empty body", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcher(""), + }, + }, + { + name: "nonempty body matches", + status: nethttp.StatusOK, + body: "hello", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + bodyCall: bodyCall{ + value: "hello", + }, + }, + { + name: "nonempty body mismatch", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + deviations: []deviationCall{ + { + payload: &model.PayloadDeviation{ Field: string(keys.FieldBody), - Expected: "expected text body", - Actual: "actual text body", + Expected: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + Actual: []byte{}, + }, + }, + }, + }, + { + name: "exists body matches empty body", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcherOperator(matcher.StringMatchOperatorExists), + }, + }, + { + name: "nonempty JSON matches empty object", + status: nethttp.StatusOK, + body: `{}`, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + bodyCall: bodyCall{ + json: true, + value: `{}`, + }, + }, + { + name: "nonempty JSON rejects empty body", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + bodyCall: bodyCall{ + json: true, + }, + deviations: []deviationCall{ + { + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + Actual: []byte{}, + Message: "response body is not valid JSON", }, }, }, }, { - name: "expected header is persisted", + name: "expected header matches", status: nethttp.StatusOK, headers: nethttp.Header{ "X-Test": {"value"}, }, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Headers: map[string][]string{ - "X-Test": {"value"}, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("value")}, }, }, }, { - name: "unexpected header is not persisted", + name: "unexpected header is ignored", status: nethttp.StatusOK, headers: nethttp.Header{ "Authorization": {"secret"}, "X-Test": {"value"}, }, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Headers: map[string][]string{ - "X-Test": {"value"}, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("value")}, }, }, }, @@ -217,10 +332,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { headers: nethttp.Header{ "X-Test": {"value"}, }, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Headers: map[string][]string{ - "x-test": {"value"}, + Headers: map[string][]matcher.String{ + "x-test": {stringMatcherValue("value")}, }, }, }, @@ -230,15 +345,15 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { headers: nethttp.Header{ "X-Test": {"actual"}, }, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Headers: map[string][]string{ - "X-Test": {"expected"}, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("expected")}, }, }, deviations: []deviationCall{ { - deviation: model.TestExecutionDeviation{ + deviation: &model.TestExecutionDeviation{ Field: "headers.X-Test", Expected: "expected", Actual: "actual", @@ -252,18 +367,82 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { headers: nethttp.Header{ "X-Other": {"value"}, }, - expect: model.HTTPResponse{ + expect: model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - Headers: map[string][]string{ - "X-Test": {"expected"}, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("expected")}, }, }, deviations: []deviationCall{ { - deviation: model.TestExecutionDeviation{ + deviation: &model.TestExecutionDeviation{ Field: "headers.X-Test", Expected: "expected", - Actual: "", + }, + }, + }, + }, + { + name: "header exists with empty value", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {""}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherOperatorValue(matcher.StringMatchOperatorExists)}, + }, + }, + }, + { + name: "header exists but is missing", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherOperatorValue(matcher.StringMatchOperatorExists)}, + }, + }, + deviations: []deviationCall{ + { + deviation: &model.TestExecutionDeviation{ + Field: "headers.X-Test", + Expected: "exists", + }, + }, + }, + }, + { + name: "nonempty header matches", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"value"}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherOperatorValue(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + }, + { + name: "nonempty header rejects empty value", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {""}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherOperatorValue(matcher.StringMatchOperatorNonEmpty)}, + }, + }, + deviations: []deviationCall{ + { + deviation: &model.TestExecutionDeviation{ + Field: "headers.X-Test", + Expected: "nonempty", }, }, }, @@ -292,27 +471,25 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { AddHTTPResponseHeaders(tt.headers) for _, deviation := range tt.deviations { - if deviation.payload { + if deviation.payload != nil { reporter.EXPECT(). - AddPayloadDeviation(&deviation.deviation) + AddPayloadDeviation(deviation.payload) } else { reporter.EXPECT(). - AddDeviation(&deviation.deviation) + AddDeviation(deviation.deviation) } } - if tt.bodyCall != nil { - if tt.bodyCall.json { - reporter.EXPECT(). - AddHTTPResponseBodyJSON( - tt.bodyCall.value, - ) - } else { - reporter.EXPECT(). - AddHTTPResponseBody( - tt.bodyCall.value, - ) - } + if tt.bodyCall.json { + reporter.EXPECT(). + AddHTTPResponseBodyJSON( + []byte(tt.bodyCall.value), + ) + } else { + reporter.EXPECT(). + AddHTTPResponseBody( + []byte(tt.bodyCall.value), + ) } err := evaluator.EvaluateResponse( @@ -352,9 +529,9 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { err := evaluator.EvaluateResponse( response, - &model.HTTPResponse{ + &model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, - BodyJSON: stringPtr(`{"result":"ok"}`), + BodyJSON: stringMatcher(`{"result":"ok"}`), }, ) @@ -395,7 +572,7 @@ func TestEvaluatorMatches(t *testing.T) { HTTP: &model.HTTPRequestPattern{ Method: "POST", Path: "/users", - BodyJSON: stringPtr(`{"name":"Yaroslav"}`), + BodyJSON: stringMatcher(`{"name":"Yaroslav"}`), }, }, match: true, @@ -448,7 +625,7 @@ func TestEvaluatorMatches(t *testing.T) { evaluator := NewEvaluator(reporter) - match, err := evaluator.Matches( + matched, err := evaluator.Matches( context.Background(), &model.ServiceSpec{}, tt.actual, @@ -461,11 +638,11 @@ func TestEvaluatorMatches(t *testing.T) { ) } - if match != tt.match { + if matched != tt.match { t.Errorf( "expected match %v, got %v", tt.match, - match, + matched, ) } }) @@ -483,6 +660,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { Headers: nethttp.Header{ "Content-Type": {"application/json"}, "X-Test": {"one", "two"}, + "X-Empty": {""}, }, Body: []byte(`{"name":"Yaroslav","active":true}`), } @@ -508,11 +686,14 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { "active": {"true"}, "role": {"admin", "user"}, }, - Headers: map[string][]string{ - "Content-Type": {"application/json"}, - "X-Test": {"one", "two"}, + Headers: map[string][]matcher.String{ + "Content-Type": {stringMatcherValue("application/json")}, + "X-Test": { + stringMatcherValue("one"), + stringMatcherValue("two"), + }, }, - BodyJSON: stringPtr( + BodyJSON: stringMatcher( `{"active":true,"name":"Yaroslav"}`, ), }, @@ -549,24 +730,27 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "header missing", expected: model.HTTPRequestPattern{ - Headers: map[string][]string{ - "X-Missing": {"value"}, + Headers: map[string][]matcher.String{ + "X-Missing": {stringMatcherValue("value")}, }, }, }, { name: "header mismatch", expected: model.HTTPRequestPattern{ - Headers: map[string][]string{ - "Content-Type": {"text/plain"}, + Headers: map[string][]matcher.String{ + "Content-Type": {stringMatcherValue("text/plain")}, }, }, }, { name: "header name is case insensitive", expected: model.HTTPRequestPattern{ - Headers: map[string][]string{ - "x-test": {"one", "two"}, + Headers: map[string][]matcher.String{ + "x-test": { + stringMatcherValue("one"), + stringMatcherValue("two"), + }, }, }, match: true, @@ -574,7 +758,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "JSON body mismatch", expected: model.HTTPRequestPattern{ - BodyJSON: stringPtr( + BodyJSON: stringMatcher( `{"name":"Other"}`, ), }, @@ -582,7 +766,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "actual body is invalid JSON", expected: model.HTTPRequestPattern{ - BodyJSON: stringPtr( + BodyJSON: stringMatcher( `{"name":"Yaroslav"}`, ), }, @@ -591,7 +775,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "exact text body matches", expected: model.HTTPRequestPattern{ - Body: stringPtr( + Body: stringMatcher( `{"name":"Yaroslav","active":true}`, ), }, @@ -600,7 +784,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "exact text body mismatch", expected: model.HTTPRequestPattern{ - Body: stringPtr( + Body: stringMatcher( `{"active":true,"name":"Yaroslav"}`, ), }, @@ -617,8 +801,8 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "headers subset matches", expected: model.HTTPRequestPattern{ - Headers: map[string][]string{ - "Content-Type": {"application/json"}, + Headers: map[string][]matcher.String{ + "Content-Type": {stringMatcherValue("application/json")}, }, }, match: true, @@ -635,25 +819,109 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { { name: "header values match regardless of order", expected: model.HTTPRequestPattern{ - Headers: map[string][]string{ - "X-Test": {"two", "one"}, + Headers: map[string][]matcher.String{ + "X-Test": { + stringMatcherValue("two"), + stringMatcherValue("one"), + }, + }, + }, + match: true, + }, + { + name: "header exists", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Test": { + stringMatcherOperatorValue(matcher.StringMatchOperatorExists), + }, + }, + }, + match: true, + }, + { + name: "header exists with empty value", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Empty": { + stringMatcherOperatorValue(matcher.StringMatchOperatorExists), + }, + }, + }, + match: true, + }, + { + name: "header exists but is missing", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Missing": { + stringMatcherOperatorValue(matcher.StringMatchOperatorExists), + }, + }, + }, + }, + { + name: "header nonempty", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Test": { + stringMatcherOperatorValue(matcher.StringMatchOperatorNonEmpty), + }, }, }, match: true, }, + { + name: "header nonempty rejects empty value", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Empty": { + stringMatcherOperatorValue(matcher.StringMatchOperatorNonEmpty), + }, + }, + }, + }, { name: "explicit empty body matches empty body", expected: model.HTTPRequestPattern{ - Body: stringPtr(""), + Body: stringMatcher(""), }, body: []byte{}, match: true, }, { - name: "explicit empty body does not match non-empty body", + name: "explicit empty body does not match nonempty body", + expected: model.HTTPRequestPattern{ + Body: stringMatcher(""), + }, + }, + { + name: "nonempty body matches", + expected: model.HTTPRequestPattern{ + Body: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + match: true, + }, + { + name: "nonempty body rejects empty body", + expected: model.HTTPRequestPattern{ + Body: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + body: []byte{}, + }, + { + name: "JSON nonempty matches", + expected: model.HTTPRequestPattern{ + BodyJSON: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + }, + match: true, + }, + { + name: "JSON exists matches", expected: model.HTTPRequestPattern{ - Body: stringPtr(""), + BodyJSON: stringMatcherOperator(matcher.StringMatchOperatorExists), }, + match: true, }, } @@ -665,16 +933,16 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { request.Body = tt.body } - match := httpCallMatchesExpectation( + matched := httpCallMatchesExpectation( request, &tt.expected, ) - if match != tt.match { + if matched != tt.match { t.Errorf( "expected match %v, got %v", tt.match, - match, + matched, ) } }) @@ -732,12 +1000,9 @@ func TestEvaluatorDeviation(t *testing.T) { Headers: func() nethttp.Header { headers := make(nethttp.Header) headers.Set( - string( - keys.E2EngineMockMissHeader, - ), + string(keys.E2EngineMockMissHeader), "true", ) - return headers }(), }, @@ -759,26 +1024,11 @@ func TestEvaluatorDeviation(t *testing.T) { tt.actual, ) - if tt.expected == nil { - if actual != nil { - t.Fatalf( - "expected no deviation, got %+v", - actual, - ) - } - - return - } - - if actual == nil { - t.Fatal("expected deviation") - } - - if *actual != *tt.expected { + if !reflect.DeepEqual(actual, tt.expected) { t.Errorf( "expected deviation %+v, got %+v", - *tt.expected, - *actual, + tt.expected, + actual, ) } }) @@ -789,9 +1039,7 @@ type errorReader struct { err error } -func (r *errorReader) Read( - _ []byte, -) (int, error) { +func (r *errorReader) Read(_ []byte) (int, error) { return 0, r.err } @@ -799,6 +1047,32 @@ func (r *errorReader) Close() error { return nil } -func stringPtr(value string) *string { - return &value +func stringMatcher(value string) *matcher.String { + return &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } +} + +func stringMatcherValue(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } +} + +func stringMatcherOperator( + operator matcher.StringMatchOperator, +) *matcher.String { + return &matcher.String{ + Operator: operator, + } +} + +func stringMatcherOperatorValue( + operator matcher.StringMatchOperator, +) matcher.String { + return matcher.String{ + Operator: operator, + } } diff --git a/execute/worker/http/executor_test.go b/execute/worker/http/executor_test.go index 6a52e5f..b19ef68 100644 --- a/execute/worker/http/executor_test.go +++ b/execute/worker/http/executor_test.go @@ -14,6 +14,7 @@ import ( "github.com/e2engine/core/execute" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" ) func TestBuildHTTPRequest(t *testing.T) { @@ -471,7 +472,7 @@ func TestExecutorExecute(t *testing.T) { }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{ + HTTP: &model.HTTPResponsePattern{ StatusCode: nethttp.StatusOK, BodyJSON: stringPtrExecutor( `{"name":"test","id":42}`, @@ -530,7 +531,7 @@ func TestExecutorExecute(t *testing.T) { reporter.EXPECT(). AddHTTPResponseBodyJSON( - `{"id":42,"name":"test"}`, + []byte(`{"id":42,"name":"test"}`), ) err := executor.Execute( @@ -547,6 +548,9 @@ func TestExecutorExecute(t *testing.T) { func stringPtrExecutor( value string, -) *string { - return &value +) *matcher.String { + return &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } } diff --git a/execute/worker/http/mock_reporter_test.go b/execute/worker/http/mock_reporter_test.go index e8f0cc5..f22fef9 100644 --- a/execute/worker/http/mock_reporter_test.go +++ b/execute/worker/http/mock_reporter_test.go @@ -66,7 +66,7 @@ func (mr *MockexecutionReporterMockRecorder) AddHTTPRequest(req any) *gomock.Cal } // AddHTTPResponseBody mocks base method. -func (m *MockexecutionReporter) AddHTTPResponseBody(body string) { +func (m *MockexecutionReporter) AddHTTPResponseBody(body []byte) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddHTTPResponseBody", body) } @@ -78,7 +78,7 @@ func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseBody(body any) *gomo } // AddHTTPResponseBodyJSON mocks base method. -func (m *MockexecutionReporter) AddHTTPResponseBodyJSON(body string) { +func (m *MockexecutionReporter) AddHTTPResponseBodyJSON(body []byte) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddHTTPResponseBodyJSON", body) } @@ -114,7 +114,7 @@ func (mr *MockexecutionReporterMockRecorder) AddHTTPResponseStatus(status any) * } // AddPayloadDeviation mocks base method. -func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { +func (m *MockexecutionReporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddPayloadDeviation", deviation) } diff --git a/execute/worker/http/reporter.go b/execute/worker/http/reporter.go index 0674259..9823cf7 100644 --- a/execute/worker/http/reporter.go +++ b/execute/worker/http/reporter.go @@ -8,12 +8,12 @@ import ( type executionReporter interface { AddDeviation(deviation *model.TestExecutionDeviation) - AddPayloadDeviation(deviation *model.TestExecutionDeviation) + AddPayloadDeviation(deviation *model.PayloadDeviation) AddHTTPRequest(req *http.Request) AddHTTPResponseStatus(status int) AddHTTPResponseHeaders(headers http.Header) - AddHTTPResponseBody(body string) - AddHTTPResponseBodyJSON(body string) + AddHTTPResponseBody(body []byte) + AddHTTPResponseBodyJSON(body []byte) } //go:generate go run -mod=mod go.uber.org/mock/mockgen -source=reporter.go -destination=mock_reporter_test.go -package=http diff --git a/execute/worker/reporter/reporter.go b/execute/worker/reporter/reporter.go index 66a02ed..da601c7 100644 --- a/execute/worker/reporter/reporter.go +++ b/execute/worker/reporter/reporter.go @@ -9,6 +9,7 @@ import ( "github.com/e2engine/core/execute/call" "github.com/e2engine/core/internal/util" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" ) type Reporter struct { @@ -81,25 +82,41 @@ func (r *Reporter) AddDeviation(deviation *model.TestExecutionDeviation) { return } r.ensureNotFinalized() + r.report.Summary.Deviations = append(r.report.Summary.Deviations, *deviation) } -func (r *Reporter) AddPayloadDeviation(deviation *model.TestExecutionDeviation) { +const dumpDisabled = "" + +func (r *Reporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { if deviation == nil { return } - d := &model.TestExecutionDeviation{ + r.ensureNotFinalized() + + d := model.TestExecutionDeviation{ Field: deviation.Field, Message: deviation.Message, } - if r.cfg.DumpPayload { - d.Actual = deviation.Actual - d.Expected = deviation.Expected + switch { + case deviation.Expected == nil: + case !r.cfg.DumpPayload: + d.Expected = dumpDisabled + default: + d.Expected = deviation.Expected.String() } - r.AddDeviation(d) + switch { + case len(deviation.Actual) == 0: + case !r.cfg.DumpPayload: + d.Actual = dumpDisabled + default: + d.Actual = string(deviation.Actual) + } + + r.report.Summary.Deviations = append(r.report.Summary.Deviations, d) } func (r *Reporter) AddHTTPRequest(req *http.Request) { @@ -111,13 +128,23 @@ func (r *Reporter) AddHTTPRequest(req *http.Request) { Headers: req.Header.Clone(), } - if r.cfg.DumpPayload { - request.Body = r.testSpec.Request.HTTP.Body + if r.testSpec.Request.HTTP.Body != "" { + switch { + case !r.cfg.DumpPayload: + request.Body = dumpDisabled + default: + request.Body = r.testSpec.Request.HTTP.Body + } + } - if r.testSpec.Request.HTTP.BodyJSON != "" { - request.BodyJSON = util.CompactJSON( + if r.testSpec.Request.HTTP.BodyJSON != "" { + switch { + case !r.cfg.DumpPayload: + request.BodyJSON = dumpDisabled + default: + request.BodyJSON = string(util.CompactJSON( json.RawMessage(r.testSpec.Request.HTTP.BodyJSON), - ) + )) } } @@ -155,7 +182,7 @@ func (r *Reporter) AddHTTPResponseHeaders(headers http.Header) { func selectHeaders( actual http.Header, - expected map[string][]string, + expected map[string][]matcher.String, ) map[string][]string { if len(expected) == 0 { return nil @@ -166,10 +193,10 @@ func selectHeaders( len(expected), ) - for key := range expected { - values := actual.Values(key) + for k := range expected { + values := actual.Values(k) if len(values) > 0 { - result[key] = util.CloneStringSlice(values) + result[k] = util.CloneStringSlice(values) } } @@ -180,26 +207,30 @@ func selectHeaders( return result } -func (r *Reporter) AddHTTPResponseBody(body string) { - if !r.cfg.DumpPayload { - return - } - +func (r *Reporter) AddHTTPResponseBody(body []byte) { r.ensureNotFinalized() - r.ensureHTTPResponseSummary() - r.report.Summary.Response.HTTP.Body = &body -} -func (r *Reporter) AddHTTPResponseBodyJSON(body string) { - if !r.cfg.DumpPayload { - return + switch { + case len(body) == 0: + case !r.cfg.DumpPayload: + r.report.Summary.Response.HTTP.Body = dumpDisabled + default: + r.report.Summary.Response.HTTP.Body = string(body) } +} +func (r *Reporter) AddHTTPResponseBodyJSON(body []byte) { r.ensureNotFinalized() - r.ensureHTTPResponseSummary() - r.report.Summary.Response.HTTP.BodyJSON = &body + + switch { + case len(body) == 0: + case !r.cfg.DumpPayload: + r.report.Summary.Response.HTTP.BodyJSON = dumpDisabled + default: + r.report.Summary.Response.HTTP.BodyJSON = string(body) + } } func (r *Reporter) ensureGRPCResponseSummary() { @@ -222,8 +253,14 @@ func (r *Reporter) AddGRPCRequest(req *model.GRPCRequest) { Metadata: util.CloneStringSliceMap(req.Metadata), } - if r.cfg.DumpPayload { - request.Message = util.CloneMap(req.Message) + if req.Message != nil { + if r.cfg.DumpPayload { + request.Message = util.CloneMap(req.Message) + } else { + request.Message = map[string]any{ + dumpDisabled: nil, + } + } } r.report.Summary.Request = &model.TestExecutionRequestSummary{ @@ -250,7 +287,7 @@ func (r *Reporter) AddGRPCResponseMetadata(metadata map[string][]string) { func selectMetadata( actual map[string][]string, - expected map[string][]string, + expected map[string][]matcher.String, ) map[string][]string { if len(expected) == 0 { return nil @@ -275,14 +312,16 @@ func selectMetadata( } func (r *Reporter) AddGRPCResponseMessage(message map[string]any) { - if !r.cfg.DumpPayload { - return - } - r.ensureNotFinalized() - r.ensureGRPCResponseSummary() - m := util.CloneMap(message) - r.report.Summary.Response.GRPC.Message = &m + switch { + case len(message) == 0: + r.report.Summary.Response.GRPC.Message = map[string]any{"": nil} + case !r.cfg.DumpPayload: + r.report.Summary.Response.GRPC.Message = map[string]any{dumpDisabled: nil} + default: + m := util.CloneMap(message) + r.report.Summary.Response.GRPC.Message = m + } } diff --git a/execute/worker/reporter/reporter_test.go b/execute/worker/reporter/reporter_test.go index 0223f57..3de64dd 100644 --- a/execute/worker/reporter/reporter_test.go +++ b/execute/worker/reporter/reporter_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" ) func TestNew(t *testing.T) { @@ -79,16 +80,17 @@ func TestReporterSetError(t *testing.T) { } mustPanic(t, func() { - r.AddDeviation( - &model.TestExecutionDeviation{}, - ) + r.AddDeviation(&model.TestExecutionDeviation{}) + }) + + mustPanic(t, func() { + r.AddPayloadDeviation(&model.PayloadDeviation{}) }) } func TestReporterFinalize(t *testing.T) { tests := []struct { - name string - + name string addDeviation bool expected model.ExecutionStatus }{ @@ -188,29 +190,76 @@ func TestReporterAddDeviation(t *testing.T) { } func TestReporterAddPayloadDeviation(t *testing.T) { - deviation := &model.TestExecutionDeviation{ - Field: "body", - Expected: "expected payload", - Actual: "actual payload", - Message: "payload differs", - } - tests := []struct { name string dumpPayload bool + expected *matcher.String + actual []byte - expectedExpected string - expectedActual string + wantExpected string + wantActual string }{ { name: "payload disabled", + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "expected payload", + }, + actual: []byte("actual payload"), + wantExpected: "", + wantActual: "", }, { - name: "payload enabled", - dumpPayload: true, - expectedExpected: deviation.Expected, - expectedActual: deviation.Actual, + name: "payload enabled", + dumpPayload: true, + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: "expected payload", + }, + actual: []byte("actual payload"), + wantExpected: "expected payload", + wantActual: "actual payload", + }, + { + name: "nonempty matcher with dumping disabled", + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + actual: []byte("actual payload"), + wantExpected: "", + wantActual: "", + }, + { + name: "nonempty matcher with dumping enabled", + dumpPayload: true, + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + actual: []byte("actual payload"), + wantExpected: "nonempty", + wantActual: "actual payload", + }, + { + name: "empty actual payload", + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + wantExpected: "", + }, + { + name: "empty actual payload with dumping enabled", + dumpPayload: true, + expected: &matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + }, + wantExpected: "nonempty", + }, + { + name: "nil expected matcher", + actual: []byte("actual payload"), + wantExpected: "", + wantActual: "", }, } @@ -225,45 +274,52 @@ func TestReporterAddPayloadDeviation(t *testing.T) { r.AddPayloadDeviation(nil) - r.AddPayloadDeviation(deviation) + r.AddPayloadDeviation(&model.PayloadDeviation{ + Field: "body", + Expected: tt.expected, + Actual: tt.actual, + Message: "payload differs", + }) + + deviations := r.Result().Summary.Deviations - if len(r.Result().Summary.Deviations) != 1 { + if len(deviations) != 1 { t.Fatalf( "expected 1 deviation, got %d", - len(r.Result().Summary.Deviations), + len(deviations), ) } - actual := r.Result().Summary.Deviations[0] + actual := deviations[0] - if actual.Field != deviation.Field { + if actual.Field != "body" { t.Errorf( "expected field %q, got %q", - deviation.Field, + "body", actual.Field, ) } - if actual.Message != deviation.Message { + if actual.Message != "payload differs" { t.Errorf( "expected message %q, got %q", - deviation.Message, + "payload differs", actual.Message, ) } - if actual.Expected != tt.expectedExpected { + if actual.Expected != tt.wantExpected { t.Errorf( "expected Expected %q, got %q", - tt.expectedExpected, + tt.wantExpected, actual.Expected, ) } - if actual.Actual != tt.expectedActual { + if actual.Actual != tt.wantActual { t.Errorf( "expected Actual %q, got %q", - tt.expectedActual, + tt.wantActual, actual.Actual, ) } @@ -281,7 +337,9 @@ func TestReporterAddHTTPRequest(t *testing.T) { expectedBodyJSON string }{ { - name: "payload disabled", + name: "payload disabled", + expectedBody: "", + expectedBodyJSON: "", }, { name: "payload enabled", @@ -328,6 +386,10 @@ func TestReporterAddHTTPRequest(t *testing.T) { r.AddHTTPRequest(req) + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + actual := r.Result().Summary.Request.HTTP if actual == nil { @@ -355,7 +417,7 @@ func TestReporterAddHTTPRequest(t *testing.T) { map[string][]string(req.Header), ) { t.Errorf( - "expected headers %#+v, got %#+v", + "expected headers %+v, got %+v", req.Header, actual.Headers, ) @@ -380,14 +442,46 @@ func TestReporterAddHTTPRequest(t *testing.T) { req.Header["X-Test"][0] = "changed" if actual.Headers["X-Test"][0] != "one" { - t.Error( - "stored headers changed with source", - ) + t.Error("stored headers changed with source") } }) } } +func TestReporterAddHTTPRequestWithoutBody(t *testing.T) { + spec := &model.TestSpec{ + Request: model.RequestSpec{ + HTTP: &model.HTTPRequest{}, + }, + } + + r := newReporterForTest( + &Config{}, + spec, + ) + + req, err := http.NewRequest( + http.MethodGet, + "http://example.com/resource", + nil, + ) + if err != nil { + t.Fatal(err) + } + + r.AddHTTPRequest(req) + + actual := r.Result().Summary.Request.HTTP + + if actual.Body != "" || actual.BodyJSON != "" { + t.Errorf( + "expected omitted body fields, got body=%q body_json=%q", + actual.Body, + actual.BodyJSON, + ) + } +} + func TestReporterAddHTTPResponseStatus(t *testing.T) { r := newReporterForTest( &Config{}, @@ -414,10 +508,19 @@ func TestReporterAddHTTPResponseStatus(t *testing.T) { func TestReporterAddHTTPResponseHeaders(t *testing.T) { spec := &model.TestSpec{ Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{ - Headers: map[string][]string{ - "X-Included": {"expected"}, - "X-Missing": {"expected"}, + HTTP: &model.HTTPResponsePattern{ + Headers: map[string][]matcher.String{ + "X-Included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "X-Missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, }, }, }, @@ -452,18 +555,31 @@ func TestReporterAddHTTPResponseHeaders(t *testing.T) { headers["X-Included"][0] = "changed" if actual["X-Included"][0] != "actual-1" { - t.Error( - "stored headers changed with source", - ) + t.Error("stored headers changed with source") } } func TestSelectHeaders(t *testing.T) { + equals := func(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } + } + + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + nonempty := matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + } + tests := []struct { name string actual http.Header - expected map[string][]string + expected map[string][]matcher.String want map[string][]string }{ @@ -478,8 +594,8 @@ func TestSelectHeaders(t *testing.T) { actual: http.Header{ "X-Test": {"value"}, }, - expected: map[string][]string{ - "X-Missing": {"expected"}, + expected: map[string][]matcher.String{ + "X-Missing": {equals("expected")}, }, }, { @@ -489,16 +605,52 @@ func TestSelectHeaders(t *testing.T) { "X-Two": {"2"}, "X-Other": {"other"}, }, - expected: map[string][]string{ - "X-One": {"expected"}, - "X-Two": {"expected"}, - "X-Missing": {"expected"}, + expected: map[string][]matcher.String{ + "X-One": {equals("expected")}, + "X-Two": {equals("expected")}, + "X-Missing": {equals("expected")}, }, want: map[string][]string{ "X-One": {"1"}, "X-Two": {"2"}, }, }, + { + name: "exists matcher", + actual: http.Header{ + "X-Test": {""}, + }, + expected: map[string][]matcher.String{ + "X-Test": {exists}, + }, + want: map[string][]string{ + "X-Test": {""}, + }, + }, + { + name: "nonempty matcher", + actual: http.Header{ + "X-Test": {"value"}, + }, + expected: map[string][]matcher.String{ + "X-Test": {nonempty}, + }, + want: map[string][]string{ + "X-Test": {"value"}, + }, + }, + { + name: "case insensitive header lookup", + actual: http.Header{ + "X-Request-Id": {"123"}, + }, + expected: map[string][]matcher.String{ + "x-request-id": {nonempty}, + }, + want: map[string][]string{ + "x-request-id": {"123"}, + }, + }, } for _, tt := range tests { @@ -520,113 +672,138 @@ func TestSelectHeaders(t *testing.T) { } func TestReporterAddHTTPResponseBody(t *testing.T) { - t.Run("payload disabled", func(t *testing.T) { - r := newReporterForTest( - &Config{}, - &model.TestSpec{}, - ) - - r.AddHTTPResponseBody("body") + tests := []struct { + name string + dumpPayload bool + body []byte + want string + }{ + { + name: "payload disabled", + body: []byte("body"), + want: "", + }, + { + name: "payload enabled", + dumpPayload: true, + body: []byte("body"), + want: "body", + }, + { + name: "empty body with dumping disabled", + body: []byte{}, + }, + { + name: "empty body with dumping enabled", + dumpPayload: true, + body: []byte{}, + }, + } - if r.Result().Summary.Response != nil { - t.Fatal( - "expected response summary not to be created", + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, ) - } - }) - t.Run("payload enabled", func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: true, - }, - &model.TestSpec{}, - ) - - r.AddHTTPResponseBody("") + r.AddHTTPResponseBody(tt.body) - response := r.Result().Summary.Response - - if response == nil || response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } + response := r.Result().Summary.Response - if response.HTTP.Body == nil { - t.Fatal( - "expected non-nil body pointer", - ) - } + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } - if *response.HTTP.Body != "" { - t.Errorf( - "expected empty body, got %q", - *response.HTTP.Body, - ) - } - }) + if response.HTTP.Body != tt.want { + t.Errorf( + "expected body %q, got %q", + tt.want, + response.HTTP.Body, + ) + } + }) + } } func TestReporterAddHTTPResponseBodyJSON(t *testing.T) { - t.Run("payload disabled", func(t *testing.T) { - r := newReporterForTest( - &Config{}, - &model.TestSpec{}, - ) - - r.AddHTTPResponseBodyJSON("{}") + tests := []struct { + name string + dumpPayload bool + body []byte + want string + }{ + { + name: "payload disabled", + body: []byte(`{"name":"test"}`), + want: "", + }, + { + name: "payload enabled", + dumpPayload: true, + body: []byte(`{"name":"test"}`), + want: `{"name":"test"}`, + }, + { + name: "empty body with dumping disabled", + body: []byte{}, + }, + { + name: "empty body with dumping enabled", + dumpPayload: true, + body: []byte{}, + }, + } - if r.Result().Summary.Response != nil { - t.Fatal( - "expected response summary not to be created", + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, ) - } - }) - t.Run("payload enabled", func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: true, - }, - &model.TestSpec{}, - ) + r.AddHTTPResponseBodyJSON(tt.body) - r.AddHTTPResponseBodyJSON("") + response := r.Result().Summary.Response - response := r.Result().Summary.Response - - if response == nil || response.HTTP == nil { - t.Fatal("expected HTTP response summary") - } - - if response.HTTP.BodyJSON == nil { - t.Fatal( - "expected non-nil JSON body pointer", - ) - } + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } - if *response.HTTP.BodyJSON != "" { - t.Errorf( - "expected empty JSON body, got %q", - *response.HTTP.BodyJSON, - ) - } - }) + if response.HTTP.BodyJSON != tt.want { + t.Errorf( + "expected JSON body %q, got %q", + tt.want, + response.HTTP.BodyJSON, + ) + } + }) + } } func TestReporterAddGRPCRequest(t *testing.T) { tests := []struct { name string - dumpPayload bool - expectMessage bool + dumpPayload bool + wantMessage map[string]any }{ { name: "payload disabled", + wantMessage: map[string]any{ + "": nil, + }, }, { - name: "payload enabled", - dumpPayload: true, - expectMessage: true, + name: "payload enabled", + dumpPayload: true, + wantMessage: map[string]any{ + "name": "test", + }, }, } @@ -653,6 +830,10 @@ func TestReporterAddGRPCRequest(t *testing.T) { r.AddGRPCRequest(req) + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + actual := r.Result().Summary.Request.GRPC if actual == nil { @@ -694,20 +875,13 @@ func TestReporterAddGRPCRequest(t *testing.T) { ) } - if tt.expectMessage { - if !reflect.DeepEqual( - actual.Message, - req.Message, - ) { - t.Errorf( - "expected message %+v, got %+v", - req.Message, - actual.Message, - ) - } - } else if actual.Message != nil { + if !reflect.DeepEqual( + actual.Message, + tt.wantMessage, + ) { t.Errorf( - "expected nil message, got %+v", + "expected message %+v, got %+v", + tt.wantMessage, actual.Message, ) } @@ -716,21 +890,38 @@ func TestReporterAddGRPCRequest(t *testing.T) { req.Message["name"] = "changed" if actual.Metadata["x-test"][0] != "one" { - t.Error( - "stored metadata changed with source", - ) + t.Error("stored metadata changed with source") } - if tt.expectMessage && + if tt.dumpPayload && actual.Message["name"] != "test" { - t.Error( - "stored message changed with source", - ) + t.Error("stored message changed with source") } }) } } +func TestReporterAddGRPCRequestWithoutMessage(t *testing.T) { + r := newReporterForTest( + &Config{}, + &model.TestSpec{}, + ) + + r.AddGRPCRequest(&model.GRPCRequest{ + Service: "example.Service", + Method: "Create", + }) + + actual := r.Result().Summary.Request.GRPC + + if actual.Message != nil { + t.Errorf( + "expected nil message, got %+v", + actual.Message, + ) + } +} + func TestReporterAddGRPCResponseStatus(t *testing.T) { r := newReporterForTest( &Config{}, @@ -757,10 +948,19 @@ func TestReporterAddGRPCResponseStatus(t *testing.T) { func TestReporterAddGRPCResponseMetadata(t *testing.T) { spec := &model.TestSpec{ Expect: model.ExpectSpec{ - GRPC: &model.GRPCResponse{ - Metadata: map[string][]string{ - "x-included": {"expected"}, - "x-missing": {"expected"}, + GRPC: &model.GRPCResponsePattern{ + Metadata: map[string][]matcher.String{ + "x-included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "x-missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, }, }, }, @@ -799,18 +999,31 @@ func TestReporterAddGRPCResponseMetadata(t *testing.T) { metadata["x-included"][0] = "changed" if actual["x-included"][0] != "actual-1" { - t.Error( - "stored metadata changed with source", - ) + t.Error("stored metadata changed with source") } } func TestSelectMetadata(t *testing.T) { + equals := func(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } + } + + exists := matcher.String{ + Operator: matcher.StringMatchOperatorExists, + } + + nonempty := matcher.String{ + Operator: matcher.StringMatchOperatorNonEmpty, + } + tests := []struct { name string actual map[string][]string - expected map[string][]string + expected map[string][]matcher.String want map[string][]string }{ @@ -825,8 +1038,8 @@ func TestSelectMetadata(t *testing.T) { actual: map[string][]string{ "x-test": {"value"}, }, - expected: map[string][]string{ - "x-missing": {"expected"}, + expected: map[string][]matcher.String{ + "x-missing": {equals("expected")}, }, }, { @@ -836,16 +1049,40 @@ func TestSelectMetadata(t *testing.T) { "x-two": {"2"}, "x-other": {"other"}, }, - expected: map[string][]string{ - "x-one": {"expected"}, - "x-two": {"expected"}, - "x-missing": {"expected"}, + expected: map[string][]matcher.String{ + "x-one": {equals("expected")}, + "x-two": {equals("expected")}, + "x-missing": {equals("expected")}, }, want: map[string][]string{ "x-one": {"1"}, "x-two": {"2"}, }, }, + { + name: "exists matcher", + actual: map[string][]string{ + "x-test": {""}, + }, + expected: map[string][]matcher.String{ + "x-test": {exists}, + }, + want: map[string][]string{ + "x-test": {""}, + }, + }, + { + name: "nonempty matcher", + actual: map[string][]string{ + "x-test": {"value"}, + }, + expected: map[string][]matcher.String{ + "x-test": {nonempty}, + }, + want: map[string][]string{ + "x-test": {"value"}, + }, + }, } for _, tt := range tests { @@ -867,102 +1104,87 @@ func TestSelectMetadata(t *testing.T) { } func TestReporterAddGRPCResponseMessage(t *testing.T) { - t.Run("payload disabled", func(t *testing.T) { - r := newReporterForTest( - &Config{}, - &model.TestSpec{}, - ) + tests := []struct { + name string - r.AddGRPCResponseMessage( - map[string]any{ + dumpPayload bool + message map[string]any + want map[string]any + }{ + { + name: "payload disabled", + message: map[string]any{ "name": "test", }, - ) - - if r.Result().Summary.Response != nil { - t.Fatal( - "expected response summary not to be created", - ) - } - }) - - t.Run("payload enabled", func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: true, + want: map[string]any{ + "": nil, }, - &model.TestSpec{}, - ) - - message := map[string]any{ - "name": "test", - } - - r.AddGRPCResponseMessage(message) - - response := r.Result().Summary.Response - - if response == nil || response.GRPC == nil { - t.Fatal("expected gRPC response summary") - } - - if response.GRPC.Message == nil { - t.Fatal( - "expected non-nil message pointer", - ) - } - - if !reflect.DeepEqual( - *response.GRPC.Message, - message, - ) { - t.Errorf( - "expected message %+v, got %+v", - message, - *response.GRPC.Message, - ) - } - - message["name"] = "changed" + }, + { + name: "payload enabled", + dumpPayload: true, + message: map[string]any{ + "name": "test", + }, + want: map[string]any{ + "name": "test", + }, + }, + { + name: "empty message with dumping disabled", + message: map[string]any{}, + want: map[string]any{ + "": nil, + }, + }, + { + name: "empty message with dumping enabled", + dumpPayload: true, + message: map[string]any{}, + want: map[string]any{ + "": nil, + }, + }, + } - if (*response.GRPC.Message)["name"] != "test" { - t.Error( - "stored message changed with source", + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, ) - } - }) - t.Run("explicit empty message", func(t *testing.T) { - r := newReporterForTest( - &Config{ - DumpPayload: true, - }, - &model.TestSpec{}, - ) + r.AddGRPCResponseMessage(tt.message) - r.AddGRPCResponseMessage( - map[string]any{}, - ) + response := r.Result().Summary.Response - response := r.Result().Summary.Response + if response == nil || response.GRPC == nil { + t.Fatal("expected gRPC response summary") + } - if response == nil || response.GRPC == nil { - t.Fatal("expected gRPC response summary") - } + if !reflect.DeepEqual( + response.GRPC.Message, + tt.want, + ) { + t.Errorf( + "expected message %+v, got %+v", + tt.want, + response.GRPC.Message, + ) + } - if response.GRPC.Message == nil { - t.Fatal( - "expected non-nil message pointer", - ) - } + if len(tt.message) > 0 { + tt.message["name"] = "changed" - if len(*response.GRPC.Message) != 0 { - t.Errorf( - "expected empty message, got %+v", - *response.GRPC.Message, - ) - } - }) + if tt.dumpPayload && + response.GRPC.Message["name"] != "test" { + t.Error("stored message changed with source") + } + } + }) + } } func newReporterForTest( diff --git a/execute/worker/worker_test.go b/execute/worker/worker_test.go index 245189a..012da56 100644 --- a/execute/worker/worker_test.go +++ b/execute/worker/worker_test.go @@ -597,7 +597,7 @@ func newHTTPTestJob( }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{ + HTTP: &model.HTTPResponsePattern{ StatusCode: expectedStatus, }, }, diff --git a/internal/util/clone.go b/internal/util/clone.go index 7f1761e..91f90ab 100644 --- a/internal/util/clone.go +++ b/internal/util/clone.go @@ -4,6 +4,8 @@ import ( "encoding/json" "net/http" "net/url" + + "github.com/e2engine/core/model/matcher" ) func CloneStruct[T any](src T) (T, error) { @@ -111,3 +113,14 @@ func CloneStringSlice(value []string) []string { return result } + +func CloneStringMatcherSlice(value []matcher.String) []matcher.String { + if value == nil { + return nil + } + + result := make([]matcher.String, len(value)) + copy(result, value) + + return result +} diff --git a/internal/util/json.go b/internal/util/json.go index 2f94785..1e101ef 100644 --- a/internal/util/json.go +++ b/internal/util/json.go @@ -6,16 +6,16 @@ import ( "reflect" ) -func CompactJSON(raw json.RawMessage) string { +func CompactJSON(raw json.RawMessage) []byte { if len(raw) == 0 { - return "" + return nil } var buf bytes.Buffer if err := json.Compact(&buf, raw); err != nil { - return string(raw) + return raw } - return buf.String() + return buf.Bytes() } func IsJSONEqual(expected, actual []byte) (bool, error) { diff --git a/internal/util/json_test.go b/internal/util/json_test.go index e2ecad2..91544d6 100644 --- a/internal/util/json_test.go +++ b/internal/util/json_test.go @@ -63,7 +63,7 @@ func TestCompactJSON(t *testing.T) { t.Run(tt.name, func(t *testing.T) { actual := CompactJSON(tt.input) - if actual != tt.expected { + if string(actual) != tt.expected { t.Fatalf( "expected %q, got %q", tt.expected, diff --git a/model/grpc.go b/model/grpc.go index 50975c3..6da7837 100644 --- a/model/grpc.go +++ b/model/grpc.go @@ -1,5 +1,7 @@ package model +import "github.com/e2engine/core/model/matcher" + type GRPCRequest struct { Target string `json:"target" yaml:"target" validate:"networkaddress"` Service string `json:"service" yaml:"service" validate:"min(1)"` @@ -9,18 +11,30 @@ type GRPCRequest struct { } type GRPCRequestPattern struct { - Service string `json:"service" yaml:"service" validate:"min(1)"` - Method string `json:"method" yaml:"method" validate:"min(1)"` - Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - // Message is a pointer to a map to allow distinguishing between an empty message and no message. - // message: {} means "empty message", while no message field means "will be skipped in matching". - Message *map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + Service string `json:"service" yaml:"service" validate:"min(1)"` + Method string `json:"method" yaml:"method" validate:"min(1)"` + Metadata map[string][]matcher.String `json:"metadata,omitempty" yaml:"metadata,omitempty" validateElem:"stringmatchers"` + + // Message is nil when message matching should be skipped. + // A non-nil matcher defines how the protobuf message is matched. + // For equals, Value contains the protobuf message encoded as JSON. + Message *matcher.GRPCMessage `json:"message,omitempty" yaml:"message,omitempty" validate:"grpcmessagematcher"` } +// GRPCResponse describes observed gRPC response or a Fixture Then response. +// Validation is needed for Fixture.Then validation. type GRPCResponse struct { Status string `json:"status" yaml:"status" validate:"oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` Metadata map[string][]string `json:"metadata,omitempty" yaml:"metadata,omitempty"` - // Message is a pointer to a map to allow distinguishing between an empty message and no message. - // message: {} means "empty message", while no message field means "will be skipped in matching". - Message *map[string]any `json:"message,omitempty" yaml:"message,omitempty"` + Message map[string]any `json:"message,omitempty" yaml:"message,omitempty"` +} + +type GRPCResponsePattern struct { + Status string `json:"status" yaml:"status" validate:"oneof(OK,Canceled,Unknown,InvalidArgument,DeadlineExceeded,NotFound,AlreadyExists,PermissionDenied,ResourceExhausted,FailedPrecondition,Aborted,OutOfRange,Unimplemented,Internal,Unavailable,DataLoss,Unauthenticated)"` + Metadata map[string][]matcher.String `json:"metadata,omitempty" yaml:"metadata,omitempty" validateElem:"stringmatchers"` + + // Message is nil when message matching should be skipped. + // A non-nil matcher defines how the protobuf message is matched. + // For equals, Value contains the protobuf message encoded as JSON. + Message *matcher.GRPCMessage `json:"message,omitempty" yaml:"message,omitempty" validate:"grpcmessagematcher"` } diff --git a/model/http.go b/model/http.go index c9a1fa4..4726598 100644 --- a/model/http.go +++ b/model/http.go @@ -6,7 +6,10 @@ import ( "strings" "github.com/ygrebnov/errorc" + modellib "github.com/ygrebnov/model" + "github.com/e2engine/core/model/matcher" + "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" ) @@ -20,7 +23,7 @@ type HTTPRequest struct { } func (h *HTTPRequest) Validate() error { - u, err := url.Parse(h.URL) + u, err := url.ParseRequestURI(h.URL) if err != nil { return errorc.With( errorc.New("invalid HTTP request URL"), @@ -28,8 +31,7 @@ func (h *HTTPRequest) Validate() error { ) } - if u.Scheme != "http" && - u.Scheme != "https" { + if u.Scheme != "http" && u.Scheme != "https" { return errorc.New( "HTTP request URL scheme must be http or https", ) @@ -53,14 +55,17 @@ func (h *HTTPRequest) Validate() error { // HTTPRequestPattern is used to match an HTTP request against a pattern. // Unlike HTTPRequest, it does not describe an outgoing request. type HTTPRequestPattern struct { - Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` - Path string `json:"path" yaml:"path" validate:"min(1)"` - Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` - Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - // Body is pointer to string to distinguish between empty body and no body. - // body: "" means empty body, while no body field means "will be skipped in matching". - Body *string `json:"body,omitempty" yaml:"body,omitempty"` - BodyJSON *string `json:"body_json,omitempty" yaml:"body_json,omitempty"` + Method string `json:"method" yaml:"method" validate:"oneof(GET,POST,PUT,DELETE,PATCH,OPTIONS,HEAD)"` + Path string `json:"path" yaml:"path" validate:"min(1)"` + Query map[string][]string `json:"query,omitempty" yaml:"query,omitempty"` + Headers map[string][]matcher.String `json:"headers,omitempty" yaml:"headers,omitempty" validateElem:"stringmatchers"` + // Body is nil when body matching should be skipped. + // A non-nil matcher defines how the body is matched, including explicit + // matching of an empty body. + Body *matcher.String `json:"body,omitempty" yaml:"body,omitempty" validate:"stringmatcher"` + // BodyJSON matches the response body as JSON. For the equals operator, + // Value must contain valid JSON and comparison is JSON-semantic. + BodyJSON *matcher.String `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"stringmatcher,validjson"` } func (h *HTTPRequestPattern) Validate() error { @@ -78,36 +83,68 @@ func (h *HTTPRequestPattern) Validate() error { ) } - if h.BodyJSON != nil && !json.Valid([]byte(*h.BodyJSON)) { - return errorc.New( - "HTTP response body_json is not valid JSON", - ) - } - return nil } +// HTTPResponse describes HTTP response observed during execution or a Fixture Then response. +// Validation is needed for Fixture.Then validation. type HTTPResponse struct { StatusCode int `json:"status_code" yaml:"status_code" validate:"min(100),max(599)"` Headers map[string][]string `json:"headers,omitempty" yaml:"headers,omitempty"` - // Body is pointer to string to distinguish between empty body and no body. - // body: "" means empty body, while no body field means "will be skipped in matching". - Body *string `json:"body,omitempty" yaml:"body,omitempty"` - BodyJSON *string `json:"body_json,omitempty" yaml:"body_json,omitempty"` + Body string `json:"body,omitempty" yaml:"body,omitempty"` + BodyJSON string `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"omitempty,validjson"` } func (h *HTTPResponse) Validate() error { - if h.Body != nil && h.BodyJSON != nil { + if h.Body != "" && h.BodyJSON != "" { return errorc.New( "HTTP response cannot have both body and body_json set", ) } - if h.BodyJSON != nil && !json.Valid([]byte(*h.BodyJSON)) { + return nil +} + +// HTTPResponsePattern is used to match an HTTP response against a pattern. +type HTTPResponsePattern struct { + StatusCode int `json:"status_code" yaml:"status_code" validate:"min(100),max(599)"` + Headers map[string][]matcher.String `json:"headers,omitempty" yaml:"headers,omitempty" validateElem:"stringmatchers"` + // Body is nil when body matching should be skipped. + // A non-nil matcher defines how the body is matched, including explicit + // matching of an empty body. + Body *matcher.String `json:"body,omitempty" yaml:"body,omitempty" validate:"stringmatcher"` + // BodyJSON matches the response body as JSON. For the equals operator, + // Value must contain valid JSON and comparison is JSON-semantic. + BodyJSON *matcher.String `json:"body_json,omitempty" yaml:"body_json,omitempty" validate:"stringmatcher,validjson"` +} + +func (h *HTTPResponsePattern) Validate() error { + if h.Body != nil && h.BodyJSON != nil { return errorc.New( - "HTTP response body_json is not valid JSON", + "HTTP response pattern cannot have both body and body_json set", ) } return nil } + +func getStringMatcherValidJSONRule() (modellib.Rule, error) { + return modellib.NewRule[*matcher.String]("validjson", func(value *matcher.String, _ ...string) error { + if value == nil { + return nil + } + if value.Operator == matcher.StringMatchOperatorEquals { + if !json.Valid([]byte(value.Value)) { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "value must contain valid JSON", + ), + ) + } + } + + return nil + }) +} diff --git a/model/matcher/doc.go b/model/matcher/doc.go new file mode 100644 index 0000000..bd8f4cd --- /dev/null +++ b/model/matcher/doc.go @@ -0,0 +1,10 @@ +// Package matcher defines declarative matchers used by E2Engine specifications. +// +// Matchers have a compact scalar form for exact equality and an expanded object +// form for other operators. For example, the YAML/JSON string `"foo"` is +// unmarshaled as String{Operator: StringMatchOperatorEquals, Value: "foo"}, +// while {"operator":"nonempty"} is unmarshaled as a nonempty matcher. Exact +// matchers are marshaled back to their compact scalar form; other operators use +// the expanded form. GRPCMessage follows the same convention, with its exact +// value represented as a JSON string containing the protobuf message. +package matcher diff --git a/model/matcher/grpc_message.go b/model/matcher/grpc_message.go new file mode 100644 index 0000000..243cbb0 --- /dev/null +++ b/model/matcher/grpc_message.go @@ -0,0 +1,154 @@ +package matcher + +import ( + "encoding/json" + + "github.com/ygrebnov/errorc" + modellib "github.com/ygrebnov/model" + "gopkg.in/yaml.v3" + + "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/pkg/keys" +) + +type GRPCMessage struct { + Operator GRPCMessageMatchOperator `json:"operator" yaml:"operator"` + Value string `json:"value,omitempty" yaml:"value,omitempty"` +} + +func (m GRPCMessage) String() string { + if m.Operator == GRPCMessageMatchOperatorEquals { + return m.Value + } + + return string(m.Operator) +} + +type GRPCMessageMatchOperator string + +const ( + GRPCMessageMatchOperatorEquals GRPCMessageMatchOperator = "equals" + GRPCMessageMatchOperatorNonEmpty GRPCMessageMatchOperator = "nonempty" +) + +func (m GRPCMessage) MarshalJSON() ([]byte, error) { + if m.Operator == GRPCMessageMatchOperatorEquals { + return json.Marshal(m.Value) + } + + type alias GRPCMessage + return json.Marshal(alias(m)) +} + +func (m *GRPCMessage) UnmarshalJSON(data []byte) error { + var value string + if err := json.Unmarshal(data, &value); err == nil { + *m = GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: value, + } + return nil + } + + type alias GRPCMessage + var matcher alias + if err := json.Unmarshal(data, &matcher); err != nil { + return errorc.With( + errors.ErrInvalidGRPCMessageMatcher, + errorc.String(keys.Validation, "gRPC message matcher must be a string or object"), + errorc.Error(keys.Cause, err), + ) + } + + *m = GRPCMessage(matcher) + return nil +} + +func (m GRPCMessage) MarshalYAML() (any, error) { + if m.Operator == GRPCMessageMatchOperatorEquals { + return m.Value, nil + } + + type alias GRPCMessage + return alias(m), nil +} + +func (m *GRPCMessage) UnmarshalYAML(node *yaml.Node) error { + if node.Kind == yaml.ScalarNode && + node.Tag == "!!str" { + *m = GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: node.Value, + } + return nil + } + + if node.Kind != yaml.MappingNode { + return errorc.With( + errors.ErrInvalidGRPCMessageMatcher, + errorc.String(keys.Validation, "gRPC message matcher must be a string or object"), + ) + } + + type alias GRPCMessage + var matcher alias + if err := node.Decode(&matcher); err != nil { + return err + } + + *m = GRPCMessage(matcher) + return nil +} + +func GetGRPCMessageMatcherRule() (modellib.Rule, error) { + return modellib.NewRule[*GRPCMessage]( + "grpcmessagematcher", + func(value *GRPCMessage, _ ...string) error { + if value == nil { + return nil + } + return validateGRPCMessageMatcher(*value) + }, + ) +} + +func validateGRPCMessageMatcher(value GRPCMessage) error { + switch value.Operator { + case GRPCMessageMatchOperatorEquals: + if !json.Valid([]byte(value.Value)) { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "value must contain valid JSON", + ), + ) + } + return nil + + case GRPCMessageMatchOperatorNonEmpty: + if value.Value != "" { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "value must be empty when operator is 'nonempty'", + ), + ) + } + return nil + + default: + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.MatcherOperator, + string(value.Operator), + ), + errorc.String( + keys.Validation, + "invalid operator", + ), + ) + } +} diff --git a/model/matcher/grpc_message_test.go b/model/matcher/grpc_message_test.go new file mode 100644 index 0000000..c88cce3 --- /dev/null +++ b/model/matcher/grpc_message_test.go @@ -0,0 +1,487 @@ +package matcher + +import ( + "encoding/json" + "reflect" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestGRPCMessageMarshalJSON(t *testing.T) { + tests := []struct { + name string + matcher GRPCMessage + want string + }{ + { + name: "equals", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + want: `"{\"id\":\"user-123\",\"name\":\"John\"}"`, + }, + { + name: "equals empty message", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + want: `"{}"`, + }, + { + name: "nonempty", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + want: `{"operator":"nonempty"}`, + }, + { + name: "expanded matcher preserves value", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + Value: `{"id":"user-123"}`, + }, + want: `{"operator":"nonempty","value":"{\"id\":\"user-123\"}"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := json.Marshal(tt.matcher) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + if string(got) != tt.want { + t.Errorf("Marshal() = %s, want %s", got, tt.want) + } + }) + } +} + +func TestGRPCMessageUnmarshalJSON(t *testing.T) { + tests := []struct { + name string + data string + want GRPCMessage + }{ + { + name: "equals", + data: `"{\"id\":\"user-123\",\"name\":\"John\"}"`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + }, + { + name: "equals empty message", + data: `"{}"`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + }, + { + name: "nonempty", + data: `{"operator":"nonempty"}`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + }, + { + name: "expanded equals", + data: `{"operator":"equals","value":"{\"id\":\"user-123\"}"}`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123"}`, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got GRPCMessage + if err := json.Unmarshal([]byte(tt.data), &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Unmarshal() = %#v, want %#v", got, tt.want) + } + }) + } +} + +func TestGRPCMessageUnmarshalJSONInvalid(t *testing.T) { + tests := []struct { + name string + data string + }{ + { + name: "number", + data: `123`, + }, + { + name: "boolean", + data: `true`, + }, + { + name: "array", + data: `["value"]`, + }, + { + name: "invalid JSON", + data: `{`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var matcher GRPCMessage + if err := json.Unmarshal([]byte(tt.data), &matcher); err == nil { + t.Fatal("Unmarshal() error = nil, want error") + } + }) + } +} + +func TestGRPCMessageMarshalYAML(t *testing.T) { + tests := []struct { + name string + matcher GRPCMessage + want string + }{ + { + name: "equals", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + want: `'{"id":"user-123","name":"John"}'` + "\n", + }, + { + name: "equals empty message", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + want: "'{}'\n", + }, + { + name: "nonempty", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + want: "operator: nonempty\n", + }, + { + name: "expanded matcher preserves value", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + Value: `{"id":"user-123"}`, + }, + want: "operator: nonempty\nvalue: '{\"id\":\"user-123\"}'\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := yaml.Marshal(tt.matcher) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + if string(got) != tt.want { + t.Errorf( + "Marshal() = %q, want %q", + string(got), + tt.want, + ) + } + }) + } +} + +func TestGRPCMessageUnmarshalYAML(t *testing.T) { + tests := []struct { + name string + data string + want GRPCMessage + }{ + { + name: "equals", + data: `message: '{"id":"user-123","name":"John"}'`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + }, + { + name: "equals empty message", + data: `message: '{}'`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + }, + { + name: "nonempty", + data: ` +message: + operator: nonempty +`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + }, + { + name: "expanded equals", + data: ` +message: + operator: equals + value: '{"id":"user-123"}' +`, + want: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123"}`, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var document struct { + Message GRPCMessage `yaml:"message"` + } + + if err := yaml.Unmarshal([]byte(tt.data), &document); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(document.Message, tt.want) { + t.Errorf( + "Unmarshal() = %#v, want %#v", + document.Message, + tt.want, + ) + } + }) + } +} + +func TestGRPCMessageUnmarshalYAMLInvalid(t *testing.T) { + tests := []struct { + name string + data string + }{ + { + name: "integer", + data: "123\n", + }, + { + name: "boolean", + data: "true\n", + }, + { + name: "sequence", + data: "- value\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var matcher GRPCMessage + if err := yaml.Unmarshal([]byte(tt.data), &matcher); err == nil { + t.Fatal("Unmarshal() error = nil, want error") + } + }) + } +} + +func TestGRPCMessageRoundTripJSON(t *testing.T) { + values := []GRPCMessage{ + { + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + { + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + { + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + } + + for _, want := range values { + data, err := json.Marshal(want) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + var got GRPCMessage + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("round trip = %#v, want %#v", got, want) + } + } +} + +func TestGRPCMessageRoundTripYAML(t *testing.T) { + values := []GRPCMessage{ + { + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123","name":"John"}`, + }, + { + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + { + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + } + + for _, want := range values { + data, err := yaml.Marshal(want) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + var got GRPCMessage + if err := yaml.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf("round trip = %#v, want %#v", got, want) + } + } +} + +func TestGRPCMessageString(t *testing.T) { + tests := []struct { + name string + matcher GRPCMessage + want string + }{ + { + name: "equals", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123"}`, + }, + want: `{"id":"user-123"}`, + }, + { + name: "equals empty message", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + want: `{}`, + }, + { + name: "nonempty", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + want: "nonempty", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.matcher.String(); got != tt.want { + t.Errorf( + "String() = %q, want %q", + got, + tt.want, + ) + } + }) + } +} + +func TestValidateGRPCMessageMatcher(t *testing.T) { + tests := []struct { + name string + matcher GRPCMessage + wantErr bool + }{ + { + name: "equals valid JSON object", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{"id":"user-123"}`, + }, + }, + { + name: "equals empty protobuf message", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{}`, + }, + }, + { + name: "equals invalid JSON", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + Value: `{`, + }, + wantErr: true, + }, + { + name: "equals empty string", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorEquals, + }, + wantErr: true, + }, + { + name: "nonempty", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + }, + }, + { + name: "nonempty with value", + matcher: GRPCMessage{ + Operator: GRPCMessageMatchOperatorNonEmpty, + Value: `{}`, + }, + wantErr: true, + }, + { + name: "unknown operator", + matcher: GRPCMessage{ + Operator: "contains", + }, + wantErr: true, + }, + { + name: "missing operator", + matcher: GRPCMessage{ + Value: `{}`, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateGRPCMessageMatcher(tt.matcher) + if (err != nil) != tt.wantErr { + t.Errorf( + "validateGRPCMessageMatcher() error = %v, wantErr %v", + err, + tt.wantErr, + ) + } + }) + } +} diff --git a/model/matcher/string.go b/model/matcher/string.go new file mode 100644 index 0000000..5bbbd54 --- /dev/null +++ b/model/matcher/string.go @@ -0,0 +1,200 @@ +package matcher + +import ( + "encoding/json" + "fmt" + + "github.com/ygrebnov/errorc" + modellib "github.com/ygrebnov/model" + "gopkg.in/yaml.v3" + + "github.com/e2engine/core/pkg/errors" + "github.com/e2engine/core/pkg/keys" +) + +type String struct { + Operator StringMatchOperator `json:"operator" yaml:"operator"` + Value string `json:"value,omitempty" yaml:"value,omitempty"` +} + +func (m String) String() string { + if m.Operator == StringMatchOperatorEquals { + return m.Value + } + + return string(m.Operator) +} + +type StringMatchOperator string + +const ( + StringMatchOperatorEquals StringMatchOperator = "equals" + StringMatchOperatorExists StringMatchOperator = "exists" + StringMatchOperatorNonEmpty StringMatchOperator = "nonempty" +) + +func (m String) MarshalJSON() ([]byte, error) { + if m.Operator == StringMatchOperatorEquals { + return json.Marshal(m.Value) + } + + type alias String + return json.Marshal(alias(m)) +} + +func (m *String) UnmarshalJSON(data []byte) error { + var value string + if err := json.Unmarshal(data, &value); err == nil { + *m = String{ + Operator: StringMatchOperatorEquals, + Value: value, + } + return nil + } + + type alias String + var matcher alias + if err := json.Unmarshal(data, &matcher); err != nil { + return fmt.Errorf( + "string matcher must be a string or object: %w", + err, + ) + } + + *m = String(matcher) + return nil +} + +func (m String) MarshalYAML() (any, error) { + if m.Operator == StringMatchOperatorEquals { + return m.Value, nil + } + + type alias String + return alias(m), nil +} + +func (m *String) UnmarshalYAML(node *yaml.Node) error { + if node.Kind == yaml.ScalarNode && + node.Tag == "!!str" { + *m = String{ + Operator: StringMatchOperatorEquals, + Value: node.Value, + } + return nil + } + + if node.Kind != yaml.MappingNode { + return fmt.Errorf( + "string matcher must be a string or object", + ) + } + + type alias String + var matcher alias + if err := node.Decode(&matcher); err != nil { + return err + } + + *m = String(matcher) + return nil +} + +func GetStringMatchersRule() (modellib.Rule, error) { + return modellib.NewRule[[]String]( + "stringmatchers", + func(values []String, _ ...string) error { + if len(values) == 0 { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "at least one string matcher must be specified", + ), + ) + } + + operator := values[0].Operator + + for _, value := range values { + if err := validateStringMatcher(value); err != nil { + return err + } + + if value.Operator != operator { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "string matcher operators cannot be mixed", + ), + ) + } + } + + if operator != StringMatchOperatorEquals && + len(values) != 1 { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.Validation, + "exists and nonempty operators can only be specified once", + ), + ) + } + + return nil + }, + ) +} + +func GetStringMatcherRule() (modellib.Rule, error) { + return modellib.NewRule[*String]( + "stringmatcher", + func(value *String, _ ...string) error { + if value == nil { + return nil + } + return validateStringMatcher(*value) + }, + ) +} + +func validateStringMatcher(value String) error { + switch value.Operator { + case StringMatchOperatorEquals: + // Any string, including an empty string, is valid. + return nil + + case StringMatchOperatorExists, + StringMatchOperatorNonEmpty: + if value.Value != "" { + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.MatcherOperator, + string(value.Operator), + ), + errorc.String( + keys.Validation, + "value must be empty for this operator", + ), + ) + } + + return nil + + default: + return errorc.With( + errors.ErrInvalidSpec, + errorc.String( + keys.MatcherOperator, + string(value.Operator), + ), + errorc.String( + keys.Validation, + "invalid operator", + ), + ) + } +} diff --git a/model/matcher/string_test.go b/model/matcher/string_test.go new file mode 100644 index 0000000..f7a062b --- /dev/null +++ b/model/matcher/string_test.go @@ -0,0 +1,517 @@ +package matcher + +import ( + "encoding/json" + "reflect" + "testing" + + "gopkg.in/yaml.v3" +) + +func TestStringMarshalJSON(t *testing.T) { + tests := []struct { + name string + matcher String + want string + }{ + { + name: "equals", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + want: `"application/json"`, + }, + { + name: "equals empty", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "", + }, + want: `""`, + }, + { + name: "exists", + matcher: String{ + Operator: StringMatchOperatorExists, + }, + want: `{"operator":"exists"}`, + }, + { + name: "nonempty", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + }, + want: `{"operator":"nonempty"}`, + }, + { + name: "expanded matcher preserves value", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + Value: "value", + }, + want: `{"operator":"nonempty","value":"value"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := json.Marshal(tt.matcher) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + if string(got) != tt.want { + t.Errorf("Marshal() = %s, want %s", got, tt.want) + } + }) + } +} + +func TestStringUnmarshalJSON(t *testing.T) { + tests := []struct { + name string + data string + want String + }{ + { + name: "equals", + data: `"application/json"`, + want: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + }, + { + name: "equals empty", + data: `""`, + want: String{ + Operator: StringMatchOperatorEquals, + Value: "", + }, + }, + { + name: "exists", + data: `{"operator":"exists"}`, + want: String{ + Operator: StringMatchOperatorExists, + }, + }, + { + name: "nonempty", + data: `{"operator":"nonempty"}`, + want: String{ + Operator: StringMatchOperatorNonEmpty, + }, + }, + { + name: "expanded equals", + data: `{"operator":"equals","value":"application/json"}`, + want: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got String + if err := json.Unmarshal([]byte(tt.data), &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Unmarshal() = %#v, want %#v", got, tt.want) + } + }) + } +} + +func TestStringUnmarshalJSONInvalid(t *testing.T) { + tests := []struct { + name string + data string + }{ + { + name: "number", + data: `123`, + }, + { + name: "boolean", + data: `true`, + }, + { + name: "array", + data: `["value"]`, + }, + { + name: "invalid JSON", + data: `{`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var matcher String + if err := json.Unmarshal([]byte(tt.data), &matcher); err == nil { + t.Fatal("Unmarshal() error = nil, want error") + } + }) + } +} + +func TestStringMarshalYAML(t *testing.T) { + tests := []struct { + name string + matcher String + want string + }{ + { + name: "equals", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + want: "application/json\n", + }, + { + name: "equals empty", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "", + }, + want: `""` + "\n", + }, + { + name: "exists", + matcher: String{ + Operator: StringMatchOperatorExists, + }, + want: "operator: exists\n", + }, + { + name: "nonempty", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + }, + want: "operator: nonempty\n", + }, + { + name: "expanded matcher preserves value", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + Value: "value", + }, + want: "operator: nonempty\nvalue: value\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := yaml.Marshal(tt.matcher) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + if string(got) != tt.want { + t.Errorf( + "Marshal() = %q, want %q", + string(got), + tt.want, + ) + } + }) + } +} + +func TestStringUnmarshalYAML(t *testing.T) { + tests := []struct { + name string + data string + want String + }{ + { + name: "equals", + data: "application/json\n", + want: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + }, + { + name: "equals empty", + data: `""`, + want: String{ + Operator: StringMatchOperatorEquals, + Value: "", + }, + }, + { + name: "exists", + data: "operator: exists\n", + want: String{ + Operator: StringMatchOperatorExists, + }, + }, + { + name: "nonempty", + data: "operator: nonempty\n", + want: String{ + Operator: StringMatchOperatorNonEmpty, + }, + }, + { + name: "expanded equals", + data: "operator: equals\nvalue: application/json\n", + want: String{ + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var got String + if err := yaml.Unmarshal([]byte(tt.data), &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Unmarshal() = %#v, want %#v", got, tt.want) + } + }) + } +} + +func TestStringUnmarshalYAMLInvalid(t *testing.T) { + tests := []struct { + name string + data string + }{ + { + name: "integer", + data: "123\n", + }, + { + name: "boolean", + data: "true\n", + }, + { + name: "sequence", + data: "- value\n", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var matcher String + if err := yaml.Unmarshal([]byte(tt.data), &matcher); err == nil { + t.Fatal("Unmarshal() error = nil, want error") + } + }) + } +} + +func TestStringRoundTripJSON(t *testing.T) { + values := []String{ + { + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + { + Operator: StringMatchOperatorEquals, + Value: "", + }, + { + Operator: StringMatchOperatorExists, + }, + { + Operator: StringMatchOperatorNonEmpty, + }, + } + + for _, want := range values { + data, err := json.Marshal(want) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + var got String + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf( + "round trip = %#v, want %#v", + got, + want, + ) + } + } +} + +func TestStringRoundTripYAML(t *testing.T) { + values := []String{ + { + Operator: StringMatchOperatorEquals, + Value: "application/json", + }, + { + Operator: StringMatchOperatorEquals, + Value: "", + }, + { + Operator: StringMatchOperatorExists, + }, + { + Operator: StringMatchOperatorNonEmpty, + }, + } + + for _, want := range values { + data, err := yaml.Marshal(want) + if err != nil { + t.Fatalf("Marshal() error = %v", err) + } + + var got String + if err := yaml.Unmarshal(data, &got); err != nil { + t.Fatalf("Unmarshal() error = %v", err) + } + + if !reflect.DeepEqual(got, want) { + t.Errorf( + "round trip = %#v, want %#v", + got, + want, + ) + } + } +} + +func TestStringString(t *testing.T) { + tests := []struct { + name string + matcher String + want string + }{ + { + name: "equals", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "hello", + }, + want: "hello", + }, + { + name: "equals empty", + matcher: String{ + Operator: StringMatchOperatorEquals, + }, + want: "", + }, + { + name: "exists", + matcher: String{ + Operator: StringMatchOperatorExists, + }, + want: "exists", + }, + { + name: "nonempty", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + }, + want: "nonempty", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.matcher.String(); got != tt.want { + t.Errorf("String() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestValidateStringMatcher(t *testing.T) { + tests := []struct { + name string + matcher String + wantErr bool + }{ + { + name: "equals", + matcher: String{ + Operator: StringMatchOperatorEquals, + Value: "hello", + }, + }, + { + name: "equals empty", + matcher: String{ + Operator: StringMatchOperatorEquals, + }, + }, + { + name: "exists", + matcher: String{ + Operator: StringMatchOperatorExists, + }, + }, + { + name: "nonempty", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + }, + }, + { + name: "exists with value", + matcher: String{ + Operator: StringMatchOperatorExists, + Value: "value", + }, + wantErr: true, + }, + { + name: "nonempty with value", + matcher: String{ + Operator: StringMatchOperatorNonEmpty, + Value: "value", + }, + wantErr: true, + }, + { + name: "unknown operator", + matcher: String{ + Operator: "contains", + }, + wantErr: true, + }, + { + name: "missing operator", + matcher: String{ + Value: "hello", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateStringMatcher(tt.matcher) + + if (err != nil) != tt.wantErr { + t.Errorf( + "validateStringMatcher() error = %v, wantErr %v", + err, + tt.wantErr, + ) + } + }) + } +} diff --git a/model/test.go b/model/test.go index 86006ec..bca218e 100644 --- a/model/test.go +++ b/model/test.go @@ -133,8 +133,8 @@ type RequestSpec struct { } type ExpectSpec struct { - HTTP *HTTPResponse `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` - GRPC *GRPCResponse `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` + HTTP *HTTPResponsePattern `json:"http,omitempty" yaml:"http,omitempty" validateElem:"omitempty,dive"` + GRPC *GRPCResponsePattern `json:"grpc,omitempty" yaml:"grpc,omitempty" validateElem:"omitempty,dive"` Calls []ServiceExpectedCalls `json:"calls,omitempty" yaml:"calls,omitempty" validateElem:"dive"` } diff --git a/model/testexecution.go b/model/testexecution.go index e3b16a6..e4e0c92 100644 --- a/model/testexecution.go +++ b/model/testexecution.go @@ -94,4 +94,15 @@ type TestExecutionDeviation struct { Message string `json:"message,omitempty" yaml:"message,omitempty"` } +type Stringer interface { + String() string +} + +type PayloadDeviation struct { + Field string + Expected Stringer + Actual []byte + Message string +} + type TestExecutionsPage = Page[TestExecution] diff --git a/model/validation.go b/model/validation.go index 522e6b6..fa5dca8 100644 --- a/model/validation.go +++ b/model/validation.go @@ -12,6 +12,7 @@ import ( "github.com/ygrebnov/errorc" modellib "github.com/ygrebnov/model" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/errors" "github.com/e2engine/core/pkg/keys" ) @@ -19,7 +20,7 @@ import ( var validationRules []modellib.Rule func init() { - validationRules = make([]modellib.Rule, 4) + validationRules = make([]modellib.Rule, 8) idRule, err := getIDRule() if err != nil { @@ -41,10 +42,34 @@ func init() { panic(err) } + stringMatcherRule, err := matcher.GetStringMatcherRule() + if err != nil { + panic(err) + } + + stringMatchersRule, err := matcher.GetStringMatchersRule() + if err != nil { + panic(err) + } + + stringMatcherValidJSONRule, err := getStringMatcherValidJSONRule() + if err != nil { + panic(err) + } + + grpcMessageMatcherRule, err := matcher.GetGRPCMessageMatcherRule() + if err != nil { + panic(err) + } + validationRules[0] = idRule validationRules[1] = networkAddressRule validationRules[2] = httpURLRule validationRules[3] = validJSONRule + validationRules[4] = stringMatcherRule + validationRules[5] = stringMatchersRule + validationRules[6] = stringMatcherValidJSONRule + validationRules[7] = grpcMessageMatcherRule environmentBinding, err = modellib.NewBinding[Environment](modellib.WithRules(validationRules...)) if err != nil { diff --git a/pkg/errors/errors.go b/pkg/errors/errors.go index af88d78..037eafe 100644 --- a/pkg/errors/errors.go +++ b/pkg/errors/errors.go @@ -58,6 +58,8 @@ var ( ErrNoTestsResolved = errorc.New("no tests resolved for test suite") ErrUnsupportedFileType = errorc.New("unsupported file type") + + ErrInvalidGRPCMessageMatcher = errorc.New("invalid gRPC message matcher") ) // Is wraps native errors package Is. diff --git a/pkg/keys/keys.go b/pkg/keys/keys.go index b32a134..33bab6b 100644 --- a/pkg/keys/keys.go +++ b/pkg/keys/keys.go @@ -39,6 +39,8 @@ var ( EnvironmentServiceListenAddress = environmentService("listen.address") EnvironmentServiceRuntimeAddress = environmentService("runtime.address") + MatcherOperator = keys.New("matcher.operator") + RequestMethod = request("method") RequestURLPath = request("url.path") diff --git a/tests/test_test.go b/tests/test_test.go index d03727c..e715373 100644 --- a/tests/test_test.go +++ b/tests/test_test.go @@ -476,7 +476,7 @@ func validTestSpec() model.TestSpec { }, }, Expect: model.ExpectSpec{ - HTTP: &model.HTTPResponse{ + HTTP: &model.HTTPResponsePattern{ StatusCode: 200, }, }, diff --git a/tests/testexecution_test.go b/tests/testexecution_test.go index dcf2965..e261dab 100644 --- a/tests/testexecution_test.go +++ b/tests/testexecution_test.go @@ -442,7 +442,7 @@ func modelTestExecutionSummary() *model.TestExecutionSummary { Response: &model.TestExecutionResponseSummary{ HTTP: &model.HTTPResponse{ StatusCode: 200, - BodyJSON: &bodyJSON, + BodyJSON: bodyJSON, }, }, } From e78f466207750d0611509153037a85771ab5afc1 Mon Sep 17 00:00:00 2001 From: Yaroslav Grebnov Date: Thu, 15 Oct 2026 21:13:04 +0200 Subject: [PATCH 4/4] Bump dependencies --- go.mod | 12 ++++++------ go.sum | 24 ++++++++++-------------- 2 files changed, 16 insertions(+), 20 deletions(-) diff --git a/go.mod b/go.mod index 49f00ea..80b97ff 100644 --- a/go.mod +++ b/go.mod @@ -14,13 +14,13 @@ require ( go.uber.org/mock v0.6.0 google.golang.org/grpc v1.84.0 google.golang.org/protobuf v1.36.12 + gopkg.in/yaml.v3 v3.0.1 ) require ( - golang.org/x/net v0.59.0 // indirect - golang.org/x/sync v0.23.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/text v0.42.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect + golang.org/x/net v0.61.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 // indirect ) diff --git a/go.sum b/go.sum index fa0381e..a4e77cb 100644 --- a/go.sum +++ b/go.sum @@ -26,22 +26,18 @@ github.com/ygrebnov/model v0.7.5 h1:9i7Xz5vxYQXeJW06gTE9/In49f0lEDhulmsBKhsQxWw= github.com/ygrebnov/model v0.7.5/go.mod h1:qYRz8F/yrt01bPyANAlN0Oqi1fwpgvvl21hjW/NK6N0= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= -golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c= -golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 h1:QG6hS4zFplRZvOQedzei4t2pT/zkQc3VR1u+S9/rcAw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.84.0 h1:soMyaPJ8pAak5PIQ0DGBUir0XRo2fRoMqhNWMLlLxO0= google.golang.org/grpc v1.84.0/go.mod h1:ljCht0DrxQrXBDRTZp52Qxh3Ffk8CdYm2sj4O2QN2C0= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=