Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for API field validation #5071

Merged
merged 1 commit into from
Nov 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions internal/api/api_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// SPDX-FileCopyrightText: Copyright 2024 The Minder Authors
// SPDX-License-Identifier: Apache-2.0

package api

import (
"context"
"testing"

"github.com/google/uuid"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"

"github.com/mindersec/minder/internal/util/ptr"
v1 "github.com/mindersec/minder/pkg/api/protobuf/go/minder/v1"
)

func TestProtoValidationInterceptor(t *testing.T) {
t.Parallel()

tests := []struct {
name string
req proto.Message
errMsg string
errCode codes.Code
}{
{
name: "valid request",
req: &v1.GetProviderRequest{
Context: &v1.Context{
Project: ptr.Ptr(uuid.New().String()),
},
Name: "valid-name",
},
},
{
name: "invalid request",
req: &v1.GetProviderRequest{
Context: &v1.Context{
Project: ptr.Ptr(uuid.New().String()),
},
Name: "-?invalid",
},
errMsg: "Validation failed:\n- Field 'name': value does not match regex pattern",
errCode: codes.InvalidArgument,
},
}

validator, err := NewValidator()
require.NoError(t, err)

interceptor := ProtoValidationInterceptor(validator)

for _, tt := range tests {
tt := tt

t.Run(tt.name, func(t *testing.T) {
t.Parallel()

handler := func(_ context.Context, _ interface{}) (interface{}, error) {
return "response", nil
}
resp, err := interceptor(context.Background(), tt.req, nil, handler)
if tt.errMsg != "" {
require.Error(t, err)
require.Nil(t, resp)
st, ok := status.FromError(err)
require.True(t, ok)
require.Equal(t, tt.errCode, st.Code())
require.Contains(t, st.Message(), tt.errMsg)
return
}

require.NoError(t, err)
require.Equal(t, "response", resp)
})
}
}