Blame view

modules/tester.js 33.1 KB
1 2 3
/*!
 * Casper is a navigation utility for PhantomJS.
 *
4
 * Documentation: http://casperjs.org/
5 6
 * Repository:    http://github.com/n1k0/casperjs
 *
7 8 9
 * Copyright (c) 2011-2012 Nicolas Perriault
 *
 * Part of source code is Copyright Joyent, Inc. and other Node contributors.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */
30

31
/*global CasperError exports phantom require __utils__*/
32

33
var fs = require('fs');
34
var events = require('events');
Nicolas Perriault authored
35
var utils = require('utils');
36
var f = utils.format;
37

38
exports.create = function create(casper, options) {
39
    "use strict";
40
    return new Tester(casper, options);
41
};
42 43 44 45

/**
 * Casper tester: makes assertions, stores test results and display then.
 *
46 47
 * @param  Casper       casper   A valid Casper instance
 * @param  Object|null  options  Options object
48
 */
49
var Tester = function Tester(casper, options) {
50
    "use strict";
51
    /*jshint maxstatements:20*/
52

53
    if (!utils.isCasperObject(casper)) {
54
        throw new CasperError("Tester needs a Casper instance");
55 56
    }

57 58
    this.casper = casper;

59 60
    this.SKIP_MESSAGE = '__termination__';

61
    this.executed = 0;
62
    this.currentTestFile = null;
63
    this.currentSuiteNum = 0;
64
    this.exporter = require('xunit').create();
Julien Moulin authored
65 66 67 68 69
    this.loadIncludes = {
        includes: [],
        pre:      [],
        post:     []
    };
70 71 72
    this.running = false;
    this.suites = [];
    this.options = utils.mergeObjects({
73
        failFast: false,  // terminates a suite as soon as a test fails?
74 75 76 77
        failText: "FAIL", // text to use for a successful test
        passText: "PASS", // text to use for a failed test
        pad:      80      // maximum number of chars for a result line
    }, options);
78 79 80 81

    // properties
    this.testResults = {
        passed: 0,
82
        failed: 0,
83
        passes: [],
84
        failures: []
85 86
    };

87
    this.configure();
88

89
    this.on('success', function onSuccess(success) {
90
        this.testResults.passes.push(success);
91
        this.exporter.addSuccess(fs.absolute(success.file), success.message || success.standard);
92 93
    });

94
    this.on('fail', function onFail(failure) {
Nicolas Perriault authored
95
        // export
96 97 98 99 100 101
        this.exporter.addFailure(
            fs.absolute(failure.file),
            failure.message  || failure.standard,
            failure.standard || "test failed",
            failure.type     || "unknown"
        );
102
        this.testResults.failures.push(failure);
Nicolas Perriault authored
103
        // special printing
104 105 106
        if (failure.type) {
            this.comment('   type: ' + failure.type);
        }
107 108
        if (failure.values && Object.keys(failure.values).length > 0) {
            for (var name in failure.values) {
109 110 111 112 113 114 115
                var comment = '   ' + name + ': ';
                var value = failure.values[name];
                try {
                    comment += utils.serialize(failure.values[name]);
                } catch (e) {
                    try {
                        comment += utils.serialize(failure.values[name].toString());
116
                    } catch (e2) {
117 118 119 120
                        comment += '(unserializable value)';
                    }
                }
                this.comment(comment);
121
            }
Nicolas Perriault authored
122
        }
123
    });
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

    // casper events
    this.casper.on('error', function onCasperError(msg, backtrace) {
        var line = 0;
        if (!utils.isString(msg) && msg.indexOf(this.SKIP_MESSAGE) === -1) {
            try {
                line = backtrace[0].line;
            } catch (e) {}
        }
        this.test.uncaughtError(msg, this.test.currentTestFile, line);
        this.test.done();
    });

    this.casper.on('step.error', function onStepError(e) {
        this.test.uncaughtError(e, this.test.currentTestFile);
        this.test.done();
    });
141
};
142

