a73x

internal/server/store/exposures_doc_test.go

Ref:   Size: 1.6 KiB   History

package store

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

// TestDocsMatchReservedPortRange keeps the documented reserved range in step
// with the constants that define it. MinAllocatedHostPort and MaxAllocatedHostPort
// are the host contract; docs/mcp.md restates the span for a reader who never
// sees the source. This reads the real doc and fails if either the constants or
// the doc moves without the other. It matches on the bare numbers so it is
// indifferent to whether the doc joins them with a hyphen or an en-dash.
func TestDocsMatchReservedPortRange(t *testing.T) {
	doc := string(readRepoFile(t, "docs/mcp.md"))
	for _, want := range []string{
		strconv.Itoa(MinAllocatedHostPort),
		strconv.Itoa(MaxAllocatedHostPort),
	} {
		if !strings.Contains(doc, want) {
			t.Errorf("docs/mcp.md no longer states the reserved-range bound %s — "+
				"update the doc and this test's constants together when the range 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
}