Skip to content

Instantly share code, notes, and snippets.

@maxatome
Created March 19, 2021 17:53
Show Gist options
  • Save maxatome/d31a99550cb7493295c50491c8b114eb to your computer and use it in GitHub Desktop.
Save maxatome/d31a99550cb7493295c50491c8b114eb to your computer and use it in GitHub Desktop.
Nested go-testdeep comparison
package main_test
import (
"fmt"
"testing"
"github.com/maxatome/go-testdeep/td"
)
type Value interface{}
type Cursor struct {
ID int `msgpack:"i"`
Value Value `msgpack:"v,omitempty"`
}
type User struct {
ID int `json:"id,omitempty"`
Active bool `json:"active,omitempty"`
Username string `json:"username,omitempty"`
}
type UserEdge struct {
Node *User `json:"node"`
Cursor Cursor `json:"cursor"`
}
type UserConnection struct {
Edges []*UserEdge `json:"edges"`
PageInfo PageInfo `json:"pageInfo"`
TotalCount int `json:"totalCount"`
}
type PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
HasPreviousPage bool `json:"hasPreviousPage"`
StartCursor *Cursor `json:"startCursor"`
EndCursor *Cursor `json:"endCursor"`
}
var got = &UserConnection{
Edges: []*UserEdge{ // <- I want to test structs at specific indexes in this slice
{
Node: &User{ // <- I want to test fields from this struct
ID: 21474836481,
Username: "user 1",
Active: true,
},
},
{
Node: &User{ // <- I want to test fields from this struct
ID: 21474836482,
Username: "user2",
Active: false,
},
},
},
}
func Test(t *testing.T) {
//
// With JSONPointer + JSON
td.Cmp(t, got,
//the index in slice --v
td.JSONPointer("/edges/1/node",
td.JSON(`
{
"id": 21474836482,
"username": "user2",
// "active" is omitted as false
}`)),
"With JSONPointer + JSON")
//
// JSONPointer to test Username field, so with SuperJSONOf
td.Cmp(t, got,
//the index in slice --v
td.JSONPointer("/edges/1/node",
td.SuperJSONOf(`{"username": "user2"}`)),
"With JSONPointer + SuperJSONOf")
// The index in Edges we want to test
index := 1
//
// Smuggle does not handle slice/array/map indexing (yet) as
// JSONPointer does, so we have to chain another Smuggle behind with
// a custom function
td.Cmp(t, got,
td.Smuggle("Edges",
td.Smuggle(
func(ue []*UserEdge) (*User, error) {
if index >= len(ue) {
return nil, fmt.Errorf("Edges len is too small: %d", len(ue))
}
if ue[index] == nil {
return nil, fmt.Errorf("Edges[%d] is nil", index)
}
return ue[index].Node, nil
},
// The final expected User
&User{
ID: 21474836482,
Username: "user2",
Active: false,
})),
"With Smuggle")
//
// Smuggle to test Username field
td.Cmp(t, got,
td.Smuggle("Edges",
td.Smuggle(
func(ue []*UserEdge) (*User, error) {
if index >= len(ue) {
return nil, fmt.Errorf("Edges len is too small: %d", len(ue))
}
if ue[index] == nil {
return nil, fmt.Errorf("Edges[%d] is nil", index)
}
return ue[index].Node, nil
},
// The final expected User
td.Struct(&User{Username: "user2"}, nil))),
"With Smuggle + Struct")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment