package meshtest import ( "go/ast" "go/parser" "go/token" "io/fs" "os" "path/filepath" "strconv" "strings" "testing" "time" ) // 1754/AC1: a wait's bound is the test's deadline less the cleanup margin, and what is left once less than the margin is, // never zero or less (the lead's answer on issue 1754, round 2). func TestABoundIsTheTestsDeadlineLessItsCleanupMargin(t *testing.T) { for _, row := range []struct{ left, want time.Duration }{ {10 * time.Minute, 10*time.Minute - cleanupMargin}, {cleanupMargin + time.Second, time.Second}, {cleanupMargin, cleanupMargin}, {time.Second, time.Second}, {0, time.Millisecond}, {-time.Minute, time.Millisecond}, } { if got := boundOf(row.left); got != row.want { t.Errorf("with %s left the bound is %s, want %s", row.left, got, row.want) } } deadline, ok := t.Deadline() if !ok { deadline = started.Add(goTestTimeout) } left := time.Until(deadline) if b := Bound(t); b <= 0 || b > left-cleanupMargin { t.Errorf("this test's bound is %s, with %s left until its deadline", b, left) } } // waitBound is, for each call that waits, which argument is its bound. var waitBound = map[string]int{ "After": 0, "NewTimer": 0, "WithTimeout": 1, "NextMsg": 0, "ReadyForConnections": 0, "Request": 2, "RequestMsg": 1, "AskWithin": 3, "HearFirst": 2, "MaxWait": 0, } // 1754/AC1: no test that starts a bus (a test file importing this package, and this package itself) waits for what the // bus carries with a fixed bound of a second or more: each such wait takes the test's own deadline, Bound(t). A few // seconds is what a loaded build node overran (issue 1754: state_counter_test.go's 5 s for a 1 s key's expire, failed on // a build node); a bound under a second is the bound under test or the window an absence is given, and is not this guard's. func TestNoWaitOnTheBusHasAFixedBound(t *testing.T) { root := moduleRoot() var found []string err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { if err != nil { return err } if d.IsDir() { if path != root && (d.Name() == "node_modules" || strings.HasPrefix(d.Name(), ".")) { return filepath.SkipDir } return nil } dir := filepath.Dir(path) ours := filepath.Base(dir) == "meshtest" && filepath.Base(filepath.Dir(dir)) == "internal" if !strings.HasSuffix(path, ".go") || !ours && !strings.HasSuffix(path, "_test.go") { return nil } found = append(found, fixedWaits(t, path, ours)...) return nil }) if err != nil { t.Fatal(err) } if len(found) > 0 { t.Errorf("waits on the bus with a fixed bound, which a loaded build node overruns: give each the test's own, meshtest.Bound(t)\n%s", strings.Join(found, "\n")) } } // fixedWaits are the waits of one file that starts a bus whose bound is a constant of a second or more. func fixedWaits(t *testing.T, path string, ours bool) []string { t.Helper() fset := token.NewFileSet() f, err := parser.ParseFile(fset, path, nil, 0) if err != nil { t.Fatal(err) } if !ours && !importsMeshtest(f) { return nil } consts := packageConsts(t, filepath.Dir(path)) var found []string flag := func(what string, bound ast.Expr) { if d, ok := duration(bound, consts); ok && d >= time.Second { rel, _ := filepath.Rel(moduleRoot(), fset.Position(bound.Pos()).Filename) found = append(found, rel+":"+strconv.Itoa(fset.Position(bound.Pos()).Line)+": "+what+" "+d.String()) } } ast.Inspect(f, func(n ast.Node) bool { switch n := n.(type) { case *ast.CallExpr: name := "" switch fn := n.Fun.(type) { case *ast.SelectorExpr: name = fn.Sel.Name case *ast.Ident: name = fn.Name } if i, ok := waitBound[name]; ok && i < len(n.Args) { flag(name, n.Args[i]) } case *ast.AssignStmt: // a deadline kept in a name, for a loop that polls until it passes for _, v := range n.Rhs { if bound, ok := nowAdd(v); ok { flag("a deadline", bound) } } case *ast.ValueSpec: for _, v := range n.Values { if bound, ok := nowAdd(v); ok { flag("a deadline", bound) } } } return true }) return found } func importsMeshtest(f *ast.File) bool { for _, i := range f.Imports { if strings.HasSuffix(strings.Trim(i.Path.Value, `"`), "/internal/meshtest") { return true } } return false } // nowAdd is d of time.Now().Add(d). func nowAdd(e ast.Expr) (ast.Expr, bool) { call, ok := e.(*ast.CallExpr) if !ok || len(call.Args) != 1 { return nil, false } sel, ok := call.Fun.(*ast.SelectorExpr) if !ok || sel.Sel.Name != "Add" { return nil, false } now, ok := sel.X.(*ast.CallExpr) if !ok { return nil, false } if s, ok := now.Fun.(*ast.SelectorExpr); ok && s.Sel.Name == "Now" && isIdent(s.X, "time") { return call.Args[0], true } return nil, false } func isIdent(e ast.Expr, name string) bool { id, ok := e.(*ast.Ident) return ok && id.Name == name } // packageConsts are the constants a package's files declare at their top, by name, unevaluated. func packageConsts(t *testing.T, dir string) map[string]ast.Expr { t.Helper() entries, err := os.ReadDir(dir) if err != nil { t.Fatal(err) } consts := map[string]ast.Expr{} for _, e := range entries { if !strings.HasSuffix(e.Name(), ".go") { continue } f, err := parser.ParseFile(token.NewFileSet(), filepath.Join(dir, e.Name()), nil, 0) if err != nil { t.Fatal(err) } for _, d := range f.Decls { g, ok := d.(*ast.GenDecl) if !ok || g.Tok != token.CONST { continue } for _, s := range g.Specs { v := s.(*ast.ValueSpec) for i, n := range v.Names { if i < len(v.Values) { consts[n.Name] = v.Values[i] } } } } } return consts } // duration is the value of a constant duration written as the tests write one: a number, time's units, a constant of // the package, and their products and sums. Anything else (a variable, Bound(t), another package's bound) is not constant. func duration(e ast.Expr, consts map[string]ast.Expr) (time.Duration, bool) { switch e := e.(type) { case *ast.ParenExpr: return duration(e.X, consts) case *ast.BasicLit: if e.Kind == token.INT { n, err := strconv.ParseInt(e.Value, 0, 64) return time.Duration(n), err == nil } if e.Kind == token.FLOAT { f, err := strconv.ParseFloat(e.Value, 64) return time.Duration(f), err == nil } case *ast.SelectorExpr: if isIdent(e.X, "time") { unit, ok := map[string]time.Duration{"Nanosecond": time.Nanosecond, "Microsecond": time.Microsecond, "Millisecond": time.Millisecond, "Second": time.Second, "Minute": time.Minute, "Hour": time.Hour}[e.Sel.Name] return unit, ok } case *ast.Ident: if v, ok := consts[e.Name]; ok { delete(consts, e.Name) // a constant read once, so none refers to itself d, ok := duration(v, consts) consts[e.Name] = v return d, ok } case *ast.UnaryExpr: if d, ok := duration(e.X, consts); ok && e.Op == token.SUB { return -d, true } case *ast.BinaryExpr: a, okA := duration(e.X, consts) b, okB := duration(e.Y, consts) if !okA || !okB { return 0, false } switch e.Op { case token.MUL: return a * b, true case token.ADD: return a + b, true case token.SUB: return a - b, true case token.QUO: if b != 0 { return a / b, true } } } return 0, false }