MCPcopy Create free account
hub / github.com/cronitorio/cronitor-cli / NewMockAPI

Function NewMockAPI

internal/testutil/mock_api.go:40–92  ·  view source on GitHub ↗

NewMockAPI creates a new mock API server.

()

Source from the content-addressed store, hash-verified

38
39// NewMockAPI creates a new mock API server.
40func NewMockAPI() *MockAPI {
41 m := &MockAPI{
42 routes: make(map[string]mockResponse),
43 defaultStatus: 200,
44 defaultBody: `{}`,
45 }
46
47 m.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
48 bodyBytes, _ := io.ReadAll(r.Body)
49 defer r.Body.Close()
50
51 m.mu.Lock()
52 m.Requests = append(m.Requests, RecordedRequest{
53 Method: r.Method,
54 Path: r.URL.Path,
55 QueryParams: r.URL.Query(),
56 Headers: r.Header.Clone(),
57 Body: string(bodyBytes),
58 })
59 m.mu.Unlock()
60
61 // Find matching route
62 key := r.Method + " " + r.URL.Path
63 if resp, ok := m.routes[key]; ok {
64 for k, v := range resp.headers {
65 w.Header().Set(k, v)
66 }
67 w.Header().Set("Content-Type", "application/json")
68 w.WriteHeader(resp.status)
69 w.Write([]byte(resp.body))
70 return
71 }
72
73 // Try wildcard match (METHOD *)
74 wildcardKey := r.Method + " *"
75 if resp, ok := m.routes[wildcardKey]; ok {
76 for k, v := range resp.headers {
77 w.Header().Set(k, v)
78 }
79 w.Header().Set("Content-Type", "application/json")
80 w.WriteHeader(resp.status)
81 w.Write([]byte(resp.body))
82 return
83 }
84
85 // Default response
86 w.Header().Set("Content-Type", "application/json")
87 w.WriteHeader(m.defaultStatus)
88 w.Write([]byte(m.defaultBody))
89 }))
90
91 return m
92}
93
94// On registers a response for a specific method + path.
95func (m *MockAPI) On(method, path string, status int, body string) {

Calls 2

CloseMethod · 0.80
WriteMethod · 0.45