github.com/lmittmann/w3@v0.20.0/rpctest/test_case.go (about) 1 package rpctest 2 3 import ( 4 "fmt" 5 "math/big" 6 "testing" 7 8 "github.com/ethereum/go-ethereum/core/types" 9 "github.com/google/go-cmp/cmp" 10 "github.com/google/go-cmp/cmp/cmpopts" 11 "github.com/lmittmann/w3" 12 "github.com/lmittmann/w3/internal" 13 "github.com/lmittmann/w3/w3types" 14 ) 15 16 type TestCase[T any] struct { 17 Golden string // File name in local "testdata/" directory without ".golden" extension 18 Call w3types.RPCCallerFactory[T] // Call to test 19 WantRet T // Wanted return value of the call 20 WantErr error // Wanted error of the call 21 } 22 23 func RunTestCases[T any](t *testing.T, tests []TestCase[T], opts ...cmp.Option) { 24 t.Helper() 25 26 for _, test := range tests { 27 t.Run(test.Golden, func(t *testing.T) { 28 t.Helper() 29 30 srv := NewFileServer(t, fmt.Sprintf("testdata/%s.golden", test.Golden)) 31 defer srv.Close() 32 33 client := w3.MustDial(srv.URL()) 34 defer client.Close() 35 36 var gotRet T 37 gotErr := client.Call(test.Call.Returns(&gotRet)) 38 comp(t, test.WantRet, gotRet, test.WantErr, gotErr, opts...) 39 }) 40 } 41 } 42 43 func comp[T any](t *testing.T, wantVal, gotVal T, wantErr, gotErr error, opts ...cmp.Option) { 44 t.Helper() 45 46 // compare errors 47 if diff := cmp.Diff(wantErr, gotErr, 48 internal.EquateErrors(), 49 ); diff != "" { 50 t.Fatalf("Err: (-want, +got)\n%s", diff) 51 } 52 if wantErr != nil { 53 return 54 } 55 56 // compare values 57 opts = append(opts, 58 cmp.AllowUnexported(big.Int{}, types.Transaction{}, types.Block{}), 59 cmpopts.IgnoreFields(types.Transaction{}, "time", "hash", "size", "from"), 60 cmpopts.IgnoreFields(types.Block{}, "hash", "size"), 61 cmpopts.EquateEmpty(), 62 ) 63 if diff := cmp.Diff(wantVal, gotVal, opts...); diff != "" { 64 t.Fatalf("(-want, +got)\n%s", diff) 65 } 66 }