internal/buildinfo/buildinfo_test.go
75 lines · 1945 bytes
4 symbols in this file
1package buildinfo
2
3import (
4 "os/exec"
5 "strings"
6 "testing"
7)
8
9// The link-time stamp wins. This is what the Makefile sets, and what a
10// deployed binary reports.
11func TestStringPrefersTheStamp(t *testing.T) {
12 prev := Commit
13 defer func() { Commit = prev }()
14
15 Commit = "abc123def456-dirty"
16 if got := String(); got != "abc123def456-dirty" {
17 t.Errorf("String() = %q, want the stamped value", got)
18 }
19}
20
21// Without a stamp it falls back to the revision the toolchain embeds. Under
22// `go test` that is this checkout, so the result is a short hex revision,
23// possibly with -dirty. It must never be empty.
24func TestStringFallsBackToTheVCSStamp(t *testing.T) {
25 prev := Commit
26 defer func() { Commit = prev }()
27
28 Commit = ""
29 got := String()
30 if got == "" {
31 t.Fatal("String() returned empty; it must always name something")
32 }
33 rev := strings.TrimSuffix(got, "-dirty")
34 if got != "unknown" && len(rev) != 12 {
35 t.Errorf("String() = %q; want \"unknown\" or a 12-char revision", got)
36 }
37}
38
39// The stamp the Makefile computes must match the commit actually checked out,
40// or a deployed binary would name the wrong one.
41func TestMakefileStampMatchesHEAD(t *testing.T) {
42 head, err := exec.Command("git", "rev-parse", "--short=12", "HEAD").Output()
43 if err != nil {
44 t.Skipf("not a git checkout: %v", err)
45 }
46 want := strings.TrimSpace(string(head))
47
48 prev := Commit
49 defer func() { Commit = prev }()
50 Commit = ""
51
52 got := strings.TrimSuffix(String(), "-dirty")
53 if got != "unknown" && got != want {
54 t.Errorf("String() = %q, but HEAD is %q", got, want)
55 }
56}
57
58func TestIdentified(t *testing.T) {
59 prev := Commit
60 defer func() { Commit = prev }()
61
62 for _, c := range []struct {
63 stamp string
64 want bool
65 }{
66 {"b685adf5ab7a", true},
67 {"b685adf5ab7a-dirty", false},
68 {"unknown", false},
69 } {
70 Commit = c.stamp
71 if got := Identified(); got != c.want {
72 t.Errorf("Identified() with stamp %q = %v, want %v", c.stamp, got, c.want)
73 }
74 }
75}