Comments (5)
What you have done will work - I'd recommend also catching the errors from request.Get
and jsonapi.UnmarshalPayload
and doing Expect(err).To(BeNil())
.
This solution assumes that your test code has access to the structs with jsonapi
annotation (ie repositories.Restaurant
). If you did not have access to these structs I would recommend doing something along the lines of:
package main
import (
"encoding/json"
"reflect"
)
func JSONStringsEqual(s1, s2 string) (b bool, err error) {
b = false
var i1, i2 interface{}
if err = json.Unmarshal([]byte(s1), &i1); err != nil {
return
}
if err = json.Unmarshal([]byte(s2), &i2); err != nil {
return
}
b = reflect.DeepEqual(i1, i2)
return
}
Then from your test you would do:
Expect(JSONStringsEqual(body, expectedPayload)).To(Equal(true))
from jsonapi.
The reason why the order is seemingly random is because the underlying data structure is a map
. When iterating over a map
in go you will find that the order changes every time you execute the code. For instance given a main.go
file with:
package main
import "fmt"
func main() {
groupOfTen := map[string]string{
"BE": "Belgium",
"CA": "Canada",
"FR": "France",
"DE": "Germany",
"IT": "Italy",
"JP": "Japan",
"NL": "Netherlands",
"SE": "Sweden",
"CH": "Switzerland",
"UK": "United Kingdom",
"US": "United States",
}
for k, v := range groupOfTen {
fmt.Println(k, v)
}
}
The first time I ran this file:
$ go run main.go
FR France
IT Italy
JP Japan
CH Switzerland
US United States
BE Belgium
DE Germany
NL Netherlands
SE Sweden
UK United Kingdom
CA Canada
The second time:
$ go run main.go
IT Italy
NL Netherlands
SE Sweden
CH Switzerland
UK United Kingdom
US United States
CA Canada
FR France
JP Japan
BE Belgium
DE Germany
The third time:
$ go run main.go
BE Belgium
NL Netherlands
SE Sweden
CH Switzerland
CA Canada
FR France
DE Germany
IT Italy
JP Japan
UK United Kingdom
US United States
And so on and so forth. Every time you execute the file you should expect a varying order. In go you should not rely on a map if you required ordered data - there are other data structures for that.
The underlying data structure for the included
key that this library produces is a []*Node
(see here and here). However this []*Node
slice is populated by iterating over the Relationships
which is a map[string]interface{}
(see here). This random iteration order over Relationships
is what is producing the behaviour you have described. This behaviour is expected and is JSON API specification compliant.
The tests you are writing should be resilient to this kind of change in ordering. If you provide me with a code sample I will be able to point you in the right direction.
from jsonapi.
Thanks for the nice explanation, I'm quite new to Go(and i love it), so still need to learn a lot about it.
type Restaurant struct {
ID uint `jsonapi:"primary,restaurants"`
Name string `jsonapi:"attr,name" valid:"required"`
Menus []*Menu `jsonapi:"relation,menus"`
}
type Menu struct {
ID uint `jsonapi:"primary,menus"`
Name string `jsonapi:"attr,name" valid:"required"`
RestaurantID uint
MenuItems []*MenuItem `jsonapi:"relation,menuItems"`
}
type MenuItem struct {
ID uint `jsonapi:"primary,menuItems"`
MenuID uint `jsonapi:"attr,menuId"`
Name string `jsonapi:"attr,name" valid:"required"`
Ingredients string `jsonapi:"attr,ingredients" valid:"required"`
Price float32 `jsonapi:"attr,price" valid:"required"`
}
I'm using gingko as my testing framework + the gomega matchers, which is pretty awesome, especially as I'm mainly a Ruby developer used to the Rspec goodies.
showUrl := fmt.Sprintf("%s/restaurants/%d", testServer.URL, restaurant.ID)
response, body, err := request.Get(showUrl).End()
Expect(err).To(BeNil())
expectedPayload := `
{
"data": {
"type": "restaurants",
"id": "1",
"attributes": {
"name": "Test"
},
"relationships": {
"menus": {
"data": [
{
"type": "menus",
"id": "1"
}
]
}
}
},
"included": [
{
"type": "menuItems",
"id": "1",
"attributes": {
"ingredients": "Tomato",
"menuId": 1,
"name": "Shopska salad",
"price": 15.5
}
},
{
"type": "menus",
"id": "1",
"attributes": {
"name": "Lunch"
},
"relationships": {
"menuItems": {
"data": [
{
"type": "menuItems",
"id": "1"
}
]
}
}
}
]
}
`
Expect(response.StatusCode).To(Equal(http.StatusOK))
Expect(body).To(MatchJSON(expectedPayload))
For every few test runs the menus
and menuItems
switch positions which breaks it.
Thanks again for your help !🙇 It was driving me mad, thinking it was me doing something stupid.
from jsonapi.
Actually, I think I can unmarshal the response body and compare it to the record from the database 🤔
from jsonapi.
I got it working like this, i think it's good enough. I'm still open to suggestions though
showUrl := fmt.Sprintf("%s/restaurants/%d", testServer.URL, restaurant.ID)
response, _, _ := request.Get(showUrl).End()
restaurantFromResponse := new(repositories.Restaurant)
jsonapi.UnmarshalPayload(response.Body, restaurantFromResponse)
Expect(response.StatusCode).To(Equal(http.StatusOK))
_, restaurantFromDb := repositories.Restaurants.FindByID(restaurant.ID)
Expect(*restaurantFromResponse).To(BeEquivalentTo(restaurantFromDb))
from jsonapi.
Related Issues (20)
- Type validation on post is skipped
- Support for partial inclusion of relationships
- Asymmetrical behavior with json.RawMessage-type fields
- Community adoption of project HOT 4
- Unmarshall array of object in attribute HOT 1
- map inside struct unmarshalling HOT 2
- Export clearIncluded HOT 1
- got the wrong id when unmarshel a stract with an Int64 id HOT 1
- Is this project active? HOT 4
- Polymorphic relationships HOT 1
- Skipping an element in an array due to unmatched type
- Does example in README have a typo? HOT 1
- int64 id value changed while decoding HOT 12
- Marshal nested object does not work
- data is not a jsonapi representation of *type HOT 2
- Support for Unmarshalling Slices of floats/ints/bools
- Empty relation atrributes HOT 1
- adding meta at time of encoding
- jsonapi.MarshalPayload sets response status to 200, but I want 201 (created) HOT 1
- The wiki shows some weird 'hack' text
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jsonapi.