143 144 145
// Tester class is an EventEmitter
utils.inherits(Tester, events.EventEmitter);
exports.Tester = Tester;
146

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
/**
 * Asserts that a condition strictly resolves to true. Also returns an
 * "assertion object" containing useful informations about the test case
 * results.
 *
 * This method is also used as the base one used for all other `assert*`
 * family methods; supplementary informations are then passed using the
 * `context` argument.
 *
 * @param  Boolean      subject  The condition to test
 * @param  String       message  Test description
 * @param  Object|null  context  Assertion context object (Optional)
 * @return Object                An assertion result object
 */
Tester.prototype.assert = Tester.prototype.assertTrue = function assert(subject, message, context) {
    "use strict";
163
    this.executed++;
164 165 166 167 168 169 170 171 172 173 174
    return this.processAssertionResult(utils.mergeObjects({
        success:  subject === true,
        type:     "assert",
        standard: "Subject is strictly true",
        message:  message,
        file:     this.currentTestFile,
        values:  {
            subject: utils.getPropertyPath(context, 'values.subject') || subject
        }
    }, context || {}));
};
175

176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
/**
 * Asserts that two values are strictly equals.
 *
 * @param  Mixed   subject   The value to test
 * @param  Mixed   expected  The expected value
 * @param  String  message   Test description (Optional)
 * @return Object            An assertion result object
 */
Tester.prototype.assertEquals = Tester.prototype.assertEqual = function assertEquals(subject, expected, message) {
    "use strict";
    return this.assert(this.testEquals(subject, expected), message, {
        type:     "assertEquals",
        standard: "Subject equals the expected value",
        values:  {
            subject:  subject,
            expected: expected
        }
    });
};
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/**
 * Asserts that two values are strictly not equals.
 *
 * @param  Mixed        subject   The value to test
 * @param  Mixed        expected  The unwanted value
 * @param  String|null  message   Test description (Optional)
 * @return Object                 An assertion result object
 */
Tester.prototype.assertNotEquals = function assertNotEquals(subject, shouldnt, message) {
    "use strict";
    return this.assert(!this.testEquals(subject, shouldnt), message, {
        type:    "assertNotEquals",
        standard: "Subject doesn't equal what it shouldn't be",
        values:  {
            subject:  subject,
            shouldnt: shouldnt
        }
    });
};
215

216 217 218 219 220
/**
 * Asserts that a code evaluation in remote DOM resolves to true.
 *
 * @param  Function  fn       A function to be evaluated in remote DOM
 * @param  String    message  Test description
221
 * @param  Object    params   Object/Array containing the parameters to inject into the function (optional)
222 223 224 225 226 227 228 229 230 231 232 233 234
 * @return Object             An assertion result object
 */
Tester.prototype.assertEval = Tester.prototype.assertEvaluate = function assertEval(fn, message, params) {
    "use strict";
    return this.assert(this.casper.evaluate(fn, params), message, {
        type:    "assertEval",
        standard: "Evaluated function returns true",
        values: {
            fn: fn,
            params: params
        }
    });
};
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
/**
 * Asserts that the result of a code evaluation in remote DOM equals
 * an expected value.
 *
 * @param  Function     fn        The function to be evaluated in remote DOM
 * @param  Boolean      expected  The expected value
 * @param  String|null  message   Test description
 * @param  Object|null  params    Object containing the parameters to inject into the function (optional)
 * @return Object                 An assertion result object
 */
Tester.prototype.assertEvalEquals = Tester.prototype.assertEvalEqual = function assertEvalEquals(fn, expected, message, params) {
    "use strict";
    var subject = this.casper.evaluate(fn, params);
    return this.assert(this.testEquals(subject, expected), message, {
        type:    "assertEvalEquals",
        standard: "Evaluated function returns the expected value",
        values:  {
            fn: fn,
            params: params,
            subject:  subject,
            expected: expected
        }
    });
};
260

261 262 263
/**
 * Asserts that a given input field has the provided value.
 *
264 265 266 267
 * @param  String   inputName  The name attribute of the input element
 * @param  String   expected   The expected value of the input element
 * @param  String   message    Test description
 * @return Object              An assertion result object
268
 */
