Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
package collector
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"testing"
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
)
|
|
|
|
// newTestClient creates a Client backed by an httptest TLS server.
|
|
// routes maps API paths (e.g. "/cluster/resources") to fixture file paths
|
|
// relative to collector/fixtures/.
|
|
func newTestClient(t *testing.T, routes map[string]string) *Client {
|
|
t.Helper()
|
|
|
|
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Strip the /api2/json prefix that Client.Get prepends.
|
|
path := r.URL.Path
|
|
const prefix = "/api2/json"
|
|
if len(path) > len(prefix) {
|
|
path = path[len(prefix):]
|
|
}
|
|
|
|
fixture, ok := routes[path]
|
|
if !ok {
|
|
w.WriteHeader(http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
data, err := os.ReadFile("fixtures/" + fixture)
|
|
if err != nil {
|
|
t.Errorf("failed to read fixture %s: %v", fixture, err)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write(data)
|
|
}))
|
|
t.Cleanup(server.Close)
|
|
|
|
client := NewClient([]string{server.URL}, "test@pam!test=test-token", false, 5)
|
|
client.httpClient = server.Client()
|
|
return client
|
|
}
|
|
|
|
// testCollectorAdapter wraps a Collector into a prometheus.Collector
|
|
// for use with testutil.GatherAndCompare.
|
|
type testCollectorAdapter struct {
|
|
client *Client
|
|
collector Collector
|
|
}
|
|
|
|
func (a *testCollectorAdapter) Describe(ch chan<- *prometheus.Desc) {
|
|
ch <- prometheus.NewDesc("dummy", "dummy", nil, nil)
|
|
}
|
|
|
|
func (a *testCollectorAdapter) Collect(ch chan<- prometheus.Metric) {
|
|
a.collector.Update(a.client, ch)
|
|
}
|