summaryrefslogtreecommitdiffstats
path: root/tpl/internal/go_templates/texttemplate/link_test.go
blob: 3db8c21e3aa8234286a18a86fd3ba970c31557ee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build go1.13

package template_test

import (
	"bytes"
	"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

// Issue 36021: verify that text/template doesn't prevent the linker from removing
// unused methods.
func _TestLinkerGC(t *testing.T) {
	if testing.Short() {
		t.Skip("skipping in short mode")
	}
	testenv.MustHaveGoBuild(t)
	const prog = `package main

import (
	_ "text/template"
)

type T struct{}

func (t *T) Unused() { println("THIS SHOULD BE ELIMINATED") }
func (t *T) Used() {}

var sink *T

func main() {
	var t T
	sink = &t
	t.Used()
}
`
	td, err := ioutil.TempDir("", "text_template_TestDeadCodeElimination")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(td)

	if err := ioutil.WriteFile(filepath.Join(td, "x.go"), []byte(prog), 0644); err != nil {
		t.Fatal(err)
	}
	cmd := exec.Command(testenv.GoToolPath(t), "build", "-o", "x.exe", "x.go")
	cmd.Dir = td
	if out, err := cmd.CombinedOutput(); err != nil {
		t.Fatalf("go build: %v, %s", err, out)
	}
	slurp, err := ioutil.ReadFile(filepath.Join(td, "x.exe"))
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Contains(slurp, []byte("THIS SHOULD BE ELIMINATED")) {
		t.Error("binary contains code that should be deadcode eliminated")
	}
}