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

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 to r260580 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
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
(...skipping 100 matching lines...) Expand 10 before | Expand all | Expand 10 after
422 GoogleNowEvent.GOOGLE_NOW_DISABLED); 744 GoogleNowEvent.GOOGLE_NOW_DISABLED);
423 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled); 745 updateRunningState(signedIn, true, notificationEnabled, googleNowEnabled);
424 }); 746 });
425 747
426 /** 748 /**
427 * Mocks global functions and APIs that onNotificationClicked() depends upon. 749 * Mocks global functions and APIs that onNotificationClicked() depends upon.
428 * @param {Test} fixture Test fixture. 750 * @param {Test} fixture Test fixture.
429 */ 751 */
430 function mockOnNotificationClickedDependencies(fixture) { 752 function mockOnNotificationClickedDependencies(fixture) {
431 fixture.makeAndRegisterMockApis([ 753 fixture.makeAndRegisterMockApis([
432 'chrome.windows.create', 754 'chrome.windows.create',
433 'chrome.windows.update', 755 'chrome.windows.update',
434 'fillFromChromeLocalStorage', 756 'fillFromChromeLocalStorage',
435 'instrumented.tabs.create']); 757 'instrumented.tabs.create']);
436 } 758 }
437 759
438 TEST_F( 760 TEST_F(TEST_NAME, 'OnNotificationClicked_NoData', function() {
439 'GoogleNowBackgroundUnitTest', 761 // Tests the case when there is no data associated with notification id.
440 'OnNotificationClicked_NoData', 762 // In this case, the function should do nothing.
441 function() { 763
442 // Tests the case when there is no data associated with notification id. 764 // Setup and expectations.
443 // In this case, the function should do nothing. 765 var testNotificationId = 'TEST_ID';
444 766 var testNotificationDataRequest = {notificationsData: {}};
445 // Setup and expectations. 767 var testNotificationData = {notificationsData: {}};
446 var testNotificationId = 'TEST_ID'; 768
447 var testNotificationDataRequest = {notificationsData: {}}; 769 mockOnNotificationClickedDependencies(this);
448 var testNotificationData = {notificationsData: {}}; 770 this.makeMockLocalFunctions(['selector']);
449 771
450 mockOnNotificationClickedDependencies(this); 772 expectChromeLocalStorageGet(
451 this.makeMockLocalFunctions(['selector']); 773 this, testNotificationDataRequest, testNotificationData);
452 774
453 expectChromeLocalStorageGet( 775 // Invoking the tested function.
454 this, testNotificationDataRequest, testNotificationData); 776 onNotificationClicked(
455 777 testNotificationId, this.mockLocalFunctions.functions().selector);
456 // Invoking the tested function. 778 });
457 onNotificationClicked( 779
458 testNotificationId, this.mockLocalFunctions.functions().selector); 780 TEST_F(TEST_NAME, 'OnNotificationClicked_ActionUrlsUndefined', function() {
459 }); 781 // Tests the case when the data associated with notification id is
460 782 // 'undefined'.
461 TEST_F( 783 // In this case, the function should do nothing.
462 'GoogleNowBackgroundUnitTest', 784
463 'OnNotificationClicked_ActionUrlsUndefined', 785 // Setup and expectations.
464 function() { 786 var testActionUrls = undefined;
465 // Tests the case when the data associated with notification id is 787 var testNotificationId = 'TEST_ID';
466 // 'undefined'. 788 var testNotificationDataRequest = {notificationsData: {}};
467 // In this case, the function should do nothing. 789 var testNotificationData = {
468 790 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
469 // Setup and expectations. 791 };
470 var testActionUrls = undefined; 792
471 var testNotificationId = 'TEST_ID'; 793 mockOnNotificationClickedDependencies(this);
472 var testNotificationDataRequest = {notificationsData: {}}; 794 this.makeMockLocalFunctions(['selector']);
473 var testNotificationData = { 795
474 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 796 expectChromeLocalStorageGet(
475 }; 797 this, testNotificationDataRequest, testNotificationData);
476 798
477 mockOnNotificationClickedDependencies(this); 799 this.mockLocalFunctions.expects(once())
478 this.makeMockLocalFunctions(['selector']); 800 .selector(eqJSON(
479 801 testNotificationData.notificationsData[testNotificationId]))
480 expectChromeLocalStorageGet( 802 .will(returnValue(undefined));
481 this, testNotificationDataRequest, testNotificationData); 803
482 804 // Invoking the tested function.
483 this.mockLocalFunctions.expects(once()) 805 onNotificationClicked(
484 .selector(eqJSON( 806 testNotificationId, this.mockLocalFunctions.functions().selector);
485 testNotificationData.notificationsData[testNotificationId])) 807 });
486 .will(returnValue(undefined)); 808
487 809 TEST_F(TEST_NAME, 'OnNotificationClicked_TabCreateSuccess', function() {
488 // Invoking the tested function. 810 // Tests the selected URL is OK and crome.tabs.create suceeds.
489 onNotificationClicked( 811
490 testNotificationId, this.mockLocalFunctions.functions().selector); 812 // Setup and expectations.
491 }); 813 var testActionUrls = {testField: 'TEST VALUE'};
492 814 var testNotificationId = 'TEST_ID';
493 TEST_F( 815 var testNotificationDataRequest = {notificationsData: {}};
494 'GoogleNowBackgroundUnitTest', 816 var testNotificationData = {
495 'OnNotificationClicked_TabCreateSuccess', 817 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
496 function() { 818 };
497 // Tests the selected URL is OK and crome.tabs.create suceeds. 819 var testActionUrl = 'http://testurl.com';
498 820 var testCreatedTab = {windowId: 239};
499 // Setup and expectations. 821
500 var testActionUrls = {testField: 'TEST VALUE'}; 822 mockOnNotificationClickedDependencies(this);
501 var testNotificationId = 'TEST_ID'; 823 this.makeMockLocalFunctions(['selector']);
502 var testNotificationDataRequest = {notificationsData: {}}; 824
503 var testNotificationData = { 825 expectChromeLocalStorageGet(
504 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 826 this, testNotificationDataRequest, testNotificationData);
505 }; 827 this.mockLocalFunctions.expects(once())
506 var testActionUrl = 'http://testurl.com'; 828 .selector(eqJSON(
507 var testCreatedTab = {windowId: 239}; 829 testNotificationData.notificationsData[testNotificationId]))
508 830 .will(returnValue(testActionUrl));
509 mockOnNotificationClickedDependencies(this); 831 var chromeTabsCreateSavedArgs = new SaveMockArguments();
510 this.makeMockLocalFunctions(['selector']); 832 this.mockApis.expects(once()).
511 833 instrumented_tabs_create(
512 expectChromeLocalStorageGet( 834 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})),
513 this, testNotificationDataRequest, testNotificationData); 835 chromeTabsCreateSavedArgs.match(ANYTHING)).
514 this.mockLocalFunctions.expects(once()) 836 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab));
515 .selector(eqJSON( 837 this.mockApis.expects(once()).chrome_windows_update(
516 testNotificationData.notificationsData[testNotificationId])) 838 testCreatedTab.windowId,
517 .will(returnValue(testActionUrl)); 839 eqJSON({focused: true}));
518 var chromeTabsCreateSavedArgs = new SaveMockArguments(); 840
519 this.mockApis.expects(once()). 841 // Invoking the tested function.
520 instrumented_tabs_create( 842 onNotificationClicked(
521 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})), 843 testNotificationId, this.mockLocalFunctions.functions().selector);
522 chromeTabsCreateSavedArgs.match(ANYTHING)). 844 });
523 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab)); 845
524 this.mockApis.expects(once()).chrome_windows_update( 846 TEST_F(TEST_NAME, 'OnNotificationClicked_TabCreateFail', function() {
525 testCreatedTab.windowId, 847 // Tests the selected URL is OK and crome.tabs.create fails.
526 eqJSON({focused: true})); 848 // In this case, the function should invoke chrome.windows.create as a
527 849 // second attempt.
528 // Invoking the tested function. 850
529 onNotificationClicked( 851 // Setup and expectations.
530 testNotificationId, this.mockLocalFunctions.functions().selector); 852 var testActionUrls = {testField: 'TEST VALUE'};
531 }); 853 var testNotificationId = 'TEST_ID';
532 854 var testNotificationDataRequest = {notificationsData: {}};
533 TEST_F( 855 var testNotificationData = {
534 'GoogleNowBackgroundUnitTest', 856 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}}
535 'OnNotificationClicked_TabCreateFail', 857 };
536 function() { 858 var testActionUrl = 'http://testurl.com';
537 // Tests the selected URL is OK and crome.tabs.create fails. 859 var testCreatedTab = undefined; // chrome.tabs.create fails
538 // In this case, the function should invoke chrome.windows.create as a 860
539 // second attempt. 861 mockOnNotificationClickedDependencies(this);
540 862 this.makeMockLocalFunctions(['selector']);
541 // Setup and expectations. 863
542 var testActionUrls = {testField: 'TEST VALUE'}; 864 expectChromeLocalStorageGet(
543 var testNotificationId = 'TEST_ID'; 865 this, testNotificationDataRequest, testNotificationData);
544 var testNotificationDataRequest = {notificationsData: {}}; 866 this.mockLocalFunctions.expects(once())
545 var testNotificationData = { 867 .selector(eqJSON(
546 notificationsData: {'TEST_ID': {actionUrls: testActionUrls}} 868 testNotificationData.notificationsData[testNotificationId]))
547 }; 869 .will(returnValue(testActionUrl));
548 var testActionUrl = 'http://testurl.com'; 870 var chromeTabsCreateSavedArgs = new SaveMockArguments();
549 var testCreatedTab = undefined; // chrome.tabs.create fails 871 this.mockApis.expects(once()).
550 872 instrumented_tabs_create(
551 mockOnNotificationClickedDependencies(this); 873 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})),
552 this.makeMockLocalFunctions(['selector']); 874 chromeTabsCreateSavedArgs.match(ANYTHING)).
553 875 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab));
554 expectChromeLocalStorageGet( 876 this.mockApis.expects(once()).chrome_windows_create(
555 this, testNotificationDataRequest, testNotificationData); 877 eqJSON({url: testActionUrl, focused: true}));
556 this.mockLocalFunctions.expects(once()) 878
557 .selector(eqJSON( 879 // Invoking the tested function.
558 testNotificationData.notificationsData[testNotificationId])) 880 onNotificationClicked(
559 .will(returnValue(testActionUrl)); 881 testNotificationId, this.mockLocalFunctions.functions().selector);
560 var chromeTabsCreateSavedArgs = new SaveMockArguments(); 882 });
561 this.mockApis.expects(once()). 883
562 instrumented_tabs_create( 884 TEST_F(TEST_NAME, 'showNotificationGroups', function() {
rgustafson 2014/04/02 18:14:06 show -> Show
robliao 2014/04/02 21:53:20 Done.
563 chromeTabsCreateSavedArgs.match(eqJSON({url: testActionUrl})), 885 // Tests showNotificationGroups function. Checks that the function properly
564 chromeTabsCreateSavedArgs.match(ANYTHING)). 886 // deletes the card that didn't get an update, updates existing card and
565 will(invokeCallback(chromeTabsCreateSavedArgs, 1, testCreatedTab)); 887 // creates a new card that previously didn't exist.
566 this.mockApis.expects(once()).chrome_windows_create( 888
567 eqJSON({url: testActionUrl, focused: true})); 889 // Setup and expectations.
568 890 var existingNotifications = {
569 // Invoking the tested function. 891 'SHOULD BE DELETED': 'SOMETHING',
570 onNotificationClicked( 892 'SHOULD BE KEPT': 'SOMETHING'
571 testNotificationId, this.mockLocalFunctions.functions().selector); 893 };
572 }); 894
573 895 var keptCard = {
574 TEST_F( 896 chromeNotificationId: 'SHOULD BE KEPT',
575 'GoogleNowBackgroundUnitTest', 897 trigger: {showTimeSec: 0, hideTimeSec: 0}
576 'ShowNotificationCards', 898 };
577 function() { 899
578 // Tests showNotificationCards function. Checks that the function properly 900 var keptNotification = {
579 // deletes the card that didn't get an update, updates existing card and 901 receivedNotification: keptCard,
580 // creates a new card that previously didn't exist. 902 showTime: 0,
581 903 hideTime: 0
582 // Setup and expectations. 904 };
583 var existingNotifications = { 905
584 'SHOULD BE DELETED': 'SOMETHING', 906 var newCard = {
585 'SHOULD BE KEPT': 'SOMETHING' 907 chromeNotificationId: 'NEW CARD',
586 }; 908 trigger: {showTimeSec: 0, hideTimeSec: 0}
587 909 };
588 var notificationGroups = { 910
589 TEST_FIELD: 'TEST VALUE' 911 var newNotification = {
590 }; 912 receivedNotification: newCard,
591 913 showTime: 0,
592 var cards = { 914 hideTime: 0
593 'SHOULD BE KEPT': [1], 915 };
594 'NEW CARD': [2] 916
595 }; 917 var notificationGroups = {
596 918 'TEST GROUP 1': {cards: [keptCard], cardsTimestamp: 0},
597 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION'; 919 'TEST GROUP 2': {cards: [newCard], cardsTimestamp: 0}
598 920 };
599 var expectedUpdatedNotifications = { 921
600 'SHOULD BE KEPT': 'KEPT CARD NOTIFICATION DATA', 922 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION';
601 'NEW CARD': 'NEW CARD NOTIFICATION DATA' 923
602 }; 924 var expectedUpdatedNotifications = {
603 925 'SHOULD BE KEPT': 'KEPT CARD NOTIFICATION DATA',
604 this.makeAndRegisterMockApis([ 926 'NEW CARD': 'NEW CARD NOTIFICATION DATA'
605 'cardSet.update', 927 };
606 'chrome.storage.local.set', 928
607 'instrumented.notifications.getAll' 929 this.makeAndRegisterMockApis([
608 ]); 930 'cardSet.update',
609 this.makeMockLocalFunctions([ 931 'chrome.storage.local.set',
610 'onSuccess' 932 'instrumented.notifications.getAll'
611 ]); 933 ]);
612 934 this.makeMockLocalFunctions([
613 var notificationsGetAllSavedArgs = new SaveMockArguments(); 935 'onSuccess'
614 this.mockApis.expects(once()). 936 ]);
615 instrumented_notifications_getAll( 937
616 notificationsGetAllSavedArgs.match(ANYTHING)). 938 var notificationsGetAllSavedArgs = new SaveMockArguments();
617 will(invokeCallback( 939 this.mockApis.expects(once()).
618 notificationsGetAllSavedArgs, 0, existingNotifications)); 940 instrumented_notifications_getAll(
619 941 notificationsGetAllSavedArgs.match(ANYTHING)).
620 this.mockApis.expects(once()). 942 will(invokeCallback(
621 cardSet_update( 943 notificationsGetAllSavedArgs, 0, existingNotifications));
622 'SHOULD BE KEPT', 944
623 [1], 945 this.mockApis.expects(once()).
624 eqJSON(notificationGroups), 946 cardSet_update(
625 fakeOnCardShownFunction). 947 'SHOULD BE KEPT',
626 will(returnValue('KEPT CARD NOTIFICATION DATA')); 948 eqJSON([keptNotification]),
627 this.mockApis.expects(once()). 949 eqJSON(notificationGroups),
628 cardSet_update( 950 fakeOnCardShownFunction).
629 'NEW CARD', 951 will(returnValue('KEPT CARD NOTIFICATION DATA'));
630 [2], 952 this.mockApis.expects(once()).
631 eqJSON(notificationGroups), 953 cardSet_update(
632 fakeOnCardShownFunction). 954 'NEW CARD',
633 will(returnValue('NEW CARD NOTIFICATION DATA')); 955 eqJSON([newNotification]),
634 this.mockApis.expects(once()). 956 eqJSON(notificationGroups),
635 cardSet_update( 957 fakeOnCardShownFunction).
636 'SHOULD BE DELETED', 958 will(returnValue('NEW CARD NOTIFICATION DATA'));
637 [], 959 this.mockApis.expects(once()).
638 eqJSON(notificationGroups), 960 cardSet_update(
639 fakeOnCardShownFunction). 961 'SHOULD BE DELETED',
640 will(returnValue(undefined)); 962 [],
641 963 eqJSON(notificationGroups),
642 this.mockApis.expects(once()). 964 fakeOnCardShownFunction).
643 chrome_storage_local_set( 965 will(returnValue(undefined));
644 eqJSON({notificationsData: expectedUpdatedNotifications})); 966
645 967 this.mockApis.expects(once()).
646 this.mockLocalFunctions.expects(once()). 968 chrome_storage_local_set(
647 onSuccess(); 969 eqJSON({notificationsData: expectedUpdatedNotifications}));
648 970
649 // Invoking the tested function. 971 this.mockLocalFunctions.expects(once()).
650 showNotificationCards( 972 onSuccess(undefined);
651 notificationGroups, 973
652 cards, 974 // Invoking the tested function.
653 this.mockLocalFunctions.functions().onSuccess, 975 showNotificationGroups(notificationGroups, fakeOnCardShownFunction)
654 fakeOnCardShownFunction); 976 .then(this.mockLocalFunctions.functions().onSuccess);
655 }); 977 });
656 978
657 TEST_F( 979 TEST_F(TEST_NAME, 'ProcessServerResponse', function() {
658 'GoogleNowBackgroundUnitTest', 980 // Tests processServerResponse function.
659 'CombineGroup', 981
660 function() { 982 // Setup and expectations.
661 // Tests combineGroup function. Verifies that both notifications with and 983 Date.now = function() { return 3000000; };
662 // without show time are handled correctly and that cards are correctly 984
663 // added to existing cards with same ID or start a new combined card. 985 // GROUP1 was requested and contains cards c4 and c5. For c5, there is a
664 986 // non-expired dismissal, so it will be ignored.
665 // Setup and expectations. 987 // GROUP2 was not requested, but is contained in server response to
666 var combinedCards = { 988 // indicate that the group still exists. Stored group GROUP2 won't change.
667 'EXISTING CARD': [1] 989 // GROUP3 is stored, but is not present in server's response, which means
668 }; 990 // it doesn't exist anymore. This group will be deleted.
669 991 // GROUP4 doesn't contain cards, but it was requested. This is treated as
670 var receivedNotificationNoShowTime = { 992 // if it had an empty array of cards. Cards in the stored group will be
671 chromeNotificationId: 'EXISTING CARD', 993 // replaced with an empty array.
672 trigger: {hideTimeSec: 1} 994 // GROUP5 doesn't have next poll time, and it will be stored without next
673 }; 995 // poll time.
674 var receivedNotificationWithShowTime = { 996 var serverResponse = {
675 chromeNotificationId: 'NEW CARD', 997 groups: {
676 trigger: {showTimeSec: 2, hideTimeSec: 3} 998 GROUP1: {requested: true, nextPollSeconds: 46},
677 } 999 GROUP2: {requested: false},
678 1000 GROUP4: {requested: true, nextPollSeconds: 45},
679 var storedGroup = { 1001 GROUP5: {requested: true}
680 cardsTimestamp: 10000, 1002 },
681 cards: [ 1003 notifications: [
682 receivedNotificationNoShowTime, 1004 {notificationId: 'c4', groupName: 'GROUP1'},
683 receivedNotificationWithShowTime 1005 {notificationId: 'c5', groupName: 'GROUP1'}
684 ] 1006 ]
685 }; 1007 };
686 1008
687 // Invoking the tested function. 1009 var recentDismissals = {
688 combineGroup(combinedCards, storedGroup); 1010 c4: 1800000, // expired dismissal
689 1011 c5: 1800001 // non-expired dismissal
690 // Check the output value. 1012 };
691 var expectedCombinedCards = { 1013
692 'EXISTING CARD': [ 1014 var storedGroups = {
693 1, 1015 GROUP2: {
694 { 1016 cards: [{notificationId: 'c2'}],
695 receivedNotification: receivedNotificationNoShowTime, 1017 cardsTimestamp: 239,
696 hideTime: 11000 1018 nextPollTime: 10000
697 } 1019 },
698 ], 1020 GROUP3: {
699 'NEW CARD': [ 1021 cards: [{notificationId: 'c3'}],
700 { 1022 cardsTimestamp: 240,
701 receivedNotification: receivedNotificationWithShowTime, 1023 nextPollTime: 10001
702 showTime: 12000, 1024 },
703 hideTime: 13000 1025 GROUP4: {
704 } 1026 cards: [{notificationId: 'c6'}],
705 ] 1027 cardsTimestamp: 241,
706 }; 1028 nextPollTime: 10002
707 1029 }
708 assertEquals( 1030 };
709 JSON.stringify(expectedCombinedCards), 1031
710 JSON.stringify(combinedCards)); 1032 var expectedUpdatedGroups = {
711 }); 1033 GROUP1: {
712 1034 cards: [{notificationId: 'c4', groupName: 'GROUP1'}],
713 TEST_F( 1035 cardsTimestamp: 3000000,
714 'GoogleNowBackgroundUnitTest', 1036 nextPollTime: 3046000
715 'CombineAndShowNotificationCards', 1037 },
716 function() { 1038 GROUP2: {
717 // Tests combineAndShowNotificationCards function. 1039 cards: [{notificationId: 'c2'}],
718 // The test passes 2 groups to combineAndShowNotificationCards, checks 1040 cardsTimestamp: 239,
719 // that it calls combineGroup() for each of these groups and calls 1041 nextPollTime: 10000
720 // showNotificationCards() with the results of these combineGroup() calls. 1042 },
721 1043 GROUP4: {
722 // Setup and expectations. 1044 cards: [],
723 var testGroups = { 1045 cardsTimestamp: 3000000,
724 'TEST GROUP 1': {testField: 'TEST VALUE 1'}, 1046 nextPollTime: 3045000
725 'TEST GROUP 2': {testField: 'TEST VALUE 2'} 1047 },
726 }; 1048 GROUP5: {
727 1049 cards: [],
728 var fakeOnSuccessFunction = 'FAKE ON SUCCESS FUNCTION'; 1050 cardsTimestamp: 3000000
729 var fakeOnCardShownFunction = 'FAKE ON CARD SHOWN FUNCTION'; 1051 }
730 1052 };
731 this.makeAndRegisterMockGlobals( 1053
732 ['combineGroup', 'showNotificationCards']); 1054 var expectedUpdatedRecentDismissals = {
733 1055 c5: 1800001
734 var combineGroupSavedArgs = new SaveMockArguments(); 1056 };
735 this.mockGlobals.expects(once()). 1057
736 combineGroup( 1058 this.makeAndRegisterMockGlobals([
737 combineGroupSavedArgs.match(eqJSON({})), 1059 'scheduleNextPoll'
738 combineGroupSavedArgs.match(eqJSON({testField: 'TEST VALUE 1'}))). 1060 ]);
739 will(callFunction(function() { 1061
740 combineGroupSavedArgs.arguments[0].card1 = { 1062 this.makeAndRegisterMockApis([
741 testValue: 'TEST CARD VALUE 1' 1063 'fillFromChromeLocalStorage',
742 }; 1064 ]);
743 })); 1065
744 this.mockGlobals.expects(once()). 1066 expectChromeLocalStorageGet(
745 combineGroup( 1067 this,
746 combineGroupSavedArgs.match( 1068 {
747 eqJSON({card1: {testValue: 'TEST CARD VALUE 1'}})), 1069 notificationGroups: {},
748 combineGroupSavedArgs.match( 1070 recentDismissals: {}
749 eqJSON({testField: 'TEST VALUE 2'}))). 1071 },
750 will(callFunction(function() { 1072 {
751 combineGroupSavedArgs.arguments[0].card2 = { 1073 notificationGroups: storedGroups,
752 testValue: 'TEST CARD VALUE 2' 1074 recentDismissals: recentDismissals
753 }; 1075 });
754 })); 1076
755 this.mockGlobals.expects(once()). 1077 this.mockGlobals.expects(once()).
756 showNotificationCards( 1078 scheduleNextPoll(eqJSON(expectedUpdatedGroups), true);
757 eqJSON(testGroups), 1079
758 eqJSON({ 1080 // Invoking the tested function.
759 card1: {testValue: 'TEST CARD VALUE 1'}, 1081 var processedResponse = processServerResponse(serverResponse);
760 card2: {testValue: 'TEST CARD VALUE 2'} 1082 });
761 }), 1083
762 fakeOnSuccessFunction, 1084 TEST_F(TEST_NAME, 'ProcessServerResponseGoogleNowDisabled', function() {
763 fakeOnCardShownFunction); 1085 // Tests processServerResponse function for the case when the response
764 1086 // indicates that Google Now is disabled.
765 // Invoking the tested function. 1087
766 combineAndShowNotificationCards( 1088 // Setup and expectations.
767 testGroups, fakeOnSuccessFunction, fakeOnCardShownFunction); 1089 var serverResponse = {
768 }); 1090 googleNowDisabled: true,
769 1091 groups: {
770 TEST_F( 1092 GROUP1: {nextPollTimeSeconds: 200}
771 'GoogleNowBackgroundUnitTest', 1093 }
772 'ProcessServerResponse', 1094 };
773 function() { 1095
774 // Tests processServerResponse function. 1096 this.makeAndRegisterMockGlobals([
775 1097 'onStateChange',
776 // Setup and expectations. 1098 'scheduleNextPoll',
777 Date.now = function() { return 3000000; }; 1099 ]);
778 1100
779 // GROUP1 was requested and contains cards c4 and c5. For c5, there is a 1101 this.makeAndRegisterMockApis([
780 // non-expired dismissal, so it will be ignored. 1102 'chrome.storage.local.set',
781 // GROUP2 was not requested, but is contained in server response to 1103 'fillFromChromeLocalStorage'
782 // indicate that the group still exists. Stored group GROUP2 won't change. 1104 ]);
783 // GROUP3 is stored, but is not present in server's response, which means 1105
784 // it doesn't exist anymore. This group will be deleted. 1106 this.mockApis.expects(once()).
785 // GROUP4 doesn't contain cards, but it was requested. This is treated as 1107 chrome_storage_local_set(eqJSON({googleNowEnabled: false}));
786 // if it had an empty array of cards. Cards in the stored group will be 1108
787 // replaced with an empty array. 1109 this.mockGlobals.expects(once()).onStateChange();
788 // GROUP5 doesn't have next poll time, and it will be stored without next 1110
789 // poll time. 1111 this.mockApis.expects(never()).fillFromChromeLocalStorage();
790 var serverResponse = { 1112
791 groups: { 1113 this.mockGlobals.expects(never()).scheduleNextPoll();
792 GROUP1: {requested: true, nextPollSeconds: 46}, 1114
793 GROUP2: {requested: false}, 1115 var processedResponse = processServerResponse(serverResponse);
794 GROUP4: {requested: true, nextPollSeconds: 45}, 1116 });
795 GROUP5: {requested: true} 1117
796 },
797 notifications: [
798 {notificationId: 'c4', groupName: 'GROUP1'},
799 {notificationId: 'c5', groupName: 'GROUP1'}
800 ]
801 };
802
803 var recentDismissals = {
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

Powered by Google App Engine
This is Rietveld 408576698