Skip to content

Commit d68fe7e

Browse files
committed
simplify token validation and add unit tests
1 parent c4b962d commit d68fe7e

File tree

2 files changed

+69
-7
lines changed

2 files changed

+69
-7
lines changed

internal/grpc/grpc.go

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -266,13 +266,6 @@ func validateTokenFile(path string) (string, error) {
266266
return "", errors.New("token file path is empty")
267267
}
268268

269-
slog.Debug("Checking token file", "path", path)
270-
_, err := os.Stat(path)
271-
if err != nil {
272-
slog.Error("Unable to find token file", "path", path, "error", err)
273-
return "", err
274-
}
275-
276269
slog.Debug("Reading dataplane key from file", "path", path)
277270
var keyVal string
278271
keyBytes, err := os.ReadFile(path)

internal/grpc/grpc_test.go

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package grpc
88
import (
99
"context"
1010
"fmt"
11+
"os"
1112
"testing"
1213

1314
"github.com/cenkalti/backoff/v4"
@@ -352,3 +353,71 @@ func Test_ValidateGrpcError(t *testing.T) {
352353
result = ValidateGrpcError(status.Errorf(codes.InvalidArgument, "error"))
353354
assert.IsType(t, &backoff.PermanentError{}, result)
354355
}
356+
357+
func Test_validateTokenFile(t *testing.T) {
358+
type args struct {
359+
path string
360+
}
361+
tests := []struct {
362+
name string
363+
createToken bool
364+
args args
365+
want string
366+
wantErrMsg string
367+
}{
368+
{
369+
name: "File exists",
370+
createToken: true,
371+
args: args{
372+
path: "test-tkn",
373+
},
374+
want: "test-tkn",
375+
wantErrMsg: "",
376+
},
377+
{
378+
name: "File does not exist",
379+
createToken: false,
380+
args: args{
381+
path: "test-tkn",
382+
},
383+
want: "",
384+
wantErrMsg: "open test-tkn: no such file or directory",
385+
},
386+
{
387+
name: "Empty path",
388+
createToken: false,
389+
args: args{
390+
path: "",
391+
},
392+
want: "",
393+
wantErrMsg: "token file path is empty",
394+
},
395+
}
396+
for _, tt := range tests {
397+
t.Run(tt.name, func(t *testing.T) {
398+
defer func() {
399+
if tt.createToken {
400+
err := os.Remove(tt.args.path)
401+
if err != nil {
402+
t.Log(err)
403+
}
404+
}
405+
}()
406+
407+
if tt.createToken {
408+
err := os.WriteFile(tt.args.path, []byte(tt.args.path), 0666)
409+
if err != nil {
410+
t.Fatal(err)
411+
}
412+
}
413+
414+
got, err := validateTokenFile(tt.args.path)
415+
if err != nil {
416+
if err.Error() != tt.wantErrMsg {
417+
t.Errorf("validateTokenFile() error = %v, wantErr %v", err, tt.wantErrMsg)
418+
}
419+
}
420+
assert.Equalf(t, tt.want, got, "validateTokenFile(%v)", tt.args.path)
421+
})
422+
}
423+
}

0 commit comments

Comments
 (0)