testcase_test.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. // Copyright 2014 The Closure Library Authors. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS-IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. goog.provide('goog.testing.TestCaseTest');
  15. goog.setTestOnly('goog.testing.TestCaseTest');
  16. goog.require('goog.Promise');
  17. goog.require('goog.Timer');
  18. goog.require('goog.functions');
  19. goog.require('goog.string');
  20. goog.require('goog.testing.ExpectedFailures');
  21. goog.require('goog.testing.JsUnitException');
  22. goog.require('goog.testing.MethodMock');
  23. goog.require('goog.testing.MockRandom');
  24. goog.require('goog.testing.PropertyReplacer');
  25. goog.require('goog.testing.TestCase');
  26. goog.require('goog.testing.jsunit');
  27. // Dual of fail().
  28. var ok = function() {
  29. assertTrue(true);
  30. };
  31. // Native Promise-based equivalent of ok().
  32. var okPromise = function() {
  33. return Promise.resolve(null);
  34. };
  35. // Native Promise-based equivalent of fail().
  36. var failPromise = function() {
  37. return Promise.reject(null);
  38. };
  39. // Native Promise-based test that returns promise which never resolves.
  40. var neverResolvedPromise = function() {
  41. return new Promise(function() {});
  42. };
  43. // goog.Promise-based equivalent of ok().
  44. var okGoogPromise = function() {
  45. return goog.Promise.resolve(null);
  46. };
  47. // goog.Promise-based equivalent of fail().
  48. var failGoogPromise = function() {
  49. return goog.Promise.reject(null);
  50. };
  51. // Native Promise-based test that returns promise which never resolves.
  52. var neverResolvedGoogPromise = function() {
  53. return new goog.Promise(function() {});
  54. };
  55. function setUp() {
  56. // TODO(b/25875505): Fix unreported assertions (go/failonunreportedasserts).
  57. goog.testing.TestCase.getActiveTestCase().failOnUnreportedAsserts = false;
  58. }
  59. function testEmptyTestCase() {
  60. var testCase = new goog.testing.TestCase();
  61. testCase.runTests();
  62. assertTrue(testCase.isSuccess());
  63. var result = testCase.getResult();
  64. assertTrue(result.complete);
  65. assertEquals(0, result.totalCount);
  66. assertEquals(0, result.runCount);
  67. assertEquals(0, result.successCount);
  68. assertEquals(0, result.errors.length);
  69. }
  70. function testEmptyTestCaseReturningPromise() {
  71. return new goog.testing.TestCase().runTestsReturningPromise().then(
  72. function(result) {
  73. assertTrue(result.complete);
  74. assertEquals(0, result.totalCount);
  75. assertEquals(0, result.runCount);
  76. assertEquals(0, result.successCount);
  77. assertEquals(0, result.errors.length);
  78. });
  79. }
  80. function testTestCase_SyncSuccess() {
  81. var testCase = new goog.testing.TestCase();
  82. testCase.addNewTest('foo', ok);
  83. testCase.runTests();
  84. assertTrue(testCase.isSuccess());
  85. var result = testCase.getResult();
  86. assertTrue(result.complete);
  87. assertEquals(1, result.totalCount);
  88. assertEquals(1, result.runCount);
  89. assertEquals(1, result.successCount);
  90. assertEquals(0, result.errors.length);
  91. }
  92. function testTestCaseReturningPromise_SyncSuccess() {
  93. var testCase = new goog.testing.TestCase();
  94. testCase.addNewTest('foo', ok);
  95. return testCase.runTestsReturningPromise().then(function(result) {
  96. assertTrue(result.complete);
  97. assertEquals(1, result.totalCount);
  98. assertEquals(1, result.runCount);
  99. assertEquals(1, result.successCount);
  100. assertEquals(0, result.errors.length);
  101. });
  102. }
  103. function testTestCaseReturningPromise_GoogPromiseResolve() {
  104. var testCase = new goog.testing.TestCase();
  105. testCase.addNewTest('foo', okGoogPromise);
  106. return testCase.runTestsReturningPromise().then(function(result) {
  107. assertTrue(result.complete);
  108. assertEquals(1, result.totalCount);
  109. assertEquals(1, result.runCount);
  110. assertEquals(1, result.successCount);
  111. assertEquals(0, result.errors.length);
  112. });
  113. }
  114. function testTestCaseReturningPromise_PromiseResolve() {
  115. if (!('Promise' in goog.global)) {
  116. return;
  117. }
  118. var testCase = new goog.testing.TestCase();
  119. testCase.addNewTest('foo', okPromise);
  120. return testCase.runTestsReturningPromise().then(function(result) {
  121. assertTrue(result.complete);
  122. assertEquals(1, result.totalCount);
  123. assertEquals(1, result.runCount);
  124. assertEquals(1, result.successCount);
  125. assertEquals(0, result.errors.length);
  126. });
  127. }
  128. function testTestCase_SyncFailure() {
  129. var testCase = new goog.testing.TestCase();
  130. testCase.addNewTest('foo', fail);
  131. testCase.runTests();
  132. assertFalse(testCase.isSuccess());
  133. var result = testCase.getResult();
  134. assertTrue(result.complete);
  135. assertEquals(1, result.totalCount);
  136. assertEquals(1, result.runCount);
  137. assertEquals(0, result.successCount);
  138. assertEquals(1, result.errors.length);
  139. assertEquals('foo', result.errors[0].source);
  140. }
  141. function testTestCaseReturningPromise_SyncFailure() {
  142. var testCase = new goog.testing.TestCase();
  143. testCase.addNewTest('foo', fail);
  144. return testCase.runTestsReturningPromise().then(function(result) {
  145. assertFalse(testCase.isSuccess());
  146. assertTrue(result.complete);
  147. assertEquals(1, result.totalCount);
  148. assertEquals(1, result.runCount);
  149. assertEquals(0, result.successCount);
  150. assertEquals(1, result.errors.length);
  151. assertEquals('foo', result.errors[0].source);
  152. });
  153. }
  154. function testTestCaseReturningPromise_GoogPromiseReject() {
  155. var testCase = new goog.testing.TestCase();
  156. testCase.addNewTest('foo', failGoogPromise);
  157. return testCase.runTestsReturningPromise().then(function(result) {
  158. assertFalse(testCase.isSuccess());
  159. assertTrue(result.complete);
  160. assertEquals(1, result.totalCount);
  161. assertEquals(1, result.runCount);
  162. assertEquals(0, result.successCount);
  163. assertEquals(1, result.errors.length);
  164. assertEquals('foo', result.errors[0].source);
  165. });
  166. }
  167. function testTestCaseReturningPromise_GoogPromiseTimeout() {
  168. var testCase = new goog.testing.TestCase();
  169. testCase.addNewTest('foo', neverResolvedGoogPromise);
  170. var startTimestamp = new Date().getTime();
  171. // We have to decrease timeout for the artificial 'foo' test otherwise current
  172. // test will timeout.
  173. testCase.promiseTimeout = 500;
  174. startTimestamp = new Date().getTime();
  175. return testCase.runTestsReturningPromise().then(function(result) {
  176. var elapsedTime = new Date().getTime() - startTimestamp;
  177. assertFalse(testCase.isSuccess());
  178. assertTrue(result.complete);
  179. assertEquals(1, result.totalCount);
  180. assertEquals(1, result.runCount);
  181. assertEquals(0, result.successCount);
  182. assertEquals(1, result.errors.length);
  183. // Check that error message mentions test name.
  184. assertTrue(goog.string.contains(result.errors[0].message, 'foo'));
  185. // Check that error message mentions how to change timeout.
  186. assertTrue(
  187. goog.string.contains(
  188. result.errors[0].message,
  189. 'goog.testing.TestCase.getActiveTestCase().promiseTimeout'));
  190. assertTrue(
  191. elapsedTime >= testCase.promiseTimeout - 100 &&
  192. elapsedTime <= testCase.promiseTimeout + 100);
  193. });
  194. }
  195. function testTestCaseReturningPromise_PromiseReject() {
  196. if (!('Promise' in goog.global)) {
  197. return;
  198. }
  199. var testCase = new goog.testing.TestCase();
  200. testCase.addNewTest('foo', failPromise);
  201. return testCase.runTestsReturningPromise().then(function(result) {
  202. assertFalse(testCase.isSuccess());
  203. assertTrue(result.complete);
  204. assertEquals(1, result.totalCount);
  205. assertEquals(1, result.runCount);
  206. assertEquals(0, result.successCount);
  207. assertEquals(1, result.errors.length);
  208. assertEquals('foo', result.errors[0].source);
  209. });
  210. }
  211. function testTestCaseReturningPromise_PromiseTimeout() {
  212. if (!('Promise' in goog.global)) {
  213. return;
  214. }
  215. var testCase = new goog.testing.TestCase();
  216. testCase.addNewTest('foo', neverResolvedPromise);
  217. // We have to decrease timeout for the artificial 'foo' test otherwise current
  218. // test will timeout.
  219. testCase.promiseTimeout = 500;
  220. var startTimestamp = new Date().getTime();
  221. return testCase.runTestsReturningPromise().then(function(result) {
  222. var elapsedTime = new Date().getTime() - startTimestamp;
  223. assertFalse(testCase.isSuccess());
  224. assertTrue(result.complete);
  225. assertEquals(1, result.totalCount);
  226. assertEquals(1, result.runCount);
  227. assertEquals(0, result.successCount);
  228. assertEquals(1, result.errors.length);
  229. // Check that error message mentions test name.
  230. assertTrue(goog.string.contains(result.errors[0].message, 'foo'));
  231. // Check that error message mentions how to change timeout.
  232. assertTrue(
  233. goog.string.contains(
  234. result.errors[0].message,
  235. 'goog.testing.TestCase.getActiveTestCase().promiseTimeout'));
  236. assertTrue(
  237. elapsedTime >= testCase.promiseTimeout - 100 &&
  238. elapsedTime <= testCase.promiseTimeout + 100);
  239. });
  240. }
  241. function testTestCase_SyncSuccess_SyncFailure() {
  242. var testCase = new goog.testing.TestCase();
  243. testCase.addNewTest('foo', ok);
  244. testCase.addNewTest('bar', fail);
  245. testCase.runTests();
  246. assertFalse(testCase.isSuccess());
  247. var result = testCase.getResult();
  248. assertTrue(result.complete);
  249. assertEquals(2, result.totalCount);
  250. assertEquals(2, result.runCount);
  251. assertEquals(1, result.successCount);
  252. assertEquals(1, result.errors.length);
  253. assertEquals('bar', result.errors[0].source);
  254. }
  255. function testTestCaseReturningPromise_SyncSuccess_SyncFailure() {
  256. var testCase = new goog.testing.TestCase();
  257. testCase.addNewTest('foo', ok);
  258. testCase.addNewTest('bar', fail);
  259. return testCase.runTestsReturningPromise().then(function(result) {
  260. assertTrue(result.complete);
  261. assertEquals(2, result.totalCount);
  262. assertEquals(2, result.runCount);
  263. assertEquals(1, result.successCount);
  264. assertEquals(1, result.errors.length);
  265. assertEquals('bar', result.errors[0].source);
  266. });
  267. }
  268. function testTestCaseReturningPromise_GoogPromiseResolve_GoogPromiseReject() {
  269. var testCase = new goog.testing.TestCase();
  270. testCase.addNewTest('foo', okGoogPromise);
  271. testCase.addNewTest('bar', failGoogPromise);
  272. return testCase.runTestsReturningPromise().then(function(result) {
  273. assertTrue(result.complete);
  274. assertEquals(2, result.totalCount);
  275. assertEquals(2, result.runCount);
  276. assertEquals(1, result.successCount);
  277. assertEquals(1, result.errors.length);
  278. assertEquals('bar', result.errors[0].source);
  279. });
  280. }
  281. function testTestCaseReturningPromise_PromiseResolve_PromiseReject() {
  282. if (!('Promise' in goog.global)) {
  283. return;
  284. }
  285. var testCase = new goog.testing.TestCase();
  286. testCase.addNewTest('foo', okPromise);
  287. testCase.addNewTest('bar', failPromise);
  288. return testCase.runTestsReturningPromise().then(function(result) {
  289. assertTrue(result.complete);
  290. assertEquals(2, result.totalCount);
  291. assertEquals(2, result.runCount);
  292. assertEquals(1, result.successCount);
  293. assertEquals(1, result.errors.length);
  294. assertEquals('bar', result.errors[0].source);
  295. });
  296. }
  297. function testTestCaseReturningPromise_PromiseResolve_GoogPromiseReject() {
  298. if (!('Promise' in goog.global)) {
  299. return;
  300. }
  301. var testCase = new goog.testing.TestCase();
  302. testCase.addNewTest('foo', okPromise);
  303. testCase.addNewTest('bar', failGoogPromise);
  304. return testCase.runTestsReturningPromise().then(function(result) {
  305. assertTrue(result.complete);
  306. assertEquals(2, result.totalCount);
  307. assertEquals(2, result.runCount);
  308. assertEquals(1, result.successCount);
  309. assertEquals(1, result.errors.length);
  310. assertEquals('bar', result.errors[0].source);
  311. });
  312. }
  313. function testTestCaseReturningPromise_GoogPromiseResolve_PromiseReject() {
  314. if (!('Promise' in goog.global)) {
  315. return;
  316. }
  317. var testCase = new goog.testing.TestCase();
  318. testCase.addNewTest('foo', okGoogPromise);
  319. testCase.addNewTest('bar', failPromise);
  320. return testCase.runTestsReturningPromise().then(function(result) {
  321. assertTrue(result.complete);
  322. assertEquals(2, result.totalCount);
  323. assertEquals(2, result.runCount);
  324. assertEquals(1, result.successCount);
  325. assertEquals(1, result.errors.length);
  326. assertEquals('bar', result.errors[0].source);
  327. });
  328. }
  329. function testTestCaseReturningPromise_PromisesInSetUpAndTest() {
  330. if (!('Promise' in goog.global)) {
  331. return;
  332. }
  333. var testCase = new goog.testing.TestCase();
  334. var events = [];
  335. testCase.setUpPage = function() {
  336. events.push('setUpPage-called');
  337. return goog.Timer.promise().then(function() {
  338. events.push('setUpPage-promiseFinished');
  339. });
  340. };
  341. testCase.setUp = function() {
  342. events.push('setUp-called');
  343. return goog.Timer.promise().then(function() {
  344. events.push('setUp-promiseFinished');
  345. });
  346. };
  347. testCase.addNewTest('foo', function() {
  348. events.push('foo-called');
  349. return goog.Timer.promise().then(function() {
  350. events.push('foo-promiseFinished');
  351. });
  352. });
  353. // Initially only setUpPage should have been called.
  354. return testCase.runTestsReturningPromise().then(function(result) {
  355. assertTrue(result.complete);
  356. assertEquals(1, result.totalCount);
  357. assertEquals(1, result.runCount);
  358. assertEquals(1, result.successCount);
  359. assertEquals(0, result.errors.length);
  360. assertArrayEquals(
  361. [
  362. 'setUpPage-called', 'setUpPage-promiseFinished', 'setUp-called',
  363. 'setUp-promiseFinished', 'foo-called', 'foo-promiseFinished'
  364. ],
  365. events);
  366. });
  367. }
  368. function testTestCaseNeverRun() {
  369. var testCase = new goog.testing.TestCase();
  370. testCase.addNewTest('foo', fail);
  371. // Missing testCase.runTests()
  372. var result = testCase.getResult();
  373. assertFalse(result.complete);
  374. assertEquals(0, result.totalCount);
  375. assertEquals(0, result.runCount);
  376. assertEquals(0, result.successCount);
  377. assertEquals(0, result.errors.length);
  378. }
  379. function testParseOrder() {
  380. assertNull(goog.testing.TestCase.parseOrder_(''));
  381. assertNull(goog.testing.TestCase.parseOrder_('?order=invalid'));
  382. assertEquals('natural', goog.testing.TestCase.parseOrder_('?order=natural'));
  383. assertEquals('sorted', goog.testing.TestCase.parseOrder_('?a&order=sorted'));
  384. assertEquals('random', goog.testing.TestCase.parseOrder_('?b&order=random'));
  385. assertEquals('random', goog.testing.TestCase.parseOrder_('?ORDER=RANDOM'));
  386. }
  387. function testParseRunTests() {
  388. assertNull(goog.testing.TestCase.parseRunTests_(''));
  389. assertNull(goog.testing.TestCase.parseRunTests_('?runTests='));
  390. assertObjectEquals(
  391. {'testOne': true},
  392. goog.testing.TestCase.parseRunTests_('?runTests=testOne'));
  393. assertObjectEquals(
  394. {'testOne': true, 'testTwo': true},
  395. goog.testing.TestCase.parseRunTests_(
  396. '?foo=bar&runTests=testOne,testTwo'));
  397. assertObjectEquals(
  398. {
  399. '1': true,
  400. '2': true,
  401. '3': true,
  402. 'testShouting': true,
  403. 'TESTSHOUTING': true
  404. },
  405. goog.testing.TestCase.parseRunTests_(
  406. '?RUNTESTS=testShouting,TESTSHOUTING,1,2,3'));
  407. }
  408. function testSortOrder_natural() {
  409. var testCase = new goog.testing.TestCase();
  410. testCase.setOrder('natural');
  411. var testIndex = 0;
  412. testCase.addNewTest('test_c', function() { assertEquals(0, testIndex++); });
  413. testCase.addNewTest('test_a', function() { assertEquals(1, testIndex++); });
  414. testCase.addNewTest('test_b', function() { assertEquals(2, testIndex++); });
  415. testCase.orderTests_();
  416. testCase.runTests();
  417. assertTrue(testCase.isSuccess());
  418. var result = testCase.getResult();
  419. assertEquals(3, result.totalCount);
  420. assertEquals(3, result.runCount);
  421. assertEquals(3, result.successCount);
  422. assertEquals(0, result.errors.length);
  423. }
  424. function testSortOrder_random() {
  425. var testCase = new goog.testing.TestCase();
  426. testCase.setOrder('random');
  427. var testIndex = 0;
  428. testCase.addNewTest('test_c', function() { assertEquals(0, testIndex++); });
  429. testCase.addNewTest('test_a', function() { assertEquals(2, testIndex++); });
  430. testCase.addNewTest('test_b', function() { assertEquals(1, testIndex++); });
  431. var mockRandom = new goog.testing.MockRandom([0.5, 0.5]);
  432. mockRandom.install();
  433. try {
  434. testCase.orderTests_();
  435. } finally {
  436. // Avoid using a global tearDown() for cleanup, since all TestCase instances
  437. // auto-detect and share the global life cycle functions.
  438. mockRandom.uninstall();
  439. }
  440. testCase.runTests();
  441. assertTrue(testCase.isSuccess());
  442. var result = testCase.getResult();
  443. assertEquals(3, result.totalCount);
  444. assertEquals(3, result.runCount);
  445. assertEquals(3, result.successCount);
  446. assertEquals(0, result.errors.length);
  447. }
  448. function testSortOrder_sorted() {
  449. var testCase = new goog.testing.TestCase();
  450. testCase.setOrder('sorted');
  451. var testIndex = 0;
  452. testCase.addNewTest('test_c', function() { assertEquals(2, testIndex++); });
  453. testCase.addNewTest('test_a', function() { assertEquals(0, testIndex++); });
  454. testCase.addNewTest('test_b', function() { assertEquals(1, testIndex++); });
  455. testCase.orderTests_();
  456. testCase.runTests();
  457. assertTrue(testCase.isSuccess());
  458. var result = testCase.getResult();
  459. assertEquals(3, result.totalCount);
  460. assertEquals(3, result.runCount);
  461. assertEquals(3, result.successCount);
  462. assertEquals(0, result.errors.length);
  463. }
  464. function testRunTests() {
  465. var testCase = new goog.testing.TestCase();
  466. testCase.setTestsToRun({'test_a': true, 'test_c': true});
  467. var testIndex = 0;
  468. testCase.addNewTest('test_c', function() { assertEquals(0, testIndex++); });
  469. testCase.addNewTest('test_a', function() { assertEquals(1, testIndex++); });
  470. testCase.addNewTest('test_b', fail);
  471. testCase.runTests();
  472. assertTrue(testCase.isSuccess());
  473. var result = testCase.getResult();
  474. assertEquals(3, result.totalCount);
  475. assertEquals(2, result.runCount);
  476. assertEquals(2, result.successCount);
  477. assertEquals(0, result.errors.length);
  478. }
  479. function testRunTests_byIndex() {
  480. var testCase = new goog.testing.TestCase();
  481. testCase.setTestsToRun({'0': true, '2': true});
  482. var testIndex = 0;
  483. testCase.addNewTest('test_c', function() { assertEquals(0, testIndex++); });
  484. testCase.addNewTest('test_a', fail);
  485. testCase.addNewTest('test_b', function() { assertEquals(1, testIndex++); });
  486. testCase.runTests();
  487. assertTrue(testCase.isSuccess());
  488. var result = testCase.getResult();
  489. assertEquals(3, result.totalCount);
  490. assertEquals(2, result.runCount);
  491. assertEquals(2, result.successCount);
  492. assertEquals(0, result.errors.length);
  493. }
  494. function testMaybeFailTestEarly() {
  495. var message = 'Error in setUpPage().';
  496. var testCase = new goog.testing.TestCase();
  497. testCase.setUpPage = function() { throw Error(message); };
  498. testCase.addNewTest('test', ok);
  499. testCase.runTests();
  500. assertFalse(testCase.isSuccess());
  501. var errors = testCase.getResult().errors;
  502. assertEquals(1, errors.length);
  503. assertEquals(message, errors[0].message);
  504. }
  505. function testSetUpReturnsPromiseThatTimesOut() {
  506. var testCase = new goog.testing.TestCase();
  507. testCase.promiseTimeout = 500;
  508. testCase.setUp = neverResolvedGoogPromise;
  509. testCase.addNewTest('test', ok);
  510. return testCase.runTestsReturningPromise().then(function(result) {
  511. assertFalse(testCase.isSuccess());
  512. assertTrue(result.complete);
  513. assertEquals(1, result.errors.length);
  514. assertTrue(goog.string.contains(result.errors[0].message, 'setUp'));
  515. });
  516. }
  517. function testTearDownReturnsPromiseThatTimesOut() {
  518. var testCase = new goog.testing.TestCase();
  519. testCase.promiseTimeout = 500;
  520. testCase.tearDown = neverResolvedGoogPromise;
  521. testCase.addNewTest('test', ok);
  522. return testCase.runTestsReturningPromise().then(function(result) {
  523. assertFalse(testCase.isSuccess());
  524. assertTrue(result.complete);
  525. assertEquals(1, result.errors.length);
  526. assertTrue(goog.string.contains(result.errors[0].message, 'tearDown'));
  527. });
  528. }
  529. function testFailOnUnreportedAsserts_EnabledByDefault() {
  530. assertTrue(new goog.testing.TestCase().failOnUnreportedAsserts);
  531. }
  532. /**
  533. * Verifies that:
  534. * <ol>
  535. * <li>when the {@code failOnUnreportedAsserts} flag is disabled, the test
  536. * function passes;
  537. * <li>when the {@code failOnUnreportedAsserts} flag is enabled, the test
  538. * function passes if {@code shouldPassWithFlagEnabled} is true and fails if
  539. * it is false; and that
  540. * <li>when the {@code failOnUnreportedAsserts} flag is enabled, and in addition
  541. * {@code invalidateAssertionException} is stubbed out to do nothing, the
  542. * test function fails.
  543. * </ol>
  544. * @param {boolean} shouldPassWithFlagEnabled
  545. * @param {function(): !goog.Promise} testFunction
  546. * @return {!goog.Promise}
  547. */
  548. function verifyTestOutcomeForFailOnUnreportedAssertsFlag(
  549. shouldPassWithFlagEnabled, testFunction) {
  550. return verifyWithFlagEnabledAndNoInvalidation(testFunction)
  551. .then(function() {
  552. return verifyWithFlagEnabled(testFunction, shouldPassWithFlagEnabled);
  553. })
  554. .then(function() { return verifyWithFlagDisabled(testFunction); });
  555. }
  556. function verifyWithFlagDisabled(testFunction) {
  557. // With the flag disabled, the test is expected to pass, as any caught
  558. // exception would not be reported.
  559. var testCase = new goog.testing.TestCase();
  560. var getTestCase = goog.functions.constant(testCase);
  561. testCase.addNewTest('test', testFunction);
  562. testCase.failOnUnreportedAsserts = false;
  563. var stubs = new goog.testing.PropertyReplacer();
  564. stubs.replace(window, '_getCurrentTestCase', getTestCase);
  565. stubs.replace(goog.testing.TestCase, 'getActiveTestCase', getTestCase);
  566. var promise = new goog
  567. .Promise(function(resolve, reject) {
  568. testCase.setCompletedCallback(resolve);
  569. })
  570. .then(function() {
  571. assertTrue(testCase.isSuccess());
  572. var result = testCase.getResult();
  573. assertTrue(result.complete);
  574. assertEquals(0, result.errors.length);
  575. })
  576. .thenAlways(function() { stubs.reset(); });
  577. testCase.runTests();
  578. return promise;
  579. }
  580. function verifyWithFlagEnabled(testFunction, shouldPassWithFlagEnabled) {
  581. // With the flag enabled, the test is expected to pass if shouldPassWithFlag
  582. // is true, and fail if shouldPassWithFlag is false.
  583. var testCase = new goog.testing.TestCase();
  584. var getTestCase = goog.functions.constant(testCase);
  585. testCase.addNewTest('test', testFunction);
  586. testCase.failOnUnreportedAsserts = true;
  587. var stubs = new goog.testing.PropertyReplacer();
  588. stubs.replace(window, '_getCurrentTestCase', getTestCase);
  589. stubs.replace(goog.testing.TestCase, 'getActiveTestCase', getTestCase);
  590. var promise =
  591. new goog
  592. .Promise(function(resolve, reject) {
  593. testCase.setCompletedCallback(resolve);
  594. })
  595. .then(function() {
  596. assertEquals(shouldPassWithFlagEnabled, testCase.isSuccess());
  597. var result = testCase.getResult();
  598. assertTrue(result.complete);
  599. // Expect both the caught assertion and the failOnUnreportedAsserts
  600. // error.
  601. assertEquals(
  602. shouldPassWithFlagEnabled ? 0 : 2, result.errors.length);
  603. })
  604. .thenAlways(function() { stubs.reset(); });
  605. testCase.runTests();
  606. return promise;
  607. }
  608. function verifyWithFlagEnabledAndNoInvalidation(testFunction) {
  609. // With the flag enabled, the test is expected to pass if shouldPassWithFlag
  610. // is true, and fail if shouldPassWithFlag is false.
  611. var testCase = new goog.testing.TestCase();
  612. var getTestCase = goog.functions.constant(testCase);
  613. testCase.addNewTest('test', testFunction);
  614. testCase.failOnUnreportedAsserts = true;
  615. var stubs = new goog.testing.PropertyReplacer();
  616. stubs.replace(window, '_getCurrentTestCase', getTestCase);
  617. stubs.replace(goog.testing.TestCase, 'getActiveTestCase', getTestCase);
  618. stubs.replace(
  619. goog.testing.TestCase.prototype, 'invalidateAssertionException',
  620. goog.nullFunction);
  621. var promise = new goog
  622. .Promise(function(resolve, reject) {
  623. testCase.setCompletedCallback(resolve);
  624. })
  625. .then(function() {
  626. assertFalse(testCase.isSuccess());
  627. var result = testCase.getResult();
  628. assertTrue(result.complete);
  629. // Expect both the caught assertion and the
  630. // failOnUnreportedAsserts error.
  631. assertEquals(2, result.errors.length);
  632. })
  633. .thenAlways(function() { stubs.reset(); });
  634. testCase.runTests();
  635. return promise;
  636. }
  637. function testFailOnUnreportedAsserts_SwallowedException() {
  638. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(false, function() {
  639. try {
  640. assertTrue(false);
  641. } catch (e) {
  642. // Swallow the exception generated by the assertion.
  643. }
  644. });
  645. }
  646. function testFailOnUnreportedAsserts_SwallowedFail() {
  647. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(false, function() {
  648. try {
  649. fail();
  650. } catch (e) {
  651. // Swallow the exception generated by fail.
  652. }
  653. });
  654. }
  655. function testFailOnUnreportedAsserts_SwallowedAssertThrowsException() {
  656. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(false, function() {
  657. try {
  658. assertThrows(goog.nullFunction);
  659. } catch (e) {
  660. // Swallow the exception generated by assertThrows.
  661. }
  662. });
  663. }
  664. function testFailOnUnreportedAsserts_SwallowedAssertNotThrowsException() {
  665. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(false, function() {
  666. try {
  667. assertNotThrows(goog.functions.error());
  668. } catch (e) {
  669. // Swallow the exception generated by assertNotThrows.
  670. }
  671. });
  672. }
  673. function testFailOnUnreportedAsserts_SwallowedExceptionViaPromise() {
  674. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(false, function() {
  675. return goog.Promise.resolve()
  676. .then(function() { assertTrue(false); })
  677. .thenCatch(function(e) {
  678. // Swallow the exception generated by the assertion.
  679. });
  680. });
  681. }
  682. function testFailOnUnreportedAsserts_NotForAssertThrowsJsUnitException() {
  683. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(true, function() {
  684. assertThrowsJsUnitException(function() { assertTrue(false); });
  685. });
  686. }
  687. function testFailOnUnreportedAsserts_NotForExpectedFailures() {
  688. return verifyTestOutcomeForFailOnUnreportedAssertsFlag(true, function() {
  689. var expectedFailures = new goog.testing.ExpectedFailures();
  690. expectedFailures.expectFailureFor(true);
  691. try {
  692. assertTrue(false);
  693. } catch (e) {
  694. expectedFailures.handleException(e);
  695. }
  696. });
  697. }
  698. function testFailOnUnreportedAsserts_ReportUnpropagatedAssertionExceptions() {
  699. var testCase = new goog.testing.TestCase();
  700. var e1 = new goog.testing.JsUnitException('foo123');
  701. var e2 = new goog.testing.JsUnitException('bar456');
  702. var mockRecordError = goog.testing.MethodMock(testCase, 'recordError_');
  703. mockRecordError('test', e1);
  704. mockRecordError('test', e2);
  705. mockRecordError.$replay();
  706. testCase.thrownAssertionExceptions_.push(e1);
  707. testCase.thrownAssertionExceptions_.push(e2);
  708. var exception = testCase.reportUnpropagatedAssertionExceptions_('test');
  709. assertContains('One or more assertions were', exception.toString());
  710. mockRecordError.$verify();
  711. mockRecordError.$tearDown();
  712. }
  713. function testSetObj() {
  714. var testCase = new goog.testing.TestCase();
  715. assertEquals(0, testCase.getCount());
  716. testCase.setTestObj({testOk: ok, somethingElse: fail});
  717. assertEquals(1, testCase.getCount());
  718. }
  719. function testSetObj_es6Class() {
  720. var FooTest;
  721. try {
  722. eval(
  723. 'FooTest = class { testOk() {assertTrue(true); } somethingElse() {} }');
  724. } catch (ex) {
  725. // IE cannot parse ES6.
  726. return;
  727. }
  728. var testCase = new goog.testing.TestCase();
  729. assertEquals(0, testCase.getCount());
  730. testCase.setTestObj(new FooTest());
  731. assertEquals(1, testCase.getCount());
  732. }
  733. function testCurrentTestName() {
  734. var currentTestName = goog.testing.TestCase.currentTestName;
  735. assertEquals('testCurrentTestName', currentTestName);
  736. }
  737. function testCurrentTestNamePromise() {
  738. var getAssertSameTest = function() {
  739. var expectedTestCase = goog.testing.TestCase.getActiveTestCase();
  740. var expectedTestName = (expectedTestCase ? expectedTestCase.getName() :
  741. '<no active TestCase>') +
  742. '.' +
  743. (goog.testing.TestCase.currentTestName || '<no active test name>');
  744. var assertSameTest = function() {
  745. var currentTestCase = goog.testing.TestCase.getActiveTestCase();
  746. var currentTestName = (currentTestCase ? currentTestCase.getName() :
  747. '<no active TestCase>') +
  748. '.' + goog.testing.TestCase.currentTestName ||
  749. '<no active test name>';
  750. assertEquals(expectedTestName, currentTestName);
  751. assertEquals(expectedTestCase, currentTestCase);
  752. };
  753. return assertSameTest;
  754. };
  755. var assertSameTest = getAssertSameTest();
  756. // do something asynchronously...
  757. return new goog.Promise(function(resolve, reject) {
  758. // ... ensure the earlier half runs during the same test ...
  759. assertSameTest();
  760. setTimeout(function() {
  761. // ... and also ensure the later half runs during the same test:
  762. try {
  763. assertSameTest();
  764. resolve();
  765. } catch (assertionFailureOrResolveException) {
  766. reject(assertionFailureOrResolveException);
  767. }
  768. });
  769. });
  770. }
  771. var testDoneTestsSeen = [];
  772. var testDoneErrorsSeen = {};
  773. var testDoneRuntime = {};
  774. /**
  775. * @param {goog.testing.TestCase} test
  776. * @param {Array<string>} errors
  777. */
  778. function storeCallsAndErrors(test, errors) {
  779. testDoneTestsSeen.push(test.name);
  780. testDoneErrorsSeen[test.name] = [];
  781. for (var i = 0; i < errors.length; i++) {
  782. testDoneErrorsSeen[test.name].push(errors[i].split('\n')[0]);
  783. }
  784. testDoneRuntime[test.name] = test.getElapsedTime();
  785. }
  786. /**
  787. * @param {Array<goog.testing.TestCase>} expectedTests
  788. * @param {Array<Array<string>>} expectedErrors
  789. */
  790. function assertStoreCallsAndErrors(expectedTests, expectedErrors) {
  791. assertArrayEquals(expectedTests, testDoneTestsSeen);
  792. for (var i = 0; i < expectedTests.length; i++) {
  793. var name = expectedTests[i];
  794. assertArrayEquals(expectedErrors, testDoneErrorsSeen[name]);
  795. assertEquals(typeof testDoneRuntime[testDoneTestsSeen[i]], 'number');
  796. }
  797. }
  798. function testCallbackToTestDoneOk() {
  799. testDoneTestsSeen = [];
  800. testDoneErrorsSeen = {};
  801. testDoneRuntime = {};
  802. var testCase = new goog.testing.TestCase('fooCase');
  803. testCase.addNewTest('foo', okGoogPromise);
  804. testCase.setTestDoneCallback(storeCallsAndErrors);
  805. return testCase.runTestsReturningPromise().then(function() {
  806. assertStoreCallsAndErrors(['foo'], []);
  807. });
  808. }
  809. function testCallbackToTestDoneFail() {
  810. testDoneTestsSeen = [];
  811. testDoneErrorsSeen = [];
  812. testDoneRuntime = {};
  813. var testCase = new goog.testing.TestCase('fooCase');
  814. testCase.addNewTest('foo', failGoogPromise);
  815. testCase.setTestDoneCallback(storeCallsAndErrors);
  816. return testCase.runTestsReturningPromise().then(function() {
  817. assertStoreCallsAndErrors(['foo'], ['ERROR in foo']);
  818. });
  819. }
  820. /**
  821. * @return {!Promise<null>}
  822. */
  823. function mockTestName() {
  824. return failGoogPromise();
  825. }
  826. function testInitializeTestCase() {
  827. testDoneTestsSeen = [];
  828. testDoneErrorsSeen = [];
  829. var testCase = new goog.testing.TestCase('fooCase');
  830. testCase.getAutoDiscoveryPrefix = function() {
  831. return 'mockTestName';
  832. };
  833. var outerTestCase = goog.testing.TestCase.getActiveTestCase();
  834. goog.global['G_testRunner'].testCase = null;
  835. goog.testing.TestCase.initializeTestCase(testCase, storeCallsAndErrors);
  836. var checkAfterInitialize = goog.testing.TestCase.getActiveTestCase();
  837. goog.global['G_testRunner'].testCase = outerTestCase;
  838. // This asserts require G_testRunner to be set.
  839. assertEquals(checkAfterInitialize, testCase);
  840. assertEquals(goog.testing.TestCase.getActiveTestCase(), outerTestCase);
  841. // If the individual test feature is used to selecte this test, erase it.
  842. testCase.setTestsToRun(null);
  843. return testCase.runTestsReturningPromise().then(function() {
  844. assertStoreCallsAndErrors(['mockTestName'], ['ERROR in mockTestName']);
  845. });
  846. }