Debian Codegraph @

dead_code_test.go

raw
1 package json_test
2
3 import (
4 "os"
5 "os/exec"
6 "path/filepath"
7 "strings"
8 "testing"
9 )
10
11 // deadCodeProgram uses the encoders and the decoders of go-json on values with marshalers and unmarshalers.
12 const deadCodeProgram = `package main
13
14 import (
15 "bytes"
16 "context"
17 "fmt"
18 "net/netip"
19 "time"
20
21 "github.com/goccy/go-json"
22 )
23
24 type stamp struct{ time.Time }
25
26 type record struct {
27 At time.Time
28 Stamp stamp
29 Addr netip.Addr
30 Any any
31 Map map[string]any
32 }
33
34 func main() {
35 v := record{At: time.Unix(0, 0).UTC(), Addr: netip.MustParseAddr("::1"), Any: 1, Map: map[string]any{"a": 1}}
36 b, err := json.Marshal(v)
37 fmt.Println(string(b), err)
38 b, err = json.MarshalIndent(v, "", " ")
39 fmt.Println(string(b), err)
40 b, err = json.MarshalContext(context.Background(), v)
41 fmt.Println(string(b), err)
42 var buf bytes.Buffer
43 fmt.Println(json.NewEncoder(&buf).Encode(v))
44 var r record
45 fmt.Println(json.Unmarshal(b, &r), r)
46 fmt.Println(json.NewDecoder(&buf).Decode(&r))
47 }
48 `
49
50 // go-json looks the methods of the marshalers up by reflect with their names as constants only: a lookup by a name
51 // the compiler can't see as a constant makes the linker keep every exported method of every type of a program
52 // which imports go-json ( see runtime.MethodLookup ). The linker marks the functions with such a lookup as
53 // <ReflectMethod> in the dependencies it dumps.
54 func TestNoReflectMethodLookupByVariableName(t *testing.T) {
55 if testing.Short() {
56 t.Skip("builds a program")
57 }
58 root, err := os.Getwd()
59 if err != nil {
60 t.Fatal(err)
61 }
62 dir := t.TempDir()
63 goMod := "module deadcode\n\ngo 1.21\n\nrequire github.com/goccy/go-json v0.0.0\n\nreplace github.com/goccy/go-json => " +
64 filepath.ToSlash(root) + "\n"
65 if err := os.WriteFile(filepath.Join(dir, "go.mod"), []byte(goMod), 0o600); err != nil {
66 t.Fatal(err)
67 }
68 if err := os.WriteFile(filepath.Join(dir, "main.go"), []byte(deadCodeProgram), 0o600); err != nil {
69 t.Fatal(err)
70 }
71 goCmd, err := exec.LookPath("go")
72 if err != nil {
73 t.Skip("the go command is not found")
74 }
75 cmd := exec.Command(goCmd, "build", "-ldflags=-dumpdep", "-o", filepath.Join(dir, "program"), ".")
76 cmd.Dir = dir
77 cmd.Env = append(os.Environ(), "GOFLAGS=-mod=mod", "GOWORK=off")
78 out, err := cmd.CombinedOutput()
79 if err != nil {
80 t.Fatalf("go build: %v\n%s", err, out)
81 }
82 marked := map[string]bool{}
83 for _, line := range strings.Split(string(out), "\n") {
84 // the dump is "caller -> callee", each followed by <ReflectMethod> if it is marked.
85 for _, fn := range strings.Split(line, " -> ") {
86 if name, ok := strings.CutSuffix(strings.TrimSpace(fn), " <ReflectMethod>"); ok && strings.HasPrefix(name, "github.com/goccy/go-json") {
87 marked[name] = true
88 }
89 }
90 }
91 for name := range marked {
92 t.Errorf("%s looks a method up by reflect with a name which is not a constant", name)
93 }
94 }