Skip to content

Commit e4b854a

Browse files
committed
refactor: varying deterministic mock values from seed
1 parent 390e3f1 commit e4b854a

File tree

1 file changed

+14
-19
lines changed

1 file changed

+14
-19
lines changed

backend/pkg/api/data_access/dummy.go

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import (
99
"regexp"
1010
"slices"
1111
"strings"
12-
"sync"
1312
"time"
1413

1514
mathrand "math/rand"
@@ -84,7 +83,7 @@ func addTagFromRegex(name string, regex *regexp.Regexp, format func(string) inte
8483
if err != nil {
8584
return nil, err
8685
}
87-
gen.SetSeed(currentGeneratorSeed)
86+
gen.SetSeed(source.Int63())
8887
s := gen.Generate(10)
8988
return format(s), nil
9089
})
@@ -97,8 +96,7 @@ func randomEthDecimal() decimal.Decimal {
9796
}
9897

9998
func randomIntFromSeed(max int64) int64 {
100-
r := rand.New(rand.NewPCG(uint64(currentGeneratorSeed), uint64(currentGeneratorSeed))) //nolint:gosec
101-
return r.Int64N(max) + 1
99+
return source.Int63() % max
102100
}
103101

104102
// generate random timestamp between two dates
@@ -110,20 +108,16 @@ func randomTimestamp(t1, t2 time.Time) int64 {
110108
return randomIntFromSeed(max-min) + min
111109
}
112110

113-
var currentGeneratorSeed int64
114-
var mockLock sync.Mutex = sync.Mutex{}
111+
var source mathrand.Source
115112

116113
// must pass a pointer to the data
117114
func populateWithFakeData(ctx context.Context, a interface{}) error {
118-
if seed, ok := ctx.Value(t.CtxMockSeedKey).(int64); ok {
119-
mockLock.Lock()
120-
defer mockLock.Unlock()
121-
faker.SetRandomSource(mathrand.NewSource(seed))
122-
currentGeneratorSeed = seed
123-
} else {
124-
currentGeneratorSeed = rand.Int64() //nolint:gosec
115+
seed, ok := ctx.Value(t.CtxMockSeedKey).(int64)
116+
if !ok {
117+
seed = time.Now().UnixNano()
125118
}
126-
119+
source = faker.NewSafeSource(mathrand.NewSource(seed))
120+
faker.SetRandomSource(source)
127121
return faker.FakeData(a, options.WithRandomMapAndSliceMaxSize(10), options.WithRandomFloatBoundaries(interfaces.RandomFloatBoundary{Start: 0, End: 1}))
128122
}
129123

@@ -147,11 +141,12 @@ func getDummyStruct[T any](ctx context.Context) (*T, error) {
147141

148142
// used for any table data that should be returned with paging
149143
func getDummyWithPaging[T any](ctx context.Context) ([]T, *t.Paging, error) {
150-
r := []T{}
151-
p := t.Paging{}
152-
_ = populateWithFakeData(ctx, &r)
153-
err := populateWithFakeData(ctx, &p)
154-
return r, &p, err
144+
r := struct {
145+
Data []T
146+
Paging t.Paging
147+
}{}
148+
err := populateWithFakeData(ctx, &r)
149+
return r.Data, &r.Paging, err
155150
}
156151

157152
func (*DummyService) Close() {

0 commit comments

Comments
 (0)