Skip to content

Commit

Permalink
testutils: log random seed to test output
Browse files Browse the repository at this point in the history
Include the used seed in the test log so that test2json contains
the full information needed to recreate a test failure. This is
useful on CI which parses the output and provides a nice UI
to see failures.

Also allow overriding the used seed via an environment variable.

Signed-off-by: Lorenz Bauer <[email protected]>
  • Loading branch information
lmb committed Aug 10, 2023
1 parent ddcc405 commit dfd74c6
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
3 changes: 2 additions & 1 deletion btf/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -649,10 +649,11 @@ func TestCORECopyWithoutQualifiers(t *testing.T) {
}

t.Run("long chain", func(t *testing.T) {
rng := testutils.Rand(t)
root := &Int{Name: "abc"}
v := Type(root)
for i := 0; i < maxTypeDepth; i++ {
q := qualifiers[testutils.Rand().Intn(len(qualifiers))]
q := qualifiers[rng.Intn(len(qualifiers))]
v = q.fn(v)
t.Log(q.name)
}
Expand Down
2 changes: 1 addition & 1 deletion btf/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func TestRoundtripVMlinux(t *testing.T) {

// Randomize the order to force different permutations of walking the type
// graph. Keep Void at index 0.
testutils.Rand().Shuffle(len(types[1:]), func(i, j int) {
testutils.Rand(t).Shuffle(len(types[1:]), func(i, j int) {
types[i+1], types[j+1] = types[j+1], types[i+1]
})

Expand Down
20 changes: 16 additions & 4 deletions internal/testutils/seed.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package testutils

import (
"fmt"
"math/rand"
"os"
"strconv"
"sync"
"testing"
"time"
)

Expand All @@ -12,10 +14,20 @@ var randSeed struct {
once sync.Once
}

func Rand() *rand.Rand {
func Rand(tb testing.TB) *rand.Rand {
randSeed.once.Do(func() {
randSeed.value = time.Now().UnixMicro()
fmt.Printf("Random seed is %d\n", randSeed.value)
})
return rand.New(rand.NewSource(randSeed.value))

seed := randSeed.value
if seedStr, ok := os.LookupEnv("TEST_SEED"); ok {
var err error
seed, err = strconv.ParseInt(seedStr, 0, 64)
if err != nil {
tb.Fatal("Parse TEST_SEED environment variable:", err)
}
}

tb.Logf("TEST_SEED=%d\n", seed)
return rand.New(rand.NewSource(seed))
}

0 comments on commit dfd74c6

Please sign in to comment.