-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathrequire.ts
More file actions
215 lines (207 loc) · 6.54 KB
/
require.ts
File metadata and controls
215 lines (207 loc) · 6.54 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
/* eslint-disable @typescript-eslint/no-explicit-any */
// @ts-ignore
import Hook from "require-in-the-middle";
import mixin from "merge-descriptors";
import fetch, { Headers, Response, ResponseInit } from "node-fetch";
import { getExecutionContext} from "../../src/context";
import { Readable } from "stream";
import { ProcessDep, stringToBinary } from "../../src/util";
import { putMocks } from "../../mock/utils";
import { HTTP, V1_BETA2 } from "../../src/keploy";
import { getRequestHeader, getResponseHeader } from "../express/middleware";
import { getReasonPhrase } from "http-status-codes";
import { DataBytes } from "../../proto/services/DataBytes";
import { MockIds } from "../../mock/mock";
import { MODE_OFF, MODE_RECORD, MODE_TEST } from "../../src/mode";
// @ts-ignore
Hook(["octokit"], function (exported) {
const octokitDefault = exported;
octokitDefault.Octokit = octokitDefault.Octokit.defaults({
request: {
fetch: wrappedNodeFetch(fetch),
},
});
class WrappedOctokit extends octokitDefault.Octokit {
constructor(props: any) {
if (
props.request !== undefined &&
props.request.fetch !== undefined &&
typeof props.request.fetch === typeof wrappedNodeFetch
) {
super(props);
return;
}
const request = {
fetch: wrappedNodeFetch(
props.request === undefined || props.request.fetch === undefined
? fetch
: props.request.fetch
),
};
if (props.request !== undefined) {
mixin(request, props.request, false);
}
props.request = request;
super(props);
}
}
class WrappedApp extends octokitDefault.App {
constructor(props: any) {
if (props.Octokit !== undefined) {
props.Octokit = props.Octokit.defaults({
request: {
fetch: wrappedNodeFetch(fetch),
},
});
} else {
props.Octokit = octokitDefault.Octokit.defaults({
request: {
fetch: wrappedNodeFetch(fetch),
},
});
}
super(props);
}
}
const wrappedExports = {
Octokit: WrappedOctokit,
App: WrappedApp,
};
exported = mixin(wrappedExports, octokitDefault, false);
return exported;
});
function getHeadersInit(headers: { [k: string]: string[] }): {
[k: string]: string;
} {
const result: { [key: string]: string } = {};
for (const key in headers) {
result[key] = headers[key].join(", ");
}
return result;
}
// eslint-disable-next-line @typescript-eslint/ban-types
export function wrappedNodeFetch(fetchFunc: Function) {
// const fetchFunc = fetch;
async function wrappedFetch(
this: { fetch: (url: any, options: any) => any },
url: any,
options: any
) {
if (
getExecutionContext() == undefined ||
getExecutionContext().context == undefined
) {
console.error("keploy context is not present to mock dependencies");
return;
}
const ctx = getExecutionContext().context;
let resp = new Response();
let rinit: ResponseInit = {};
const meta = {
name: "node-fetch",
url: url,
options: options,
type: "HTTP_CLIENT",
};
switch (ctx.mode) {
case MODE_RECORD:
resp = await fetchFunc.apply(this, [url, options]);
const clonedResp = resp.clone();
rinit = {
headers: getHeadersInit(clonedResp.headers.raw()),
status: resp.status,
statusText: resp.statusText,
};
const respData: Buffer[] = [];
clonedResp?.body?.on("data", function (chunk: Buffer) {
respData.push(chunk);
});
clonedResp?.body?.on("end", async function () {
const httpMock = {
Version: V1_BETA2,
Name: ctx.testId,
Kind: HTTP,
Spec: {
Metadata: meta,
Req: {
URL: url,
Body: JSON.stringify(options?.body),
Header: getRequestHeader(options.headers),
Method: options.method,
// URLParams:
},
Res: {
StatusCode: rinit.status,
Header: getResponseHeader(rinit.headers),
Body: respData.toString(),
},
},
};
// record mocks for unit-test-mock-library
if (ctx.fileExport === true) {
MockIds[ctx.testId] !== true ? putMocks(httpMock) : "";
} else {
ctx.mocks.push(httpMock);
// ProcessDep(meta, [respData, rinit]);
const res: DataBytes[] = [];
// for (let i = 0; i < outputs.length; i++) {
res.push({ Bin: stringToBinary(JSON.stringify(respData)) });
res.push({ Bin: stringToBinary(JSON.stringify(rinit)) });
// }
ctx.deps.push({
Name: meta.name,
Type: meta.type,
Meta: meta,
Data: res,
});
}
});
break;
case MODE_TEST:
const outputs = new Array(2);
if (
ctx.mocks != undefined &&
ctx.mocks.length > 0 &&
ctx.mocks[0].Kind == HTTP
) {
const header: { [key: string]: string[] } = {};
for (const k in ctx.mocks[0].Spec?.Res?.Header) {
header[k] = ctx.mocks[0].Spec?.Res?.Header[k]?.Value;
}
outputs[1] = {
headers: getHeadersInit(header),
status: ctx.mocks[0].Spec.Res.StatusCode,
statusText: getReasonPhrase(ctx.mocks[0].Spec.Res.StatusCode),
};
outputs[0] = [ctx.mocks[0].Spec.Res.Body];
if (ctx?.fileExport) {
console.log(
"🤡 Returned the mocked outputs for Http dependency call with meta: ",
meta
);
}
ctx.mocks.shift();
} else {
ProcessDep({}, outputs);
}
rinit.headers = new Headers(outputs[1].headers);
rinit.status = outputs[1].status;
rinit.statusText = outputs[1].statusText;
const buf: Buffer[] = [];
outputs[0].map((el: any) => {
buf.push(Buffer.from(el));
});
resp = new Response(Readable.from(buf), rinit);
break;
case MODE_OFF:
return fetchFunc.apply(this, [url, options]);
default:
console.debug(
`keploy mode '${ctx.mode}' is invalid. Modes: 'record' / 'test' / 'off'(default)`
);
return fetchFunc.apply(this, [url, options]);
}
return resp;
}
return mixin(wrappedFetch, fetchFunc, false);
}