Debian Codegraph @

test/reporters/xunit.spec.js

raw symbols SCIP
1 "use strict";
2
3 var EventEmitter = require("node:events").EventEmitter;
4 var fs = require("node:fs");
5 var path = require("node:path");
6 var sinon = require("sinon");
7 var createStatsCollector = require("../../lib/stats-collector");
8 var events = require("../../").Runner.constants;
9 var reporters = require("../../").reporters;
10 var states = require("../../").Runnable.constants;
11
12 const { createTempDir, touchFile } = require("../integration/helpers");
13
14 var Base = reporters.Base;
15 var XUnit = reporters.XUnit;
16
17 var EVENT_RUN_END = events.EVENT_RUN_END;
18 var EVENT_TEST_END = events.EVENT_TEST_END;
19 var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
20 var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
21 var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
22
23 var STATE_FAILED = states.STATE_FAILED;
24 var STATE_PASSED = states.STATE_PASSED;
25
26 describe("XUnit reporter", function () {
27 var runner;
28 var noop = function () {};
29
30 var expectedLine = "some-line";
31 var expectedClassName = "fullTitle";
32 var expectedTitle = "some title";
33 var expectedFile = "testFile.spec.js";
34 var expectedMessage = "some message";
35 var expectedDiff =
36 "\n + expected - actual\n\n -foo\n +bar\n ";
37 var expectedStack = "some-stack";
38
39 beforeEach(function () {
40 runner = { on: noop, once: noop };
41 createStatsCollector(runner);
42 });
43
44 describe("when 'reporterOptions.output' is provided", function () {
45 var expectedOutput = path.join(path.sep, "path", "to", "some-output");
46 var options = {
47 reporterOptions: {
48 output: expectedOutput,
49 },
50 };
51
52 describe("when fileStream can be created", function () {
53 var fsMkdirSync;
54 var fsCreateWriteStream;
55
56 beforeEach(function () {
57 fsMkdirSync = sinon.stub(fs, "mkdirSync");
58 fsCreateWriteStream = sinon.stub(fs, "createWriteStream");
59 });
60
61 it("should open given file for writing, recursively creating directories in pathname", function () {
62 var fakeThis = {
63 fileStream: null,
64 };
65 XUnit.call(fakeThis, runner, options);
66
67 var expectedDirectory = path.dirname(expectedOutput);
68 expect(
69 fsMkdirSync.calledWith(expectedDirectory, {
70 recursive: true,
71 }),
72 "to be true",
73 );
74
75 expect(fsCreateWriteStream.calledWith(expectedOutput), "to be true");
76 });
77
78 afterEach(function () {
79 sinon.restore();
80 });
81 });
82
83 describe("when fileStream cannot be created", function () {
84 describe("when given an invalid pathname", function () {
85 /**
86 * @type {string}
87 */
88 let tmpdir;
89
90 /**
91 * @type {import('../integration/helpers').RemoveTempDirCallback}
92 */
93 let cleanup;
94 var invalidPath;
95
96 beforeEach(async function () {
97 const { dirpath, removeTempDir } = await createTempDir();
98 tmpdir = dirpath;
99 cleanup = removeTempDir;
100
101 // Create path where file 'some-file' used as directory
102 invalidPath = path.join(
103 tmpdir,
104 "some-file",
105 path.basename(expectedOutput),
106 );
107 touchFile(path.dirname(invalidPath));
108 });
109
110 it("should throw system error", function () {
111 var options = {
112 reporterOptions: {
113 output: invalidPath,
114 },
115 };
116 var boundXUnit = XUnit.bind({}, runner, options);
117 expect(
118 boundXUnit,
119 "to throw",
120 expect.it("to be an", Error).and("to satisfy", {
121 syscall: "mkdir",
122 code: "EEXIST",
123 path: path.dirname(invalidPath),
124 }),
125 );
126 });
127
128 afterEach(function () {
129 cleanup();
130 });
131 });
132
133 describe("when run in browser", function () {
134 beforeEach(function () {
135 sinon.stub(fs, "createWriteStream").value(false);
136 });
137
138 it("should throw unsupported error", function () {
139 var boundXUnit = XUnit.bind({}, runner, options);
140 expect(
141 boundXUnit,
142 "to throw",
143 "file output not supported in browser",
144 );
145 });
146
147 afterEach(function () {
148 sinon.restore();
149 });
150 });
151 });
152 });
153
154 describe("event handlers", function () {
155 describe("on 'pending', 'pass' and 'fail' events", function () {
156 it("should add test to tests called on 'end' event", function () {
157 var pendingTest = {
158 name: "pending",
159 slow: noop,
160 };
161 var failTest = {
162 name: "fail",
163 slow: noop,
164 };
165 var passTest = {
166 name: "pass",
167 slow: noop,
168 };
169 runner.on = runner.once = function (event, callback) {
170 if (event === EVENT_TEST_PENDING) {
171 callback(pendingTest);
172 } else if (event === EVENT_TEST_PASS) {
173 callback(passTest);
174 } else if (event === EVENT_TEST_FAIL) {
175 callback(failTest);
176 } else if (event === EVENT_RUN_END) {
177 callback();
178 }
179 };
180
181 var calledTests = [];
182 var fakeThis = {
183 write: noop,
184 test: function (test) {
185 calledTests.push(test);
186 },
187 };
188 XUnit.call(fakeThis, runner);
189
190 var expectedCalledTests = [pendingTest, passTest, failTest];
191 expect(calledTests, "to equal", expectedCalledTests);
192 });
193 });
194 });
195
196 describe("#done", function () {
197 var xunit;
198 var options = {
199 reporterOptions: {},
200 };
201 var expectedNFailures = 13;
202 var callback;
203
204 beforeEach(function () {
205 callback = sinon.spy();
206 });
207
208 afterEach(function () {
209 callback = null;
210 xunit = null;
211 sinon.restore();
212 });
213
214 describe("when output directed to file", function () {
215 var fakeThis;
216
217 beforeEach(function () {
218 xunit = new XUnit(runner, options);
219
220 fakeThis = {
221 fileStream: {
222 end: sinon.stub().callsFake(function (chunk, encoding, cb) {
223 if (typeof arguments[0] === "function") {
224 cb = arguments[0];
225 }
226 cb();
227 }),
228 write: function () {},
229 },
230 };
231 });
232
233 it("should run completion callback via 'fileStream.end'", function () {
234 xunit.done.call(fakeThis, expectedNFailures, callback);
235
236 expect(fakeThis.fileStream.end.calledOnce, "to be true");
237 expect(callback.calledOnce, "to be true");
238 expect(callback.calledWith(expectedNFailures), "to be true");
239 });
240 });
241
242 describe("when output directed to stdout (or console)", function () {
243 var fakeThis;
244
245 beforeEach(function () {
246 xunit = new XUnit(runner, options);
247 fakeThis = {};
248 });
249
250 it("should run completion callback", function () {
251 xunit.done.call(fakeThis, expectedNFailures, callback);
252
253 expect(callback.calledOnce, "to be true");
254 expect(callback.calledWith(expectedNFailures), "to be true");
255 });
256 });
257 });
258
259 describe("#write", function () {
260 // :TODO: Method should be named 'writeln', not 'write'
261 describe("when output directed to file", function () {
262 var fileStream = {
263 write: sinon.spy(),
264 };
265
266 it("should call 'fileStream.write' with line and newline", function () {
267 var xunit = new XUnit(runner);
268 var fakeThis = { fileStream };
269 xunit.write.call(fakeThis, expectedLine);
270
271 expect(fileStream.write.calledWith(expectedLine + "\n"), "to be true");
272 });
273 });
274
275 describe("when output directed to stdout", function () {
276 it("should call 'process.stdout.write' with line and newline", function () {
277 var xunit = new XUnit(runner);
278 var fakeThis = { fileStream: false };
279 var stdoutWriteStub = sinon.stub(process.stdout, "write");
280 xunit.write.call(fakeThis, expectedLine);
281 stdoutWriteStub.restore();
282
283 expect(stdoutWriteStub.calledWith(expectedLine + "\n"), "to be true");
284 });
285 });
286
287 describe("when output directed to console", function () {
288 it("should call 'Base.consoleLog' with line", function () {
289 // :TODO: XUnit needs a trivially testable means to force console.log()
290 var realProcess = process;
291 process = false; // eslint-disable-line no-native-reassign, no-global-assign
292
293 var xunit = new XUnit(runner);
294 var fakeThis = { fileStream: false };
295 var consoleLogStub = sinon.stub(Base, "consoleLog");
296 xunit.write.call(fakeThis, expectedLine);
297 consoleLogStub.restore();
298
299 process = realProcess; // eslint-disable-line no-native-reassign, no-global-assign
300
301 expect(consoleLogStub.calledWith(expectedLine), "to be true");
302 });
303 });
304 });
305
306 describe("#test", function () {
307 var expectedWrite;
308 var fakeThis = {
309 write: function (str) {
310 expectedWrite = str;
311 },
312 };
313
314 beforeEach(function () {
315 sinon.stub(Base, "useColors").value(false);
316 });
317
318 afterEach(function () {
319 sinon.restore();
320 expectedWrite = null;
321 });
322
323 describe("on test failure", function () {
324 it("should write expected tag with error details", function () {
325 var xunit = new XUnit(runner);
326 var expectedTest = {
327 state: STATE_FAILED,
328 title: expectedTitle,
329 file: expectedFile,
330 parent: {
331 fullTitle: function () {
332 return expectedClassName;
333 },
334 },
335 duration: 1000,
336 err: {
337 actual: "foo",
338 expected: "bar",
339 message: expectedMessage,
340 stack: expectedStack,
341 },
342 };
343
344 xunit.test.call(fakeThis, expectedTest);
345 sinon.restore();
346
347 var expectedTag =
348 '<testcase classname="' +
349 expectedClassName +
350 '" name="' +
351 expectedTitle +
352 '" file="' +
353 expectedFile +
354 '" time="1"><failure>' +
355 expectedMessage +
356 "\n" +
357 expectedDiff +
358 "\n" +
359 expectedStack +
360 "</failure></testcase>";
361 expect(expectedWrite, "to be", expectedTag);
362 });
363
364 it("should handle non-string diff values", function () {
365 var runner = new EventEmitter();
366 createStatsCollector(runner);
367 var xunit = new XUnit(runner);
368
369 var expectedTest = {
370 state: STATE_FAILED,
371 title: expectedTitle,
372 file: expectedFile,
373 parent: {
374 fullTitle: function () {
375 return expectedClassName;
376 },
377 },
378 duration: 1000,
379 err: {
380 actual: 1,
381 expected: 2,
382 message: expectedMessage,
383 stack: expectedStack,
384 },
385 };
386
387 sinon.stub(xunit, "write").callsFake(function (str) {
388 expectedWrite += str;
389 });
390
391 runner.emit(EVENT_TEST_FAIL, expectedTest, expectedTest.err);
392 runner.emit(EVENT_RUN_END);
393 sinon.restore();
394
395 var expectedDiff =
396 "\n + expected - actual\n\n -1\n +2\n ";
397
398 expect(expectedWrite, "to contain", expectedDiff);
399 });
400 });
401
402 describe("on test pending", function () {
403 it("should write expected tag", function () {
404 var xunit = new XUnit(runner);
405 var expectedTest = {
406 isPending: function () {
407 return true;
408 },
409 title: expectedTitle,
410 file: expectedFile,
411 parent: {
412 fullTitle: function () {
413 return expectedClassName;
414 },
415 },
416 duration: 1000,
417 };
418
419 xunit.test.call(fakeThis, expectedTest);
420 sinon.restore();
421
422 var expectedTag =
423 '<testcase classname="' +
424 expectedClassName +
425 '" name="' +
426 expectedTitle +
427 '" file="' +
428 expectedFile +
429 '" time="1"><skipped/></testcase>';
430 expect(expectedWrite, "to be", expectedTag);
431 });
432 });
433
434 describe("on test in any other state", function () {
435 it("should write expected tag", function () {
436 var xunit = new XUnit(runner);
437 var expectedTest = {
438 isPending: function () {
439 return false;
440 },
441 title: expectedTitle,
442 file: expectedFile,
443 parent: {
444 fullTitle: function () {
445 return expectedClassName;
446 },
447 },
448 duration: false,
449 };
450
451 xunit.test.call(fakeThis, expectedTest);
452 sinon.restore();
453
454 var expectedTag =
455 '<testcase classname="' +
456 expectedClassName +
457 '" name="' +
458 expectedTitle +
459 '" file="' +
460 expectedFile +
461 '" time="0"/>';
462 expect(expectedWrite, "to be", expectedTag);
463 });
464 });
465
466 it("should write expected summary statistics", function () {
467 var numTests = 0;
468 var numPass = 0;
469 var numFail = 0;
470 var simpleError = {
471 actual: "foo",
472 expected: "bar",
473 message: expectedMessage,
474 stack: expectedStack,
475 };
476 var generateTest = function (passed) {
477 numTests++;
478 if (passed) {
479 numPass++;
480 } else {
481 numFail++;
482 }
483 return {
484 title: [expectedTitle, numTests].join(": "),
485 state: passed ? STATE_PASSED : STATE_FAILED,
486 isPending: function () {
487 return false;
488 },
489 slow: function () {
490 return false;
491 },
492 parent: {
493 fullTitle: function () {
494 return expectedClassName;
495 },
496 },
497 duration: 1000,
498 };
499 };
500
501 var runner = new EventEmitter();
502 createStatsCollector(runner);
503 var xunit = new XUnit(runner);
504 expectedWrite = "";
505 sinon.stub(xunit, "write").callsFake(function (str) {
506 expectedWrite += str;
507 });
508
509 // 3 tests, no failures (i.e. tests that could not run), and 2 errors
510 runner.emit(EVENT_TEST_PASS, generateTest(true));
511 runner.emit(EVENT_TEST_END);
512 runner.emit(EVENT_TEST_FAIL, generateTest(false), simpleError);
513 runner.emit(EVENT_TEST_END);
514 runner.emit(EVENT_TEST_FAIL, generateTest(false), simpleError);
515 runner.emit(EVENT_TEST_END);
516 runner.emit(EVENT_RUN_END);
517
518 sinon.restore();
519
520 var expectedNumPass = 1;
521 var expectedNumFail = 2;
522 var expectedNumTests = 3;
523
524 expect(expectedNumPass, "to be", numPass);
525 expect(expectedNumFail, "to be", numFail);
526 expect(expectedNumTests, "to be", numTests);
527
528 // :NOTE: Mocha test "fail" is an XUnit "error"
529 var expectedTag =
530 '<testsuite name="Mocha Tests" tests="3" failures="0" errors="2" skipped="0"';
531
532 expect(expectedWrite, "to contain", expectedTag);
533 expect(expectedWrite, "to contain", "</testsuite>");
534 });
535 });
536
537 describe("suite name", function () {
538 // Capture the events that the reporter subscribes to
539 var events = {};
540 // Capture output lines (will contain the resulting XML of XUnit reporter)
541 var lines = [];
542 // File stream into which the XUnit reporter will write
543 var fileStream;
544
545 before(function () {
546 fileStream = {
547 write: function (chunk) {
548 lines.push(chunk);
549 },
550 };
551 });
552
553 beforeEach(function () {
554 lines = [];
555 events = {};
556
557 runner.on = runner.once = function (eventName, eventHandler) {
558 // Capture the event handler
559 events[eventName] = eventHandler;
560 };
561 });
562
563 it("should use custom name if provided via reporter options", function () {
564 var customSuiteName = "Mocha Is Great!";
565 var options = {
566 reporterOptions: {
567 suiteName: customSuiteName,
568 },
569 };
570
571 var xunit = new XUnit(runner, options);
572 xunit.fileStream = fileStream;
573
574 // Trigger end event to force XUnit reporter to write its output
575 events[EVENT_RUN_END]();
576
577 expect(lines[0], "to contain", customSuiteName);
578 });
579
580 it("should use default name otherwise", function () {
581 var defaultSuiteName = "Mocha Tests";
582 var options = {
583 reporterOptions: {},
584 };
585
586 var xunit = new XUnit(runner, options);
587 xunit.fileStream = fileStream;
588
589 // Trigger end event to force XUnit reporter to write its output
590 events[EVENT_RUN_END]();
591
592 expect(lines[0], "to contain", defaultSuiteName);
593 });
594 });
595
596 describe("showRelativePaths reporter option", function () {
597 const projectPath = path.join("home", "username", "demo-project");
598 const relativeTestPath = path.join("tests", "demo-test.spec.js");
599 const absoluteTestPath = path.join(projectPath, relativeTestPath);
600
601 var expectedWrite = "";
602 const fakeThis = {
603 write: function (str) {
604 expectedWrite = expectedWrite + str;
605 },
606 };
607
608 const failingTest = {
609 state: STATE_FAILED,
610 title: expectedTitle,
611 file: absoluteTestPath,
612 parent: {
613 fullTitle: function () {
614 return expectedClassName;
615 },
616 },
617 duration: 1000,
618 err: {
619 actual: "foo",
620 expected: "bar",
621 message: expectedMessage,
622 stack: expectedStack,
623 },
624 };
625
626 beforeEach(function () {
627 sinon.stub(process, "cwd").returns(projectPath);
628 });
629
630 afterEach(function () {
631 sinon.restore();
632 expectedWrite = "";
633 });
634
635 it("shows relative paths for tests if showRelativePaths reporter option is set", function () {
636 const options = {
637 reporterOptions: {
638 showRelativePaths: true,
639 },
640 };
641 const xunit = new XUnit(runner, options);
642
643 xunit.test.call(fakeThis, failingTest, options);
644
645 expect(expectedWrite, "not to contain", absoluteTestPath);
646 expect(expectedWrite, "to contain", relativeTestPath);
647 });
648
649 it("shows absolute paths for tests by default", function () {
650 const options = {};
651 const xunit = new XUnit(runner);
652
653 xunit.test.call(fakeThis, failingTest, options);
654
655 expect(expectedWrite, "to contain", absoluteTestPath);
656 // Double quote included to ensure printed paths don't start with relative path. Example printed line: <testcase classname="suite" name="test" file="some/tesfile.js" time="0"/>
657 expect(expectedWrite, "not to contain", `"${relativeTestPath}`);
658 });
659 });
660 });