github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/testing/slogtest/example_test.go (about) 1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package slogtest_test 6 7 import ( 8 "github.com/shogo82148/std/bytes" 9 "github.com/shogo82148/std/encoding/json" 10 "github.com/shogo82148/std/log" 11 "github.com/shogo82148/std/log/slog" 12 "github.com/shogo82148/std/testing/slogtest" 13 ) 14 15 // この例は、このパッケージを使用してハンドラをテストする一つの手法を示しています。 16 // ハンドラには [bytes.Buffer] が書き込み用に与えられ、結果の出力の各行が解析されます。 17 // JSON出力の場合、[encoding/json.Unmarshal] はmap[string]anyへのポインタを与えると、 18 // 望ましい形式の結果を生成します。 19 func Example_parsing() { 20 var buf bytes.Buffer 21 h := slog.NewJSONHandler(&buf, nil) 22 23 results := func() []map[string]any { 24 var ms []map[string]any 25 for _, line := range bytes.Split(buf.Bytes(), []byte{'\n'}) { 26 if len(line) == 0 { 27 continue 28 } 29 var m map[string]any 30 if err := json.Unmarshal(line, &m); err != nil { 31 panic(err) // 実際のテストでは、t.Fatalを使用します。 32 } 33 ms = append(ms, m) 34 } 35 return ms 36 } 37 err := slogtest.TestHandler(h, results) 38 if err != nil { 39 log.Fatal(err) 40 } 41 42 // Output: 43 }