Co-Authored-By: Virgil <virgil@lethean.io> Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
82 lines
2.1 KiB
Go
82 lines
2.1 KiB
Go
// SPDX-License-Identifier: EUPL-1.2
|
|
|
|
package api_test
|
|
|
|
import (
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
api "forge.lthn.ai/core/go-api"
|
|
)
|
|
|
|
// ── Swagger endpoint ────────────────────────────────────────────────────
|
|
|
|
func TestSwaggerEndpoint_Good(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
e, err := api.New(api.WithSwagger("Test API", "A test API service", "1.0.0"))
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
|
|
// Use a real test server because gin-swagger reads RequestURI
|
|
// which is not populated by httptest.NewRecorder.
|
|
srv := httptest.NewServer(e.Handler())
|
|
defer srv.Close()
|
|
|
|
resp, err := http.Get(srv.URL + "/swagger/doc.json")
|
|
if err != nil {
|
|
t.Fatalf("request failed: %v", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
t.Fatalf("expected 200, got %d", resp.StatusCode)
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatalf("failed to read body: %v", err)
|
|
}
|
|
if len(body) == 0 {
|
|
t.Fatal("expected non-empty response body")
|
|
}
|
|
|
|
// Verify the body is valid JSON with expected fields.
|
|
var doc map[string]any
|
|
if err := json.Unmarshal(body, &doc); err != nil {
|
|
t.Fatalf("expected valid JSON, got unmarshal error: %v", err)
|
|
}
|
|
|
|
info, ok := doc["info"].(map[string]any)
|
|
if !ok {
|
|
t.Fatal("expected 'info' object in swagger doc")
|
|
}
|
|
if info["title"] != "Test API" {
|
|
t.Fatalf("expected title=%q, got %q", "Test API", info["title"])
|
|
}
|
|
if info["version"] != "1.0.0" {
|
|
t.Fatalf("expected version=%q, got %q", "1.0.0", info["version"])
|
|
}
|
|
}
|
|
|
|
func TestSwaggerDisabledByDefault_Good(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
|
|
// Without WithSwagger, GET /swagger/doc.json should return 404.
|
|
e, _ := api.New()
|
|
|
|
h := e.Handler()
|
|
w := httptest.NewRecorder()
|
|
req, _ := http.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
|
|
h.ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusNotFound {
|
|
t.Fatalf("expected 404 for /swagger/doc.json without WithSwagger, got %d", w.Code)
|
|
}
|
|
}
|