|
| 1 | +package aibridged //nolint:testpackage |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/google/uuid" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + "google.golang.org/protobuf/proto" |
| 11 | + "google.golang.org/protobuf/types/known/anypb" |
| 12 | + "google.golang.org/protobuf/types/known/structpb" |
| 13 | + "google.golang.org/protobuf/types/known/timestamppb" |
| 14 | + |
| 15 | + "github.com/coder/aibridge" |
| 16 | + abpb "github.com/coder/coder/v2/enterprise/aibridged/proto" |
| 17 | + "github.com/coder/coder/v2/testutil" |
| 18 | +) |
| 19 | + |
| 20 | +const ( |
| 21 | + MetaKeyUserAgent = "user-agent" |
| 22 | +) |
| 23 | + |
| 24 | +type mockClient struct { |
| 25 | + abpb.DRPCRecorderClient |
| 26 | + got *abpb.RecordInterceptionRequest |
| 27 | +} |
| 28 | + |
| 29 | +func (mc *mockClient) RecordInterception(ctx context.Context, in *abpb.RecordInterceptionRequest) (*abpb.RecordInterceptionResponse, error) { |
| 30 | + mc.got = in |
| 31 | + return &abpb.RecordInterceptionResponse{}, nil |
| 32 | +} |
| 33 | + |
| 34 | +func mustAnypbNew(t *testing.T, src proto.Message) *anypb.Any { |
| 35 | + ret, err := anypb.New(src) |
| 36 | + require.NoError(t, err) |
| 37 | + return ret |
| 38 | +} |
| 39 | + |
| 40 | +func TestRecordInterception(t *testing.T) { |
| 41 | + t.Parallel() |
| 42 | + |
| 43 | + tests := []struct { |
| 44 | + name string |
| 45 | + apiKeyID string |
| 46 | + userAgent string |
| 47 | + in aibridge.InterceptionRecord |
| 48 | + expect *abpb.RecordInterceptionRequest |
| 49 | + }{ |
| 50 | + { |
| 51 | + name: "ok", |
| 52 | + apiKeyID: "key", |
| 53 | + in: aibridge.InterceptionRecord{ |
| 54 | + ID: uuid.UUID{1}.String(), |
| 55 | + InitiatorID: uuid.UUID{2}.String(), |
| 56 | + Provider: "prov", |
| 57 | + Model: "model", |
| 58 | + UserAgent: "user-agent", |
| 59 | + Metadata: map[string]any{"some": "data"}, |
| 60 | + StartedAt: time.UnixMicro(123), |
| 61 | + }, |
| 62 | + expect: &abpb.RecordInterceptionRequest{ |
| 63 | + Id: uuid.UUID{1}.String(), |
| 64 | + ApiKeyId: "key", |
| 65 | + InitiatorId: uuid.UUID{2}.String(), |
| 66 | + Provider: "prov", |
| 67 | + Model: "model", |
| 68 | + UserAgent: "user-agent", |
| 69 | + Metadata: map[string]*anypb.Any{ |
| 70 | + "some": mustAnypbNew(t, structpb.NewStringValue("data")), |
| 71 | + }, |
| 72 | + StartedAt: timestamppb.New(time.UnixMicro(123)), |
| 73 | + }, |
| 74 | + }, |
| 75 | + } |
| 76 | + |
| 77 | + for _, tc := range tests { |
| 78 | + t.Run(tc.name, func(t *testing.T) { |
| 79 | + t.Parallel() |
| 80 | + ctx := testutil.Context(t, testutil.WaitShort) |
| 81 | + |
| 82 | + mc := &mockClient{} |
| 83 | + rt := &recorderTranslation{ |
| 84 | + apiKeyID: tc.apiKeyID, |
| 85 | + client: mc, |
| 86 | + } |
| 87 | + rt.RecordInterception(ctx, &tc.in) |
| 88 | + require.Equal(t, tc.expect, mc.got) |
| 89 | + }) |
| 90 | + } |
| 91 | +} |
0 commit comments