-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathpublicApis.test.ts
More file actions
596 lines (567 loc) · 16.9 KB
/
publicApis.test.ts
File metadata and controls
596 lines (567 loc) · 16.9 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
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { AmplifyClassV6 } from '@aws-amplify/core';
import {
getRetryDecider,
parseJsonError,
} from '@aws-amplify/core/internals/aws-client-utils';
import { ApiError } from '@aws-amplify/core/internals/utils';
import { authenticatedHandler } from '../../../src/apis/common/baseHandlers/authenticatedHandler';
import { unauthenticatedHandler } from '../../../src/apis/common/baseHandlers/unauthenticatedHandler';
import {
del,
get,
head,
patch,
post,
put,
} from '../../../src/apis/common/publicApis';
import {
RestApiError,
RestApiValidationErrorCode,
isCancelError,
validationErrorMap,
} from '../../../src/errors';
import { RestApiResponse } from '../../../src/types';
jest.mock('@aws-amplify/core/internals/aws-client-utils');
jest.mock('../../../src/apis/common/baseHandlers/authenticatedHandler');
jest.mock('../../../src/apis/common/baseHandlers/unauthenticatedHandler');
const mockAuthenticatedHandler = authenticatedHandler as jest.Mock;
const mockUnauthenticatedHandler = unauthenticatedHandler as jest.Mock;
const mockFetchAuthSession = jest.fn();
const mockConfig = {
API: {
REST: {
restApi1: {
endpoint: 'https://123.execute-api.us-west-2.amazonaws.com/development',
region: 'us-west-2',
},
invalidEndpoint: {
endpoint: '123',
},
},
},
};
const mockParseJsonError = parseJsonError as jest.Mock;
const mockRestHeaders = jest.fn();
const mockGetConfig = jest.fn();
const mockAssertConfigured = jest.fn();
const mockAmplifyInstance = {
Auth: {
fetchAuthSession: mockFetchAuthSession,
},
getConfig: mockGetConfig,
assertConfigured: mockAssertConfigured,
libraryOptions: {
API: {
REST: {
headers: mockRestHeaders,
},
},
},
} as any as AmplifyClassV6;
const credentials = {
accessKeyId: 'accessKeyId',
sessionToken: 'sessionToken',
secretAccessKey: 'secretAccessKey',
};
const mockSuccessResponse = {
statusCode: 200,
headers: {
'response-header': 'response-header-value',
},
body: {
blob: jest.fn(),
json: jest.fn(),
text: jest.fn(),
},
};
const mockGetRetryDecider = jest.mocked(getRetryDecider);
const mockRetryDeciderResponse = () => Promise.resolve({ retryable: true });
describe('public APIs', () => {
beforeEach(() => {
jest.resetAllMocks();
mockFetchAuthSession.mockResolvedValue({
credentials,
});
mockSuccessResponse.body.json.mockResolvedValue({ foo: 'bar' });
mockAuthenticatedHandler.mockResolvedValue(mockSuccessResponse);
mockUnauthenticatedHandler.mockResolvedValue(mockSuccessResponse);
mockGetConfig.mockReturnValue(mockConfig);
mockGetRetryDecider.mockReturnValue(mockRetryDeciderResponse);
});
const APIs = [
{ name: 'get', fn: get, method: 'GET' },
{ name: 'post', fn: post, method: 'POST' },
{ name: 'put', fn: put, method: 'PUT' },
{ name: 'del', fn: del, method: 'DELETE' },
{ name: 'head', fn: head, method: 'HEAD' },
{ name: 'patch', fn: patch, method: 'PATCH' },
];
// TODO: use describe.each after upgrading Jest
APIs.forEach(({ name, fn, method }) => {
describe(name, () => {
it('should call authenticatedHandler with specified region from signingServiceInfo', async () => {
const response = await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
options: {
withCredentials: true,
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
{
url: new URL(
'https://123.execute-api.us-west-2.amazonaws.com/development/items',
),
method,
headers: {},
body: undefined,
},
expect.objectContaining({
region: 'us-west-2',
service: 'execute-api',
withCrossDomainCredentials: true,
}),
);
expect(response.headers).toEqual({
'response-header': 'response-header-value',
});
expect(response.statusCode).toBe(200);
if (fn !== head && fn !== del) {
expect(await (response as RestApiResponse).body.json()).toEqual({
foo: 'bar',
});
}
});
it('should support custom headers from library options', async () => {
mockRestHeaders.mockResolvedValue({
'custom-header': 'custom-value',
});
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
{
url: new URL(
'https://123.execute-api.us-west-2.amazonaws.com/development/items',
),
method,
headers: {
'custom-header': 'custom-value',
},
body: undefined,
},
expect.objectContaining({
region: 'us-west-2',
service: 'execute-api',
}),
);
});
it('should support headers options', async () => {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
options: {
headers: {
'custom-header': 'custom-value',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
{
url: new URL(
'https://123.execute-api.us-west-2.amazonaws.com/development/items',
),
method,
headers: {
'custom-header': 'custom-value',
},
body: undefined,
},
expect.objectContaining({
region: 'us-west-2',
service: 'execute-api',
}),
);
});
it('should support path parameters', async () => {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items/123',
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.objectContaining({
url: new URL(
'https://123.execute-api.us-west-2.amazonaws.com/development/items/123',
),
}),
expect.anything(),
);
});
it('should support queryParams options', async () => {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
options: {
queryParams: {
param1: 'value1',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.objectContaining({
url: expect.objectContaining({
href: 'https://123.execute-api.us-west-2.amazonaws.com/development/items?param1=value1',
}),
}),
expect.anything(),
);
});
it('should support query parameters in path', async () => {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items?param1=value1',
options: {
queryParams: {
foo: 'bar',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.objectContaining({
url: expect.objectContaining({
href: 'https://123.execute-api.us-west-2.amazonaws.com/development/items?param1=value1&foo=bar',
}),
}),
expect.anything(),
);
});
it('should throw if apiName is not configured', async () => {
expect.assertions(2);
try {
await fn(mockAmplifyInstance, {
apiName: 'nonExistentApi',
path: '/items',
}).response;
} catch (error) {
expect(error).toBeInstanceOf(RestApiError);
expect(error).toMatchObject(
validationErrorMap[RestApiValidationErrorCode.InvalidApiName],
);
}
});
it('should throw if resolve URL is not valid', async () => {
expect.assertions(2);
try {
await fn(mockAmplifyInstance, {
apiName: 'invalidEndpoint',
path: '/items',
}).response;
} catch (error) {
expect(error).toBeInstanceOf(RestApiError);
expect(error).toMatchObject({
...validationErrorMap[RestApiValidationErrorCode.InvalidApiName],
recoverySuggestion: expect.stringContaining(
'Please make sure the REST endpoint URL is a valid URL string.',
),
});
}
});
it('should use unauthenticated request if credentials are not available', async () => {
expect.assertions(1);
mockFetchAuthSession.mockResolvedValueOnce({});
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
}).response;
expect(mockUnauthenticatedHandler).toHaveBeenCalledWith(
expect.objectContaining({
url: new URL(
'https://123.execute-api.us-west-2.amazonaws.com/development/items/123',
),
}),
expect.anything(),
);
});
it('should throw when error response conforms to AWS service errors', async () => {
expect.assertions(4);
const errorResponseObj = { message: 'fooMessage', name: 'badRequest' };
const errorResponse = {
statusCode: 400,
headers: {},
body: {
blob: jest.fn(),
json: jest.fn(),
text: jest.fn().mockResolvedValue(JSON.stringify(errorResponseObj)),
},
};
mockParseJsonError.mockImplementationOnce(async response => {
const errorResponsePayload = await response.body?.json();
const error = new Error(errorResponsePayload.message);
return Object.assign(error, {
name: errorResponsePayload.name,
});
});
mockAuthenticatedHandler.mockResolvedValueOnce(errorResponse);
try {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
}).response;
fail('should throw RestApiError');
} catch (error) {
expect(mockParseJsonError).toHaveBeenCalledWith({
...errorResponse,
body: {
json: expect.any(Function),
blob: expect.any(Function),
text: expect.any(Function),
},
});
expect(error).toEqual(expect.any(RestApiError));
expect(error).toEqual(expect.any(ApiError));
expect((error as ApiError).response).toEqual({
statusCode: 400,
headers: {},
body: JSON.stringify(errorResponseObj),
});
}
});
it('should throw when error response has custom payload', async () => {
expect.assertions(4);
const errorResponseStr = 'custom error message';
const errorResponse = {
statusCode: 400,
headers: {},
body: {
blob: jest.fn(),
json: jest.fn(),
text: jest.fn().mockResolvedValue(errorResponseStr),
},
};
mockParseJsonError.mockImplementationOnce(async response => {
const errorResponsePayload = await response.body?.json();
const error = new Error(errorResponsePayload.message);
return Object.assign(error, {
name: errorResponsePayload.name,
});
});
mockAuthenticatedHandler.mockResolvedValueOnce(errorResponse);
try {
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
}).response;
fail('should throw RestApiError');
} catch (error) {
expect(mockParseJsonError).toHaveBeenCalledWith({
...errorResponse,
body: {
json: expect.any(Function),
blob: expect.any(Function),
text: expect.any(Function),
},
});
expect(error).toEqual(expect.any(RestApiError));
expect(error).toEqual(expect.any(ApiError));
expect((error as ApiError).response).toEqual({
statusCode: 400,
headers: {},
body: errorResponseStr,
});
}
});
it('should support cancel', async () => {
expect.assertions(2);
const abortSpy = jest.spyOn(AbortController.prototype, 'abort');
let underLyingHandlerReject;
mockAuthenticatedHandler.mockReset();
mockAuthenticatedHandler.mockReturnValue(
new Promise((_resolve, reject) => {
underLyingHandlerReject = reject;
}),
);
abortSpy.mockImplementation(() => {
const mockAbortError = new Error('AbortError');
mockAbortError.name = 'AbortError';
underLyingHandlerReject(mockAbortError);
});
const { response, cancel } = fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
});
const cancelMessage = 'cancelMessage';
try {
setTimeout(() => {
cancel(cancelMessage);
});
await response;
fail('should throw cancel error');
} catch (error: any) {
expect(isCancelError(error)).toBe(true);
expect(error.message).toBe(cancelMessage);
}
});
describe('retry strategy', () => {
beforeEach(() => {
mockAuthenticatedHandler.mockReset();
mockAuthenticatedHandler.mockResolvedValue(mockSuccessResponse);
});
it('should not retry when retry is set to "no-retry"', async () => {
expect.assertions(3);
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
options: {
retryStrategy: {
strategy: 'no-retry',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).not.toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: false });
});
it('should retry when retry is set to "jittered-exponential-backoff"', async () => {
expect.assertions(3);
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
options: {
retryStrategy: {
strategy: 'jittered-exponential-backoff',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: true });
});
it('should retry when retry strategy is not provided', async () => {
expect.assertions(3);
await fn(mockAmplifyInstance, {
apiName: 'restApi1',
path: '/items',
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: true });
});
it('should retry and prefer the individual retry strategy over the library options', async () => {
expect.assertions(3);
const mockAmplifyInstanceWithNoRetry = {
...mockAmplifyInstance,
libraryOptions: {
API: {
REST: {
retryStrategy: {
strategy: 'no-retry',
},
},
},
},
} as any as AmplifyClassV6;
await fn(mockAmplifyInstanceWithNoRetry, {
apiName: 'restApi1',
path: 'items',
options: {
retryStrategy: {
strategy: 'jittered-exponential-backoff',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: true });
});
it('should not retry and prefer the individual retry strategy over the library options', async () => {
expect.assertions(3);
const mockAmplifyInstanceWithRetry = {
...mockAmplifyInstance,
libraryOptions: {
API: {
REST: {
retryStrategy: {
strategy: 'jittered-exponential-backoff',
},
},
},
},
} as any as AmplifyClassV6;
await fn(mockAmplifyInstanceWithRetry, {
apiName: 'restApi1',
path: 'items',
options: {
retryStrategy: {
strategy: 'no-retry',
},
},
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).not.toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: false });
});
it('should not retry when configured through library options', async () => {
expect.assertions(3);
const mockAmplifyInstanceWithRetry = {
...mockAmplifyInstance,
libraryOptions: {
API: {
REST: {
retryStrategy: {
strategy: 'no-retry',
},
},
},
},
} as any as AmplifyClassV6;
await fn(mockAmplifyInstanceWithRetry, {
apiName: 'restApi1',
path: 'items',
}).response;
expect(mockAuthenticatedHandler).toHaveBeenCalledWith(
expect.any(Object),
expect.objectContaining({ retryDecider: expect.any(Function) }),
);
const callArgs = mockAuthenticatedHandler.mock.calls[0];
expect(mockGetRetryDecider).not.toHaveBeenCalled();
const { retryDecider } = callArgs[1];
const result = await retryDecider();
expect(result).toEqual({ retryable: false });
});
});
});
});
});