Skip to content
This repository has been archived by the owner on Dec 8, 2022. It is now read-only.

Commit

Permalink
bugfix: don't panic on typed array
Browse files Browse the repository at this point in the history
Fixed error:
```
$ cat > /tmp/1.go <<EOF
package main
import "github.com/bxcodec/faker"
type array [16]byte
func main() {
        var a array
        faker.FakeData(&a)
}
EOF

$ go run /tmp/1.go
panic: reflect.MakeSlice of non-slice type

goroutine 1 [running]:
reflect.MakeSlice(0x53d860, 0x4eed00, 0xd, 0xd, 0x0, 0x0, 0x0)
        /home/xaionaro/.gimme/versions/go1.13.linux.amd64/src/reflect/value.go:2256 +0x1d8
github.com/bxcodec/faker.getValue(0x4eed00, 0xc0000163a0, 0x191, 0x4eed01, 0x4eed00, 0xc0000163a0, 0x20300000000000)
        /home/xaionaro/go/src/github.com/bxcodec/faker/faker.go:444 +0xca0
github.com/bxcodec/faker.getValue(0x4dea40, 0xc000016380, 0xc00000e240, 0xc00000e220, 0x40c556, 0xc00000e1e0, 0xc00000e1c0)
        /home/xaionaro/go/src/github.com/bxcodec/faker/faker.go:355 +0x169e
github.com/bxcodec/faker.FakeData(0x4dea40, 0xc000016380, 0x56e00, 0xc0000240b8)
        /home/xaionaro/go/src/github.com/bxcodec/faker/faker.go:280 +0x1c6
main.main()
        /tmp/1.go:6 +0x3d
exit status 2
```

Signed-off-by: Dmitry Yu Okunev <xaionaro@dx.center>
  • Loading branch information
xaionaro committed Jun 6, 2020
1 parent 7b6a077 commit eaf3a5c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
13 changes: 12 additions & 1 deletion faker.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ func getValue(a interface{}) (reflect.Value, error) {
case reflect.String:
res := randomString(randomStringLen, &lang)
return reflect.ValueOf(res), nil
case reflect.Array, reflect.Slice:
case reflect.Slice:
len := randomSliceAndMapSize()
if shouldSetNil && len == 0 {
return reflect.Zero(t), nil
Expand All @@ -482,6 +482,17 @@ func getValue(a interface{}) (reflect.Value, error) {
v.Index(i).Set(val)
}
return v, nil
case reflect.Array:
v := reflect.New(t).Elem()
for i := 0; i < v.Len(); i++ {
val, err := getValue(v.Index(i).Interface())
if err != nil {
return reflect.Value{}, err
}
val = val.Convert(v.Index(i).Type())
v.Index(i).Set(val)
}
return v, nil
case reflect.Int:
return reflect.ValueOf(randomInteger()), nil
case reflect.Int8:
Expand Down
3 changes: 3 additions & 0 deletions faker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ var (

type SomeInt32 int32

type TArray [16]byte

type SomeStruct struct {
Inta int
Int8 int8
Expand Down Expand Up @@ -65,6 +67,7 @@ type SomeStruct struct {
SFloat64 []float64
SBool []bool
Struct AStruct
TArray TArray
Time time.Time
Stime []time.Time
Currency string `faker:"currency"`
Expand Down

0 comments on commit eaf3a5c

Please sign in to comment.