...

Source file src/text/template/link_test.go

Documentation: text/template

     1  // Copyright 2019 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 template_test
     6  
     7  import (
     8  	"bytes"
     9  	"internal/testenv"
    10  	"os"
    11  	"os/exec"
    12  	"path/filepath"
    13  	"testing"
    14  )
    15  
    16  // Issue 36021: verify that text/template doesn't prevent the linker from removing
    17  // unused methods.
    18  func TestLinkerGC(t *testing.T) {
    19  	if testing.Short() {
    20  		t.Skip("skipping in short mode")
    21  	}
    22  	testenv.MustHaveGoBuild(t)
    23  	const prog = `package main
    24  
    25  import (
    26  	_ "text/template"
    27  )
    28  
    29  type T struct{}
    30  
    31  func (t *T) Unused() { println("THIS SHOULD BE ELIMINATED") }
    32  func (t *T) Used() {}
    33  
    34  var sink *T
    35  
    36  func main() {
    37  	var t T
    38  	sink = &t
    39  	t.Used()
    40  }
    41  `
    42  	td := t.TempDir()
    43  
    44  	if err := os.WriteFile(filepath.Join(td, "x.go"), []byte(prog), 0644); err != nil {
    45  		t.Fatal(err)
    46  	}
    47  	cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "x.exe", "x.go")
    48  	cmd.Dir = td
    49  	if out, err := cmd.CombinedOutput(); err != nil {
    50  		t.Fatalf("go build: %v, %s", err, out)
    51  	}
    52  	slurp, err := os.ReadFile(filepath.Join(td, "x.exe"))
    53  	if err != nil {
    54  		t.Fatal(err)
    55  	}
    56  	if bytes.Contains(slurp, []byte("THIS SHOULD BE ELIMINATED")) {
    57  		t.Error("binary contains code that should be deadcode eliminated")
    58  	}
    59  }
    60  

View as plain text