runner.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. var path = require("path"),
  3. benchmark = require("benchmark"),
  4. reporter = require("./reporter");
  5. /**
  6. * Runner for benchmarks.
  7. * @method runner
  8. * @param {Object|Array|String} tests The tests walk and execute
  9. * if {Object}, should be in format similar to mocha `exports` UI
  10. * if {String}, should be reference to file that exports tests
  11. * if {Array}, should be list of tests
  12. */
  13. module.exports = function runner(tests) { //jshint maxcomplexity:19
  14. var ctx = this && this.constructor === Object ? this : {};
  15. if (!ctx.reporter) ctx.reporter = reporter;
  16. if (typeof tests === "string") tests = require(ctx.file = path.resolve(tests));
  17. if (Array.isArray(tests) && !ctx.parent) return tests.forEach(runner.bind(ctx));
  18. if (tests.before instanceof Function) tests.before.call(ctx);
  19. for (var name in tests) { //jshint ignore:line
  20. if (!tests.hasOwnProperty(name)) continue;
  21. if (["before", "after", "beforeEach", "afterEach"].indexOf(name) !== -1) continue;
  22. var test = tests[name],
  23. fullName = ctx.fullName ? ctx.fullName + " " + name : name;
  24. if (test instanceof Function) {
  25. var bench = benchmark(fullName, test);
  26. for (var key in ctx) {
  27. if (ctx.hasOwnProperty(key) && !bench.hasOwnProperty(key)) bench[key] = ctx[key];
  28. }
  29. ctx.reporter.call(ctx, bench);
  30. try {
  31. if (tests.beforeEach instanceof Function) tests.beforeEach.call(bench);
  32. test.call(bench); // run once outside of bench for better error handling
  33. bench.run();
  34. if (tests.afterEach instanceof Function) tests.afterEach.call(bench);
  35. } catch (e) {
  36. bench.emit("error", bench.error = e);
  37. }
  38. } else {
  39. var newCtx = {};
  40. for (var key2 in ctx) {
  41. if (ctx.hasOwnProperty(key2)){
  42. newCtx[key2] = ctx[key2];
  43. }
  44. }
  45. newCtx.parent = ctx;
  46. newCtx.name = name;
  47. newCtx.fullName = fullName;
  48. runner.call(newCtx, test);
  49. }
  50. }
  51. if (tests.after instanceof Function) tests.after.call(ctx);
  52. };