Metrics are served on METRICS_PORT (default 2112, "off" to disable), never on the public port. Besides the Go runtime and process metrics this adds: - http_requests_total and http_request_duration_seconds per route pattern, from an Echo middleware. - musicserver_songs_requested_total and musicserver_songs_played_total by pick mode (random, low, classic). The mode is now stored with each queued song (migration 000006, not released yet). - Library size, sync duration, last successful sync, broken songs from the last full sync, and the database connection pool. Refs #35, #36, #37 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package metrics
|
|
|
|
import (
|
|
"context"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
|
|
"music-server/internal/logging"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestMain(m *testing.M) {
|
|
logging.Init("fatal", false)
|
|
os.Exit(m.Run())
|
|
}
|
|
|
|
func TestServerServesRuntimeMetrics(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
NewServer(0).Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
|
|
|
|
assert.Equal(t, http.StatusOK, rec.Code)
|
|
assert.Contains(t, rec.Body.String(), "go_goroutines")
|
|
assert.Contains(t, rec.Body.String(), "process_start_time_seconds")
|
|
}
|
|
|
|
func TestServerServesOnlyMetrics(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
NewServer(0).Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
|
|
assert.Equal(t, http.StatusNotFound, rec.Code)
|
|
}
|
|
|
|
func TestServerStartAndShutdown(t *testing.T) {
|
|
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
|
require.NoError(t, err)
|
|
port := ln.Addr().(*net.TCPAddr).Port
|
|
require.NoError(t, ln.Close())
|
|
|
|
s := NewServer(port)
|
|
require.NoError(t, s.Start())
|
|
resp, err := http.Get("http://" + ln.Addr().String() + "/metrics")
|
|
require.NoError(t, err)
|
|
body, _ := io.ReadAll(resp.Body)
|
|
resp.Body.Close()
|
|
assert.Contains(t, string(body), "go_goroutines")
|
|
|
|
require.NoError(t, s.Shutdown(context.Background()))
|
|
_, err = http.Get("http://" + ln.Addr().String() + "/metrics")
|
|
assert.Error(t, err, "the port is closed after shutdown")
|
|
}
|
|
|
|
func TestServerStartFailsWhenPortIsTaken(t *testing.T) {
|
|
ln, err := net.Listen("tcp", ":0")
|
|
require.NoError(t, err)
|
|
defer ln.Close()
|
|
|
|
assert.Error(t, NewServer(ln.Addr().(*net.TCPAddr).Port).Start())
|
|
}
|