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