MCPcopy Index your code
hub / github.com/coder/coder / PopulateStruct

Function PopulateStruct

testutil/reflect.go:34–67  ·  view source on GitHub ↗

PopulateStruct does a best effort to populate a struct with random values.

(s interface{}, r *Random)

Source from the content-addressed store, hash-verified

32
33// PopulateStruct does a best effort to populate a struct with random values.
34func PopulateStruct(s interface{}, r *Random) error {
35 if r == nil {
36 r = NewRandom()
37 }
38
39 v := reflect.ValueOf(s)
40 if v.Kind() != reflect.Ptr || v.IsNil() {
41 return xerrors.Errorf("s must be a non-nil pointer")
42 }
43
44 v = v.Elem()
45 if v.Kind() != reflect.Struct {
46 return xerrors.Errorf("s must be a pointer to a struct")
47 }
48
49 t := v.Type()
50 for i := 0; i < t.NumField(); i++ {
51 field := t.Field(i)
52 fieldName := field.Name
53
54 fieldValue := v.Field(i)
55 if !fieldValue.CanSet() {
56 continue // Skip if field is unexported
57 }
58
59 nv, err := populateValue(fieldValue, r)
60 if err != nil {
61 return xerrors.Errorf("%s : %w", fieldName, err)
62 }
63 v.Field(i).Set(nv)
64 }
65
66 return nil
67}
68
69func populateValue(v reflect.Value, r *Random) (reflect.Value, error) {
70 var err error

Callers 3

TestTaskTableConvertFunction · 0.92
populateValueFunction · 0.85

Calls 5

NewRandomFunction · 0.85
populateValueFunction · 0.85
TypeMethod · 0.65
SetMethod · 0.65
ErrorfMethod · 0.45

Tested by 2

TestTaskTableConvertFunction · 0.74