tester.js 22.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 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
/*!
 * Casper is a navigation utility for PhantomJS.
 *
 * Documentation: http://casperjs.org/
 * Repository:    http://github.com/n1k0/casperjs
 *
 * Copyright (c) 2011-2012 Nicolas Perriault
 *
 * Part of source code is Copyright Joyent, Inc. and other Node contributors.
 *
 * 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.
 *
 */

var fs = require('fs');
var events = require('events');
var utils = require('utils');
var f = utils.format;

exports.create = function create(casper, options) {
    return new Tester(casper, options);
};

/**
 * Casper tester: makes assertions, stores test results and display then.
 *
 * @param  Casper       casper   A valid Casper instance
 * @param  Object|null  options  Options object
 */
var Tester = function Tester(casper, options) {
    if (!utils.isCasperObject(casper)) {
        throw new CasperError("Tester needs a Casper instance");
    }

    this.currentTestFile = null;
    this.exporter = require('xunit').create();
    this.running = false;
    this.suites = [];
    this.options = utils.mergeObjects({
        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);

    // properties
    this.testResults = {
        passed: 0,
        failed: 0,
        failures: []
    };

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

    this.on('success', function onSuccess(success) {
        this.exporter.addSuccess(fs.absolute(success.file), success.message);
    });

    this.on('fail', function onFail(failure) {
        this.exporter.addFailure(fs.absolute(failure.file), failure.message, failure.details || "test failed", failure.type || "unknown");
        this.testResults.failures.push(failure);
    });

    // methods
    /**
     * Asserts that a condition strictly resolves to true.
     *
     * @param  Boolean  subject
     * @param  String   message  Test description
     */
    this.assert = this.assertTrue = function assert(subject, message, context) {
        this.processAssertionResult(utils.mergeObjects({
            success: subject === true,
            type:    "assert",
            details: "test failed",
            message: message,
            file:    this.currentTestFile,
            values:  {
                subject: subject
            }
        }, context || {}));
    };

    /**
     * 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
     */
    this.assertEquals = this.assertEqual = function assertEquals(subject, expected, message) {
        var eventName;
        message = message || "";
        if (this.testEquals(subject, expected)) {
            eventName = "success";
            casper.echo(this.colorize(this.options.passText, 'INFO') + ' ' + this.formatMessage(message));
            this.testResults.passed++;
        } else {
            eventName = "fail";
            casper.echo(this.colorize(this.options.failText, 'RED_BAR') + ' ' + this.formatMessage(message, 'WARNING'));
            this.comment('   got:      ' + utils.serialize(subject));
            this.comment('   expected: ' + utils.serialize(expected));
            this.testResults.failed++;
        }
        this.emit(eventName, {
            type:   "assertEquals",
            message: message,
            details: f("test failed; expected: %s; got: %s", expected, subject),
            file:    this.currentTestFile,
            values:  {
                subject:  subject,
                expected: expected
            }
        });
    };

    /**
     * Asserts that two values are strictly not equals.
     *
     * @param  Mixed   subject    The value to test
     * @param  Mixed   expected   The unwanted value
     * @param  String  message    Test description
     */
    this.assertNotEquals = function assertNotEquals(subject, shouldnt, message) {
        var eventName;
        message = message || "";
        if (!this.testEquals(subject, shouldnt)) {
            eventName = "success";
            casper.echo(this.colorize(this.options.passText, 'INFO') + ' ' + this.formatMessage(message));
            this.testResults.passed++;
        } else {
            eventName = "fail";
            casper.echo(this.colorize(this.options.failText, 'RED_BAR') + ' ' + this.formatMessage(message, 'WARNING'));
            this.comment('   got:      ' + utils.serialize(subject));
            this.comment('   shouldnt: ' + utils.serialize(shouldnt));
            this.testResults.failed++;
        }
        this.emit(eventName, {
            type:   "assertNotEquals",
            message: message,
            details: f("test failed; shouldnt: %s; got: %s", shouldnt, subject),
            file:    this.currentTestFile,
            values:  {
                subject:  subject,
                shouldnt: shouldnt
            }
        });
    };

    /**
     * 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
     * @param  Object    context    Object containing the parameters to inject into the function (optional)
     */
    this.assertEval = function assertEval(fn, message, context) {
        return this.assert(casper.evaluate(fn, context), message);
    };

    /**
     * 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   message    Test description
     * @param  Object   context    Object containing the parameters to inject into the function (optional)
     */
    this.assertEvalEquals = this.assertEvalEqual = function assertEvalEquals(fn, expected, message, context) {
        return this.assertEquals(casper.evaluate(fn, context), expected, message);
    };

    /**
     * Asserts that an element matching the provided selector expression exists in
     * remote DOM.
     *
     * @param  String   selector   Selector expression
     * @param  String   message    Test description
     */
    this.assertExists = this.assertExist = function assertExists(selector, message) {
        return this.assert(casper.exists(selector), message);
    };

    /**
     * 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
     */
    this.assertDoesntExist = this.assertNotExists = function assertDoesntExist(selector, message) {
        return this.assertNot(casper.exists(selector), message);
    };

    /**
     * Asserts that current HTTP status is the one passed as argument.
     *
     * @param  Number  status   HTTP status code
     * @param  String  message  Test description
     */
    this.assertHttpStatus = function assertHttpStatus(status, message) {
        return this.assertEquals(casper.currentHTTPStatus, status, message || f("HTTP status code is %d", status));
    };

    /**
     * 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
     */
    this.assertMatch = this.assertMatches = function assertMatch(subject, pattern, message) {
        var eventName;
        if (pattern.test(subject)) {
            eventName = "success";
            casper.echo(this.colorize(this.options.passText, 'INFO') + ' ' + this.formatMessage(message));
            this.testResults.passed++;
        } else {
            eventName = "fail";
            casper.echo(this.colorize(this.options.failText, 'RED_BAR') + ' ' + this.formatMessage(message, 'WARNING'));
            this.comment('   subject: ' + subject);
            this.comment('   pattern: ' + pattern.toString());
            this.testResults.failed++;
        }
        this.emit(eventName, {
            type:   "assertMatch",
            message: message,
            details: f("test failed; subject: %s; pattern: %s", subject, pattern.toString()),
            file:    this.currentTestFile,
            values:  {
                subject: subject,
                pattern: pattern
            }
        });
    };

    /**
     * Asserts a condition resolves to false.
     *
     * @param  Boolean  condition
     * @param  String   message    Test description
     */
    this.assertNot = function assertNot(condition, message) {
        return this.assert(!condition, message);
    };

    /**
     * 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
     */
    this.assertRaises = this.assertRaise = function assertRaises(fn, args, message) {
        try {
            fn.apply(null, args);
            this.fail(message);
        } catch (e) {
            this.pass(message);
        }
    };

    /**
     * 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
     */
    this.assertResourceExists = this.assertResourceExist = function assertResourceExists(test, message) {
        return this.assert(casper.resourceExists(test), message);
    };

    /**
     * Asserts that at least an element matching the provided selector expression
     * exists in remote DOM.
     *
     * @param  String   selector   A selector expression string
     * @param  String   message    Test description
     */
    this.assertSelectorExists = this.assertSelectorExist = function assertSelectorExists(selector, message) {
        return this.assert(casper.exists(selector), message);
    };

    /**
     * Asserts that given text exits in the document body.
     *
     * @param  String   text       Text to be found
     * @param  String   message    Test description
     */
    this.assertTextExists = this.assertTextExist = function assertTextExists(text, message) {
        return this.assert((casper.evaluate(function _evaluate() {
            return document.body.innerText;
        }).indexOf(text) != -1), message);
    };

    /**
     * Asserts that title of the remote page equals to the expected one.
     *
     * @param  String  expected   The expected title string
     * @param  String  message    Test description
     */
    this.assertTitle = function assertTitle(expected, message) {
        return this.assertEquals(casper.getTitle(), expected, message);
    };

    /**
     * Asserts that the provided input is of the given type.
     *
     * @param  mixed   input    The value to test
     * @param  String  type     The javascript type name
     * @param  String  message  Test description
     */
    this.assertType = function assertType(input, type, message) {
        return this.assertEquals(utils.betterTypeOf(input), type, message);
    };

    /**
     * Asserts that a the current page url matches the provided RegExp
     * pattern.
     *
     * @param  RegExp   pattern    A RegExp object instance
     * @param  String   message    Test description
     */
    this.assertUrlMatch = this.assertUrlMatches = function assertUrlMatch(pattern, message) {
        return this.assertMatch(casper.getCurrentUrl(), pattern, message);
    };

    this.bar = function bar(text, style) {
        casper.echo(text, style, this.options.pad);
    };

    /**
     * Render a colorized output. Basically a proxy method for
     * Casper.Colorizer#colorize()
     */
    this.colorize = function colorize(message, style) {
        return casper.colorizer.colorize(message, style);
    };

    /**
     * Writes a comment-style formatted message to stdout.
     *
     * @param  String  message
     */
    this.comment = function comment(message) {
        casper.echo('# ' + message, 'COMMENT');
    };

    /**
     * Declares the current test suite done.
     *
     */
    this.done = function done() {
        this.running = false;
    };

    /**
     * Writes an error-style formatted message to stdout.
     *
     * @param  String  message
     */
    this.error = function error(message) {
        casper.echo(message, 'ERROR');
    };

    /**
     * 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
     */
    this.exec = function exec(file) {
        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;
        try {
            new Function('casper', phantom.getScriptCode(file))(casper);
        } catch (e) {
            // do not abort the whole suite, just fail fast displaying the
            // caught error and process next suite
            this.uncaughtError(e, file);
            this.done();
        }
    };

    /**
     * Adds a failed test entry to the stack.
     *
     * @param  String  message
     */
    this.fail = function fail(message, context) {
        this.assert(false, message, context);
    };

    /**
     * Recursively finds all test files contained in a given directory.
     *
     * @param  String  dir  Path to some directory to scan
     */
    this.findTestFiles = function findTestFiles(dir) {
        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));
            }
        });
        return entries.filter(function _filter(entry) {
            return utils.isJsFile(fs.absolute(fs.pathJoin(dir, entry)));
        }).sort();
    };

    /**
     * Formats a message to highlight some parts of it.
     *
     * @param  String  message
     * @param  String  style
     */
    this.formatMessage = function formatMessage(message, style) {
        var parts = /([a-z0-9_\.]+\(\))(.*)/i.exec(message);
        if (!parts) {
            return message;
        }
        return this.colorize(parts[1], 'PARAMETER') + this.colorize(parts[2], style);
    };

    /**
     * Writes an info-style formatted message to stdout.
     *
     * @param  String  message
     */
    this.info = function info(message) {
        casper.echo(message, 'PARAMETER');
    };

    /**
     * Adds a successful test entry to the stack.
     *
     * @param  String  message
     */
    this.pass = function pass(message) {
        this.assert(true, message);
    };

    /**
     * Processes an assertion result.
     *
     * @param  Object  result  An assertion result object
     */
    this.processAssertionResult = function processAssertionResult(result) {
        var eventName, style, status;
        if (result.success === true) {
            eventName = 'success';
            style = 'INFO';
            status = this.options.passText;
            this.testResults.passed++;
        } else {
            eventName = 'fail';
            style = 'RED_BAR';
            status = this.options.failText;
            this.testResults.failed++;
        }
        this.emit(eventName, result);
        casper.echo([this.colorize(status, style), this.formatMessage(result.message)].join(' '));
    };

    /**
     * Renders a detailed report for each failed test.
     *
     * @param  Array  failures
     */
    this.renderFailureDetails = function renderFailureDetails(failures) {
        if (failures.length === 0) {
            return;
        }
        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;
            casper.echo(f('In %s:%d', failure.file, line));
            casper.echo(f('   %s: %s', type, message || "(no message was entered)"), "COMMENT");
        });
    };

    /**
     * Render tests results, an optionnaly exit phantomjs.
     *
     * @param  Boolean  exit
     */
    this.renderResults = function renderResults(exit, status, save) {
        save = utils.isString(save) ? save : this.options.save;
        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) {
                statusText = this.options.failText;
                style = 'RED_BAR';
            } else {
                statusText = this.options.passText;
                style = 'GREEN_BAR';
            }
            result = f('%s %s tests executed, %d passed, %d failed.',
                       statusText, total, this.testResults.passed, this.testResults.failed);
        }
        casper.echo(result, style, this.options.pad);
        if (this.testResults.failed > 0) {
            this.renderFailureDetails(this.testResults.failures);
        }
        if (save && utils.isFunction(require)) {
            try {
                fs.write(save, this.exporter.getXML(), 'w');
                casper.echo(f('Result log stored in %s', save), 'INFO', 80);
            } catch (e) {
                casper.echo(f('Unable to write results to %s: %s', save, e), 'ERROR', 80);
            }
        }
        if (exit === true) {
            casper.exit(exitStatus);
        }
    };

    /**
     * Runs al suites contained in the paths passed as arguments.
     *
     */
    this.runSuites = function runSuites() {
        var testFiles = [], self = this;
        if (arguments.length === 0) {
            throw new CasperError("runSuites() needs at least one path argument");
        }
        Array.prototype.forEach.call(arguments, function _forEach(path) {
            if (!fs.exists(path)) {
                self.bar(f("Path %s doesn't exist", path), "RED_BAR");
            }
            if (fs.isDirectory(path)) {
                testFiles = testFiles.concat(self.findTestFiles(path));
            } else if (fs.isFile(path)) {
                testFiles.push(path);
            }
        });
        if (testFiles.length === 0) {
            this.bar(f("No test file found in %s, aborting.", Array.prototype.slice.call(arguments)), "RED_BAR");
            casper.exit(1);
        }
        var current = 0;
        var interval = setInterval(function _check(self) {
            if (self.running) {
                return;
            }
            if (current === testFiles.length) {
                self.emit('tests.complete');
                clearInterval(interval);
            } else {
                self.runTest(testFiles[current]);
                current++;
            }
        }, 100, this);
    };

    /**
     * Runs a test file
     *
     */
    this.runTest = function runTest(testFile) {
        this.bar(f('Test file: %s', testFile), 'INFO_BAR');
        this.running = true; // this.running is set back to false with done()
        try {
            this.exec(testFile);
        } catch (e) {
            this.uncaughtError(e, testFile);
            this.done();
        }
    };

    /**
     * Tests equality between the two passed arguments.
     *
     * @param  Mixed  v1
     * @param  Mixed  v2
     * @param  Boolean
     */
    this.testEquals = this.testEqual = function testEquals(v1, v2) {
        if (utils.betterTypeOf(v1) !== utils.betterTypeOf(v2)) {
            return false;
        }
        if (utils.isFunction(v1)) {
            return v1.toString() === v2.toString();
        }
        if (v1 instanceof Object && v2 instanceof Object) {
            if (Object.keys(v1).length !== Object.keys(v2).length) {
                return false;
            }
            for (var k in v1) {
                if (!this.testEquals(v1[k], v2[k])) {
                    return false;
                }
            }
            return true;
        }
        return v1 === v2;
    };

    /**
     * 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 occured
     */
    this.uncaughtError = function uncaughtError(error, file) {
        this.processAssertionResult({
            success: false,
            type: "uncaughtError",
            file: this.currentTestFile,
            message: utils.isObject(error) ? error.message : error
        });
    };
};

// Tester class is an EventEmitter
utils.inherits(Tester, events.EventEmitter);

exports.Tester = Tester;