Source file src/log/slog/dependency_test.go

     1  // Copyright 2026 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 slog
     6  
     7  import (
     8  	"bytes"
     9  	"internal/testenv"
    10  	"os"
    11  	"path/filepath"
    12  	"testing"
    13  )
    14  
    15  // Test that TextHandler doesn't pull in the full encoding/json package.
    16  func TestTextHandlerDependency(t *testing.T) {
    17  	testenv.MustHaveGoBuild(t)
    18  	t.Parallel()
    19  
    20  	tempDir := t.TempDir()
    21  	main := filepath.Join(tempDir, "main.go")
    22  	if err := os.WriteFile(main, []byte(`
    23  package main
    24  import (
    25  	"log/slog"
    26  	"os"
    27  )
    28  func main() {
    29  	h := slog.NewTextHandler(os.Stderr, nil)
    30  	l := slog.New(h)
    31  	l.Info("hello")
    32  }
    33  `), 0644); err != nil {
    34  		t.Fatal(err)
    35  	}
    36  
    37  	binary := filepath.Join(tempDir, "main.exe")
    38  	goBin := testenv.GoToolPath(t)
    39  	out, err := testenv.Command(t, goBin, "build", "-o", binary, main).CombinedOutput()
    40  	if err != nil {
    41  		t.Fatalf("go build failed: %v\n%s", err, out)
    42  	}
    43  
    44  	out, err = testenv.Command(t, goBin, "tool", "nm", binary).CombinedOutput()
    45  	if err != nil {
    46  		t.Fatalf("go tool nm failed: %v\n%s", err, out)
    47  	}
    48  
    49  	// We expect some encoding/json symbols due to initialization of global variables
    50  	// in encoding/json, but we don't expect the JSON encoder or slog's JSON value
    51  	// formatting to be linked in if we only use TextHandler.
    52  	forbiddenSyms := []string{
    53  		"log/slog.appendJSONMarshal",
    54  		"encoding/json.(*Encoder).Encode",
    55  	}
    56  
    57  	for _, sym := range forbiddenSyms {
    58  		if bytes.Contains(out, []byte(sym)) {
    59  			t.Errorf("TextHandler program unexpectedly links in %q", sym)
    60  		}
    61  	}
    62  }
    63  

View as plain text