2
0

test.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. "use strict";
  2. function TestError(s) {this.__s = s;}
  3. TestError.prototype.toString = function(){return this.__s;};
  4. function runImpl(tests, stat, tab){
  5. for(var t in tests)
  6. runTest(t, tests, stat, tab);
  7. }
  8. function runTest(t, tests, stat, tab){
  9. var r = tests[t];
  10. if (typeof r != "function"){
  11. console.log(tab + t);
  12. runImpl(r, stat, tab + "\t");
  13. return;
  14. }
  15. var padding = " ";
  16. var log = t;
  17. if (log.length < padding.length)
  18. log = t + padding.substring(log.length);
  19. else
  20. log += " ";
  21. try {
  22. ++stat.count;
  23. r();
  24. //log += "OK";
  25. }
  26. catch (x){
  27. ++stat.failCount;
  28. if (x instanceof TestError)
  29. log += "Failed\n\t" + tab + x;
  30. else
  31. log += "Failed\n" + (x.stack ? x.stack : '\t' + tab + x);
  32. console.log(tab + log);
  33. }
  34. }
  35. function run(tests){
  36. var stat = {count: 0, failCount: 0};
  37. console.log("Running..." );
  38. var start = (new Date()).getTime();
  39. if (typeof process != "undefined" && process.argv.length > 2){
  40. var testName = process.argv[2];
  41. while (!tests[testName]){
  42. var dotPos = testName.indexOf(".");
  43. if (dotPos == -1){
  44. console.log("test '" + testName + "' not found");
  45. return;
  46. }
  47. var suite = testName.substr(0, dotPos);
  48. tests = tests[suite];
  49. if (!tests){
  50. console.log("suite '" + suite + "' not found");
  51. return;
  52. }
  53. testName = testName.substr(dotPos + 1);
  54. }
  55. runTest(testName, tests, stat, "");
  56. }
  57. else
  58. runImpl(tests, stat, "");
  59. var stop = (new Date()).getTime();
  60. console.log("elapsed: " + (stop - start) / 1000 + " s" );
  61. console.log(stat.count + " test(s) run");
  62. if (!stat.failCount)
  63. console.log("All OK!");
  64. else
  65. console.log(stat.failCount + " test(s) failed");
  66. return !stat.failCount;
  67. }
  68. exports.run = run;
  69. exports.TestError = TestError;