-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathrequest.test.ts
1166 lines (1076 loc) · 34.1 KB
/
request.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
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
import fs from "node:fs";
import stream from "node:stream";
import { ReadableStream } from "node:stream/web";
import { getUserAgent } from "universal-user-agent";
import fetchMock from "fetch-mock";
import { createAppAuth } from "@octokit/auth-app";
import lolex from "lolex";
import type {
EndpointOptions,
RequestInterface,
ResponseHeaders,
} from "@octokit/types";
import { request } from "../src/index.ts";
const userAgent = `octokit-request.js/0.0.0-development ${getUserAgent()}`;
const stringToArrayBuffer = require("string-to-arraybuffer");
describe("request()", () => {
it("Test ReDoS - attack string", () => {
const fakeFetch = async (url: string, options?: RequestInit) => {
const response = await fetch(url, options);
const fakeHeaders = new Headers(response.headers);
fakeHeaders.set("link", "<".repeat(100000) + ">");
fakeHeaders.set("deprecation", "true");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: fakeHeaders,
});
};
const startTime = performance.now();
request("GET /repos/octocat/hello-world", {
request: { fetch: fakeFetch },
});
const endTime = performance.now();
const elapsedTime = endTime - startTime;
const reDosThreshold = 2000;
expect(elapsedTime).toBeLessThanOrEqual(reDosThreshold);
if (elapsedTime > reDosThreshold) {
console.warn(
`🚨 Potential ReDoS Attack! getDuration method took ${elapsedTime.toFixed(2)} ms, exceeding threshold of ${reDosThreshold} ms.`,
);
}
});
it("is a function", () => {
expect(request).toBeInstanceOf(Function);
});
it("README example", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/orgs/octokit/repos?type=private", [], {
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /orgs/{org}/repos", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual([]);
});
});
it("README example alternative", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/orgs/octokit/repos?type=private", []);
return request({
method: "GET",
url: "/orgs/{org}/repos",
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
org: "octokit",
type: "private",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual([]);
});
});
it("README authentication example", async () => {
const clock = lolex.install({
now: 0,
toFake: ["Date"],
});
const APP_ID = 1;
const PRIVATE_KEY = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1c7+9z5Pad7OejecsQ0bu3aozN3tihPmljnnudb9G3HECdnH
lWu2/a1gB9JW5TBQ+AVpum9Okx7KfqkfBKL9mcHgSL0yWMdjMfNOqNtrQqKlN4kE
p6RD++7sGbzbfZ9arwrlD/HSDAWGdGGJTSOBM6pHehyLmSC3DJoR/CTu0vTGTWXQ
rO64Z8tyXQPtVPb/YXrcUhbBp8i72b9Xky0fD6PkEebOy0Ip58XVAn2UPNlNOSPS
ye+Qjtius0Md4Nie4+X8kwVI2Qjk3dSm0sw/720KJkdVDmrayeljtKBx6AtNQsSX
gzQbeMmiqFFkwrG1+zx6E7H7jqIQ9B6bvWKXGwIDAQABAoIBAD8kBBPL6PPhAqUB
K1r1/gycfDkUCQRP4DbZHt+458JlFHm8QL6VstKzkrp8mYDRhffY0WJnYJL98tr4
4tohsDbqFGwmw2mIaHjl24LuWXyyP4xpAGDpl9IcusjXBxLQLp2m4AKXbWpzb0OL
Ulrfc1ZooPck2uz7xlMIZOtLlOPjLz2DuejVe24JcwwHzrQWKOfA11R/9e50DVse
hnSH/w46Q763y4I0E3BIoUMsolEKzh2ydAAyzkgabGQBUuamZotNfvJoDXeCi1LD
8yNCWyTlYpJZJDDXooBU5EAsCvhN1sSRoaXWrlMSDB7r/E+aQyKua4KONqvmoJuC
21vSKeECgYEA7yW6wBkVoNhgXnk8XSZv3W+Q0xtdVpidJeNGBWnczlZrummt4xw3
xs6zV+rGUDy59yDkKwBKjMMa42Mni7T9Fx8+EKUuhVK3PVQyajoyQqFwT1GORJNz
c/eYQ6VYOCSC8OyZmsBM2p+0D4FF2/abwSPMmy0NgyFLCUFVc3OECpkCgYEA5OAm
I3wt5s+clg18qS7BKR2DuOFWrzNVcHYXhjx8vOSWV033Oy3yvdUBAhu9A1LUqpwy
Ma+unIgxmvmUMQEdyHQMcgBsVs10dR/g2xGjMLcwj6kn+xr3JVIZnbRT50YuPhf+
ns1ScdhP6upo9I0/sRsIuN96Gb65JJx94gQ4k9MCgYBO5V6gA2aMQvZAFLUicgzT
u/vGea+oYv7tQfaW0J8E/6PYwwaX93Y7Q3QNXCoCzJX5fsNnoFf36mIThGHGiHY6
y5bZPPWFDI3hUMa1Hu/35XS85kYOP6sGJjf4kTLyirEcNKJUWH7CXY+00cwvTkOC
S4Iz64Aas8AilIhRZ1m3eQKBgQCUW1s9azQRxgeZGFrzC3R340LL530aCeta/6FW
CQVOJ9nv84DLYohTVqvVowdNDTb+9Epw/JDxtDJ7Y0YU0cVtdxPOHcocJgdUGHrX
ZcJjRIt8w8g/s4X6MhKasBYm9s3owALzCuJjGzUKcDHiO2DKu1xXAb0SzRcTzUCn
7daCswKBgQDOYPZ2JGmhibqKjjLFm0qzpcQ6RPvPK1/7g0NInmjPMebP0K6eSPx0
9/49J6WTD++EajN7FhktUSYxukdWaCocAQJTDNYP0K88G4rtC2IYy5JFn9SWz5oh
x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
-----END RSA PRIVATE KEY-----`;
// see https://runkit.com/gr2m/reproducable-jwt
const BEARER =
"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOi0zMCwiZXhwIjo1NzAsImlzcyI6MX0.q3foRa78U3WegM5PrWLEh5N0bH1SD62OqW66ZYzArp95JBNiCbo8KAlGtiRENCIfBZT9ibDUWy82cI4g3F09mdTq3bD1xLavIfmTksIQCz5EymTWR5v6gL14LSmQdWY9lSqkgUG0XCFljWUglEP39H4yeHbFgdjvAYg3ifDS12z9oQz2ACdSpvxPiTuCC804HkPVw8Qoy0OSXvCkFU70l7VXCVUxnuhHnk8-oCGcKUspmeP6UdDnXk-Aus-eGwDfJbU2WritxxaXw6B4a3flTPojkYLSkPBr6Pi0H2-mBsW_Nvs0aLPVLKobQd4gqTkosX3967DoAG8luUMhrnxe8Q";
const mock = fetchMock
.sandbox()
.postOnce("https://api.github.com/app/installations/123/access_tokens", {
token: "secret123",
expires_at: "1970-01-01T01:00:00.000Z",
permissions: {
metadata: "read",
},
repository_selection: "all",
})
.getOnce(
"https://api.github.com/app",
{ id: 123 },
{
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent,
authorization: `bearer ${BEARER}`,
},
},
)
.postOnce(
"https://api.github.com/repos/octocat/hello-world/issues",
{ id: 456 },
{
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent,
authorization: `token secret123`,
},
},
);
const auth = createAppAuth({
appId: APP_ID,
privateKey: PRIVATE_KEY,
installationId: 123,
});
const requestWithAuth = request.defaults({
request: {
fetch: mock,
hook: auth.hook,
},
});
await requestWithAuth("GET /app");
await requestWithAuth("POST /repos/{owner}/{repo}/issues", {
owner: "octocat",
repo: "hello-world",
title: "Hello from the engine room",
});
expect(mock.done()).toBe(true);
clock.reset();
});
it("Request with body", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/repos/octocat/hello-world/issues", 201, {
headers: {
"content-type": "application/json; charset=utf-8",
},
});
request("POST /repos/{owner}/{repo}/issues", {
owner: "octocat",
repo: "hello-world",
headers: {
accept: "text/html;charset=utf-8",
},
title: "Found a bug",
body: "I'm having a problem with this.",
assignees: ["octocat"],
milestone: 1,
labels: ["bug"],
request: {
fetch: mock,
},
}).then((response) => {
expect(response.status).toEqual(201);
});
});
it("Put without request body", () => {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/user/starred/octocat/hello-world", 204, {
body: undefined,
});
request("PUT /user/starred/{owner}/{repo}", {
headers: {
authorization: `token 0000000000000000000000000000000000000001`,
},
owner: "octocat",
repo: "hello-world",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.status).toEqual(204);
});
});
it("HEAD requests (octokit/rest.js#841)", () => {
const mock = fetchMock
.sandbox()
.head("https://api.github.com/repos/whatwg/html/pulls/1", {
status: 200,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": "19137",
},
})
.head("https://api.github.com/repos/whatwg/html/pulls/2", {
status: 404,
headers: {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": "120",
},
});
const options = {
owner: "whatwg",
repo: "html",
number: 1,
request: {
fetch: mock,
},
};
request(`HEAD /repos/{owner}/{repo}/pulls/{number}`, options)
.then((response) => {
expect(response.status).toEqual(200);
return request(
`HEAD /repos/{owner}/{repo}/pulls/{number}`,
Object.assign(options, { number: 2 }),
);
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(404);
});
});
it.skip("Binary response with redirect (🤔 unclear how to mock fetch redirect properly)", () => {
const mock = fetchMock
.sandbox()
.get(
"https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
status: 200,
body: Buffer.from(
"1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000",
"hex",
),
headers: {
"content-type": "application/x-gzip",
"content-length": "172",
},
},
);
return request("GET /repos/{owner}/{repo}/{archive_format}/{ref}", {
owner: "octokit-fixture-org",
repo: "get-archive",
archive_format: "tarball",
ref: "master",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data.length).toEqual(172);
});
});
// TODO: fails with "response.buffer is not a function" in browser
it("Binary response", () => {
const mock = fetchMock
.sandbox()
.get(
"https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
status: 200,
// expect(response.data.length).toEqual(172)
// body: Buffer.from('1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000', 'hex'),
body: Buffer.from(
"1f8b0800000000000003cb4f2ec9cfce2cd14dcbac28292d4ad5cd2f4ad74d4f2dd14d2c4acec82c4bd53580007d060a0050bfb9b9a90203c428741ac2313436343307222320dbc010a8dc5c81c194124b8905a5c525894540a714e5e797e05347481edd734304e41319ff41ae8e2ebeae7ab92964d801d46f66668227fe0d4d51e3dfc8d0c8d808284f75df6201233cfe951590627ba01d330a46c1281805a3806e000024cb59d6000a0000",
"hex",
),
headers: {
"content-type": "application/x-gzip",
"content-length": "172",
},
},
);
return request(
"GET https://codeload.github.com/octokit-fixture-org/get-archive/legacy.tar.gz/master",
{
request: {
fetch: mock,
},
},
);
});
it("304 etag", () => {
const mock = fetchMock.sandbox().get((url, { headers }) => {
return (
url === "https://api.github.com/orgs/myorg" &&
(headers as ResponseHeaders)["if-none-match"] === "etag"
);
}, 304);
return request("GET /orgs/{org}", {
org: "myorg",
headers: { "If-None-Match": "etag" },
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(304);
});
});
it("304 last-modified", () => {
const mock = fetchMock.sandbox().get((url, { headers }) => {
return (
url === "https://api.github.com/orgs/myorg" &&
(headers as ResponseHeaders)["if-modified-since"] ===
"Sun Dec 24 2017 22:00:00 GMT-0600 (CST)"
);
}, 304);
return request("GET /orgs/{org}", {
org: "myorg",
headers: {
"If-Modified-Since": "Sun Dec 24 2017 22:00:00 GMT-0600 (CST)",
},
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(304);
});
});
it("Not found", () => {
const mock = fetchMock.sandbox().get("path:/orgs/nope", 404);
return request("GET /orgs/{org}", {
org: "nope",
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(404);
expect(error.request.method).toEqual("GET");
expect(error.request.url).toEqual("https://api.github.com/orgs/nope");
});
});
it("should error when globalThis.fetch is undefined", async () => {
const originalFetch = globalThis.fetch;
// @ts-expect-error force undefined to mimic older node version
globalThis.fetch = undefined;
let error: Error | undefined;
try {
await request("GET /orgs/me");
} catch (e) {
error = e as Error;
}
globalThis.fetch = originalFetch;
expect(error?.message).toEqual(
"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing",
);
});
it("error response with no body (octokit/request.js#649)", () => {
const mock = fetchMock
.sandbox()
.get("path:/repos/octokit-fixture-org/hello-world/contents/README.md", {
status: 500,
body: "",
headers: {
"content-type": "application/json",
},
});
expect(request).not.toThrow();
return request("GET /repos/{owner}/{repo}/contents/{path}", {
headers: {
accept: "content-type: application/json",
},
owner: "octokit-fixture-org",
repo: "hello-world",
path: "README.md",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.response.data).toEqual("");
});
});
it("non-JSON response", () => {
const mock = fetchMock
.sandbox()
.get("path:/repos/octokit-fixture-org/hello-world/contents/README.md", {
status: 200,
body: "# hello-world",
headers: {
"content-length": "13",
"content-type": "application/vnd.github.v3.raw; charset=utf-8",
},
});
return request("GET /repos/{owner}/{repo}/contents/{path}", {
headers: {
accept: "application/vnd.github.v3.raw",
},
owner: "octokit-fixture-org",
repo: "hello-world",
path: "README.md",
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("# hello-world");
});
});
it("Request error", () => {
// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
return request("GET https://127.0.0.1:8/")
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(500);
});
});
it("Request TypeError error with an Error cause", () => {
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
throws: Object.assign(new TypeError("fetch failed"), {
cause: new Error("bad"),
}),
});
// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
return request("GET https://127.0.0.1:8/", {
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(500);
expect(error.message).toEqual("bad");
});
});
it("Request TypeError error with a string cause", () => {
const mock = fetchMock.sandbox().get("https://127.0.0.1:8/", {
throws: Object.assign(new TypeError("fetch failed"), { cause: "bad" }),
});
// port: 8 // officially unassigned port. See https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers
return request("GET https://127.0.0.1:8/", {
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.status).toEqual(500);
expect(error.message).toEqual("bad");
});
});
it("custom user-agent", () => {
const mock = fetchMock
.sandbox()
.get(
(_url, { headers }) =>
(headers as ResponseHeaders)["user-agent"] === "funky boom boom pow",
200,
);
return request("GET /", {
headers: {
"user-agent": "funky boom boom pow",
},
request: {
fetch: mock,
},
});
});
it("422 error with details", () => {
const mock = fetchMock
.sandbox()
.post("https://api.github.com/repos/octocat/hello-world/labels", {
status: 422,
headers: {
"Content-Type": "application/json; charset=utf-8",
"X-Foo": "bar",
},
body: {
message: "Validation Failed",
errors: [
{
resource: "Label",
code: "invalid",
field: "color",
},
],
documentation_url:
"https://developer.github.com/v3/issues/labels/#create-a-label",
},
});
return request("POST /repos/octocat/hello-world/labels", {
name: "foo",
color: "invalid",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.status).toEqual(422);
expect(error.response.headers["x-foo"]).toEqual("bar");
expect(error.response.data.documentation_url).toEqual(
"https://developer.github.com/v3/issues/labels/#create-a-label",
);
expect(error.response.data.errors).toEqual([
{ resource: "Label", code: "invalid", field: "color" },
]);
});
});
it("redacts credentials from error.request.headers.authorization", () => {
const mock = fetchMock.sandbox().get("https://api.github.com/", {
status: 500,
});
return request("/", {
headers: {
authorization: "token secret123",
},
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.request.headers.authorization).toEqual("token [REDACTED]");
});
});
it("redacts credentials from error.request.url", () => {
const mock = fetchMock
.sandbox()
.get("https://api.github.com/?client_id=123&client_secret=secret123", {
status: 500,
});
return request("/", {
client_id: "123",
client_secret: "secret123",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.request.url).toEqual(
"https://api.github.com/?client_id=123&client_secret=[REDACTED]",
);
});
});
it("Just URL", () => {
const mock = fetchMock.sandbox().get("path:/", 200);
return request("/", {
request: {
fetch: mock,
},
}).then(({ status }) => {
expect(status).toEqual(200);
});
});
it("Resolves with url", function () {
// this test cannot be mocked with `fetch-mock`. I don’t like to rely on
// external websites to run tests, but in this case I’ll make an exception.
// The alternative would be to start a local server we then send a request to,
// this would only work in Node, so we would need to adapt the test setup, too.
// We also can’t test the GitHub API, because on Travis unauthenticated
// GitHub API requests are usually blocked due to IP rate limiting
return request("https://www.githubstatus.com/api/v2/status.json").then(
({ url }) => {
expect(url).toEqual("https://www.githubstatus.com/api/v2/status.json");
},
);
});
it("options.request.fetch", function () {
return request("/", {
request: {
fetch: () =>
Promise.resolve({
status: 200,
headers: new Headers({
"Content-Type": "application/json; charset=utf-8",
}),
url: "http://api.github.com/",
json() {
return Promise.resolve("funk");
},
}),
},
}).then((result) => {
expect(result.data).toEqual("funk");
});
});
it("options.request.hook", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/foo",
{ ok: true },
{
headers: {
"x-foo": "bar",
},
},
);
const hook = (request: RequestInterface, options: EndpointOptions) => {
expect(request.endpoint).toBeInstanceOf(Function);
expect(request.defaults).toBeInstanceOf(Function);
expect(options).toEqual({
baseUrl: "https://api.github.com",
headers: {
accept: "application/vnd.github.v3+json",
"user-agent": userAgent,
},
mediaType: {
format: "",
},
method: "GET",
request: {
fetch: mock,
hook: hook,
},
url: "/",
});
return request("/foo", {
headers: {
"x-foo": "bar",
},
request: {
fetch: mock,
},
});
};
return request("/", {
request: {
fetch: mock,
hook,
},
}).then((result) => {
expect(result.data).toEqual({ ok: true });
});
});
it("options.mediaType.format", function () {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/repos/octokit/request.js/issues/1", "ok", {
headers: {
accept: "application/vnd.github.v3.raw+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /repos/{owner}/{repo}/issues/{number}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
mediaType: {
format: "raw+json",
},
owner: "octokit",
repo: "request.js",
number: 1,
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("ok");
});
});
it("options.mediaType.previews", function () {
const mock = fetchMock
.sandbox()
.mock("https://api.github.com/graphql", "ok", {
headers: {
accept:
"application/vnd.github.foo-preview+json,application/vnd.github.bar-preview+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
});
return request("GET /graphql", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
mediaType: {
previews: ["foo", "bar"],
},
request: {
fetch: mock,
},
}).then((response) => {
expect(response.data).toEqual("ok");
});
});
it("octokit/octokit.js#1497", function () {
const mock = fetchMock.sandbox().mock(
"https://request-errors-test.com/repos/gr2m/sandbox/branches/gr2m-patch-1/protection",
{
status: 400,
body: {
message: "Validation failed",
errors: [
"Only organization repositories can have users and team restrictions",
{ resource: "Search", field: "q", code: "invalid" },
],
documentation_url:
"https://developer.github.com/v3/repos/branches/#update-branch-protection",
},
},
{
method: "PUT",
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token secret123",
},
},
);
return request("PUT /repos/{owner}/{repo}/branches/{branch}/protection", {
baseUrl: "https://request-errors-test.com",
headers: {
authorization: "token secret123",
},
owner: "gr2m",
repo: "sandbox",
branch: "gr2m-patch-1",
required_status_checks: { strict: true, contexts: ["wip"] },
enforce_admins: true,
required_pull_request_reviews: {
required_approving_review_count: 1,
dismiss_stale_reviews: true,
require_code_owner_reviews: true,
dismissal_restrictions: { users: [], teams: [] },
},
restrictions: { users: [], teams: [] },
request: {
fetch: mock,
},
})
.then(() => {
fail("This should return error.");
})
.catch((error) => {
expect(error).toHaveProperty(
"message",
`Validation failed: "Only organization repositories can have users and team restrictions", {"resource":"Search","field":"q","code":"invalid"} - https://developer.github.com/v3/repos/branches/#update-branch-protection`,
);
});
});
it("logs deprecation warning if `deprecation` header is present", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/teams/123",
{
body: {
id: 123,
},
headers: {
deprecation: "Sat, 01 Feb 2020 00:00:00 GMT",
sunset: "Mon, 01 Feb 2021 00:00:00 GMT",
link: '<https://developer.github.com/changes/2020-01-21-moving-the-team-api-endpoints/>; rel="deprecation"; type="text/html", <https://api.github.com/organizations/3430433/team/4177875>; rel="alternate"',
},
},
{
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
},
);
const warn = jest.fn();
return request("GET /teams/{team_id}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
team_id: 123,
request: { fetch: mock, log: { warn } },
}).then((response) => {
expect(response.data).toEqual({ id: 123 });
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
'[@octokit/request] "GET https://api.github.com/teams/123" is deprecated. It is scheduled to be removed on Mon, 01 Feb 2021 00:00:00 GMT. See https://developer.github.com/changes/2020-01-21-moving-the-team-api-endpoints/',
);
});
});
it("deprecation header without deprecation link", function () {
const mock = fetchMock.sandbox().mock(
"https://api.github.com/teams/123",
{
body: {
id: 123,
},
headers: {
deprecation: "Sat, 01 Feb 2020 00:00:00 GMT",
sunset: "Mon, 01 Feb 2021 00:00:00 GMT",
},
},
{
headers: {
accept: "application/vnd.github.v3+json",
authorization: "token 0000000000000000000000000000000000000001",
"user-agent": userAgent,
},
},
);
const warn = jest.fn();
return request("GET /teams/{team_id}", {
headers: {
authorization: "token 0000000000000000000000000000000000000001",
},
team_id: 123,
request: { fetch: mock, log: { warn } },
}).then((response) => {
expect(response.data).toEqual({ id: 123 });
expect(warn).toHaveBeenCalledTimes(1);
expect(warn).toHaveBeenCalledWith(
'[@octokit/request] "GET https://api.github.com/teams/123" is deprecated. It is scheduled to be removed on Mon, 01 Feb 2021 00:00:00 GMT',
);
});
});
it("404 not found", () => {
const mock = fetchMock
.sandbox()
.get("https://api.github.com/repos/octocat/unknown", {
status: 404,
headers: {},
body: {
message: "Not Found",
documentation_url:
"https://docs.github.com/en/rest/reference/repos#get-a-repository",
},
});
return request("GET /repos/octocat/unknown", {
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.status).toEqual(404);
expect(error.response.data.message).toEqual("Not Found");
expect(error.response.data.documentation_url).toEqual(
"https://docs.github.com/en/rest/reference/repos#get-a-repository",
);
});
});
it("Request timeout", () => {
const delay = (millis = 3000) => {
return new Promise((resolve) => {
setTimeout(resolve, millis);
});
};
const mock = (url: string) => {
expect(url).toEqual("https://api.github.com/");
return delay().then(() => {
return {
status: 200,
headers: {},
body: {
message: "OK",
},
};
});
};
return request("GET /", {
request: {
fetch: mock,
},
})
.then(() => {
throw new Error("should not resolve");
})
.catch((error) => {
expect(error.name).toEqual("HttpError");
expect(error.status).toEqual(500);
});
});
it("validate request with readstream data", () => {
const size = fs.statSync(__filename).size;
const mock = fetchMock
.sandbox()
.post(
"https://api.github.com/repos/octokit-fixture-org/release-assets/releases/v1.0.0/assets",
{
status: 200,
},
);
return request("POST /repos/{owner}/{repo}/releases/{release_id}/assets", {
owner: "octokit-fixture-org",
repo: "release-assets",
release_id: "v1.0.0",
request: {
fetch: mock,
},
headers: {
"content-type": "text/json",