jsonapi/response_test.go

111 lines
2.0 KiB
Go
Raw Normal View History

2015-07-05 11:59:30 -04:00
package jsonapi
2015-07-05 13:59:35 -04:00
import (
"bytes"
"encoding/json"
"fmt"
"testing"
)
type Post struct {
Id int `jsonapi:"primary,posts"`
Title string `jsonapi:"attr,title"`
Body string `jsonapi:"attr,body"`
}
2015-07-05 11:59:30 -04:00
type Blog struct {
2015-07-06 13:38:42 -04:00
Id int `jsonapi:"primary,blogs"`
Title string `jsonapi:"attr,title"`
Posts []*Post `jsonapi:"relation,posts"`
CurrentPost *Post `jsonapi:"relation,current_post"`
2015-07-05 11:59:30 -04:00
}
func TestHasPrimaryAnnotation(t *testing.T) {
2015-07-06 13:38:42 -04:00
testModel := &Blog{
2015-07-05 11:59:30 -04:00
Id: 5,
Title: "Title 1",
2015-07-06 13:38:42 -04:00
Posts: []*Post{
&Post{
2015-07-05 13:59:35 -04:00
Id: 1,
Title: "Foo",
Body: "Bar",
},
2015-07-06 13:38:42 -04:00
&Post{
2015-07-05 13:59:35 -04:00
Id: 2,
Title: "Fuubar",
Body: "Bas",
},
},
2015-07-06 13:38:42 -04:00
CurrentPost: &Post{
Id: 1,
Title: "Foo",
Body: "Bar",
},
2015-07-05 11:59:30 -04:00
}
resp, err := CreateJsonApiResponse(testModel)
if err != nil {
t.Fatal(err)
}
2015-07-05 13:59:35 -04:00
out := bytes.NewBuffer(nil)
json.NewEncoder(out).Encode(resp)
fmt.Printf("%s\n", out.Bytes())
response := resp.Data
2015-07-06 13:38:42 -04:00
if response.Type != "blogs" {
t.Fatalf("type should have been blogs, got %s", response.Type)
2015-07-05 11:59:30 -04:00
}
if response.Id != "5" {
t.Fatalf("Id not transfered")
}
}
func TestSupportsAttributes(t *testing.T) {
2015-07-06 13:38:42 -04:00
testModel := &Blog{
2015-07-05 11:59:30 -04:00
Id: 5,
Title: "Title 1",
}
resp, err := CreateJsonApiResponse(testModel)
if err != nil {
t.Fatal(err)
}
2015-07-05 13:59:35 -04:00
response := resp.Data
2015-07-05 11:59:30 -04:00
if response.Attributes == nil || len(response.Attributes) != 1 {
t.Fatalf("Expected 1 Attributes")
}
if response.Attributes["title"] != "Title 1" {
t.Fatalf("Attributes hash not populated using tags correctly")
}
}
2015-07-06 13:38:42 -04:00
func TestNoRelations(t *testing.T) {
testModel := &Blog{Id: 1, Title: "Title 1"}
resp, err := CreateJsonApiResponse(testModel)
if err != nil {
t.Fatal(err)
}
jsonBuffer := bytes.NewBuffer(nil)
json.NewEncoder(jsonBuffer).Encode(resp)
fmt.Printf("%s\n", jsonBuffer.Bytes())
decodedResponse := new(JsonApiResponse)
json.NewDecoder(jsonBuffer).Decode(decodedResponse)
if decodedResponse.Included != nil {
fmt.Printf("%v\n", decodedResponse.Included)
t.Fatalf("Encoding json response did not omit included")
}
}