/
index.ts
288 lines (254 loc) · 9.06 KB
/
index.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
import type { SlsAwsLambdaPlugin } from "serverless-aws-lambda/defineConfig";
import { accessSync, mkdirSync, writeFileSync } from "fs";
import path from "path";
import { calculateCoverage, handleInvoke } from "./utils";
import { generateBadge } from "./badge";
import { TestRequestListener } from "./requestListener";
import type { supportedService } from "./requestListener";
// @ts-ignore
import { actualDirName, jest, readInitialOptions } from "resolvedPaths";
const cwd = process.cwd();
const setupFile = `${actualDirName.slice(0, -5)}/resources/setup.js`;
const coverage: any = {};
interface IJestPluginOptions {
configFile: string;
oneshot?: boolean | { delay: number };
coverage?: {
outDir: string;
json?: boolean;
badge?: boolean;
threshold?: number;
};
}
const jestPlugin = (options: IJestPluginOptions): SlsAwsLambdaPlugin => {
const eventListener = new TestRequestListener();
let outdir = `${cwd}/.aws_lambda/`;
const getOutDir = {
name: "jest-get-outdir",
setup: async (build) => {
if (build.initialOptions.outdir) {
outdir = path.resolve(build.initialOptions.outdir);
}
},
};
return {
name: "jest-plugin",
onInit: function () {
if (Array.isArray(this.config.esbuild.plugins)) {
this.config.esbuild.plugins.push(getOutDir);
} else {
this.config.esbuild.plugins = [getOutDir];
}
this.lambdas.forEach((l) => {
const lambdaConverage = {
done: false,
coverage: 0,
alb: [],
apg: [],
s3: [],
sns: [],
sqs: [],
ddb: [],
};
l.endpoints.forEach((e) => {
let c: any = {
paths: e.paths,
methods: {},
};
e.methods.forEach((m) => {
c.methods[m] = false;
});
lambdaConverage[e.kind].push(c);
});
l.sns.forEach((sns) => {
lambdaConverage.sns.push({
done: false,
event: sns,
});
});
l.sqs.forEach((sqs) => {
lambdaConverage.sqs.push({
done: false,
event: sqs,
});
});
l.ddb.forEach((ddb) => {
lambdaConverage.ddb.push({
done: false,
event: ddb,
});
});
l.s3.forEach((s3) => {
lambdaConverage.s3.push({
done: false,
event: s3,
});
});
coverage[l.name] = lambdaConverage;
l.onInvoke((event, info) => {
if (!event || !info) {
return;
}
handleInvoke(coverage[l.name], event, info);
});
l.onInvokeSuccess((input, output, info) => {
if (input && typeof input == "object" && info) {
const kind: supportedService = info.kind;
if (eventListener.support.has(kind)) {
eventListener.handleInvokeResponse(kind, l.name, input, output, true);
}
}
});
l.onInvokeError((input, error, info) => {
if (input && typeof input == "object" && info) {
const kind: supportedService = info.kind;
if (eventListener.support.has(kind)) {
eventListener.handleInvokeResponse(kind, l.name, input, error, false);
}
}
});
});
},
onExit: function (code) {
if (options.coverage) {
if (options.coverage.outDir) {
const threshold = options.coverage.threshold;
const coverageResult = calculateCoverage(coverage);
if (threshold && code == 0 && coverageResult.coverage < threshold) {
process.exitCode = 1;
console.log(`Covered events: ${coverageResult.coverage}%\nThreshold: ${threshold}%`);
}
const outdir = path.resolve(options.coverage.outDir);
try {
accessSync(outdir);
} catch (error) {
mkdirSync(outdir, { recursive: true });
}
if (options.coverage.json) {
writeFileSync(`${outdir}/jest-it-coverage.json`, JSON.stringify(coverageResult, null, 2), { encoding: "utf-8" });
}
if (options.coverage.badge) {
writeFileSync(`${outdir}/jest-it-coverage.svg`, generateBadge(coverageResult.coverage), { encoding: "utf-8" });
}
} else {
console.log("coverage 'outDir' is required");
}
}
},
offline: {
request: [
{
filter: "/__jest_plugin/",
callback: async function (req, res) {
const { searchParams } = new URL(req.url, "http://localhost:3000");
const kind = searchParams.get("kind") as supportedService;
const id = searchParams.get("id");
const lambdaName = searchParams.get("lambdaName");
const listener = (success: boolean, output: any, foundLambdaName: string) => {
if (!success) {
res.statusCode = 400;
}
if (!lambdaName || lambdaName == foundLambdaName) {
eventListener.removeListener(id, listener);
res.end(output ? JSON.stringify(output) : undefined);
}
};
eventListener.on(id, listener);
const foundEvent = eventListener.getPendingRequest(kind, id, lambdaName);
if (foundEvent) {
eventListener.removeListener(id, listener);
const output = foundEvent.error ?? foundEvent.output;
if (foundEvent.error) {
res.statusCode = 400;
}
res.end(output ? JSON.stringify(output) : undefined);
} else {
eventListener.registerRequest(kind, id, lambdaName);
}
},
},
],
onReady: async function (port) {
process.env.LOCAL_PORT = String(port);
if (!options?.configFile) {
throw new Error("jest config file path is required");
}
const confFilePath = path.resolve(options.configFile);
const { config } = await readInitialOptions(confFilePath);
const setupFiles = config.setupFiles ?? [];
setupFiles.push(setupFile);
config.setupFiles = setupFiles;
if (options.oneshot) {
config.watch = false;
config.watchAll = false;
}
if (!config.rootDir) {
throw new Error("jest config must include 'rootDir'");
}
const initialRootDir = config.rootDir;
config.rootDir = ".";
const roots = [initialRootDir];
if (config.roots) {
roots.push(...config.roots.map((x) => path.join(initialRootDir, x)));
}
roots.push(outdir);
config.roots = roots;
const startTestRunner = async () => {
try {
const result = await jest.runCLI(config, [config.rootDir]);
if (options.oneshot) {
let timeout = 0;
if (typeof options.oneshot == "object" && options.oneshot.delay) {
timeout = options.oneshot.delay * 1000;
}
setTimeout(() => {
this.stop();
process.exit(result.results.success ? 0 : 1);
}, timeout);
}
} catch (error) {
console.error(error);
this.stop();
process.exit(1);
}
};
const ddbPlugin = this.options.plugins?.find((x: SlsAwsLambdaPlugin) => x.name == "ddblocal-stream") as SlsAwsLambdaPlugin;
if (ddbPlugin) {
console.log("Waiting for DynamoDB Local Streams plugin to initialize...");
ddbPlugin.pluginData.onReady(startTestRunner);
} else {
await startTestRunner();
}
},
},
};
};
declare global {
/**
* @param {string} messageId MessageId returned by AWS SDK SQS Client's `SendMessageCommand` or from `SendMessageBatchCommand`'s Success MessageId.
* @param {string} lambdaName consumer name if SQS will be consumed by multiple Lambdas.
*/
const sqsResponse: (messageId: string, lambdaName?: string) => Promise<any>;
/**
* @param {string} messageId MessageId returned by AWS SDK SNS Client's `PublishCommand` or from `PublishBatchCommand`'s Success MessageId.
* @param {string} lambdaName consumer name if SNS will be consumed by multiple Lambdas.
*/
const snsResponse: (messageId: string, lambdaName?: string) => Promise<any>;
/**
* @param {string} requestId requestId returned by AWS SDK S3 Client's send() response `$metadata`.
* @param {string} lambdaName consumer name if S3 event will be consumed by multiple Lambdas.
*/
const s3Response: (requestId: string, lambdaName?: string) => Promise<any>;
/**
* @param {any} identifier DynamoDB Item identifier.
* Example: {id:{N: 12}}.
* @param {string} lambdaName consumer name if Stream will be consumed by multiple Lambdas.
*/
const dynamoResponse: (identifier: { [key: string]: any }, lambdaName?: string) => Promise<any>;
/**
* serverless-aws-lambda local server port
*/
const LOCAL_PORT: number;
}
export default jestPlugin;
export { jestPlugin };