package response import ( "encoding/json" "errors" "net/http" "net/http/httptest" "testing" "github.com/gin-gonic/gin" ) func init() { gin.SetMode(gin.TestMode) } func run(handler gin.HandlerFunc) *httptest.ResponseRecorder { r := gin.New() r.GET("/x", handler) rec := httptest.NewRecorder() req, _ := http.NewRequest(http.MethodGet, "/x", nil) r.ServeHTTP(rec, req) return rec } func decodeEnv(t *testing.T, rec *httptest.ResponseRecorder) Envelope { t.Helper() var env Envelope if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil { t.Fatalf("decode: %v (body=%s)", err, rec.Body.String()) } return env } func TestOK_Wraps200AndMessage(t *testing.T) { rec := run(func(c *gin.Context) { OK(c, map[string]int{"n": 7}) }) if rec.Code != http.StatusOK { t.Fatalf("status: %d", rec.Code) } env := decodeEnv(t, rec) if env.Error != nil { t.Errorf("error should be nil, got %q", *env.Error) } if env.Message != "OK" { t.Errorf("message: %q", env.Message) } } func TestErr_SerialisesErrorAndMessage(t *testing.T) { rec := run(func(c *gin.Context) { Err(c, http.StatusBadRequest, errors.New("boom")) }) if rec.Code != http.StatusBadRequest { t.Fatalf("status: %d", rec.Code) } env := decodeEnv(t, rec) if env.Error == nil || *env.Error != "boom" { t.Errorf("error: %v", env.Error) } if env.Message != "boom" { t.Errorf("message: %q", env.Message) } if env.Data != nil { t.Errorf("data should be nil on error, got %v", env.Data) } } func TestNoContent_NoBody(t *testing.T) { rec := run(func(c *gin.Context) { NoContent(c) }) if rec.Code != http.StatusNoContent { t.Fatalf("status: %d", rec.Code) } if rec.Body.Len() != 0 { t.Errorf("204 should have empty body, got %q", rec.Body.String()) } }