Skip to content
Permalink
Browse files
randbp: Fix typed nil error
Also add an unit test to make sure of it.
  • Loading branch information
fishy committed Aug 31, 2020
1 parent dfb983d commit 0f916e7afc0212b8015a11cff20963017ab92a80
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 3 deletions.
@@ -21,6 +21,7 @@ go_test(
"rand_test.go",
"sample_test.go",
"string_example_test.go",
"string_test.go",
],
embed = [":go_default_library"],
)
@@ -38,8 +38,10 @@ type intner interface {
//
// It could be used to help implement testing/quick.Generator interface.
func GenerateRandomString(args RandomStringArgs) string {
var r intner = args.R
if r == nil {
var r intner
if args.R != nil {
r = args.R
} else {
r = R
}
runes := args.Runes
@@ -58,5 +58,5 @@ func RandomStringTest(t *testing.T) {
// testing/quick package.
func ExampleGenerateRandomString() {
// Nothing really here.
// The real example is on the other functions/types above,
// The real example is on the other functions/types above.
}
@@ -0,0 +1,61 @@
package randbp_test

import (
"math/rand"
"reflect"
"testing"
"testing/quick"

"github.com/reddit/baseplate.go/randbp"
)

func TestGenerateRandomStringNil(t *testing.T) {
// Just make sure it doesn't panic when all optional args are absent.
// No real tests here.
randbp.GenerateRandomString(randbp.RandomStringArgs{
MaxLength: 10,
})
}

const (
minLength = 1
maxLength = 20
)

type randomString string

func (randomString) Generate(r *rand.Rand, _ int) reflect.Value {
return reflect.ValueOf(randomString(randbp.GenerateRandomString(
randbp.RandomStringArgs{
R: r,
MinLength: minLength,
MaxLength: maxLength,
},
)))
}

var _ quick.Generator = randomString("")

func TestRandomStringQuick(t *testing.T) {
f := func(input randomString) bool {
s := string(input)
if len(s) < minLength {
t.Errorf(
"Expected random string to have a minimal length of %d, got %q",
minLength,
s,
)
}
if len(s) >= maxLength {
t.Errorf(
"Expected random string to have a maximum length of %d, got %q",
maxLength,
s,
)
}
return !t.Failed()
}
if err := quick.Check(f, nil); err != nil {
t.Error(err)
}
}

0 comments on commit 0f916e7

Please sign in to comment.