269
Tester.prototype.assertField = function assertField(inputName, expected,  message) {
270
    "use strict";
271 272
    var actual = this.casper.evaluate(function(inputName) {
        return __utils__.getFieldValue(inputName);
273
    }, inputName);
274
    return this.assert(this.testEquals(actual, expected),  message, {
275
        type: 'assertField',
276
        standard: f('"%s" input field has the value "%s"', inputName, expected),
277
        values:  {
278 279 280 281
            inputName: inputName,
            actual: actual,
            expected:  expected
         }
282 283
    });
};
284

285 286 287 288 289 290 291 292
/**
 * Asserts that an element matching the provided selector expression exists in
 * remote DOM.
 *
 * @param  String   selector  Selector expression
 * @param  String   message   Test description
 * @return Object             An assertion result object
 */
293
Tester.prototype.assertExists = Tester.prototype.assertExist = Tester.prototype.assertSelectorExists = Tester.prototype.assertSelectorExist = function assertExists(selector, message) {
294 295 296 297 298 299 300 301 302
    "use strict";
    return this.assert(this.casper.exists(selector), message, {
        type: "assertExists",
        standard: f("Found an element matching: %s", selector),
        values: {
            selector: selector
        }
    });
};
303

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
/**
 * Asserts that an element matching the provided selector expression does not
 * exists in remote DOM.
 *
 * @param  String   selector  Selector expression
 * @param  String   message   Test description
 * @return Object             An assertion result object
 */
Tester.prototype.assertDoesntExist = Tester.prototype.assertNotExists = function assertDoesntExist(selector, message) {
    "use strict";
    return this.assert(!this.casper.exists(selector), message, {
        type: "assertDoesntExist",
        standard: f("No element found matching selector: %s", selector),
        values: {
            selector: selector
        }
    });
};
322

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
/**
 * Asserts that current HTTP status is the one passed as argument.
 *
 * @param  Number  status   HTTP status code
 * @param  String  message  Test description
 * @return Object           An assertion result object
 */
Tester.prototype.assertHttpStatus = function assertHttpStatus(status, message) {
    "use strict";
    var currentHTTPStatus = this.casper.currentHTTPStatus;
    return this.assert(this.testEquals(this.casper.currentHTTPStatus, status), message, {
        type: "assertHttpStatus",
        standard: f("HTTP status code is: %s", status),
        values: {
            current: currentHTTPStatus,
            expected: status
        }
    });
};
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
/**
 * Asserts that a provided string matches a provided RegExp pattern.
 *
 * @param  String   subject  The string to test
 * @param  RegExp   pattern  A RegExp object instance
 * @param  String   message  Test description
 * @return Object            An assertion result object
 */
Tester.prototype.assertMatch = Tester.prototype.assertMatches = function assertMatch(subject, pattern, message) {
    "use strict";
    return this.assert(pattern.test(subject), message, {
        type: "assertMatch",
        standard: "Subject matches the provided pattern",
        values:  {
            subject: subject,
            pattern: pattern.toString()
        }
    });
};
362

363 364 365 366 367 368 369
/**
 * Asserts a condition resolves to false.
 *
 * @param  Boolean  condition  The condition to test
 * @param  String   message    Test description
 * @return Object              An assertion result object
 */
370
Tester.prototype.assertNot = Tester.prototype.assertFalse = function assertNot(condition, message) {
371 372 373 374 375 376 377 378 379
    "use strict";
    return this.assert(!condition, message, {
        type: "assertNot",
        standard: "Subject is falsy",
        values: {
            condition: condition
        }
    });
};
380

381 382 383 384 385 386 387 388 389 390 391 392 393 394
/**
 * Asserts that a selector expression is not currently visible.
 *
 * @param  String  expected  selector expression
 * @param  String  message   Test description
 * @return Object            An assertion result object
 */
Tester.prototype.assertNotVisible = Tester.prototype.assertInvisible = function assertNotVisible(selector, message) {
    "use strict";
    return this.assert(!this.casper.visible(selector), message, {
        type: "assertVisible",
        standard: "Selector is not visible",
        values: {
            selector: selector
395
        }
396 397
    });
};
398

399 400 401 402 403 404 405 406 407
/**
 * Asserts that the provided function called with the given parameters
 * will raise an exception.
 *
 * @param  Function  fn       The function to test
 * @param  Array     args     The arguments to pass to the function
 * @param  String    message  Test description
 * @return Object             An assertion result object
 */
