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/Makefile b/Makefile index 32101be..6df5802 100644 --- a/Makefile +++ b/Makefile @@ -16,6 +16,8 @@ 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 + go generate ./... .PHONY: lint lint: install-golangci-lint diff --git a/api/service_run_test.go b/api/service_run_test.go index 1d1dc97..58619a6 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.HTTPResponsePattern{ + 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/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/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/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..897d135 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" @@ -275,13 +276,9 @@ func (r *Router) newHandler( stream.Context(), ) - outgoingMetadata := e2enginegrpc.WithoutTestExecutionID( - incomingMetadata, - ) - outgoingContext := metadata.NewOutgoingContext( ctx, - outgoingMetadata, + incomingMetadata.Copy(), ) var response rawMessage @@ -300,13 +297,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,9 +350,15 @@ func (r *Router) newHandler( } } -func cloneMetadata(source metadata.MD) map[string][]string { - source = e2enginegrpc.WithoutTestExecutionID(source) +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 { 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 252179a..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", ) } @@ -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, ) } @@ -367,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, ) } @@ -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/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 f76ff87..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" @@ -44,11 +46,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][]matcher.String + message *matcher.GRPCMessage + + status codes.Code + responseMetadata map[string][]string + response map[string]any } func NewMockGRPCService( @@ -58,9 +63,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 +82,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 +109,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 +135,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 +163,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 +187,31 @@ 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, + ) if err != nil { return status.Error( codes.Internal, @@ -192,10 +226,7 @@ func (s *MockGRPCService) handle( ) stream.SetTrailer( - metadata.Pairs( - string(keys.E2EngineMockMissMetadata), - "true", - ), + metadata.Pairs(string(keys.E2EngineMockMissMetadata), "true"), ) return status.Error( @@ -204,6 +235,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 +276,10 @@ func (s *MockGRPCService) handle( } func methodName(fullMethod string) string { - index := strings.LastIndex(fullMethod, "/") + index := strings.LastIndex( + fullMethod, + "/", + ) if index == -1 { return fullMethod } @@ -241,38 +290,46 @@ func methodName(fullMethod string) string { func (s *MockGRPCService) match( fullMethod string, actual proto.Message, - method protoreflect.MethodDescriptor, + actualMetadata metadata.MD, ) (*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 } - expected, err := buildMessage( - method.Input(), + if fixture.message == nil { + return fixture, nil + } + + 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.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 } } @@ -280,11 +337,32 @@ func (s *MockGRPCService) match( return nil, nil } +func areMetadataEqual( + expected map[string][]matcher.String, + actual metadata.MD, +) bool { + for key, expectedValues := range expected { + actualValues, exists := actual[strings.ToLower(key)] + + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { + return false + } + } + + 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 +376,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,24 +406,37 @@ 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] - if spec.When.GRPC == nil || - spec.Then.GRPC == nil { - 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{ - rpc: spec.When.GRPC.Method, - message: spec.When.GRPC.Message, - status: grpcCode(spec.Then.GRPC.Status), - response: spec.Then.GRPC.Message, - }, + fixture, ) } @@ -344,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 cd0e2f0..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" @@ -9,6 +10,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" @@ -16,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" ) @@ -68,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 { @@ -166,42 +106,78 @@ func TestGRPCCode(t *testing.T) { } } +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.GRPCFixtureWhen{ - Method: "GetUser", - Message: map[string]any{ - "id": "42", + GRPC: &model.GRPCRequestPattern{ + Service: "users.v1.UserService", + Method: "GetUser", + Metadata: map[string][]matcher.String{ + "x-request-id": { + grpcStringEquals("one"), + grpcStringEquals("two"), + }, }, + Message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), }, }, Then: model.FixtureThen{ - GRPC: &model.GRPCFixtureThen{ - Status: "not_found", + GRPC: &model.GRPCResponse{ + Status: "NotFound", + Metadata: map[string][]string{ + "x-response-id": { + "three", + "four", + }, + }, Message: map[string]any{ "message": "not found", }, }, }, }, - { - When: model.FixtureWhen{}, - Then: model.FixtureThen{ - GRPC: &model.GRPCFixtureThen{ - Status: "ok", - }, - }, - }, - { - When: model.FixtureWhen{ - GRPC: &model.GRPCFixtureWhen{ - Method: "Ignored", - }, - }, - Then: model.FixtureThen{}, - }, } fixtures := compileFixtures(specs) @@ -215,11 +191,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, ) } @@ -231,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 equals operator, got %q", + fixture.message.Operator, + ) + } + + if fixture.message.Value != `{"id":"42"}` { t.Errorf( - "expected request id %q, got %v", - "42", - fixture.message["id"], + "expected request message %q, got %q", + `{"id":"42"}`, + fixture.message.Value, ) } @@ -246,6 +241,28 @@ func TestCompileFixtures(t *testing.T) { fixture.response["message"], ) } + + requestMetadata := fixture.metadata["x-request-id"] + + if len(requestMetadata) != 2 || + requestMetadata[0].Value != "one" || + requestMetadata[1].Value != "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) { @@ -387,6 +404,183 @@ func TestBuildMessageInvalidField(t *testing.T) { } } +func TestAreMetadataEqual(t *testing.T) { + tests := []struct { + name string + expected map[string][]matcher.String + actual metadata.MD + want bool + }{ + { + name: "nil expected", + actual: metadata.MD{ + "additional": {"value"}, + }, + want: true, + }, + { + name: "matching value", + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + }, + want: true, + }, + { + name: "matching repeated values", + expected: map[string][]matcher.String{ + "x-request-id": { + grpcStringEquals("one"), + grpcStringEquals("two"), + }, + }, + actual: metadata.MD{ + "x-request-id": { + "two", + "one", + }, + }, + want: true, + }, + { + name: "additional actual key ignored", + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{ + "x-request-id": {"one"}, + "additional": {"value"}, + }, + want: true, + }, + { + name: "missing expected key", + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{}, + }, + { + name: "different value", + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{ + "x-request-id": {"two"}, + }, + }, + { + name: "additional value for expected key", + expected: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + actual: metadata.MD{ + "x-request-id": { + "one", + "two", + }, + }, + }, + { + 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, + }, + } + + 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) @@ -403,60 +597,233 @@ func TestMockGRPCServiceMatch(t *testing.T) { 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", - message: map[string]any{ + service: "users.v1.UserService", + method: "GetUser", + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), }, }, 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", - message: map[string]any{ + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": { + grpcStringEquals("one"), + grpcStringEquals("two"), + }, + }, + message: grpcMessageMatcher(map[string]any{ "id": "42", + }), + }, + }, + expected: true, + }, + { + name: "additional metadata ignored", + fullMethod: "/users.v1.UserService/GetUser", + metadata: metadata.MD{ + "x-request-id": {"one"}, + "additional": {"value"}, + }, + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, }, + message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), }, }, expected: true, }, { - name: "different rpc", + name: "different service", fullMethod: "/users.v1.UserService/GetUser", fixtures: []Fixture{ { - rpc: "CreateUser", - message: map[string]any{ + service: "users.v1.AdminService", + method: "GetUser", + message: grpcMessageMatcher(map[string]any{ "id": "42", - }, + }), + }, + }, + }, + { + name: "different method", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "CreateUser", + message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), }, }, - expected: false, }, { name: "different message", fullMethod: "/users.v1.UserService/GetUser", fixtures: []Fixture{ { - rpc: "GetUser", - message: map[string]any{ + service: "users.v1.UserService", + method: "GetUser", + message: grpcMessageMatcher(map[string]any{ "id": "43", + }), + }, + }, + }, + { + name: "missing metadata", + fullMethod: "/users.v1.UserService/GetUser", + fixtures: []Fixture{ + { + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), + }, + }, + }, + { + 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][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + message: grpcMessageMatcher(map[string]any{ + "id": "42", + }), + }, + }, + }, + { + 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][]matcher.String{ + "x-request-id": {grpcStringEquals("one")}, + }, + 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, }, } @@ -469,10 +836,13 @@ func TestMockGRPCServiceMatch(t *testing.T) { fixture, err := service.match( tt.fullMethod, request, - method, + tt.metadata, ) if err != nil { - t.Fatalf("match() error = %v", err) + t.Fatalf( + "match() error = %v", + err, + ) } if tt.expected && fixture == nil { @@ -489,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, ) { @@ -501,16 +930,20 @@ 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", - message: map[string]any{ + service: "users.v1.UserService", + method: "GetUser", + message: grpcMessageMatcher(map[string]any{ "unknown": "value", - }, + }), }, }, } @@ -518,7 +951,7 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( _, err = service.match( "/users.v1.UserService/GetUser", request, - method, + nil, ) if err == nil { t.Fatal("expected error") @@ -536,7 +969,9 @@ func TestMockGRPCServiceMatchInvalidFixtureMessage( } } -func TestMockGRPCServiceMountCanceledContext(t *testing.T) { +func TestMockGRPCServiceMountCanceledContext( + t *testing.T, +) { service := &MockGRPCService{} ctx, cancel := context.WithCancel( @@ -546,7 +981,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, @@ -563,7 +1001,9 @@ func TestMockGRPCServiceMountCanceledContext(t *testing.T) { } } -func TestMockGRPCServiceUnmountBeforeMount(t *testing.T) { +func TestMockGRPCServiceUnmountBeforeMount( + t *testing.T, +) { service := &MockGRPCService{} if err := service.Unmount( @@ -626,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{ @@ -644,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, @@ -675,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, @@ -692,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", ), @@ -731,7 +1151,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 +1166,24 @@ func TestMockGRPCServiceHandle(t *testing.T) { }, fixtures: []Fixture{ { - rpc: "GetUser", - message: map[string]any{ - "id": "42", + service: "users.v1.UserService", + method: "GetUser", + metadata: map[string][]matcher.String{ + "x-request-id": { + grpcStringEquals("one"), + grpcStringEquals("two"), + }, }, + message: grpcMessageMatcher(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 +1249,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,6 +1278,31 @@ 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") @@ -845,3 +1319,37 @@ func TestMockGRPCServiceHandle(t *testing.T) { ) } } + +func containsString( + values []string, + expected string, +) bool { + for _, value := range values { + if value == expected { + return true + } + } + + 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 29f6159..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" @@ -121,7 +123,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( @@ -139,54 +143,66 @@ func (s *MockHTTPService) match(r *http.Request) (*Fixture, error) { ) } - for _, fixture := range s.fixtures { - if fixture.method == r.Method && - fixture.path == r.URL.Path && + 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(fixture.body, body) { - return &fixture, nil + areHeadersEqual(fixture.headers, r.Header) { + equalBody, errBodyEqual := isBodyEqual( + fixture.body, + fixture.bodyJSON, + body, + ) + if errBodyEqual != nil { + return nil, errBodyEqual + } + if equalBody { + return fixture, 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 *matcher.String, + expectedBodyJSON *matcher.String, + actual []byte, +) (bool, error) { + if expectedBody != nil { + return match.IsStringMatched(actual, expectedBody), nil } - var expectedValue any - if err := json.Unmarshal(expected, &expectedValue); err != nil { - return false - } + if expectedBodyJSON != nil { + if !json.Valid(actual) { + return false, nil + } - var actualValue any - if err := json.Unmarshal(actual, &actualValue); err != nil { - return false + return match.IsJSONMatched(actual, expectedBodyJSON) } - return reflect.DeepEqual(expectedValue, actualValue) + 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 } @@ -194,10 +210,20 @@ 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(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 +231,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 +248,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 } } @@ -243,33 +268,55 @@ type Fixture struct { method string path string query url.Values - headers map[string][]string - body json.RawMessage + headers map[string][]matcher.String + + body *matcher.String + bodyJSON *matcher.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{ 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, - responseHeaders: spec.Then.HTTP.Headers, - responseBody: json.RawMessage(spec.Then.HTTP.Body), + status: spec.Then.HTTP.StatusCode, + + responseHeaders: spec.Then.HTTP.Headers, + responseBody: spec.Then.HTTP.Body, + responseBodyJSON: spec.Then.HTTP.BodyJSON, + } + + if spec.When.HTTP.Body != nil { + fixture.body = spec.When.HTTP.Body + } + + if spec.When.HTTP.BodyJSON != nil { + fixture.bodyJSON = spec.When.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 6737e86..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" ) @@ -25,12 +26,13 @@ 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}`, + nil, + ptr(`{"name":"Alice","age":42}`), http.StatusCreated, ), method: "POST", @@ -40,12 +42,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusCreated, }, { - name: "array body", + name: "JSON array body", fixture: newHTTPFixture( "POST", "/values", nil, - `[1,2,3]`, + nil, + ptr(`[1,2,3]`), http.StatusOK, ), method: "POST", @@ -55,12 +58,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "scalar body", + name: "JSON scalar body", fixture: newHTTPFixture( "POST", "/value", nil, - `42`, + nil, + ptr(`42`), http.StatusOK, ), method: "POST", @@ -70,12 +74,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "string body", + name: "JSON string body", fixture: newHTTPFixture( "POST", "/value", nil, - `"hello"`, + nil, + ptr(`"hello"`), http.StatusOK, ), method: "POST", @@ -85,12 +90,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "boolean body", + name: "JSON boolean body", fixture: newHTTPFixture( "POST", "/value", nil, - `true`, + nil, + ptr(`true`), http.StatusOK, ), method: "POST", @@ -100,12 +106,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, { - name: "null body", + name: "JSON null body", fixture: newHTTPFixture( "POST", "/value", nil, - `null`, + nil, + ptr(`null`), http.StatusOK, ), method: "POST", @@ -114,13 +121,63 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusOK, }, + { + name: "exact text body", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + ptr("hello world"), + nil, + http.StatusOK, + ), + method: "POST", + path: "/text", + body: "hello world", + + expectedStatus: http.StatusOK, + }, + { + name: "arbitrary non-JSON text body", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + ptr("this is not JSON: {"), + nil, + 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, + ptr(`{"name":"Alice","age":42}`), + nil, + http.StatusOK, + ), + method: "POST", + path: "/users", + body: `{"age":42,"name":"Alice"}`, + + expectedStatus: http.StatusNotImplemented, + expectedMiss: true, + }, { name: "empty body", fixture: newHTTPFixture( "GET", "/users", nil, - "", + ptr(""), + nil, http.StatusOK, ), method: "GET", @@ -134,7 +191,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?status=active&page=2", nil, - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -148,7 +206,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?role=admin&role=operator", nil, - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -161,10 +220,19 @@ 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, http.StatusOK, ), method: "GET", @@ -180,10 +248,16 @@ 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, http.StatusOK, ), method: "GET", @@ -200,10 +274,16 @@ 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, http.StatusOK, ), method: "GET", @@ -220,7 +300,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", + nil, + nil, http.StatusOK, ), method: "POST", @@ -235,7 +316,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users", nil, - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -250,7 +332,8 @@ func TestMockHTTPServiceMatch(t *testing.T) { "GET", "/users?page=1", nil, - "", + nil, + nil, http.StatusOK, ), method: "GET", @@ -260,29 +343,35 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss: true, }, { - name: "unexpected query is miss", + name: "additional query parameters ignored", fixture: newHTTPFixture( "GET", "/users", nil, - "", + nil, + nil, http.StatusOK, ), 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, http.StatusOK, ), method: "GET", @@ -296,10 +385,16 @@ 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, http.StatusOK, ), method: "GET", @@ -316,10 +411,16 @@ 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, http.StatusOK, ), method: "GET", @@ -332,12 +433,13 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedMiss: true, }, { - name: "body miss", + name: "JSON body miss", fixture: newHTTPFixture( "POST", "/users", nil, - `{"name":"Alice"}`, + nil, + ptr(`{"name":"Alice"}`), http.StatusOK, ), method: "POST", @@ -347,13 +449,31 @@ func TestMockHTTPServiceMatch(t *testing.T) { expectedStatus: http.StatusNotImplemented, expectedMiss: true, }, + { + name: "text body miss", + fixture: newHTTPFixture( + "POST", + "/text", + nil, + ptr("expected"), + nil, + 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( "POST", "/users", nil, - "", + ptr(""), + nil, http.StatusOK, ), method: "POST", @@ -364,12 +484,213 @@ 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, - `{}`, + nil, + ptr(`{}`), + 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, + ptr("expected"), + nil, + http.StatusOK, + ), + 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", @@ -387,34 +708,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 +770,9 @@ func TestMockHTTPServiceMatch(t *testing.T) { } gotMiss := resp.Header.Get( - string(keys.E2EngineMockMissHeader), + string( + keys.E2EngineMockMissHeader, + ), ) == "true" if gotMiss != tt.expectedMiss { @@ -442,83 +787,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), + ) + } + }) } } @@ -551,23 +950,32 @@ func newTestMockHTTPService( func newHTTPFixture( method, path string, - headers map[string][]string, - body string, + headers map[string][]matcher.String, + body, + bodyJSON *matcher.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, }, }, } } + +func ptr(s string) *matcher.String { + return &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: s, + } +} diff --git a/execute/evaluate/evaluator.go b/execute/worker/evaluator/evaluator.go similarity index 75% rename from execute/evaluate/evaluator.go rename to execute/worker/evaluator/evaluator.go index a826982..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" ) @@ -16,7 +15,7 @@ type CallEvaluator interface { ctx context.Context, service *model.ServiceSpec, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) Deviation( @@ -28,24 +27,27 @@ 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, } } func (e *Evaluator) EvaluateCalls( ctx context.Context, services []model.ServiceSpec, - expectedCalls []model.CallExpectation, + 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) } } } @@ -107,9 +109,9 @@ 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, + 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", + }) } } @@ -177,7 +173,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: @@ -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 77% rename from execute/evaluate/evaluator_test.go rename to execute/worker/evaluator/evaluator_test.go index 2714174..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(), @@ -62,18 +71,18 @@ 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, - 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(), @@ -388,15 +422,15 @@ func TestEvaluatorEvaluateExpectedCalls(t *testing.T) { Kind: model.ServiceKindHTTP, }, }, - []model.CallExpectation{ + []model.ServiceExpectedCalls{ { ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, Count: tt.count, }, }, 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{ @@ -468,14 +477,14 @@ func TestEvaluatorEvaluateExpectedCallsError( Kind: model.ServiceKindHTTP, }, }, - []model.CallExpectation{ + []model.ServiceExpectedCalls{ { ServiceID: "service-1", - HTTP: &model.HTTPCallExpectation{}, + HTTP: &model.HTTPRequestPattern{}, }, }, calls, - result, + "execution-1", ) if !errors.Is(err, expectedErr) { @@ -491,36 +500,41 @@ func TestEvaluatorMatches(t *testing.T) { tests := []struct { name string - expected model.CallExpectation + expected model.ServiceExpectedCalls expectedHTTPCalls int expectedGRPCCalls int expectedMatch bool + expectedPanic bool }{ { 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, }, { 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,14 +622,15 @@ func TestEvaluatorMatchesError(t *testing.T) { evaluator := New( httpEvaluator, &testCallEvaluator{}, + reporter, ) _, err := evaluator.matches( context.Background(), &model.ServiceSpec{}, call.Call{}, - model.CallExpectation{ - HTTP: &model.HTTPCallExpectation{}, + model.ServiceExpectedCalls{ + HTTP: &model.HTTPRequestPattern{}, }, ) @@ -619,7 +656,7 @@ func (e *testCallEvaluator) Matches( _ context.Context, _ *model.ServiceSpec, _ call.Call, - _ model.CallExpectation, + _ model.ServiceExpectedCalls, ) (bool, error) { e.matchesCalls++ @@ -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 e741653..9f8256e 100644 --- a/execute/worker/grpc/evaluate.go +++ b/execute/worker/grpc/evaluate.go @@ -3,6 +3,8 @@ package grpc import ( "context" "encoding/json" + "slices" + "strings" "github.com/ygrebnov/errorc" "google.golang.org/grpc/codes" @@ -12,10 +14,10 @@ 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" + "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" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/keys" @@ -26,44 +28,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.GRPCExpectSpec, - result *execute.TestExecutionResult, + expect *model.GRPCResponsePattern, ) error { - if err := ctx.Err(); err != nil { + if err := e.evaluateStatus(callErr, expect); err != nil { return err } - result.Summary.Response = &model.TestExecutionResponseSummary{ - GRPC: &model.TestExecutionGRPCResponseSummary{}, + if err := e.evaluateMetadata(header, trailer, expect); err != nil { + return err } - actualStatus := status.Code(callErr) - - result.Summary.Response.GRPC.Status = - actualStatus.String() + return e.evaluateMessage(response, expect) +} - result.Summary.Response.GRPC.Metadata = - mergeMetadata(header, trailer) +func (e *Evaluator) evaluateStatus( + callErr error, + expect *model.GRPCResponsePattern, +) error { + actualStatus := status.Code(callErr) + e.reporter.AddGRPCResponseStatus(actualStatus.String()) expectedStatus, err := grpcCode( expect.Status, @@ -73,68 +78,91 @@ 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.GRPCResponsePattern, +) error { + actualMetadata := mergeMetadata(header, trailer) + e.reporter.AddGRPCResponseMetadata(actualMetadata) + + for key, expectedValues := range expect.Metadata { + 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(expectedStrings, ","), + Actual: strings.Join(sortedActual, ","), + }) } + return nil +} + +func (e *Evaluator) evaluateMessage( + response *dynamicpb.Message, + expect *model.GRPCResponsePattern, +) error { responseMap, err := messageToMap(response) if err != nil { return err } - result.Summary.Response.GRPC.Message = - responseMap + e.reporter.AddGRPCResponseMessage(responseMap) if expect.Message == nil { 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, ) if err != nil { return err } - actualJSON, err := protojson.Marshal( - response, - ) + if matched { + return nil + } + + actualJSON, err := protojson.Marshal(response) if err != nil { return err } - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "message", - Expected: string(expectedJSON), - Actual: string(actualJSON), - }, - ) + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ + Field: string(keys.FieldMessage), + Expected: expect.Message, + Actual: actualJSON, + }) return nil } @@ -143,7 +171,7 @@ 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,25 +182,19 @@ 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 } 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 } } @@ -204,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( @@ -237,9 +248,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..83c1536 100644 --- a/execute/worker/grpc/evaluate_test.go +++ b/execute/worker/grpc/evaluate_test.go @@ -2,10 +2,12 @@ package grpc import ( "context" + "encoding/json" "errors" "reflect" "testing" + "go.uber.org/mock/gomock" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" @@ -16,10 +18,10 @@ 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" + "github.com/e2engine/core/model/matcher" "github.com/e2engine/core/pkg/keys" ) @@ -31,17 +33,17 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { header metadata.MD trailer metadata.MD message map[string]any - expect model.GRPCExpectSpec + expect model.GRPCResponsePattern - expectedStatus string - expectedMetadata map[string][]string - expectedMessage map[string]any - expectedDeviations []model.TestExecutionDeviation + expectedStatus string + expectedDeviations []model.TestExecutionDeviation + expectedPayloadDeviations []model.PayloadDeviation }{ { 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"}, @@ -49,20 +51,150 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponsePattern{ Status: "OK", - Message: map[string]any{ - "name": "actual", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("header-value")}, + "x-trailer": {grpcStringEquals("trailer-value")}, }, + Message: mapPtr(map[string]any{ + "name": "actual", + }), }, expectedStatus: "OK", - expectedMetadata: map[string][]string{ - "x-header": {"header-value"}, + }, + { + name: "unrelated metadata", + header: metadata.MD{ + "x-header": {"header-value"}, + }, + trailer: metadata.MD{ "x-trailer": {"trailer-value"}, }, - expectedMessage: map[string]any{ + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + }, + expectedStatus: "OK", + }, + { + name: "metadata mismatch", + header: metadata.MD{ + "x-header": {"actual"}, + }, + message: map[string]any{ + "name": "actual", + }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("expected")}, + }, + }, + expectedStatus: "OK", + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "expected", + Actual: "actual", + }, + }, + }, + { + name: "expected metadata missing", + message: map[string]any{ "name": "actual", }, + expect: model.GRPCResponsePattern{ + Status: "OK", + Metadata: map[string][]matcher.String{ + "x-header": {grpcStringEquals("expected")}, + }, + }, + expectedStatus: "OK", + expectedDeviations: []model.TestExecutionDeviation{ + { + Field: "metadata.x-header", + Expected: "expected", + Actual: "", + }, + }, + }, + { + 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", @@ -73,14 +205,10 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponsePattern{ Status: "OK", }, - expectedStatus: "NotFound", - expectedMetadata: map[string][]string{}, - expectedMessage: map[string]any{ - "name": "actual", - }, + expectedStatus: "NotFound", expectedDeviations: []model.TestExecutionDeviation{ { Field: "status", @@ -89,27 +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.GRPCExpectSpec{ + expect: model.GRPCResponsePattern{ Status: "OK", - Message: map[string]any{ + Message: mapPtr(map[string]any{ "name": "expected", - }, + }), }, - expectedStatus: "OK", - expectedMetadata: map[string][]string{}, - expectedMessage: map[string]any{ - "name": "actual", - }, - expectedDeviations: []model.TestExecutionDeviation{ + expectedStatus: "OK", + expectedPayloadDeviations: []model.PayloadDeviation{ { - Field: "message", - Expected: `{"name":"expected"}`, - Actual: `{"name":"actual"}`, + Field: "message", + Expected: mapPtr(map[string]any{ + "name": "expected", + }), + Actual: []byte(`{"name":"actual"}`), }, }, }, @@ -118,38 +255,100 @@ func TestEvaluatorEvaluateResponse(t *testing.T) { message: map[string]any{ "name": "actual", }, - expect: model.GRPCExpectSpec{ + expect: model.GRPCResponsePattern{ Status: "OK", }, - expectedStatus: "OK", - expectedMetadata: map[string][]string{}, - expectedMessage: map[string]any{ + expectedStatus: "OK", + }, + { + name: "explicit empty message", + message: map[string]any{}, + 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: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + }, + expectedStatus: "OK", + expectedPayloadDeviations: []model.PayloadDeviation{ + { + Field: "message", + Expected: &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorNonEmpty, + }, + Actual: []byte(`{}`), + }, + }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - response := newTestMessage( - t, - tt.message, + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := newTestEvaluator(reporter) + response := newTestMessage(t, tt.message) + + reporter.EXPECT(). + AddGRPCResponseStatus(tt.expectedStatus) + + for i := range tt.expectedDeviations { + reporter.EXPECT(). + AddDeviation(&tt.expectedDeviations[i]) + } + + expectedMetadata := mergeMetadata( + tt.header, + tt.trailer, ) - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, + reporter.EXPECT(). + AddGRPCResponseMetadata(expectedMetadata) + + expectedMessage := tt.message + if expectedMessage == nil { + expectedMessage = map[string]any{} } - evaluator := newTestEvaluator() + reporter.EXPECT(). + AddGRPCResponseMessage(expectedMessage) + + 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( @@ -157,110 +356,27 @@ 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() +func TestEvaluatorEvaluateResponseUnknownStatus(t *testing.T) { + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, - } + evaluator := newTestEvaluator(reporter) - evaluator := newTestEvaluator() + reporter.EXPECT(). + AddGRPCResponseStatus("OK") err := evaluator.EvaluateResponse( - ctx, - nil, - newTestMessage( - t, - map[string]any{}, - ), - nil, - nil, - &model.GRPCExpectSpec{ - 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{}, - } - - evaluator := newTestEvaluator() - - err := evaluator.EvaluateResponse( - context.Background(), nil, - newTestMessage( - t, - map[string]any{}, - ), + newTestMessage(t, map[string]any{}), nil, nil, - &model.GRPCExpectSpec{ + &model.GRPCResponsePattern{ Status: "invalid", }, - result, ) if !errors.Is(err, ErrUnknownStatus) { @@ -282,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"), @@ -299,21 +410,18 @@ 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) } - evaluator := NewEvaluator(resolver) - actual := call.Call{ 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-empty": {""}, }, Message: messageBytes, }, @@ -324,24 +432,23 @@ func TestEvaluatorMatches(t *testing.T) { name string actual call.Call - expected model.CallExpectation - - match bool + 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"}, + Metadata: map[string][]matcher.String{ + "x-request-id": {grpcStringEquals("request-1")}, }, - Message: map[string]any{ + Message: mapPtr(map[string]any{ "name": "Yaroslav", - }, + }), }, }, match: true, @@ -349,9 +456,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 +469,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 +480,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 +498,13 @@ 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"}, + Metadata: map[string][]matcher.String{ + "x-missing": {grpcStringEquals("value")}, }, }, }, @@ -405,98 +512,202 @@ func TestEvaluatorMatches(t *testing.T) { { name: "metadata mismatch", actual: actual, - expected: model.CallExpectation{ + expected: model.ServiceExpectedCalls{ + ServiceID: "service-1", + GRPC: &model.GRPCRequestPattern{ + Service: "users.UserService", + Method: "Create", + 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.GRPCCallExpectation{ + GRPC: &model.GRPCRequestPattern{ Service: "users.UserService", Method: "Create", - Metadata: map[string][]string{ - "x-request-id": {"different"}, + 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", 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{ + Message: mapPtr(map[string]any{ "name": "Other", - }, + }), }, }, }, { 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", }, }, 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{}), + }, + }, + }, + { + 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, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - match, err := evaluator.Matches( + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(resolver, reporter) + + 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) + service := testServiceSpec() - evaluator := newTestEvaluator() + evaluator := newTestEvaluator(reporter) actual := call.Call{ 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{ + Message: mapPtr(map[string]any{ "name": "Yaroslav", - }, + }), }, } - match, err := evaluator.Matches( + matched, err := evaluator.Matches( context.Background(), service, actual, @@ -507,35 +718,37 @@ 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) + service := testServiceSpec() - evaluator := newTestEvaluator() + evaluator := newTestEvaluator(reporter) actual := call.Call{ 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{ + Message: mapPtr(map[string]any{ "name": "Yaroslav", - }, + }), }, } @@ -546,10 +759,7 @@ func TestEvaluatorMatchesInvalidCapturedMessage( expected, ) - if !errors.Is( - err, - ErrCannotDecodeCapturedRequest, - ) { + if !errors.Is(err, ErrCannotDecodeCapturedRequest) { t.Fatalf( "expected ErrCannotDecodeCapturedRequest, got %v", err, @@ -558,13 +768,14 @@ func TestEvaluatorMatchesInvalidCapturedMessage( } func TestEvaluatorDeviation(t *testing.T) { - evaluator := newTestEvaluator() + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + evaluator := newTestEvaluator(reporter) service := testServiceSpec() tests := []struct { - name string - + name string actual call.Call expected *model.TestExecutionDeviation }{ @@ -580,7 +791,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,15 +806,12 @@ 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{ - string( - keys.E2EngineMockMissMetadata, - ): { - "false", - }, + string(keys.E2EngineMockMissMetadata): {"false"}, }, }, }, @@ -614,15 +823,12 @@ 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{ - string( - keys.E2EngineMockMissMetadata, - ): { - "true", - }, + string(keys.E2EngineMockMissMetadata): {"true"}, }, }, }, @@ -643,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, ) } }) @@ -679,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, @@ -712,10 +897,7 @@ func TestMergeMetadata(t *testing.T) { "x-shared": {"trailer"}, } - actual := mergeMetadata( - header, - trailer, - ) + actual := mergeMetadata(header, trailer) expected := map[string][]string{ "x-header": {"one"}, @@ -723,10 +905,7 @@ func TestMergeMetadata(t *testing.T) { "x-shared": {"header", "trailer"}, } - if !reflect.DeepEqual( - actual, - expected, - ) { + if !reflect.DeepEqual(actual, expected) { t.Errorf( "expected %#v, got %#v", expected, @@ -737,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 { @@ -863,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, @@ -881,9 +981,12 @@ func TestGRPCCodeUnknown(t *testing.T) { } } -func newTestEvaluator() *Evaluator { +func newTestEvaluator( + reporter executionReporter, +) *Evaluator { return NewEvaluator( servicegrpc.NewProtoMethodResolver(nil), + reporter, ) } @@ -936,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(), }, }, }, @@ -955,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) } } @@ -1005,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, @@ -1023,30 +1097,29 @@ func newMapMessage( return message } -func assertGRPCDeviations( - t *testing.T, - actual []model.TestExecutionDeviation, - expected []model.TestExecutionDeviation, -) { - t.Helper() +func mapPtr(value map[string]any) *matcher.GRPCMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) + } - if len(actual) != len(expected) { - t.Fatalf( - "expected %d deviations, got %d: %+v", - len(expected), - len(actual), - actual, - ) + return &matcher.GRPCMessage{ + Operator: matcher.GRPCMessageMatchOperatorEquals, + Value: string(data), + } +} + +func grpcStringEquals(value string) matcher.String { + return matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, } +} - for i := range expected { - if actual[i] != expected[i] { - t.Errorf( - "deviation %d: expected %+v, got %+v", - i, - expected[i], - actual[i], - ) - } +func grpcStringOperator( + operator matcher.StringMatchOperator, +) matcher.String { + return matcher.String{ + Operator: operator, } } 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 83a1137..c4aa36f 100644 --- a/execute/worker/grpc/executor_test.go +++ b/execute/worker/grpc/executor_test.go @@ -2,12 +2,14 @@ package grpc import ( "context" + "encoding/json" "errors" "net" "reflect" "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" @@ -18,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" ) @@ -322,10 +325,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 +343,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 +392,9 @@ func TestExecutorExecute(t *testing.T) { ), ) - return stream.SendMsg(response) + return stream.SendMsg( + response, + ) }, ), ) @@ -395,9 +406,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{ @@ -412,7 +432,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,25 +447,119 @@ func TestExecutorExecute(t *testing.T) { }, }, Expect: model.ExpectSpec{ - GRPC: &model.GRPCExpectSpec{ + GRPC: &model.GRPCResponsePattern{ 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( @@ -453,63 +567,18 @@ 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, - ) - } - - expectedMetadata := map[string][]string{ - "content-type": { - "application/grpc", - }, - "x-header": { - "header-value", - }, - "x-trailer": { - "trailer-value", - }, - } - - if !reflect.DeepEqual( - response.Metadata, - expectedMetadata, - ) { - t.Errorf( - "expected metadata %#v, got %#v", - expectedMetadata, - response.Metadata, - ) +func mapPtrExecutor( + value map[string]any, +) *matcher.GRPCMessage { + data, err := json.Marshal(value) + if err != nil { + panic(err) } - if len(result.Summary.Deviations) != 0 { - t.Errorf( - "expected no deviations, got %+v", - result.Summary.Deviations, - ) + 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 new file mode 100644 index 0000000..969d228 --- /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.PayloadDeviation) { + 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..a2d1fd5 --- /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.PayloadDeviation) + 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 6735dac..8c5a715 100644 --- a/execute/worker/http/evaluate.go +++ b/execute/worker/http/evaluate.go @@ -5,100 +5,156 @@ import ( "encoding/json" "io" "net/http" + "slices" "strconv" + "strings" - "github.com/e2engine/core/execute" "github.com/e2engine/core/execute/call" - "github.com/e2engine/core/execute/evaluate" + "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" ) -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.HTTPExpectSpec, - result *execute.TestExecutionResult, + expect *model.HTTPResponsePattern, ) error { - result.Summary.Response = &model.TestExecutionResponseSummary{ - HTTP: &model.TestExecutionHTTPResponseSummary{StatusCode: resp.StatusCode}, - } - - if resp.StatusCode != expect.Status { - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: "status_code", - Expected: strconv.Itoa(expect.Status), - Actual: strconv.Itoa(resp.StatusCode), - }, - ) + e.evaluateStatusCode(expect.StatusCode, resp.StatusCode) + + e.evaluateHeaders(expect.Headers, resp.Header) + + actualBody, err := io.ReadAll(resp.Body) + if err != nil { + return err } - if expect.Body != "" { - 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 + } + + if expect.Body != nil { + e.reporter.AddHTTPResponseBody(actualBody) - if json.Valid(actualBody) { - result.Summary.Response.HTTP.BodyJSON = util.CompactJSON(actualBody) - - equal, err := util.IsJSONEqual( - []byte(expect.Body), - 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 + if !match.IsStringMatched(actualBody, expect.Body) { + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ + Field: string(keys.FieldBody), + Expected: expect.Body, + Actual: actualBody, + }) } - result.Summary.Response.HTTP.BodyText = string(actualBody) + return nil + } - result.Summary.Deviations = append( - result.Summary.Deviations, - model.TestExecutionDeviation{ - Field: string(keys.FieldBody), - Expected: util.CompactJSON([]byte(expect.Body)), - Actual: string(actualBody), - Message: "response body is not valid JSON", - }, - ) + if !json.Valid(actualBody) { + e.reporter.AddHTTPResponseBodyJSON(actualBody) + + e.reporter.AddPayloadDeviation(&model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: expect.BodyJSON, + Actual: actualBody, + Message: "response body is not valid JSON", + }) return nil } + actualJSON := util.CompactJSON(actualBody) + + e.reporter.AddHTTPResponseBodyJSON(actualJSON) + + matched, err := match.IsJSONMatched( + actualBody, + expect.BodyJSON, + ) + if err != nil { + // Expected JSON has already been validated. + return err + } + + 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, actual call.Call, - expected model.CallExpectation, + expected model.ServiceExpectedCalls, ) (bool, error) { if actual.ServiceID != expected.ServiceID { return false, nil @@ -116,7 +172,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,18 +190,28 @@ func httpCallMatchesExpectation( } for key, expectedValues := range expected.Headers { - actualValues, ok := actual.Headers[key] - if !ok || !util.IsStringSlicesEqual(actualValues, expectedValues) { + canonicalKey := http.CanonicalHeaderKey(key) + actualValues, exists := actual.Headers[canonicalKey] + + if !match.IsStringSliceMatched( + actualValues, + exists, + expectedValues, + ) { return false } } - if expected.Body != "" { - equal, err := util.IsJSONEqual( - []byte(expected.Body), + if expected.Body != nil && !match.IsStringMatched(actual.Body, expected.Body) { + return false + } + + if expected.BodyJSON != nil { + 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 075ce15..f52b508 100644 --- a/execute/worker/http/evaluate_test.go +++ b/execute/worker/http/evaluate_test.go @@ -5,46 +5,64 @@ import ( "errors" "io" nethttp "net/http" + "reflect" "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/model/matcher" "github.com/e2engine/core/pkg/keys" ) func TestEvaluatorEvaluateResponse(t *testing.T) { + type bodyCall struct { + json bool + value string + } + + type deviationCall struct { + deviation *model.TestExecutionDeviation + payload *model.PayloadDeviation + } + tests := []struct { name string - status int - body string - expect model.HTTPExpectSpec + status int + body string + headers nethttp.Header + expect model.HTTPResponsePattern - expectedBodyJSON string - expectedBodyText string - expected []model.TestExecutionDeviation + bodyCall bodyCall + deviations []deviationCall }{ { name: "matching status without body expectation", status: nethttp.StatusOK, body: `{"ignored":true}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + }, + bodyCall: bodyCall{ + value: `{"ignored":true}`, }, }, { name: "status mismatch", status: nethttp.StatusNotFound, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + 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", + }, }, }, }, @@ -52,26 +70,47 @@ 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.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"count":1,"name":"test"}`), + }, + 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"}`, }, - expectedBodyJSON: `{"name":"test","count":1}`, }, { name: "JSON body mismatch", status: nethttp.StatusOK, body: `{"name":"actual"}`, - expect: model.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"name":"expected"}`, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"name":"expected"}`), + }, + bodyCall: bodyCall{ + json: true, + value: `{"name":"actual"}`, }, - expectedBodyJSON: `{"name":"actual"}`, - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: "body", - Expected: `{"name":"expected"}`, - Actual: `{"name":"actual"}`, + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: stringMatcher(`{"name":"expected"}`), + Actual: []byte(`{"name":"actual"}`), + }, }, }, }, @@ -79,17 +118,22 @@ 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.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"message":"hello"}`), + }, + bodyCall: bodyCall{ + value: "hello", + json: true, }, - expectedBodyText: "hello", - expected: []model.TestExecutionDeviation{ + deviations: []deviationCall{ { - Field: "body", - Expected: `{"message":"hello"}`, - Actual: "hello", - Message: "response body is not valid JSON", + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: stringMatcher(`{"message":"hello"}`), + Actual: []byte("hello"), + Message: "response body is not valid JSON", + }, }, }, }, @@ -97,21 +141,309 @@ 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.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"expected":true}`), + }, + bodyCall: bodyCall{ + json: true, + value: `{"actual":true}`, + }, + deviations: []deviationCall{ + { + deviation: &model.TestExecutionDeviation{ + Field: string(keys.FieldStatusCode), + Expected: "200", + Actual: "400", + }, + }, + { + payload: &model.PayloadDeviation{ + Field: string(keys.FieldBodyJSON), + Expected: stringMatcher(`{"expected":true}`), + Actual: []byte(`{"actual":true}`), + }, + }, + }, + }, + { + name: "matching exact text body", + status: nethttp.StatusOK, + body: "plain text body", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcher("plain text body"), + }, + bodyCall: bodyCall{ + value: "plain text body", + }, + }, + { + name: "mismatched exact text body", + status: nethttp.StatusOK, + body: "actual text body", + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcher("expected text body"), + }, + bodyCall: bodyCall{ + value: "actual text body", + }, + deviations: []deviationCall{ + { + 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: stringMatcherOperator(matcher.StringMatchOperatorNonEmpty), + Actual: []byte{}, + }, + }, + }, + }, + { + name: "exists body matches empty body", + status: nethttp.StatusOK, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Body: stringMatcherOperator(matcher.StringMatchOperatorExists), }, - expectedBodyJSON: `{"actual":true}`, - expected: []model.TestExecutionDeviation{ + }, + { + 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 matches", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"value"}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("value")}, + }, + }, + }, + { + name: "unexpected header is ignored", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "Authorization": {"secret"}, + "X-Test": {"value"}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("value")}, + }, + }, + }, + { + name: "header name is case insensitive", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"value"}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "x-test": {stringMatcherValue("value")}, + }, + }, + }, + { + name: "header mismatch", + status: nethttp.StatusOK, + headers: nethttp.Header{ + "X-Test": {"actual"}, + }, + expect: model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("expected")}, + }, + }, + deviations: []deviationCall{ { - Field: "status_code", - Expected: "200", - Actual: "400", + deviation: &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.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + Headers: map[string][]matcher.String{ + "X-Test": {stringMatcherValue("expected")}, }, + }, + deviations: []deviationCall{ { - Field: "body", - Expected: `{"expected":true}`, - Actual: `{"actual":true}`, + deviation: &model.TestExecutionDeviation{ + Field: "headers.X-Test", + Expected: "expected", + }, + }, + }, + }, + { + 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", + }, }, }, }, @@ -119,64 +451,57 @@ 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, + Header: tt.headers, Body: io.NopCloser( strings.NewReader(tt.body), ), } - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, + reporter.EXPECT(). + AddHTTPResponseStatus(tt.status) + + reporter.EXPECT(). + AddHTTPResponseHeaders(tt.headers) + + for _, deviation := range tt.deviations { + if deviation.payload != nil { + reporter.EXPECT(). + AddPayloadDeviation(deviation.payload) + } else { + reporter.EXPECT(). + AddDeviation(deviation.deviation) + } + } + + if tt.bodyCall.json { + reporter.EXPECT(). + AddHTTPResponseBodyJSON( + []byte(tt.bodyCall.value), + ) + } else { + reporter.EXPECT(). + AddHTTPResponseBody( + []byte(tt.bodyCall.value), + ) } 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, - ) - } - - if actual.BodyJSON != tt.expectedBodyJSON { - t.Errorf( - "expected JSON body %q, got %q", - tt.expectedBodyJSON, - actual.BodyJSON, + t.Fatalf( + "EvaluateResponse() error = %v", + err, ) } - - if actual.BodyText != tt.expectedBodyText { - t.Errorf( - "expected text body %q, got %q", - tt.expectedBodyText, - actual.BodyText, - ) - } - - assertDeviations( - t, - result.Summary.Deviations, - tt.expected, - ) }) } } @@ -184,7 +509,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, @@ -193,18 +521,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.HTTPExpectSpec{ - Status: nethttp.StatusOK, - Body: `{"result":"ok"}`, + &model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + BodyJSON: stringMatcher(`{"result":"ok"}`), }, - result, ) if !errors.Is(err, expectedErr) { @@ -217,8 +545,6 @@ func TestEvaluatorEvaluateResponseReadError(t *testing.T) { } func TestEvaluatorMatches(t *testing.T) { - evaluator := NewEvaluator() - actual := call.Call{ ServiceID: "service-1", HTTP: &call.HTTPCall{ @@ -231,20 +557,22 @@ func TestEvaluatorMatches(t *testing.T) { } tests := []struct { - name string + name string + actual call.Call - expected model.CallExpectation - match bool + 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: stringMatcher(`{"name":"Yaroslav"}`), }, }, match: true, @@ -252,9 +580,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 +592,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 +602,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", }, }, @@ -292,21 +620,29 @@ func TestEvaluatorMatches(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - match, err := evaluator.Matches( + ctrl := gomock.NewController(t) + reporter := NewMockexecutionReporter(ctrl) + + evaluator := NewEvaluator(reporter) + + matched, err := evaluator.Matches( context.Background(), &model.ServiceSpec{}, 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, ) } }) @@ -324,14 +660,18 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { Headers: nethttp.Header{ "Content-Type": {"application/json"}, "X-Test": {"one", "two"}, + "X-Empty": {""}, }, Body: []byte(`{"name":"Yaroslav","active":true}`), } tests := []struct { - name string - expected model.HTTPCallExpectation - match bool + name string + + expected model.HTTPRequestPattern + body []byte + + match bool }{ { name: "empty expectation", @@ -339,36 +679,41 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "all fields match", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Method: "POST", Path: "/users", Query: map[string][]string{ "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"), + }, }, - Body: `{"active":true,"name":"Yaroslav"}`, + BodyJSON: stringMatcher( + `{"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 +721,7 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "query mismatch", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "active": {"false"}, }, @@ -384,36 +729,69 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "header missing", - expected: model.HTTPCallExpectation{ - Headers: map[string][]string{ - "X-Missing": {"value"}, + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "X-Missing": {stringMatcherValue("value")}, }, }, }, { name: "header mismatch", - expected: model.HTTPCallExpectation{ - Headers: map[string][]string{ - "Content-Type": {"text/plain"}, + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "Content-Type": {stringMatcherValue("text/plain")}, }, }, }, + { + name: "header name is case insensitive", + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "x-test": { + stringMatcherValue("one"), + stringMatcherValue("two"), + }, + }, + }, + match: true, + }, { name: "JSON body mismatch", - expected: model.HTTPCallExpectation{ - Body: `{"name":"Other"}`, + expected: model.HTTPRequestPattern{ + BodyJSON: stringMatcher( + `{"name":"Other"}`, + ), }, }, { name: "actual body is invalid JSON", - expected: model.HTTPCallExpectation{ - Body: `{"name":"Yaroslav"}`, + expected: model.HTTPRequestPattern{ + BodyJSON: stringMatcher( + `{"name":"Yaroslav"}`, + ), + }, + body: []byte("not-json"), + }, + { + name: "exact text body matches", + expected: model.HTTPRequestPattern{ + Body: stringMatcher( + `{"name":"Yaroslav","active":true}`, + ), + }, + match: true, + }, + { + name: "exact text body mismatch", + expected: model.HTTPRequestPattern{ + Body: stringMatcher( + `{"active":true,"name":"Yaroslav"}`, + ), }, - match: false, }, { name: "query subset matches", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "active": {"true"}, }, @@ -422,16 +800,16 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "headers subset matches", - expected: model.HTTPCallExpectation{ - Headers: map[string][]string{ - "Content-Type": {"application/json"}, + expected: model.HTTPRequestPattern{ + Headers: map[string][]matcher.String{ + "Content-Type": {stringMatcherValue("application/json")}, }, }, match: true, }, { name: "query values match regardless of order", - expected: model.HTTPCallExpectation{ + expected: model.HTTPRequestPattern{ Query: map[string][]string{ "role": {"user", "admin"}, }, @@ -440,33 +818,131 @@ func TestHTTPCallMatchesExpectation(t *testing.T) { }, { name: "header values match regardless of order", - expected: model.HTTPCallExpectation{ - Headers: map[string][]string{ - "X-Test": {"two", "one"}, + expected: model.HTTPRequestPattern{ + 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: stringMatcher(""), + }, + body: []byte{}, + match: true, + }, + { + 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{ + BodyJSON: stringMatcherOperator(matcher.StringMatchOperatorExists), + }, + match: true, + }, } for _, tt := range tests { 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( + matched := httpCallMatchesExpectation( request, &tt.expected, ) - if match != tt.match { + if matched != tt.match { t.Errorf( "expected match %v, got %v", tt.match, - match, + matched, ) } }) @@ -474,15 +950,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 }{ { @@ -518,16 +999,20 @@ 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 }(), }, }, }, 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", }, }, } @@ -539,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, ) } }) @@ -569,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 } @@ -579,30 +1047,32 @@ func (r *errorReader) Close() error { return nil } -func assertDeviations( - t *testing.T, - actual []model.TestExecutionDeviation, - expected []model.TestExecutionDeviation, -) { - t.Helper() +func stringMatcher(value string) *matcher.String { + return &matcher.String{ + Operator: matcher.StringMatchOperatorEquals, + Value: value, + } +} - if len(actual) != len(expected) { - t.Fatalf( - "expected %d deviations, got %d: %+v", - len(expected), - len(actual), - actual, - ) +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, } +} - for i := range expected { - if actual[i] != expected[i] { - t.Errorf( - "deviation %d: expected %+v, got %+v", - i, - expected[i], - actual[i], - ) - } +func stringMatcherOperatorValue( + operator matcher.StringMatchOperator, +) matcher.String { + return matcher.String{ + Operator: operator, } } diff --git a/execute/worker/http/executor.go b/execute/worker/http/executor.go index e62a915..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 } @@ -64,13 +66,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 +88,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 +104,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..b19ef68 100644 --- a/execute/worker/http/executor_test.go +++ b/execute/worker/http/executor_test.go @@ -10,9 +10,11 @@ import ( "testing" e2enginehttp "github.com/e2engine/instrumentation-go/http" + "go.uber.org/mock/gomock" "github.com/e2engine/core/execute" "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" ) func TestBuildHTTPRequest(t *testing.T) { @@ -20,7 +22,7 @@ func TestBuildHTTPRequest(t *testing.T) { tests := []struct { name string - spec *model.HTTPRequestSpec + spec *model.HTTPRequest expectedMethod string expectedURL string @@ -29,7 +31,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 +39,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 +78,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 +126,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 +137,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 +183,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 +215,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 +273,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 +291,7 @@ func TestBuildHTTPRequestCanceledContext(t *testing.T) { req, err := buildHTTPRequest( ctx, - &model.HTTPRequestSpec{ + &model.HTTPRequest{ Method: nethttp.MethodGet, URL: "https://example.com", }, @@ -403,7 +426,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", @@ -425,9 +450,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{ @@ -435,32 +466,77 @@ 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: `{ - "name": "test", - "id": 42 - }`, + HTTP: &model.HTTPResponsePattern{ + StatusCode: nethttp.StatusOK, + 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( + []byte(`{"id":42,"name":"test"}`), + ) err := executor.Execute( context.Background(), job, - result, ) if err != nil { t.Fatalf( @@ -468,33 +544,13 @@ 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, +) *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 new file mode 100644 index 0000000..f22fef9 --- /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 []byte) { + 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 []byte) { + 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.PayloadDeviation) { + 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..9823cf7 --- /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.PayloadDeviation) + AddHTTPRequest(req *http.Request) + AddHTTPResponseStatus(status int) + AddHTTPResponseHeaders(headers http.Header) + 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/calls.go b/execute/worker/reporter/calls.go new file mode 100644 index 0000000..d0b6d3d --- /dev/null +++ b/execute/worker/reporter/calls.go @@ -0,0 +1,153 @@ +package reporter + +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/worker/reporter/calls_test.go b/execute/worker/reporter/calls_test.go new file mode 100644 index 0000000..fb65cd0 --- /dev/null +++ b/execute/worker/reporter/calls_test.go @@ -0,0 +1,803 @@ +package reporter + +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"}`), + }, + }, + }) + + 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, + 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/worker/reporter/reporter.go b/execute/worker/reporter/reporter.go new file mode 100644 index 0000000..da601c7 --- /dev/null +++ b/execute/worker/reporter/reporter.go @@ -0,0 +1,327 @@ +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" + "github.com/e2engine/core/model/matcher" +) + +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) +} + +const dumpDisabled = "" + +func (r *Reporter) AddPayloadDeviation(deviation *model.PayloadDeviation) { + if deviation == nil { + return + } + + r.ensureNotFinalized() + + d := model.TestExecutionDeviation{ + Field: deviation.Field, + Message: deviation.Message, + } + + switch { + case deviation.Expected == nil: + case !r.cfg.DumpPayload: + d.Expected = dumpDisabled + default: + d.Expected = deviation.Expected.String() + } + + 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) { + r.ensureNotFinalized() + + request := &model.HTTPRequest{ + Method: req.Method, + URL: req.URL.String(), + Headers: req.Header.Clone(), + } + + 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 != "" { + switch { + case !r.cfg.DumpPayload: + request.BodyJSON = dumpDisabled + default: + request.BodyJSON = string(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][]matcher.String, +) map[string][]string { + if len(expected) == 0 { + return nil + } + + result := make( + map[string][]string, + len(expected), + ) + + for k := range expected { + values := actual.Values(k) + if len(values) > 0 { + result[k] = util.CloneStringSlice(values) + } + } + + if len(result) == 0 { + return nil + } + + return result +} + +func (r *Reporter) AddHTTPResponseBody(body []byte) { + r.ensureNotFinalized() + r.ensureHTTPResponseSummary() + + 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() + + 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() { + 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 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{ + 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][]matcher.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) { + r.ensureNotFinalized() + r.ensureGRPCResponseSummary() + + 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 new file mode 100644 index 0000000..3de64dd --- /dev/null +++ b/execute/worker/reporter/reporter_test.go @@ -0,0 +1,1215 @@ +package reporter + +import ( + "errors" + "net/http" + "net/url" + "reflect" + "testing" + + "github.com/e2engine/core/model" + "github.com/e2engine/core/model/matcher" +) + +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{}) + }) + + mustPanic(t, func() { + r.AddPayloadDeviation(&model.PayloadDeviation{}) + }) +} + +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) { + tests := []struct { + name string + + dumpPayload bool + expected *matcher.String + actual []byte + + 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, + 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: "", + }, + } + + 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(&model.PayloadDeviation{ + Field: "body", + Expected: tt.expected, + Actual: tt.actual, + Message: "payload differs", + }) + + deviations := r.Result().Summary.Deviations + + if len(deviations) != 1 { + t.Fatalf( + "expected 1 deviation, got %d", + len(deviations), + ) + } + + actual := deviations[0] + + if actual.Field != "body" { + t.Errorf( + "expected field %q, got %q", + "body", + actual.Field, + ) + } + + if actual.Message != "payload differs" { + t.Errorf( + "expected message %q, got %q", + "payload differs", + actual.Message, + ) + } + + if actual.Expected != tt.wantExpected { + t.Errorf( + "expected Expected %q, got %q", + tt.wantExpected, + actual.Expected, + ) + } + + if actual.Actual != tt.wantActual { + t.Errorf( + "expected Actual %q, got %q", + tt.wantActual, + actual.Actual, + ) + } + }) + } +} + +func TestReporterAddHTTPRequest(t *testing.T) { + tests := []struct { + name string + + dumpPayload bool + + expectedBody string + expectedBodyJSON string + }{ + { + name: "payload disabled", + expectedBody: "", + expectedBodyJSON: "", + }, + { + 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) + + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + + 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 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{}, + &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.HTTPResponsePattern{ + Headers: map[string][]matcher.String{ + "X-Included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "X-Missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + }, + }, + } + + 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) { + 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][]matcher.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][]matcher.String{ + "X-Missing": {equals("expected")}, + }, + }, + { + name: "selected headers", + actual: http.Header{ + "X-One": {"1"}, + "X-Two": {"2"}, + "X-Other": {"other"}, + }, + 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 { + 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) { + 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{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBody(tt.body) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + if response.HTTP.Body != tt.want { + t.Errorf( + "expected body %q, got %q", + tt.want, + response.HTTP.Body, + ) + } + }) + } +} + +func TestReporterAddHTTPResponseBodyJSON(t *testing.T) { + 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{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddHTTPResponseBodyJSON(tt.body) + + response := r.Result().Summary.Response + + if response == nil || response.HTTP == nil { + t.Fatal("expected HTTP response summary") + } + + 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 + wantMessage map[string]any + }{ + { + name: "payload disabled", + wantMessage: map[string]any{ + "": nil, + }, + }, + { + name: "payload enabled", + dumpPayload: true, + wantMessage: map[string]any{ + "name": "test", + }, + }, + } + + 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) + + if r.Result().Summary.Request == nil { + t.Fatal("expected request summary") + } + + 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 !reflect.DeepEqual( + actual.Message, + tt.wantMessage, + ) { + t.Errorf( + "expected message %+v, got %+v", + tt.wantMessage, + 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.dumpPayload && + actual.Message["name"] != "test" { + 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{}, + &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.GRPCResponsePattern{ + Metadata: map[string][]matcher.String{ + "x-included": { + { + Operator: matcher.StringMatchOperatorEquals, + Value: "expected", + }, + }, + "x-missing": { + { + Operator: matcher.StringMatchOperatorExists, + }, + }, + }, + }, + }, + } + + 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) { + 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][]matcher.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][]matcher.String{ + "x-missing": {equals("expected")}, + }, + }, + { + name: "selected metadata", + actual: map[string][]string{ + "x-one": {"1"}, + "x-two": {"2"}, + "x-other": {"other"}, + }, + 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 { + 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) { + tests := []struct { + name string + + dumpPayload bool + message map[string]any + want map[string]any + }{ + { + name: "payload disabled", + message: map[string]any{ + "name": "test", + }, + want: map[string]any{ + "": nil, + }, + }, + { + 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, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + r := newReporterForTest( + &Config{ + DumpPayload: tt.dumpPayload, + }, + &model.TestSpec{}, + ) + + r.AddGRPCResponseMessage(tt.message) + + response := r.Result().Summary.Response + + 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 len(tt.message) > 0 { + tt.message["name"] = "changed" + + if tt.dumpPayload && + response.GRPC.Message["name"] != "test" { + t.Error("stored message changed with source") + } + } + }) + } +} + +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 4e799f3..0000000 --- a/execute/worker/summary.go +++ /dev/null @@ -1,84 +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 { - 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)), - }, - } - - case spec.Request.GRPC != nil: - summary.Request = &model.TestExecutionRequestSummary{ - GRPC: &model.TestExecutionGRPCRequestSummary{ - 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 deleted file mode 100644 index 7a3c876..0000000 --- a/execute/worker/summary_test.go +++ /dev/null @@ -1,268 +0,0 @@ -package worker - -import ( - "net/http" - "net/url" - "testing" - - "github.com/e2engine/core/model" -) - -func TestNewSummaryHTTP(t *testing.T) { - spec := &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{ - Method: http.MethodPost, - URL: "https://example.com/users", - Headers: http.Header{ - "Content-Type": {"application/json"}, - }, - 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") - } - - if summary.Request.HTTP == nil { - t.Fatal("expected HTTP request summary") - } - - if summary.Request.GRPC != nil { - t.Fatal("expected nil gRPC request summary") - } - - if summary.ExpectedCalls != nil { - t.Fatal("expected nil expected calls summary") - } - - if summary.Request.HTTP.Method != http.MethodPost { - t.Errorf( - "expected method %q, got %q", - http.MethodPost, - summary.Request.HTTP.Method, - ) - } - - if summary.Request.HTTP.URL != "https://example.com/users" { - t.Errorf( - "unexpected URL %q", - summary.Request.HTTP.URL, - ) - } - - if summary.Request.HTTP.BodyJSON != `{"id":42}` { - t.Errorf( - "expected compact body %q, got %q", - `{"id":42}`, - summary.Request.HTTP.BodyJSON, - ) - } - - spec.Request.HTTP.Headers["Content-Type"][0] = "text/plain" - - if summary.Request.HTTP.Headers["Content-Type"][0] != - "application/json" { - t.Error("expected request headers to be cloned") - } -} - -func TestNewSummaryGRPC(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", - }, - }, - }, - } - - 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") - } - - if summary.ExpectedCalls != nil { - t.Fatal("expected nil expected calls summary") - } - - if summary.Request.GRPC.Service != "users.v1.UserService" { - t.Errorf( - "unexpected service %q", - summary.Request.GRPC.Service, - ) - } - - if summary.Request.GRPC.Method != "GetUser" { - t.Errorf( - "unexpected method %q", - summary.Request.GRPC.Method, - ) - } - - spec.Request.GRPC.Metadata["x-request-id"][0] = "changed" - spec.Request.GRPC.Message["id"] = "changed" - - 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, - ) - } -} - -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{ - Service: "users.v1.UserService", - Method: "GetUser", - Metadata: map[string][]string{ - "x-request-id": {"123"}, - }, - Message: map[string]any{ - "id": "42", - }, - }, - }, - } - - summary := newExpectedCallsSummary(expected) - - if len(summary) != 2 { - t.Fatalf( - "expected 2 summaries, got %d", - len(summary), - ) - } - - httpSummary := summary[0] - - if httpSummary.ServiceID != "http-service" { - t.Errorf( - "unexpected service ID %q", - httpSummary.ServiceID, - ) - } - - if httpSummary.Count != &count && - (httpSummary.Count == nil || *httpSummary.Count != count) { - t.Errorf( - "unexpected count %#v", - httpSummary.Count, - ) - } - - if httpSummary.HTTP == nil { - t.Fatal("expected HTTP call expectation summary") - } - - if httpSummary.HTTP.BodyJSON != `{"id":42}` { - t.Errorf( - "unexpected HTTP body %q", - httpSummary.HTTP.BodyJSON, - ) - } - - grpcSummary := summary[1] - - if grpcSummary.GRPC == nil { - t.Fatal("expected gRPC call expectation summary") - } - - if grpcSummary.GRPC.Service != "users.v1.UserService" { - t.Errorf( - "unexpected service %q", - grpcSummary.GRPC.Service, - ) - } - - 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" - - if httpSummary.HTTP.Query["active"][0] != "true" { - t.Error("expected query to be cloned") - } - - if httpSummary.HTTP.Headers["Content-Type"][0] != - "application/json" { - t.Error("expected headers to be cloned") - } - - if grpcSummary.GRPC.Metadata["x-request-id"][0] != "123" { - t.Error("expected metadata to be cloned") - } - - if grpcSummary.GRPC.Message["id"] != "42" { - t.Error("expected message to be cloned") - } -} diff --git a/execute/worker/worker.go b/execute/worker/worker.go index 9936635..21816c4 100644 --- a/execute/worker/worker.go +++ b/execute/worker/worker.go @@ -8,10 +8,11 @@ import ( "github.com/ygrebnov/errorc" "github.com/e2engine/core/execute" - "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" @@ -22,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( @@ -79,79 +58,103 @@ func (w *Worker) Execute( ) defer cancel() - callStore := job.Runtime.Calls + reporterCfg := w.cfg.Reporter + if reporterCfg == nil { + reporterCfg = &reporterPkg.Config{} + } + reporter := reporterPkg.New( + reporterCfg, + &job.Test.Spec, + job.ExecutionID, + job.TestSuiteExecutionID, + ) - result := &execute.TestExecutionResult{ - ExecutionID: job.ExecutionID, - TestSuiteExecutionID: job.TestSuiteExecutionID, - Summary: newSummary(&job.Test.Spec), + // 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) + + return reporter.Result(), nil } - if err := validateExpectedCalls( - job.Environment.Spec.Services, - job.Test.Spec.Expect.Calls, - ); err != nil { - setExecutionError(result, err) + httpEvaluator := httpworker.NewEvaluator(reporter) - return result, nil + 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") } - executor, err := w.getExecutor(&job.Test.Spec) - if err != nil { - return nil, err + callStore := job.Runtime.Calls + + if errValidate := validateExpectedCalls( + job.Environment.Spec.Services, + job.Test.Spec.Expect.Calls, + ); errValidate != nil { + reporter.SetError(errValidate) + + return reporter.Result(), nil } if err := executor.Execute( runCtx, &job, - result, ); err != nil { - 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 { - setExecutionError(result, err) + reporter.SummarizeCalls(callStore) + reporter.SetError(err) - return result, nil + return reporter.Result(), nil } - 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 (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( services []model.ServiceSpec, - expected []model.CallExpectation, + expected []model.ServiceExpectedCalls, ) error { byID := make(map[string]model.ServiceSpec, len(services)) for i := range services { @@ -215,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 f2fb01d..012da56 100644 --- a/execute/worker/worker_test.go +++ b/execute/worker/worker_test.go @@ -3,31 +3,22 @@ package worker import ( "context" nativeerrors "errors" + "net/http" + "net/http/httptest" "testing" "time" "github.com/e2engine/core/execute" + "github.com/e2engine/core/execute/call" "github.com/e2engine/core/model" "github.com/e2engine/core/pkg/errors" ) -type testProtocolExecutor struct { - err error -} - -func (e *testProtocolExecutor) Execute( - _ context.Context, - _ *execute.TestJob, - _ *execute.TestExecutionResult, -) error { - return e.err -} - func TestValidateExpectedCalls(t *testing.T) { tests := []struct { name string services []model.ServiceSpec - expected []model.CallExpectation + expected []model.ServiceExpectedCalls wantErr bool }{ { @@ -38,10 +29,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 +44,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 +59,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 +75,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 +91,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, @@ -146,97 +137,206 @@ func TestValidateExpectedCalls(t *testing.T) { } } -func TestWorkerGetExecutor(t *testing.T) { - httpExecutor := &testProtocolExecutor{} - grpcExecutor := &testProtocolExecutor{} +func TestWorkerExecutePassed(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer server.Close() + + worker := newHTTPTestWorker( + server.Client(), + ) + + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) - w := &Worker{ - httpExecutor: httpExecutor, - grpcExecutor: grpcExecutor, + result, err := worker.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) } - tests := []struct { - name string - spec *model.TestSpec - expected execute.ProtocolExecutor - wantErr error - }{ - { - name: "HTTP", - spec: &model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{}, - }, - }, - expected: httpExecutor, - }, - { - name: "gRPC", - spec: &model.TestSpec{ - Request: model.RequestSpec{ - GRPC: &model.GRPCRequestSpec{}, - }, - }, - expected: grpcExecutor, - }, - { - name: "unsupported", - spec: &model.TestSpec{}, - wantErr: errors.ErrUnsupportedTestProtocol, - }, + if result == nil { + t.Fatal("expected result") } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actual, err := w.getExecutor(tt.spec) + if result.Status != model.ExecutionStatusPassed { + t.Errorf( + "expected status %q, got %q", + model.ExecutionStatusPassed, + result.Status, + ) + } - if tt.wantErr != nil { - if !nativeerrors.Is(err, tt.wantErr) { - t.Errorf( - "expected error %v, got %v", - tt.wantErr, - err, - ) - } + if len(result.Summary.Deviations) != 0 { + t.Errorf( + "expected no deviations, got %+v", + result.Summary.Deviations, + ) + } - return - } + if result.Summary.Calls != nil { + t.Errorf( + "expected no summarized calls, got %+v", + result.Summary.Calls, + ) + } - if err != nil { - t.Fatalf( - "getExecutor() error = %v", - err, - ) - } + if result.Summary.Error != "" { + t.Errorf( + "expected no summary error, got %q", + result.Summary.Error, + ) + } - if actual != tt.expected { - t.Errorf( - "expected executor %T, got %T", - tt.expected, - actual, - ) - } - }) + if result.FinishedAt.IsZero() { + t.Error("expected FinishedAt") } } -func TestSetExecutionError(t *testing.T) { - result := &execute.TestExecutionResult{ - Summary: &model.TestExecutionSummary{}, +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( + &call.Store{}, + server.URL, + http.StatusOK, + ) + + result, err := worker.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), + ) } - executionErr := nativeerrors.New( - "execution failed", + deviation := result.Summary.Deviations[0] + + if deviation.Field != "status_code" { + t.Errorf( + "expected field %q, got %q", + "status_code", + deviation.Field, + ) + } + + if deviation.Expected != "200" { + t.Errorf( + "expected expected value %q, got %q", + "200", + deviation.Expected, + ) + } + + if deviation.Actual != "418" { + t.Errorf( + "expected actual value %q, got %q", + "418", + deviation.Actual, + ) + } + + if result.Summary.Error != "" { + t.Errorf( + "expected no summary error, got %q", + result.Summary.Error, + ) + } + + if result.FinishedAt.IsZero() { + t.Error("expected FinishedAt") + } +} + +func TestWorkerExecuteExecutorError(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), ) - before := time.Now().UTC() + client := server.Client() + url := server.URL + + server.Close() + + worker := newHTTPTestWorker( + client, + ) + + job := newHTTPTestJob( + &call.Store{}, + url, + http.StatusOK, + ) - setExecutionError( - result, - executionErr, + result, err := worker.Execute( + context.Background(), + job, ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } - after := time.Now().UTC() + if result == nil { + t.Fatal("expected result") + } if result.Status != model.ExecutionStatusError { t.Errorf( @@ -246,58 +346,145 @@ func TestSetExecutionError(t *testing.T) { ) } - if result.Summary.Error != "execution failed" { - t.Errorf( - "expected error %q, got %q", - "execution failed", - result.Summary.Error, + 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 result.FinishedAt.Before(before) || - result.FinishedAt.After(after) { + if result.Summary.Response != nil { t.Errorf( - "unexpected FinishedAt %v", - result.FinishedAt, + "expected no response summary, got %+v", + result.Summary.Response, ) } + + if result.FinishedAt.IsZero() { + t.Error("expected FinishedAt") + } } -func TestWorkerExecuteExecutorError(t *testing.T) { - executionErr := nativeerrors.New( - "execution failed", +func TestWorkerExecuteInvalidExpectedCalls(t *testing.T) { + server := httptest.NewServer( + http.HandlerFunc( + func( + w http.ResponseWriter, + _ *http.Request, + ) { + w.WriteHeader(http.StatusOK) + }, + ), + ) + defer server.Close() + + worker := newHTTPTestWorker( + server.Client(), ) - w := &Worker{ + job := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) + + job.Environment.Spec.Services = + []model.ServiceSpec{ + { + ID: "service-1", + Kind: model.ServiceKindHTTP, + }, + } + + job.Test.Spec.Expect.Calls = + []model.ServiceExpectedCalls{ + { + ServiceID: "unknown", + HTTP: &model.HTTPRequestPattern{ + Method: http.MethodGet, + Path: "/health", + }, + }, + } + + result, err := worker.Execute( + context.Background(), + job, + ) + if err != nil { + t.Fatalf( + "Execute() error = %v", + err, + ) + } + + 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.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, + ) + } + + 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 TestWorkerExecuteInvalidTest(t *testing.T) { + worker := &Worker{ cfg: &Config{ TestTimeout: time.Second, }, - httpExecutor: &testProtocolExecutor{ - err: executionErr, - }, + client: http.DefaultClient, } job := execute.TestJob{ ExecutionID: "execution-1", + Runtime: execute.TestExecutionRuntime{ + Calls: &call.Store{}, + }, Test: model.Test{ - Spec: model.TestSpec{ - Request: model.RequestSpec{ - HTTP: &model.HTTPRequestSpec{}, - }, - Expect: model.ExpectSpec{ - HTTP: &model.HTTPExpectSpec{}, - }, - }, + 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, ) } @@ -314,18 +501,14 @@ func TestWorkerExecuteExecutorError(t *testing.T) { ) } - if result.Summary.Error != executionErr.Error() { - t.Errorf( - "expected summary error %q, got %q", - executionErr.Error(), - result.Summary.Error, - ) + if result.Summary.Error == "" { + t.Error("expected summary error") } - if result.Summary.ExpectedCalls != nil { + if result.Summary.Request != nil { t.Errorf( - "expected no expected calls, got %#v", - result.Summary.ExpectedCalls, + "expected no request summary, got %+v", + result.Summary.Request, ) } @@ -333,3 +516,92 @@ func TestWorkerExecuteExecutorError(t *testing.T) { t.Error("expected FinishedAt") } } + +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 := newHTTPTestJob( + &call.Store{}, + server.URL, + http.StatusOK, + ) + + result, err := worker.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, + ) + } +} + +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.HTTPResponsePattern{ + StatusCode: expectedStatus, + }, + }, + }, + }, + } +} 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 02a5008..a4e77cb 100644 --- a/go.sum +++ b/go.sum @@ -26,18 +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/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/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= 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/mock/Execute.go b/mock/Execute.go new file mode 100644 index 0000000..d0d9e4f --- /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) error { + m.ctrl.T.Helper() + 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 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockProtocolExecutor)(nil).Execute), ctx, job) +} 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..6da7837 --- /dev/null +++ b/model/grpc.go @@ -0,0 +1,40 @@ +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)"` + 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][]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 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 new file mode 100644 index 0000000..4726598 --- /dev/null +++ b/model/http.go @@ -0,0 +1,150 @@ +package model + +import ( + "encoding/json" + "net/url" + "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" +) + +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.ParseRequestURI(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][]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 { + 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 != nil && h.BodyJSON != nil { + return errorc.New( + "HTTP request pattern cannot have both body and body_json set", + ) + } + + 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 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 +} + +// 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 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 9674374..bca218e 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 *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"` } -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..e4e0c92 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,70 +52,57 @@ 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"` } +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 6327dfd..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") @@ -51,7 +53,11 @@ var ( GRPCFieldType = grpc("field.type") GRPCServiceTargetAddress = grpc("service.target.address") - FieldBody = keys.New("body") + 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/test_test.go b/tests/test_test.go index 4ecb004..e715373 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.HTTPResponsePattern{ + StatusCode: 200, }, }, } diff --git a/tests/testexecution_test.go b/tests/testexecution_test.go index 4c9d936..e261dab 100644 --- a/tests/testexecution_test.go +++ b/tests/testexecution_test.go @@ -431,17 +431,18 @@ func modelTestExecution() *model.TestExecution { } func modelTestExecutionSummary() *model.TestExecutionSummary { + bodyJSON := `{"status":"ok"}` 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"}`, + BodyJSON: bodyJSON, }, }, }