Improves LengthOfResponse() utility function:

Problems arise from the fact that the are two kind of successful
    responses: The array of objects response like
    {"key":[{obj1},{obj2},...]} and the single object response like
    {"key":{obj}}. The function will try to check if the response can be
    unmarshaled in an array of generic type variables so to match the
    first case. If not it will try to unmarshal to a single generic type
    variable and 1 will be returned as the length of the response. If
    this will also fail -1 will be returned.
This commit is contained in:
smavros 2019-08-11 16:55:20 +02:00
parent 8f5c47dde9
commit 6a9709f7b8

View file

@ -40,7 +40,6 @@ func LengthOfResponse(router *gin.Engine, token string, url string,
method string, body []byte) int { method string, body []byte) int {
w := httptest.NewRecorder() w := httptest.NewRecorder()
responseLength := 0
if body != nil { if body != nil {
req, _ := http.NewRequest(method, url, bytes.NewBuffer(body)) req, _ := http.NewRequest(method, url, bytes.NewBuffer(body))
@ -53,23 +52,37 @@ func LengthOfResponse(router *gin.Engine, token string, url string,
router.ServeHTTP(w, req) router.ServeHTTP(w, req)
} }
// Get the response // Convert the response in array of bytes
var body_data map[string][]interface{} responseBytes := []byte(w.Body.String())
err := json.Unmarshal([]byte(w.Body.String()), &body_data) // First we are trying to unmarshal the response into an array of
if err != nil { // general type variables ([]interface{}). If this fails we will try
return responseLength // to unmarshal into a single general type variable (interface{}).
// If that also fails we will return -1.
// Response might be array of objects
var arrayResponse map[string][]interface{}
err := json.Unmarshal(responseBytes, &arrayResponse)
if err == nil {
// Get an arbitrary key from tha map. The only key (entry) of
// course is the model's name. With that trick we do not have to
// pass the higher level key as argument.
for arbitrary_tag := range arrayResponse {
return len(arrayResponse[arbitrary_tag])
}
} }
// Get an arbitrary key from tha map. The only key (entry) of course // Response might be a single object
// is the model's name. With that trick we do not have to pass the var singleResponse map[string]interface{}
// higher level key as argument. err = json.Unmarshal(responseBytes, &singleResponse)
for arbitrary_tag := range body_data { if err == nil {
responseLength = len(body_data[arbitrary_tag]) return 1
break
} }
return responseLength // Failed to identify response. It means we got a different HTTP
// code than 200.
return -1
} }
func NewTestEndpoint(router *gin.Engine, token string, url string, func NewTestEndpoint(router *gin.Engine, token string, url string,