Skip to content

Commit f857951

Browse files
author
Matt Jones
committed
generate Generate methods for enums (compatible with testing/quick)
1 parent 67448a7 commit f857951

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

@@ -386,6 +387,22 @@ func (e *%s) UnmarshalJSON(b []byte) error {
386387
}
387388
`, enumName, enumName, enumName, enumName)
388389

390+
valueStrings := make([]string, 0, len(enum.Values))
391+
for _, val := range enum.Values {
392+
valueStrings = append(valueStrings, strconv.FormatInt(int64(val.Value), 10))
393+
}
394+
sort.Strings(valueStrings)
395+
valueStringsName := strings.ToLower(enumName) + "Values"
396+
397+
g.write(out, `
398+
var %s = []int32{%s}
399+
400+
func (e *%s) Generate(rand *rand.Rand, size int) reflect.Value {
401+
v := %s(%s[rand.Intn(%d)])
402+
return reflect.ValueOf(&v)
403+
}
404+
`, valueStringsName, strings.Join(valueStrings, ", "), enumName, enumName, valueStringsName, len(valueNames))
405+
389406
return nil
390407
}
391408

@@ -584,7 +601,7 @@ func (g *GoGenerator) generateSingle(out io.Writer, thriftPath string, thrift *p
584601
// Imports
585602
imports := []string{"fmt"}
586603
if len(thrift.Enums) > 0 {
587-
imports = append(imports, "strconv")
604+
imports = append(imports, "strconv", "math/rand", "reflect")
588605
}
589606
if len(thrift.Includes) > 0 {
590607
for _, path := range thrift.Includes {

0 commit comments

Comments
 (0)