package version import ( "bytes" "encoding/json" "runtime/debug" "strings" "testing" ) func run(t *testing.T, i Info, args ...string) (int, string, string) { t.Helper() var out, errOut bytes.Buffer code := i.Run(args, &out, &errOut) return code, out.String(), errOut.String() } func noBuildInfo(t *testing.T) { t.Helper() old := readBuildInfo readBuildInfo = func() (*debug.BuildInfo, bool) { return nil, false } t.Cleanup(func() { readBuildInfo = old }) } func TestText(t *testing.T) { noBuildInfo(t) code, out, _ := run(t, Info{Program: "yatool", Version: "0.2.0", Commit: "abc1234", BuildDate: "2026-10-23T10:00:00Z"}) if code != ExitOK { t.Fatalf("code %d", code) } for _, want := range []string{"yatool version 0.2.0\n", "commit: abc1234\n", "built: 2026-10-23T10:00:00Z\n", "go: go"} { if !strings.Contains(out, want) { t.Errorf("output %q lacks %q", out, want) } } } func TestJSON(t *testing.T) { noBuildInfo(t) i := Info{Program: "yasta", Version: "v0.11.1", Commit: "eb3675a", BuildDate: "x", Contracts: map[string][]int{"envelope": {1}, "session": {1, 2}}} code, out, _ := run(t, i, "--json") if code != ExitOK { t.Fatalf("code %d", code) } var got map[string]any if err := json.Unmarshal([]byte(out), &got); err != nil { t.Fatalf("%v: %s", err, out) } // The keys yavebu and others already read from yasta's output. for _, k := range []string{"program", "version", "commit", "build_date", "go", "platform", "contracts"} { if _, ok := got[k]; !ok { t.Errorf("missing key %q in %s", k, out) } } if got["version"] != "0.11.1" { t.Errorf("version %v, want the leading v dropped", got["version"]) } if code, out, _ = run(t, Info{Program: "x"}, "--json"); code != ExitOK || strings.Contains(out, "contracts") { t.Errorf("contracts must be omitted when empty: %s", out) } } func TestDefaultsAndBuildInfoFallback(t *testing.T) { old := readBuildInfo readBuildInfo = func() (*debug.BuildInfo, bool) { return &debug.BuildInfo{Settings: []debug.BuildSetting{ {Key: "vcs.revision", Value: "0123456789abcdef"}, {Key: "vcs.time", Value: "2026-10-01T00:00:00Z"}, {Key: "vcs.modified", Value: "true"}, }}, true } t.Cleanup(func() { readBuildInfo = old }) i := Info{Program: "x", Commit: "unknown"}.Complete() if i.Version != "dev" || i.Commit != "0123456-dirty" || i.BuildDate != "2026-10-01T00:00:00Z" { t.Errorf("got %+v", i) } if v := (Info{Version: "version-x"}).Complete().Version; v != "version-x" { t.Errorf("a non-tag v must stay: %q", v) } } func TestUsage(t *testing.T) { noBuildInfo(t) if code, _, errOut := run(t, Info{Program: "x"}, "--yaml"); code != ExitUsage || errOut == "" { t.Errorf("unknown flag: code %d, err %q", code, errOut) } if code, out, _ := run(t, Info{Program: "x"}, "--help"); code != ExitOK || !strings.Contains(out, "usage") { t.Errorf("--help: code %d, out %q", code, out) } } func TestShort(t *testing.T) { noBuildInfo(t) if s := (Info{Version: "0.1.0", Commit: "c", BuildDate: "d"}).Short(); s != "0.1.0 (c, built d)" { t.Errorf("Short %q", s) } }