a73x

internal/cli/hosted_defaults_doc_test.go

Ref:   Size: 1.5 KiB   History

package cli

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

// TestDocsMatchHostedDefaults keeps the prose from drifting from the code. The
// client's hosted fallback lives once, in defaultURL and defaultGate; the
// docs restate those addresses for a reader who never sees the source. This
// test reads the real doc and fails if either the constant or the doc moves
// without the other, so the two can never quietly disagree.
func TestDocsMatchHostedDefaults(t *testing.T) {
	doc := string(readRepoFile(t, "docs/connecting.md"))
	for _, want := range []string{defaultURL, defaultGate} {
		if !strings.Contains(doc, "`"+want+"`") {
			t.Errorf("docs/connecting.md no longer states the hosted default `%s` — "+
				"update the doc and this test together when the constant changes", want)
		}
	}
}

// readRepoFile reads a path relative to the repo root, found by walking up from
// this source file to the go.mod. Tests run from the package directory, so the
// repo root is not the working directory.
func readRepoFile(t *testing.T, rel string) []byte {
	t.Helper()
	_, self, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("runtime.Caller failed")
	}
	dir := filepath.Dir(self)
	for {
		if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
			break
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			t.Fatal("could not find repo root (go.mod) above " + self)
		}
		dir = parent
	}
	b, err := os.ReadFile(filepath.Join(dir, rel))
	if err != nil {
		t.Fatal(err)
	}
	return b
}