408
Tester.prototype.assertRaises = Tester.prototype.assertRaise = Tester.prototype.assertThrows = function assertRaises(fn, args, message) {
409 410 411 412 413 414 415 416 417 418
    "use strict";
    var context = {
        type: "assertRaises",
        standard: "Function raises an error"
    };
    try {
        fn.apply(null, args);
        this.assert(false, message, context);
    } catch (error) {
        this.assert(true, message, utils.mergeObjects(context, {
419
            values: {
420
                error: error
421
            }
422 423 424
        }));
    }
};
425

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
/**
 * Asserts that the current page has a resource that matches the provided test
 *
 * @param  Function/String  test     A test function that is called with every response
 * @param  String           message  Test description
 * @return Object                    An assertion result object
 */
Tester.prototype.assertResourceExists = Tester.prototype.assertResourceExist = function assertResourceExists(test, message) {
    "use strict";
    return this.assert(this.casper.resourceExists(test), message, {
        type: "assertResourceExists",
        standard: "Expected resource has been found",
        values: {
            test: test
        }
    });
};
443

444
/**
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
 * Asserts that given text doesn't exist in the document body.
 *
 * @param  String  text     Text not to be found
 * @param  String  message  Test description
 * @return Object           An assertion result object
 */
Tester.prototype.assertTextDoesntExist = Tester.prototype.assertTextDoesntExist = function assertTextDoesntExist(text, message) {
    "use strict";
    var textFound = (this.casper.evaluate(function _evaluate() {
        return document.body.textContent || document.body.innerText;
    }).indexOf(text) === -1);
    return this.assert(textFound, message, {
        type: "assertTextDoesntExists",
        standard: "Text doesn't exist within the document body",
        values: {
            text: text
        }
    });
};

/**
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
 * Asserts that given text exists in the document body.
 *
 * @param  String  text     Text to be found
 * @param  String  message  Test description
 * @return Object           An assertion result object
 */
Tester.prototype.assertTextExists = Tester.prototype.assertTextExist = function assertTextExists(text, message) {
    "use strict";
    var textFound = (this.casper.evaluate(function _evaluate() {
        return document.body.textContent || document.body.innerText;
    }).indexOf(text) !== -1);
    return this.assert(textFound, message, {
        type: "assertTextExists",
        standard: "Found expected text within the document body",
        values: {
            text: text
        }
    });
};
485

486 487 488 489 490 491 492 493
/**
 * Asserts that given text exists in the provided selector.
 *
 * @param  String   selector  Selector expression
 * @param  String   text      Text to be found
 * @param  String   message   Test description
 * @return Object             An assertion result object
 */
494
Tester.prototype.assertSelectorHasText = Tester.prototype.assertSelectorContains = function assertSelectorHasText(selector, text, message) {
495 496 497
    "use strict";
    var textFound = this.casper.fetchText(selector).indexOf(text) !== -1;
    return this.assert(textFound, message, {
498
        type: "assertSelectorHasText",
499 500 501 502 503 504 505
        standard: f('Found "%s" within the selector "%s"', text, selector),
        values: {
            selector: selector,
            text: text
        }
    });
};
506

507 508 509 510 511 512 513 514
/**
 * Asserts that given text does not exist in the provided selector.
 *
 * @param  String   selector  Selector expression
 * @param  String   text      Text not to be found
 * @param  String   message   Test description
 * @return Object             An assertion result object
 */
515
Tester.prototype.assertSelectorDoesntHaveText = Tester.prototype.assertSelectorDoesntContain = function assertSelectorDoesntHaveText(selector, text, message) {
516 517 518
    "use strict";
    var textFound = this.casper.fetchText(selector).indexOf(text) === -1;
    return this.assert(textFound, message, {
519
        type: "assertSelectorDoesntHaveText",
520 521 522 523 524 525 526
        standard: f('Did not find "%s" within the selector "%s"', text, selector),
        values: {
            selector: selector,
            text: text
        }
    });
};
527

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
/**
 * Asserts that title of the remote page equals to the expected one.
 *
 * @param  String  expected  The expected title string
 * @param  String  message   Test description
 * @return Object            An assertion result object
 */
