Skip to content
go-libfossil Artifact [281fc08281]
Login

Artifact [281fc08281]

Artifact 281fc08281c98d0c68111bea5c1f2688152a73a436d58f53efa7ce25c4585db1:


package conformance

import (
	"go/ast"
	"go/parser"
	"go/token"
	"path/filepath"
	"strconv"
	"strings"
	"testing"
)

// TestSuiteCompleteness checks two invariants TestCoverage cannot see on its
// own: every Case literal declared in conformance/*_test.go (outside the
// harness's own self-tests) is registered in suites(), and every registered
// case is reachable from a real Test* function (either via its collector or
// directly via its package-level Case variable).
func TestSuiteCompleteness(t *testing.T) {
	registered := registeredCaseIDs()
	fset := token.NewFileSet()
	files, err := parseConformanceTestFiles(fset)
	if err != nil {
		t.Fatal(err)
	}
	checkDeclaredCasesRegistered(t, files, registered)
	checkRegisteredCasesExecuted(t, files)
}

func TestCompletenessDetectsUnregistered(t *testing.T) {
	fset := token.NewFileSet()
	src := `package conformance
var orphan = Case{ID: "artifact.orphan", Req: "AF-3.1-1"}
`
	f, err := parser.ParseFile(fset, "synthetic_test.go", src, 0)
	if err != nil {
		t.Fatal(err)
	}
	ids := caseLiteralIDs(f)
	if len(ids) != 1 || ids[0] != "artifact.orphan" {
		t.Fatalf("caseLiteralIDs = %v, want [artifact.orphan]", ids)
	}
}

func registeredCaseIDs() map[string]bool {
	ids := map[string]bool{}
	for _, s := range suites() {
		for _, c := range s.cases {
			ids[c.ID] = true
		}
	}
	if len(ids) == 0 {
		panic("conformance: suites() returned no cases")
	}
	return ids
}

func parseConformanceTestFiles(fset *token.FileSet) (map[string]*ast.File, error) {
	if fset == nil {
		panic("conformance: nil FileSet")
	}
	paths, err := filepath.Glob("*_test.go")
	if err != nil {
		return nil, err
	}
	out := make(map[string]*ast.File, len(paths))
	for _, p := range paths {
		f, err := parser.ParseFile(fset, p, nil, 0)
		if err != nil {
			return nil, err
		}
		out[p] = f
	}
	return out, nil
}

func checkDeclaredCasesRegistered(
	t *testing.T, files map[string]*ast.File, registered map[string]bool,
) {
	t.Helper()
	skip := map[string]bool{
		"harness_self_test.go":  true,
		"harness_check_test.go": true,
		"completeness_test.go":  true,
	}
	for name, f := range files {
		if skip[name] {
			continue
		}
		for _, id := range caseLiteralIDs(f) {
			if !registered[id] {
				t.Errorf("%s declares Case %q which is not registered in suites()", name, id)
			}
		}
	}
}

func caseLiteralIDs(f *ast.File) []string {
	if f == nil {
		panic("conformance: nil AST file")
	}
	var ids []string
	ast.Inspect(f, func(n ast.Node) bool {
		lit, ok := n.(*ast.CompositeLit)
		if !ok {
			return true
		}
		ident, ok := lit.Type.(*ast.Ident)
		if !ok || ident.Name != "Case" {
			return true
		}
		if id, ok := caseLitID(lit); ok {
			ids = append(ids, id)
		}
		return true
	})
	return ids
}

func caseLitID(lit *ast.CompositeLit) (string, bool) {
	for _, elt := range lit.Elts {
		kv, ok := elt.(*ast.KeyValueExpr)
		if !ok {
			continue
		}
		key, ok := kv.Key.(*ast.Ident)
		if !ok || key.Name != "ID" {
			continue
		}
		basic, ok := kv.Value.(*ast.BasicLit)
		if !ok || basic.Kind != token.STRING {
			return "", false
		}
		unquoted, err := strconv.Unquote(basic.Value)
		if err != nil {
			return "", false
		}
		return unquoted, true
	}
	return "", false
}

func checkRegisteredCasesExecuted(t *testing.T, files map[string]*ast.File) {
	t.Helper()
	funcs, callGraph := indexTestFuncs(files)
	reached := reachableFromRealTests(callGraph)
	caseVars := packageCaseVars(files)
	referencedVars := identsReferencedInFuncs(funcs, reached)
	for name := range caseVars {
		if !referencedVars[name] {
			t.Errorf("package Case var %s is never referenced by any real Test*", name)
		}
	}
	for _, fn := range suiteCollectors(callGraph) {
		if reached[fn] || returnsOnlyCaseVars(funcs[fn], caseVars) {
			continue
		}
		t.Errorf("collector %s() is registered in suites() but not called by any Test*", fn)
	}
}

