Skip to content

Commit e44f185

Browse files
authored
feat: Faker should preserve previous values, if set (#1429)
This helps simplify codegen/mockgen scenarios, where some enums aren't faked correctly. This way the template struct can have correct enums in a specific field, while faking other fields. Used in stripe plugin. Co-authored-by: Kemal Hadimli <[email protected]>
1 parent 870936f commit e44f185

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

faker/faker.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,19 @@ func (f faker) getFakedValue(a any) (reflect.Value, error) {
4848
ft := time.Now().Add(time.Duration(rand.Int63()))
4949
return reflect.ValueOf(ft), nil
5050
default:
51+
cur := reflect.ValueOf(a)
52+
5153
v := reflect.New(t).Elem()
5254
for i := 0; i < v.NumField(); i++ {
5355
if !v.Field(i).CanSet() {
5456
continue // to avoid panic to set on unexported field in struct
5557
}
58+
curField := cur.Field(i)
59+
if curField.IsValid() && !curField.IsZero() {
60+
v.Field(i).Set(curField) // preserve non-empty field values
61+
continue
62+
}
63+
5664
val, err := f.getFakedValue(v.Field(i).Interface())
5765
if err != nil {
5866
if err == errEFaceNotAllowed { // skip empty interfaces

faker/faker_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,22 @@ func TestFakerWithCustomType(t *testing.T) {
5151
assert.NotEmpty(t, a.D)
5252
}
5353

54+
func TestFakerWithCustomTypePreserve(t *testing.T) {
55+
a := fakerStructWithCustomType{
56+
A: "A",
57+
B: map[string]customType{"b": "B"},
58+
C: map[customType]string{"c": "C"},
59+
D: []customType{"D", "D2"},
60+
}
61+
if err := FakeObject(&a); err != nil {
62+
t.Fatal(err)
63+
}
64+
assert.EqualValues(t, "A", a.A)
65+
assert.EqualValues(t, map[string]customType{"b": "B"}, a.B)
66+
assert.EqualValues(t, map[customType]string{"c": "C"}, a.C)
67+
assert.EqualValues(t, []customType{"D", "D2"}, a.D)
68+
}
69+
5470
type complexType struct {
5571
IPAddress net.IP
5672
IPAddresses []net.IP

0 commit comments

Comments
 (0)