From 64206cfe07b4b5014b36770f7eac6b7dfeb6cb8f Mon Sep 17 00:00:00 2001
From: Genadi Samokovarov <gsamokovarov@gmail.com>
Date: Wed, 14 Jun 2017 16:53:55 +0300
Subject: [PATCH] Fix randomization for enums with single value

Hey there,

I hit a bug that panicked the tests with:

    panic: invalid argument to Intn

The problem happened, because I have a Postgres `ENUM` with a single
value, that caused a `rand.Intn(0)` call, which panics on zero.

See: https://golang.org/src/math/rand/rand.go?s=4112:4142#L129
---
 randomize/randomize.go      |  2 ++
 randomize/randomize_test.go | 14 ++++++++++++--
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/randomize/randomize.go b/randomize/randomize.go
index 59f7eff..e3b63c4 100644
--- a/randomize/randomize.go
+++ b/randomize/randomize.go
@@ -627,6 +627,8 @@ 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)
+	} else if len(vals) == 1 {
+		return vals[0], nil
 	}
 
 	return vals[rand.Intn(len(vals)-1)], nil
diff --git a/randomize/randomize_test.go b/randomize/randomize_test.go
index 6f117b7..1ca35ba 100644
--- a/randomize/randomize_test.go
+++ b/randomize/randomize_test.go
@@ -150,6 +150,7 @@ func TestRandEnumValue(t *testing.T) {
 
 	enum1 := "enum.workday('monday','tuesday')"
 	enum2 := "enum('monday','tuesday')"
+	enum3 := "enum('monday')"
 
 	r1, err := randEnumValue(enum1)
 	if err != nil {
@@ -157,7 +158,7 @@ func TestRandEnumValue(t *testing.T) {
 	}
 
 	if r1 != "monday" && r1 != "tuesday" {
-		t.Errorf("Expected monday or tueday, got: %q", r1)
+		t.Errorf("Expected monday or tuesday, got: %q", r1)
 	}
 
 	r2, err := randEnumValue(enum2)
@@ -166,6 +167,15 @@ func TestRandEnumValue(t *testing.T) {
 	}
 
 	if r2 != "monday" && r2 != "tuesday" {
-		t.Errorf("Expected monday or tueday, got: %q", r2)
+		t.Errorf("Expected monday or tuesday, got: %q", r2)
+	}
+
+	r3, err := randEnumValue(enum3)
+	if err != nil {
+		t.Error(err)
+	}
+
+	if r3 != "monday" {
+		t.Errorf("Expected monday got: %q", r3)
 	}
 }