-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc-client.test.ts
336 lines (291 loc) · 8.53 KB
/
rpc-client.test.ts
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import { jest } from "@jest/globals";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import { configureLogger, SystemError } from "../src/index.js";
configureLogger({ level: "silent" });
// Override the createJsonRpcRequest for testing to avoid type checking
function createTestRequest(
method: string,
params: any,
id: string | number = "test-" + Math.random().toString(36).substring(2, 9)
): any {
return {
jsonrpc: "2.0",
id,
method,
params,
};
}
// Define a simpler version of executeJsonRpcRequest for testing
async function executeJsonRpcRequestTest(
baseUrl: URL,
method: string,
params: any,
headers: Record<string, string> = {},
options: { timeout?: number } = {}
): Promise<any> {
const requestBody = createTestRequest(method, params);
const controller = new AbortController();
let timeoutId: NodeJS.Timeout | undefined;
if (options.timeout) {
timeoutId = setTimeout(() => controller.abort(), options.timeout);
}
try {
const response = await fetch(baseUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
...headers,
},
body: JSON.stringify(requestBody),
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const textResponse = await response.text();
return parseResponseTest(textResponse);
} catch (error) {
if (error instanceof DOMException && error.name === "AbortError") {
throw new Error("Request timeout");
}
throw error;
} finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
}
}
// Define a simpler version of parseResponse for testing
function parseResponseTest(data: string): any {
if (!data) {
throw new Error("Empty response");
}
const parsed = JSON.parse(data);
if (parsed.error) {
throw new SystemError(
parsed.error.message,
parsed.error.code,
parsed.error.data
);
}
if (
typeof parsed !== "object" ||
parsed === null ||
parsed.jsonrpc !== "2.0"
) {
throw new Error("Invalid response format");
}
if (parsed.result === undefined) {
throw new Error("Invalid response: missing result");
}
return parsed.result;
}
// Define the structure of our expected request body
interface TestJsonRpcRequest {
jsonrpc: string;
id: string | number;
method: string;
params?: Record<string, any>;
}
// Setup MSW server for mocking HTTP requests
const server = setupServer(
// Mock successful JSON-RPC request
http.post("https://example.com/api", async ({ request }) => {
const body = (await request.json()) as TestJsonRpcRequest;
if (typeof body === "object" && body !== null) {
if (body.method === "test/echo") {
return HttpResponse.json({
jsonrpc: "2.0",
id: body.id,
result: body.params,
});
}
if (body.method === "test/error") {
return HttpResponse.json({
jsonrpc: "2.0",
id: body.id,
error: {
code: -32603,
message: "Test error",
data: { detail: "This is a test error" },
},
});
}
return HttpResponse.json({
jsonrpc: "2.0",
id: body.id || "unknown",
error: {
code: -32601,
message: "Method not found",
},
});
}
// Return a generic error for invalid bodies
return HttpResponse.json({
jsonrpc: "2.0",
id: null,
error: {
code: -32700,
message: "Parse error",
},
});
}),
// Mock error response
http.post("https://example.com/api/error", () => {
return new HttpResponse(null, { status: 500 });
}),
// Mock timeout
http.post("https://example.com/api/timeout", () => {
return new Promise((resolve) => {
// Resolve after timeout to simulate network timeout
setTimeout(() => {
resolve(
HttpResponse.json({
jsonrpc: "2.0",
id: "timeout-request",
result: { message: "Too late" },
})
);
}, 2000);
});
})
);
describe("RPC Client", () => {
beforeAll(() => {
server.listen();
});
afterAll(() => {
server.close();
});
beforeEach(() => {
server.resetHandlers();
});
describe("createJsonRpcRequest", () => {
it("creates a valid JSON-RPC 2.0 request object", () => {
// Use our test function instead of the actual one
const request = createTestRequest("test/method", { param1: "value1" });
expect(request.jsonrpc).toBe("2.0");
expect(request.method).toBe("test/method");
expect(request.params).toEqual({ param1: "value1" });
expect(request.id).toBeDefined();
expect(typeof request.id).toBe("string");
});
it("preserves the provided ID if supplied", () => {
const customId = "custom-request-id";
// Use our test function instead of the actual one
const request = createTestRequest(
"test/method",
{ param1: "value1" },
customId
);
expect(request.id).toBe(customId);
});
});
describe("executeJsonRpcRequest", () => {
it("successfully executes a JSON-RPC request and returns the result", async () => {
const params = { message: "Hello, API!" };
const result = await executeJsonRpcRequestTest(
new URL("https://example.com/api"),
"test/echo",
params
);
expect(result).toEqual(params);
});
it("throws a SystemError on JSON-RPC error response", async () => {
await expect(
executeJsonRpcRequestTest(
new URL("https://example.com/api"),
"test/error",
{}
)
).rejects.toThrow(SystemError);
try {
await executeJsonRpcRequestTest(
new URL("https://example.com/api"),
"test/error",
{}
);
} catch (error) {
expect(error).toBeInstanceOf(SystemError);
expect((error as SystemError).code).toBe(-32603);
expect((error as SystemError).message).toBe("Test error");
expect((error as SystemError).data).toEqual({
detail: "This is a test error",
});
}
});
it("throws an error for non-existent methods", async () => {
await expect(
executeJsonRpcRequestTest(
new URL("https://example.com/api"),
"non/existent/method",
{}
)
).rejects.toThrow("Method not found");
});
it("throws an error for HTTP error responses", async () => {
await expect(
executeJsonRpcRequestTest(
new URL("https://example.com/api/error"),
"test/method",
{}
)
).rejects.toThrow();
});
it("times out for long-running requests", async () => {
// Set a short timeout for this test
await expect(
executeJsonRpcRequestTest(
new URL("https://example.com/api/timeout"),
"test/method",
{},
{},
{ timeout: 500 } // 500ms timeout
)
).rejects.toThrow(/timeout/i);
}, 2000); // Set a timeout for the test itself
});
describe("parseResponse", () => {
it("parses a valid JSON-RPC response", async () => {
const responseText = JSON.stringify({
jsonrpc: "2.0",
id: "test-id",
result: { success: true },
});
const parsedResult = parseResponseTest(responseText);
expect(parsedResult).toEqual({ success: true });
});
it("throws for invalid JSON responses", async () => {
const responseText = "This is not JSON";
expect(() => parseResponseTest(responseText)).toThrow();
});
it("throws for missing result and error fields", async () => {
const responseText = JSON.stringify({
jsonrpc: "2.0",
id: "test-id",
// Missing both result and error fields
});
expect(() => parseResponseTest(responseText)).toThrow("Invalid response");
});
it("throws for error responses", async () => {
const responseText = JSON.stringify({
jsonrpc: "2.0",
id: "test-id",
error: {
code: -32000,
message: "Error message",
},
});
expect(() => parseResponseTest(responseText)).toThrow(SystemError);
try {
parseResponseTest(responseText);
} catch (error) {
expect(error).toBeInstanceOf(SystemError);
expect((error as SystemError).code).toBe(-32000);
expect((error as SystemError).message).toBe("Error message");
}
});
});
});