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

Side by Side Diff: components/ntp_snippets/remote/remote_suggestions_fetcher_unittest.cc

Issue 2672253003: [Remote fetcher] Add unit-tests for the authenticated case (Closed)
Patch Set: Cleaning up DLOGs Created 3 years, 10 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
« no previous file with comments | « no previous file | 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 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 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 #include "components/ntp_snippets/remote/remote_suggestions_fetcher.h" 5 #include "components/ntp_snippets/remote/remote_suggestions_fetcher.h"
6 6
7 #include <deque> 7 #include <deque>
8 #include <map> 8 #include <map>
9 #include <set> 9 #include <set>
10 #include <utility> 10 #include <utility>
11 #include <vector> 11 #include <vector>
12 12
13 #include "base/json/json_reader.h" 13 #include "base/json/json_reader.h"
14 #include "base/memory/ptr_util.h" 14 #include "base/memory/ptr_util.h"
15 #include "base/strings/stringprintf.h" 15 #include "base/strings/stringprintf.h"
16 #include "base/test/histogram_tester.h" 16 #include "base/test/histogram_tester.h"
17 #include "base/test/test_mock_time_task_runner.h" 17 #include "base/test/test_mock_time_task_runner.h"
18 #include "base/threading/thread_task_runner_handle.h" 18 #include "base/threading/thread_task_runner_handle.h"
19 #include "base/time/time.h" 19 #include "base/time/time.h"
20 #include "base/values.h" 20 #include "base/values.h"
21 #include "components/ntp_snippets/category.h" 21 #include "components/ntp_snippets/category.h"
22 #include "components/ntp_snippets/features.h" 22 #include "components/ntp_snippets/features.h"
23 #include "components/ntp_snippets/ntp_snippets_constants.h" 23 #include "components/ntp_snippets/ntp_snippets_constants.h"
24 #include "components/ntp_snippets/remote/remote_suggestion.h" 24 #include "components/ntp_snippets/remote/remote_suggestion.h"
25 #include "components/ntp_snippets/remote/request_params.h" 25 #include "components/ntp_snippets/remote/request_params.h"
26 #include "components/ntp_snippets/remote/test_utils.h"
26 #include "components/ntp_snippets/user_classifier.h" 27 #include "components/ntp_snippets/user_classifier.h"
27 #include "components/prefs/testing_pref_service.h" 28 #include "components/prefs/testing_pref_service.h"
28 #include "components/signin/core/browser/account_tracker_service.h"
29 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" 29 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
30 #include "components/signin/core/browser/fake_signin_manager.h" 30 #include "components/signin/core/browser/fake_signin_manager.h"
31 #include "components/signin/core/browser/test_signin_client.h"
32 #include "components/variations/entropy_provider.h" 31 #include "components/variations/entropy_provider.h"
33 #include "components/variations/variations_params_manager.h" 32 #include "components/variations/variations_params_manager.h"
33 #include "google_apis/gaia/fake_oauth2_token_service_delegate.h"
34 #include "net/url_request/test_url_fetcher_factory.h" 34 #include "net/url_request/test_url_fetcher_factory.h"
35 #include "net/url_request/url_request_test_util.h" 35 #include "net/url_request/url_request_test_util.h"
36 #include "testing/gmock/include/gmock/gmock.h" 36 #include "testing/gmock/include/gmock/gmock.h"
37 #include "testing/gtest/include/gtest/gtest.h" 37 #include "testing/gtest/include/gtest/gtest.h"
38 38
39 namespace ntp_snippets { 39 namespace ntp_snippets {
40 40
41 namespace { 41 namespace {
42 42
43 using testing::_; 43 using testing::_;
44 using testing::AllOf; 44 using testing::AllOf;
45 using testing::ElementsAre; 45 using testing::ElementsAre;
46 using testing::Eq; 46 using testing::Eq;
47 using testing::Field; 47 using testing::Field;
48 using testing::IsEmpty; 48 using testing::IsEmpty;
49 using testing::Not; 49 using testing::Not;
50 using testing::NotNull; 50 using testing::NotNull;
51 using testing::Pointee; 51 using testing::Pointee;
52 using testing::PrintToString; 52 using testing::PrintToString;
53 using testing::Return; 53 using testing::Return;
54 using testing::StartsWith; 54 using testing::StartsWith;
55 using testing::WithArg; 55 using testing::WithArg;
56 56
57 const char kAPIKey[] = "fakeAPIkey"; 57 const char kAPIKey[] = "fakeAPIkey";
58 const char kTestChromeReaderUrl[] = 58 const char kTestChromeReaderUrl[] =
59 "https://chromereader-pa.googleapis.com/v1/fetch?key=fakeAPIkey"; 59 "https://chromereader-pa.googleapis.com/v1/fetch?key=fakeAPIkey";
60 const char kTestChromeContentSuggestionsUrl[] = 60 const char kTestChromeContentSuggestionsUrl[] =
Marc Treib 2017/02/06 11:03:17 nit: Maybe rename this to ...SignedOutUrl to make
jkrcal 2017/02/07 08:44:18 Done.
61 "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/" 61 "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/"
62 "fetch?key=fakeAPIkey"; 62 "fetch?key=fakeAPIkey";
63 const char kTestChromeContentSuggestionsSignedInUrl[] =
64 "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/fetch";
65
66 const char kTestEmail[] = "foo@bar.com";
63 67
64 // Artificial time delay for JSON parsing. 68 // Artificial time delay for JSON parsing.
65 const int64_t kTestJsonParsingLatencyMs = 20; 69 const int64_t kTestJsonParsingLatencyMs = 20;
66 70
67 ACTION_P(MoveArgument1PointeeTo, ptr) { 71 ACTION_P(MoveArgument1PointeeTo, ptr) {
68 *ptr = std::move(*arg1); 72 *ptr = std::move(*arg1);
69 } 73 }
70 74
71 MATCHER(HasValue, "") { 75 MATCHER(HasValue, "") {
72 return static_cast<bool>(*arg); 76 return static_cast<bool>(*arg);
(...skipping 191 matching lines...) Expand 10 before | Expand all | Expand 10 after
264 std::move(error_callback)), 268 std::move(error_callback)),
265 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); 269 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs));
266 } 270 }
267 271
268 } // namespace 272 } // namespace
269 273
270 // TODO(jkrcal): Add unit-tests with signin client being signed in (covering 274 // TODO(jkrcal): Add unit-tests with signin client being signed in (covering
271 // sign-in / refresh tokens / access token code). crbug.com/688310 275 // sign-in / refresh tokens / access token code). crbug.com/688310
272 class RemoteSuggestionsFetcherTestBase : public testing::Test { 276 class RemoteSuggestionsFetcherTestBase : public testing::Test {
273 public: 277 public:
274 explicit RemoteSuggestionsFetcherTestBase(const GURL& gurl) 278 explicit RemoteSuggestionsFetcherTestBase()
275 : default_variation_params_( 279 : default_variation_params_(
276 {{"send_top_languages", "true"}, {"send_user_class", "true"}}), 280 {{"send_top_languages", "true"}, {"send_user_class", "true"}}),
277 params_manager_(ntp_snippets::kStudyName, 281 params_manager_(ntp_snippets::kStudyName,
278 default_variation_params_, 282 default_variation_params_,
279 {ntp_snippets::kArticleSuggestionsFeature.name}), 283 {ntp_snippets::kArticleSuggestionsFeature.name}),
280 mock_task_runner_(new base::TestMockTimeTaskRunner()), 284 mock_task_runner_(new base::TestMockTimeTaskRunner()),
281 mock_task_runner_handle_(mock_task_runner_), 285 mock_task_runner_handle_(mock_task_runner_) {
282 signin_client_(base::MakeUnique<TestSigninClient>(nullptr)), 286 RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry());
283 account_tracker_(base::MakeUnique<AccountTrackerService>()), 287 UserClassifier::RegisterProfilePrefs(utils_.pref_service()->registry());
284 fake_signin_manager_( 288 user_classifier_ =
285 base::MakeUnique<FakeSigninManagerBase>(signin_client_.get(), 289 base::MakeUnique<UserClassifier>(utils_.pref_service());
286 account_tracker_.get())),
287 fake_token_service_(base::MakeUnique<FakeProfileOAuth2TokenService>()),
288 pref_service_(base::MakeUnique<TestingPrefServiceSimple>()),
289 test_url_(gurl) {
290 RequestThrottler::RegisterProfilePrefs(pref_service_->registry());
291 UserClassifier::RegisterProfilePrefs(pref_service_->registry());
292 user_classifier_ = base::MakeUnique<UserClassifier>(pref_service_.get());
293 // Increase initial time such that ticks are non-zero. 290 // Increase initial time such that ticks are non-zero.
294 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234)); 291 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234));
295 ResetSnippetsFetcher(); 292 ResetSnippetsFetcher();
296 } 293 }
297 294
298 void ResetSnippetsFetcher() { 295 void ResetSnippetsFetcher() {
296 scoped_refptr<net::TestURLRequestContextGetter> request_context_getter =
297 new net::TestURLRequestContextGetter(mock_task_runner_.get());
298
299 request_context_getter_ =
300 new net::TestURLRequestContextGetter(mock_task_runner_.get());
Marc Treib 2017/02/06 11:03:17 Why do we create another request context getter he
jkrcal 2017/02/07 08:44:18 Done. Sorry, this was a rest from my experiments h
301 fake_token_service_delegate_ =
302 new FakeOAuth2TokenServiceDelegate(request_context_getter_.get());
Marc Treib 2017/02/06 11:03:17 This looks like a memleak?
jkrcal 2017/02/07 08:44:18 It does but it is not. Added a comment to explain.
Marc Treib 2017/02/07 09:18:12 Acknowledged.
303 fake_token_service_ = base::MakeUnique<FakeProfileOAuth2TokenService>(
304 fake_token_service_delegate_);
305
299 snippets_fetcher_ = base::MakeUnique<RemoteSuggestionsFetcher>( 306 snippets_fetcher_ = base::MakeUnique<RemoteSuggestionsFetcher>(
300 fake_signin_manager_.get(), fake_token_service_.get(), 307 utils_.fake_signin_manager(), fake_token_service_.get(),
301 scoped_refptr<net::TestURLRequestContextGetter>( 308 std::move(request_context_getter), utils_.pref_service(), nullptr,
302 new net::TestURLRequestContextGetter(mock_task_runner_.get())), 309 base::Bind(&ParseJsonDelayed), kAPIKey, user_classifier_.get());
303 pref_service_.get(), nullptr, base::Bind(&ParseJsonDelayed), kAPIKey,
304 user_classifier_.get());
305 310
306 snippets_fetcher_->SetTickClockForTesting( 311 snippets_fetcher_->SetTickClockForTesting(
307 mock_task_runner_->GetMockTickClock()); 312 mock_task_runner_->GetMockTickClock());
308 } 313 }
309 314
315 void IssueRefreshToken() {
316 fake_token_service_delegate_->UpdateCredentials(kTestEmail, "token");
317 }
318
319 void IssueOAuth2Token() {
320 fake_token_service_->IssueAllTokensForAccount(kTestEmail, "access_token",
321 base::Time::Max());
322 }
323
324 void CancelOAuth2TokenRequests() {
325 fake_token_service_->IssueErrorForAllPendingRequestsForAccount(
326 kTestEmail, GoogleServiceAuthError(
327 GoogleServiceAuthError::State::REQUEST_CANCELED));
328 }
329
330 void SignIn() {
Marc Treib 2017/02/06 11:03:17 nitty nit: Put this before IssueRefreshToken? That
jkrcal 2017/02/07 08:44:18 Done.
331 utils_.fake_signin_manager()->SignIn(kTestEmail);
332 }
333
310 RemoteSuggestionsFetcher::SnippetsAvailableCallback 334 RemoteSuggestionsFetcher::SnippetsAvailableCallback
311 ToSnippetsAvailableCallback(MockSnippetsAvailableCallback* callback) { 335 ToSnippetsAvailableCallback(MockSnippetsAvailableCallback* callback) {
312 return base::BindOnce(&MockSnippetsAvailableCallback::WrappedRun, 336 return base::BindOnce(&MockSnippetsAvailableCallback::WrappedRun,
313 base::Unretained(callback)); 337 base::Unretained(callback));
314 } 338 }
315 339
316 RemoteSuggestionsFetcher& snippets_fetcher() { return *snippets_fetcher_; } 340 RemoteSuggestionsFetcher& snippets_fetcher() { return *snippets_fetcher_; }
317 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; } 341 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; }
318 void FastForwardUntilNoTasksRemain() { 342 void FastForwardUntilNoTasksRemain() {
319 mock_task_runner_->FastForwardUntilNoTasksRemain(); 343 mock_task_runner_->FastForwardUntilNoTasksRemain();
(...skipping 20 matching lines...) Expand all
340 void SetVariationParam(std::string param_name, std::string value) { 364 void SetVariationParam(std::string param_name, std::string value) {
341 std::map<std::string, std::string> params = default_variation_params_; 365 std::map<std::string, std::string> params = default_variation_params_;
342 params[param_name] = value; 366 params[param_name] = value;
343 367
344 params_manager_.ClearAllVariationParams(); 368 params_manager_.ClearAllVariationParams();
345 params_manager_.SetVariationParamsWithFeatureAssociations( 369 params_manager_.SetVariationParamsWithFeatureAssociations(
346 ntp_snippets::kStudyName, params, 370 ntp_snippets::kStudyName, params,
347 {ntp_snippets::kArticleSuggestionsFeature.name}); 371 {ntp_snippets::kArticleSuggestionsFeature.name});
348 } 372 }
349 373
350 void SetFakeResponse(const std::string& response_data, 374 void SetFakeResponse(const std::string& test_url,
Marc Treib 2017/02/06 11:03:17 Should this be a GURL?
jkrcal 2017/02/07 08:44:18 Removed (see below).
375 const std::string& response_data,
351 net::HttpStatusCode response_code, 376 net::HttpStatusCode response_code,
352 net::URLRequestStatus::Status status) { 377 net::URLRequestStatus::Status status) {
353 InitFakeURLFetcherFactory(); 378 InitFakeURLFetcherFactory();
354 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, 379 fake_url_fetcher_factory_->SetFakeResponse(GURL(test_url), response_data,
355 response_code, status); 380 response_code, status);
356 } 381 }
357 382
358 TestingPrefServiceSimple* pref_service() const { return pref_service_.get(); }
359
360 protected: 383 protected:
361 std::map<std::string, std::string> default_variation_params_; 384 std::map<std::string, std::string> default_variation_params_;
362 385
363 private: 386 private:
387 test::RemoteSuggestionsTestUtils utils_;
364 variations::testing::VariationParamsManager params_manager_; 388 variations::testing::VariationParamsManager params_manager_;
365 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; 389 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_;
366 base::ThreadTaskRunnerHandle mock_task_runner_handle_; 390 base::ThreadTaskRunnerHandle mock_task_runner_handle_;
367 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; 391 FailingFakeURLFetcherFactory failing_url_fetcher_factory_;
368 // Initialized lazily in SetFakeResponse(). 392 // Initialized lazily in SetFakeResponse().
369 std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_; 393 std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_;
370 std::unique_ptr<TestSigninClient> signin_client_; 394 FakeOAuth2TokenServiceDelegate* fake_token_service_delegate_;
371 std::unique_ptr<AccountTrackerService> account_tracker_; 395 std::unique_ptr<FakeProfileOAuth2TokenService> fake_token_service_;
372 std::unique_ptr<SigninManagerBase> fake_signin_manager_;
373 std::unique_ptr<OAuth2TokenService> fake_token_service_;
374 std::unique_ptr<RemoteSuggestionsFetcher> snippets_fetcher_; 396 std::unique_ptr<RemoteSuggestionsFetcher> snippets_fetcher_;
375 std::unique_ptr<TestingPrefServiceSimple> pref_service_;
376 std::unique_ptr<UserClassifier> user_classifier_; 397 std::unique_ptr<UserClassifier> user_classifier_;
377 MockSnippetsAvailableCallback mock_callback_; 398 MockSnippetsAvailableCallback mock_callback_;
378 const GURL test_url_;
379 base::HistogramTester histogram_tester_; 399 base::HistogramTester histogram_tester_;
400 scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
380 401
381 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsFetcherTestBase); 402 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsFetcherTestBase);
382 }; 403 };
383 404
384 class ChromeReaderSnippetsFetcherTest 405 class ChromeReaderSnippetsFetcherTest
385 : public RemoteSuggestionsFetcherTestBase { 406 : public RemoteSuggestionsFetcherTestBase {
386 public: 407 public:
387 ChromeReaderSnippetsFetcherTest() 408 ChromeReaderSnippetsFetcherTest()
388 : RemoteSuggestionsFetcherTestBase(GURL(kTestChromeReaderUrl)) { 409 : RemoteSuggestionsFetcherTestBase() {
389 default_variation_params_["content_suggestions_backend"] = 410 default_variation_params_["content_suggestions_backend"] =
390 kChromeReaderServer; 411 kChromeReaderServer;
391 SetVariationParam("content_suggestions_backend", kChromeReaderServer); 412 SetVariationParam("content_suggestions_backend", kChromeReaderServer);
392 ResetSnippetsFetcher(); 413 ResetSnippetsFetcher();
393 } 414 }
394 }; 415 };
395 416
396 class NTPSnippetsContentSuggestionsFetcherTest 417 class NTPSnippetsContentSuggestionsFetcherTest
397 : public RemoteSuggestionsFetcherTestBase { 418 : public RemoteSuggestionsFetcherTestBase {
398 public: 419 public:
399 NTPSnippetsContentSuggestionsFetcherTest() 420 NTPSnippetsContentSuggestionsFetcherTest()
400 : RemoteSuggestionsFetcherTestBase( 421 : RemoteSuggestionsFetcherTestBase() {}
Marc Treib 2017/02/06 11:03:17 Possible alternative: Keep the TestUrl in the ctor
jkrcal 2017/02/07 08:44:18 Done.
401 GURL(kTestChromeContentSuggestionsUrl)) {}
402 }; 422 };
403 423
404 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) { 424 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) {
405 // The lack of registered baked in responses would cause any fetch to fail. 425 // The lack of registered baked in responses would cause any fetch to fail.
406 FastForwardUntilNoTasksRemain(); 426 FastForwardUntilNoTasksRemain();
407 EXPECT_THAT(histogram_tester().GetAllSamples( 427 EXPECT_THAT(histogram_tester().GetAllSamples(
408 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 428 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
409 IsEmpty()); 429 IsEmpty());
410 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 430 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
411 IsEmpty()); 431 IsEmpty());
412 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); 432 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty());
413 } 433 }
414 434
415 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfully) { 435 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfully) {
416 const std::string kJsonStr = 436 const std::string kJsonStr =
417 "{\"recos\": [{" 437 "{\"recos\": [{"
418 " \"contentInfo\": {" 438 " \"contentInfo\": {"
419 " \"url\" : \"http://localhost/foobar\"," 439 " \"url\" : \"http://localhost/foobar\","
420 " \"sourceCorpusInfo\" : [{" 440 " \"sourceCorpusInfo\" : [{"
421 " \"ampUrl\" : \"http://localhost/amp\"," 441 " \"ampUrl\" : \"http://localhost/amp\","
422 " \"corpusId\" : \"http://localhost/foobar\"," 442 " \"corpusId\" : \"http://localhost/foobar\","
423 " \"publisherData\": { \"sourceName\" : \"Foo News\" }" 443 " \"publisherData\": { \"sourceName\" : \"Foo News\" }"
424 " }]" 444 " }]"
425 " }" 445 " }"
426 "}]}"; 446 "}]}";
427 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 447 SetFakeResponse(kTestChromeReaderUrl, /*response_data=*/kJsonStr,
428 net::URLRequestStatus::SUCCESS); 448 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
429 EXPECT_CALL(mock_callback(), 449 EXPECT_CALL(mock_callback(),
430 Run(IsSuccess(), 450 Run(IsSuccess(),
431 AllOf(IsSingleArticle("http://localhost/foobar"), 451 AllOf(IsSingleArticle("http://localhost/foobar"),
432 FirstCategoryHasInfo(IsCategoryInfoForArticles())))); 452 FirstCategoryHasInfo(IsCategoryInfoForArticles()))));
433 snippets_fetcher().FetchSnippets( 453 snippets_fetcher().FetchSnippets(
434 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 454 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
435 FastForwardUntilNoTasksRemain(); 455 FastForwardUntilNoTasksRemain();
436 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 456 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
437 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 457 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
438 EXPECT_THAT(histogram_tester().GetAllSamples( 458 EXPECT_THAT(histogram_tester().GetAllSamples(
(...skipping 15 matching lines...) Expand all
454 " \"snippet\" : \"...\"," 474 " \"snippet\" : \"...\","
455 " \"fullPageUrl\" : \"http://localhost/foobar\"," 475 " \"fullPageUrl\" : \"http://localhost/foobar\","
456 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\"," 476 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
457 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\"," 477 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
458 " \"attribution\" : \"Foo News\"," 478 " \"attribution\" : \"Foo News\","
459 " \"imageUrl\" : \"http://localhost/foobar.jpg\"," 479 " \"imageUrl\" : \"http://localhost/foobar.jpg\","
460 " \"ampUrl\" : \"http://localhost/amp\"," 480 " \"ampUrl\" : \"http://localhost/amp\","
461 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " 481 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
462 " }]" 482 " }]"
463 "}]}"; 483 "}]}";
464 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 484 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
465 net::URLRequestStatus::SUCCESS); 485 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
466 EXPECT_CALL(mock_callback(), 486 EXPECT_CALL(mock_callback(),
467 Run(IsSuccess(), 487 Run(IsSuccess(),
468 AllOf(IsSingleArticle("http://localhost/foobar"), 488 AllOf(IsSingleArticle("http://localhost/foobar"),
469 FirstCategoryHasInfo(IsCategoryInfoForArticles())))); 489 FirstCategoryHasInfo(IsCategoryInfoForArticles()))));
470 snippets_fetcher().FetchSnippets( 490 snippets_fetcher().FetchSnippets(
471 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 491 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
472 FastForwardUntilNoTasksRemain(); 492 FastForwardUntilNoTasksRemain();
473 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 493 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
474 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 494 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
475 EXPECT_THAT(histogram_tester().GetAllSamples( 495 EXPECT_THAT(histogram_tester().GetAllSamples(
496 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
497 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
498 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
499 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs,
500 /*count=*/1)));
501 }
502
503 TEST_F(NTPSnippetsContentSuggestionsFetcherTest,
504 ShouldFetchSuccessfullyWhenSignedIn) {
505 SignIn();
506 IssueRefreshToken();
507
508 const std::string kJsonStr =
Marc Treib 2017/02/06 11:03:17 Completely orthogonal to this CL, but at some poin
jkrcal 2017/02/07 08:44:18 Acknowledged.
509 "{\"categories\" : [{"
510 " \"id\": 1,"
511 " \"localizedTitle\": \"Articles for You\","
512 " \"suggestions\" : [{"
513 " \"ids\" : [\"http://localhost/foobar\"],"
514 " \"title\" : \"Foo Barred from Baz\","
515 " \"snippet\" : \"...\","
516 " \"fullPageUrl\" : \"http://localhost/foobar\","
517 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
518 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
519 " \"attribution\" : \"Foo News\","
520 " \"imageUrl\" : \"http://localhost/foobar.jpg\","
521 " \"ampUrl\" : \"http://localhost/amp\","
522 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
523 " }]"
524 "}]}";
525 SetFakeResponse(kTestChromeContentSuggestionsSignedInUrl,
526 /*response_data=*/kJsonStr, net::HTTP_OK,
527 net::URLRequestStatus::SUCCESS);
528 EXPECT_CALL(mock_callback(),
529 Run(IsSuccess(),
530 AllOf(IsSingleArticle("http://localhost/foobar"),
531 FirstCategoryHasInfo(IsCategoryInfoForArticles()))));
532
533 snippets_fetcher().FetchSnippets(
534 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
535
536 IssueOAuth2Token();
537 FastForwardUntilNoTasksRemain();
Marc Treib 2017/02/06 11:03:17 This is necessary for the fake response, right? Wo
jkrcal 2017/02/07 08:44:18 Done.
538
539 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
540 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
541 EXPECT_THAT(histogram_tester().GetAllSamples(
542 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
543 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
544 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
545 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs,
546 /*count=*/1)));
547 }
548
549 TEST_F(NTPSnippetsContentSuggestionsFetcherTest,
550 ShouldFetchSuccessfullyWhenSignedInAndOAuthCancelled) {
Marc Treib 2017/02/06 11:03:17 This really tests the retry, correct? Maybe someth
jkrcal 2017/02/07 08:44:18 Done.
551 SignIn();
552 IssueRefreshToken();
553
554 const std::string kJsonStr =
555 "{\"categories\" : [{"
556 " \"id\": 1,"
557 " \"localizedTitle\": \"Articles for You\","
558 " \"suggestions\" : [{"
559 " \"ids\" : [\"http://localhost/foobar\"],"
560 " \"title\" : \"Foo Barred from Baz\","
561 " \"snippet\" : \"...\","
562 " \"fullPageUrl\" : \"http://localhost/foobar\","
563 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
564 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
565 " \"attribution\" : \"Foo News\","
566 " \"imageUrl\" : \"http://localhost/foobar.jpg\","
567 " \"ampUrl\" : \"http://localhost/amp\","
568 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
569 " }]"
570 "}]}";
571 SetFakeResponse(kTestChromeContentSuggestionsSignedInUrl,
572 /*response_data=*/kJsonStr, net::HTTP_OK,
573 net::URLRequestStatus::SUCCESS);
574 EXPECT_CALL(mock_callback(),
575 Run(IsSuccess(),
576 AllOf(IsSingleArticle("http://localhost/foobar"),
577 FirstCategoryHasInfo(IsCategoryInfoForArticles()))));
578
579 snippets_fetcher().FetchSnippets(
580 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
581
582 CancelOAuth2TokenRequests();
583 IssueOAuth2Token();
584 FastForwardUntilNoTasksRemain();
585
586 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
587 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
588 EXPECT_THAT(histogram_tester().GetAllSamples(
476 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 589 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
477 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 590 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
478 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 591 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
479 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs, 592 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs,
480 /*count=*/1))); 593 /*count=*/1)));
481 } 594 }
482 595
483 TEST_F(NTPSnippetsContentSuggestionsFetcherTest, EmptyCategoryIsOK) { 596 TEST_F(NTPSnippetsContentSuggestionsFetcherTest, EmptyCategoryIsOK) {
484 const std::string kJsonStr = 597 const std::string kJsonStr =
485 "{\"categories\" : [{" 598 "{\"categories\" : [{"
486 " \"id\": 1," 599 " \"id\": 1,"
487 " \"localizedTitle\": \"Articles for You\"" 600 " \"localizedTitle\": \"Articles for You\""
488 "}]}"; 601 "}]}";
489 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 602 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
490 net::URLRequestStatus::SUCCESS); 603 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
491 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); 604 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList()));
492 snippets_fetcher().FetchSnippets( 605 snippets_fetcher().FetchSnippets(
493 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 606 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
494 FastForwardUntilNoTasksRemain(); 607 FastForwardUntilNoTasksRemain();
495 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 608 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
496 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 609 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
497 EXPECT_THAT(histogram_tester().GetAllSamples( 610 EXPECT_THAT(histogram_tester().GetAllSamples(
498 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 611 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
499 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 612 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
500 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 613 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
(...skipping 28 matching lines...) Expand all
529 " \"snippet\" : \"...\"," 642 " \"snippet\" : \"...\","
530 " \"fullPageUrl\" : \"http://localhost/foo2\"," 643 " \"fullPageUrl\" : \"http://localhost/foo2\","
531 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\"," 644 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
532 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\"," 645 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
533 " \"attribution\" : \"Foo News\"," 646 " \"attribution\" : \"Foo News\","
534 " \"imageUrl\" : \"http://localhost/foo2.jpg\"," 647 " \"imageUrl\" : \"http://localhost/foo2.jpg\","
535 " \"ampUrl\" : \"http://localhost/amp\"," 648 " \"ampUrl\" : \"http://localhost/amp\","
536 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " 649 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
537 " }]" 650 " }]"
538 "}]}"; 651 "}]}";
539 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 652 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
540 net::URLRequestStatus::SUCCESS); 653 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
541 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories; 654 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories;
542 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) 655 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _))
543 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); 656 .WillOnce(MoveArgument1PointeeTo(&fetched_categories));
544 snippets_fetcher().FetchSnippets( 657 snippets_fetcher().FetchSnippets(
545 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 658 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
546 FastForwardUntilNoTasksRemain(); 659 FastForwardUntilNoTasksRemain();
547 660
548 ASSERT_TRUE(fetched_categories); 661 ASSERT_TRUE(fetched_categories);
549 ASSERT_THAT(fetched_categories->size(), Eq(2u)); 662 ASSERT_THAT(fetched_categories->size(), Eq(2u));
550 for (const auto& category : *fetched_categories) { 663 for (const auto& category : *fetched_categories) {
(...skipping 39 matching lines...) Expand 10 before | Expand all | Expand 10 after
590 " \"snippet\" : \"...\"," 703 " \"snippet\" : \"...\","
591 " \"fullPageUrl\" : \"http://localhost/foo2\"," 704 " \"fullPageUrl\" : \"http://localhost/foo2\","
592 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\"," 705 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
593 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\"," 706 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
594 " \"attribution\" : \"Foo News\"," 707 " \"attribution\" : \"Foo News\","
595 " \"imageUrl\" : \"http://localhost/foo2.jpg\"," 708 " \"imageUrl\" : \"http://localhost/foo2.jpg\","
596 " \"ampUrl\" : \"http://localhost/amp\"," 709 " \"ampUrl\" : \"http://localhost/amp\","
597 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " 710 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
598 " }]" 711 " }]"
599 "}]}"; 712 "}]}";
600 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 713 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
601 net::URLRequestStatus::SUCCESS); 714 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
602 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories; 715 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories;
603 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) 716 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _))
604 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); 717 .WillOnce(MoveArgument1PointeeTo(&fetched_categories));
605 snippets_fetcher().FetchSnippets( 718 snippets_fetcher().FetchSnippets(
606 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 719 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
607 FastForwardUntilNoTasksRemain(); 720 FastForwardUntilNoTasksRemain();
608 721
609 ASSERT_TRUE(fetched_categories); 722 ASSERT_TRUE(fetched_categories);
610 ASSERT_THAT(fetched_categories->size(), Eq(1u)); 723 ASSERT_THAT(fetched_categories->size(), Eq(1u));
611 EXPECT_THAT(fetched_categories->front().info.has_fetch_action(), Eq(false)); 724 EXPECT_THAT(fetched_categories->front().info.has_fetch_action(), Eq(false));
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after
654 " \"snippet\" : \"...\"," 767 " \"snippet\" : \"...\","
655 " \"fullPageUrl\" : \"http://localhost/foo3\"," 768 " \"fullPageUrl\" : \"http://localhost/foo3\","
656 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\"," 769 " \"creationTime\" : \"2016-06-30T11:01:37.000Z\","
657 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\"," 770 " \"expirationTime\" : \"2016-07-01T11:01:37.000Z\","
658 " \"attribution\" : \"Foo News\"," 771 " \"attribution\" : \"Foo News\","
659 " \"imageUrl\" : \"http://localhost/foo3.jpg\"," 772 " \"imageUrl\" : \"http://localhost/foo3.jpg\","
660 " \"ampUrl\" : \"http://localhost/amp\"," 773 " \"ampUrl\" : \"http://localhost/amp\","
661 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " 774 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
662 " }]" 775 " }]"
663 "}]}"; 776 "}]}";
664 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 777 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
665 net::URLRequestStatus::SUCCESS); 778 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
666 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories; 779 RemoteSuggestionsFetcher::OptionalFetchedCategories fetched_categories;
667 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) 780 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _))
668 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); 781 .WillOnce(MoveArgument1PointeeTo(&fetched_categories));
669 782
670 RequestParams params = test_params(); 783 RequestParams params = test_params();
671 params.exclusive_category = 784 params.exclusive_category =
672 base::Optional<Category>(Category::FromRemoteCategory(2)); 785 base::Optional<Category>(Category::FromRemoteCategory(2));
673 786
674 snippets_fetcher().FetchSnippets( 787 snippets_fetcher().FetchSnippets(
675 params, ToSnippetsAvailableCallback(&mock_callback())); 788 params, ToSnippetsAvailableCallback(&mock_callback()));
676 FastForwardUntilNoTasksRemain(); 789 FastForwardUntilNoTasksRemain();
677 790
678 ASSERT_TRUE(fetched_categories); 791 ASSERT_TRUE(fetched_categories);
679 ASSERT_THAT(fetched_categories->size(), Eq(1u)); 792 ASSERT_THAT(fetched_categories->size(), Eq(1u));
680 const auto& category = (*fetched_categories)[0]; 793 const auto& category = (*fetched_categories)[0];
681 EXPECT_THAT(category.category.id(), Eq(Category::FromRemoteCategory(2).id())); 794 EXPECT_THAT(category.category.id(), Eq(Category::FromRemoteCategory(2).id()));
682 ASSERT_THAT(category.suggestions.size(), Eq(1u)); 795 ASSERT_THAT(category.suggestions.size(), Eq(1u));
683 EXPECT_THAT(category.suggestions[0]->url().spec(), 796 EXPECT_THAT(category.suggestions[0]->url().spec(),
684 Eq("http://localhost/foo2")); 797 Eq("http://localhost/foo2"));
685 } 798 }
686 799
687 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { 800 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) {
688 const std::string kJsonStr = "{\"recos\": []}"; 801 const std::string kJsonStr = "{\"recos\": []}";
689 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 802 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
690 net::URLRequestStatus::SUCCESS); 803 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
691 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); 804 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList()));
692 snippets_fetcher().FetchSnippets( 805 snippets_fetcher().FetchSnippets(
693 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 806 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
694 FastForwardUntilNoTasksRemain(); 807 FastForwardUntilNoTasksRemain();
695 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 808 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
696 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 809 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
697 EXPECT_THAT( 810 EXPECT_THAT(
698 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 811 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
699 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); 812 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
700 EXPECT_THAT(histogram_tester().GetAllSamples( 813 EXPECT_THAT(histogram_tester().GetAllSamples(
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
739 params, ToSnippetsAvailableCallback(&mock_callback())); 852 params, ToSnippetsAvailableCallback(&mock_callback()));
740 853
741 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); 854 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher();
742 ASSERT_THAT(fetcher, NotNull()); 855 ASSERT_THAT(fetcher, NotNull());
743 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(retry_config.expected_value)) 856 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(retry_config.expected_value))
744 << retry_config.description; 857 << retry_config.description;
745 } 858 }
746 } 859 }
747 860
748 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportUrlStatusError) { 861 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportUrlStatusError) {
749 SetFakeResponse(/*response_data=*/std::string(), net::HTTP_NOT_FOUND, 862 SetFakeResponse(kTestChromeContentSuggestionsUrl,
863 /*response_data=*/std::string(), net::HTTP_NOT_FOUND,
750 net::URLRequestStatus::FAILED); 864 net::URLRequestStatus::FAILED);
751 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 865 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
752 /*snippets=*/Not(HasValue()))) 866 /*snippets=*/Not(HasValue())))
753 .Times(1); 867 .Times(1);
754 snippets_fetcher().FetchSnippets( 868 snippets_fetcher().FetchSnippets(
755 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 869 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
756 FastForwardUntilNoTasksRemain(); 870 FastForwardUntilNoTasksRemain();
757 EXPECT_THAT(snippets_fetcher().last_status(), 871 EXPECT_THAT(snippets_fetcher().last_status(),
758 Eq("URLRequestStatus error -2")); 872 Eq("URLRequestStatus error -2"));
759 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty()); 873 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty());
760 EXPECT_THAT( 874 EXPECT_THAT(
761 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 875 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
762 ElementsAre(base::Bucket(/*min=*/2, /*count=*/1))); 876 ElementsAre(base::Bucket(/*min=*/2, /*count=*/1)));
763 EXPECT_THAT(histogram_tester().GetAllSamples( 877 EXPECT_THAT(histogram_tester().GetAllSamples(
764 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 878 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
765 ElementsAre(base::Bucket(/*min=*/-2, /*count=*/1))); 879 ElementsAre(base::Bucket(/*min=*/-2, /*count=*/1)));
766 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 880 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
767 Not(IsEmpty())); 881 Not(IsEmpty()));
768 } 882 }
769 883
770 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportHttpError) { 884 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportHttpError) {
771 SetFakeResponse(/*response_data=*/std::string(), net::HTTP_NOT_FOUND, 885 SetFakeResponse(kTestChromeContentSuggestionsUrl,
886 /*response_data=*/std::string(), net::HTTP_NOT_FOUND,
772 net::URLRequestStatus::SUCCESS); 887 net::URLRequestStatus::SUCCESS);
773 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 888 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
774 /*snippets=*/Not(HasValue()))) 889 /*snippets=*/Not(HasValue())))
775 .Times(1); 890 .Times(1);
776 snippets_fetcher().FetchSnippets( 891 snippets_fetcher().FetchSnippets(
777 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 892 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
778 FastForwardUntilNoTasksRemain(); 893 FastForwardUntilNoTasksRemain();
779 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty()); 894 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty());
780 EXPECT_THAT( 895 EXPECT_THAT(
781 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 896 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
782 ElementsAre(base::Bucket(/*min=*/3, /*count=*/1))); 897 ElementsAre(base::Bucket(/*min=*/3, /*count=*/1)));
783 EXPECT_THAT(histogram_tester().GetAllSamples( 898 EXPECT_THAT(histogram_tester().GetAllSamples(
784 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 899 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
785 ElementsAre(base::Bucket(/*min=*/404, /*count=*/1))); 900 ElementsAre(base::Bucket(/*min=*/404, /*count=*/1)));
786 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 901 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
787 Not(IsEmpty())); 902 Not(IsEmpty()));
788 } 903 }
789 904
790 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportJsonError) { 905 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportJsonError) {
791 const std::string kInvalidJsonStr = "{ \"recos\": []"; 906 const std::string kInvalidJsonStr = "{ \"recos\": []";
792 SetFakeResponse(/*response_data=*/kInvalidJsonStr, net::HTTP_OK, 907 SetFakeResponse(kTestChromeContentSuggestionsUrl,
908 /*response_data=*/kInvalidJsonStr, net::HTTP_OK,
793 net::URLRequestStatus::SUCCESS); 909 net::URLRequestStatus::SUCCESS);
794 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 910 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
795 /*snippets=*/Not(HasValue()))) 911 /*snippets=*/Not(HasValue())))
796 .Times(1); 912 .Times(1);
797 snippets_fetcher().FetchSnippets( 913 snippets_fetcher().FetchSnippets(
798 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 914 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
799 FastForwardUntilNoTasksRemain(); 915 FastForwardUntilNoTasksRemain();
800 EXPECT_THAT(snippets_fetcher().last_status(), 916 EXPECT_THAT(snippets_fetcher().last_status(),
801 StartsWith("Received invalid JSON (error ")); 917 StartsWith("Received invalid JSON (error "));
802 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kInvalidJsonStr)); 918 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kInvalidJsonStr));
803 EXPECT_THAT( 919 EXPECT_THAT(
804 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 920 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
805 ElementsAre(base::Bucket(/*min=*/4, /*count=*/1))); 921 ElementsAre(base::Bucket(/*min=*/4, /*count=*/1)));
806 EXPECT_THAT(histogram_tester().GetAllSamples( 922 EXPECT_THAT(histogram_tester().GetAllSamples(
807 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 923 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
808 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 924 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
809 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 925 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
810 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs, 926 ElementsAre(base::Bucket(/*min=*/kTestJsonParsingLatencyMs,
811 /*count=*/1))); 927 /*count=*/1)));
812 } 928 }
813 929
814 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportJsonErrorForEmptyResponse) { 930 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportJsonErrorForEmptyResponse) {
815 SetFakeResponse(/*response_data=*/std::string(), net::HTTP_OK, 931 SetFakeResponse(kTestChromeContentSuggestionsUrl,
932 /*response_data=*/std::string(), net::HTTP_OK,
816 net::URLRequestStatus::SUCCESS); 933 net::URLRequestStatus::SUCCESS);
817 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 934 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
818 /*snippets=*/Not(HasValue()))) 935 /*snippets=*/Not(HasValue())))
819 .Times(1); 936 .Times(1);
820 snippets_fetcher().FetchSnippets( 937 snippets_fetcher().FetchSnippets(
821 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 938 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
822 FastForwardUntilNoTasksRemain(); 939 FastForwardUntilNoTasksRemain();
823 EXPECT_THAT(snippets_fetcher().last_json(), std::string()); 940 EXPECT_THAT(snippets_fetcher().last_json(), std::string());
824 EXPECT_THAT( 941 EXPECT_THAT(
825 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 942 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
826 ElementsAre(base::Bucket(/*min=*/4, /*count=*/1))); 943 ElementsAre(base::Bucket(/*min=*/4, /*count=*/1)));
827 EXPECT_THAT(histogram_tester().GetAllSamples( 944 EXPECT_THAT(histogram_tester().GetAllSamples(
828 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 945 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
829 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 946 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
830 } 947 }
831 948
832 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportInvalidListError) { 949 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldReportInvalidListError) {
833 const std::string kJsonStr = 950 const std::string kJsonStr =
834 "{\"recos\": [{ \"contentInfo\": { \"foo\" : \"bar\" }}]}"; 951 "{\"recos\": [{ \"contentInfo\": { \"foo\" : \"bar\" }}]}";
835 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 952 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
836 net::URLRequestStatus::SUCCESS); 953 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
837 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 954 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
838 /*snippets=*/Not(HasValue()))) 955 /*snippets=*/Not(HasValue())))
839 .Times(1); 956 .Times(1);
840 snippets_fetcher().FetchSnippets( 957 snippets_fetcher().FetchSnippets(
841 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 958 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
842 FastForwardUntilNoTasksRemain(); 959 FastForwardUntilNoTasksRemain();
843 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 960 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
844 EXPECT_THAT( 961 EXPECT_THAT(
845 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 962 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
846 ElementsAre(base::Bucket(/*min=*/5, /*count=*/1))); 963 ElementsAre(base::Bucket(/*min=*/5, /*count=*/1)));
(...skipping 12 matching lines...) Expand all
859 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR), 976 EXPECT_CALL(mock_callback(), Run(HasCode(StatusCode::TEMPORARY_ERROR),
860 /*snippets=*/Not(HasValue()))) 977 /*snippets=*/Not(HasValue())))
861 .Times(1); 978 .Times(1);
862 snippets_fetcher().FetchSnippets( 979 snippets_fetcher().FetchSnippets(
863 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 980 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
864 FastForwardUntilNoTasksRemain(); 981 FastForwardUntilNoTasksRemain();
865 } 982 }
866 983
867 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldProcessConcurrentFetches) { 984 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldProcessConcurrentFetches) {
868 const std::string kJsonStr = "{ \"recos\": [] }"; 985 const std::string kJsonStr = "{ \"recos\": [] }";
869 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 986 SetFakeResponse(kTestChromeContentSuggestionsUrl, /*response_data=*/kJsonStr,
870 net::URLRequestStatus::SUCCESS); 987 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
871 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())).Times(5); 988 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())).Times(5);
872 snippets_fetcher().FetchSnippets( 989 snippets_fetcher().FetchSnippets(
873 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 990 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
874 // More calls to FetchSnippets() do not interrupt the previous. 991 // More calls to FetchSnippets() do not interrupt the previous.
875 // Callback is expected to be called once each time. 992 // Callback is expected to be called once each time.
876 snippets_fetcher().FetchSnippets( 993 snippets_fetcher().FetchSnippets(
877 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 994 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
878 snippets_fetcher().FetchSnippets( 995 snippets_fetcher().FetchSnippets(
879 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 996 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
880 snippets_fetcher().FetchSnippets( 997 snippets_fetcher().FetchSnippets(
(...skipping 18 matching lines...) Expand all
899 fetched_categories) { 1016 fetched_categories) {
900 if (fetched_categories) { 1017 if (fetched_categories) {
901 // Matchers above aren't any more precise than this, so this is sufficient 1018 // Matchers above aren't any more precise than this, so this is sufficient
902 // for test-failure diagnostics. 1019 // for test-failure diagnostics.
903 return os << "list with " << fetched_categories->size() << " elements"; 1020 return os << "list with " << fetched_categories->size() << " elements";
904 } 1021 }
905 return os << "null"; 1022 return os << "null";
906 } 1023 }
907 1024
908 } // namespace ntp_snippets 1025 } // namespace ntp_snippets
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698