func indexTestFuncs(
	files map[string]*ast.File,
) (map[string]*ast.FuncDecl, map[string][]string) {
	funcs := map[string]*ast.FuncDecl{}
	graph := map[string][]string{}
	for _, f := range files {
		for _, decl := range f.Decls {
			fd, ok := decl.(*ast.FuncDecl)
			if !ok || fd.Recv != nil || fd.Body == nil {
				continue
			}
			funcs[fd.Name.Name] = fd
			graph[fd.Name.Name] = directCalls(fd.Body)
		}
	}
	return funcs, graph
}

func packageCaseVars(files map[string]*ast.File) map[string]bool {
	out := map[string]bool{}
	for name, f := range files {
		if name == "harness_self_test.go" || name == "harness_check_test.go" ||
			name == "completeness_test.go" {
			continue
		}
		for _, decl := range f.Decls {
			gd, ok := decl.(*ast.GenDecl)
			if !ok || gd.Tok != token.VAR {
				continue
			}
			collectCaseVarSpecs(gd.Specs, out)
		}
	}
	return out
}

func collectCaseVarSpecs(specs []ast.Spec, out map[string]bool) {
	for _, s := range specs {
		vs, ok := s.(*ast.ValueSpec)
		if !ok {
			continue
		}
		for i, val := range vs.Values {
			lit, ok := val.(*ast.CompositeLit)
			if !ok {
				continue
			}
			if id, ok := lit.Type.(*ast.Ident); ok && id.Name == "Case" && i < len(vs.Names) {
				out[vs.Names[i].Name] = true
			}
		}
	}
}

func identsReferencedInFuncs(
	funcs map[string]*ast.FuncDecl, reached map[string]bool,
) map[string]bool {
	out := map[string]bool{}
	for name := range reached {
		fd := funcs[name]
		if fd == nil || fd.Body == nil {
			continue
		}
		ast.Inspect(fd.Body, func(n ast.Node) bool {
			if id, ok := n.(*ast.Ident); ok {
				out[id.Name] = true
			}
			return true
		})
	}
	return out
}

// returnsOnlyCaseVars reports whether fd is a pure slice literal of known
// package-level Case variables (e.g. horizonContentCases), each of which is
// already verified directly against reachable Test* functions.
func returnsOnlyCaseVars(fd *ast.FuncDecl, caseVars map[string]bool) bool {
	if fd == nil || fd.Body == nil || len(fd.Body.List) != 1 {
		return false
	}
	ret, ok := fd.Body.List[0].(*ast.ReturnStmt)
	if !ok || len(ret.Results) != 1 {
		return false
	}
	lit, ok := ret.Results[0].(*ast.CompositeLit)
	if !ok || len(lit.Elts) == 0 {
		return false
	}
	for _, elt := range lit.Elts {
		id, ok := elt.(*ast.Ident)
		if !ok || !caseVars[id.Name] {
			return false
		}
	}
	return true
}

func directCalls(body *ast.BlockStmt) []string {
	var calls []string
	ast.Inspect(body, func(n ast.Node) bool {
		ce, ok := n.(*ast.CallExpr)
		if !ok {
			return true
		}
		if id, ok := ce.Fun.(*ast.Ident); ok {
			calls = append(calls, id.Name)
		}
		return true
	})
	return calls
}

func suiteCollectors(graph map[string][]string) []string {
	seen := map[string]bool{}
	var out []string
	for _, root := range graph["suites"] {
		if !strings.HasSuffix(root, "Cases") {
			continue
		}
		for _, callee := range graph[root] {
			if strings.HasSuffix(callee, "Cases") && !seen[callee] {
				seen[callee] = true
				out = append(out, callee)
			}
		}
	}
	return out
}

func reachableFromRealTests(graph map[string][]string) map[string]bool {
	visited := map[string]bool{}
	var queue []string
	for name := range graph {
		if !isRealConformanceTest(name) {
			continue
		}
		visited[name] = true
		queue = append(queue, name)
	}
	const maxSteps = 10000
	for steps := 0; len(queue) > 0 && steps < maxSteps; steps++ {
		cur := queue[0]
		queue = queue[1:]
		for _, next := range graph[cur] {
			if visited[next] {
				continue
			}
			if _, ok := graph[next]; ok {
				visited[next] = true
				queue = append(queue, next)
			}
		}
	}
	return visited
}

func isRealConformanceTest(name string) bool {
	if !strings.HasPrefix(name, "Test") {
		return false
	}
	if name == "TestCoverage" || name == "TestSuiteCompleteness" {
		return false
	}
	return !strings.HasSuffix(name, "GapKeys")
}