-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
287 lines (253 loc) · 8.87 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
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 { startVitest } from "vitest/node";
import type { supportedService } from "./requestListener";
// @ts-ignore
import { actualDirName } from "resolvedPaths";
const setupFile = `${actualDirName.slice(0, -5)}/resources/setup.ts`;
let vite;
interface IVitestPlugin {
configFile: string;
oneshot?: boolean | { delay: number };
coverage?: {
outDir: string;
json?: boolean;
badge?: boolean;
threshold?: number;
};
}
const coverage: any = {};
const vitestPlugin = (options: IVitestPlugin) => {
let isWatching: boolean = false;
const eventListener = new TestRequestListener();
const config: SlsAwsLambdaPlugin = {
name: "vitest-plugin",
onInit: function () {
this.lambdas.forEach((l) => {
const lambdaConverage = {
done: false,
coverage: 0,
alb: [],
apg: [],
s3: [],
sns: [],
sqs: [],
ddb: [],
documentDb: [],
};
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,
});
});
// TODO: add documentDb and FunctionURL
coverage[l.name] = lambdaConverage;
l.onInvoke((event: any, info: any) => {
if (!event || !info) {
return;
}
handleInvoke(coverage[l.name], event, info);
});
l.onInvokeSuccess((input, output, info) => {
// TODO if kind is dynamo or document db get table name and collection name
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}/vitest-it-coverage.json`, JSON.stringify(coverageResult, null, 2), { encoding: "utf-8" });
}
if (options.coverage.badge) {
writeFileSync(`${outdir}/vitest-it-coverage.svg`, generateBadge(coverageResult.coverage), { encoding: "utf-8" });
}
} else {
console.log("coverage 'outDir' is required");
}
}
},
offline: {
request: [
{
filter: "/__vitest_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) {
if (!options?.configFile) {
throw new Error("Vitest config file path is required");
}
const startTestRunner = async () => {
try {
vite = await startVitest(
"test",
[],
{
config: options.configFile,
},
{
define: {
LOCAL_PORT: port,
},
test: {
watchExclude: [".aws_lambda", "src", "serverless.yml", "node_modules", ".git"],
setupFiles: [setupFile],
env: {
LOCAL_PORT: String(port),
},
},
}
);
} catch (error) {
console.error(error);
process.exit(1);
}
isWatching = vite.config.watch;
if (options.oneshot) {
let timeout = 0;
if (typeof options.oneshot == "object" && options.oneshot.delay) {
timeout = options.oneshot.delay * 1000;
}
await new Promise((resolve) => setTimeout(resolve, timeout));
try {
await this.stop();
await vite.exit();
} catch (error) {
console.error(error);
} finally {
process.exit();
}
}
};
const ddbPlugin = this.options.plugins?.find((x: SlsAwsLambdaPlugin) => x.name == "ddblocal-stream") as SlsAwsLambdaPlugin;
if (ddbPlugin && !ddbPlugin.pluginData.isReady) {
console.log("Waiting for DynamoDB Local Streams plugin to initialize...");
ddbPlugin.pluginData.onReady(startTestRunner);
} else {
await startTestRunner();
}
},
},
buildCallback: async function (result, isRebuild) {
if (isWatching && isRebuild) {
vite.rerunFiles();
}
},
};
return config;
};
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 vitestPlugin;
export { vitestPlugin };