Tester.prototype.assertTitle = function assertTitle(expected, message) {
    "use strict";
    var currentTitle = this.casper.getTitle();
    return this.assert(this.testEquals(currentTitle, expected), message, {
        type: "assertTitle",
        standard: f('Page title is: "%s"', expected),
        values: {
            subject: currentTitle,
            expected: expected
        }
    });
};
547

548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
/**
 * Asserts that title of the remote page matched the provided pattern.
 *
 * @param  RegExp  pattern  The pattern to test the title against
 * @param  String  message  Test description
 * @return Object           An assertion result object
 */
Tester.prototype.assertTitleMatch = Tester.prototype.assertTitleMatches = function assertTitleMatch(pattern, message) {
    "use strict";
    var currentTitle = this.casper.getTitle();
    return this.assert(pattern.test(currentTitle), message, {
        type: "assertTitle",
        details: "Page title does not match the provided pattern",
        values: {
            subject: currentTitle,
            pattern: pattern.toString()
        }
    });
};
567

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
/**
 * Asserts that the provided subject is of the given type.
 *
 * @param  mixed   subject  The value to test
 * @param  String  type     The javascript type name
 * @param  String  message  Test description
 * @return Object           An assertion result object
 */
Tester.prototype.assertType = function assertType(subject, type, message) {
    "use strict";
    var actual = utils.betterTypeOf(subject);
    return this.assert(this.testEquals(actual, type), message, {
        type: "assertType",
        standard: f('Subject type is: "%s"', type),
        values: {
            subject: subject,
            type: type,
            actual: actual
        }
    });
};
589

590
/**
591 592 593
 * Asserts that a the current page url matches a given pattern. A pattern may be
 * either a RegExp object or a String. The method will test if the URL matches
 * the pattern or contains the String.
594
 *
595 596 597
 * @param  RegExp|String  pattern  The test pattern
 * @param  String         message  Test description
 * @return Object                  An assertion result object
598 599 600
 */
Tester.prototype.assertUrlMatch = Tester.prototype.assertUrlMatches = function assertUrlMatch(pattern, message) {
    "use strict";
601 602 603 604 605 606 607 608 609 610 611
    var currentUrl = this.casper.getCurrentUrl(),
        patternType = utils.betterTypeOf(pattern),
        result;
    if (patternType === "regexp") {
        result = pattern.test(currentUrl);
    } else if (patternType === "string") {
        result = currentUrl.indexOf(pattern) !== -1;
    } else {
        throw new CasperError("assertUrlMatch() only accepts strings or regexps");
    }
    return this.assert(result, message, {
612 613 614 615 616 617 618 619
        type: "assertUrlMatch",
        standard: "Current url matches the provided pattern",
        values: {
            currentUrl: currentUrl,
            pattern: pattern.toString()
        }
    });
};
620

621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
/**
 * Asserts that a selector expression is currently visible.
 *
 * @param  String  expected  selector expression
 * @param  String  message   Test description
 * @return Object            An assertion result object
 */
Tester.prototype.assertVisible = function assertVisible(selector, message) {
    "use strict";
    return this.assert(this.casper.visible(selector), message, {
        type: "assertVisible",
        standard: "Selector is visible",
        values: {
            selector: selector
        }
    });
};
638

639 640 641 642 643 644 645 646
/**
 * Prints out a colored bar onto the console.
 *
 */
Tester.prototype.bar = function bar(text, style) {
    "use strict";
    this.casper.echo(text, style, this.options.pad);
};
647

648 649 650 651 652 653 654 655
/**
 * Render a colorized output. Basically a proxy method for
 * Casper.Colorizer#colorize()
 */
Tester.prototype.colorize = function colorize(message, style) {
    "use strict";
    return this.casper.getColorizer().colorize(message, style);
};
656

657 658 659 660 661 662 663 664 665
/**
 * Writes a comment-style formatted message to stdout.
 *
 * @param  String  message
 */
Tester.prototype.comment = function comment(message) {
    "use strict";
    this.casper.echo('# ' + message, 'COMMENT');
};
666

667 668 669 670
/**
 * Configure casper callbacks for testing purpose.
 *
 */
