2025-01-29 10:42:21 +00:00
|
|
|
package testserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2025-01-31 13:31:23 +00:00
|
|
|
"io"
|
2025-01-29 10:42:21 +00:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
|
2025-01-31 13:31:23 +00:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
2025-01-29 10:42:21 +00:00
|
|
|
"github.com/databricks/cli/internal/testutil"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Server struct {
|
|
|
|
*httptest.Server
|
|
|
|
Mux *http.ServeMux
|
|
|
|
|
|
|
|
t testutil.TestingT
|
2025-01-31 13:31:23 +00:00
|
|
|
|
|
|
|
RecordRequests bool
|
|
|
|
|
|
|
|
Requests []Request
|
|
|
|
}
|
|
|
|
|
|
|
|
type Request struct {
|
|
|
|
Method string `json:"method"`
|
|
|
|
Path string `json:"path"`
|
|
|
|
Body any `json:"body"`
|
2025-01-29 10:42:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func New(t testutil.TestingT) *Server {
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
server := httptest.NewServer(mux)
|
2025-01-29 15:54:33 +00:00
|
|
|
t.Cleanup(server.Close)
|
2025-01-29 10:42:21 +00:00
|
|
|
|
|
|
|
return &Server{
|
|
|
|
Server: server,
|
|
|
|
Mux: mux,
|
|
|
|
t: t,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type HandlerFunc func(req *http.Request) (resp any, err error)
|
|
|
|
|
|
|
|
func (s *Server) Handle(pattern string, handler HandlerFunc) {
|
|
|
|
s.Mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
resp, err := handler(r)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2025-01-31 13:31:23 +00:00
|
|
|
if s.RecordRequests {
|
|
|
|
body, err := io.ReadAll(r.Body)
|
|
|
|
assert.NoError(s.t, err)
|
|
|
|
|
|
|
|
s.Requests = append(s.Requests, Request{
|
|
|
|
Method: r.Method,
|
|
|
|
Path: r.URL.Path,
|
|
|
|
Body: json.RawMessage(body),
|
|
|
|
})
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2025-01-29 10:42:21 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
|
|
|
|
var respBytes []byte
|
|
|
|
|
|
|
|
respString, ok := resp.(string)
|
|
|
|
if ok {
|
|
|
|
respBytes = []byte(respString)
|
|
|
|
} else {
|
|
|
|
respBytes, err = json.MarshalIndent(resp, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if _, err := w.Write(respBytes); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|