Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(4)

Side by Side Diff: chrome/browser/resources/google_now/background_unittest.gtestjs

Issue 207243002: Google Now Card Processing Pipeline Refactor (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Rebase Unit Tests Created 6 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « chrome/browser/resources/google_now/background_test_util.js ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // TODO(robliao,vadimt): Determine the granularity of testing to perform. 5 // TODO(robliao,vadimt): Determine the granularity of testing to perform.
6 6
7 /** 7 /**
8 * Test fixture for background.js. 8 * Test fixture for background.js.
9 * @constructor 9 * @constructor
10 * @extends {testing.Test} 10 * @extends {testing.Test}
11 */ 11 */
12 function GoogleNowBackgroundUnitTest () { 12 function GoogleNowBackgroundUnitTest () {
13 testing.Test.call(this); 13 testing.Test.call(this);
14 } 14 }
15 15
16 GoogleNowBackgroundUnitTest.prototype = { 16 GoogleNowBackgroundUnitTest.prototype = {
17 __proto__: testing.Test.prototype, 17 __proto__: testing.Test.prototype,
18 18
19 /** @override */ 19 /** @override */
20 extraLibraries: [ 20 extraLibraries: [
21 'common_test_util.js', 21 'common_test_util.js',
22 'background_test_util.js', 22 'background_test_util.js',
23 'background.js' 23 'background.js'
24 ] 24 ]
25 }; 25 };
26 26
27 TEST_F('GoogleNowBackgroundUnitTest', 'AreTasksConflicting', function() { 27 var TEST_NAME = 'GoogleNowBackgroundUnitTest';
28
29 /**
30 * Tasks Conflict Test
31 */
32 TEST_F(TEST_NAME, 'AreTasksConflicting', function() {
28 function testTaskPair(newTaskName, scheduledTaskName, expected) { 33 function testTaskPair(newTaskName, scheduledTaskName, expected) {
29 assertTrue(areTasksConflicting(newTaskName, scheduledTaskName) == expected, 34 assertTrue(areTasksConflicting(newTaskName, scheduledTaskName) == expected,
30 '(' + newTaskName + ', ' + scheduledTaskName + ')'); 35 '(' + newTaskName + ', ' + scheduledTaskName + ')');
31 } 36 }
32 37
33 testTaskPair(UPDATE_CARDS_TASK_NAME, UPDATE_CARDS_TASK_NAME, true); 38 testTaskPair(UPDATE_CARDS_TASK_NAME, UPDATE_CARDS_TASK_NAME, true);
34 testTaskPair(UPDATE_CARDS_TASK_NAME, DISMISS_CARD_TASK_NAME, false); 39 testTaskPair(UPDATE_CARDS_TASK_NAME, DISMISS_CARD_TASK_NAME, false);
35 testTaskPair(UPDATE_CARDS_TASK_NAME, RETRY_DISMISS_TASK_NAME, false); 40 testTaskPair(UPDATE_CARDS_TASK_NAME, RETRY_DISMISS_TASK_NAME, false);
36 testTaskPair(UPDATE_CARDS_TASK_NAME, STATE_CHANGED_TASK_NAME, false); 41 testTaskPair(UPDATE_CARDS_TASK_NAME, STATE_CHANGED_TASK_NAME, false);
37 42
38 testTaskPair(DISMISS_CARD_TASK_NAME, UPDATE_CARDS_TASK_NAME, false); 43 testTaskPair(DISMISS_CARD_TASK_NAME, UPDATE_CARDS_TASK_NAME, false);
39 testTaskPair(DISMISS_CARD_TASK_NAME, DISMISS_CARD_TASK_NAME, false); 44 testTaskPair(DISMISS_CARD_TASK_NAME, DISMISS_CARD_TASK_NAME, false);
40 testTaskPair(DISMISS_CARD_TASK_NAME, RETRY_DISMISS_TASK_NAME, false); 45 testTaskPair(DISMISS_CARD_TASK_NAME, RETRY_DISMISS_TASK_NAME, false);
41 testTaskPair(DISMISS_CARD_TASK_NAME, STATE_CHANGED_TASK_NAME, false); 46 testTaskPair(DISMISS_CARD_TASK_NAME, STATE_CHANGED_TASK_NAME, false);
42 47
43 testTaskPair(RETRY_DISMISS_TASK_NAME, UPDATE_CARDS_TASK_NAME, true); 48 testTaskPair(RETRY_DISMISS_TASK_NAME, UPDATE_CARDS_TASK_NAME, true);
44 testTaskPair(RETRY_DISMISS_TASK_NAME, DISMISS_CARD_TASK_NAME, true); 49 testTaskPair(RETRY_DISMISS_TASK_NAME, DISMISS_CARD_TASK_NAME, true);
45 testTaskPair(RETRY_DISMISS_TASK_NAME, RETRY_DISMISS_TASK_NAME, true); 50 testTaskPair(RETRY_DISMISS_TASK_NAME, RETRY_DISMISS_TASK_NAME, true);
46 testTaskPair(RETRY_DISMISS_TASK_NAME, STATE_CHANGED_TASK_NAME, false); 51 testTaskPair(RETRY_DISMISS_TASK_NAME, STATE_CHANGED_TASK_NAME, false);
47 52
48 testTaskPair(STATE_CHANGED_TASK_NAME, UPDATE_CARDS_TASK_NAME, false); 53 testTaskPair(STATE_CHANGED_TASK_NAME, UPDATE_CARDS_TASK_NAME, false);
49 testTaskPair(STATE_CHANGED_TASK_NAME, DISMISS_CARD_TASK_NAME, false); 54 testTaskPair(STATE_CHANGED_TASK_NAME, DISMISS_CARD_TASK_NAME, false);
50 testTaskPair(STATE_CHANGED_TASK_NAME, RETRY_DISMISS_TASK_NAME, false); 55 testTaskPair(STATE_CHANGED_TASK_NAME, RETRY_DISMISS_TASK_NAME, false);
51 testTaskPair(STATE_CHANGED_TASK_NAME, STATE_CHANGED_TASK_NAME, false); 56 testTaskPair(STATE_CHANGED_TASK_NAME, STATE_CHANGED_TASK_NAME, false);
52 }); 57 });
53 58
54 /** 59 /**
55 * Server Request Tests 60 * Server Request Tests
56 */ 61 */
57 TEST_F('GoogleNowBackgroundUnitTest', 'AuthServerRequestSuccess', function() { 62 TEST_F(TEST_NAME, 'AuthServerRequestSuccess', function() {
58 expectServerRequests(this, 200, '{}'); 63 expectServerRequests(this, 200, '{}');
59 var callbackCalled = false; 64 var callbackCalled = false;
60 requestFromServer('GET', 'test/target').then(function(request) { 65 requestFromServer('GET', 'test/target').then(function(request) {
61 callbackCalled = true; 66 callbackCalled = true;
62 assertTrue(request.status === 200); 67 assertTrue(request.status === 200);
63 assertTrue(request.responseText === '{}'); 68 assertTrue(request.responseText === '{}');
64 }); 69 });
65 assertTrue(callbackCalled); 70 assertTrue(callbackCalled);
66 }); 71 });
67 72
68 TEST_F('GoogleNowBackgroundUnitTest', 'AuthServerRequestForbidden', function() { 73 TEST_F(TEST_NAME, 'AuthServerRequestForbidden', function() {
69 this.makeAndRegisterMockApis(['authenticationManager.removeToken']); 74 this.makeAndRegisterMockApis(['authenticationManager.removeToken']);
70 this.mockApis.expects(once()).authenticationManager_removeToken(ANYTHING); 75 this.mockApis.expects(once()).authenticationManager_removeToken(ANYTHING);
71 76
72 expectServerRequests(this, 403, ''); 77 expectServerRequests(this, 403, '');
73 78
74 var callbackCalled = false; 79 var callbackCalled = false;
75 requestFromServer('GET', 'test/target').then(function(request) { 80 requestFromServer('GET', 'test/target').then(function(request) {
76 // The promise is resolved even on HTTP failures. 81 // The promise is resolved even on HTTP failures.
77 callbackCalled = true; 82 callbackCalled = true;
78 assertTrue(request.status === 403); 83 assertTrue(request.status === 403);
79 }); 84 });
80 assertTrue(callbackCalled); 85 assertTrue(callbackCalled);
81 }); 86 });
82 87
83 TEST_F('GoogleNowBackgroundUnitTest', 'AuthServerRequestNoAuth', function() { 88 TEST_F(TEST_NAME, 'AuthServerRequestNoAuth', function() {
84 this.makeAndRegisterMockApis(['authenticationManager.removeToken']); 89 this.makeAndRegisterMockApis(['authenticationManager.removeToken']);
85 this.mockApis.expects(once()).authenticationManager_removeToken(ANYTHING); 90 this.mockApis.expects(once()).authenticationManager_removeToken(ANYTHING);
86 91
87 expectServerRequests(this, 401, ''); 92 expectServerRequests(this, 401, '');
88 93
89 var callbackCalled = false; 94 var callbackCalled = false;
90 requestFromServer('GET', 'test/target').then(function(request) { 95 requestFromServer('GET', 'test/target').then(function(request) {
91 // The promise is resolved even on HTTP failures. 96 // The promise is resolved even on HTTP failures.
92 callbackCalled = true; 97 callbackCalled = true;
93 assertTrue(request.status === 401); 98 assertTrue(request.status === 401);
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
129 loadEndSavedArgs.match(eq(false))); 134 loadEndSavedArgs.match(eq(false)));
130 135
131 mockXMLHttpRequestProxy.status = httpStatus; 136 mockXMLHttpRequestProxy.status = httpStatus;
132 mockXMLHttpRequestProxy.response = responseText; 137 mockXMLHttpRequestProxy.response = responseText;
133 mockXMLHttpRequestProxy.responseText = responseText; 138 mockXMLHttpRequestProxy.responseText = responseText;
134 139
135 mockXMLHttpRequest.expects(once()).send() 140 mockXMLHttpRequest.expects(once()).send()
136 .will(invokeCallback(loadEndSavedArgs, 1, mockXMLHttpRequestProxy)); 141 .will(invokeCallback(loadEndSavedArgs, 1, mockXMLHttpRequestProxy));
137 } 142 }
138 143
139 TEST_F('GoogleNowBackgroundUnitTest', 'AuthServerRequestNoToken', function() { 144 TEST_F(TEST_NAME, 'AuthServerRequestNoToken', function() {
140 this.makeAndRegisterMockApis([ 145 this.makeAndRegisterMockApis([
141 'authenticationManager.getAuthToken', 146 'authenticationManager.getAuthToken',
142 'buildServerRequest' 147 'buildServerRequest'
143 ]); 148 ]);
144 149
145 this.mockApis.expects(once()).authenticationManager_getAuthToken() 150 this.mockApis.expects(once()).authenticationManager_getAuthToken()
146 .will(returnValue(Promise.reject())); 151 .will(returnValue(Promise.reject()));
147 this.mockApis.expects(never()).buildServerRequest() 152 this.mockApis.expects(never()).buildServerRequest()
148 153
149 var thenCalled = false; 154 var thenCalled = false;
150 var catchCalled = false; 155 var catchCalled = false;
151 requestFromServer('GET', 'test/target').then(function(request) { 156 requestFromServer('GET', 'test/target').then(function(request) {
152 thenCalled = true; 157 thenCalled = true;
153 }).catch(function() { 158 }).catch(function() {
154 catchCalled = true; 159 catchCalled = true;
155 }); 160 });
156 assertFalse(thenCalled); 161 assertFalse(thenCalled);
157 assertTrue(catchCalled); 162 assertTrue(catchCalled);
158 }) 163 })
159 164
160 /** 165 /**
166 * requestNotificationGroupsFromServer Tests
167 */
168 TEST_F(TEST_NAME, 'RequestNotificationGroupsFromServerEmpty', function() {
169 this.makeAndRegisterMockGlobals([
170 'shouldShowExplanatoryCard',
171 'recordEvent',
172 'requestFromServer'
173 ]);
174
175 this.mockGlobals.expects(once()).shouldShowExplanatoryCard()
176 .will(returnValue(false));
177
178 this.mockGlobals.expects(once()).recordEvent(
179 GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);
180
181 this.mockGlobals.expects(once()).recordEvent(
182 GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
183
184 var requestFromServerArgs = new SaveMockArguments();
185 this.mockGlobals.expects(once()).requestFromServer(
186 requestFromServerArgs.match(eq('GET')),
187 requestFromServerArgs.match(ANYTHING))
188 .will(returnValue(
189 Promise.resolve({status: 200, responseText: "{}"})));
190
191 requestNotificationGroupsFromServer([]);
192
193 var pathAndQuery = requestFromServerArgs.arguments[1];
194 var query = pathAndQuery.split('?')[1];
195 assertTrue(query.search('timeZoneOffsetMs') >= 0);
196 assertTrue(query.search('uiLocale') >= 0);
197 assertFalse(query.search('cardExplanation') >= 0);
198 });
199
200 TEST_F(TEST_NAME, 'RequestNotificationGroupsFromServerWithGroups', function() {
201 this.makeAndRegisterMockGlobals([
202 'shouldShowExplanatoryCard',
203 'recordEvent',
204 'requestFromServer'
205 ]);
206
207 this.mockGlobals.expects(once()).shouldShowExplanatoryCard()
208 .will(returnValue(false));
209
210 this.mockGlobals.expects(once()).recordEvent(
211 GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);
212
213 this.mockGlobals.expects(once()).recordEvent(
214 GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
215
216 var requestFromServerArgs = new SaveMockArguments();
217 this.mockGlobals.expects(once()).requestFromServer(
218 requestFromServerArgs.match(eq('GET')),
219 requestFromServerArgs.match(ANYTHING))
220 .will(returnValue(
221 Promise.resolve({status: 200, responseText: "{}"})));
222
223 requestNotificationGroupsFromServer(['A', 'B', 'C']);
224
225 var pathAndQuery = requestFromServerArgs.arguments[1];
226 var query = pathAndQuery.split('?')[1];
227 assertTrue(query.search('timeZoneOffsetMs') >= 0);
228 assertTrue(query.search('uiLocale') >= 0);
229 assertFalse(query.search('cardExplanation') >= 0);
230 assertTrue(query.search('requestTypes=A') >= 0);
231 assertTrue(query.search('requestTypes=B') >= 0);
232 assertTrue(query.search('requestTypes=C') >= 0);
233 });
234
235 TEST_F(TEST_NAME, 'RequestNotificationGroupsFromServerExplanatory', function() {
236 this.makeAndRegisterMockGlobals([
237 'shouldShowExplanatoryCard',
238 'recordEvent',
239 'requestFromServer'
240 ]);
241
242 this.mockGlobals.expects(once()).shouldShowExplanatoryCard()
243 .will(returnValue(true));
244
245 this.mockGlobals.expects(once()).recordEvent(
246 GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);
247
248 this.mockGlobals.expects(once()).recordEvent(
249 GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
250
251 var requestFromServerArgs = new SaveMockArguments();
252 this.mockGlobals.expects(once()).requestFromServer(
253 requestFromServerArgs.match(eq('GET')),
254 requestFromServerArgs.match(ANYTHING))
255 .will(returnValue(
256 Promise.resolve({status: 200, responseText: "{}"})));
257
258 requestNotificationGroupsFromServer([]);
259
260 var pathAndQuery = requestFromServerArgs.arguments[1];
261 var query = pathAndQuery.split('?')[1];
262 assertTrue(query.search('timeZoneOffsetMs') >= 0);
263 assertTrue(query.search('uiLocale') >= 0);
264 assertTrue(query.search('cardExplanation=true') >= 0);
265 });
266
267 TEST_F(TEST_NAME, 'RequestNotificationGroupsFromServerFailure', function() {
268 this.makeAndRegisterMockGlobals([
269 'shouldShowExplanatoryCard',
270 'recordEvent',
271 'requestFromServer'
272 ]);
273
274 this.mockGlobals.expects(once()).shouldShowExplanatoryCard()
275 .will(returnValue(false));
276
277 this.mockGlobals.expects(once()).recordEvent(
278 GoogleNowEvent.REQUEST_FOR_CARDS_TOTAL);
279
280 this.mockGlobals.expects(never()).recordEvent(
281 GoogleNowEvent.REQUEST_FOR_CARDS_SUCCESS);
282
283 var requestFromServerArgs = new SaveMockArguments();
284 this.mockGlobals.expects(once()).requestFromServer(
285 requestFromServerArgs.match(eq('GET')),
286 requestFromServerArgs.match(ANYTHING))
287 .will(returnValue(
288 Promise.resolve({status: 401})));
289
290 requestNotificationGroupsFromServer([]);
291 });
292
293 /**
294 * requestAndUpdateOptIn Tests
295 */
296 TEST_F(TEST_NAME, 'RequestAndUpdateOptInOptedIn', function() {
297 this.makeAndRegisterMockApis([
298 'chrome.storage.local.set',
299 'onStateChange',
300 'requestFromServer',
301 'scheduleNextPoll'
302 ]);
303
304 this.mockApis.expects(once()).requestFromServer('GET', 'settings/optin')
305 .will(returnValue(Promise.resolve({
306 status: 200,
307 responseText: '{"value": true}'})));
308
309 this.mockApis.expects(once())
310 .chrome_storage_local_set(eqJSON({googleNowEnabled: true}));
311
312 this.mockApis.expects(once()).onStateChange();
313
314 this.mockApis.expects(never()).scheduleNextPoll();
315
316 var thenCalled = false;
317 var catchCalled = false;
318 requestAndUpdateOptedIn().then(function() {
319 thenCalled = true;
320 }).catch(function() {
321 catchCalled = true;
322 });
323 assertTrue(thenCalled);
324 assertFalse(catchCalled);
325 });
326
327 TEST_F(TEST_NAME, 'RequestAndUpdateOptInOptedOut', function() {
328 this.makeAndRegisterMockApis([
329 'chrome.storage.local.set',
330 'onStateChange',
331 'requestFromServer',
332 'scheduleNextPoll'
333 ]);
334
335 this.mockApis.expects(once()).requestFromServer('GET', 'settings/optin')
336 .will(returnValue(Promise.resolve({
337 status: 200,
338 responseText: '{"value": false}'})));
339
340 this.mockApis.expects(never()).chrome_storage_local_set();
341
342 this.mockApis.expects(never()).onStateChange();
343
344 this.mockApis.expects(once()).scheduleNextPoll(eqJSON({}), false);
345
346 var thenCalled = false;
347 var catchCalled = false;
348 requestAndUpdateOptedIn().then(function() {
349 thenCalled = true;
350 }).catch(function() {
351 catchCalled = true;
352 });
353 assertFalse(thenCalled);
354 assertTrue(catchCalled);
355 });
356
357 TEST_F(TEST_NAME, 'RequestAndUpdateOptInFailure', function() {
358 this.makeAndRegisterMockApis([
359 'chrome.storage.local.set',
360 'onStateChange',
361 'requestFromServer',
362 'scheduleNextPoll'
363 ]);
364
365 this.mockApis.expects(once()).requestFromServer('GET', 'settings/optin')
366 .will(returnValue(Promise.resolve({status: 404})));
367
368 this.mockApis.expects(never()).chrome_storage_local_set();
369
370 this.mockApis.expects(never()).onStateChange();
371
372 this.mockApis.expects(never()).scheduleNextPoll();
373
374 var thenCalled = false;
375 var catchCalled = false;
376 requestAndUpdateOptedIn().then(function() {
377 thenCalled = true;
378 }).catch(function() {
379 catchCalled = true;
380 });
381 assertFalse(thenCalled);
382 assertTrue(catchCalled);
383 });
384
385 /**
386 * getGroupsToRequest Tests
387 */
388 TEST_F(TEST_NAME, 'GetGroupsToRequestNone', function() {
389 this.makeAndRegisterMockApis([
390 'fillFromChromeLocalStorage',
391 'Date.now'
392 ]);
393
394 this.mockApis.expects(once())
395 .fillFromChromeLocalStorage(eqJSON({notificationGroups: {}}))
396 .will(returnValue(Promise.resolve({notificationGroups: {}})));
397
398 this.mockApis.expects(once()).Date_now().will(returnValue(20));
399
400 getGroupsToRequest().then(function(groupsToRequest) {
401 assertTrue(JSON.stringify(groupsToRequest) === '[]');
402 });
403 });
404
405 TEST_F(TEST_NAME, 'GetGroupsToRequestWithGroups', function() {
406 this.makeAndRegisterMockApis([
407 'fillFromChromeLocalStorage',
408 'Date.now'
409 ]);
410
411 this.mockApis.expects(once())
412 .fillFromChromeLocalStorage(eqJSON({notificationGroups: {}}))
413 .will(returnValue(Promise.resolve({notificationGroups: {
414 TIME18: {nextPollTime: 18},
415 TIME19: {nextPollTime: 19},
416 TIME20: {nextPollTime: 20},
417 TIME21: {nextPollTime: 21},
418 TIME22: {nextPollTime: 22},
419 TIMEUNDEF: {}
420 }})));
421
422 this.mockApis.expects(once()).Date_now().will(returnValue(20));
423
424 getGroupsToRequest().then(function(groupsToRequest) {
425 assertTrue(groupsToRequest.length == 3);
426 assertTrue(groupsToRequest.indexOf('TIME18') >= 0);
427 assertTrue(groupsToRequest.indexOf('TIME19') >= 0);
428 assertTrue(groupsToRequest.indexOf('TIME20') >= 0);
429 });
430 });
431
432 /**
433 * combineGroup Tests
434 */
435 TEST_F(TEST_NAME, 'CombineGroup', function() {
436 // Tests combineGroup function. Verifies that both notifications with and
437 // without show time are handled correctly and that cards are correctly
438 // added to existing cards with same ID or start a new combined card.
439
440 // Setup and expectations.
441 var combinedCards = {
442 'EXISTING CARD': [1]
443 };
444
445 var receivedNotificationNoShowTime = {
446 chromeNotificationId: 'EXISTING CARD',
447 trigger: {hideTimeSec: 1}
448 };
449 var receivedNotificationWithShowTime = {
450 chromeNotificationId: 'NEW CARD',
451 trigger: {showTimeSec: 2, hideTimeSec: 3}
452 }
453
454 var storedGroup = {
455 cardsTimestamp: 10000,
456 cards: [
457 receivedNotificationNoShowTime,
458 receivedNotificationWithShowTime
459 ]
460 };
461
462 // Invoking the tested function.
463 combineGroup(combinedCards, storedGroup);
464
465 // Check the output value.
466 var expectedCombinedCards = {
467 'EXISTING CARD': [
468 1,
469 {
470 receivedNotification: receivedNotificationNoShowTime,
471 hideTime: 11000
472 }
473 ],
474 'NEW CARD': [
475 {
476 receivedNotification: receivedNotificationWithShowTime,
477 showTime: 12000,
478 hideTime: 13000
479 }
480 ]
481 };
482
483 assertEquals(
484 JSON.stringify(expectedCombinedCards),
485 JSON.stringify(combinedCards));
486 });
487
488 /**
161 * Mocks global functions and APIs that initialize() depends upon. 489 * Mocks global functions and APIs that initialize() depends upon.
162 * @param {Test} fixture Test fixture. 490 * @param {Test} fixture Test fixture.
163 */ 491 */
164 function mockInitializeDependencies(fixture) { 492 function mockInitializeDependencies(fixture) {
165 fixture.makeAndRegisterMockGlobals([ 493 fixture.makeAndRegisterMockGlobals([
166 'recordEvent', 494 'recordEvent',
167 'setBackgroundEnable', 495 'setBackgroundEnable',
168 'startPollingCards' 496 'startPollingCards'
169 ]); 497 ]);
170 fixture.makeAndRegisterMockApis([ 498 fixture.makeAndRegisterMockApis([
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
250 will(invokeCallback(tasksAddSavedArgs, 1, function() {})); 578 will(invokeCallback(tasksAddSavedArgs, 1, function() {}));
251 var updateCardsAttemptsIsRunningSavedArgs = new SaveMockArguments(); 579 var updateCardsAttemptsIsRunningSavedArgs = new SaveMockArguments();
252 mockApisObj.expects(once()). 580 mockApisObj.expects(once()).
253 updateCardsAttempts_isRunning( 581 updateCardsAttempts_isRunning(
254 updateCardsAttemptsIsRunningSavedArgs.match(ANYTHING)). 582 updateCardsAttemptsIsRunningSavedArgs.match(ANYTHING)).
255 will( 583 will(
256 invokeCallback( 584 invokeCallback(
257 updateCardsAttemptsIsRunningSavedArgs, 0, false)); 585 updateCardsAttemptsIsRunningSavedArgs, 0, false));
258 } 586 }
259 587
260 TEST_F( 588 TEST_F(TEST_NAME,'Initialize_ToastStateEmpty', function() {
261 'GoogleNowBackgroundUnitTest', 589 // Tests the case when getAuthToken fails most likely because the user is
262 'Initialize_ToastStateEmpty', 590 // not signed in. In this case, the function should quietly exit after
263 function() { 591 // finding out that getAuthToken fails.
264 // Tests the case when getAuthToken fails most likely because the user is
265 // not signed in. In this case, the function should quietly exit after
266 // finding out that getAuthToken fails.
267 592
268 // Setup and expectations. 593 // Setup and expectations.
269 var testIdentityToken = undefined; 594 var testIdentityToken = undefined;
270 var testExperimentVariationParams = {}; 595 var testExperimentVariationParams = {};
271 var testNotificationPermissionLevel = 'denied'; 596 var testNotificationPermissionLevel = 'denied';
272 var testGoogleNowEnabled = undefined; 597 var testGoogleNowEnabled = undefined;
273 598
274 mockInitializeDependencies(this); 599 mockInitializeDependencies(this);
275 600
276 this.mockGlobals.expects(once()).recordEvent( 601 this.mockGlobals.expects(once()).recordEvent(GoogleNowEvent.EXTENSION_START);
277 GoogleNowEvent.EXTENSION_START);
278 602
279 this.mockGlobals.expects(once()).recordEvent( 603 this.mockGlobals.expects(once()).recordEvent(GoogleNowEvent.STOPPED);
280 GoogleNowEvent.STOPPED);
281 604
282 this.mockGlobals.expects(once()).recordEvent( 605 this.mockGlobals.expects(once()).recordEvent(
283 GoogleNowEvent.SIGNED_OUT); 606 GoogleNowEvent.SIGNED_OUT);
284 607
285 expectInitialization(this.mockApis); 608 expectInitialization(this.mockApis);
286 609
287 expectStateMachineCalls( 610 expectStateMachineCalls(
288 this, 611 this,
289 testIdentityToken, 612 testIdentityToken,
290 testExperimentVariationParams, 613 testExperimentVariationParams,
291 testNotificationPermissionLevel, 614 testNotificationPermissionLevel,
292 testGoogleNowEnabled); 615 testGoogleNowEnabled);
293 616
294 // Invoking the tested function. 617 // Invoking the tested function.
295 initialize(); 618 initialize();
296 }); 619 });
297 620
298 TEST_F('GoogleNowBackgroundUnitTest', 'Initialize_RunGoogleNow', function() { 621 TEST_F(TEST_NAME, 'Initialize_RunGoogleNow', function() {
299 // Tests if Google Now will invoke startPollingCards when all 622 // Tests if Google Now will invoke startPollingCards when all
300 // of the required state is fulfilled. 623 // of the required state is fulfilled.
301 624
302 // Setup and expectations. 625 // Setup and expectations.
303 var testIdentityToken = 'some identity token'; 626 var testIdentityToken = 'some identity token';
304 var testExperimentVariationParams = {}; 627 var testExperimentVariationParams = {};
305 var testNotificationPermissionLevel = 'granted'; 628 var testNotificationPermissionLevel = 'granted';
306 var testGoogleNowEnabled = true; 629 var testGoogleNowEnabled = true;
307 630
308 mockInitializeDependencies(this); 631 mockInitializeDependencies(this);
309 632
310 this.mockGlobals.expects(once()).recordEvent( 633 this.mockGlobals.expects(once()).recordEvent(GoogleNowEvent.EXTENSION_START);
311 GoogleNowEvent.EXTENSION_START);
312 634
313 expectInitialization(this.mockApis); 635 expectInitialization(this.mockApis);
314 636
315 expectStateMachineCalls( 637 expectStateMachineCalls(
316 this, 638 this,
317 testIdentityToken, 639 testIdentityToken,
318 testExperimentVariationParams, 640 testExperimentVariationParams,
319 testNotificationPermissionLevel, 641 testNotificationPermissionLevel,
320 testGoogleNowEnabled); 642 testGoogleNowEnabled);
321 643
322 this.mockGlobals.expects(once()).startPollingCards(); 644 this.mockGlobals.expects(once()).startPollingCards();
323 645
324 // Invoking the tested function. 646 // Invoking the tested function.
325 initialize(); 647 initialize();
326 }); 648 });
327 649
328 /** 650 /**
329 * No Cards Event Recording Tests 651 * No Cards Event Recording Tests
330 */ 652 */
331 TEST_F('GoogleNowBackgroundUnitTest', 'NoCardsSignedOut', function() { 653 TEST_F(TEST_NAME, 'NoCardsSignedOut', function() {
332 var signedIn = false; 654 var signedIn = false;
333 var notificationEnabled = false; 655 var notificationEnabled = false;
334 var googleNowEnabled = false; 656 var googleNowEnabled = false;
335 this.makeAndRegisterMockGlobals([ 657 this.makeAndRegisterMockGlobals([
336 'recordEvent', 658 'recordEvent',
337 'setBackgroundEnable', 659 'setBackgroundEnable',
338 'setShouldPollCards']); 660 'setShouldPollCards']);
339 661
340 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING); 662 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING);
341 this.mockGlobals.stubs().setShouldPollCards(ANYTHING); 663 this.mockGlobals.stubs().setShouldPollCards(ANYTHING);
342 664
343 this.mockGlobals.expects(once()).recordEvent( 665 this.mockGlobals.expects(once()).recordEvent(
344 GoogleNowEvent.STOPPED); 666 GoogleNowEvent.STOPPED);
345 this.mockGlobals.expects(once()).recordEvent( 667 this.mockGlobals.expects(once()).recordEvent(
346 GoogleNowEvent.SIGNED_OUT); 668 GoogleNowEvent.SIGNED_OUT);
347 this.mockGlobals.expects(never()).recordEvent( 669 this.mockGlobals.expects(never()).recordEvent(
348 GoogleNowEvent.NOTIFICATION_DISABLED); 670 GoogleNowEvent.NOTIFICATION_DISABLED);
349 this.mockGlobals.expects(never()).recordEvent( 671 this.mockGlobals.expects(never()).recordEvent(
350 GoogleNowEvent.GOOGLE_NOW_DISABLED); 672 GoogleNowEvent.GOOGLE_NOW_DISABLED);
351 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled); 673 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled);
352 }); 674 });
353 675
354 TEST_F( 676 TEST_F(TEST_NAME, 'NoCardsNotificationsDisabled', function() {
355 'GoogleNowBackgroundUnitTest', 677 var signedIn = true;
356 'NoCardsNotificationsDisabled', 678 var notificationEnabled = false;
357 function() { 679 var googleNowEnabled = false;
358 var signedIn = true; 680 this.makeAndRegisterMockGlobals([
359 var notificationEnabled = false; 681 'recordEvent',
360 var googleNowEnabled = false; 682 'setBackgroundEnable',
361 this.makeAndRegisterMockGlobals([ 683 'setShouldPollCards']);
362 'recordEvent',
363 'setBackgroundEnable',
364 'setShouldPollCards']);
365 684
366 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING); 685 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING);
367 this.mockGlobals.stubs().setShouldPollCards(ANYTHING); 686 this.mockGlobals.stubs().setShouldPollCards(ANYTHING);
368 687
369 this.mockGlobals.expects(once()).recordEvent( 688 this.mockGlobals.expects(once()).recordEvent(
370 GoogleNowEvent.STOPPED); 689 GoogleNowEvent.STOPPED);
371 this.mockGlobals.expects(never()).recordEvent( 690 this.mockGlobals.expects(never()).recordEvent(
372 GoogleNowEvent.SIGNED_OUT); 691 GoogleNowEvent.SIGNED_OUT);
373 this.mockGlobals.expects(once()).recordEvent( 692 this.mockGlobals.expects(once()).recordEvent(
374 GoogleNowEvent.NOTIFICATION_DISABLED); 693 GoogleNowEvent.NOTIFICATION_DISABLED);
375 this.mockGlobals.expects(never()).recordEvent( 694 this.mockGlobals.expects(never()).recordEvent(
376 GoogleNowEvent.GOOGLE_NOW_DISABLED); 695 GoogleNowEvent.GOOGLE_NOW_DISABLED);
377 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled); 696 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled);
378 }); 697 });
379 698
380 TEST_F('GoogleNowBackgroundUnitTest', 'NoCardsGoogleNowDisabled', function() { 699 TEST_F(TEST_NAME, 'NoCardsGoogleNowDisabled', function() {
381 var signedIn = true; 700 var signedIn = true;
382 var notificationEnabled = true; 701 var notificationEnabled = true;
383 var googleNowEnabled = false; 702 var googleNowEnabled = false;
384 this.makeAndRegisterMockGlobals([ 703 this.makeAndRegisterMockGlobals([
385 'recordEvent', 704 'recordEvent',
386 'setBackgroundEnable', 705 'setBackgroundEnable',
387 'setShouldPollCards']); 706 'setShouldPollCards']);
388 707
389 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING); 708 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING);
390 this.mockGlobals.stubs().setShouldPollCards(ANYTHING); 709 this.mockGlobals.stubs().setShouldPollCards(ANYTHING);
391 710
392 this.mockGlobals.expects(never()).recordEvent( 711 this.mockGlobals.expects(never()).recordEvent(
393 GoogleNowEvent.STOPPED); 712 GoogleNowEvent.STOPPED);
394 this.mockGlobals.expects(never()).recordEvent( 713 this.mockGlobals.expects(never()).recordEvent(
395 GoogleNowEvent.SIGNED_OUT); 714 GoogleNowEvent.SIGNED_OUT);
396 this.mockGlobals.expects(never()).recordEvent( 715 this.mockGlobals.expects(never()).recordEvent(
397 GoogleNowEvent.NOTIFICATION_DISABLED); 716 GoogleNowEvent.NOTIFICATION_DISABLED);
398 this.mockGlobals.expects(once()).recordEvent( 717 this.mockGlobals.expects(once()).recordEvent(
399 GoogleNowEvent.GOOGLE_NOW_DISABLED); 718 GoogleNowEvent.GOOGLE_NOW_DISABLED);
400 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled); 719 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled);
401 }); 720 });
402 721
403 TEST_F('GoogleNowBackgroundUnitTest', 'NoCardsEverythingEnabled', function() { 722 TEST_F(TEST_NAME, 'NoCardsEverythingEnabled', function() {
404 var signedIn = true; 723 var signedIn = true;
405 var notificationEnabled = true; 724 var notificationEnabled = true;
406 var googleNowEnabled = true; 725 var googleNowEnabled = true;
407 this.makeAndRegisterMockGlobals([ 726 this.makeAndRegisterMockGlobals([
408 'recordEvent', 727 'recordEvent',
409 'setBackgroundEnable', 728 'setBackgroundEnable',
410 'setShouldPollCards']); 729 'setShouldPollCards']);
411 730
412 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING); 731 this.mockGlobals.stubs().setBackgroundEnable(ANYTHING);
413 this.mockGlobals.stubs().setShouldPollCards(ANYTHING); 732 this.mockGlobals.stubs().setShouldPollCards(ANYTHING);
414 733
415 this.mockGlobals.expects(never()).recordEvent( 734 this.mockGlobals.expects(never()).recordEvent(
416 GoogleNowEvent.STOPPED); 735 GoogleNowEvent.STOPPED);
417 this.mockGlobals.expects(never()).recordEvent( 736 this.mockGlobals.expects(never()).recordEvent(
418 GoogleNowEvent.SIGNED_OUT); 737 GoogleNowEvent.SIGNED_OUT);
419 this.mockGlobals.expects(never()).recordEvent( 738 this.mockGlobals.expects(never()).recordEvent(
420 GoogleNowEvent.NOTIFICATION_DISABLED); 739 GoogleNowEvent.NOTIFICATION_DISABLED);
421 this.mockGlobals.expects(never()).recordEvent( 740 this.mockGlobals.expects(never()).recordEvent(
422 GoogleNowEvent.GOOGLE_NOW_DISABLED); 741 GoogleNowEvent.GOOGLE_NOW_DISABLED);
423 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled); 742 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled);
424 }); 743 });
425 744
426 /** 745 /**
427 * Mocks global functions and APIs that onNotificationClicked() depends upon. 746 * Mocks global functions and APIs that onNotificationClicked() depends upon.
428 * @param {Test} fixture Test fixture. 747 * @param {Test} fixture Test fixture.
429 */ 748 */
430 function mockOnNotificationClickedDependencies(fixture) { 749 function mockOnNotificationClickedDependencies(fixture) {
431 fixture.makeAndRegisterMockApis([ 750 fixture.makeAndRegisterMockApis([
432 'chrome.windows.create', 751 'chrome.windows.create',
433 'chrome.windows.update', 752 'chrome.windows.update',
434 'fillFromChromeLocalStorage', 753 'fillFromChromeLocalStorage',
435 'instrumented.tabs.create']); 754 'instrumented.tabs.create']);
436 } 755 }
437 756
438 TEST_F( 757 TEST_F(TEST_NAME, 'OnNotificationClicked_NoData', function() {
439 'GoogleNowBackgroundUnitTest', 758 // Tests the case when there is no data associated with notification id.
440 'OnNotificationClicked_NoData', 759 // In this case, the function should do nothing.
441 function() { 760
442 // Tests the case when there is no data associated with notification id. 761 // Setup and expectations.
443 // In this case, the function should do nothing. 762 var testNotificationId = 'TEST_ID';
444 763 var testNotificationDataRequest = {notificationsData: {}};
445 // Setup and expectations. 764 var testNotificationData = {notificationsData: {}};
446 var testNotificationId = 'TEST_ID'; 765
447 var testNotificationDataRequest = {notificationsData: {}}; 766 mockOnNotificationClickedDependencies(this);
448 var testNotificationData = {notificationsData: {}}; 767 this.makeMockLocalFunctions(['selector']);
449 768
450 mockOnNotificationClickedDependencies(this); 769 expectChromeLocalStorageGet(
451 this.makeMockLocalFunctions(['selector']); 770 this, testNotificationDataRequest, testNotificationData);
452 771
453 expectChromeLocalStorageGet( 772 // Invoking the tested function.
454 this, testNotificationDataRequest, testNotificationData); 773 onNotificationClicked(
455 774 testNotificationId, this.mockLocalFunctions.functions().selector);
456 // Invoking the tested function. 775 });
457 onNotificationClicked( 776
458 testNotificationId, this.mockLocalFunctions.functions().selector); 777 TEST_F(TEST_NAME, 'OnNotificationClicked_ActionUrlsUndefined', function() {
459 }); 778 // Tests the case when the data associated with notification id is
460 779 // 'undefined'.
461 TEST_F( 780 // In this case, the function should do nothing.
462 'GoogleNowBackgroundUnitTest', 781
463 'OnNotificationClicked_ActionUrlsUndefined', 782 // Setup and expectations.
464 function() { 783 var testActionUrls = undefined;
465 // Tests the case when the data associated with notification id is 784 var testNotificationId = 'TEST_ID';
466 // 'undefined'. 785 var testNotificationDataRequest = {notificationsData: {}};
467 // In this case, the function should do nothing. 786 var testNotificationData = {
468 787 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
469 // Setup and expectations. 788 };
470 var testActionUrls = undefined; 789
471 var testNotificationId = 'TEST_ID'; 790 mockOnNotificationClickedDependencies(this);
472 var testNotificationDataRequest = {notificationsData: {}}; 791 this.makeMockLocalFunctions(['selector']);
473 var testNotificationData = { 792
474 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 793 expectChromeLocalStorageGet(
475 }; 794 this, testNotificationDataRequest, testNotificationData);
476 795
477 mockOnNotificationClickedDependencies(this); 796 this.mockLocalFunctions.expects(once())
478 this.makeMockLocalFunctions(['selector']); 797 .selector(eqJSON(
479 798 testNotificationData.notificationsData[testNotificationId]))
480 expectChromeLocalStorageGet( 799 .will(returnValue(undefined));
481 this, testNotificationDataRequest, testNotificationData); 800
482 801 // Invoking the tested function.
483 this.mockLocalFunctions.expects(once()) 802 onNotificationClicked(
484 .selector(eqJSON( 803 testNotificationId, this.mockLocalFunctions.functions().selector);
485 testNotificationData.notificationsData[testNotificationId])) 804 });
486 .will(returnValue(undefined)); 805
487 806 TEST_F(TEST_NAME, 'OnNotificationClicked_TabCreateSuccess', function() {
488 // Invoking the tested function. 807 // Tests the selected URL is OK and crome.tabs.create suceeds.
489 onNotificationClicked( 808
490 testNotificationId, this.mockLocalFunctions.functions().selector); 809 // Setup and expectations.
491 }); 810 var testActionUrls = {testField: 'TEST VALUE'};
492 811 var testNotificationId = 'TEST_ID';
493 TEST_F( 812 var testNotificationDataRequest = {notificationsData: {}};
494 'GoogleNowBackgroundUnitTest', 813 var testNotificationData = {
495 'OnNotificationClicked_TabCreateSuccess', 814 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
496 function() { 815 };
497 // Tests the selected URL is OK and crome.tabs.create suceeds. 816 var testActionUrl = 'http://testurl.com';
498 817 var testCreatedTab = {windowId: 239};
499 // Setup and expectations. 818
500 var testActionUrls = {testField: 'TEST VALUE'}; 819 mockOnNotificationClickedDependencies(this);
501 var testNotificationId = 'TEST_ID'; 820 this.makeMockLocalFunctions(['selector']);
502 var testNotificationDataRequest = {notificationsData: {}}; 821
503 var testNotificationData = { 822 expectChromeLocalStorageGet(
504 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 823 this, testNotificationDataRequest, testNotificationData);
505 }; 824 this.mockLocalFunctions.expects(once())
506 var testActionUrl = 'http://testurl.com'; 825 .selector(eqJSON(
507 var testCreatedTab = {windowId: 239}; 826 testNotificationData.notificationsData[testNotificationId]))
508 827 .will(returnValue(testActionUrl));
509 mockOnNotificationClickedDependencies(this); 828 var chromeTabsCreateSavedArgs = new SaveMockArguments();
510 this.makeMockLocalFunctions(['selector']); 829 this.mockApis.expects(once()).
511 830 instrumented_tabs_create(
512 expectChromeLocalStorageGet( 831 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})),
513 this, testNotificationDataRequest, testNotificationData); 832 chromeTabsCreateSavedArgs.match(ANYTHING)).
514 this.mockLocalFunctions.expects(once()) 833 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab));
515 .selector(eqJSON( 834 this.mockApis.expects(once()).chrome_windows_update(
516 testNotificationData.notificationsData[testNotificationId])) 835 testCreatedTab.windowId,
517 .will(returnValue(testActionUrl)); 836 eqJSON({focused: true}));
518 var chromeTabsCreateSavedArgs = new SaveMockArguments(); 837
519 this.mockApis.expects(once()). 838 // Invoking the tested function.
520 instrumented_tabs_create( 839 onNotificationClicked(
521 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})), 840 testNotificationId, this.mockLocalFunctions.functions().selector);
522 chromeTabsCreateSavedArgs.match(ANYTHING)). 841 });
523 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab)); 842
524 this.mockApis.expects(once()).chrome_windows_update( 843 TEST_F(TEST_NAME, 'OnNotificationClicked_TabCreateFail', function() {
525 testCreatedTab.windowId, 844 // Tests the selected URL is OK and crome.tabs.create fails.
526 eqJSON({focused: true})); 845 // In this case, the function should invoke chrome.windows.create as a
527 846 // second attempt.
528 // Invoking the tested function. 847
529 onNotificationClicked( 848 // Setup and expectations.
530 testNotificationId, this.mockLocalFunctions.functions().selector); 849 var testActionUrls = {testField: 'TEST VALUE'};
531 }); 850 var testNotificationId = 'TEST_ID';
532 851 var testNotificationDataRequest = {notificationsData: {}};
533 TEST_F( 852 var testNotificationData = {
534 'GoogleNowBackgroundUnitTest', 853 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
535 'OnNotificationClicked_TabCreateFail', 854 };
536 function() { 855 var testActionUrl = 'http://testurl.com';
537 // Tests the selected URL is OK and crome.tabs.create fails. 856 var testCreatedTab = undefined; // chrome.tabs.create fails
538 // In this case, the function should invoke chrome.windows.create as a 857
539 // second attempt. 858 mockOnNotificationClickedDependencies(this);
540 859 this.makeMockLocalFunctions(['selector']);
541 // Setup and expectations. 860
542 var testActionUrls = {testField: 'TEST VALUE'}; 861 expectChromeLocalStorageGet(
543 var testNotificationId = 'TEST_ID'; 862 this, testNotificationDataRequest, testNotificationData);
544 var testNotificationDataRequest = {notificationsData: {}}; 863 this.mockLocalFunctions.expects(once())
545 var testNotificationData = { 864 .selector(eqJSON(
546 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 865 testNotificationData.notificationsData[testNotificationId]))
547 }; 866 .will(returnValue(testActionUrl));
548 var testActionUrl = 'http://testurl.com'; 867 var chromeTabsCreateSavedArgs = new SaveMockArguments();
549 var testCreatedTab = undefined; // chrome.tabs.create fails 868 this.mockApis.expects(once()).
550 869 instrumented_tabs_create(
551 mockOnNotificationClickedDependencies(this); 870 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})),
552 this.makeMockLocalFunctions(['selector']); 871 chromeTabsCreateSavedArgs.match(ANYTHING)).
553 872 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab));
554 expectChromeLocalStorageGet( 873 this.mockApis.expects(once()).chrome_windows_create(
555 this, testNotificationDataRequest, testNotificationData); 874 eqJSON({url: testActionUrl, focused: true}));
556 this.mockLocalFunctions.expects(once()) 875
557 .selector(eqJSON( 876 // Invoking the tested function.
558 testNotificationData.notificationsData[testNotificationId])) 877 onNotificationClicked(
559 .will(returnValue(testActionUrl)); 878 testNotificationId, this.mockLocalFunctions.functions().selector);
560 var chromeTabsCreateSavedArgs = new SaveMockArguments(); 879 });
561 this.mockApis.expects(once()). 880
562 instrumented_tabs_create( 881 TEST_F(TEST_NAME, 'ShowNotificationGroups', function() {
563 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})), 882 // Tests showNotificationGroups function. Checks that the function properly
564 chromeTabsCreateSavedArgs.match(ANYTHING)). 883 // deletes the card that didn't get an update, updates existing card and
565 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab)); 884 // creates a new card that previously didn't exist.
566 this.mockApis.expects(once()).chrome_windows_create( 885
567 eqJSON({url: testActionUrl, focused: true})); 886 // Setup and expectations.
568 887 var existingNotifications = {
569 // Invoking the tested function. 888 'SHOULD BE DELETED': 'SOMETHING',
570 onNotificationClicked( 889 'SHOULD BE KEPT': 'SOMETHING'
571 testNotificationId, this.mockLocalFunctions.functions().selector); 890 };
572 }); 891
573 892 var keptCard = {
574 TEST_F( 893 chromeNotificationId: 'SHOULD BE KEPT',
575 'GoogleNowBackgroundUnitTest', 894 trigger: {showTimeSec: 0, hideTimeSec: 0}
576 'ShowNotificationCards', 895 };
577 function() { 896
578 // Tests showNotificationCards function. Checks that the function properly 897 var keptNotification = {
579 // deletes the card that didn't get an update, updates existing card and 898 receivedNotification: keptCard,
580 // creates a new card that previously didn't exist. 899 showTime: 0,
581 900 hideTime: 0
582 // Setup and expectations. 901 };
583 var existingNotifications = { 902
584 'SHOULD BE DELETED': 'SOMETHING', 903 var newCard = {
585 'SHOULD BE KEPT': 'SOMETHING' 904 chromeNotificationId: 'NEW CARD',
586 }; 905 trigger: {showTimeSec: 0, hideTimeSec: 0}
587 906 };
588 var notificationGroups = { 907
589 TEST_FIELD: 'TEST VALUE' 908 var newNotification = {
590 }; 909 receivedNotification: newCard,
591 910 showTime: 0,
592 var cards = { 911 hideTime: 0
593 'SHOULD BE KEPT': [1], 912 };
594 'NEW CARD': [2] 913
595 }; 914 var notificationGroups = {
596 915 'TEST GROUP 1': {cards: [keptCard], cardsTimestamp: 0},
597 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION'; 916 'TEST GROUP 2': {cards: [newCard], cardsTimestamp: 0}
598 917 };
599 var expectedUpdatedNotifications = { 918
600 'SHOULD BE KEPT': 'KEPT CARD NOTIFICATION DATA', 919 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION';
601 'NEW CARD': 'NEW CARD NOTIFICATION DATA' 920
602 }; 921 var expectedUpdatedNotifications = {
603 922 'SHOULD BE KEPT': 'KEPT CARD NOTIFICATION DATA',
604 this.makeAndRegisterMockApis([ 923 'NEW CARD': 'NEW CARD NOTIFICATION DATA'
605 'cardSet.update', 924 };
606 'chrome.storage.local.set', 925
607 'instrumented.notifications.getAll' 926 this.makeAndRegisterMockApis([
608 ]); 927 'cardSet.update',
609 this.makeMockLocalFunctions([ 928 'chrome.storage.local.set',
610 'onSuccess' 929 'instrumented.notifications.getAll'
611 ]); 930 ]);
612 931 this.makeMockLocalFunctions([
613 var notificationsGetAllSavedArgs = new SaveMockArguments(); 932 'onSuccess'
614 this.mockApis.expects(once()). 933 ]);
615 instrumented_notifications_getAll( 934
616 notificationsGetAllSavedArgs.match(ANYTHING)). 935 var notificationsGetAllSavedArgs = new SaveMockArguments();
617 will(invokeCallback( 936 this.mockApis.expects(once()).
618 notificationsGetAllSavedArgs, 0, existingNotifications)); 937 instrumented_notifications_getAll(
619 938 notificationsGetAllSavedArgs.match(ANYTHING)).
620 this.mockApis.expects(once()). 939 will(invokeCallback(
621 cardSet_update( 940 notificationsGetAllSavedArgs, 0, existingNotifications));
622 'SHOULD BE KEPT', 941
623 [1], 942 this.mockApis.expects(once()).
624 eqJSON(notificationGroups), 943 cardSet_update(
625 fakeOnCardShownFunction). 944 'SHOULD BE KEPT',
626 will(returnValue('KEPT CARD NOTIFICATION DATA')); 945 eqJSON([keptNotification]),
627 this.mockApis.expects(once()). 946 eqJSON(notificationGroups),
628 cardSet_update( 947 fakeOnCardShownFunction).
629 'NEW CARD', 948 will(returnValue('KEPT CARD NOTIFICATION DATA'));
630 [2], 949 this.mockApis.expects(once()).
631 eqJSON(notificationGroups), 950 cardSet_update(
632 fakeOnCardShownFunction). 951 'NEW CARD',
633 will(returnValue('NEW CARD NOTIFICATION DATA')); 952 eqJSON([newNotification]),
634 this.mockApis.expects(once()). 953 eqJSON(notificationGroups),
635 cardSet_update( 954 fakeOnCardShownFunction).
636 'SHOULD BE DELETED', 955 will(returnValue('NEW CARD NOTIFICATION DATA'));
637 [], 956 this.mockApis.expects(once()).
638 eqJSON(notificationGroups), 957 cardSet_update(
639 fakeOnCardShownFunction). 958 'SHOULD BE DELETED',
640 will(returnValue(undefined)); 959 [],
641 960 eqJSON(notificationGroups),
642 this.mockApis.expects(once()). 961 fakeOnCardShownFunction).
643 chrome_storage_local_set( 962 will(returnValue(undefined));
644 eqJSON({notificationsData: expectedUpdatedNotifications})); 963
645 964 this.mockApis.expects(once()).
646 this.mockLocalFunctions.expects(once()). 965 chrome_storage_local_set(
647 onSuccess(); 966 eqJSON({notificationsData: expectedUpdatedNotifications}));
648 967
649 // Invoking the tested function. 968 this.mockLocalFunctions.expects(once()).
650 showNotificationCards( 969 onSuccess(undefined);
651 notificationGroups, 970
652 cards, 971 // Invoking the tested function.
653 this.mockLocalFunctions.functions().onSuccess, 972 showNotificationGroups(notificationGroups, fakeOnCardShownFunction)
654 fakeOnCardShownFunction); 973 .then(this.mockLocalFunctions.functions().onSuccess);
655 }); 974 });
656 975
657 TEST_F( 976 TEST_F(TEST_NAME, 'ProcessServerResponse', function() {
658 'GoogleNowBackgroundUnitTest', 977 // Tests processServerResponse function.
659 'CombineGroup', 978
660 function() { 979 // Setup and expectations.
661 // Tests combineGroup function. Verifies that both notifications with and 980 Date.now = function() { return 3000000; };
662 // without show time are handled correctly and that cards are correctly 981
663 // added to existing cards with same ID or start a new combined card. 982 // GROUP1 was requested and contains cards c4 and c5. For c5, there is a
664 983 // non-expired dismissal, so it will be ignored.
665 // Setup and expectations. 984 // GROUP2 was not requested, but is contained in server response to
666 var combinedCards = { 985 // indicate that the group still exists. Stored group GROUP2 won't change.
667 'EXISTING CARD': [1] 986 // GROUP3 is stored, but is not present in server's response, which means
668 }; 987 // it doesn't exist anymore. This group will be deleted.
669 988 // GROUP4 doesn't contain cards, but it was requested. This is treated as
670 var receivedNotificationNoShowTime = { 989 // if it had an empty array of cards. Cards in the stored group will be
671 chromeNotificationId: 'EXISTING CARD', 990 // replaced with an empty array.
672 trigger: {hideTimeSec: 1} 991 // GROUP5 doesn't have next poll time, and it will be stored without next
673 }; 992 // poll time.
674 var receivedNotificationWithShowTime = { 993 var serverResponse = {
675 chromeNotificationId: 'NEW CARD', 994 groups: {
676 trigger: {showTimeSec: 2, hideTimeSec: 3} 995 GROUP1: {requested: true, nextPollSeconds: 46},
677 } 996 GROUP2: {requested: false},
678 997 GROUP4: {requested: true, nextPollSeconds: 45},
679 var storedGroup = { 998 GROUP5: {requested: true}
680 cardsTimestamp: 10000, 999 },
681 cards: [ 1000 notifications: [
682 receivedNotificationNoShowTime, 1001 {notificationId: 'c4', groupName: 'GROUP1'},
683 receivedNotificationWithShowTime 1002 {notificationId: 'c5', groupName: 'GROUP1'}
684 ] 1003 ]
685 }; 1004 };
686 1005
687 // Invoking the tested function. 1006 var recentDismissals = {
688 combineGroup(combinedCards, storedGroup); 1007 c4: 1800000, // expired dismissal
689 1008 c5: 1800001 // non-expired dismissal
690 // Check the output value. 1009 };
691 var expectedCombinedCards = { 1010
692 'EXISTING CARD': [ 1011 var storedGroups = {
693 1, 1012 GROUP2: {
694 { 1013 cards: [{notificationId: 'c2'}],
695 receivedNotification: receivedNotificationNoShowTime, 1014 cardsTimestamp: 239,
696 hideTime: 11000 1015 nextPollTime: 10000
697 } 1016 },
698 ], 1017 GROUP3: {
699 'NEW CARD': [ 1018 cards: [{notificationId: 'c3'}],
700 { 1019 cardsTimestamp: 240,
701 receivedNotification: receivedNotificationWithShowTime, 1020 nextPollTime: 10001
702 showTime: 12000, 1021 },
703 hideTime: 13000 1022 GROUP4: {
704 } 1023 cards: [{notificationId: 'c6'}],
705 ] 1024 cardsTimestamp: 241,
706 }; 1025 nextPollTime: 10002
707 1026 }
708 assertEquals( 1027 };
709 JSON.stringify(expectedCombinedCards), 1028
710 JSON.stringify(combinedCards)); 1029 var expectedUpdatedGroups = {
711 }); 1030 GROUP1: {
712 1031 cards: [{notificationId: 'c4', groupName: 'GROUP1'}],
713 TEST_F( 1032 cardsTimestamp: 3000000,
714 'GoogleNowBackgroundUnitTest', 1033 nextPollTime: 3046000
715 'CombineAndShowNotificationCards', 1034 },
716 function() { 1035 GROUP2: {
717 // Tests combineAndShowNotificationCards function. 1036 cards: [{notificationId: 'c2'}],
718 // The test passes 2 groups to combineAndShowNotificationCards, checks 1037 cardsTimestamp: 239,
719 // that it calls combineGroup() for each of these groups and calls 1038 nextPollTime: 10000
720 // showNotificationCards() with the results of these combineGroup() calls. 1039 },
721 1040 GROUP4: {
722 // Setup and expectations. 1041 cards: [],
723 var testGroups = { 1042 cardsTimestamp: 3000000,
724 'TEST GROUP 1': {testField: 'TEST VALUE 1'}, 1043 nextPollTime: 3045000
725 'TEST GROUP 2': {testField: 'TEST VALUE 2'} 1044 },
726 }; 1045 GROUP5: {
727 1046 cards: [],
728 var fakeOnSuccessFunction = 'FAKE ON SUCCESS FUNCTION'; 1047 cardsTimestamp: 3000000
729 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION'; 1048 }
730 1049 };
731 this.makeAndRegisterMockGlobals( 1050
732 ['combineGroup', 'showNotificationCards']); 1051 var expectedUpdatedRecentDismissals = {
733 1052 c5: 1800001
734 var combineGroupSavedArgs = new SaveMockArguments(); 1053 };
735 this.mockGlobals.expects(once()). 1054
736 combineGroup( 1055 this.makeAndRegisterMockGlobals([
737 combineGroupSavedArgs.match(eqJSON({})), 1056 'scheduleNextPoll'
738 combineGroupSavedArgs.match(eqJSON({testField: 'TEST VALUE 1'}))). 1057 ]);
739 will(callFunction(function() { 1058
740 combineGroupSavedArgs.arguments[0].card1 = { 1059 this.makeAndRegisterMockApis([
741 testValue: 'TEST CARD VALUE 1' 1060 'fillFromChromeLocalStorage',
742 }; 1061 ]);
743 })); 1062
744 this.mockGlobals.expects(once()). 1063 expectChromeLocalStorageGet(
745 combineGroup( 1064 this,
746 combineGroupSavedArgs.match( 1065 {
747 eqJSON({card1: {testValue: 'TEST CARD VALUE 1'}})), 1066 notificationGroups: {},
748 combineGroupSavedArgs.match( 1067 recentDismissals: {}
749 eqJSON({testField: 'TEST VALUE 2'}))). 1068 },
750 will(callFunction(function() { 1069 {
751 combineGroupSavedArgs.arguments[0].card2 = { 1070 notificationGroups: storedGroups,
752 testValue: 'TEST CARD VALUE 2' 1071 recentDismissals: recentDismissals
753 }; 1072 });
754 })); 1073
755 this.mockGlobals.expects(once()). 1074 this.mockGlobals.expects(once()).
756 showNotificationCards( 1075 scheduleNextPoll(eqJSON(expectedUpdatedGroups), true);
757 eqJSON(testGroups), 1076
758 eqJSON({ 1077 // Invoking the tested function.
759 card1: {testValue: 'TEST CARD VALUE 1'}, 1078 processServerResponse(serverResponse);
760 card2: {testValue: 'TEST CARD VALUE 2'} 1079 });
761 }), 1080
762 fakeOnSuccessFunction, 1081 TEST_F(TEST_NAME, 'ProcessServerResponseGoogleNowDisabled', function() {
763 fakeOnCardShownFunction); 1082 // Tests processServerResponse function for the case when the response
764 1083 // indicates that Google Now is disabled.
765 // Invoking the tested function. 1084
766 combineAndShowNotificationCards( 1085 // Setup and expectations.
767 testGroups, fakeOnSuccessFunction, fakeOnCardShownFunction); 1086 var serverResponse = {
768 }); 1087 googleNowDisabled: true,
769 1088 groups: {}
770 TEST_F( 1089 };
771 'GoogleNowBackgroundUnitTest', 1090
772 'ProcessServerResponse', 1091 this.makeAndRegisterMockGlobals([
773 function() { 1092 'onStateChange',
774 // Tests processServerResponse function. 1093 'scheduleNextPoll',
775 1094 ]);
776 // Setup and expectations. 1095
777 Date.now = function() { return 3000000; }; 1096 this.makeAndRegisterMockApis([
778 1097 'chrome.storage.local.set',
779 // GROUP1 was requested and contains cards c4 and c5. For c5, there is a 1098 'fillFromChromeLocalStorage'
780 // non-expired dismissal, so it will be ignored. 1099 ]);
781 // GROUP2 was not requested, but is contained in server response to 1100
782 // indicate that the group still exists. Stored group GROUP2 won't change. 1101 this.mockApis.expects(once()).
783 // GROUP3 is stored, but is not present in server's response, which means 1102 chrome_storage_local_set(eqJSON({googleNowEnabled: false}));
784 // it doesn't exist anymore. This group will be deleted. 1103
785 // GROUP4 doesn't contain cards, but it was requested. This is treated as 1104 this.mockGlobals.expects(once()).onStateChange();
786 // if it had an empty array of cards. Cards in the stored group will be 1105
787 // replaced with an empty array. 1106 expectChromeLocalStorageGet(
788 // GROUP5 doesn't have next poll time, and it will be stored without next 1107 this,
789 // poll time. 1108 {
790 var serverResponse = { 1109 notificationGroups: {},
791 groups: { 1110 recentDismissals: {}
792 GROUP1: {requested: true, nextPollSeconds: 46}, 1111 },
793 GROUP2: {requested: false}, 1112 {
794 GROUP4: {requested: true, nextPollSeconds: 45}, 1113 notificationGroups: {},
795 GROUP5: {requested: true} 1114 recentDismissals: {}
796 }, 1115 });
797 notifications: [ 1116
798 {notificationId: 'c4', groupName: 'GROUP1'}, 1117 this.mockGlobals.expects(once()).scheduleNextPoll(eqJSON({}), false);
799 {notificationId: 'c5', groupName: 'GROUP1'} 1118
800 ] 1119 // Invoking the tested function.
801 }; 1120 processServerResponse(serverResponse);
802 1121 });
803 var recentDismissals = { 1122
804 c4: 1800000, // expired dismissal
805 c5: 1800001 // non-expired dismissal
806 };
807
808 var storedGroups = {
809 GROUP2: {
810 cards: [{notificationId: 'c2'}],
811 cardsTimestamp: 239,
812 nextPollTime: 10000
813 },
814 GROUP3: {
815 cards: [{notificationId: 'c3'}],
816 cardsTimestamp: 240,
817 nextPollTime: 10001
818 },
819 GROUP4: {
820 cards: [{notificationId: 'c6'}],
821 cardsTimestamp: 241,
822 nextPollTime: 10002
823 }
824 };
825
826 var expectedUpdatedGroups = {
827 GROUP1: {
828 cards: [{notificationId: 'c4', groupName: 'GROUP1'}],
829 cardsTimestamp: 3000000,
830 nextPollTime: 3046000
831 },
832 GROUP2: {
833 cards: [{notificationId: 'c2'}],
834 cardsTimestamp: 239,
835 nextPollTime: 10000
836 },
837 GROUP4: {
838 cards: [],
839 cardsTimestamp: 3000000,
840 nextPollTime: 3045000
841 },
842 GROUP5: {
843 cards: [],
844 cardsTimestamp: 3000000
845 }
846 };
847
848 var expectedUpdatedRecentDismissals = {
849 c5: 1800001
850 };
851
852 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION';
853
854 this.makeAndRegisterMockGlobals([
855 'combineAndShowNotificationCards',
856 'recordEvent',
857 'scheduleNextPoll'
858 ]);
859
860 this.makeAndRegisterMockApis([
861 'chrome.storage.local.set',
862 'fillFromChromeLocalStorage'
863 ]);
864
865 expectChromeLocalStorageGet(
866 this,
867 {
868 notificationGroups: {},
869 recentDismissals: {}
870 },
871 {
872 notificationGroups: storedGroups,
873 recentDismissals: recentDismissals
874 });
875
876 this.mockGlobals.expects(once()).
877 scheduleNextPoll(eqJSON(expectedUpdatedGroups), true);
878
879 var combineAndShowNotificationCardsSavedArgs = new SaveMockArguments();
880 this.mockGlobals.expects(once()).
881 combineAndShowNotificationCards(
882 combineAndShowNotificationCardsSavedArgs.match(
883 eqJSON(expectedUpdatedGroups)),
884 combineAndShowNotificationCardsSavedArgs.match(
885 ANYTHING),
886 combineAndShowNotificationCardsSavedArgs.match(
887 eq(fakeOnCardShownFunction))).
888 will(invokeCallback(combineAndShowNotificationCardsSavedArgs, 1));
889
890 this.mockApis.expects(once()).
891 chrome_storage_local_set(
892 eqJSON({
893 notificationGroups: expectedUpdatedGroups,
894 recentDismissals: expectedUpdatedRecentDismissals}));
895
896 this.mockGlobals.expects(once()).
897 recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS);
898
899 // Invoking the tested function.
900 processServerResponse(serverResponse, fakeOnCardShownFunction);
901 });
902
903 TEST_F(
904 'GoogleNowBackgroundUnitTest',
905 'ProcessServerResponseGoogleNowDisabled',
906 function() {
907 // Tests processServerResponse function for the case when the response
908 // indicates that Google Now is disabled.
909
910 // Setup and expectations.
911 var serverResponse = {
912 googleNowDisabled: true,
913 groups: {
914 GROUP1: {nextPollTimeSeconds: 200}
915 }
916 };
917
918 var storedGroups = {
919 GROUP2: {
920 cards: [{notificationId: 'c2'}],
921 cardsTimestamp: 239,
922 nextPollTime: 10000
923 },
924 GROUP3: {
925 cards: [{notificationId: 'c3'}],
926 cardsTimestamp: 240,
927 nextPollTime: 10001
928 }
929 };
930
931 var expectedUpdatedGroups = {
932 };
933
934 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION';
935
936 this.makeAndRegisterMockGlobals([
937 'combineAndShowNotificationCards',
938 'onStateChange',
939 'recordEvent',
940 'scheduleNextPoll'
941 ]);
942
943 this.makeAndRegisterMockApis([
944 'chrome.storage.local.set',
945 'fillFromChromeLocalStorage'
946 ]);
947
948 this.mockApis.expects(once()).
949 chrome_storage_local_set(
950 eqJSON({googleNowEnabled: false}));
951
952 this.mockGlobals.expects(once()).onStateChange();
953
954 expectChromeLocalStorageGet(
955 this,
956 {
957 notificationGroups: {},
958 recentDismissals: {}
959 },
960 {
961 notificationGroups: storedGroups,
962 recentDismissals: {}
963 });
964
965 this.mockGlobals.expects(once()).
966 scheduleNextPoll(eqJSON(expectedUpdatedGroups), false);
967
968 var combineAndShowNotificationCardsSavedArgs = new SaveMockArguments();
969 this.mockGlobals.expects(once()).
970 combineAndShowNotificationCards(
971 combineAndShowNotificationCardsSavedArgs.match(
972 eqJSON(expectedUpdatedGroups)),
973 combineAndShowNotificationCardsSavedArgs.match(
974 ANYTHING),
975 combineAndShowNotificationCardsSavedArgs.match(
976 eq(fakeOnCardShownFunction))).
977 will(invokeCallback(combineAndShowNotificationCardsSavedArgs, 1));
978
979 this.mockApis.expects(once()).
980 chrome_storage_local_set(
981 eqJSON({
982 notificationGroups: expectedUpdatedGroups,
983 recentDismissals: {}}));
984
985 this.mockGlobals.expects(once()).
986 recordEvent(GoogleNowEvent.CARDS_PARSE_SUCCESS);
987
988 // Invoking the tested function.
989 processServerResponse(serverResponse, fakeOnCardShownFunction);
990 });
OLDNEW
« no previous file with comments | « chrome/browser/resources/google_now/background_test_util.js ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698