implement mtest package
This commit is contained in:
parent
0b9c02c62a
commit
3f2f00d367
29
mtest/mtest.go
Normal file
29
mtest/mtest.go
Normal file
@ -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)
|
||||||
|
}
|
23
mtest/mtest_test.go
Normal file
23
mtest/mtest_test.go
Normal file
@ -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)
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user