Skip to content

Commit

Permalink
add flag testify.shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
stamm committed Jul 9, 2023
1 parent 78aedbf commit 5a26333
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
19 changes: 19 additions & 0 deletions suite/suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ package suite
import (
"flag"
"fmt"
"math/rand"
"os"
"reflect"
"regexp"
"runtime/debug"
"strconv"
"sync"
"testing"
"time"
Expand All @@ -17,6 +19,7 @@ import (

var allTestsFilter = func(_, _ string) (bool, error) { return true, nil }
var matchMethod = flag.String("testify.m", "", "regular expression to select tests of the testify suite to run")
var shuffle = flag.String("testify.shuffle", "off", "randomize the execution order of tests")

// Suite is a basic testing suite with methods for storing and
// retrieving the current *testing.T context.
Expand Down Expand Up @@ -199,6 +202,22 @@ func Run(t *testing.T, suite TestingSuite) {
}
tests = append(tests, test)
}
if *shuffle != "off" {
var n int64
var err error
if *shuffle == "on" {
n = time.Now().UnixNano()
} else {
n, err = strconv.ParseInt(*shuffle, 10, 64)
if err != nil {
fmt.Fprintln(os.Stderr, `testing: -shuffle should be "off", "on", or a valid integer:`, err)
return
}
}
fmt.Println("-testify.shuffle", n)
rng := rand.New(rand.NewSource(n))
rng.Shuffle(len(tests), func(i, j int) { tests[i], tests[j] = tests[j], tests[i] })
}
if suiteSetupDone {
defer func() {
if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok {
Expand Down
44 changes: 44 additions & 0 deletions suite/suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,3 +617,47 @@ func (s *FailfastSuite) Test_B_Passes() {
s.call("Test B Passes")
s.Require().True(true)
}

type ShuffleOrderSuite struct {
Suite
callOrder []string
}

func (s *ShuffleOrderSuite) call(method string) {
s.callOrder = append(s.callOrder, method)
}

func TestSuiteShuffleOrder(t *testing.T) {
Run(t, new(ShuffleOrderSuite))
}

func TestShuffleOrderSuiteShuffleOn(t *testing.T) {
// To test this with testify.shuffle on we launch it in its own process
cmd := exec.Command("go", "test", "-v", "-race", "-run", "TestSuiteShuffleOrder", "-testify.shuffle", "2")
var out bytes.Buffer
cmd.Stdout = &out
t.Logf("Running %s", strings.Join(cmd.Args, " "))
err := cmd.Run()
t.Log(out.String())
if err != nil {
t.Log(err)
t.Fail()
}
}

func (s *ShuffleOrderSuite) TearDownSuite() {
shuffle := flag.Lookup("testify.shuffle").Value.(flag.Getter).Get().(string)
if shuffle == "off" {
assert.Equal(s.T(), "Test A;Test B", strings.Join(s.callOrder, ";"))
} else {
assert.Equal(s.T(), "Test B;Test A", strings.Join(s.callOrder, ";"))
}
}

func (s *ShuffleOrderSuite) Test_A() {
s.call("Test A")
}

func (s *ShuffleOrderSuite) Test_B() {
s.call("Test B")
}

0 comments on commit 5a26333

Please sign in to comment.