diff options
| author | Jonathan Amsterdam <jba@google.com> | 2023-04-23 11:23:53 -0400 |
|---|---|---|
| committer | Jonathan Amsterdam <jba@google.com> | 2023-04-24 18:07:26 +0000 |
| commit | c80cedec9378b0a1cd5cb400e179bb25e2e7f810 (patch) | |
| tree | fd0da6d5813983dd701d6b1a359d61718548e811 /src/testing/slogtest/example_test.go | |
| parent | ddd822e5ca0e686ae64d921bcfe28119c34278fb (diff) | |
| download | go-c80cedec9378b0a1cd5cb400e179bb25e2e7f810.tar.xz | |
testing/slogtest: tests for slog handlers
Add a package for testing that a slog.Handler implementation
satisfies that interface's documented requirements.
Code copied from x/exp/slog/slogtest.
Updates #56345.
Change-Id: I89e94d93bfbe58e3c524758f7ac3c3fba2a2ea96
Reviewed-on: https://go-review.googlesource.com/c/go/+/487895
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
Diffstat (limited to 'src/testing/slogtest/example_test.go')
| -rw-r--r-- | src/testing/slogtest/example_test.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/src/testing/slogtest/example_test.go b/src/testing/slogtest/example_test.go new file mode 100644 index 0000000000..61e4b46e12 --- /dev/null +++ b/src/testing/slogtest/example_test.go @@ -0,0 +1,44 @@ +// Copyright 2023 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package slogtest_test + +import ( + "bytes" + "encoding/json" + "log" + "log/slog" + "testing/slogtest" +) + +// This example demonstrates one technique for testing a handler with this +// package. The handler is given a [bytes.Buffer] to write to, and each line +// of the resulting output is parsed. +// For JSON output, [encoding/json.Unmarshal] produces a result in the desired +// format when given a pointer to a map[string]any. +func Example_parsing() { + var buf bytes.Buffer + h := slog.NewJSONHandler(&buf) + + results := func() []map[string]any { + var ms []map[string]any + for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) { + if len(line) == 0 { + continue + } + var m map[string]any + if err := json.Unmarshal(line, &m); err != nil { + panic(err) // In a real test, use t.Fatal. + } + ms = append(ms, m) + } + return ms + } + err := slogtest.TestHandler(h, results) + if err != nil { + log.Fatal(err) + } + + // Output: +} |
