54 lines
1.4 KiB
Go
54 lines
1.4 KiB
Go
package response
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/gofiber/fiber/v2"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestResponseEnvelope(t *testing.T) {
|
|
for _, status := range []int{200, 299, 300, 400, 500} {
|
|
for _, paginated := range []bool{false, true} {
|
|
t.Run(fmt.Sprintf("%d/paginated=%v", status, paginated), func(t *testing.T) {
|
|
app := fiber.New()
|
|
app.Get("/", func(c *fiber.Ctx) error {
|
|
if paginated {
|
|
return WritePaginatedJSON(c, status, "result", []string{}, nil, 0, 0)
|
|
}
|
|
return WriteJSON(c, status, "result", []string{}, nil)
|
|
})
|
|
res, err := app.Test(httptest.NewRequest("GET", "/", nil))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer res.Body.Close()
|
|
var body map[string]json.RawMessage
|
|
if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
wantStatus := `"error"`
|
|
if status < 300 {
|
|
wantStatus = `"success"`
|
|
}
|
|
if res.StatusCode != status || string(body["status"]) != wantStatus {
|
|
t.Fatalf("status %d, body %s", res.StatusCode, body["status"])
|
|
}
|
|
if _, ok := body["metadata"]; ok {
|
|
t.Error("nil metadata should be omitted")
|
|
}
|
|
for _, key := range []string{"page", "total"} {
|
|
raw, ok := body[key]
|
|
if ok != paginated || (paginated && string(raw) != "0") {
|
|
t.Errorf("%s = %s, present=%v", key, raw, ok)
|
|
}
|
|
}
|
|
if len(body["timestamp"]) == 0 {
|
|
t.Error("missing timestamp")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
}
|