...

Source file src/testing/slogtest/example_test.go

Documentation: testing/slogtest

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

View as plain text