github.com/go-asm/go@v1.21.1-0.20240213172139-40c5ead50c48/cmd/link/ld/deadcode_test.go (about)

     1  // Copyright 2020 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 ld
     6  
     7  import (
     8  	"bytes"
     9  	"path/filepath"
    10  	"testing"
    11  
    12  	"github.com/go-asm/go/testenv"
    13  )
    14  
    15  func TestDeadcode(t *testing.T) {
    16  	testenv.MustHaveGoBuild(t)
    17  	t.Parallel()
    18  
    19  	tmpdir := t.TempDir()
    20  
    21  	tests := []struct {
    22  		src      string
    23  		pos, neg []string // positive and negative patterns
    24  	}{
    25  		{"reflectcall", nil, []string{"main.T.M"}},
    26  		{"typedesc", nil, []string{"type:main.T"}},
    27  		{"ifacemethod", nil, []string{"main.T.M"}},
    28  		{"ifacemethod2", []string{"main.T.M"}, nil},
    29  		{"ifacemethod3", []string{"main.S.M"}, nil},
    30  		{"ifacemethod4", nil, []string{"main.T.M"}},
    31  		{"ifacemethod5", []string{"main.S.M"}, nil},
    32  		{"ifacemethod6", []string{"main.S.M"}, []string{"main.S.N"}},
    33  		{"structof_funcof", []string{"main.S.M"}, []string{"main.S.N"}},
    34  		{"globalmap", []string{"main.small", "main.effect"},
    35  			[]string{"main.large"}},
    36  	}
    37  	for _, test := range tests {
    38  		test := test
    39  		t.Run(test.src, func(t *testing.T) {
    40  			t.Parallel()
    41  			src := filepath.Join("testdata", "deadcode", test.src+".go")
    42  			exe := filepath.Join(tmpdir, test.src+".exe")
    43  			cmd := testenv.Command(t, testenv.GoToolPath(t), "build", "-ldflags=-dumpdep", "-o", exe, src)
    44  			out, err := cmd.CombinedOutput()
    45  			if err != nil {
    46  				t.Fatalf("%v: %v:\n%s", cmd.Args, err, out)
    47  			}
    48  			for _, pos := range test.pos {
    49  				if !bytes.Contains(out, []byte(pos+"\n")) {
    50  					t.Errorf("%s should be reachable. Output:\n%s", pos, out)
    51  				}
    52  			}
    53  			for _, neg := range test.neg {
    54  				if bytes.Contains(out, []byte(neg+"\n")) {
    55  					t.Errorf("%s should not be reachable. Output:\n%s", neg, out)
    56  				}
    57  			}
    58  		})
    59  	}
    60  }