671 672 673
Tester.prototype.configure = function configure() {
    "use strict";
    var tester = this;
674 675 676 677 678 679

    // Do not hook casper if we're not testing
    if (!phantom.casperTest) {
        return;
    }

680 681
    // specific timeout callbacks
    this.casper.options.onStepTimeout = function test_onStepTimeout(timeout, step) {
682
        tester.fail(f("Step timeout occured at step %s (%dms)", step, timeout));
683 684 685 686 687 688 689 690 691 692 693
    };

    this.casper.options.onTimeout = function test_onTimeout(timeout) {
        tester.fail(f("Timeout occured (%dms)", timeout));
    };

    this.casper.options.onWaitTimeout = function test_onWaitTimeout(timeout) {
        tester.fail(f("Wait timeout occured (%dms)", timeout));
    };
};

694 695 696
/**
 * Declares the current test suite done.
 *
697
 * @param  Number  planned  Number of planned tests
698
 */
699
Tester.prototype.done = function done(planned) {
700
    "use strict";
701 702 703 704
    if (planned > 0 && planned !== this.executed) {
        this.fail(f('%s: %d tests planned, %d tests executed',
            this.currentTestFile, planned, this.executed));
    }
705 706 707
    this.emit('test.done');
    this.running = false;
};
708

709 710 711 712 713 714 715 716 717
/**
 * Writes an error-style formatted message to stdout.
 *
 * @param  String  message
 */
Tester.prototype.error = function error(message) {
    "use strict";
    this.casper.echo(message, 'ERROR');
};
718

719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
/**
 * Executes a file, wraping and evaluating its code in an isolated
 * environment where only the current `casper` instance is passed.
 *
 * @param  String  file  Absolute path to some js/coffee file
 */
Tester.prototype.exec = function exec(file) {
    "use strict";
    file = this.filter('exec.file', file) || file;
    if (!fs.isFile(file) || !utils.isJsFile(file)) {
        var e = new CasperError(f("Cannot exec %s: can only exec() files with .js or .coffee extensions", file));
        e.fileName = file;
        throw e;
    }
    this.currentTestFile = file;
    phantom.injectJs(file);
};
736

737 738 739 740 741 742 743 744 745 746 747 748
/**
 * Adds a failed test entry to the stack.
 *
 * @param  String  message
 */
Tester.prototype.fail = function fail(message) {
    "use strict";
    return this.assert(false, message, {
        type:    "fail",
        standard: "explicit call to fail()"
    });
};
749

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
/**
 * Recursively finds all test files contained in a given directory.
 *
 * @param  String  dir  Path to some directory to scan
 */
Tester.prototype.findTestFiles = function findTestFiles(dir) {
    "use strict";
    var self = this;
    if (!fs.isDirectory(dir)) {
        return [];
    }
    var entries = fs.list(dir).filter(function _filter(entry) {
        return entry !== '.' && entry !== '..';
    }).map(function _map(entry) {
        return fs.absolute(fs.pathJoin(dir, entry));
    });
    entries.forEach(function _forEach(entry) {
        if (fs.isDirectory(entry)) {
            entries = entries.concat(self.findTestFiles(entry));
769
        }
770 771 772 773 774
    });
    return entries.filter(function _filter(entry) {
        return utils.isJsFile(fs.absolute(fs.pathJoin(dir, entry)));
    }).sort();
};
775

776 777 778 779 780 781 782 783 784 785 786 787 788 789
/**
 * Formats a message to highlight some parts of it.
 *
 * @param  String  message
 * @param  String  style
 */
Tester.prototype.formatMessage = function formatMessage(message, style) {
    "use strict";
    var parts = /^([a-z0-9_\.]+\(\))(.*)/i.exec(message);
    if (!parts) {
        return message;
    }
    return this.colorize(parts[1], 'PARAMETER') + this.colorize(parts[2], style);
};
790

791 792 793 794 795 796 797 798 799 800 801 802
/**
 * Retrieves current failure data and all failed cases.
 *
 * @return Object casedata An object containg information about cases
 * @return Number casedata.length The number of failed cases
 * @return Array  casedata.cases An array of all the failed case objects
 */
