Debian Codegraph @

slog/slogtest/example_test.go

raw symbols SCIP
1 package slogtest_test
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7
8 "golang.org/x/exp/slog"
9 "golang.org/x/exp/slog/slogtest"
10 )
11
12 // This example demonstrates one technique for testing a handler with this
13 // package. The handler is given a [bytes.Buffer] to write to, and each line
14 // of the resulting output is parsed.
15 // For JSON output, [encoding/json.Unmarshal] produces a result in the desired
16 // format when given a pointer to a map[string]any.
17 func Example_parsing() {
18 var buf bytes.Buffer
19 h := slog.NewJSONHandler(&buf, nil)
20
21 results := func() []map[string]any {
22 var ms []map[string]any
23 for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) {
24 if len(line) == 0 {
25 continue
26 }
27 var m map[string]any
28 if err := json.Unmarshal(line, &m); err != nil {
29 panic(err) // In a real test, use t.Fatal.
30 }
31 ms = append(ms, m)
32 }
33 return ms
34 }
35 err := slogtest.TestHandler(h, results)
36 fmt.Println(err)
37
38 // Output:
39 // <nil>
40 }