forked from mtusi2026/mtusi2026lab6
74 lines
2.2 KiB
Go
74 lines
2.2 KiB
Go
package fiber
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// TestMetricsEndpoint exposes completed requests without token or user labels.
|
|
func TestMetricsEndpoint(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
call(t, ctrl, http.MethodGet, "/health/live", "", nil, http.StatusOK)
|
|
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = resp.Body.Close()
|
|
}()
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if resp.StatusCode != http.StatusOK || !strings.Contains(string(body), "messenger_http_requests_total") || !strings.Contains(string(body), "messenger_http_duration_seconds_bucket") {
|
|
t.Fatalf("invalid metrics response: status %d", resp.StatusCode)
|
|
}
|
|
if resp.Header.Get("X-Instance-Id") == "" {
|
|
t.Fatal("metrics response lacks instance ID")
|
|
}
|
|
}
|
|
|
|
// TestInstanceIdentityRemainsStable verifies errors and successes identify the same process.
|
|
func TestInstanceIdentityRemainsStable(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
var instance string
|
|
for _, path := range []string{"/health/live", "/unknown"} {
|
|
resp, err := ctrl.server.Test(httptest.NewRequest(http.MethodGet, path, nil))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if instance == "" {
|
|
instance = resp.Header.Get("X-Instance-Id")
|
|
}
|
|
if instance == "" || resp.Header.Get("X-Instance-Id") != instance {
|
|
t.Fatal("unstable instance identity")
|
|
}
|
|
if err := resp.Body.Close(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestMissingIdempotencyHeader rejects an otherwise valid authenticated write.
|
|
func TestMissingIdempotencyHeader(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
caller := user(t, ctrl)
|
|
room := chat(t, ctrl, caller)
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room+"/messages", strings.NewReader(`{"text":"valid"}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+caller)
|
|
resp, err := ctrl.server.Test(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = resp.Body.Close()
|
|
}()
|
|
if resp.StatusCode != http.StatusBadRequest {
|
|
t.Fatalf("missing key accepted: %d", resp.StatusCode)
|
|
}
|
|
}
|