Skip to content

Commit

Permalink
Abstract randReader to fix a test data-race
Browse files Browse the repository at this point in the history
  • Loading branch information
olegbespalov committed Nov 20, 2023
1 parent 1467dd2 commit 7e0a8ec
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
7 changes: 4 additions & 3 deletions js/modules/k6/crypto/crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ type (

// Crypto represents an instance of the crypto module.
Crypto struct {
vu modules.VU
randReader func(b []byte) (n int, err error)
vu modules.VU
}
)

Expand All @@ -47,7 +48,7 @@ func New() *RootModule {
// NewModuleInstance implements the modules.Module interface to return
// a new instance for each VU.
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
return &Crypto{vu: vu}
return &Crypto{vu: vu, randReader: rand.Read}
}

// Exports returns the exports of the execution module.
Expand Down Expand Up @@ -78,7 +79,7 @@ func (c *Crypto) randomBytes(size int) (*goja.ArrayBuffer, error) {
return nil, errors.New("invalid size")
}
bytes := make([]byte, size)
_, err := rand.Read(bytes)
_, err := c.randReader(bytes)
if err != nil {
return nil, err
}
Expand Down
21 changes: 15 additions & 6 deletions js/modules/k6/crypto/crypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package crypto

import (
"context"
"crypto/rand"
"errors"
"fmt"
"testing"
Expand Down Expand Up @@ -74,13 +73,23 @@ func TestCryptoAlgorithms(t *testing.T) {
t.Run("RandomBytesFailure", func(t *testing.T) {
t.Parallel()

rt := makeRuntime(t)

SavedReader := rand.Reader
rand.Reader = MockReader{}
rt := goja.New()
rt.SetFieldNameMapper(common.FieldNameMapper{})

m, ok := New().NewModuleInstance(
&modulestest.VU{
RuntimeField: rt,
InitEnvField: &common.InitEnvironment{},
CtxField: context.Background(),
StateField: nil,
},
).(*Crypto)
require.True(t, ok)
require.NoError(t, rt.Set("crypto", m.Exports().Named))

m.randReader = MockReader{}.Read
_, err := rt.RunString(`
crypto.randomBytes(5);`)
rand.Reader = SavedReader

assert.Error(t, err)
})
Expand Down

0 comments on commit 7e0a8ec

Please sign in to comment.