Tester.prototype.getFailures = function getFailures() {
    "use strict";
    return {
        length: this.testResults.failed,
        cases: this.testResults.failures
803
    };
804
};
805

806 807 808 809 810 811 812 813 814 815 816 817
/**
 * Retrieves current passed data and all passed cases.
 *
 * @return Object casedata An object containg information about cases
 * @return Number casedata.length The number of passed cases
 * @return Array  casedata.cases An array of all the passed case objects
 */
Tester.prototype.getPasses = function getPasses() {
    "use strict";
    return {
        length: this.testResults.passed,
        cases: this.testResults.passes
818
    };
819
};
820

821 822 823 824 825 826 827 828 829
/**
 * Writes an info-style formatted message to stdout.
 *
 * @param  String  message
 */
Tester.prototype.info = function info(message) {
    "use strict";
    this.casper.echo(message, 'PARAMETER');
};
830

831 832 833 834 835 836 837 838 839 840 841 842
/**
 * Adds a successful test entry to the stack.
 *
 * @param  String  message
 */
Tester.prototype.pass = function pass(message) {
    "use strict";
    return this.assert(true, message, {
        type:    "pass",
        standard: "explicit call to pass()"
    });
};
843

844 845 846 847 848 849 850 851 852
/**
 * Processes an assertion result by emitting the appropriate event and
 * printing result onto the console.
 *
 * @param  Object  result  An assertion result object
 * @return Object  The passed assertion result Object
 */
Tester.prototype.processAssertionResult = function processAssertionResult(result) {
    "use strict";
853 854 855
    var eventName= 'success',
        message = result.message || result.standard,
        style = 'INFO',
856
        status = this.options.passText;
857
    if (!result.success) {
858 859 860 861
        eventName = 'fail';
        style = 'RED_BAR';
        status = this.options.failText;
        this.testResults.failed++;
862 863
    } else {
        this.testResults.passed++;
864 865 866
    }
    this.casper.echo([this.colorize(status, style), this.formatMessage(message)].join(' '));
    this.emit(eventName, result);
867 868 869
    if (this.options.failFast && !result.success) {
        throw this.SKIP_MESSAGE;
    }
870 871
    return result;
};
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
/**
 * Renders a detailed report for each failed test.
 *
 * @param  Array  failures
 */
Tester.prototype.renderFailureDetails = function renderFailureDetails(failures) {
    "use strict";
    if (failures.length === 0) {
        return;
    }
    this.casper.echo(f("\nDetails for the %d failed test%s:\n", failures.length, failures.length > 1 ? "s" : ""), "PARAMETER");
    failures.forEach(function _forEach(failure) {
        var type, message, line;
        type = failure.type || "unknown";
        line = ~~failure.line;
        message = failure.message;
        this.casper.echo(f('In %s:%s', failure.file, line));
        this.casper.echo(f('   %s: %s', type, message || failure.standard || "(no message was entered)"), "COMMENT");
    });
};

/**
 * Render tests results, an optionally exit phantomjs.
 *
 * @param  Boolean  exit
 */
Tester.prototype.renderResults = function renderResults(exit, status, save) {
    "use strict";
901 902
    /*jshint maxstatements:20*/
    save = save || this.options.save;
903 904 905 906 907 908 909 910
    var total = this.testResults.passed + this.testResults.failed, statusText, style, result;
    var exitStatus = ~~(status || (this.testResults.failed > 0 ? 1 : 0));
    if (total === 0) {
        statusText = this.options.failText;
        style = 'RED_BAR';
        result = f("%s Looks like you didn't run any test.", statusText);
    } else {
        if (this.testResults.failed > 0) {
911
            statusText = this.options.failText;
912 913
            style = 'RED_BAR';
        } else {
914 915
            statusText = this.options.passText;
            style = 'GREEN_BAR';
916
        }
917 918 919 920 921 922 923
        result = f('%s %s tests executed, %d passed, %d failed.',
                   statusText, total, this.testResults.passed, this.testResults.failed);
    }
    this.casper.echo(result, style, this.options.pad);
    if (this.testResults.failed > 0) {
        this.renderFailureDetails(this.testResults.failures);
    }
924 925
    if (save) {
        this.saveResults(save);
926 927 928 929 930
    }
    if (exit === true) {
        this.casper.exit(exitStatus);
    }
};
Julien Moulin authored
931

