-
Notifications
You must be signed in to change notification settings - Fork 41
/
sandbox_command.test.ts
316 lines (282 loc) · 11.3 KB
/
sandbox_command.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
import { beforeEach, describe, it, mock } from 'node:test';
import { AmplifyPrompter } from '@aws-amplify/cli-core';
import yargs, { CommandModule } from 'yargs';
import {
TestCommandError,
TestCommandRunner,
} from '../../test-utils/command_runner.js';
import assert from 'node:assert';
import fs from 'fs';
import fsp from 'fs/promises';
import { EventHandler, SandboxCommand } from './sandbox_command.js';
import { createSandboxCommand } from './sandbox_command_factory.js';
import { SandboxDeleteCommand } from './sandbox-delete/sandbox_delete_command.js';
import { Sandbox, SandboxSingletonFactory } from '@aws-amplify/sandbox';
import { createSandboxSecretCommand } from './sandbox-secret/sandbox_secret_command_factory.js';
import { ClientConfigGeneratorAdapter } from '../../client-config/client_config_generator_adapter.js';
import { CommandMiddleware } from '../../command_middleware.js';
import path from 'path';
void describe('sandbox command factory', () => {
void it('instantiate a sandbox command correctly', () => {
assert.ok(createSandboxCommand() instanceof SandboxCommand);
});
});
void describe('sandbox command', () => {
let commandRunner: TestCommandRunner;
let sandbox: Sandbox;
let sandboxStartMock = mock.fn<typeof sandbox.start>();
const clientConfigGenerationMock = mock.fn<EventHandler>();
const clientConfigDeletionMock = mock.fn<EventHandler>();
const clientConfigGeneratorAdapterMock = {
generateClientConfigToFile: clientConfigGenerationMock,
} as unknown as ClientConfigGeneratorAdapter;
const commandMiddleware = new CommandMiddleware();
const mockHandleProfile = mock.method(
commandMiddleware,
'ensureAwsCredentialAndRegion',
() => null
);
const sandboxProfile = 'test-sandbox';
beforeEach(async () => {
const sandboxFactory = new SandboxSingletonFactory(() =>
Promise.resolve({
namespace: 'testSandboxId',
name: 'testSandboxName',
type: 'sandbox',
})
);
sandbox = await sandboxFactory.getInstance();
sandboxStartMock = mock.method(sandbox, 'start', () => Promise.resolve());
const sandboxDeleteCommand = new SandboxDeleteCommand(sandboxFactory);
const sandboxCommand = new SandboxCommand(
sandboxFactory,
[sandboxDeleteCommand, createSandboxSecretCommand()],
clientConfigGeneratorAdapterMock,
commandMiddleware,
() => ({
successfulDeployment: [clientConfigGenerationMock],
successfulDeletion: [clientConfigDeletionMock],
})
);
const parser = yargs().command(sandboxCommand as unknown as CommandModule);
commandRunner = new TestCommandRunner(parser);
sandboxStartMock.mock.resetCalls();
mockHandleProfile.mock.resetCalls();
});
void it('registers a callback on the "successfulDeployment" event', async () => {
const mockOn = mock.method(sandbox, 'on');
await commandRunner.runCommand('sandbox');
assert.equal(mockOn.mock.calls[0].arguments[0], 'successfulDeployment');
assert.equal(mockOn.mock.calls[0].arguments[1], clientConfigGenerationMock);
});
void it('registers a callback on the "successfulDeletion" event', async () => {
const mockOn = mock.method(sandbox, 'on');
await commandRunner.runCommand('sandbox');
assert.equal(mockOn.mock.calls[1].arguments[0], 'successfulDeletion');
assert.equal(mockOn.mock.calls[1].arguments[1], clientConfigDeletionMock);
});
void it('starts sandbox without any additional flags', async () => {
await commandRunner.runCommand('sandbox');
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.ok(!sandboxStartMock.mock.calls[0].arguments[0].name);
});
void it('starts sandbox with user provided app name', async () => {
await commandRunner.runCommand('sandbox --name user-app-name');
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.deepStrictEqual(
sandboxStartMock.mock.calls[0].arguments[0].name,
'user-app-name'
);
});
void it('shows available options in help output', async () => {
const output = await commandRunner.runCommand('sandbox --help');
assert.match(output, /--name/);
assert.match(output, /--dir-to-watch/);
assert.match(output, /--exclude/);
assert.match(output, /--config-format/);
assert.match(output, /--config-out-dir/);
assert.equal(mockHandleProfile.mock.callCount(), 0);
});
void it('shows version should not call profile middleware', async () => {
void commandRunner.runCommand('sandbox --version');
assert.equal(mockHandleProfile.mock.callCount(), 0);
});
void it('fails if invalid dir-to-watch is provided', async () => {
const dirToWatchError = new Error(
'--dir-to-watch nonExistentDir does not exist'
);
mock.method(fsp, 'stat', () => Promise.reject(dirToWatchError));
await assert.rejects(
() => commandRunner.runCommand('sandbox --dir-to-watch nonExistentDir'),
(err: TestCommandError) => {
assert.equal(err.error.message, dirToWatchError.message);
return true;
}
);
});
void it('fails if a file is provided in the --dir-to-watch flag', async (contextual) => {
const dirToWatchError = new Error(
'--dir-to-watch existentFile is not a valid directory'
);
contextual.mock.method(fsp, 'stat', () => ({
isDirectory: () => false,
}));
await assert.rejects(
() => commandRunner.runCommand('sandbox --dir-to-watch existentFile'),
(err: TestCommandError) => {
assert.equal(err.error.message, dirToWatchError.message);
return true;
}
);
});
void it('asks to delete the sandbox environment when users send ctrl-C and say yes to delete', async (contextual) => {
// Mock process and extract the sigint handler after calling the sandbox command
const processSignal = contextual.mock.method(process, 'on', () => {
/* no op */
});
const sandboxStartMock = contextual.mock.method(
sandbox,
'start',
async () => Promise.resolve()
);
const sandboxDeleteMock = contextual.mock.method(sandbox, 'delete', () =>
Promise.resolve()
);
// User said yes to delete
contextual.mock.method(AmplifyPrompter, 'yesOrNo', () =>
Promise.resolve(true)
);
await commandRunner.runCommand('sandbox');
// Similar to the later 0ms timeout. Without this tests in github action are failing
// but working locally
await new Promise((resolve) => setTimeout(resolve, 0));
const sigIntHandlerFn = processSignal.mock.calls[0].arguments[1];
if (sigIntHandlerFn) sigIntHandlerFn();
// I can't find any open node:test or yargs issues that would explain why this is necessary
// but for some reason the mock call count does not update without this 0ms wait
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.equal(sandboxDeleteMock.mock.callCount(), 1);
});
void it('asks to delete the sandbox environment when users send ctrl-C and say no to delete', async (contextual) => {
// Mock process and extract the sigint handler after calling the sandbox command
const processSignal = contextual.mock.method(process, 'on', () => {
/* no op */
});
const sandboxStartMock = contextual.mock.method(
sandbox,
'start',
async () => Promise.resolve()
);
const sandboxDeleteMock = contextual.mock.method(
sandbox,
'delete',
async () => Promise.resolve()
);
// User said no to delete
contextual.mock.method(AmplifyPrompter, 'yesOrNo', () =>
Promise.resolve(false)
);
await commandRunner.runCommand('sandbox');
// Similar to the previous test's 0ms timeout. Without this tests in github action are failing
// but working locally
await new Promise((resolve) => setTimeout(resolve, 0));
const sigIntHandlerFn = processSignal.mock.calls[0].arguments[1];
if (sigIntHandlerFn) sigIntHandlerFn();
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.equal(sandboxDeleteMock.mock.callCount(), 0);
});
void it('starts sandbox with user provided invalid AWS profile', async () => {
const profileErr = new Error('some profile error');
mockHandleProfile.mock.mockImplementationOnce(() => {
throw profileErr;
});
await assert.rejects(
() => commandRunner.runCommand(`sandbox --profile ${sandboxProfile}`), // profile doesn't exist
(err: TestCommandError) => {
assert.equal(err.error, profileErr);
return true;
}
);
assert.equal(sandboxStartMock.mock.callCount(), 0);
assert.equal(mockHandleProfile.mock.callCount(), 1);
assert.equal(
mockHandleProfile.mock.calls[0].arguments[0]?.profile,
sandboxProfile
);
});
void it('starts sandbox with user provided valid AWS profile', async () => {
mockHandleProfile.mock.mockImplementationOnce(() => null);
const sandboxFactory = new SandboxSingletonFactory(() =>
Promise.resolve({
namespace: 'testSandboxId',
name: 'testSandboxName',
type: 'sandbox',
})
);
sandbox = await sandboxFactory.getInstance();
sandboxStartMock = mock.method(sandbox, 'start', () => Promise.resolve());
const sandboxCommand = new SandboxCommand(
sandboxFactory,
[],
clientConfigGeneratorAdapterMock,
commandMiddleware,
undefined
);
const parser = yargs().command(sandboxCommand as unknown as CommandModule);
commandRunner = new TestCommandRunner(parser);
await commandRunner.runCommand(`sandbox --profile ${sandboxProfile}`);
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.equal(
mockHandleProfile.mock.calls[0].arguments[0]?.profile,
sandboxProfile
);
});
void it('fails if invalid config-out-dir is provided', async () => {
const configOutDirError = new Error(
'--config-out-dir nonExistentDir does not exist'
);
mock.method(fsp, 'stat', () => Promise.reject(configOutDirError));
await assert.rejects(
() => commandRunner.runCommand('sandbox --config-out-dir nonExistentDir'),
(err: TestCommandError) => {
assert.equal(err.error.message, configOutDirError.message);
return true;
}
);
});
void it('fails if a file is provided for config-out-dir', async (contextual) => {
const configOutDirError = new Error(
'--config-out-dir existentFile is not a valid directory'
);
contextual.mock.method(fsp, 'stat', () => ({
isDirectory: () => false,
}));
await assert.rejects(
() => commandRunner.runCommand('sandbox --config-out-dir existentFile'),
(err: TestCommandError) => {
assert.equal(err.error.message, configOutDirError.message);
return true;
}
);
});
void it('starts sandbox with provided client config options as watch exclusions', async (contextual) => {
mock.method(fs, 'lstatSync', () => {
return {
isFile: () => false,
isDir: () => true,
};
});
contextual.mock.method(fsp, 'stat', () => ({
isDirectory: () => true,
}));
await commandRunner.runCommand(
'sandbox --config-out-dir existentDir --config-format ts'
);
assert.equal(sandboxStartMock.mock.callCount(), 1);
assert.deepStrictEqual(
sandboxStartMock.mock.calls[0].arguments[0].exclude,
[path.join(process.cwd(), 'existentDir', 'amplifyconfiguration.ts')]
);
});
});