github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/text/template/link_test.go (about) 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, err := os.MkdirTemp("", "text_template_TestDeadCodeElimination") 43 if err != nil { 44 t.Fatal(err) 45 } 46 defer os.RemoveAll(td) 47 48 if err := os.WriteFile(filepath.Join(td, "x.go"), []byte(prog), 0644); err != nil { 49 t.Fatal(err) 50 } 51 cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "x.exe", "x.go") 52 cmd.Dir = td 53 if out, err := cmd.CombinedOutput(); err != nil { 54 t.Fatalf("go build: %v, %s", err, out) 55 } 56 slurp, err := os.ReadFile(filepath.Join(td, "x.exe")) 57 if err != nil { 58 t.Fatal(err) 59 } 60 if bytes.Contains(slurp, []byte("THIS SHOULD BE ELIMINATED")) { 61 t.Error("binary contains code that should be deadcode eliminated") 62 } 63 }