Fix randomization of enum values

- Fix #179
This commit is contained in:
Aaron L 2017-08-07 15:29:21 -07:00
parent 50b854ef83
commit 040f9e41be
2 changed files with 9 additions and 10 deletions

View file

@ -159,18 +159,17 @@ func randDate(s *Seed) time.Time {
// If canBeNull is true:
// The value has the possibility of being null or non-zero at random.
func randomizeField(s *Seed, field reflect.Value, fieldType string, canBeNull bool) error {
kind := field.Kind()
typ := field.Type()
if strings.HasPrefix(fieldType, "enum") {
enum, err := randEnumValue(fieldType)
enum, err := randEnumValue(s, fieldType)
if err != nil {
return err
}
if kind == reflect.Struct {
val := null.NewString(enum, rand.Intn(1) == 0)
val := null.NewString(enum, s.nextInt()%2 == 0)
field.Set(reflect.ValueOf(val))
} else {
field.Set(reflect.ValueOf(enum))
@ -623,13 +622,11 @@ func getVariableRandValue(s *Seed, kind reflect.Kind, typ reflect.Type) interfac
return nil
}
func randEnumValue(enum string) (string, error) {
func randEnumValue(s *Seed, enum string) (string, error) {
vals := strmangle.ParseEnumVals(enum)
if vals == nil || len(vals) == 0 {
return "", fmt.Errorf("unable to parse enum string: %s", enum)
} else if len(vals) == 1 {
return vals[0], nil
}
return vals[rand.Intn(len(vals)-1)], nil
return vals[s.nextInt()%len(vals)], nil
}

View file

@ -148,11 +148,13 @@ func TestRandomizeField(t *testing.T) {
func TestRandEnumValue(t *testing.T) {
t.Parallel()
s := NewSeed()
enum1 := "enum.workday('monday','tuesday')"
enum2 := "enum('monday','tuesday')"
enum3 := "enum('monday')"
r1, err := randEnumValue(enum1)
r1, err := randEnumValue(s, enum1)
if err != nil {
t.Error(err)
}
@ -161,7 +163,7 @@ func TestRandEnumValue(t *testing.T) {
t.Errorf("Expected monday or tuesday, got: %q", r1)
}
r2, err := randEnumValue(enum2)
r2, err := randEnumValue(s, enum2)
if err != nil {
t.Error(err)
}
@ -170,7 +172,7 @@ func TestRandEnumValue(t *testing.T) {
t.Errorf("Expected monday or tuesday, got: %q", r2)
}
r3, err := randEnumValue(enum3)
r3, err := randEnumValue(s, enum3)
if err != nil {
t.Error(err)
}