Debian Codegraph @

closure-library/closure/goog/labs/testing/environment.js

raw
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
15 goog.provide('goog.labs.testing.Environment');
16
17 goog.require('goog.Thenable');
18 goog.require('goog.array');
19 goog.require('goog.asserts');
20 goog.require('goog.debug.Console');
21 goog.require('goog.testing.MockClock');
22 goog.require('goog.testing.MockControl');
23 goog.require('goog.testing.PropertyReplacer');
24 goog.require('goog.testing.TestCase');
25 goog.require('goog.testing.jsunit');
26
27
28 /**
29 * JsUnit environments allow developers to customize the existing testing
30 * lifecycle by hitching additional setUp and tearDown behaviors to tests.
31 *
32 * Environments will run their setUp steps in the order in which they
33 * are instantiated and registered. During tearDown, the environments will
34 * unwind the setUp and execute in reverse order.
35 *
36 * See http://go/jsunit-env for more information.
37 */
38 goog.labs.testing.Environment = goog.defineClass(null, {
39 /** @constructor */
40 constructor: function() {
41 var testcase = goog.labs.testing.EnvironmentTestCase_.getInstance();
42 testcase.registerEnvironment_(this);
43
44 // Record the active test case, in normal usage this is a singleton,
45 // but while testing this case it is reset.
46 goog.labs.testing.Environment.activeTestCase_ = testcase;
47
48 /** @type {goog.testing.MockControl} */
49 this.mockControl = null;
50
51 /** @type {goog.testing.MockClock} */
52 this.mockClock = null;
53
54 /** @private {boolean} */
55 this.shouldMakeMockControl_ = false;
56
57 /** @private {boolean} */
58 this.shouldMakeMockClock_ = false;
59
60 /** @const {!goog.debug.Console} */
61 this.console = goog.labs.testing.Environment.console_;
62
63 /** @const {!goog.testing.PropertyReplacer} */
64 this.replacer = new goog.testing.PropertyReplacer();
65 },
66
67
68 /**
69 * Runs immediately before the setUpPage phase of JsUnit tests.
70 * @return {!goog.Promise<?>|undefined} An optional Promise which must be
71 * resolved before the test is executed.
72 */
73 setUpPage: function() {
74 if (this.mockClock && this.mockClock.isDisposed()) {
75 this.mockClock = new goog.testing.MockClock(true);
76 }
77 },
78
79
80 /** Runs immediately after the tearDownPage phase of JsUnit tests. */
81 tearDownPage: function() {
82 // If we created the mockClock, we'll also dispose it.
83 if (this.shouldMakeMockClock_) {
84 this.mockClock.dispose();
85 }
86 },
87
88 /**
89 * Runs immediately before the setUp phase of JsUnit tests.
90 * @return {!goog.Promise<?>|undefined} An optional Promise which must be
91 * resolved before the test case is executed.
92 */
93 setUp: goog.nullFunction,
94
95 /** Runs immediately after the tearDown phase of JsUnit tests. */
96 tearDown: function() {
97 // Make sure promises and other stuff that may still be scheduled, get a
98 // chance to run (and throw errors).
99 if (this.mockClock) {
100 for (var i = 0; i < 100; i++) {
101 this.mockClock.tick(1000);
102 }
103 // If we created the mockClock, we'll also reset it.
104 if (this.shouldMakeMockClock_) {
105 this.mockClock.reset();
106 }
107 }
108 // Reset all changes made by the PropertyReplacer.
109 this.replacer.reset();
110 // Make sure the user did not forget to call $replayAll & $verifyAll in
111 // their test. This is a noop if they did.
112 // This is important because:
113 // - Engineers thinks that not all their tests need to replay and verify.
114 // That lets tests sneak in that call mocks but never replay those calls.
115 // - Then some well meaning maintenance engineer wants to update the test
116 // with some new mock, adds a replayAll and BOOM the test fails
117 // because completely unrelated mocks now get replayed.
118 if (this.mockControl) {
119 try {
120 this.mockControl.$verifyAll();
121 this.mockControl.$replayAll();
122 this.mockControl.$verifyAll();
123 } finally {
124 this.mockControl.$resetAll();
125 if (this.shouldMakeMockControl_) {
126 // If we created the mockControl, we'll also tear it down.
127 this.mockControl.$tearDown();
128 }
129 }
130 }
131 // Verifying the mockControl may throw, so if cleanup needs to happen,
132 // add it further up in the function.
133 },
134
135
136 /**
137 * Create a new {@see goog.testing.MockControl} accessible via
138 * {@code env.mockControl} for each test. If your test has more than one
139 * testing environment, don't call this on more than one of them.
140 * @return {!goog.labs.testing.Environment} For chaining.
141 */
142 withMockControl: function() {
143 if (!this.shouldMakeMockControl_) {
144 this.shouldMakeMockControl_ = true;
145 this.mockControl = new goog.testing.MockControl();
146 }
147 return this;
148 },
149
150
151 /**
152 * Create a {@see goog.testing.MockClock} for each test. The clock will be
153 * installed (override i.e. setTimeout) by default. It can be accessed
154 * using {@code env.mockClock}. If your test has more than one testing
155 * environment, don't call this on more than one of them.
156 * @return {!goog.labs.testing.Environment} For chaining.
157 */
158 withMockClock: function() {
159 if (!this.shouldMakeMockClock_) {
160 this.shouldMakeMockClock_ = true;
161 this.mockClock = new goog.testing.MockClock(true);
162 }
163 return this;
164 },
165
166
167 /**
168 * Creates a basic strict mock of a {@code toMock}. For more advanced mocking,
169 * please use the MockControl directly.
170 * @param {Function} toMock
171 * @return {!goog.testing.StrictMock}
172 */
173 mock: function(toMock) {
174 if (!this.shouldMakeMockControl_) {
175 throw new Error(
176 'MockControl not available on this environment. ' +
177 'Call withMockControl if this environment is expected ' +
178 'to contain a MockControl.');
179 }
180 return this.mockControl.createStrictMock(toMock);
181 }
182 });
183
184
185 /**
186 * @private {?goog.testing.TestCase}
187 */
188 goog.labs.testing.Environment.activeTestCase_ = null;
189
190
191 // TODO(johnlenz): make this package private when it moves out of labs.
192 /**
193 * @return {?goog.testing.TestCase}
194 */
195 goog.labs.testing.Environment.getTestCaseIfActive = function() {
196 return goog.labs.testing.Environment.activeTestCase_;
197 };
198
199
200 /** @private @const {!goog.debug.Console} */
201 goog.labs.testing.Environment.console_ = new goog.debug.Console();
202
203
204 // Activate logging to the browser's console by default.
205 goog.labs.testing.Environment.console_.setCapturing(true);
206
207
208
209 /**
210 * An internal TestCase used to hook environments into the JsUnit test runner.
211 * Environments cannot be used in conjunction with custom TestCases for JsUnit.
212 * @private @final @constructor
213 * @extends {goog.testing.TestCase}
214 */
215 goog.labs.testing.EnvironmentTestCase_ = function() {
216 goog.labs.testing.EnvironmentTestCase_.base(this, 'constructor');
217
218 /** @private {!Array<!goog.labs.testing.Environment>}> */
219 this.environments_ = [];
220
221 /** @private {!Object} */
222 this.testobj_ = goog.global; // default
223
224 // Automatically install this TestCase when any environment is used in a test.
225 goog.testing.TestCase.initializeTestRunner(this);
226 };
227 goog.inherits(goog.labs.testing.EnvironmentTestCase_, goog.testing.TestCase);
228 goog.addSingletonGetter(goog.labs.testing.EnvironmentTestCase_);
229
230
231 /**
232 * @param {!Object} obj An object providing the test and life cycle methods.
233 * @override
234 */
235 goog.labs.testing.EnvironmentTestCase_.prototype.setTestObj = function(obj) {
236 goog.asserts.assert(
237 this.testobj_ == goog.global,
238 'A test method object has already been provided ' +
239 'and only one is supported.');
240 this.testobj_ = obj;
241 goog.labs.testing.EnvironmentTestCase_.base(this, 'setTestObj', obj);
242 };
243
244
245 /**
246 * Override the default global scope discovery of lifecycle functions to prevent
247 * overriding the custom environment setUp(Page)/tearDown(Page) logic.
248 * @override
249 */
250 goog.labs.testing.EnvironmentTestCase_.prototype.autoDiscoverLifecycle =
251 function() {
252 if (this.testobj_['runTests']) {
253 this.runTests = goog.bind(this.testobj_['runTests'], this.testobj_);
254 }
255 if (this.testobj_['shouldRunTests']) {
256 this.shouldRunTests =
257 goog.bind(this.testobj_['shouldRunTests'], this.testobj_);
258 }
259 };
260
261 /**
262 * @override
263 */
264 goog.labs.testing.EnvironmentTestCase_.prototype.createTest = function(
265 name, ref, scope, objChain) {
266 return new goog.labs.testing.EnvironmentTest_(name, ref, scope, objChain);
267 };
268
269
270 /**
271 * Adds an environment to the JsUnit test.
272 * @param {!goog.labs.testing.Environment} env
273 * @private
274 */
275 goog.labs.testing.EnvironmentTestCase_.prototype.registerEnvironment_ =
276 function(env) {
277 this.environments_.push(env);
278 };
279
280
281 /** @override */
282 goog.labs.testing.EnvironmentTestCase_.prototype.setUpPage = function() {
283 var setUpPageFns = goog.array.map(this.environments_, function(env) {
284 return goog.bind(env.setUpPage, env);
285 }, this);
286
287 // User defined setUpPage method.
288 if (this.testobj_['setUpPage']) {
289 setUpPageFns.push(goog.bind(this.testobj_['setUpPage'], this.testobj_));
290 }
291 return this.callAndChainPromises_(setUpPageFns);
292 };
293
294
295 /** @override */
296 goog.labs.testing.EnvironmentTestCase_.prototype.setUp = function() {
297 var setUpFns = [];
298 // User defined configure method.
299 if (this.testobj_['configureEnvironment']) {
300 setUpFns.push(
301 goog.bind(this.testobj_['configureEnvironment'], this.testobj_));
302 }
303 var test = this.getCurrentTest();
304 if (test instanceof goog.labs.testing.EnvironmentTest_) {
305 goog.array.extend(setUpFns, test.configureEnvironments);
306 }
307
308 goog.array.forEach(this.environments_, function(env) {
309 setUpFns.push(goog.bind(env.setUp, env));
310 }, this);
311
312 // User defined setUp method.
313 if (this.testobj_['setUp']) {
314 setUpFns.push(goog.bind(this.testobj_['setUp'], this.testobj_));
315 }
316 return this.callAndChainPromises_(setUpFns);
317 };
318
319
320 /**
321 * Calls a chain of methods and makes sure to properly chain them if any of the
322 * methods returns a thenable.
323 * @param {!Array<function()>} fns
324 * @return {!goog.Thenable|undefined}
325 * @private
326 */
327 goog.labs.testing.EnvironmentTestCase_.prototype.callAndChainPromises_ =
328 function(fns) {
329 return goog.array.reduce(fns, function(previousResult, fn) {
330 if (goog.Thenable.isImplementedBy(previousResult)) {
331 return previousResult.then(function() {
332 return fn();
333 });
334 }
335 return fn();
336 }, undefined /* initialValue */, this);
337 };
338
339
340 /** @override */
341 goog.labs.testing.EnvironmentTestCase_.prototype.tearDown = function() {
342 var firstException;
343 // User defined tearDown method.
344 if (this.testobj_['tearDown']) {
345 try {
346 this.testobj_['tearDown']();
347 } catch (e) {
348 if (!firstException) {
349 firstException = e || new Error('Exception thrown: ' + String(e));
350 }
351 }
352 }
353
354 // Execute the tearDown methods for the environment in the reverse order
355 // in which they were registered to "unfold" the setUp.
356 goog.array.forEachRight(this.environments_, function(env) {
357 // For tearDowns between tests make sure they run as much as possible to
358 // avoid interference between tests.
359 try {
360 env.tearDown();
361 } catch (e) {
362 if (!firstException) {
363 firstException = e || new Error('Exception thrown: ' + String(e));
364 }
365 }
366 });
367 if (firstException) {
368 throw firstException;
369 }
370 };
371
372
373 /** @override */
374 goog.labs.testing.EnvironmentTestCase_.prototype.tearDownPage = function() {
375 // User defined tearDownPage method.
376 if (this.testobj_['tearDownPage']) {
377 this.testobj_['tearDownPage']();
378 }
379
380 goog.array.forEachRight(
381 this.environments_, function(env) { env.tearDownPage(); });
382 };
383
384 /**
385 * An internal Test used to hook environments into the JsUnit test runner.
386 * @param {string} name The test name.
387 * @param {function()} ref Reference to the test function or test object.
388 * @param {?Object=} scope Optional scope that the test function should be
389 * called in.
390 * @param {!Array<!Object>=} objChain A chain of objects used to populate setUps
391 * and tearDowns.
392 * @private
393 * @final
394 * @constructor
395 * @extends {goog.testing.TestCase.Test}
396 */
397 goog.labs.testing.EnvironmentTest_ = function(name, ref, scope, objChain) {
398 goog.labs.testing.EnvironmentTest_.base(
399 this, 'constructor', name, ref, scope, objChain);
400
401 /**
402 * @type {!Array<function()>}
403 */
404 this.configureEnvironments = goog.array.map(
405 goog.array.filter(
406 objChain || [],
407 function(obj) {
408 return goog.isFunction(obj.configureEnvironment);
409 }), /**
410 * @param {{configureEnvironment: function()}} obj
411 * @return {function()}
412 */
413 function(obj) {
414 return goog.bind(obj.configureEnvironment, obj);
415 });
416 };
417 goog.inherits(goog.labs.testing.EnvironmentTest_, goog.testing.TestCase.Test);