From ab237fae3dd63322966bd584c3e12f62685a4f70 Mon Sep 17 00:00:00 2001 From: Oleg Bespalov Date: Mon, 20 Nov 2023 16:24:13 +0100 Subject: [PATCH] Abstract randReader to fix a test data-race --- js/modules/k6/crypto/crypto.go | 7 ++++--- js/modules/k6/crypto/crypto_test.go | 21 +++++++++++++++------ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/js/modules/k6/crypto/crypto.go b/js/modules/k6/crypto/crypto.go index e6202dd4c75..8eee7ad7121 100644 --- a/js/modules/k6/crypto/crypto.go +++ b/js/modules/k6/crypto/crypto.go @@ -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 } ) @@ -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. @@ -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 } diff --git a/js/modules/k6/crypto/crypto_test.go b/js/modules/k6/crypto/crypto_test.go index 00a9d040497..7e4138c63fc 100644 --- a/js/modules/k6/crypto/crypto_test.go +++ b/js/modules/k6/crypto/crypto_test.go @@ -2,7 +2,6 @@ package crypto import ( "context" - "crypto/rand" "errors" "fmt" "testing" @@ -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) })