Skip to content

Commit

Permalink
Add tests for unexported pointer to struct
Browse files Browse the repository at this point in the history
  • Loading branch information
acj committed Feb 2, 2024
1 parent d7f9412 commit 699dc4a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions scrub.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ func scrub(src any, shouldScrubFn func(field reflect.StructField) bool) {
continue
} else {
if !structField.IsExported() {
// Avoids "cannot return value obtained from unexported field or method" error
continue
}
scrub(field.Interface(), shouldScrubFn)
Expand Down
58 changes: 58 additions & 0 deletions scrub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,31 @@ func TestTaggedField(t *testing.T) {
assert.Equal(t, expected, actual)
})

t.Run("with a struct containing an unexported pointer to a struct, leaves the unexported field alone", func(t *testing.T) {
type place struct {
Name string `scrub:"true"`
Latitude float64
Longitude float64
}
type person struct {
Name string `scrub:"true"`
Age int
place *place
}
actual := person{Name: "Testy Tester", Age: 26, place: &place{Name: "Testy Tester", Latitude: 1.0, Longitude: 2.0}}
expected := person{
Name: "",
Age: 26,
place: &place{
Name: "Testy Tester",
Latitude: 1.0,
Longitude: 2.0,
},
}
TaggedFields(&actual)
assert.Equal(t, expected, actual)
})

t.Run("with a struct containing a non-nil pointer to a non-struct, scrubs the tagged fields", func(t *testing.T) {
type person struct {
Name string `scrub:"true"`
Expand Down Expand Up @@ -456,6 +481,39 @@ func TestNamedFields(t *testing.T) {
assert.Equal(t, expected, actual)
})

t.Run("with a struct containing an unexported pointer to a struct, leaves the unexported field alone", func(t *testing.T) {
type place struct {
Name string
Latitude float64
Longitude float64
}
type person struct {
Name string
Age int
place *place
}
actual := person{
Name: "Testy Tester",
Age: 26,
place: &place{
Name: "Testy Tester",
Latitude: 1.0,
Longitude: 2.0,
},
}
expected := person{
Name: "",
Age: 26,
place: &place{
Name: "Testy Tester",
Latitude: 1.0,
Longitude: 2.0,
},
}
NamedFields(&actual, "Name")
assert.Equal(t, expected, actual)
})

t.Run("with a struct containing a non-nil pointer to a non-struct, scrubs the named fields", func(t *testing.T) {
type person struct {
Name string
Expand Down

0 comments on commit 699dc4a

Please sign in to comment.