jsonapi/response_test.go

88 lines
1.5 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 {
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) {
testModel := Blog{
Id: 5,
Title: "Title 1",
2015-07-05 13:59:35 -04:00
Posts: []Post{
Post{
Id: 1,
Title: "Foo",
Body: "Bar",
},
Post{
Id: 2,
Title: "Fuubar",
Body: "Bas",
},
},
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
if response.Type != "Blogs" {
t.Fatalf("type should have been Blogs")
2015-07-05 11:59:30 -04:00
}
if response.Id != "5" {
t.Fatalf("Id not transfered")
}
}
func TestSupportsAttributes(t *testing.T) {
testModel := Blog{
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")
}
}