Add randomize support for enums, add enums for pq

This commit is contained in:
Patrick O'brien 2016-11-12 15:47:24 +10:00
commit d891bcb9f0
4 changed files with 102 additions and 0 deletions

View file

@ -158,6 +158,16 @@ 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 {
if strings.HasPrefix(fieldType, "enum") {
enum, err := randEnumValue(fieldType)
if err != nil {
return err
}
field.Set(reflect.ValueOf(enum))
return nil
}
kind := field.Kind()
typ := field.Type()
@ -604,3 +614,12 @@ func getVariableRandValue(s *Seed, kind reflect.Kind, typ reflect.Type) interfac
return nil
}
func randEnumValue(enum string) (string, error) {
vals := strmangle.ParseEnumVals(enum)
if vals == nil || len(vals) == 0 {
return "", fmt.Errorf("unable to parse enum string: %s", enum)
}
return vals[rand.Intn(len(vals)-1)], nil
}

View file

@ -144,3 +144,28 @@ func TestRandomizeField(t *testing.T) {
}
}
}
func TestRandEnumValue(t *testing.T) {
t.Parallel()
enum1 := "enum.workday('monday','tuesday')"
enum2 := "enum('monday','tuesday')"
r1, err := randEnumValue(enum1)
if err != nil {
t.Error(err)
}
if r1 != "monday" && r1 != "tuesday" {
t.Errorf("Expected monday or tueday, got: %q", r1)
}
r2, err := randEnumValue(enum2)
if err != nil {
t.Error(err)
}
if r2 != "monday" && r2 != "tuesday" {
t.Errorf("Expected monday or tueday, got: %q", r2)
}
}