-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
912 lines (782 loc) · 27.5 KB
/
main.js
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
"use strict";
const fs = require("fs");
const path = require("path");
const Mocha = require("mocha");
const Electron = require("electron");
const utils = require("./utils.js");
const {New, addTo, regexFromString, wait} = utils;
class AtomMocha{
constructor(args){
// Initialise Atom's test environment
global.AtomMocha = this;
this.headless = args.headless;
this.isCI =
!!(process.env.CI
|| process.env.CONTINUOUS_INTEGRATION
|| process.env.BUILD_NUMBER
|| process.env.TRAVIS_JOB_ID
|| process.env.GITHUB_ACTIONS
|| process.env.GITLAB_CI
|| process.env.APPVEYOR
|| process.env.RUN_ID);
this.utils = utils;
this.setup(args);
// Load and manage configuration
this.files = this.getFiles(args.testPaths);
this.options = this.getOptions(this.files, args);
this.files = this.filterSpecs(this.files.specs);
// Activate extensions, unless instructed not to
this.options.noExtensions || require("./extensions");
// Talk to Mocha
this.mocha = new Mocha(this.options);
this.reporter = this.mocha._reporter;
this.setupTestHooks();
// Tell it what specs to load
this.files.forEach(s => this.mocha.addFile(s));
// Prep the spec-runner window if we're using Mocha's HTML reporter
if("html" === this.options.reporter){
document.querySelector("atom-styles").remove();
addTo(document.body)(New("div", {id: "mocha"}));
addTo(document.head)(New("link", {
type: "text/css",
rel: "stylesheet",
href: require.resolve("mocha/mocha.css"),
}));
}
}
/** Configure Atom's test environment */
setup(args){
const applicationDelegate = args.buildDefaultApplicationDelegate();
window.atom = args.buildAtomEnvironment({
applicationDelegate,
window,
document,
configDirPath: process.env.ATOM_HOME,
enablePersistence: false,
});
// Shiv to let Mocha print to STDOUT/STDERR with unmangled feedback
if(this.headless){
const {remote} = Electron;
const {format} = require("util");
Object.defineProperties(process, {
stdout: {value: remote.process.stdout},
stderr: {value: remote.process.stderr},
});
const stdout = (...x) => process.stdout.write(format(...x) + "\n");
const stderr = (...x) => process.stderr.write(format(...x) + "\n");
console.info = console.log = stdout;
console.warn = console.error = stderr;
// Terminate with correct status on interrupt
remote.process.on("SIGINT", () => {
process.stdout.write("\n");
if(this.runner) this.runner.abort();
remote.process.exit(130);
});
}
}
/**
* Locate specs and configs in the specified directories.
*
* The returned object contains two arrays: "specs" and "opts",
* for loaded spec files and `mocha.opts` files, respectively.
*
* @param {Array} paths
* @return {Object}
*/
getFiles(paths){
const specs = [];
const opts = [];
for(const testPath of paths){
const stats = fs.statSync(testPath);
// Individually-specified file
if(stats.isFile()){
// This is an options file, not a spec
if(this.isOptionsFile(testPath))
opts.push(testPath);
else specs.push(testPath);
}
// Folder of specs and possible configuration files
else if(stats.isDirectory()){
for(const file of fs.readdirSync(testPath)){
const filePath = path.join(testPath, file);
if(fs.statSync(filePath).isFile()){
if(this.isOptionsFile(file))
opts.push(filePath);
// Toss it in as a spec, we'll filter it later
else specs.push(filePath);
}
}
}
}
return {specs, opts};
}
/**
* Load and resolve runtime options, handling defaults when necessary.
*
* @param {Array} files - Paths loaded by getFiles()
* @param {Object} args - Arguments supplied by Atom's test-runner API
* @return {Object} An object to pass directly to Mocha
*/
getOptions(files, args){
const {specs, opts} = files;
const {findBasePath} = utils;
const opt = {
// Spec-runner options
autoIt: true,
autoScroll: true,
formatCode: true,
escapeHTML: true,
clipPaths: true,
linkPaths: true,
slide: true,
minimal: false,
title: "Mocha",
// Mocha options
bail: false,
color: true,
fgrep: null,
grep: null,
reporter: "spec",
reporterOptions: {},
require: [],
retries: 0,
slow: 75,
timeout: 2000,
ui: "bdd",
};
// Locate the package's "package.json" file
let basePath = findBasePath([...specs, ...opts]);
while(basePath && basePath !== "/"){
const packagePath = path.join(basePath, "package.json");
if(fs.existsSync(packagePath)){
// If there's a `.mocharc.*` file in the package's base directory, load it
for(const ext of ["js", "yaml", "yml", "json", "jsonc"]){
const file = path.join(basePath, `.mocharc.${ext}`);
if(fs.existsSync(file)){
this.readOptionsFile(opt, file);
break;
}
}
try{
let data = require(packagePath);
this.packagePath = basePath;
// Assign options from an object read from package.json
const grabOptions = data => {
Object.assign(opt, data.mocha || {});
// Load Atom-Mocha's options
if(null != data.slide) opt.slide = data.slide;
if(null != data.title) opt.title = data.title;
if(null != data.autoIt) opt.autoIt = data.autoIt;
if(null != data.minimal) opt.minimal = data.minimal;
if(null != data.clipPaths) opt.clipPaths = data.clipPaths;
if(null != data.linkPaths) opt.linkPaths = data.linkPaths;
if(null != data.formatCode) opt.formatCode = data.formatCode;
if(null != data.escapeHTML) opt.escapeHTML = data.escapeHTML;
if(null != data.escapeHtml) opt.escapeHTML = data.escapeHtml;
if(null != data.autoScroll) opt.autoScroll = data.autoScroll;
if(null != data.hidePending) opt.hidePending = data.hidePending;
if(null != data.hideStatBar) opt.hideStatBar = data.hideStatBar;
if(null != data.specPattern) opt.specPattern = data.specPattern;
if(null != data.stackFilter) opt.stackFilter = data.stackFilter;
if(null != data.noExtensions) opt.noExtensions = data.noExtensions;
if(null != data.beforeTest) opt.beforeTest = data.beforeTest;
if(null != data.afterTest) opt.afterTest = data.afterTest;
if(null != data.onTest) opt.afterTest = data.onTest;
if(null != data.onFail) opt.onFail = data.onFail;
if(null != data.onPass) opt.onPass = data.onPass;
if(null != data.js) opt.js = this.mergeAssets(opt.js, this.resolveAssets(data.js, this.packagePath));
if(null != data.css) opt.css = this.mergeAssets(opt.css, this.resolveAssets(data.css, this.packagePath));
// Paths to additional specs/options
let {tests, optFiles} = data, extraPaths;
tests = Array.isArray(tests) ? tests : (tests ? [tests] : []);
optFiles = Array.isArray(optFiles) ? optFiles : (optFiles ? [optFiles] : []);
extraPaths = tests.concat(optFiles);
// If any were found, push them onto our existing lists
if(extraPaths.length){
extraPaths = this.getFiles(extraPaths.map(p => path.resolve(basePath, p)));
if(extraPaths.opts.length) opts.push(...extraPaths.opts);
if(extraPaths.specs.length) files.specs.push(...extraPaths.specs);
}
};
// We have options described in package.json
if(data = data["atom-mocha"]){
grabOptions(data);
// Load any mode-specific options
if(!args.headless && data.interactive) grabOptions(data.interactive);
if(args.headless && data.headless) grabOptions(data.headless);
}
}
catch(e){ console.error(e); }
break;
}
basePath = path.dirname(basePath);
}
// Load externally-defined options
opts.forEach(file => this.readOptionsFile(opt, file));
// Make sure patterns are actual regular expressions.
opt.specPattern = regexFromString(opt.specPattern) || /[-_.](?:spec|test)\.(?:coffee|[jt]sx?)$/i;
opt.stackFilter = regexFromString(opt.stackFilter) || /node_modules([\\/])mocha(?:\1|\.js|[:)])/;
// Load specs in subdirectories if --recursive is enabled
if(opt.recursive){
const dirs = new Set([
...files.specs.map(file => path.dirname(file)),
...files.opts.map(file => path.dirname(file)),
]);
const load = dirPath => {
fs.statSync(dirPath).isDirectory() && fs.readdirSync(dirPath).forEach(entity => {
if(~files.specs.indexOf(entity = path.join(dirPath, entity))) return;
const realPath = fs.realpathSync(entity);
const stats = fs.statSync(entity);
if(stats.isDirectory() && !dirs.has(realPath)){
dirs.add(realPath);
load(entity);
}
else if(stats.isFile() && opt.specPattern.test(entity))
files.specs.push(entity);
});
};
[...dirs].forEach(load);
files.specs.sort();
}
// Load any --require'd resources
if(opt.require && opt.require.length){
if(!Array.isArray(opt.require))
opt.require = [opt.require];
for(let file of opt.require)
try{
if(/^chai\/(assert|expect|should)$/.test(file))
file = "chai/register-" + RegExp.lastParen;
require(file);
}
catch(e){
console.error(e);
}
}
// Negate some boolean options that're enabled by default
if(opt.noAutoScroll) opt.autoScroll = false;
if(opt.noClipPaths) opt.clipPaths = false;
if(opt.noLinkPaths) opt.linkPaths = false;
if(opt.noFormatCode) opt.formatCode = false;
if(opt.noSlide) opt.slide = false;
if(opt.noEscapeHTML || opt.noEscapeHtml)
opt.escapeHTML = false;
// Don't enable the "autoIt" option unless BDD is being used
if(opt.autoIt && ("bdd" !== opt.ui && null != opt.ui))
opt.autoIt = false;
// Disable coloured output if output is redirected
if(!Electron.remote.process.stdout.isTTY)
opt.color = false;
// Resolve colour override
const override = this.resolveColourOverride();
if(null != override)
opt.color = override;
// Always disable colours when running interactively
if(!args.headless){
opt.color = false;
// Use default reporter if unspecified (or a console-only reporter)
switch(opt.reporter){
case "json-stream":
case "json":
case "landing":
case "list":
case "markdown":
case "min":
case "doc":
case "nyan":
case "progress":
case "spec":
case "tap":
case "xunit":
case undefined:
case null:
opt.reporter = "atom";
break;
// Activate minimal-mode if requesting the "dot" reporter
case "dot":
opt.minimal = true;
opt.reporter = "atom";
break;
}
}
// Don't try using an HTML reporter when running headlessly
else if("atom" === opt.reporter || "html" === opt.reporter)
opt.reporter = "spec";
// Finally, replace "atom" with a working instance of the default reporter
if("atom" === opt.reporter)
opt.reporter = require("./reporter");
// Stop commas showing between words for multi-word titles
if(Array.isArray(opt.title))
opt.title = opt.title.join(" ");
// Store the package's directory for the "clipPaths" option
opt.packagePath = this.packagePath;
return opt;
}
/**
* Determine whether a pathname would be recognised by Mocha as an options file.
*
* @param {String} path
* @return {Boolean}
* @internal
*/
isOptionsFile(path){
return /(?:^|[\\/])(?:\.mocharc\.(?:js|jsonc?|ya?ml)|mocha\.opts)$/.test(path);
}
/**
* Load options from a `.mocharc.*` or `mocha.opts` file.
*
* @param {Object} target - Object to store parsed options upon
* @param {String} file - Path to options file
* @return {Object}
* @internal
*/
readOptionsFile(target, file){
const {loadRc, loadMochaOpts} = require("mocha/lib/cli/options");
const mochaOpts = "mocha.opts" === path.basename(file)
? loadMochaOpts({opts: file})
: loadRc({config: file});
delete mochaOpts._;
// Convert "kebab-cased" keys to camelCase
const keys = "autoIt autoScroll clipPaths escapeHtml formatCode hidePending hideStatBar linkPaths noExtensions specPattern stackFilter";
for(const key of keys.split(" ")){
let kebab = key.replace(/([a-z]+)([A-Z])/g, (_, a, B) => `${a}-${B}`).toLowerCase();
if(kebab in mochaOpts || (kebab = "no-" + kebab) in mochaOpts){
mochaOpts[key] = mochaOpts[kebab];
delete mochaOpts[kebab];
}
}
// Resolve any --require'd modules relative to options file
const arrayify = x => Array.isArray(x) ? x : [x];
if(mochaOpts.require && mochaOpts.require.length){
target.require = arrayify(target.require);
const req = arrayify(mochaOpts.require)
.filter(s => s && !~target.require.indexOf(s))
.map(spec => /^\.+(?:[\\/]|$)|^[\\/]/.test(spec)
? path.resolve(path.dirname(file), spec)
: spec)
.filter(s => s && !~target.require.indexOf(s));
target.require.push(...req);
}
delete mochaOpts.require;
// Resolve any CSS/JS paths relative to options file
if(mochaOpts.css) target.css = this.mergeAssets(target.css, this.resolveAssets(mochaOpts.css, path.dirname(file)));
if(mochaOpts.js) target.js = this.mergeAssets(target.js, this.resolveAssets(mochaOpts.js, path.dirname(file)));
delete mochaOpts.css;
delete mochaOpts.js;
Object.assign(target, mochaOpts);
}
/**
* Purge an array of files that aren't specs.
*
* Because package.json is loaded *after* the testPaths have been scanned, it has the
* potential to modify the "specPattern" property that governs which files are picked
* up as specs. We do things this way because the testPaths determine where to search
* for package.json… and we can't always rely on the CWD to tell us where to look.
*
* @param {Array} paths
* @return {Array}
*/
filterSpecs(paths){
const specs = [];
const {specPattern} = this.options;
for(const path of paths)
if(specPattern.test(path))
specs.push(path);
return specs;
}
/**
* Attach any user-defined scripts or stylesheets.
*
* @param {Object} assets - Hash holding CSS/JS paths
* @return {Promise}
* @private
*/
attachAssets(assets){
return new Promise(resolve => {
if(assets.css){
const {header, footer} = assets.css;
if(header) header.forEach(s => this.attachStyle(s));
if(footer) footer.forEach(s => this.attachStyle(s, true));
}
if(assets.js){
const {header, footer} = assets.js;
if(header) header.forEach(s => this.attachScript(s));
if(footer) footer.forEach(s => this.attachScript(s, true));
}
resolve();
});
}
/**
* Attach a user-supplied script to the test-runner environment.
*
* @param {String} path - Absolute path to script
* @param {Boolean} footer - Append to <html> instead of <head>
* @return {HTMLScriptElement}
* @private
*/
attachScript(path, footer = false){
const el = New("script", {
src: path,
type: /\.coffee$/i.test(path)
? "text/coffeescript"
: "application/javascript",
});
addTo(footer ? document.documentElement : document.head)(el);
return el;
}
/**
* Attach a user-supplied stylesheet to the test-runner environment.
*
* @param {String} path - Absolute path to stylesheet
* @param {Boolean} footer - Append to <html> instead of <head>
* @return {HTMLStyleElement}
* @private
*/
attachStyle(path, footer = false){
const el = New("link", {
type: "text/css",
href: path,
rel: /\.less$/i.test(path)
? "stylesheet/less"
: "stylesheet",
});
addTo(footer ? document.documentElement : document.head)(el);
return el;
}
/**
* Normalise asset paths relative to a given directory.
*
* @param {Mixed} paths - Either a string, array or object
* @param {String} against - Path to resolve relative paths against
* @return {Object}
* @private
*/
resolveAssets(paths, against){
if(!paths) return null;
// Box any paths supplied as strings or arrays
if("string" === typeof paths) paths = {header: [paths]};
else if(Array.isArray(paths)) paths = {header: paths};
else{
if("string" === typeof paths.header) paths.header = [paths.header];
if("string" === typeof paths.footer) paths.footer = [paths.footer];
if(!paths.header && !paths.footer) return null;
}
// Resolve asset paths relative to a directory
if(against)
for(const k in paths) if(paths[k])
paths[k] = paths[k].map(p => path.resolve(against, p));
return paths;
}
/**
* Merge a normalised assets object into another.
*
* @param {Object} into - An object holding previously-resolved paths
* @param {Object} from - The new data to append
* @return {Object}
* @private
*/
mergeAssets(into, from){
if(!into) return from;
if(!from) return into;
if(from.header) into.header = (into.header || []).concat(from.header);
if(from.footer) into.footer = (into.footer || []).concat(from.footer);
return into;
}
/**
* Start Mocha. Called by Atom's test-runner API.
*
* The returned promise *must* resolve with an exit code, even if tests
* were unsuccessful. Returning a rejected promise will hang the process.
*
* @return {Promise<number>}
* @private
*/
run(){
return new Promise(async resolve => {
const runHook = async name => {
try{
if("function" === typeof this.options[name]) await this.options[name](this);
if("function" === typeof this.reporter[name]) await this.reporter[name](this);
} catch(error){
this.displayError(error, `In "${name}" hook:`);
return resolve(1), false;
}
return true;
};
// Run `beforeStart` callback(s)
if(!await runHook("beforeStart")) return;
// Add user-supplied DOM juice
await this.attachAssets(this.options);
// Start the actual tests
this.runner = this.mocha.run(failures => {
try{
if("function" === typeof this.options.beforeFinish)
return resolve(this.options.beforeFinish(failures));
} catch(error){
this.displayError(error, 'In "beforeFinish" hook:');
return resolve(Math.max(1, failures));
}
return resolve(failures);
});
// Run `afterStart` callback(s)
runHook("afterStart");
}).catch(error => {
this.displayError(error, "Unexpected error");
return 1;
});
}
/**
* Display an error caught whilst executing a lifecycle event handler.
*
* @param {Error|String} error
* @param {String} [title=""]
* @private
*/
displayError(error, title = ""){
if(this.headless){
title && console.error(" " + String(title));
error = this.formatError(error).replace(/^/gm, " ".repeat(title ? 4 : 2));
console.error(error);
}
else{
console.error(error);
const mocha = document.querySelector("#mocha");
// Default reporter: Display a properly-formatted stack-trace
if(mocha && mocha.reporter instanceof require("./reporter.js")){
const {report} = mocha.reporter;
const div = addTo(report)
(New("div", {className: "error-message"}))
(title && New("h1", {className: "error-title", textContent: title}))[1];
addTo(div)(error instanceof Error
? mocha.reporter.createErrorBlock(error)
: New("div", {className: "error-block", textContent: error}));
if(this.options.autoScroll)
report.scrollTop = report.scrollHeight;
}
// Other HTML-based reporters: Just stringify the error in a <pre> block
else addTo(document.querySelector("#mocha-report") || mocha || document.body)
(New("div", {className: "test error message"}))(
New("h1", {className: "error-title", textContent: title}),
New("pre", {error,
className: "error-message error",
textContent: error.stack
? Mocha.utils.stackTraceFilter()(error.stack)
: String(error),
})
);
}
}
/**
* Format an {@link Error} with ANSI escapes for terminal display.
*
* @param {Error} error
* @return {String}
* @private
*/
formatError(error){
const {generateDiff, color:colour} = Mocha.reporters.Base;
if(error instanceof Error){
const {inlineDiffs, stringify, stackTraceFilter} = Mocha.utils;
let result = colour("error message", `${error.name}: ${error.message}`) + "\n";
let indent = " ";
// Generate an inline diff if this error has `expected`/`actual` properties
const exp = stringify(error.expected);
const act = stringify(error.actual);
if(false !== error.showDiff && undefined !== error.expected && act !== exp){
Mocha.utils.inlineDiffs = true;
result += utils.deindent(generateDiff(act, exp)) + "\n\n";
Mocha.utils.inlineDiffs = inlineDiffs;
indent = "";
}
return result + colour("error stack", stackTraceFilter()(error.stack)
.split(/\n+/g)
.map(line => line.trim())
.filter(line => line && !~line.indexOf(error.message))
.join("\n"))
.replace(/^/gm, indent);
}
else return colour("error message", String(error));
}
/**
* Resolve environment variables for overriding terminal colour support.
*
* Much of the functionality for ascertaining colour support is already provided by
* the `supports-color` module Mocha uses. We check only for alternate spellings and
* lesser-known "dumb" terminals, plus CI environments not (yet) known by upstream.
*
* @see {@link https://invisible-island.net/ncurses/terminfo.ti.html#toc-_Specials}
* @param {Object} [env=process.env]
* @return {Boolean?} True if forcefully enabled, false if forcefully disabled, and null if neither.
* @private
*/
resolveColourOverride({env} = process){
const forced =
undefined !== env.FORCE_COLOR ? env.FORCE_COLOR :
undefined !== env.FORCE_COLOUR ? env.FORCE_COLOUR :
undefined;
switch(forced){
case true: case "true": case "":
case "1": case 1: case 1n: return 16; // 16-colour support
case "2": case 2: case 2n: return 256; // 256-colour support
case "3": case 3: case 3n: return 16000000; // 24-bit (true colour) support
}
const disabled =
undefined !== env.NO_COLOR ? env.NO_COLOR :
undefined !== env.NO_COLOUR ? env.NO_COLOUR :
undefined !== env.NODE_DISABLE_COLORS ? env.NODE_DISABLE_COLORS :
undefined !== env.NODE_DISABLE_COLOURS ? env.NODE_DISABLE_COLOURS :
undefined;
if(undefined !== disabled)
return false;
switch(env.TERM || ""){
case "":
case "dumb":
case "unknown":
case "lpr":
case "printer":
case "glasstty":
case "vanilla":
return false;
}
if(env.CI) return (
"codeship" === env.CI_NAME
|| env.TRAVIS
|| env.CIRCLECI
|| env.APPVEYOR
|| env.GITLAB_CI
|| env.GITHUB_ACTIONS
);
return null;
}
/**
* Prepare a destination for writing snapshot files to.
*
* @example AtomMocha.resolveSnapshotPath("/tmp") == "/tmp/atom-712-1628352650081";
* @example AtomMocha.resolveSnapshotPath("/tmp/existing-file") == "/tmp/existing-file.1";
* @param {String} input
* @return {String}
* @private
*/
resolveSnapshotPath(input){
if(!path.isAbsolute(input)){
const root = this.options.packagePath || path.resolve(__dirname, "..");
input = path.resolve(root, input);
}
if(fs.existsSync(input)){
if(fs.statSync(input).isDirectory())
input = path.join(input, `atom-${process.pid}-${Date.now()}`);
let count = 1;
const originalPath = input;
while(fs.existsSync(input + ".html") || fs.existsSync(input + ".png"))
input = `${originalPath}.${count++}`;
return input;
}
const dir = path.dirname(input);
fs.existsSync(dir) || fs.mkdirSync(dir, {recursive: true});
return input;
}
/**
* Record a screenshot of the current workspace and save the current DOM state.
*
* @throws {Error} Raises an exception if the `<atom-workspace>` element hasn't
* been {@link attachToDOM|attached to the DOM} — it makes little sense to take
* a screen-capture of an empty workspace.
*
* @example AtomMocha.snapshot(".atom-mocha/snapshot") == {
* img: ".atom-mocha/snapshot.png",
* dom: ".atom-mocha/snapshot.html",
* };
* @param {String} to - Location to save the screenshot and HTML files to, sans extension
* @param {"png"|"jpg"|"pdf"} [format="png"] - Screenshot format
* @param {Number} [quality=75] - JPEG quality (0–100)
* @return {Promise<{{dom: String, img: String}}>}
*/
async snapshot(to, format = "png", quality = 75){
// Raise an exception if the Atom workspace isn't attached to the DOM
if(!document.body.contains(atom.workspace.getElement())){
const error = new Error("Workspace element not attached to DOM");
error.details = "Use `attachToDOM(atom.workspace.getElement());` to fix";
console.error(`${error.message}. ${error.details}`);
throw error;
}
// Resolve arguments
to = this.resolveSnapshotPath(to);
format = String(format).toLowerCase().replace(/^\.|(?<=^\.?jp)e(?=g$)/g, "");
quality = Math.max(0, Math.min(100, ~~quality || 0));
const paths = {img: to + "." + format, dom: to + ".html"};
// Save current DOM state
fs.writeFileSync(paths.dom, document.documentElement.outerHTML);
// Hide our reporter, if visible
const mocha = document.getElementById("mocha");
if(mocha)
mocha.style.display = "none";
await wait(100);
// Save screenshot
const image = await this.utils.captureWindow(format, quality);
fs.writeFileSync(paths.img, image, {encoding: null});
// Show our reporter again
if(mocha){
mocha.style.display = null;
mocha.getAttribute("style") || mocha.removeAttribute("style");
}
return paths;
}
/**
* Monkey-patch Mocha's {@link Mocha.Runnable} class for test-level hooks.
*
* This is necessary because async handlers need to finish resolving before
* the next runnable starts, something which is particularly important when
* taking screenshots.
*
* @return {void}
* @private
*/
setupTestHooks(){
const {options} = this;
// If we're capturing snapshots, make sure they're taken before hooks are run
if(options.snapshotDir){
const now = new Date().toISOString().replace(/:/g, "-");
const dir = path.join(path.resolve(options.packagePath, options.snapshotDir), now);
options.snapshotDir = dir;
console.debug(`Saving screen-captures of failed tests to ${dir}`);
let errors = 0;
const {onFail} = options;
options.onFail = async (test, error) => {
const ui = atom.workspace.getElement();
document.body.contains(ui) || attachToDOM(ui);
const paths = await this.snapshot(path.join(dir, String(++errors)), options.snapshotFormat || "png");
fs.writeFileSync(paths.dom.replace(/\.html?$/i, "") + ".json", JSON.stringify({
test: test.titlePath(),
file: test.file,
error: error.stack || error.toString(),
snapshot: paths,
}, null, "\t") + "\n");
if("function" === typeof onFail)
return onFail.call(options, test, error);
};
}
// Only hack Mocha if we absolutely need to
if(!"beforeTest onPass onFail afterTest".split(" ").some(name =>
"function" === typeof options[name])) return;
const {run} = Mocha.Runnable.prototype;
Mocha.Runnable.prototype.run = function(fn){
if("test" !== this.type)
return run.call(this, fn);
const runTest = () => run.call(this, (...args) => {
const hookOpts = ["onPass", "afterTest"];
const hookArgs = [this, null];
if(args[0] instanceof Error){
hookOpts[0] = "onFail";
hookArgs[1] = args[0];
}
Promise.all(hookOpts.map(opt => {
if("function" === typeof options[opt])
return options[opt](...hookArgs);
})).then(() => fn.apply(this, args));
});
if("function" === typeof options.beforeTest)
Promise.resolve(options.beforeTest(this)).then(runTest);
else return runTest();
};
}
}
module.exports = AtomMocha;