runner.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. "use strict";
  2. /**
  3. * Create benchmarks defined similarly to tests in the mocha exports UI
  4. */
  5. var path = require("path"),
  6. benchmark = require("benchmark"),
  7. reporter = require("./reporter");
  8. /**
  9. * Runner for benchmarks defined similarly to tests in the mocha exports UI
  10. * @param {Object|Array|String} tests The tests walk and execute
  11. * @private
  12. */
  13. module.exports = function runner(tests) {
  14. var ctx = this && this !== global ? 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) {
  20. if (!tests.hasOwnProperty(name)) continue;
  21. if (~["before", "after", "beforeEach", "afterEach"].indexOf(name)) 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, {defer: test.length === 1});
  26. reporter.call(ctx, bench);
  27. try {
  28. if (tests.beforeEach instanceof Function) tests.beforeEach.call(ctx);
  29. test(); // run once outside of bench for better error handling
  30. bench.run();
  31. if (tests.afterEach instanceof Function) tests.afterEach.call(ctx);
  32. } catch (e) {
  33. bench.emit("error", bench.error = e);
  34. }
  35. } else {
  36. var newCtx = {};
  37. for (var key in ctx) {
  38. if (ctx.hasOwnProperty(key)) newCtx[key] = ctx[key];
  39. }
  40. newCtx.parent = ctx;
  41. newCtx.name = name;
  42. newCtx.fullName = fullName;
  43. runner.call(newCtx, test);
  44. }
  45. }
  46. if (tests.after instanceof Function) tests.after.call(ctx);
  47. };