Repository navigation
Expand file tree
/
Copy pathmock_test.go
More file actions
310 lines (258 loc) · 6.95 KB
/
Copy pathmock_test.go
File metadata and controls
310 lines (258 loc) · 6.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package mcp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
)
// ============================================================
// Mock Logger
// ============================================================
// MockLogger Mock logger (for testing)
type MockLogger struct {
mu sync.Mutex
Logs []LogEntry
Enabled bool // Whether logging is enabled
}
// LogEntry log entry
type LogEntry struct {
Level string
Format string
Args []any
Message string // Formatted message
}
func NewMockLogger() *MockLogger {
return &MockLogger{
Logs: make([]LogEntry, 0),
Enabled: true,
}
}
func (m *MockLogger) Debugf(format string, args ...any) {
m.log("DEBUG", format, args...)
}
func (m *MockLogger) Infof(format string, args ...any) {
m.log("INFO", format, args...)
}
func (m *MockLogger) Warnf(format string, args ...any) {
m.log("WARN", format, args...)
}
func (m *MockLogger) Errorf(format string, args ...any) {
m.log("ERROR", format, args...)
}
func (m *MockLogger) log(level, format string, args ...any) {
if !m.Enabled {
return
}
m.mu.Lock()
defer m.mu.Unlock()
message := fmt.Sprintf(format, args...)
m.Logs = append(m.Logs, LogEntry{
Level: level,
Format: format,
Args: args,
Message: message,
})
}
// GetLogs gets all logs
func (m *MockLogger) GetLogs() []LogEntry {
m.mu.Lock()
defer m.mu.Unlock()
return append([]LogEntry{}, m.Logs...)
}
// GetLogsByLevel gets logs by specified level
func (m *MockLogger) GetLogsByLevel(level string) []LogEntry {
m.mu.Lock()
defer m.mu.Unlock()
var result []LogEntry
for _, log := range m.Logs {
if log.Level == level {
result = append(result, log)
}
}
return result
}
// Clear clears all logs
func (m *MockLogger) Clear() {
m.mu.Lock()
defer m.mu.Unlock()
m.Logs = make([]LogEntry, 0)
}
// HasLog checks if contains specified message
func (m *MockLogger) HasLog(level, message string) bool {
m.mu.Lock()
defer m.mu.Unlock()
for _, log := range m.Logs {
if log.Level == level && log.Message == message {
return true
}
}
return false
}
// ============================================================
// Mock HTTP Client (implements http.RoundTripper)
// ============================================================
// MockHTTPClient Mock HTTP client (implements http.RoundTripper)
type MockHTTPClient struct {
mu sync.Mutex
// Configuration
Response string
StatusCode int
Error error
ResponseFunc func(req *http.Request) (*http.Response, error) // Custom response function
// Recording
Requests []*http.Request
}
func NewMockHTTPClient() *MockHTTPClient {
return &MockHTTPClient{
StatusCode: http.StatusOK,
Requests: make([]*http.Request, 0),
}
}
// ToHTTPClient converts to http.Client
func (m *MockHTTPClient) ToHTTPClient() *http.Client {
return &http.Client{
Transport: m,
}
}
// RoundTrip implements http.RoundTripper interface
func (m *MockHTTPClient) RoundTrip(req *http.Request) (*http.Response, error) {
m.mu.Lock()
defer m.mu.Unlock()
// Record request
m.Requests = append(m.Requests, req)
// If custom response function exists, use it
if m.ResponseFunc != nil {
return m.ResponseFunc(req)
}
// If error is set, return error
if m.Error != nil {
return nil, m.Error
}
// Return mock response
resp := &http.Response{
StatusCode: m.StatusCode,
Body: io.NopCloser(bytes.NewBufferString(m.Response)),
Header: make(http.Header),
}
return resp, nil
}
// GetRequests gets all requests
func (m *MockHTTPClient) GetRequests() []*http.Request {
m.mu.Lock()
defer m.mu.Unlock()
return append([]*http.Request{}, m.Requests...)
}
// GetLastRequest gets last request
func (m *MockHTTPClient) GetLastRequest() *http.Request {
m.mu.Lock()
defer m.mu.Unlock()
if len(m.Requests) == 0 {
return nil
}
return m.Requests[len(m.Requests)-1]
}
// Reset resets state
func (m *MockHTTPClient) Reset() {
m.mu.Lock()
defer m.mu.Unlock()
m.Requests = make([]*http.Request, 0)
}
// SetSuccessResponse sets success response
func (m *MockHTTPClient) SetSuccessResponse(content string) {
m.mu.Lock()
defer m.mu.Unlock()
m.StatusCode = http.StatusOK
m.Response = `{"choices":[{"message":{"content":"` + content + `"}}]}`
m.Error = nil
}
// SetErrorResponse sets error response
func (m *MockHTTPClient) SetErrorResponse(statusCode int, message string) {
m.mu.Lock()
defer m.mu.Unlock()
m.StatusCode = statusCode
m.Response = message
m.Error = nil
}
// SetNetworkError sets network error
func (m *MockHTTPClient) SetNetworkError(err error) {
m.mu.Lock()
defer m.mu.Unlock()
m.Error = err
}
// ============================================================
// Mock Client Hooks (for testing hook mechanism)
// ============================================================
// MockClientHooks Mock client hooks
type MockClientHooks struct {
BuildRequestBodyCalled int
BuildUrlCalled int
SetAuthHeaderCalled int
MarshalRequestCalled int
ParseResponseCalled int
IsRetryableErrorCalled int
// Custom return values
BuildUrlFunc func() string
ParseResponseFunc func([]byte) (string, error)
IsRetryableErrorFunc func(error) bool
BuildRequestBodyFunc func(string, string) map[string]any
MarshalRequestBodyFunc func(map[string]any) ([]byte, error)
}
func NewMockClientHooks() *MockClientHooks {
return &MockClientHooks{}
}
func (m *MockClientHooks) buildMCPRequestBody(systemPrompt, userPrompt string) map[string]any {
m.BuildRequestBodyCalled++
if m.BuildRequestBodyFunc != nil {
return m.BuildRequestBodyFunc(systemPrompt, userPrompt)
}
return map[string]any{
"model": "test-model",
"messages": []map[string]string{
{"role": "system", "content": systemPrompt},
{"role": "user", "content": userPrompt},
},
}
}
func (m *MockClientHooks) buildUrl() string {
m.BuildUrlCalled++
if m.BuildUrlFunc != nil {
return m.BuildUrlFunc()
}
return "https://api.test.com/chat/completions"
}
func (m *MockClientHooks) setAuthHeader(headers http.Header) {
m.SetAuthHeaderCalled++
headers.Set("Authorization", "Bearer test-key")
}
func (m *MockClientHooks) marshalRequestBody(body map[string]any) ([]byte, error) {
m.MarshalRequestCalled++
if m.MarshalRequestBodyFunc != nil {
return m.MarshalRequestBodyFunc(body)
}
return json.Marshal(body)
}
func (m *MockClientHooks) parseMCPResponse(body []byte) (string, error) {
m.ParseResponseCalled++
if m.ParseResponseFunc != nil {
return m.ParseResponseFunc(body)
}
return "mocked response", nil
}
func (m *MockClientHooks) isRetryableError(err error) bool {
m.IsRetryableErrorCalled++
if m.IsRetryableErrorFunc != nil {
return m.IsRetryableErrorFunc(err)
}
return false
}
func (m *MockClientHooks) buildRequest(url string, jsonData []byte) (*http.Request, error) {
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
m.setAuthHeader(req.Header)
return req, nil
}
func (m *MockClientHooks) call(systemPrompt, userPrompt string) (string, error) {
return "mocked call result", nil
}