github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/utils/unittest/strings.go (about) 1 package unittest 2 3 import ( 4 "crypto/rand" 5 "encoding/base64" 6 "testing" 7 8 "github.com/stretchr/testify/require" 9 ) 10 11 // RandomStringFixture is a test helper that generates a cryptographically secure random string of size n. 12 func RandomStringFixture(t *testing.T, n int) string { 13 require.Greater(t, n, 0, "size should be positive") 14 15 // The base64 encoding uses 64 different characters to represent data in 16 // strings, which makes it possible to represent 6 bits of data with each 17 // character (as 2^6 is 64). This means that every 3 bytes (24 bits) of 18 // input data will be represented by 4 characters (4 * 6 bits) in the 19 // base64 encoding. Consequently, base64 encoding increases the size of 20 // the data by approximately 1/3 compared to the original input data. 21 // 22 // 1. (n+3) / 4 - This calculates how many groups of 4 characters are needed 23 // in the base64 encoded output to represent at least 'n' characters. 24 // The +3 ensures rounding up, as integer division truncates the result. 25 // 26 // 2. ... * 3 - Each group of 4 base64 characters represents 3 bytes 27 // of input data. This multiplication calculates the number of bytes 28 // needed to produce the required length of the base64 string. 29 byteSlice := make([]byte, (n+3)/4*3) 30 n, err := rand.Read(byteSlice) 31 require.NoError(t, err) 32 require.Equal(t, n, len(byteSlice)) 33 34 encodedString := base64.URLEncoding.EncodeToString(byteSlice) 35 return encodedString[:n] 36 }