-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathordering.go
99 lines (81 loc) · 2.16 KB
/
ordering.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package testcase
import (
"fmt"
"math/rand"
"os"
"sync"
"go.llib.dev/testcase/internal"
"go.llib.dev/testcase/internal/environ"
)
func newOrderer(seed int64) orderer {
switch mod := getGlobalOrderMod(); mod {
case OrderingAsDefined:
return nullOrderer{}
case OrderingAsRandom, undefinedOrdering:
return randomOrderer{Seed: seed}
default:
panic(fmt.Sprintf(`unknown ordering mod: %s`, mod))
}
}
type orderer interface {
Order(tc []func())
}
type testOrderingMod string
const (
undefinedOrdering testOrderingMod = ``
OrderingAsDefined testOrderingMod = `defined`
OrderingAsRandom testOrderingMod = `random`
)
//------------------------------------------------- order as defined -------------------------------------------------//
type nullOrderer struct{}
func (o nullOrderer) Order([]func()) {}
//-------------------------------------------------- order randomly --------------------------------------------------//
type randomOrderer struct {
Seed int64
}
func (o randomOrderer) Order(tests []func()) {
o.rand().Shuffle(len(tests), o.swapFunc(tests))
}
func (o randomOrderer) rand() *rand.Rand {
return rand.New(rand.NewSource(o.Seed))
}
func (o randomOrderer) swapFunc(tests []func()) func(i int, j int) {
return func(i, j int) {
tests[i], tests[j] = tests[j], tests[i]
}
}
//---------------------------------------------- Global Test ordering Mod ----------------------------------------------//
var (
globalOrderMod testOrderingMod
globalOrderModInit sync.Once
_ = internal.RegisterCacheFlush(func() {
globalOrderModInit = sync.Once{}
})
)
func getGlobalOrderMod() testOrderingMod {
globalOrderModInit.Do(func() { globalOrderMod = getOrderingModFromENV() })
return globalOrderMod
}
func getOrderingModFromENV() testOrderingMod {
var (
mod string
ok bool
)
for _, envKey := range environ.OrderingKeys() {
mod, ok = os.LookupEnv(envKey)
if ok {
break
}
}
if !ok {
return OrderingAsRandom
}
switch testOrderingMod(mod) {
case OrderingAsDefined:
return OrderingAsDefined
case OrderingAsRandom:
return OrderingAsRandom
default:
panic(fmt.Sprintf(`unknown testCase ordering/arrange mod: %s`, mod))
}
}