-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathtokens-add.test.ts
More file actions
393 lines (358 loc) · 12.8 KB
/
tokens-add.test.ts
File metadata and controls
393 lines (358 loc) · 12.8 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
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
import { expect } from 'chai';
import * as sinon from 'sinon';
import { configHandler, cliux } from '@contentstack/cli-utilities';
import TokensAddCommand from '../../../src/commands/auth/tokens/add';
import { stub, assert } from 'sinon';
import { config as dotenvConfig } from 'dotenv';
import nock from 'nock';
<<<<<<< HEAD
import { readFileSync } from 'fs';
import { join } from 'path';
const conf = JSON.parse(readFileSync(join(__dirname, '../config.json'), "utf-8"));
=======
// @ts-ignore
import * as conf from '../config.json';
>>>>>>> main
dotenvConfig();
// Check for PREPACK_MODE - GitHub workflows set NODE_ENV=PREPACK_MODE during setup
const isPrepackMode = process.env.NODE_ENV === 'PREPACK_MODE';
// Handle uncaught exceptions in PREPACK_MODE to prevent nyc from exiting early
if (isPrepackMode) {
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception in PREPACK_MODE:', error);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection in PREPACK_MODE:', reason);
});
}
// Set up nock at the top level to intercept all HTTP requests in PREPACK_MODE
if (isPrepackMode) {
if (!nock.isActive()) {
nock.activate();
}
// Mock the management token validation endpoint - match any query params
nock('https://api.contentstack.io')
.persist()
.get('/v3/environments')
.query(true) // Match any query params
.reply(200, { environments: [] });
// Also mock without query params just in case
nock('https://api.contentstack.io')
.persist()
.get('/v3/environments')
.reply(200, { environments: [] });
// Disable all real HTTP requests - only allow our mocked requests
nock.disableNetConnect();
nock.enableNetConnect('localhost');
nock.enableNetConnect('127.0.0.1');
}
const config = configHandler;
const configKeyTokens = 'tokens';
process.env.BRANCH_ENABLED_API_KEY = 'enabled_api_key';
process.env.BRANCH_ENABLED_MGMT_TOKEN = 'tokens';
process.env.BRANCH_ENABLED_DELIVERY_TOKEN = 'enabled_delivery_token';
process.env.BRANCH_ENABLED_ENVIRONMENT = 'enabled_env';
process.env.BRANCH_DISABLED_API_KEY = 'disabled_api_key';
process.env.BRANCH_DISABLED_MGMT_TOKEN = 'tokens';
process.env.BRANCH_DISABLED_DELIVERY_TOKEN = 'disabled_delivery_token';
process.env.BRANCH_DISABLED_ENVIRONMENT = 'disabled_env';
function resetConfig() {
config.delete(`${configKeyTokens}.test-api-key-token2`);
config.delete(`${configKeyTokens}.test-management-token`);
config.delete(`${configKeyTokens}.test-management-token2`);
config.delete(`${configKeyTokens}.test-api-key-token`);
config.delete(`${configKeyTokens}.newToken`);
}
describe('Tokens Add Command', () => {
let printStub: sinon.SinonStub;
const validAPIKey = conf.validAPIKey;
const validDeliveryToken = '***REMOVED***';
const validmanagementToken = 'cmajhsd98939482';
const validEnvironment = 'textenv';
before(function () {
resetConfig();
if ((cliux.print as any).restore) (cliux.print as any).restore();
printStub = stub(cliux, 'print');
});
after(() => {
printStub.restore();
resetConfig();
});
it('Add a token with valid api key, should be added scuccessfully', async function () {
const inquireStub = sinon.stub(cliux, 'inquire').resolves(validEnvironment);
await TokensAddCommand.run([
'--alias',
'test-api-key-token',
'--stack-api-key',
validAPIKey,
'--delivery',
'--token',
validDeliveryToken,
]);
expect(Boolean(config.get(`${configKeyTokens}.test-api-key-token`))).to.be.true;
inquireStub.restore();
});
it('Add a valid management token, should be added successfully', async function () {
// Skip this test in PREPACK_MODE if HTTP requests aren't properly mocked
if (isPrepackMode) {
this.skip();
return;
}
try {
await TokensAddCommand.run([
'--alias',
'test-management-token',
'--stack-api-key',
validAPIKey,
'--management',
'--token',
validmanagementToken,
]);
expect(Boolean(config.get(`${configKeyTokens}.test-management-token`))).to.be.true;
} catch (error: any) {
expect(Boolean(config.get(`${configKeyTokens}.test-management-token`))).to.be.false;
}
});
it('Replace an existing token, should prompt for confirmation', async function () {
// Skip this test in PREPACK_MODE if HTTP requests aren't properly mocked
if (isPrepackMode) {
this.skip();
return;
}
config.set(`${configKeyTokens}.test-management-token`, { token: validmanagementToken });
const inquireStub = sinon.stub(cliux, 'inquire').resolves(true);
await TokensAddCommand.run([
'--alias',
'test-management-token',
'--stack-api-key',
validAPIKey,
'--management',
'--token',
'invalid',
]);
expect(inquireStub.calledOnce).to.be.true;
inquireStub.restore();
});
it('Add a invalid management token, should fail to add', async function () {
// Skip this test in PREPACK_MODE if HTTP requests aren't properly mocked
if (isPrepackMode) {
this.skip();
return;
}
await TokensAddCommand.run([
'--alias',
'test-management-token2',
'--stack-api-key',
validAPIKey,
'--management',
'--token',
'invalid',
]);
expect(Boolean(config.get(`${configKeyTokens}.test-management-token2`))).to.be.false;
});
it('Add a token without alias, should prompt for alias', async function () {
// Skip this test in PREPACK_MODE if HTTP requests aren't properly mocked
if (isPrepackMode) {
this.skip();
return;
}
if ((cliux.inquire as any).restore) (cliux.inquire as any).restore();
const inquireStub = sinon.stub(cliux, 'inquire').resolves(true);
await TokensAddCommand.run(['--stack-api-key', validAPIKey, '--management', '--token', 'invalid']);
expect(inquireStub.calledOnce).to.be.true;
inquireStub.restore();
});
});
describe('Management and Delivery token flags', () => {
let inquireStub: sinon.SinonStub;
let errorStub: sinon.SinonStub;
let successStub: sinon.SinonStub;
let printStub: sinon.SinonStub;
beforeEach(() => {
if ((cliux.inquire as any).restore) (cliux.inquire as any).restore();
if ((cliux.error as any).restore) (cliux.error as any).restore();
if ((cliux.success as any).restore) (cliux.success as any).restore();
if ((cliux.print as any).restore) (cliux.print as any).restore();
inquireStub = sinon.stub(cliux, 'inquire');
errorStub = sinon.stub(cliux, 'error');
successStub = sinon.stub(cliux, 'success');
printStub = sinon.stub(cliux, 'print');
nock.cleanAll();
resetConfig();
});
afterEach(() => {
sinon.restore();
inquireStub.restore();
errorStub.restore();
successStub.restore();
printStub.restore();
if ((cliux.inquire as any).restore) (cliux.inquire as any).restore();
if ((cliux.error as any).restore) (cliux.error as any).restore();
if ((cliux.success as any).restore) (cliux.success as any).restore();
if ((cliux.print as any).restore) (cliux.print as any).restore();
// Don't clean nock in PREPACK_MODE - the persistent mocks need to stay active
if (!isPrepackMode) {
nock.cleanAll();
}
resetConfig();
});
describe('- Management token', () => {
// Skip all management token tests in PREPACK_MODE if HTTP requests aren't properly mocked
if (isPrepackMode) {
before(function() {
this.skip();
});
}
it('Should ask for a prompt to select type of token to add', async () => {
await TokensAddCommand.run([]);
assert.calledWith(inquireStub, {
type: 'list',
name: 'tokenType',
message: 'CLI_SELECT_TOKEN_TYPE',
choices: [
{ name: 'Management Token', value: 'management' },
{ name: 'Delivery Token', value: 'delivery' },
],
});
});
it('Should ask for api key ', async () => {
await TokensAddCommand.run(['--management', '--alias', 'newToken']);
assert.calledWith(inquireStub, { type: 'input', message: 'CLI_AUTH_TOKENS_ADD_ENTER_API_KEY', name: 'apiKey' });
});
it('Should ask for api key ', async () => {
await TokensAddCommand.run(['--management', '--alias', 'newToken']);
assert.calledWith(inquireStub, { type: 'input', message: 'CLI_AUTH_TOKENS_ADD_ENTER_API_KEY', name: 'apiKey' });
});
it.skip('Should add a token successfully when all values are passed', async () => {
nock('https://api.contentstack.io').get('/v3/environments').query({ limit: 1 }).reply(200, { environments: [] });
await TokensAddCommand.run([
'--management',
'--alias',
'newToken',
'--stack-api-key',
conf.validAPIKey,
'--token',
conf.validToken,
'--branch',
'main',
]);
assert.calledOnce(successStub);
});
it('Should error when --token has no value', async () => {
try {
await TokensAddCommand.run(['--management', '--alias', 'newToken', '--stack-api-key']);
throw new Error('Test should not reach here');
} catch (error: any) {
expect(error.message).to.contain('expects a value');
}
});
it.skip('Should add a token successfully after all the values are passed with stack having branches enabled', async () => {
nock('https://api.contentstack.io').get('/v3/environments').query({ limit: 1 }).reply(200, { environments: [] });
await TokensAddCommand.run([
'--management',
'--alias',
'newToken',
'--stack-api-key',
conf.validAPIKey,
'--token',
conf.validToken,
'--branch',
'main',
]);
assert.calledOnce(successStub);
});
it.skip('Should add a token successfully for stack with branches disabled after all the values are passed', async () => {
nock('https://api.contentstack.io').get('/v3/environments').query({ limit: 1 }).reply(200, { environments: [] });
await TokensAddCommand.run([
'--management',
'--alias',
'newToken',
'--stack-api-key',
conf.validAPIKey,
'--token',
conf.validToken,
]);
assert.calledOnce(successStub);
});
});
describe('- Delivery token', () => {
it('Should ask for api key', async () => {
await TokensAddCommand.run(['--delivery', '--alias', 'newToken']);
assert.calledWith(inquireStub, { type: 'input', message: 'CLI_AUTH_TOKENS_ADD_ENTER_API_KEY', name: 'apiKey' });
});
it('Should ask for delivery token', async () => {
await TokensAddCommand.run([
'--delivery',
'--alias',
'newToken',
'--stack-api-key',
process.env.BRANCH_ENABLED_API_KEY!,
]);
assert.calledWith(inquireStub, { type: 'input', message: 'CLI_AUTH_TOKENS_ADD_ENTER_TOKEN', name: 'token' });
});
it('Should ask for environment', async () => {
await TokensAddCommand.run([
'--delivery',
'--alias',
'newToken',
'--stack-api-key',
process.env.BRANCH_ENABLED_API_KEY!,
'--token',
process.env.BRANCH_ENABLED_DELIVERY_TOKEN!,
]);
assert.calledWith(inquireStub, {
type: 'input',
message: 'CLI_AUTH_TOKENS_ADD_ENTER_ENVIRONMENT',
name: 'env',
});
});
it('Should add a new token if all the values are set correctly for stack with branches enabled', async () => {
await TokensAddCommand.run([
'--delivery',
'--alias',
'newToken',
'--stack-api-key',
process.env.BRANCH_ENABLED_API_KEY!,
'--token',
process.env.BRANCH_ENABLED_DELIVERY_TOKEN!,
'--environment',
process.env.BRANCH_ENABLED_ENVIRONMENT!,
]);
assert.calledWith(successStub, 'CLI_AUTH_TOKENS_ADD_SUCCESS');
});
it('Should add a new token if all the values are set correctly for stack with branches disabled', async () => {
await TokensAddCommand.run([
'--delivery',
'--alias',
'newToken',
'--stack-api-key',
process.env.BRANCH_DISABLED_API_KEY!,
'--token',
process.env.BRANCH_DISABLED_DELIVERY_TOKEN!,
'--environment',
process.env.BRANCH_DISABLED_ENVIRONMENT!,
]);
assert.calledWith(successStub, 'CLI_AUTH_TOKENS_ADD_SUCCESS');
});
it('Should throw and error for stack with branches disabled', async () => {
let branch = 'my-branch';
try {
await TokensAddCommand.run([
'--delivery',
'--alias',
'newToken',
'--stack-api-key',
process.env.BRANCH_DISABLED_API_KEY!,
'--token',
process.env.BRANCH_DISABLED_DELIVERY_TOKEN!,
'--environment',
process.env.BRANCH_DISABLED_ENVIRONMENT!,
'--branch',
branch,
]);
} catch (error: any) {
assert.calledOnce(errorStub);
}
});
});
});