-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathmanagedidentity_with_logger_test.go
More file actions
80 lines (64 loc) · 2.35 KB
/
managedidentity_with_logger_test.go
File metadata and controls
80 lines (64 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//go:build go1.21
package managedidentity
import (
"bytes"
"context"
"log/slog"
"net/http"
"strings"
"testing"
"github.com/AzureAD/microsoft-authentication-library-for-go/apps/internal/mock"
)
type BufferHandler struct {
buf bytes.Buffer
level slog.Level
}
func (h *BufferHandler) Enabled(ctx context.Context, level slog.Level) bool {
return level <= h.level
}
func (h *BufferHandler) Handle(ctx context.Context, record slog.Record) error {
h.buf.WriteString(record.Message + " ")
record.Attrs(func(attr slog.Attr) bool {
h.buf.WriteString(attr.Key + "=" + attr.Value.String() + " ")
return true
})
return nil
}
func (h *BufferHandler) WithAttrs(attrs []slog.Attr) slog.Handler { return h }
func (h *BufferHandler) WithGroup(name string) slog.Handler { return h }
func TestClientLogging(t *testing.T) {
mockClient := mock.Client{}
headers := http.Header{}
headers.Set("www-authenticate", "Basic realm=/path/to/secret.key")
mockClient.AppendResponse(mock.WithHTTPStatusCode(http.StatusUnauthorized), mock.WithHTTPHeader(headers))
bufferHandler := &BufferHandler{}
customLogger := slog.New(bufferHandler)
client, err := New(SystemAssigned(), WithHTTPClient(&mockClient), WithLogger(customLogger, false))
if err != nil {
t.Fatal(err)
}
_, _ = client.AcquireToken(context.Background(), "https://resource")
logOutput := bufferHandler.buf.String()
expectedLogMessage := "Managed Identity"
if !strings.Contains(logOutput, expectedLogMessage) {
t.Errorf("expected log message %q not found in output", expectedLogMessage)
}
}
func TestClientLogging_CustomHandler(t *testing.T) {
mockClient := mock.Client{}
headers := http.Header{}
headers.Set("www-authenticate", "Basic realm=/path/to/secret.key")
mockClient.AppendResponse(mock.WithHTTPStatusCode(http.StatusUnauthorized), mock.WithHTTPHeader(headers))
filteredBufferHandler := &BufferHandler{level: slog.LevelDebug}
customLogger := slog.New(filteredBufferHandler)
client, err := New(SystemAssigned(), WithHTTPClient(&mockClient), WithLogger(customLogger, false))
if err != nil {
t.Fatal(err)
}
_, _ = client.AcquireToken(context.Background(), "https://resource")
logOutput := filteredBufferHandler.buf.String()
unexpectedLogMessage := "Managed Identity"
if strings.Contains(logOutput, unexpectedLogMessage) {
t.Errorf("unexpected log message %q found in output", unexpectedLogMessage)
}
}