Skip to content

Commit 1821c94

Browse files
author
Matt Jones
committed
generate Generate methods for enums (compatible with testing/quick)
1 parent 7133949 commit 1821c94

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

generator/go.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"os"
1717
"path/filepath"
1818
"runtime"
19+
"sort"
1920
"strconv"
2021
"strings"
2122

@@ -422,6 +423,22 @@ func (e *%s) UnmarshalJSON(b []byte) error {
422423
}
423424
`, enumName, enumName, enumName, enumName)
424425

426+
valueStrings := make([]string, 0, len(enum.Values))
427+
for _, val := range enum.Values {
428+
valueStrings = append(valueStrings, strconv.FormatInt(int64(val.Value), 10))
429+
}
430+
sort.Strings(valueStrings)
431+
valueStringsName := strings.ToLower(enumName) + "Values"
432+
433+
g.write(out, `
434+
var %s = []int32{%s}
435+
436+
func (e *%s) Generate(rand *rand.Rand, size int) reflect.Value {
437+
v := %s(%s[rand.Intn(%d)])
438+
return reflect.ValueOf(&v)
439+
}
440+
`, valueStringsName, strings.Join(valueStrings, ", "), enumName, enumName, valueStringsName, len(valueNames))
441+
425442
return nil
426443
}
427444

@@ -620,7 +637,7 @@ func (g *GoGenerator) generateSingle(out io.Writer, thriftPath string, thrift *p
620637
// Imports
621638
imports := []string{"fmt"}
622639
if len(thrift.Enums) > 0 {
623-
imports = append(imports, "strconv")
640+
imports = append(imports, "strconv", "math/rand", "reflect")
624641
}
625642
if len(thrift.Includes) > 0 {
626643
for _, path := range thrift.Includes {

0 commit comments

Comments
 (0)