/
options.ts
executable file
·523 lines (503 loc) · 15.8 KB
/
options.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
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
import * as findUp from 'find-up';
import * as yargs from 'yargs';
import { Retrieval } from './retrieval';
import * as yaml from './yaml';
/**
* Ply options. Empty values are populated with Defaults.
*/
export interface Options {
/**
* Tests base directory ('.').
*/
testsLocation?: string;
/**
* Request files glob pattern, relative to testsLocation ('**\/*.{ply.yaml,ply.yml}').
*/
requestFiles?: string;
/**
* Case files glob pattern, relative to testsLocation ('**\/*.ply.ts').
*/
caseFiles?: string;
/**
* Flow files glob pattern, relative to testsLocation ('**\/*.flow').
*/
flowFiles?: string;
/**
* File pattern to ignore, relative to testsLocation ('**\/{node_modules,bin,dist,out}\/**').
*/
ignore?: string;
/**
* File pattern for requests/cases/flows that shouldn't be directly executed, relative to testsLocation.
*/
skip?: string;
/**
* Expected results base dir (testsLocation + '/results/expected').
*/
expectedLocation?: string;
/**
* Actual results base dir (this.testsLocation + '/results/actual').
*/
actualLocation?: string;
/**
* Result files live under a similar subpath as request/case files (true).
* (eg: Expected result relative to 'expectedLocation' is the same as
* request file relative to 'testsLocation').
*/
resultFollowsRelativePath?: boolean;
/**
* Log file base dir (this.actualLocation).
*/
logLocation?: string;
/**
* Files containing values JSON (or CSV or XLSX).
*/
valuesFiles?: string[];
/**
* Results summary output JSON
*/
outputFile?: string;
/**
* Verbose output (false). Takes precedence over 'quiet' if both are true.
*/
verbose?: boolean;
/**
* The opposite of 'verbose' (false).
*/
quiet?: boolean;
/**
* Bail on first failure (false).
*/
bail?: boolean;
/**
* Run suites in parallel.
*/
parallel?: boolean;
/**
* (For use with rowwise values). Number of rows to run per batch.
*/
batchRows?: number;
/**
* (For use with rowwise values). Delay in ms between row batches.
*/
batchDelay?: number;
/**
* Reporter output format. Built-in formats: json, csv, xlsx.
* See https://github.com/ply-ct/ply-viz for more options.
*/
reporter?: string;
/**
* (When flows have loopback links). Max instance count per step (10). Overridable in flow design.
*/
maxLoops?: number;
/**
* Predictable ordering of response body JSON property keys -- needed for verification (true).
*/
responseBodySortedKeys?: boolean;
/**
* Response headers to exclude when generating expected results.
*/
genExcludeResponseHeaders?: string[];
/**
* Prettification indent for yaml and response body (2).
*/
prettyIndent?: number;
}
/**
* Populated ply options.
*/
export interface PlyOptions extends Options {
testsLocation: string;
requestFiles: string;
caseFiles: string;
flowFiles: string;
ignore: string;
skip: string;
expectedLocation: string;
actualLocation: string;
resultFollowsRelativePath: boolean;
logLocation: string;
valuesFiles: string[];
outputFile?: string;
verbose: boolean;
quiet: boolean;
bail: boolean;
parallel: boolean;
batchRows: number;
batchDelay: number;
reporter?: string;
maxLoops: number;
responseBodySortedKeys: boolean;
genExcludeResponseHeaders?: string[];
prettyIndent: number;
args?: any;
runOptions?: RunOptions;
}
/**
* Options specified on a per-run basis.
*/
export interface RunOptions {
/**
* Run test requests but don't verify outcomes.
*/
submit?: boolean;
/**
* Skip verify only if expected result does not exist.
*/
submitIfExpectedMissing?: boolean;
/**
* Create expected from actual and verify based on that.
*/
createExpected?: boolean;
/**
* Create expected from actual only if expected does not exist.
*/
createExpectedIfMissing?: boolean;
/**
* If untrusted, enforce safe expression evaluation without side-effects.
* Supports a limited subset of template literal expressions.
* Default is false assuming expressions from untrusted sources are evaluated.
*/
trusted?: boolean;
/**
* Import requests or values from external format (currently 'postman' or 'insomnia' is supported).
* Overwrites existing same-named files.
*/
import?: 'postman' | 'insomnia';
/**
* Import collections into request suites (.yaml files), instead of individual (.ply) requests.
*/
importToSuite?: boolean;
/**
* Generate report from previously-executed Ply results. See --reporter for options.
*/
report?: string;
/**
* Augment OpenAPI v3 doc at specified path with operation summaries, request/response samples,
* and code snippets from Ply expected results.
*/
openapi?: string;
/**
* Import case suite modules from generated .js instead of .ts source (default = false).
* This runOption needs to be set in your case's calls to Suite.run (for requests),
* and also in originating the call to Suite.run (for the case(s)).
*/
useDist?: boolean;
requireTsNode?: boolean;
/**
* Runtime override values
*/
values?: { [key: string]: string };
}
/**
* Locations are lazily inited to reflect bootstrapped testsLocation.
*/
export class Defaults implements PlyOptions {
private _expectedLocation?: string;
private _actualLocation?: string;
private _logLocation?: string;
constructor(readonly testsLocation: string = '.') {}
requestFiles = '**/*.{ply,ply.yaml,ply.yml}';
caseFiles = '**/*.ply.ts';
flowFiles = '**/*.flow';
ignore = '**/{node_modules,bin,dist,out}/**';
skip = '**/*.ply';
reporter = '' as any;
get expectedLocation() {
if (!this._expectedLocation) {
this._expectedLocation = this.testsLocation + '/results/expected';
}
return this._expectedLocation;
}
get actualLocation() {
if (!this._actualLocation) {
this._actualLocation = this.testsLocation + '/results/actual';
}
return this._actualLocation;
}
get logLocation() {
if (!this._logLocation) {
this._logLocation = this.actualLocation;
}
return this._logLocation;
}
resultFollowsRelativePath = true;
valuesFiles = [];
verbose = false;
quiet = false;
bail = false;
parallel = false;
batchRows = 1;
batchDelay = 0;
maxLoops = 10;
responseBodySortedKeys = true;
genExcludeResponseHeaders = [
'cache-control',
'connection',
'content-length',
'date',
'etag',
'server',
'transfer-encoding',
'x-powered-by'
];
prettyIndent = 2;
}
export const PLY_CONFIGS = ['plyconfig.yaml', 'plyconfig.yml', 'plyconfig.json'];
export class Config {
public options: PlyOptions;
private yargsOptions: any = {
testsLocation: {
describe: 'Tests base directory',
alias: 't'
},
requestFiles: {
describe: 'Request files glob pattern'
},
caseFiles: {
describe: 'Case files glob pattern'
},
flowFiles: {
describe: 'Flow files glob pattern'
},
ignore: {
describe: 'File patterns to ignore'
},
skip: {
describe: 'File patterns to skip'
},
submit: {
describe: "Send requests but don't verify",
alias: 's',
type: 'boolean'
},
create: {
describe: 'Create expected result from actual',
type: 'boolean'
},
trusted: {
describe: 'Expressions are from trusted source',
type: 'boolean'
},
expectedLocation: {
describe: 'Expected results base dir',
type: 'string' // avoid premature reading of default
},
actualLocation: {
describe: 'Actual results base dir',
type: 'string' // avoid premature reading of default
},
resultFollowsRelativePath: {
describe: 'Results under similar subpath'
},
logLocation: {
describe: 'Test logs base dir',
type: 'string' // avoid premature reading of default
},
valuesFiles: {
describe: 'Values files (comma-separated)',
type: 'string'
},
outputFile: {
describe: 'Report or summary json file path',
alias: 'o',
type: 'string'
},
verbose: {
describe: "Much output (supersedes 'quiet')"
},
quiet: {
describe: "Opposite of 'verbose'"
},
bail: {
describe: 'Stop on first failure'
},
parallel: {
describe: 'Run suites in parallel'
},
batchRows: {
describe: '(Rowwise values) rows per batch'
},
batchDelay: {
describe: '(Rowwise values) ms batch delay'
},
reporter: {
describe: 'Reporter output format'
},
maxLoops: {
describe: 'Flow step instance limit'
},
import: {
describe: 'Import requests/values from external',
type: 'string'
},
importToSuite: {
describe: 'Import into .yaml suite files',
type: 'boolean'
},
report: {
describe: 'Generate report from ply results',
type: 'string'
},
openapi: {
describe: 'Augment OpenAPI 3 docs with examples',
type: 'string'
},
useDist: {
describe: 'Load cases from compiled js',
type: 'boolean'
},
responseBodySortedKeys: {
describe: 'Sort response body JSON keys'
},
genExcludeResponseHeaders: {
describe: 'Exclude from generated results',
type: 'string'
},
prettyIndent: {
describe: 'Format response JSON'
}
};
constructor(
private readonly defaults: PlyOptions = new Defaults(),
commandLine = false,
configPath?: string
) {
this.options = this.load(defaults, commandLine, configPath);
this.defaults.testsLocation = this.options.testsLocation;
// result locations may need priming
if (!this.options.expectedLocation) {
this.options.expectedLocation = defaults.expectedLocation;
}
if (!this.options.actualLocation) {
this.options.actualLocation = defaults.actualLocation;
}
if (!this.options.logLocation) {
this.options.logLocation = this.options.actualLocation;
}
}
private load(defaults: PlyOptions, commandLine: boolean, configPath?: string): PlyOptions {
let opts: any;
if (commandLine) {
// help pre-check to avoid premature yargs parsing
const needsHelp = process.argv.length > 2 && process.argv[2] === '--help';
if (!configPath && !needsHelp && yargs.argv.config) {
configPath = '' + yargs.argv.config;
console.debug(`Loading config from ${configPath}`);
}
if (!configPath) {
configPath = findUp.sync(PLY_CONFIGS, { cwd: defaults.testsLocation });
}
const config = configPath ? this.read(configPath) : {};
let spec = yargs
.usage('Usage: $0 <tests> [options]')
.help('help')
.alias('help', 'h')
.version()
.alias('version', 'v')
.config(config)
.option('config', {
description: 'Ply config location',
type: 'string',
alias: 'c'
});
for (const option of Object.keys(this.yargsOptions)) {
const yargsOption = this.yargsOptions[option];
let type = yargsOption.type;
if (!type) {
// infer from default
type = typeof (defaults as any)[option];
}
spec = spec.option(option, {
type,
// default: val, // clutters help output
...yargsOption
});
if (type === 'boolean') {
spec = spec.boolean(option);
}
}
opts = spec.argv;
if (typeof opts.valuesFiles === 'string') {
opts.valuesFiles = opts.valuesFiles.split(',').map((v: string) => v.trim());
}
if (opts.genExcludeResponseHeaders) {
if (typeof opts.genExcludeResponseHeaders === 'string') {
opts.genExcludeResponseHeaders = opts.genExcludeResponseHeaders
.split(',')
.map((v: string) => v.trim());
}
opts.genExcludeResponseHeaders = opts.genExcludeResponseHeaders.map((v: string) =>
v.toLowerCase()
);
}
opts.args = opts._;
delete opts._;
} else {
if (!configPath) {
configPath = findUp.sync(PLY_CONFIGS, { cwd: defaults.testsLocation });
}
opts = configPath ? this.read(configPath) : {};
}
let options = { ...defaults, ...opts };
// clean up garbage keys added by yargs, and private defaults
options = Object.keys(options).reduce((obj: any, key) => {
if (key.length > 1 && key.indexOf('_') === -1 && key.indexOf('-') === -1) {
obj[key] = options[key];
}
return obj;
}, {});
// run options
options.runOptions = {};
if (options.submit) {
options.runOptions.submit = options.submit;
delete options.submit;
}
if (options.create) {
options.runOptions.createExpected = options.create;
delete options.create;
}
if (options.trusted) {
options.runOptions.trusted = options.trusted;
delete options.trusted;
}
if (options.useDist) {
options.runOptions.useDist = options.useDist;
delete options.useDist;
}
if (options.import) {
options.runOptions.import = options.import;
delete options.import;
}
if (options.importToSuite) {
options.runOptions.importToSuite = options.importToSuite;
delete options.importToSuite;
}
if (options.report) {
options.runOptions.report = options.report;
delete options.report;
}
if (options.openapi) {
options.runOptions.openapi = options.openapi;
delete options.openapi;
}
if (options.reporter || options.runOptions.report) {
if (!process.argv.includes('-o') && !process.argv.find(av => av.startsWith('--outputFile='))) {
delete options.outputFile;
}
}
return options;
}
private read(configPath: string): object {
const retrieval = new Retrieval(configPath);
const contents = retrieval.sync();
if (typeof contents === 'string') {
if (retrieval.location.isYaml) {
return yaml.load(retrieval.location.path, contents);
} else {
return JSON.parse(contents);
}
} else {
throw new Error('Cannot load config: ' + configPath);
}
}
}