diff --git a/mtest/mtest.go b/mtest/mtest.go new file mode 100644 index 0000000..326b66f --- /dev/null +++ b/mtest/mtest.go @@ -0,0 +1,29 @@ +// Package mtest contains types and functions which are useful when writing +// tests +package mtest + +import ( + crand "crypto/rand" + "encoding/hex" + "math/rand" + "time" +) + +// Rand is a public instance of rand.Rand, seeded with the current +// nano-timestamp +var Rand = rand.New(rand.NewSource(time.Now().UnixNano())) + +// RandBytes returns n random bytes +func RandBytes(n int) []byte { + b := make([]byte, n) + if _, err := crand.Read(b); err != nil { + panic(err) + } + return b +} + +// RandHex returns a random hex string which is n characters long +func RandHex(n int) string { + b := RandBytes(hex.DecodedLen(n)) + return hex.EncodeToString(b) +} diff --git a/mtest/mtest_test.go b/mtest/mtest_test.go new file mode 100644 index 0000000..3f283fd --- /dev/null +++ b/mtest/mtest_test.go @@ -0,0 +1,23 @@ +package mtest + +import ( + . "testing" + + "github.com/stretchr/testify/assert" +) + +func TestRandBytes(t *T) { + var prev []byte + for i := 0; i < 10000; i++ { + curr := RandBytes(16) + assert.Len(t, curr, 16) + assert.NotEqual(t, prev, curr) + prev = curr + } +} + +func TestRandHex(t *T) { + // RandHex is basically a wrapper of RandBytes, so we don't have to test it + // much + assert.Len(t, RandHex(16), 16) +}