/
util.ts
1673 lines (1410 loc) 路 50.3 KB
/
util.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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {replaceProjectIdToken} from '@google-cloud/projectify';
import * as assert from 'assert';
import * as extend from 'extend';
import {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';
import * as nock from 'nock';
import * as proxyquire from 'proxyquire';
import * as r from 'teeny-request';
import * as retryRequest from 'retry-request';
import * as sinon from 'sinon';
import * as stream from 'stream';
import {teenyRequest} from 'teeny-request';
import {
Abortable,
ApiError,
DecorateRequestOptions,
Duplexify,
DuplexifyConstructor,
GoogleErrorBody,
GoogleInnerError,
MakeAuthenticatedRequestFactoryConfig,
MakeRequestConfig,
ParsedHttpRespMessage,
Util,
} from '../src/util';
const duplexify: DuplexifyConstructor = require('duplexify');
nock.disableNetConnect();
const fakeResponse = {
statusCode: 200,
body: {star: 'trek'},
} as r.Response;
const fakeBadResp = {
statusCode: 400,
statusMessage: 'Not Good',
} as r.Response;
const fakeReqOpts: DecorateRequestOptions = {
uri: 'http://so-fake',
method: 'GET',
};
const fakeError = new Error('this error is like so fake');
// tslint:disable-next-line:no-any
let requestOverride: any;
function fakeRequest() {
return (requestOverride || teenyRequest).apply(null, arguments);
}
fakeRequest.defaults = () => {
// Ignore the default values, so we don't have to test for them in every API
// call.
return fakeRequest;
};
let retryRequestOverride: Function | null;
function fakeRetryRequest() {
return (retryRequestOverride || retryRequest).apply(null, arguments);
}
let replaceProjectIdTokenOverride: Function | null;
function fakeReplaceProjectIdToken() {
return (replaceProjectIdTokenOverride || replaceProjectIdToken).apply(
null,
arguments
);
}
describe('common/util', () => {
let util: Util & {[index: string]: Function};
// tslint:disable-next-line:no-any
function stub(method: keyof Util, meth: (...args: any[]) => void) {
return sandbox.stub(util, method).callsFake(meth);
}
function createExpectedErrorMessage(errors: string[]): string {
if (errors.length < 2) {
return errors[0];
}
errors = errors.map((error, i) => ` ${i + 1}. ${error}`);
errors.unshift(
'Multiple errors occurred during the request. Please see the `errors` array for complete details.\n'
);
errors.push('\n');
return errors.join('\n');
}
const fakeGoogleAuth = {
GoogleAuth: class {
constructor(config?: GoogleAuthOptions) {
return new GoogleAuth(config);
}
},
};
before(() => {
util = proxyquire('../src/util', {
'google-auth-library': fakeGoogleAuth,
'retry-request': fakeRetryRequest,
'teeny-request': {teenyRequest: fakeRequest},
'@google-cloud/projectify': {
replaceProjectIdToken: fakeReplaceProjectIdToken,
},
}).util;
});
let sandbox: sinon.SinonSandbox;
beforeEach(() => {
sandbox = sinon.createSandbox();
requestOverride = null;
retryRequestOverride = null;
replaceProjectIdTokenOverride = null;
});
afterEach(() => {
sandbox.restore();
});
describe('ApiError', () => {
it('should accept just a message', () => {
const expectedMessage = 'Hi, I am an error message!';
const apiError = new ApiError(expectedMessage);
assert.strictEqual(apiError.message, expectedMessage);
});
it('should use message in stack', () => {
const expectedMessage = 'Message is in the stack too!';
const apiError = new ApiError(expectedMessage);
assert.strictEqual(
(apiError.stack || '').split('\n')[0],
`Error: ${expectedMessage}`
);
});
it('should build correct ApiError', () => {
const fakeMessage = 'Formatted Error.';
const fakeResponse = {statusCode: 200} as r.Response;
const errors = [{message: 'Hi'}, {message: 'Bye'}];
const error = {
errors,
code: 100,
message: 'Uh oh',
response: fakeResponse,
};
sandbox
.stub(ApiError, 'createMultiErrorMessage')
.withArgs(error, errors)
.returns(fakeMessage);
const apiError = new ApiError(error);
assert.strictEqual(apiError.errors, error.errors);
assert.strictEqual(apiError.code, error.code);
assert.strictEqual(apiError.response, error.response);
assert.strictEqual(apiError.message, fakeMessage);
});
it('should parse the response body for errors', () => {
const fakeMessage = 'Formatted Error.';
const error = {message: 'Error.'};
const errors = [error, error];
const errorBody = {
code: 123,
response: {
body: JSON.stringify({
error: {
errors,
},
}),
} as r.Response,
};
sandbox
.stub(ApiError, 'createMultiErrorMessage')
.withArgs(errorBody, errors)
.returns(fakeMessage);
const apiError = new ApiError(errorBody);
assert.strictEqual(apiError.message, fakeMessage);
});
describe('createMultiErrorMessage', () => {
it('should append the custom error message', () => {
const errorMessage = 'API error message';
const customErrorMessage = 'Custom error message';
const errors = [new Error(errorMessage)];
const error = {
code: 100,
response: {} as r.Response,
message: customErrorMessage,
};
const expectedErrorMessage = createExpectedErrorMessage([
customErrorMessage,
errorMessage,
]);
const multiError = ApiError.createMultiErrorMessage(error, errors);
assert.strictEqual(multiError, expectedErrorMessage);
});
it('should use any inner errors', () => {
const messages = ['Hi, I am an error!', 'Me too!'];
const errors: GoogleInnerError[] = messages.map(message => ({message}));
const error: GoogleErrorBody = {
code: 100,
response: {} as r.Response,
};
const expectedErrorMessage = createExpectedErrorMessage(messages);
const multiError = ApiError.createMultiErrorMessage(error, errors);
assert.strictEqual(multiError, expectedErrorMessage);
});
it('should parse and append the decoded response body', () => {
const errorMessage = 'API error message';
const responseBodyMsg = 'Response body message <';
const error = {
message: errorMessage,
code: 100,
response: {
body: Buffer.from(responseBodyMsg),
} as r.Response,
};
const expectedErrorMessage = createExpectedErrorMessage([
'API error message',
'Response body message <',
]);
const multiError = ApiError.createMultiErrorMessage(error);
assert.strictEqual(multiError, expectedErrorMessage);
});
it('should use default message if there are no errors', () => {
const fakeResponse = {statusCode: 200} as r.Response;
const expectedErrorMessage = 'A failure occurred during this request.';
const error = {
code: 100,
response: fakeResponse,
};
const multiError = ApiError.createMultiErrorMessage(error);
assert.strictEqual(multiError, expectedErrorMessage);
});
it('should filter out duplicate errors', () => {
const expectedErrorMessage = 'Error during request.';
const error = {
code: 100,
message: expectedErrorMessage,
response: {
body: expectedErrorMessage,
} as r.Response,
};
const multiError = ApiError.createMultiErrorMessage(error);
assert.strictEqual(multiError, expectedErrorMessage);
});
});
});
describe('PartialFailureError', () => {
it('should build correct PartialFailureError', () => {
const fakeMessage = 'Formatted Error.';
const errors = [{}, {}];
const error = {
code: 123,
errors,
response: fakeResponse,
message: 'Partial failure occurred',
};
sandbox
.stub(util.ApiError, 'createMultiErrorMessage')
.withArgs(error, errors)
.returns(fakeMessage);
const partialFailureError = new util.PartialFailureError(error);
assert.strictEqual(partialFailureError.errors, error.errors);
assert.strictEqual(partialFailureError.name, 'PartialFailureError');
assert.strictEqual(partialFailureError.response, error.response);
assert.strictEqual(partialFailureError.message, fakeMessage);
});
});
describe('handleResp', () => {
it('should handle errors', done => {
const error = new Error('Error.');
util.handleResp(error, fakeResponse, null, err => {
assert.strictEqual(err, error);
done();
});
});
it('uses a no-op callback if none is sent', () => {
util.handleResp(null, fakeResponse, '');
});
it('should parse response', done => {
stub('parseHttpRespMessage', resp_ => {
assert.deepStrictEqual(resp_, fakeResponse);
return {
resp: fakeResponse,
};
});
stub('parseHttpRespBody', body_ => {
assert.strictEqual(body_, fakeResponse.body);
return {
body: fakeResponse.body,
};
});
util.handleResp(
fakeError,
fakeResponse,
fakeResponse.body,
(err, body, resp) => {
assert.deepStrictEqual(err, fakeError);
assert.deepStrictEqual(body, fakeResponse.body);
assert.deepStrictEqual(resp, fakeResponse);
done();
}
);
});
it('should parse response for error', done => {
const error = new Error('Error.');
sandbox.stub(util, 'parseHttpRespMessage').callsFake(() => {
return {err: error} as ParsedHttpRespMessage;
});
util.handleResp(null, fakeResponse, {}, err => {
assert.deepStrictEqual(err, error);
done();
});
});
it('should parse body for error', done => {
const error = new Error('Error.');
stub('parseHttpRespBody', () => {
return {err: error};
});
util.handleResp(null, fakeResponse, {}, err => {
assert.deepStrictEqual(err, error);
done();
});
});
it('should not parse undefined response', done => {
stub('parseHttpRespMessage', () => done()); // Will throw.
util.handleResp(null, null, null, done);
});
it('should not parse undefined body', done => {
stub('parseHttpRespBody', () => done()); // Will throw.
util.handleResp(null, null, null, done);
});
it('should surface the response body in the error message when it cannot be JSON-parsed', done => {
const unparseableBody = '<html>There was some error</html>';
util.handleResp(null, null, unparseableBody, err => {
if (err === null) {
assert.fail('there should be an error');
} else {
assert.ok(err.message.includes(unparseableBody));
}
done();
});
});
it('should surface the response body as an error property when it cannot be JSON-parsed', done => {
const unparseableBody = '<html>There was some error</html>';
util.handleResp(
null,
{body: unparseableBody} as r.Response,
unparseableBody,
err => {
if (err === null) {
assert.fail('there should be an error');
} else {
const response = (err! as ApiError).response;
if (!response) {
assert.fail('there should be a response property on the error');
} else {
assert.strictEqual(response.body, unparseableBody);
}
}
done();
}
);
});
});
describe('parseHttpRespMessage', () => {
it('should build ApiError with non-200 status and message', () => {
const res = util.parseHttpRespMessage(fakeBadResp);
const error_ = res.err!;
assert.strictEqual(error_.code, fakeBadResp.statusCode);
assert.strictEqual(error_.message, fakeBadResp.statusMessage);
assert.strictEqual(error_.response, fakeBadResp);
});
it('should return the original response message', () => {
const parsedHttpRespMessage = util.parseHttpRespMessage(fakeBadResp);
assert.strictEqual(parsedHttpRespMessage.resp, fakeBadResp);
});
});
describe('parseHttpRespBody', () => {
it('should detect body errors', () => {
const apiErr = {
errors: [{message: 'bar'}],
code: 400,
message: 'an error occurred',
};
const parsedHttpRespBody = util.parseHttpRespBody({error: apiErr});
const expectedErrorMessage = createExpectedErrorMessage([
apiErr.message,
apiErr.errors[0].message,
]);
const err = parsedHttpRespBody.err as ApiError;
assert.deepStrictEqual(err.errors, apiErr.errors);
assert.strictEqual(err.code, apiErr.code);
assert.deepStrictEqual(err.message, expectedErrorMessage);
});
it('should try to parse JSON if body is string', () => {
const httpRespBody = '{ "foo": "bar" }';
const parsedHttpRespBody = util.parseHttpRespBody(httpRespBody);
assert.strictEqual(parsedHttpRespBody.body.foo, 'bar');
});
it('should return the original body', () => {
const httpRespBody = {};
const parsedHttpRespBody = util.parseHttpRespBody(httpRespBody);
assert.strictEqual(parsedHttpRespBody.body, httpRespBody);
});
});
describe('makeWritableStream', () => {
it('should use defaults', done => {
const dup = duplexify();
// tslint:disable-next-line:no-any
const metadata = {a: 'b', c: 'd'} as any;
util.makeWritableStream(dup, {
metadata,
makeAuthenticatedRequest(request: DecorateRequestOptions) {
assert.strictEqual(request.method, 'POST');
assert.strictEqual(request.qs.uploadType, 'multipart');
assert.strictEqual(request.timeout, 0);
assert.strictEqual(request.maxRetries, 0);
assert.strictEqual(Array.isArray(request.multipart), true);
const mp = request.multipart as r.RequestPart[];
assert.strictEqual(
// tslint:disable-next-line:no-any
(mp[0] as any)['Content-Type'],
'application/json'
);
assert.strictEqual(mp[0].body, JSON.stringify(metadata));
assert.strictEqual(
// tslint:disable-next-line:no-any
(mp[1] as any)['Content-Type'],
'application/octet-stream'
);
// (is a writable stream:)
assert.strictEqual(
// tslint:disable-next-line no-any
typeof (mp[1].body as any)._writableState,
'object'
);
done();
},
});
});
it('should allow overriding defaults', done => {
const dup = duplexify();
const req = {
uri: 'http://foo',
method: 'PUT',
qs: {
uploadType: 'media',
},
} as DecorateRequestOptions;
util.makeWritableStream(dup, {
metadata: {
contentType: 'application/json',
},
makeAuthenticatedRequest(request) {
assert.strictEqual(request.method, req.method);
assert.deepStrictEqual(request.qs, req.qs);
assert.strictEqual(request.uri, req.uri);
// tslint:disable-next-line:no-any
const mp = request.multipart as any[];
assert.strictEqual(mp[1]['Content-Type'], 'application/json');
done();
},
request: req,
});
});
it('should emit an error', done => {
const error = new Error('Error.');
const ws = duplexify();
ws.on('error', err => {
assert.strictEqual(err, error);
done();
});
util.makeWritableStream(ws, {
makeAuthenticatedRequest(request, opts) {
opts!.onAuthenticated(error);
},
});
});
it('should set the writable stream', done => {
const dup = duplexify();
dup.setWritable = () => {
done();
};
util.makeWritableStream(dup, {makeAuthenticatedRequest() {}});
});
it('should emit an error if the request fails', done => {
const dup = duplexify();
const fakeStream = new stream.Writable();
const error = new Error('Error.');
fakeStream.write =
// tslint:disable-next-line:no-any
(chunk: any, encoding?: string | Function, cb?: Function) => false;
dup.end = () => {};
stub('handleResp', (err, res, body, callback) => {
callback(error);
});
requestOverride = (
reqOpts: DecorateRequestOptions,
callback: (err: Error) => void
) => {
callback(error);
};
requestOverride.defaults = (opts: DecorateRequestOptions) => {
return requestOverride;
};
dup.on('error', err => {
assert.strictEqual(err, error);
done();
});
util.makeWritableStream(dup, {
makeAuthenticatedRequest(request, opts) {
opts.onAuthenticated(null);
},
});
setImmediate(() => {
fakeStream.emit('complete', {});
});
});
it('should emit the response', done => {
const dup = duplexify();
const fakeStream = new stream.Writable();
// tslint:disable-next-line:no-any
(fakeStream as any).write = () => {};
stub('handleResp', (err, res, body, callback) => {
callback();
});
requestOverride = (
reqOpts: DecorateRequestOptions,
callback: (err: Error | null, res: r.Response) => void
) => {
callback(null, fakeResponse);
};
requestOverride.defaults = (opts: DecorateRequestOptions) =>
requestOverride;
const options = {
// tslint:disable-next-line:no-any
makeAuthenticatedRequest(request: DecorateRequestOptions, opts: any) {
opts.onAuthenticated();
},
};
dup.on('response', resp => {
assert.strictEqual(resp, fakeResponse);
done();
});
util.makeWritableStream(dup, options, util.noop);
});
it('should pass back the response data to the callback', done => {
const dup = duplexify();
// tslint:disable-next-line:no-any
const fakeStream: any = new stream.Writable();
const fakeResponse = {};
fakeStream.write = () => {};
stub('handleResp', (err, res, body, callback) => {
callback(null, fakeResponse);
});
requestOverride = (
reqOpts: DecorateRequestOptions,
callback: () => void
) => {
callback();
};
requestOverride.defaults = (opts: DecorateRequestOptions) => {
return requestOverride;
};
const options = {
// tslint:disable-next-line:no-any
makeAuthenticatedRequest(request: DecorateRequestOptions, opts: any) {
opts.onAuthenticated();
},
};
util.makeWritableStream(dup, options, (data: {}) => {
assert.strictEqual(data, fakeResponse);
done();
});
setImmediate(() => {
fakeStream.emit('complete', {});
});
});
});
describe('makeAuthenticatedRequestFactory', () => {
const authClient = {
getCredentials() {},
_cachedProjectId: 'project-id',
// tslint:disable-next-line:no-any
} as any;
it('should create an authClient', done => {
const config = {test: true} as MakeAuthenticatedRequestFactoryConfig;
sandbox
.stub(fakeGoogleAuth, 'GoogleAuth')
.callsFake((config_: GoogleAuthOptions) => {
assert.deepStrictEqual(config_, config);
setImmediate(done);
return authClient;
});
util.makeAuthenticatedRequestFactory(config);
});
it('should not pass projectId token to google-auth-library', done => {
const config = {projectId: '{{projectId}}'};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(config_ => {
assert.strictEqual(config_.projectId, undefined);
setImmediate(done);
return authClient;
});
util.makeAuthenticatedRequestFactory(config);
});
it('should not remove projectId from config object', done => {
const config = {projectId: '{{projectId}}'};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => {
assert.strictEqual(config.projectId, '{{projectId}}');
setImmediate(done);
return authClient;
});
util.makeAuthenticatedRequestFactory(config);
});
it('should return a function', () => {
assert.strictEqual(
typeof util.makeAuthenticatedRequestFactory({}),
'function'
);
});
it('should return a getCredentials method', done => {
function getCredentials() {
done();
}
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => {
return {getCredentials};
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory({});
makeAuthenticatedRequest.getCredentials(util.noop);
});
it('should return the authClient', () => {
const authClient = {getCredentials() {}};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
const mar = util.makeAuthenticatedRequestFactory({});
assert.strictEqual(mar.authClient, authClient);
});
describe('customEndpoint (no authentication attempted)', () => {
// tslint:disable-next-line:no-any
let makeAuthenticatedRequest: any;
const config = {customEndpoint: true};
const expectedProjectId = authClient.projectId;
beforeEach(() => {
makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(config);
});
it('should decorate the request', done => {
const decoratedRequest = {};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
stub('decorateRequest', reqOpts_ => {
assert.strictEqual(reqOpts_, fakeReqOpts);
return decoratedRequest;
});
makeAuthenticatedRequest(fakeReqOpts, {
onAuthenticated(
err: Error,
authenticatedReqOpts: DecorateRequestOptions
) {
assert.ifError(err);
assert.strictEqual(authenticatedReqOpts, decoratedRequest);
done();
},
});
});
it('should return an error while decorating', done => {
const error = new Error('Error.');
stub('decorateRequest', () => {
throw error;
});
makeAuthenticatedRequest(fakeReqOpts, {
onAuthenticated(err: Error) {
assert.strictEqual(err, error);
done();
},
});
});
it('should pass options back to callback', done => {
const reqOpts = {a: 'b', c: 'd'};
makeAuthenticatedRequest(reqOpts, {
onAuthenticated(
err: Error,
authenticatedReqOpts: DecorateRequestOptions
) {
assert.ifError(err);
assert.deepStrictEqual(reqOpts, authenticatedReqOpts);
done();
},
});
});
it('should not authenticate requests with a custom API', done => {
const reqOpts = {a: 'b', c: 'd'};
stub('makeRequest', rOpts => {
assert.deepStrictEqual(rOpts, reqOpts);
done();
});
makeAuthenticatedRequest(reqOpts, assert.ifError);
});
});
describe('needs authentication', () => {
it('should pass correct args to authorizeRequest', done => {
const fake = extend(true, authClient, {
authorizeRequest: async (rOpts: {}) => {
assert.deepStrictEqual(rOpts, fakeReqOpts);
done();
},
});
retryRequestOverride = () => {
return new stream.PassThrough();
};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(fake);
const mar = util.makeAuthenticatedRequestFactory({});
mar(fakeReqOpts);
});
it('should return a stream if callback is missing', () => {
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').callsFake(() => {
return extend(true, authClient, {
authorizeRequest: async (rOpts: {}) => {
return rOpts;
},
});
});
retryRequestOverride = () => {
return new stream.PassThrough();
};
const mar = util.makeAuthenticatedRequestFactory({});
const s = mar(fakeReqOpts);
assert(s instanceof stream.Stream);
});
describe('projectId', () => {
const reqOpts = {} as DecorateRequestOptions;
it('should default to authClient projectId', done => {
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
authClient._cachedProjectId = 'authclient-project-id';
stub('decorateRequest', (reqOpts, projectId) => {
assert.strictEqual(projectId, authClient._cachedProjectId);
setImmediate(done);
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
{customEndpoint: true}
);
makeAuthenticatedRequest(reqOpts, {
onAuthenticated: assert.ifError,
});
});
it('should use user-provided projectId', done => {
authClient.projectId = 'authclient-project-id';
const config = {customEndpoint: true, projectId: 'project-id'};
stub('decorateRequest', (reqOpts, projectId) => {
assert.strictEqual(projectId, config.projectId);
setImmediate(done);
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
config
);
makeAuthenticatedRequest(reqOpts, {
onAuthenticated: assert.ifError,
});
});
});
describe('authentication errors', () => {
const error = new Error('馃ぎ');
beforeEach(() => {
authClient.authorizeRequest = async (rOpts: {}) => {
throw error;
};
});
it('should attempt request anyway', done => {
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
{}
);
const correctReqOpts = {} as DecorateRequestOptions;
const incorrectReqOpts = {} as DecorateRequestOptions;
authClient.authorizeRequest = async (rOpts: {}) => {
throw new Error('Could not load the default credentials');
};
makeAuthenticatedRequest(correctReqOpts, {
onAuthenticated(err, reqOpts) {
assert.ifError(err);
assert.strictEqual(reqOpts, correctReqOpts);
assert.notStrictEqual(reqOpts, incorrectReqOpts);
done();
},
});
});
it('should block 401 API errors', done => {
const authClientError = new Error(
'Could not load the default credentials'
);
authClient.authorizeRequest = async () => {
throw authClientError;
};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
const makeRequestArg1 = new Error('API 401 Error.') as ApiError;
makeRequestArg1.code = 401;
const makeRequestArg2 = {};
const makeRequestArg3 = {};
stub('makeRequest', (authenticatedReqOpts, cfg, callback) => {
callback(makeRequestArg1, makeRequestArg2, makeRequestArg3);
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
{}
);
makeAuthenticatedRequest(
{} as DecorateRequestOptions,
(arg1, arg2, arg3) => {
assert.strictEqual(arg1, authClientError);
assert.strictEqual(arg2, makeRequestArg2);
assert.strictEqual(arg3, makeRequestArg3);
done();
}
);
});
it('should not block 401 errors if auth client succeeds', done => {
authClient.authorizeRequest = async (rOpts: {}) => {};
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
const makeRequestArg1 = new Error('API 401 Error.') as ApiError;
makeRequestArg1.code = 401;
const makeRequestArg2 = {};
const makeRequestArg3 = {};
stub('makeRequest', (authenticatedReqOpts, cfg, callback) => {
callback(makeRequestArg1, makeRequestArg2, makeRequestArg3);
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(
{}
);
makeAuthenticatedRequest(
{} as DecorateRequestOptions,
(arg1, arg2, arg3) => {
assert.strictEqual(arg1, makeRequestArg1);
assert.strictEqual(arg2, makeRequestArg2);
assert.strictEqual(arg3, makeRequestArg3);
done();
}
);
});
it('should block decorateRequest error', done => {
const decorateRequestError = new Error('Error.');
sandbox.stub(fakeGoogleAuth, 'GoogleAuth').returns(authClient);
stub('decorateRequest', () => {
throw decorateRequestError;
});
const makeAuthenticatedRequest = util.makeAuthenticatedRequestFactory(