jsonapi/request_test.go

89 lines
1.6 KiB
Go
Raw Normal View History

package jsonapi
2015-07-07 18:46:20 -04:00
import (
"bytes"
"encoding/json"
"fmt"
"testing"
)
2015-07-07 18:46:20 -04:00
//func TestUnmarshalSetsId(t *testing.T) {
//in := samplePayload()
//out := new(Blog)
2015-07-07 18:46:20 -04:00
//if err := UnmarshalJsonApiPayload(in, out); err != nil {
//t.Fatal(err)
//}
2015-07-07 18:46:20 -04:00
//if out.Id != 0 {
//t.Fatalf("Did not set Id on dst interface")
//}
//}
2015-07-06 17:41:53 -04:00
func TestUnmarshalSetsAttrs(t *testing.T) {
in := samplePayload()
out := new(Blog)
if err := UnmarshalJsonApiPayload(in, out); err != nil {
t.Fatal(err)
}
2015-07-07 18:46:20 -04:00
o := bytes.NewBuffer(nil)
json.NewEncoder(o).Encode(out)
fmt.Printf("%s\n", o.Bytes())
if out.CreatedAt.IsZero() {
t.Fatalf("Did not parse time")
}
if out.ViewCount != 1000 {
t.Fatalf("View count not properly serialized")
}
}
2015-07-06 17:41:53 -04:00
2015-07-07 12:52:38 -04:00
func samplePayload() *JsonApiOnePayload {
2015-07-07 18:46:20 -04:00
payload := &JsonApiOnePayload{
2015-07-06 17:41:53 -04:00
Data: &JsonApiNode{
Type: "blogs",
Attributes: map[string]interface{}{
"title": "New blog",
"created_at": 1436216820,
"view_count": 1000,
},
2015-07-07 18:46:20 -04:00
Relationships: map[string]interface{}{
"posts": &JsonApiRelationshipManyNode{
Data: []*JsonApiNode{
&JsonApiNode{
Type: "posts",
Attributes: map[string]interface{}{
"title": "Foo",
"body": "Bar",
},
},
},
},
"current_post": &JsonApiRelationshipOneNode{
Data: &JsonApiNode{
Type: "posts",
Attributes: map[string]interface{}{
"title": "Bas",
"body": "Fuubar",
},
},
},
},
2015-07-06 17:41:53 -04:00
},
}
2015-07-07 18:46:20 -04:00
out := bytes.NewBuffer(nil)
json.NewEncoder(out).Encode(payload)
p := new(JsonApiOnePayload)
json.NewDecoder(out).Decode(p)
return p
2015-07-06 17:41:53 -04:00
}