932 933 934 935 936 937 938 939 940 941 942 943 944
/**
 * Runs al suites contained in the paths passed as arguments.
 *
 */
Tester.prototype.runSuites = function runSuites() {
    "use strict";
    var testFiles = [], self = this;
    if (arguments.length === 0) {
        throw new CasperError("runSuites() needs at least one path argument");
    }
    this.loadIncludes.includes.forEach(function _forEachInclude(include) {
        phantom.injectJs(include);
    });
Julien Moulin authored
945

946 947 948
    this.loadIncludes.pre.forEach(function _forEachPreTest(preTestFile) {
        testFiles = testFiles.concat(preTestFile);
    });
Julien Moulin authored
949

950 951 952
    Array.prototype.forEach.call(arguments, function _forEachArgument(path) {
        if (!fs.exists(path)) {
            self.bar(f("Path %s doesn't exist", path), "RED_BAR");
953
        }
954 955 956 957 958 959
        if (fs.isDirectory(path)) {
            testFiles = testFiles.concat(self.findTestFiles(path));
        } else if (fs.isFile(path)) {
            testFiles.push(path);
        }
    });
960

961 962 963
    this.loadIncludes.post.forEach(function _forEachPostTest(postTestFile) {
        testFiles = testFiles.concat(postTestFile);
    });
964

965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
    if (testFiles.length === 0) {
        this.bar(f("No test file found in %s, aborting.", Array.prototype.slice.call(arguments)), "RED_BAR");
        this.casper.exit(1);
    }
    self.currentSuiteNum = 0;
    var interval = setInterval(function _check(self) {
        if (self.running) {
            return;
        }
        if (self.currentSuiteNum === testFiles.length) {
            self.emit('tests.complete');
            clearInterval(interval);
        } else {
            self.runTest(testFiles[self.currentSuiteNum]);
            self.currentSuiteNum++;
        }
    }, 100, this);
};
983

984 985 986 987 988 989 990 991
/**
 * Runs a test file
 *
 */
Tester.prototype.runTest = function runTest(testFile) {
    "use strict";
    this.bar(f('Test file: %s', testFile), 'INFO_BAR');
    this.running = true; // this.running is set back to false with done()
992
    this.executed = 0;
993
    this.exec(testFile);
994
};
995

996
/**
997 998 999 1000 1001 1002
 * Saves results to file.
 *
 * @param   String  filename  Target file path.
 */
Tester.prototype.saveResults = function saveResults(filepath) {
    "use strict";
1003 1004 1005 1006
    // FIXME: looks like phantomjs has a pb with fs.isWritable https://groups.google.com/forum/#!topic/casperjs/hcUdwgGZOrU
    // if (!fs.isWritable(filepath)) {
    //     throw new CasperError(f('Path %s is not writable.', filepath));
    // }
1007 1008 1009 1010 1011 1012 1013 1014 1015
    try {
        fs.write(filepath, this.exporter.getXML(), 'w');
        this.casper.echo(f('Result log stored in %s', filepath), 'INFO', 80);
    } catch (e) {
        this.casper.echo(f('Unable to write results to %s: %s', filepath, e), 'ERROR', 80);
    }
};

/**
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
 * Tests equality between the two passed arguments.
 *
 * @param  Mixed  v1
 * @param  Mixed  v2
 * @param  Boolean
 */
Tester.prototype.testEquals = Tester.prototype.testEqual = function testEquals(v1, v2) {
    "use strict";
    return utils.equals(v1, v2);
};
1026

1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
/**
 * Processes an error caught while running tests contained in a given test
 * file.
 *
 * @param  Error|String  error      The error
 * @param  String        file       Test file where the error occurred
 * @param  Number        line       Line number (optional)
 */
Tester.prototype.uncaughtError = function uncaughtError(error, file, line) {
    "use strict";
    return this.processAssertionResult({
        success: false,
        type: "uncaughtError",
        file: file,
        line: ~~line || "unknown",
        message: utils.isObject(error) ? error.message : error,
        values: {
            error: error
        }
    });
};