Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text