Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package signalbot
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"sync"
|
|
"testing"
|
|
)
|
|
|
|
// fakeAPI is a minimal stand-in for signal-cli-rest-api. Routes are
|
|
// registered on mux; hits counts requests per "METHOD path".
|
|
type fakeAPI struct {
|
|
*httptest.Server
|
|
mux *http.ServeMux
|
|
mu sync.Mutex
|
|
hits map[string]int
|
|
}
|
|
|
|
func newFakeAPI(t *testing.T) *fakeAPI {
|
|
t.Helper()
|
|
f := &fakeAPI{mux: http.NewServeMux(), hits: map[string]int{}}
|
|
f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
f.mu.Lock()
|
|
f.hits[r.Method+" "+r.URL.Path]++
|
|
f.mu.Unlock()
|
|
f.mux.ServeHTTP(w, r)
|
|
}))
|
|
t.Cleanup(f.Close)
|
|
return f
|
|
}
|
|
|
|
func (f *fakeAPI) hitCount(key string) int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
return f.hits[key]
|
|
}
|
|
|
|
// accounts serves GET /v1/accounts with the given raw JSON body.
|
|
func (f *fakeAPI) accounts(body string) {
|
|
f.mux.HandleFunc("GET /v1/accounts", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_, _ = w.Write([]byte(body))
|
|
})
|
|
}
|
|
|
|
func (f *fakeAPI) health() {
|
|
f.mux.HandleFunc("GET /v1/health", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func mustNew(t *testing.T, url string, opts ...Option) *Client {
|
|
t.Helper()
|
|
c, err := New(url, opts...)
|
|
if err != nil {
|
|
t.Fatalf("New: %v", err)
|
|
}
|
|
return c
|
|
}
|