Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

properly comparing and finding difference between two structs with exported members using go-cmp

I'm writing a Go application, and I want to create a test for it, in that test, I query something from the db, insert it into a struct, and compare that struct values with a static struct of the same type that I had, if they match, the test succeeded, if not, I wanna show the difference. so I'm trying to use go-cmp package.

In general I'm getting this error:

panic: cannot handle unexported field at {main.fooTest}.F1.Int.neg:
    "math/big".Int
consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported [recovered]

I'm getting this is because of the pgtype.Numeric that I have in my struct

type fooTest struct {
    I1   int
    I2   *int
    S1   string
    S2   *string
    F1   pgtype.Numeric
    F2   *pgtype.Numeric
    Ff1  float64
    Ff2  *float64
    Ia1  []int
    Ia2  []*int
    Ia3  *[]int
    Sa1  []string
    Sa2  []*string
    Sa3  *[]string
    Fa1  pgtype.Float8Array
    Fa2  *pgtype.Float8Array
    Faf1 []float64
    Faf2 []*float64
    Faf3 *[]float64
}

so I tried to test with `AllowUnnexported` but the `cmp.Equal` line still fails with that error.

if !cmp.Equal(fooFoo, bar,cmp.AllowUnexported(fooTest{})) {
            t.Errorf("failed test: %v",cmp.Diff(fooFoo, bar))
        }

any ideas how to resolve this ?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried

cmp.Equal(fooFoo, bar, cmp.AllowUnexported(pgtype.Numeric.Int{}))

The documentation of AllowUnexported doesn't mention that it recursively applies this to all values in the struct.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...