Skip to content

Commit f2ba5f1

Browse files
committed
add test for list attributes
1 parent a7bd22a commit f2ba5f1

1 file changed

Lines changed: 73 additions & 0 deletions

File tree

handler_test.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,79 @@ func TestSlog(t *testing.T) {
3232
}
3333
}
3434

35+
func TestListAttributes(t *testing.T) {
36+
type testStruct struct {
37+
text string
38+
}
39+
40+
testCases := []struct {
41+
attribute slog.Attr
42+
expectedOutput string
43+
}{
44+
{
45+
attribute: slog.Any("stringList", []string{"test1", "test2", "test3"}),
46+
expectedOutput: ` stringList:
47+
- test1
48+
- test2
49+
- test3`,
50+
},
51+
{
52+
attribute: slog.Any("structList", []testStruct{{"test1"}, {"test2"}}),
53+
expectedOutput: ` structList:
54+
- {test1}
55+
- {test2}`,
56+
},
57+
{
58+
attribute: slog.Any("multilineStringList", []string{`multiline
59+
string 1`, `multiline
60+
string 2`}),
61+
expectedOutput: ` multilineStringList:
62+
- multiline
63+
string 1
64+
- multiline
65+
string 2`,
66+
},
67+
{
68+
attribute: slog.Any("multilineStructList", []testStruct{{`multiline
69+
string 1`}, {`multiline
70+
string 2`}}),
71+
expectedOutput: ` multilineStructList:
72+
- {multiline
73+
string 1}
74+
- {multiline
75+
string 2}`,
76+
},
77+
{
78+
attribute: slog.Any("singleListItem", []string{"single"}),
79+
expectedOutput: " singleListItem: single",
80+
},
81+
}
82+
83+
for _, testCase := range testCases {
84+
t.Run(testCase.attribute.Key, func(t *testing.T) {
85+
var buf bytes.Buffer
86+
logger := slog.New(devlog.NewHandler(&buf, &devlog.Options{DisableColors: true}))
87+
logger.Info("", testCase.attribute)
88+
89+
output := buf.String()
90+
t.Log(output)
91+
if !strings.Contains(output, testCase.expectedOutput) {
92+
t.Errorf(`log output did not contain list attribute as expected
93+
got:
94+
----------------------------------------
95+
%s
96+
----------------------------------------
97+
98+
want:
99+
----------------------------------------
100+
%s
101+
----------------------------------------
102+
`, output, testCase.expectedOutput)
103+
}
104+
})
105+
}
106+
}
107+
35108
// slogtest.TestHandler requires us to parse our logging output to a []map[string]any.
36109
func parseLogEntries(data string) ([]map[string]any, error) {
37110
entryStrings := strings.Split(data, "\n[")

0 commit comments

Comments
 (0)