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

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

Issue 2557363002: [NTP Snippets] Refactor background scheduling for remote suggestions (Closed)
Patch Set: Tim's comments + fix ios compilation Created 3 years, 12 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
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 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_provider.h" 5 #include "components/ntp_snippets/remote/remote_suggestions_provider_impl.h"
6 6
7 #include <memory> 7 #include <memory>
8 #include <utility> 8 #include <utility>
9 #include <vector> 9 #include <vector>
10 10
11 #include "base/command_line.h" 11 #include "base/command_line.h"
12 #include "base/files/file_path.h" 12 #include "base/files/file_path.h"
13 #include "base/files/scoped_temp_dir.h" 13 #include "base/files/scoped_temp_dir.h"
14 #include "base/json/json_reader.h" 14 #include "base/json/json_reader.h"
15 #include "base/macros.h" 15 #include "base/macros.h"
(...skipping 12 matching lines...) Expand all
28 #include "components/image_fetcher/image_fetcher_delegate.h" 28 #include "components/image_fetcher/image_fetcher_delegate.h"
29 #include "components/ntp_snippets/category.h" 29 #include "components/ntp_snippets/category.h"
30 #include "components/ntp_snippets/category_info.h" 30 #include "components/ntp_snippets/category_info.h"
31 #include "components/ntp_snippets/category_rankers/category_ranker.h" 31 #include "components/ntp_snippets/category_rankers/category_ranker.h"
32 #include "components/ntp_snippets/category_rankers/constant_category_ranker.h" 32 #include "components/ntp_snippets/category_rankers/constant_category_ranker.h"
33 #include "components/ntp_snippets/category_rankers/mock_category_ranker.h" 33 #include "components/ntp_snippets/category_rankers/mock_category_ranker.h"
34 #include "components/ntp_snippets/ntp_snippets_constants.h" 34 #include "components/ntp_snippets/ntp_snippets_constants.h"
35 #include "components/ntp_snippets/pref_names.h" 35 #include "components/ntp_snippets/pref_names.h"
36 #include "components/ntp_snippets/remote/ntp_snippet.h" 36 #include "components/ntp_snippets/remote/ntp_snippet.h"
37 #include "components/ntp_snippets/remote/ntp_snippets_fetcher.h" 37 #include "components/ntp_snippets/remote/ntp_snippets_fetcher.h"
38 #include "components/ntp_snippets/remote/ntp_snippets_scheduler.h" 38 #include "components/ntp_snippets/remote/persistent_scheduler.h"
39 #include "components/ntp_snippets/remote/remote_suggestions_database.h" 39 #include "components/ntp_snippets/remote/remote_suggestions_database.h"
40 #include "components/ntp_snippets/remote/test_utils.h" 40 #include "components/ntp_snippets/remote/test_utils.h"
41 #include "components/ntp_snippets/user_classifier.h" 41 #include "components/ntp_snippets/user_classifier.h"
42 #include "components/prefs/testing_pref_service.h" 42 #include "components/prefs/testing_pref_service.h"
43 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" 43 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
44 #include "components/signin/core/browser/fake_signin_manager.h" 44 #include "components/signin/core/browser/fake_signin_manager.h"
45 #include "components/variations/variations_params_manager.h" 45 #include "components/variations/variations_params_manager.h"
46 #include "net/url_request/test_url_fetcher_factory.h" 46 #include "net/url_request/test_url_fetcher_factory.h"
47 #include "net/url_request/url_request_test_util.h" 47 #include "net/url_request/url_request_test_util.h"
48 #include "testing/gmock/include/gmock/gmock.h" 48 #include "testing/gmock/include/gmock/gmock.h"
49 #include "testing/gtest/include/gtest/gtest.h" 49 #include "testing/gtest/include/gtest/gtest.h"
50 #include "ui/gfx/image/image.h" 50 #include "ui/gfx/image/image.h"
51 #include "ui/gfx/image/image_unittest_util.h" 51 #include "ui/gfx/image/image_unittest_util.h"
52 52
53 using image_fetcher::ImageFetcher; 53 using image_fetcher::ImageFetcher;
54 using image_fetcher::ImageFetcherDelegate; 54 using image_fetcher::ImageFetcherDelegate;
55 using testing::_; 55 using testing::_;
56 using testing::ElementsAre; 56 using testing::ElementsAre;
57 using testing::Eq; 57 using testing::Eq;
58 using testing::InSequence; 58 using testing::InSequence;
59 using testing::Invoke; 59 using testing::Invoke;
60 using testing::IsEmpty; 60 using testing::IsEmpty;
61 using testing::Mock; 61 using testing::Mock;
62 using testing::MockFunction; 62 using testing::MockFunction;
63 using testing::NiceMock; 63 using testing::NiceMock;
64 using testing::Not; 64 using testing::Not;
65 using testing::SaveArg; 65 using testing::SaveArg;
66 using testing::SizeIs; 66 using testing::SizeIs;
67 using testing::StartsWith; 67 using testing::StartsWith;
68 using testing::StrictMock;
68 using testing::WithArgs; 69 using testing::WithArgs;
69 70
70 namespace ntp_snippets { 71 namespace ntp_snippets {
71 72
72 namespace { 73 namespace {
73 74
74 MATCHER_P(IdEq, value, "") { 75 MATCHER_P(IdEq, value, "") {
75 return arg->id() == value; 76 return arg->id() == value;
76 } 77 }
77 78
(...skipping 204 matching lines...) Expand 10 before | Expand all | Expand 10 after
282 283
283 void ServeOneByOneImage( 284 void ServeOneByOneImage(
284 image_fetcher::ImageFetcherDelegate* notify, 285 image_fetcher::ImageFetcherDelegate* notify,
285 const std::string& id, 286 const std::string& id,
286 base::Callback<void(const std::string&, const gfx::Image&)> callback) { 287 base::Callback<void(const std::string&, const gfx::Image&)> callback) {
287 base::ThreadTaskRunnerHandle::Get()->PostTask( 288 base::ThreadTaskRunnerHandle::Get()->PostTask(
288 FROM_HERE, base::Bind(callback, id, gfx::test::CreateImage(1, 1))); 289 FROM_HERE, base::Bind(callback, id, gfx::test::CreateImage(1, 1)));
289 notify->OnImageDataFetched(id, "1-by-1-image-data"); 290 notify->OnImageDataFetched(id, "1-by-1-image-data");
290 } 291 }
291 292
292 gfx::Image FetchImage(RemoteSuggestionsProvider* service, 293 gfx::Image FetchImage(RemoteSuggestionsProviderImpl* service,
293 const ContentSuggestion::ID& suggestion_id) { 294 const ContentSuggestion::ID& suggestion_id) {
294 gfx::Image result; 295 gfx::Image result;
295 base::RunLoop run_loop; 296 base::RunLoop run_loop;
296 service->FetchSuggestionImage(suggestion_id, 297 service->FetchSuggestionImage(suggestion_id,
297 base::Bind( 298 base::Bind(
298 [](base::Closure signal, gfx::Image* output, 299 [](base::Closure signal, gfx::Image* output,
299 const gfx::Image& loaded) { 300 const gfx::Image& loaded) {
300 *output = loaded; 301 *output = loaded;
301 signal.Run(); 302 signal.Run();
302 }, 303 },
(...skipping 21 matching lines...) Expand all
324 int id, 325 int id,
325 const GURL& url, 326 const GURL& url,
326 net::URLFetcher::RequestType request_type, 327 net::URLFetcher::RequestType request_type,
327 net::URLFetcherDelegate* d) override { 328 net::URLFetcherDelegate* d) override {
328 return base::MakeUnique<net::FakeURLFetcher>( 329 return base::MakeUnique<net::FakeURLFetcher>(
329 url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND, 330 url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND,
330 net::URLRequestStatus::FAILED); 331 net::URLRequestStatus::FAILED);
331 } 332 }
332 }; 333 };
333 334
334 class MockScheduler : public NTPSnippetsScheduler {
335 public:
336 MOCK_METHOD2(Schedule,
337 bool(base::TimeDelta period_wifi,
338 base::TimeDelta period_fallback));
339 MOCK_METHOD0(Unschedule, bool());
340 };
341
342 class MockImageFetcher : public ImageFetcher { 335 class MockImageFetcher : public ImageFetcher {
343 public: 336 public:
344 MOCK_METHOD1(SetImageFetcherDelegate, void(ImageFetcherDelegate*)); 337 MOCK_METHOD1(SetImageFetcherDelegate, void(ImageFetcherDelegate*));
345 MOCK_METHOD1(SetDataUseServiceName, void(DataUseServiceName)); 338 MOCK_METHOD1(SetDataUseServiceName, void(DataUseServiceName));
346 MOCK_METHOD3( 339 MOCK_METHOD3(
347 StartOrQueueNetworkRequest, 340 StartOrQueueNetworkRequest,
348 void(const std::string&, 341 void(const std::string&,
349 const GURL&, 342 const GURL&,
350 base::Callback<void(const std::string&, const gfx::Image&)>)); 343 base::Callback<void(const std::string&, const gfx::Image&)>));
351 }; 344 };
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
408 } 401 }
409 402
410 void SetDecodedImage(const gfx::Image& image) { decoded_image_ = image; } 403 void SetDecodedImage(const gfx::Image& image) { decoded_image_ = image; }
411 404
412 private: 405 private:
413 gfx::Image decoded_image_; 406 gfx::Image decoded_image_;
414 }; 407 };
415 408
416 } // namespace 409 } // namespace
417 410
418 class RemoteSuggestionsProviderTest : public ::testing::Test { 411 class RemoteSuggestionsProviderImplTest : public ::testing::Test {
419 public: 412 public:
420 RemoteSuggestionsProviderTest() 413 RemoteSuggestionsProviderImplTest()
421 : params_manager_(ntp_snippets::kStudyName, 414 : params_manager_(ntp_snippets::kStudyName,
422 {{"content_suggestions_backend", 415 {{"content_suggestions_backend",
423 kTestContentSuggestionsServerEndpoint}, 416 kTestContentSuggestionsServerEndpoint},
424 {"fetching_personalization", "non_personal"}}), 417 {"fetching_personalization", "non_personal"}}),
425 fake_url_fetcher_factory_( 418 fake_url_fetcher_factory_(
426 /*default_factory=*/&failing_url_fetcher_factory_), 419 /*default_factory=*/&failing_url_fetcher_factory_),
427 test_url_(kTestContentSuggestionsServerWithAPIKey), 420 test_url_(kTestContentSuggestionsServerWithAPIKey),
428 category_ranker_(base::MakeUnique<ConstantCategoryRanker>()), 421 category_ranker_(base::MakeUnique<ConstantCategoryRanker>()),
429 user_classifier_(/*pref_service=*/nullptr), 422 user_classifier_(/*pref_service=*/nullptr),
430 image_fetcher_(nullptr), 423 image_fetcher_(nullptr),
431 image_decoder_(nullptr), 424 image_decoder_(nullptr),
432 database_(nullptr) { 425 database_(nullptr) {
433 RemoteSuggestionsProvider::RegisterProfilePrefs( 426 RemoteSuggestionsProviderImpl::RegisterProfilePrefs(
434 utils_.pref_service()->registry()); 427 utils_.pref_service()->registry());
435 RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry()); 428 RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry());
436 429
437 EXPECT_TRUE(database_dir_.CreateUniqueTempDir()); 430 EXPECT_TRUE(database_dir_.CreateUniqueTempDir());
438 } 431 }
439 432
440 ~RemoteSuggestionsProviderTest() override { 433 ~RemoteSuggestionsProviderImplTest() override {
441 // We need to run the message loop after deleting the database, because 434 // We need to run the message loop after deleting the database, because
442 // ProtoDatabaseImpl deletes the actual LevelDB asynchronously on the task 435 // ProtoDatabaseImpl deletes the actual LevelDB asynchronously on the task
443 // runner. Without this, we'd get reports of memory leaks. 436 // runner. Without this, we'd get reports of memory leaks.
444 base::RunLoop().RunUntilIdle(); 437 base::RunLoop().RunUntilIdle();
445 } 438 }
446 439
447 // TODO(vitaliii): Rewrite this function to initialize a test class member 440 // TODO(vitaliii): Rewrite this function to initialize a test class member
448 // instead of creating a new service. 441 // instead of creating a new service.
449 std::unique_ptr<RemoteSuggestionsProvider> MakeSnippetsService( 442 std::unique_ptr<RemoteSuggestionsProviderImpl> MakeSnippetsService(
450 bool set_empty_response = true) { 443 bool set_empty_response = true) {
451 auto service = MakeSnippetsServiceWithoutInitialization(); 444 auto service = MakeSnippetsServiceWithoutInitialization();
452 WaitForSnippetsServiceInitialization(service.get(), set_empty_response); 445 WaitForSnippetsServiceInitialization(service.get(), set_empty_response);
453 return service; 446 return service;
454 } 447 }
455 448
456 std::unique_ptr<RemoteSuggestionsProvider> 449 std::unique_ptr<RemoteSuggestionsProviderImpl>
457 MakeSnippetsServiceWithoutInitialization() { 450 MakeSnippetsServiceWithoutInitialization() {
458 scoped_refptr<base::SingleThreadTaskRunner> task_runner( 451 scoped_refptr<base::SingleThreadTaskRunner> task_runner(
459 base::ThreadTaskRunnerHandle::Get()); 452 base::ThreadTaskRunnerHandle::Get());
460 scoped_refptr<net::TestURLRequestContextGetter> request_context_getter = 453 scoped_refptr<net::TestURLRequestContextGetter> request_context_getter =
461 new net::TestURLRequestContextGetter(task_runner.get()); 454 new net::TestURLRequestContextGetter(task_runner.get());
462 455
463 utils_.ResetSigninManager(); 456 utils_.ResetSigninManager();
464 std::unique_ptr<NTPSnippetsFetcher> snippets_fetcher = 457 std::unique_ptr<NTPSnippetsFetcher> snippets_fetcher =
465 base::MakeUnique<NTPSnippetsFetcher>( 458 base::MakeUnique<NTPSnippetsFetcher>(
466 utils_.fake_signin_manager(), fake_token_service_.get(), 459 utils_.fake_signin_manager(), fake_token_service_.get(),
467 std::move(request_context_getter), utils_.pref_service(), nullptr, 460 std::move(request_context_getter), utils_.pref_service(), nullptr,
468 base::Bind(&ParseJson), kAPIKey, &user_classifier_); 461 base::Bind(&ParseJson), kAPIKey, &user_classifier_);
469 462
470 utils_.fake_signin_manager()->SignIn("foo@bar.com"); 463 utils_.fake_signin_manager()->SignIn("foo@bar.com");
471 464
472 auto image_fetcher = base::MakeUnique<NiceMock<MockImageFetcher>>(); 465 auto image_fetcher = base::MakeUnique<NiceMock<MockImageFetcher>>();
473 466
474 image_fetcher_ = image_fetcher.get(); 467 image_fetcher_ = image_fetcher.get();
475 EXPECT_CALL(*image_fetcher, SetImageFetcherDelegate(_)); 468 EXPECT_CALL(*image_fetcher, SetImageFetcherDelegate(_));
476 auto image_decoder = base::MakeUnique<FakeImageDecoder>(); 469 auto image_decoder = base::MakeUnique<FakeImageDecoder>();
477 image_decoder_ = image_decoder.get(); 470 image_decoder_ = image_decoder.get();
478 EXPECT_FALSE(observer_); 471 EXPECT_FALSE(observer_);
479 observer_ = base::MakeUnique<FakeContentSuggestionsProviderObserver>(); 472 observer_ = base::MakeUnique<FakeContentSuggestionsProviderObserver>();
480 auto database = base::MakeUnique<RemoteSuggestionsDatabase>( 473 auto database = base::MakeUnique<RemoteSuggestionsDatabase>(
481 database_dir_.GetPath(), task_runner); 474 database_dir_.GetPath(), task_runner);
482 database_ = database.get(); 475 database_ = database.get();
483 return base::MakeUnique<RemoteSuggestionsProvider>( 476 return base::MakeUnique<RemoteSuggestionsProviderImpl>(
484 observer_.get(), utils_.pref_service(), "fr", category_ranker_.get(), 477 observer_.get(), utils_.pref_service(), "fr", category_ranker_.get(),
485 &user_classifier_, &scheduler_, std::move(snippets_fetcher), 478 std::move(snippets_fetcher), std::move(image_fetcher),
486 std::move(image_fetcher), std::move(image_decoder), std::move(database), 479 std::move(image_decoder), std::move(database),
487 base::MakeUnique<RemoteSuggestionsStatusService>( 480 base::MakeUnique<RemoteSuggestionsStatusService>(
488 utils_.fake_signin_manager(), utils_.pref_service())); 481 utils_.fake_signin_manager(), utils_.pref_service()));
489 } 482 }
490 483
491 void WaitForSnippetsServiceInitialization(RemoteSuggestionsProvider* service, 484 void WaitForSnippetsServiceInitialization(
492 bool set_empty_response) { 485 RemoteSuggestionsProviderImpl* service,
493 EXPECT_EQ(RemoteSuggestionsProvider::State::NOT_INITED, service->state_); 486 bool set_empty_response) {
487 EXPECT_EQ(RemoteSuggestionsProviderImpl::State::NOT_INITED,
488 service->state_);
494 489
495 // Add an initial fetch response, as the service tries to fetch when there 490 // Add an initial fetch response, as the service tries to fetch when there
496 // is nothing in the DB. 491 // is nothing in the DB.
497 if (set_empty_response) { 492 if (set_empty_response) {
498 SetUpFetchResponse(GetTestJson(std::vector<std::string>())); 493 SetUpFetchResponse(GetTestJson(std::vector<std::string>()));
499 } 494 }
500 495
501 // TODO(treib): Find a better way to wait for initialization to finish. 496 // TODO(treib): Find a better way to wait for initialization to finish.
502 base::RunLoop().RunUntilIdle(); 497 base::RunLoop().RunUntilIdle();
503 EXPECT_NE(RemoteSuggestionsProvider::State::NOT_INITED, service->state_); 498 EXPECT_NE(RemoteSuggestionsProviderImpl::State::NOT_INITED,
499 service->state_);
504 } 500 }
505 501
506 void ResetSnippetsService(std::unique_ptr<RemoteSuggestionsProvider>* service, 502 void ResetSnippetsService(
507 bool set_empty_response) { 503 std::unique_ptr<RemoteSuggestionsProviderImpl>* service,
504 bool set_empty_response) {
508 service->reset(); 505 service->reset();
509 observer_.reset(); 506 observer_.reset();
510 *service = MakeSnippetsService(set_empty_response); 507 *service = MakeSnippetsService(set_empty_response);
511 } 508 }
512 509
513 void SetCategoryRanker(std::unique_ptr<CategoryRanker> category_ranker) { 510 void SetCategoryRanker(std::unique_ptr<CategoryRanker> category_ranker) {
514 category_ranker_ = std::move(category_ranker); 511 category_ranker_ = std::move(category_ranker);
515 } 512 }
516 513
517 ContentSuggestion::ID MakeArticleID(const std::string& id_within_category) { 514 ContentSuggestion::ID MakeArticleID(const std::string& id_within_category) {
(...skipping 12 matching lines...) Expand all
530 // unknown_category() helpers -- tests can just define their own. 527 // unknown_category() helpers -- tests can just define their own.
531 Category other_category() { return Category::FromRemoteCategory(2); } 528 Category other_category() { return Category::FromRemoteCategory(2); }
532 529
533 Category unknown_category() { 530 Category unknown_category() {
534 return Category::FromRemoteCategory(kUnknownRemoteCategoryId); 531 return Category::FromRemoteCategory(kUnknownRemoteCategoryId);
535 } 532 }
536 533
537 protected: 534 protected:
538 const GURL& test_url() { return test_url_; } 535 const GURL& test_url() { return test_url_; }
539 FakeContentSuggestionsProviderObserver& observer() { return *observer_; } 536 FakeContentSuggestionsProviderObserver& observer() { return *observer_; }
540 MockScheduler& mock_scheduler() { return scheduler_; }
541 // TODO(tschumann): Make this a strict-mock. We want to avoid unneccesary 537 // TODO(tschumann): Make this a strict-mock. We want to avoid unneccesary
542 // network requests. 538 // network requests.
543 NiceMock<MockImageFetcher>* image_fetcher() { return image_fetcher_; } 539 NiceMock<MockImageFetcher>* image_fetcher() { return image_fetcher_; }
544 FakeImageDecoder* image_decoder() { return image_decoder_; } 540 FakeImageDecoder* image_decoder() { return image_decoder_; }
545 PrefService* pref_service() { return utils_.pref_service(); } 541 PrefService* pref_service() { return utils_.pref_service(); }
546 RemoteSuggestionsDatabase* database() { return database_; } 542 RemoteSuggestionsDatabase* database() { return database_; }
547 543
548 // Provide the json to be returned by the fake fetcher. 544 // Provide the json to be returned by the fake fetcher.
549 void SetUpFetchResponse(const std::string& json) { 545 void SetUpFetchResponse(const std::string& json) {
550 fake_url_fetcher_factory_.SetFakeResponse(test_url_, json, net::HTTP_OK, 546 fake_url_fetcher_factory_.SetFakeResponse(test_url_, json, net::HTTP_OK,
551 net::URLRequestStatus::SUCCESS); 547 net::URLRequestStatus::SUCCESS);
552 } 548 }
553 549
554 // Have the fake fetcher fail due to a HTTP error like a 404. 550 // Have the fake fetcher fail due to a HTTP error like a 404.
555 void SetUpHttpError() { 551 void SetUpHttpError() {
556 fake_url_fetcher_factory_.SetFakeResponse(test_url_, /*json=*/std::string(), 552 fake_url_fetcher_factory_.SetFakeResponse(test_url_, /*json=*/std::string(),
557 net::HTTP_NOT_FOUND, 553 net::HTTP_NOT_FOUND,
558 net::URLRequestStatus::SUCCESS); 554 net::URLRequestStatus::SUCCESS);
559 } 555 }
560 556
561 void LoadFromJSONString(RemoteSuggestionsProvider* service, 557 void LoadFromJSONString(RemoteSuggestionsProviderImpl* service,
562 const std::string& json) { 558 const std::string& json) {
563 SetUpFetchResponse(json); 559 SetUpFetchResponse(json);
564 service->FetchSnippets(true); 560 service->FetchSnippets(
561 true, std::unique_ptr<RemoteSuggestionsProvider::FetchStatusCallback>(
562 nullptr));
565 base::RunLoop().RunUntilIdle(); 563 base::RunLoop().RunUntilIdle();
566 } 564 }
567 565
568 void LoadMoreFromJSONString(RemoteSuggestionsProvider* service, 566 void LoadMoreFromJSONString(RemoteSuggestionsProviderImpl* service,
569 const Category& category, 567 const Category& category,
570 const std::string& json, 568 const std::string& json,
571 const std::set<std::string>& known_ids, 569 const std::set<std::string>& known_ids,
572 FetchDoneCallback callback) { 570 FetchDoneCallback callback) {
573 SetUpFetchResponse(json); 571 SetUpFetchResponse(json);
574 service->Fetch(category, known_ids, callback); 572 service->Fetch(category, known_ids, callback);
575 base::RunLoop().RunUntilIdle(); 573 base::RunLoop().RunUntilIdle();
576 } 574 }
577 575
578 private: 576 private:
579 variations::testing::VariationParamsManager params_manager_; 577 variations::testing::VariationParamsManager params_manager_;
580 test::RemoteSuggestionsTestUtils utils_; 578 test::RemoteSuggestionsTestUtils utils_;
581 base::MessageLoop message_loop_; 579 base::MessageLoop message_loop_;
582 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; 580 FailingFakeURLFetcherFactory failing_url_fetcher_factory_;
583 // Instantiation of factory automatically sets itself as URLFetcher's factory. 581 // Instantiation of factory automatically sets itself as URLFetcher's factory.
584 net::FakeURLFetcherFactory fake_url_fetcher_factory_; 582 net::FakeURLFetcherFactory fake_url_fetcher_factory_;
585 const GURL test_url_; 583 const GURL test_url_;
586 std::unique_ptr<OAuth2TokenService> fake_token_service_; 584 std::unique_ptr<OAuth2TokenService> fake_token_service_;
587 std::unique_ptr<CategoryRanker> category_ranker_; 585 std::unique_ptr<CategoryRanker> category_ranker_;
588 UserClassifier user_classifier_; 586 UserClassifier user_classifier_;
589 NiceMock<MockScheduler> scheduler_;
590 std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_; 587 std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_;
591 NiceMock<MockImageFetcher>* image_fetcher_; 588 NiceMock<MockImageFetcher>* image_fetcher_;
592 FakeImageDecoder* image_decoder_; 589 FakeImageDecoder* image_decoder_;
593 590
594 base::ScopedTempDir database_dir_; 591 base::ScopedTempDir database_dir_;
595 RemoteSuggestionsDatabase* database_; 592 RemoteSuggestionsDatabase* database_;
596 593
597 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsProviderTest); 594 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsProviderImplTest);
598 }; 595 };
599 596
600 TEST_F(RemoteSuggestionsProviderTest, ScheduleOnStart) { 597 TEST_F(RemoteSuggestionsProviderImplTest, Full) {
601 // We should get two |Schedule| calls: The first when initialization
602 // completes, the second one after the automatic (since the service doesn't
603 // have any data yet) fetch finishes.
604 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
605 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(0);
606 auto service = MakeSnippetsService();
607
608 // When we have no snippets are all, loading the service initiates a fetch.
609 EXPECT_EQ("OK", service->snippets_fetcher()->last_status());
610 }
611
612 TEST_F(RemoteSuggestionsProviderTest, DontRescheduleOnStart) {
613 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
614 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(0);
615 SetUpFetchResponse(GetTestJson({GetSnippet()}));
616 auto service = MakeSnippetsService(/*set_empty_response=*/false);
617
618 // When recreating the service, we should not get any |Schedule| calls:
619 // The tasks are already scheduled with the correct intervals, so nothing on
620 // initialization, and the service has data from the DB, so no automatic fetch
621 // should happen.
622 Mock::VerifyAndClearExpectations(&mock_scheduler());
623 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(0);
624 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(0);
625 ResetSnippetsService(&service, /*set_empty_response=*/true);
626 }
627
628 TEST_F(RemoteSuggestionsProviderTest, RescheduleAfterSuccessfulFetch) {
629 // We should get two |Schedule| calls: The first when initialization
630 // completes, the second one after the automatic (since the service doesn't
631 // have any data yet) fetch finishes.
632 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
633 auto service = MakeSnippetsService();
634
635 // A successful fetch should trigger another |Schedule|.
636 EXPECT_CALL(mock_scheduler(), Schedule(_, _));
637 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
638 }
639
640 TEST_F(RemoteSuggestionsProviderTest, DontRescheduleAfterFailedFetch) {
641 // We should get two |Schedule| calls: The first when initialization
642 // completes, the second one after the automatic (since the service doesn't
643 // have any data yet) fetch finishes.
644 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
645 auto service = MakeSnippetsService();
646
647 // A failed fetch should NOT trigger another |Schedule|.
648 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(0);
649 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
650 }
651
652 TEST_F(RemoteSuggestionsProviderTest, IgnoreRescheduleBeforeInit) {
653 // We should get two |Schedule| calls: The first when initialization
654 // completes, the second one after the automatic (since the service doesn't
655 // have any data yet) fetch finishes.
656 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
657 // The |RescheduleFetching| call shouldn't do anything (in particular not
658 // result in an |Unschedule|), since the service isn't initialized yet.
659 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(0);
660 auto service = MakeSnippetsServiceWithoutInitialization();
661 service->RescheduleFetching(false);
662 WaitForSnippetsServiceInitialization(service.get(),
663 /*set_empty_response=*/true);
664 }
665
666 TEST_F(RemoteSuggestionsProviderTest, HandleForcedRescheduleBeforeInit) {
667 {
668 InSequence s;
669 // The |RescheduleFetching| call with force=true should result in an
670 // |Unschedule|, since the service isn't initialized yet.
671 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(1);
672 // We should get two |Schedule| calls: The first when initialization
673 // completes, the second one after the automatic (since the service doesn't
674 // have any data yet) fetch finishes.
675 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
676 }
677 auto service = MakeSnippetsServiceWithoutInitialization();
678 service->RescheduleFetching(true);
679 WaitForSnippetsServiceInitialization(service.get(),
680 /*set_empty_response=*/true);
681 }
682
683 TEST_F(RemoteSuggestionsProviderTest, RescheduleOnStateChange) {
684 {
685 InSequence s;
686 // Initial startup.
687 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
688 // Service gets disabled.
689 EXPECT_CALL(mock_scheduler(), Unschedule());
690 // Service gets enabled again.
691 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
692 }
693 auto service = MakeSnippetsService();
694 ASSERT_TRUE(service->ready());
695
696 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
697 RemoteSuggestionsStatus::EXPLICITLY_DISABLED);
698 ASSERT_FALSE(service->ready());
699 base::RunLoop().RunUntilIdle();
700
701 service->OnStatusChanged(RemoteSuggestionsStatus::EXPLICITLY_DISABLED,
702 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT);
703 ASSERT_TRUE(service->ready());
704 base::RunLoop().RunUntilIdle();
705 }
706
707 TEST_F(RemoteSuggestionsProviderTest, DontUnscheduleOnShutdown) {
708 EXPECT_CALL(mock_scheduler(), Schedule(_, _)).Times(2);
709 EXPECT_CALL(mock_scheduler(), Unschedule()).Times(0);
710
711 auto service = MakeSnippetsService();
712
713 service.reset();
714 base::RunLoop().RunUntilIdle();
715 }
716
717 TEST_F(RemoteSuggestionsProviderTest, Full) {
718 std::string json_str(GetTestJson({GetSnippet()})); 598 std::string json_str(GetTestJson({GetSnippet()}));
719 599
720 auto service = MakeSnippetsService(); 600 auto service = MakeSnippetsService();
721 601
722 LoadFromJSONString(service.get(), json_str); 602 LoadFromJSONString(service.get(), json_str);
723 603
724 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 604 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
725 SizeIs(1)); 605 SizeIs(1));
726 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 606 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
727 607
728 const ContentSuggestion& suggestion = 608 const ContentSuggestion& suggestion =
729 observer().SuggestionsForCategory(articles_category()).front(); 609 observer().SuggestionsForCategory(articles_category()).front();
730 610
731 EXPECT_EQ(MakeArticleID(kSnippetUrl), suggestion.id()); 611 EXPECT_EQ(MakeArticleID(kSnippetUrl), suggestion.id());
732 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); 612 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title()));
733 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); 613 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text()));
734 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); 614 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
735 EXPECT_EQ(kSnippetPublisherName, 615 EXPECT_EQ(kSnippetPublisherName,
736 base::UTF16ToUTF8(suggestion.publisher_name())); 616 base::UTF16ToUTF8(suggestion.publisher_name()));
737 } 617 }
738 618
739 TEST_F(RemoteSuggestionsProviderTest, CategoryTitle) { 619 TEST_F(RemoteSuggestionsProviderImplTest, CategoryTitle) {
740 const base::string16 test_default_title = 620 const base::string16 test_default_title =
741 base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle); 621 base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle);
742 622
743 // Don't send an initial response -- we want to test what happens without any 623 // Don't send an initial response -- we want to test what happens without any
744 // server status. 624 // server status.
745 auto service = MakeSnippetsService(/*set_empty_response=*/false); 625 auto service = MakeSnippetsService(/*set_empty_response=*/false);
746 626
747 // The articles category should be there by default, and have a title. 627 // The articles category should be there by default, and have a title.
748 CategoryInfo info_before = service->GetCategoryInfo(articles_category()); 628 CategoryInfo info_before = service->GetCategoryInfo(articles_category());
749 ASSERT_THAT(info_before.title(), Not(IsEmpty())); 629 ASSERT_THAT(info_before.title(), Not(IsEmpty()));
(...skipping 14 matching lines...) Expand all
764 // Make sure we updated the title in the CategoryInfo. 644 // Make sure we updated the title in the CategoryInfo.
765 CategoryInfo info_with_title = service->GetCategoryInfo(articles_category()); 645 CategoryInfo info_with_title = service->GetCategoryInfo(articles_category());
766 EXPECT_THAT(info_before.title(), Not(Eq(info_with_title.title()))); 646 EXPECT_THAT(info_before.title(), Not(Eq(info_with_title.title())));
767 EXPECT_THAT(test_default_title, Eq(info_with_title.title())); 647 EXPECT_THAT(test_default_title, Eq(info_with_title.title()));
768 EXPECT_THAT(info_before.has_more_action(), Eq(true)); 648 EXPECT_THAT(info_before.has_more_action(), Eq(true));
769 EXPECT_THAT(info_before.has_reload_action(), Eq(true)); 649 EXPECT_THAT(info_before.has_reload_action(), Eq(true));
770 EXPECT_THAT(info_before.has_view_all_action(), Eq(false)); 650 EXPECT_THAT(info_before.has_view_all_action(), Eq(false));
771 EXPECT_THAT(info_before.show_if_empty(), Eq(true)); 651 EXPECT_THAT(info_before.show_if_empty(), Eq(true));
772 } 652 }
773 653
774 TEST_F(RemoteSuggestionsProviderTest, MultipleCategories) { 654 TEST_F(RemoteSuggestionsProviderImplTest, MultipleCategories) {
775 auto service = MakeSnippetsService(); 655 auto service = MakeSnippetsService();
776 std::string json_str = 656 std::string json_str =
777 MultiCategoryJsonBuilder() 657 MultiCategoryJsonBuilder()
778 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 658 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
779 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2) 659 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2)
780 .Build(); 660 .Build();
781 LoadFromJSONString(service.get(), json_str); 661 LoadFromJSONString(service.get(), json_str);
782 662
783 ASSERT_THAT(observer().statuses(), 663 ASSERT_THAT(observer().statuses(),
784 Eq(std::map<Category, CategoryStatus, Category::CompareByID>{ 664 Eq(std::map<Category, CategoryStatus, Category::CompareByID>{
(...skipping 25 matching lines...) Expand all
810 observer().SuggestionsForCategory(other_category()).front(); 690 observer().SuggestionsForCategory(other_category()).front();
811 EXPECT_EQ(MakeOtherID(std::string(kSnippetUrl) + "/1"), suggestion.id()); 691 EXPECT_EQ(MakeOtherID(std::string(kSnippetUrl) + "/1"), suggestion.id());
812 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); 692 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title()));
813 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); 693 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text()));
814 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); 694 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
815 EXPECT_EQ(kSnippetPublisherName, 695 EXPECT_EQ(kSnippetPublisherName,
816 base::UTF16ToUTF8(suggestion.publisher_name())); 696 base::UTF16ToUTF8(suggestion.publisher_name()));
817 } 697 }
818 } 698 }
819 699
820 TEST_F(RemoteSuggestionsProviderTest, ArticleCategoryInfo) { 700 TEST_F(RemoteSuggestionsProviderImplTest, ArticleCategoryInfo) {
821 auto service = MakeSnippetsService(); 701 auto service = MakeSnippetsService();
822 CategoryInfo article_info = service->GetCategoryInfo(articles_category()); 702 CategoryInfo article_info = service->GetCategoryInfo(articles_category());
823 EXPECT_THAT(article_info.has_more_action(), Eq(true)); 703 EXPECT_THAT(article_info.has_more_action(), Eq(true));
824 EXPECT_THAT(article_info.has_reload_action(), Eq(true)); 704 EXPECT_THAT(article_info.has_reload_action(), Eq(true));
825 EXPECT_THAT(article_info.has_view_all_action(), Eq(false)); 705 EXPECT_THAT(article_info.has_view_all_action(), Eq(false));
826 EXPECT_THAT(article_info.show_if_empty(), Eq(true)); 706 EXPECT_THAT(article_info.show_if_empty(), Eq(true));
827 } 707 }
828 708
829 TEST_F(RemoteSuggestionsProviderTest, ExperimentalCategoryInfo) { 709 TEST_F(RemoteSuggestionsProviderImplTest, ExperimentalCategoryInfo) {
830 auto service = MakeSnippetsService(); 710 auto service = MakeSnippetsService();
831 std::string json_str = 711 std::string json_str =
832 MultiCategoryJsonBuilder() 712 MultiCategoryJsonBuilder()
833 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 713 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
834 .AddCategory({GetSnippetN(1)}, kUnknownRemoteCategoryId) 714 .AddCategory({GetSnippetN(1)}, kUnknownRemoteCategoryId)
835 .Build(); 715 .Build();
836 // Load data with multiple categories so that a new experimental category gets 716 // Load data with multiple categories so that a new experimental category gets
837 // registered. 717 // registered.
838 LoadFromJSONString(service.get(), json_str); 718 LoadFromJSONString(service.get(), json_str);
839 719
840 CategoryInfo info = service->GetCategoryInfo(unknown_category()); 720 CategoryInfo info = service->GetCategoryInfo(unknown_category());
841 EXPECT_THAT(info.has_more_action(), Eq(false)); 721 EXPECT_THAT(info.has_more_action(), Eq(false));
842 EXPECT_THAT(info.has_reload_action(), Eq(false)); 722 EXPECT_THAT(info.has_reload_action(), Eq(false));
843 EXPECT_THAT(info.has_view_all_action(), Eq(false)); 723 EXPECT_THAT(info.has_view_all_action(), Eq(false));
844 EXPECT_THAT(info.show_if_empty(), Eq(false)); 724 EXPECT_THAT(info.show_if_empty(), Eq(false));
845 } 725 }
846 726
847 TEST_F(RemoteSuggestionsProviderTest, AddRemoteCategoriesToCategoryRanker) { 727 TEST_F(RemoteSuggestionsProviderImplTest, AddRemoteCategoriesToCategoryRanker) {
848 auto mock_ranker = base::MakeUnique<MockCategoryRanker>(); 728 auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
849 MockCategoryRanker* raw_mock_ranker = mock_ranker.get(); 729 MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
850 SetCategoryRanker(std::move(mock_ranker)); 730 SetCategoryRanker(std::move(mock_ranker));
851 std::string json_str = 731 std::string json_str =
852 MultiCategoryJsonBuilder() 732 MultiCategoryJsonBuilder()
853 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11) 733 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11)
854 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13) 734 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13)
855 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12) 735 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12)
856 .Build(); 736 .Build();
857 SetUpFetchResponse(json_str); 737 SetUpFetchResponse(json_str);
858 { 738 {
859 // The order of categories is determined by the order in which they are 739 // The order of categories is determined by the order in which they are
860 // added. Thus, the latter is tested here. 740 // added. Thus, the latter is tested here.
861 InSequence s; 741 InSequence s;
862 EXPECT_CALL(*raw_mock_ranker, 742 EXPECT_CALL(*raw_mock_ranker,
863 AppendCategoryIfNecessary(Category::FromRemoteCategory(11))); 743 AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
864 EXPECT_CALL(*raw_mock_ranker, 744 EXPECT_CALL(*raw_mock_ranker,
865 AppendCategoryIfNecessary(Category::FromRemoteCategory(13))); 745 AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
866 EXPECT_CALL(*raw_mock_ranker, 746 EXPECT_CALL(*raw_mock_ranker,
867 AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); 747 AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
868 } 748 }
869 auto service = MakeSnippetsService(/*set_empty_response=*/false); 749 auto service = MakeSnippetsService(/*set_empty_response=*/false);
870 } 750 }
871 751
872 TEST_F(RemoteSuggestionsProviderTest, PersistCategoryInfos) { 752 TEST_F(RemoteSuggestionsProviderImplTest, PersistCategoryInfos) {
873 auto service = MakeSnippetsService(); 753 auto service = MakeSnippetsService();
874 // TODO(vitaliii): Use |articles_category()| instead of constant ID below. 754 // TODO(vitaliii): Use |articles_category()| instead of constant ID below.
875 std::string json_str = 755 std::string json_str =
876 MultiCategoryJsonBuilder() 756 MultiCategoryJsonBuilder()
877 .AddCategoryWithCustomTitle( 757 .AddCategoryWithCustomTitle(
878 {GetSnippetN(0)}, /*remote_category_id=*/1, "Articles for You") 758 {GetSnippetN(0)}, /*remote_category_id=*/1, "Articles for You")
879 .AddCategoryWithCustomTitle({GetSnippetN(1)}, 759 .AddCategoryWithCustomTitle({GetSnippetN(1)},
880 kUnknownRemoteCategoryId, "Other Things") 760 kUnknownRemoteCategoryId, "Other Things")
881 .Build(); 761 .Build();
882 LoadFromJSONString(service.get(), json_str); 762 LoadFromJSONString(service.get(), json_str);
(...skipping 24 matching lines...) Expand all
907 787
908 CategoryInfo info_articles_after = 788 CategoryInfo info_articles_after =
909 service->GetCategoryInfo(articles_category()); 789 service->GetCategoryInfo(articles_category());
910 CategoryInfo info_unknown_after = 790 CategoryInfo info_unknown_after =
911 service->GetCategoryInfo(unknown_category()); 791 service->GetCategoryInfo(unknown_category());
912 792
913 EXPECT_EQ(info_articles_before.title(), info_articles_after.title()); 793 EXPECT_EQ(info_articles_before.title(), info_articles_after.title());
914 EXPECT_EQ(info_unknown_before.title(), info_unknown_after.title()); 794 EXPECT_EQ(info_unknown_before.title(), info_unknown_after.title());
915 } 795 }
916 796
917 TEST_F(RemoteSuggestionsProviderTest, PersistRemoteCategoryOrder) { 797 TEST_F(RemoteSuggestionsProviderImplTest, PersistRemoteCategoryOrder) {
918 // We create a service with a normal ranker to store the order. 798 // We create a service with a normal ranker to store the order.
919 std::string json_str = 799 std::string json_str =
920 MultiCategoryJsonBuilder() 800 MultiCategoryJsonBuilder()
921 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11) 801 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11)
922 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13) 802 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13)
923 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12) 803 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12)
924 .Build(); 804 .Build();
925 SetUpFetchResponse(json_str); 805 SetUpFetchResponse(json_str);
926 auto service = MakeSnippetsService(/*set_empty_response=*/false); 806 auto service = MakeSnippetsService(/*set_empty_response=*/false);
927 807
(...skipping 15 matching lines...) Expand all
943 EXPECT_CALL(*raw_mock_ranker, 823 EXPECT_CALL(*raw_mock_ranker,
944 AppendCategoryIfNecessary(Category::FromRemoteCategory(11))); 824 AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
945 EXPECT_CALL(*raw_mock_ranker, 825 EXPECT_CALL(*raw_mock_ranker,
946 AppendCategoryIfNecessary(Category::FromRemoteCategory(13))); 826 AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
947 EXPECT_CALL(*raw_mock_ranker, 827 EXPECT_CALL(*raw_mock_ranker,
948 AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); 828 AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
949 } 829 }
950 ResetSnippetsService(&service, /*set_empty_response=*/false); 830 ResetSnippetsService(&service, /*set_empty_response=*/false);
951 } 831 }
952 832
953 TEST_F(RemoteSuggestionsProviderTest, PersistSuggestions) { 833 TEST_F(RemoteSuggestionsProviderImplTest, PersistSuggestions) {
954 auto service = MakeSnippetsService(); 834 auto service = MakeSnippetsService();
955 std::string json_str = 835 std::string json_str =
956 MultiCategoryJsonBuilder() 836 MultiCategoryJsonBuilder()
957 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 837 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
958 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/2) 838 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/2)
959 .Build(); 839 .Build();
960 LoadFromJSONString(service.get(), json_str); 840 LoadFromJSONString(service.get(), json_str);
961 841
962 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 842 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
963 SizeIs(1)); 843 SizeIs(1));
964 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 844 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
965 845
966 // Recreate the service to simulate a Chrome restart. 846 // Recreate the service to simulate a Chrome restart.
967 ResetSnippetsService(&service, /*set_empty_response=*/true); 847 ResetSnippetsService(&service, /*set_empty_response=*/true);
968 848
969 // The suggestions in both categories should have been restored. 849 // The suggestions in both categories should have been restored.
970 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), 850 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
971 SizeIs(1)); 851 SizeIs(1));
972 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 852 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
973 } 853 }
974 854
975 TEST_F(RemoteSuggestionsProviderTest, DontNotifyIfNotAvailable) { 855 TEST_F(RemoteSuggestionsProviderImplTest, DontNotifyIfNotAvailable) {
976 // Get some suggestions into the database. 856 // Get some suggestions into the database.
977 auto service = MakeSnippetsService(); 857 auto service = MakeSnippetsService();
978 std::string json_str = 858 std::string json_str =
979 MultiCategoryJsonBuilder() 859 MultiCategoryJsonBuilder()
980 .AddCategory({GetSnippetN(0)}, 860 .AddCategory({GetSnippetN(0)},
981 /*remote_category_id=*/1) 861 /*remote_category_id=*/1)
982 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2) 862 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2)
983 .Build(); 863 .Build();
984 LoadFromJSONString(service.get(), json_str); 864 LoadFromJSONString(service.get(), json_str);
985 865
986 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 866 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
987 SizeIs(1)); 867 SizeIs(1));
988 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 868 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
989 869
990 service.reset(); 870 service.reset();
991 871
992 // Set the pref that disables remote suggestions. 872 // Set the pref that disables remote suggestions.
993 pref_service()->SetBoolean(prefs::kEnableSnippets, false); 873 pref_service()->SetBoolean(prefs::kEnableSnippets, false);
994 874
995 // Recreate the service to simulate a Chrome start. 875 // Recreate the service to simulate a Chrome start.
996 ResetSnippetsService(&service, /*set_empty_response=*/true); 876 ResetSnippetsService(&service, /*set_empty_response=*/true);
997 877
998 ASSERT_THAT(RemoteSuggestionsProvider::State::DISABLED, Eq(service->state_)); 878 ASSERT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED,
879 Eq(service->state_));
999 880
1000 // Now the observer should not have received any suggestions. 881 // Now the observer should not have received any suggestions.
1001 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), 882 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
1002 IsEmpty()); 883 IsEmpty());
1003 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), IsEmpty()); 884 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), IsEmpty());
1004 } 885 }
1005 886
1006 TEST_F(RemoteSuggestionsProviderTest, Clear) { 887 TEST_F(RemoteSuggestionsProviderImplTest, Clear) {
1007 auto service = MakeSnippetsService(); 888 auto service = MakeSnippetsService();
1008 889
1009 std::string json_str(GetTestJson({GetSnippet()})); 890 std::string json_str(GetTestJson({GetSnippet()}));
1010 891
1011 LoadFromJSONString(service.get(), json_str); 892 LoadFromJSONString(service.get(), json_str);
1012 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 893 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1013 894
1014 service->ClearCachedSuggestions(articles_category()); 895 service->ClearCachedSuggestions(articles_category());
1015 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 896 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1016 } 897 }
1017 898
1018 TEST_F(RemoteSuggestionsProviderTest, ReplaceSnippets) { 899 TEST_F(RemoteSuggestionsProviderImplTest, ReplaceSnippets) {
1019 auto service = MakeSnippetsService(); 900 auto service = MakeSnippetsService();
1020 901
1021 std::string first("http://first"); 902 std::string first("http://first");
1022 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(first)})); 903 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(first)}));
1023 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 904 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1024 ElementsAre(IdEq(first))); 905 ElementsAre(IdEq(first)));
1025 906
1026 std::string second("http://second"); 907 std::string second("http://second");
1027 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(second)})); 908 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(second)}));
1028 // The snippets loaded last replace all that was loaded previously. 909 // The snippets loaded last replace all that was loaded previously.
1029 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 910 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1030 ElementsAre(IdEq(second))); 911 ElementsAre(IdEq(second)));
1031 } 912 }
1032 913
1033 TEST_F(RemoteSuggestionsProviderTest, LoadsAdditionalSnippets) { 914 TEST_F(RemoteSuggestionsProviderImplTest, LoadsAdditionalSnippets) {
1034 auto service = MakeSnippetsService(); 915 auto service = MakeSnippetsService();
1035 916
1036 LoadFromJSONString(service.get(), 917 LoadFromJSONString(service.get(),
1037 GetTestJson({GetSnippetWithUrl("http://first")})); 918 GetTestJson({GetSnippetWithUrl("http://first")}));
1038 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 919 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1039 ElementsAre(IdEq("http://first"))); 920 ElementsAre(IdEq("http://first")));
1040 921
1041 auto expect_only_second_suggestion_received = base::Bind([]( 922 auto expect_only_second_suggestion_received = base::Bind([](
1042 Status status, std::vector<ContentSuggestion> suggestions) { 923 Status status, std::vector<ContentSuggestion> suggestions) {
1043 EXPECT_THAT(suggestions, SizeIs(1)); 924 EXPECT_THAT(suggestions, SizeIs(1));
(...skipping 29 matching lines...) Expand all
1073 // The tests TestMergingFetchedMoreSnippetsFillup and 954 // The tests TestMergingFetchedMoreSnippetsFillup and
1074 // TestMergingFetchedMoreSnippetsReplaceAll simulate the following user story: 955 // TestMergingFetchedMoreSnippetsReplaceAll simulate the following user story:
1075 // 1) fetch suggestions in NTP A 956 // 1) fetch suggestions in NTP A
1076 // 2) fetch more suggestions in NTP A. 957 // 2) fetch more suggestions in NTP A.
1077 // 3) open new NTP B: See the last 10 results visible in step 2). 958 // 3) open new NTP B: See the last 10 results visible in step 2).
1078 // 4) fetch more suggestions in NTP B. Make sure no results from step 1) which 959 // 4) fetch more suggestions in NTP B. Make sure no results from step 1) which
1079 // were superseded in step 2) get merged back in again. 960 // were superseded in step 2) get merged back in again.
1080 // TODO(tschumann): Test step 4) on a higher level instead of peeking into the 961 // TODO(tschumann): Test step 4) on a higher level instead of peeking into the
1081 // internal 'dismissed' data. The proper check is to make sure we tell the 962 // internal 'dismissed' data. The proper check is to make sure we tell the
1082 // backend to exclude these snippets. 963 // backend to exclude these snippets.
1083 TEST_F(RemoteSuggestionsProviderTest, TestMergingFetchedMoreSnippetsFillup) { 964 TEST_F(RemoteSuggestionsProviderImplTest,
965 TestMergingFetchedMoreSnippetsFillup) {
1084 auto service = MakeSnippetsService(/*set_empty_response=*/false); 966 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1085 LoadFromJSONString( 967 LoadFromJSONString(
1086 service.get(), 968 service.get(),
1087 GetTestJson( 969 GetTestJson(
1088 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"), 970 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"),
1089 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"), 971 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"),
1090 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"), 972 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"),
1091 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"), 973 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"),
1092 GetSnippetWithUrl("http://id-9"), 974 GetSnippetWithUrl("http://id-9"),
1093 GetSnippetWithUrl("http://id-10")})); 975 GetSnippetWithUrl("http://id-10")}));
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
1126 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"), 1008 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"),
1127 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"), 1009 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"),
1128 IdWithinCategoryEq("http://id-9"), IdWithinCategoryEq("http://id-10"), 1010 IdWithinCategoryEq("http://id-9"), IdWithinCategoryEq("http://id-10"),
1129 IdWithinCategoryEq("http://more-id-1"), 1011 IdWithinCategoryEq("http://more-id-1"),
1130 IdWithinCategoryEq("http://more-id-2"))); 1012 IdWithinCategoryEq("http://more-id-2")));
1131 // Verify the superseded suggestions got marked as dismissed. 1013 // Verify the superseded suggestions got marked as dismissed.
1132 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1014 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1133 ElementsAre(IdEq("http://id-1"), IdEq("http://id-2"))); 1015 ElementsAre(IdEq("http://id-1"), IdEq("http://id-2")));
1134 } 1016 }
1135 1017
1136 TEST_F(RemoteSuggestionsProviderTest, 1018 TEST_F(RemoteSuggestionsProviderImplTest,
1137 TestMergingFetchedMoreSnippetsReplaceAll) { 1019 TestMergingFetchedMoreSnippetsReplaceAll) {
1138 auto service = MakeSnippetsService(/*set_empty_response=*/false); 1020 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1139 LoadFromJSONString( 1021 LoadFromJSONString(
1140 service.get(), 1022 service.get(),
1141 GetTestJson( 1023 GetTestJson(
1142 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"), 1024 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"),
1143 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"), 1025 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"),
1144 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"), 1026 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"),
1145 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"), 1027 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"),
1146 GetSnippetWithUrl("http://id-9"), 1028 GetSnippetWithUrl("http://id-9"),
1147 GetSnippetWithUrl("http://id-10")})); 1029 GetSnippetWithUrl("http://id-10")}));
1148 EXPECT_THAT( 1030 EXPECT_THAT(
1149 observer().SuggestionsForCategory(articles_category()), 1031 observer().SuggestionsForCategory(articles_category()),
1150 ElementsAre( 1032 ElementsAre(
1151 IdWithinCategoryEq("http://id-1"), IdWithinCategoryEq("http://id-2"), 1033 IdWithinCategoryEq("http://id-1"), IdWithinCategoryEq("http://id-2"),
1152 IdWithinCategoryEq("http://id-3"), IdWithinCategoryEq("http://id-4"), 1034 IdWithinCategoryEq("http://id-3"), IdWithinCategoryEq("http://id-4"),
1153 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"), 1035 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"),
1154 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"), 1036 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"),
1155 IdWithinCategoryEq("http://id-9"), 1037 IdWithinCategoryEq("http://id-9"),
1156 IdWithinCategoryEq("http://id-10"))); 1038 IdWithinCategoryEq("http://id-10")));
1157 1039
1158 auto expect_receiving_ten_new_snippets = 1040 auto expect_receiving_ten_new_snippets =
1159 base::Bind([](Status status, std::vector<ContentSuggestion> suggestions) { 1041 base::Bind([](Status status, std::vector<ContentSuggestion> suggestions) {
1160 EXPECT_THAT(suggestions, ElementsAre( 1042 EXPECT_THAT(suggestions,
1161 IdWithinCategoryEq("http://more-id-1"), 1043 ElementsAre(IdWithinCategoryEq("http://more-id-1"),
1162 IdWithinCategoryEq("http://more-id-2"), 1044 IdWithinCategoryEq("http://more-id-2"),
1163 IdWithinCategoryEq("http://more-id-3"), 1045 IdWithinCategoryEq("http://more-id-3"),
1164 IdWithinCategoryEq("http://more-id-4"), 1046 IdWithinCategoryEq("http://more-id-4"),
1165 IdWithinCategoryEq("http://more-id-5"), 1047 IdWithinCategoryEq("http://more-id-5"),
1166 IdWithinCategoryEq("http://more-id-6"), 1048 IdWithinCategoryEq("http://more-id-6"),
1167 IdWithinCategoryEq("http://more-id-7"), 1049 IdWithinCategoryEq("http://more-id-7"),
1168 IdWithinCategoryEq("http://more-id-8"), 1050 IdWithinCategoryEq("http://more-id-8"),
1169 IdWithinCategoryEq("http://more-id-9"), 1051 IdWithinCategoryEq("http://more-id-9"),
1170 IdWithinCategoryEq("http://more-id-10"))); 1052 IdWithinCategoryEq("http://more-id-10")));
1171 }); 1053 });
1172 LoadMoreFromJSONString( 1054 LoadMoreFromJSONString(
1173 service.get(), articles_category(), 1055 service.get(), articles_category(),
1174 GetTestJson({GetSnippetWithUrl("http://more-id-1"), 1056 GetTestJson({GetSnippetWithUrl("http://more-id-1"),
1175 GetSnippetWithUrl("http://more-id-2"), 1057 GetSnippetWithUrl("http://more-id-2"),
1176 GetSnippetWithUrl("http://more-id-3"), 1058 GetSnippetWithUrl("http://more-id-3"),
1177 GetSnippetWithUrl("http://more-id-4"), 1059 GetSnippetWithUrl("http://more-id-4"),
1178 GetSnippetWithUrl("http://more-id-5"), 1060 GetSnippetWithUrl("http://more-id-5"),
1179 GetSnippetWithUrl("http://more-id-6"), 1061 GetSnippetWithUrl("http://more-id-6"),
1180 GetSnippetWithUrl("http://more-id-7"), 1062 GetSnippetWithUrl("http://more-id-7"),
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
1215 // Workaround for gMock's lack of support for movable types. 1097 // Workaround for gMock's lack of support for movable types.
1216 void SuggestionsLoaded( 1098 void SuggestionsLoaded(
1217 MockFunction<void(Status, const std::vector<ContentSuggestion>&)>* loaded, 1099 MockFunction<void(Status, const std::vector<ContentSuggestion>&)>* loaded,
1218 Status status, 1100 Status status,
1219 std::vector<ContentSuggestion> suggestions) { 1101 std::vector<ContentSuggestion> suggestions) {
1220 loaded->Call(status, suggestions); 1102 loaded->Call(status, suggestions);
1221 } 1103 }
1222 1104
1223 } // namespace 1105 } // namespace
1224 1106
1225 TEST_F(RemoteSuggestionsProviderTest, ReturnFetchRequestEmptyBeforeInit) { 1107 TEST_F(RemoteSuggestionsProviderImplTest, ReturnFetchRequestEmptyBeforeInit) {
1226 auto service = MakeSnippetsServiceWithoutInitialization(); 1108 auto service = MakeSnippetsServiceWithoutInitialization();
1227 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1109 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1228 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1110 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1229 service->Fetch(articles_category(), std::set<std::string>(), 1111 service->Fetch(articles_category(), std::set<std::string>(),
1230 base::Bind(&SuggestionsLoaded, &loaded)); 1112 base::Bind(&SuggestionsLoaded, &loaded));
1231 base::RunLoop().RunUntilIdle(); 1113 base::RunLoop().RunUntilIdle();
1232 } 1114 }
1233 1115
1234 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForInvalidJson) { 1116 TEST_F(RemoteSuggestionsProviderImplTest, ReturnTemporaryErrorForInvalidJson) {
1235 auto service = MakeSnippetsService(); 1117 auto service = MakeSnippetsService();
1236 1118
1237 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1119 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1238 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1120 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1239 LoadMoreFromJSONString(service.get(), articles_category(), 1121 LoadMoreFromJSONString(service.get(), articles_category(),
1240 "invalid json string}]}", 1122 "invalid json string}]}",
1241 /*known_ids=*/std::set<std::string>(), 1123 /*known_ids=*/std::set<std::string>(),
1242 base::Bind(&SuggestionsLoaded, &loaded)); 1124 base::Bind(&SuggestionsLoaded, &loaded));
1243 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1125 EXPECT_THAT(
1244 StartsWith("Received invalid JSON")); 1126 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1127 StartsWith("Received invalid JSON"));
1245 } 1128 }
1246 1129
1247 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForInvalidSnippet) { 1130 TEST_F(RemoteSuggestionsProviderImplTest,
1131 ReturnTemporaryErrorForInvalidSnippet) {
1248 auto service = MakeSnippetsService(); 1132 auto service = MakeSnippetsService();
1249 1133
1250 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1134 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1251 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1135 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1252 LoadMoreFromJSONString(service.get(), articles_category(), 1136 LoadMoreFromJSONString(service.get(), articles_category(),
1253 GetTestJson({GetIncompleteSnippet()}), 1137 GetTestJson({GetIncompleteSnippet()}),
1254 /*known_ids=*/std::set<std::string>(), 1138 /*known_ids=*/std::set<std::string>(),
1255 base::Bind(&SuggestionsLoaded, &loaded)); 1139 base::Bind(&SuggestionsLoaded, &loaded));
1256 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1140 EXPECT_THAT(
1257 StartsWith("Invalid / empty list")); 1141 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1142 StartsWith("Invalid / empty list"));
1258 } 1143 }
1259 1144
1260 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForRequestFailure) { 1145 TEST_F(RemoteSuggestionsProviderImplTest,
1146 ReturnTemporaryErrorForRequestFailure) {
1261 // Created SnippetsService will fail by default with unsuccessful request. 1147 // Created SnippetsService will fail by default with unsuccessful request.
1262 auto service = MakeSnippetsService(/*set_empty_response=*/false); 1148 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1263 1149
1264 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1150 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1265 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1151 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1266 service->Fetch(articles_category(), 1152 service->Fetch(articles_category(),
1267 /*known_ids=*/std::set<std::string>(), 1153 /*known_ids=*/std::set<std::string>(),
1268 base::Bind(&SuggestionsLoaded, &loaded)); 1154 base::Bind(&SuggestionsLoaded, &loaded));
1269 base::RunLoop().RunUntilIdle(); 1155 base::RunLoop().RunUntilIdle();
1270 } 1156 }
1271 1157
1272 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForHttpFailure) { 1158 TEST_F(RemoteSuggestionsProviderImplTest, ReturnTemporaryErrorForHttpFailure) {
1273 auto service = MakeSnippetsService(); 1159 auto service = MakeSnippetsService();
1274 SetUpHttpError(); 1160 SetUpHttpError();
1275 1161
1276 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1162 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1277 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1163 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1278 service->Fetch(articles_category(), 1164 service->Fetch(articles_category(),
1279 /*known_ids=*/std::set<std::string>(), 1165 /*known_ids=*/std::set<std::string>(),
1280 base::Bind(&SuggestionsLoaded, &loaded)); 1166 base::Bind(&SuggestionsLoaded, &loaded));
1281 base::RunLoop().RunUntilIdle(); 1167 base::RunLoop().RunUntilIdle();
1282 } 1168 }
1283 1169
1284 TEST_F(RemoteSuggestionsProviderTest, LoadInvalidJson) { 1170 TEST_F(RemoteSuggestionsProviderImplTest, LoadInvalidJson) {
1285 auto service = MakeSnippetsService(); 1171 auto service = MakeSnippetsService();
1286 1172
1287 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1173 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1288 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1174 EXPECT_THAT(
1289 StartsWith("Received invalid JSON")); 1175 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1176 StartsWith("Received invalid JSON"));
1290 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1177 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1291 } 1178 }
1292 1179
1293 TEST_F(RemoteSuggestionsProviderTest, LoadInvalidJsonWithExistingSnippets) { 1180 TEST_F(RemoteSuggestionsProviderImplTest, LoadInvalidJsonWithExistingSnippets) {
1294 auto service = MakeSnippetsService(); 1181 auto service = MakeSnippetsService();
1295 1182
1296 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1183 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1297 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1184 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1298 ASSERT_EQ("OK", service->snippets_fetcher()->last_status()); 1185 ASSERT_EQ(
1186 "OK",
1187 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1299 1188
1300 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1189 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1301 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1190 EXPECT_THAT(
1302 StartsWith("Received invalid JSON")); 1191 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1192 StartsWith("Received invalid JSON"));
1303 // This should not have changed the existing snippets. 1193 // This should not have changed the existing snippets.
1304 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1194 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1305 } 1195 }
1306 1196
1307 TEST_F(RemoteSuggestionsProviderTest, LoadIncompleteJson) { 1197 TEST_F(RemoteSuggestionsProviderImplTest, LoadIncompleteJson) {
1308 auto service = MakeSnippetsService(); 1198 auto service = MakeSnippetsService();
1309 1199
1310 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); 1200 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()}));
1311 EXPECT_EQ("Invalid / empty list.", 1201 EXPECT_EQ(
1312 service->snippets_fetcher()->last_status()); 1202 "Invalid / empty list.",
1203 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1313 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1204 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1314 } 1205 }
1315 1206
1316 TEST_F(RemoteSuggestionsProviderTest, LoadIncompleteJsonWithExistingSnippets) { 1207 TEST_F(RemoteSuggestionsProviderImplTest,
1208 LoadIncompleteJsonWithExistingSnippets) {
1317 auto service = MakeSnippetsService(); 1209 auto service = MakeSnippetsService();
1318 1210
1319 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1211 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1320 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1212 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1321 1213
1322 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); 1214 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()}));
1323 EXPECT_EQ("Invalid / empty list.", 1215 EXPECT_EQ(
1324 service->snippets_fetcher()->last_status()); 1216 "Invalid / empty list.",
1217 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1325 // This should not have changed the existing snippets. 1218 // This should not have changed the existing snippets.
1326 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1219 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1327 } 1220 }
1328 1221
1329 TEST_F(RemoteSuggestionsProviderTest, Dismiss) { 1222 TEST_F(RemoteSuggestionsProviderImplTest, Dismiss) {
1330 auto service = MakeSnippetsService(); 1223 auto service = MakeSnippetsService();
1331 1224
1332 std::string json_str( 1225 std::string json_str(
1333 GetTestJson({GetSnippetWithSources("http://site.com", "Source 1", "")})); 1226 GetTestJson({GetSnippetWithSources("http://site.com", "Source 1", "")}));
1334 1227
1335 LoadFromJSONString(service.get(), json_str); 1228 LoadFromJSONString(service.get(), json_str);
1336 1229
1337 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1230 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1338 // Load the image to store it in the database. 1231 // Load the image to store it in the database.
1339 ServeImageCallback cb = 1232 ServeImageCallback cb =
(...skipping 30 matching lines...) Expand all
1370 LoadFromJSONString(service.get(), json_str); 1263 LoadFromJSONString(service.get(), json_str);
1371 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1264 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1372 1265
1373 // The snippet can be added again after clearing dismissed snippets. 1266 // The snippet can be added again after clearing dismissed snippets.
1374 service->ClearDismissedSuggestionsForDebugging(articles_category()); 1267 service->ClearDismissedSuggestionsForDebugging(articles_category());
1375 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1268 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1376 LoadFromJSONString(service.get(), json_str); 1269 LoadFromJSONString(service.get(), json_str);
1377 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1270 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1378 } 1271 }
1379 1272
1380 TEST_F(RemoteSuggestionsProviderTest, GetDismissed) { 1273 TEST_F(RemoteSuggestionsProviderImplTest, GetDismissed) {
1381 auto service = MakeSnippetsService(); 1274 auto service = MakeSnippetsService();
1382 1275
1383 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1276 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1384 1277
1385 service->DismissSuggestion(MakeArticleID(kSnippetUrl)); 1278 service->DismissSuggestion(MakeArticleID(kSnippetUrl));
1386 1279
1387 service->GetDismissedSuggestionsForDebugging( 1280 service->GetDismissedSuggestionsForDebugging(
1388 articles_category(), 1281 articles_category(),
1389 base::Bind( 1282 base::Bind(
1390 [](RemoteSuggestionsProvider* service, 1283 [](RemoteSuggestionsProviderImpl* service,
1391 RemoteSuggestionsProviderTest* test, 1284 RemoteSuggestionsProviderImplTest* test,
1392 std::vector<ContentSuggestion> dismissed_suggestions) { 1285 std::vector<ContentSuggestion> dismissed_suggestions) {
1393 EXPECT_EQ(1u, dismissed_suggestions.size()); 1286 EXPECT_EQ(1u, dismissed_suggestions.size());
1394 for (auto& suggestion : dismissed_suggestions) { 1287 for (auto& suggestion : dismissed_suggestions) {
1395 EXPECT_EQ(test->MakeArticleID(kSnippetUrl), suggestion.id()); 1288 EXPECT_EQ(test->MakeArticleID(kSnippetUrl), suggestion.id());
1396 } 1289 }
1397 }, 1290 },
1398 service.get(), this)); 1291 service.get(), this));
1399 base::RunLoop().RunUntilIdle(); 1292 base::RunLoop().RunUntilIdle();
1400 1293
1401 // There should be no dismissed snippet after clearing the list. 1294 // There should be no dismissed snippet after clearing the list.
1402 service->ClearDismissedSuggestionsForDebugging(articles_category()); 1295 service->ClearDismissedSuggestionsForDebugging(articles_category());
1403 service->GetDismissedSuggestionsForDebugging( 1296 service->GetDismissedSuggestionsForDebugging(
1404 articles_category(), 1297 articles_category(),
1405 base::Bind( 1298 base::Bind(
1406 [](RemoteSuggestionsProvider* service, 1299 [](RemoteSuggestionsProviderImpl* service,
1407 RemoteSuggestionsProviderTest* test, 1300 RemoteSuggestionsProviderImplTest* test,
1408 std::vector<ContentSuggestion> dismissed_suggestions) { 1301 std::vector<ContentSuggestion> dismissed_suggestions) {
1409 EXPECT_EQ(0u, dismissed_suggestions.size()); 1302 EXPECT_EQ(0u, dismissed_suggestions.size());
1410 }, 1303 },
1411 service.get(), this)); 1304 service.get(), this));
1412 base::RunLoop().RunUntilIdle(); 1305 base::RunLoop().RunUntilIdle();
1413 } 1306 }
1414 1307
1415 TEST_F(RemoteSuggestionsProviderTest, CreationTimestampParseFail) { 1308 TEST_F(RemoteSuggestionsProviderImplTest, CreationTimestampParseFail) {
1416 auto service = MakeSnippetsService(); 1309 auto service = MakeSnippetsService();
1417 1310
1418 std::string json = 1311 std::string json =
1419 GetSnippetWithTimes(GetDefaultCreationTime(), GetDefaultExpirationTime()); 1312 GetSnippetWithTimes(GetDefaultCreationTime(), GetDefaultExpirationTime());
1420 base::ReplaceFirstSubstringAfterOffset( 1313 base::ReplaceFirstSubstringAfterOffset(
1421 &json, 0, FormatTime(GetDefaultCreationTime()), "aaa1448459205"); 1314 &json, 0, FormatTime(GetDefaultCreationTime()), "aaa1448459205");
1422 std::string json_str(GetTestJson({json})); 1315 std::string json_str(GetTestJson({json}));
1423 1316
1424 LoadFromJSONString(service.get(), json_str); 1317 LoadFromJSONString(service.get(), json_str);
1425 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1318 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1426 } 1319 }
1427 1320
1428 TEST_F(RemoteSuggestionsProviderTest, RemoveExpiredDismissedContent) { 1321 TEST_F(RemoteSuggestionsProviderImplTest, RemoveExpiredDismissedContent) {
1429 auto service = MakeSnippetsService(); 1322 auto service = MakeSnippetsService();
1430 1323
1431 std::string json_str1(GetTestJson({GetExpiredSnippet()})); 1324 std::string json_str1(GetTestJson({GetExpiredSnippet()}));
1432 // Load it. 1325 // Load it.
1433 LoadFromJSONString(service.get(), json_str1); 1326 LoadFromJSONString(service.get(), json_str1);
1434 // Load the image to store it in the database. 1327 // Load the image to store it in the database.
1435 // TODO(tschumann): Introduce some abstraction to nicely work with image 1328 // TODO(tschumann): Introduce some abstraction to nicely work with image
1436 // fetching expectations. 1329 // fetching expectations.
1437 ServeImageCallback cb = 1330 ServeImageCallback cb =
1438 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1331 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
(...skipping 12 matching lines...) Expand all
1451 std::string json_str2(GetTestJson({GetSnippetWithUrl(kSnippetUrl2)})); 1344 std::string json_str2(GetTestJson({GetSnippetWithUrl(kSnippetUrl2)}));
1452 LoadFromJSONString(service.get(), json_str2); 1345 LoadFromJSONString(service.get(), json_str2);
1453 1346
1454 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1347 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1455 IsEmpty()); 1348 IsEmpty());
1456 1349
1457 // Verify the image got removed, too. 1350 // Verify the image got removed, too.
1458 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1351 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1459 } 1352 }
1460 1353
1461 TEST_F(RemoteSuggestionsProviderTest, ExpiredContentNotRemoved) { 1354 TEST_F(RemoteSuggestionsProviderImplTest, ExpiredContentNotRemoved) {
1462 auto service = MakeSnippetsService(); 1355 auto service = MakeSnippetsService();
1463 1356
1464 std::string json_str(GetTestJson({GetExpiredSnippet()})); 1357 std::string json_str(GetTestJson({GetExpiredSnippet()}));
1465 1358
1466 LoadFromJSONString(service.get(), json_str); 1359 LoadFromJSONString(service.get(), json_str);
1467 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1360 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1468 } 1361 }
1469 1362
1470 TEST_F(RemoteSuggestionsProviderTest, TestSingleSource) { 1363 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSource) {
1471 auto service = MakeSnippetsService(); 1364 auto service = MakeSnippetsService();
1472 1365
1473 std::string json_str(GetTestJson({GetSnippetWithSources( 1366 std::string json_str(GetTestJson({GetSnippetWithSources(
1474 "http://source1.com", "Source 1", "http://source1.amp.com")})); 1367 "http://source1.com", "Source 1", "http://source1.amp.com")}));
1475 1368
1476 LoadFromJSONString(service.get(), json_str); 1369 LoadFromJSONString(service.get(), json_str);
1477 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1370 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1478 const NTPSnippet& snippet = 1371 const NTPSnippet& snippet =
1479 *service->GetSnippetsForTesting(articles_category()).front(); 1372 *service->GetSnippetsForTesting(articles_category()).front();
1480 EXPECT_EQ(snippet.id(), kSnippetUrl); 1373 EXPECT_EQ(snippet.id(), kSnippetUrl);
1481 EXPECT_EQ(snippet.url(), GURL("http://source1.com")); 1374 EXPECT_EQ(snippet.url(), GURL("http://source1.com"));
1482 EXPECT_EQ(snippet.publisher_name(), std::string("Source 1")); 1375 EXPECT_EQ(snippet.publisher_name(), std::string("Source 1"));
1483 EXPECT_EQ(snippet.amp_url(), GURL("http://source1.amp.com")); 1376 EXPECT_EQ(snippet.amp_url(), GURL("http://source1.amp.com"));
1484 } 1377 }
1485 1378
1486 TEST_F(RemoteSuggestionsProviderTest, TestSingleSourceWithMalformedUrl) { 1379 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMalformedUrl) {
1487 auto service = MakeSnippetsService(); 1380 auto service = MakeSnippetsService();
1488 1381
1489 std::string json_str(GetTestJson({GetSnippetWithSources( 1382 std::string json_str(GetTestJson({GetSnippetWithSources(
1490 "ceci n'est pas un url", "Source 1", "http://source1.amp.com")})); 1383 "ceci n'est pas un url", "Source 1", "http://source1.amp.com")}));
1491 1384
1492 LoadFromJSONString(service.get(), json_str); 1385 LoadFromJSONString(service.get(), json_str);
1493 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1386 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1494 } 1387 }
1495 1388
1496 TEST_F(RemoteSuggestionsProviderTest, TestSingleSourceWithMissingData) { 1389 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMissingData) {
1497 auto service = MakeSnippetsService(); 1390 auto service = MakeSnippetsService();
1498 1391
1499 std::string json_str( 1392 std::string json_str(
1500 GetTestJson({GetSnippetWithSources("http://source1.com", "", "")})); 1393 GetTestJson({GetSnippetWithSources("http://source1.com", "", "")}));
1501 1394
1502 LoadFromJSONString(service.get(), json_str); 1395 LoadFromJSONString(service.get(), json_str);
1503 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1396 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1504 } 1397 }
1505 1398
1506 TEST_F(RemoteSuggestionsProviderTest, LogNumArticlesHistogram) { 1399 TEST_F(RemoteSuggestionsProviderImplTest, LogNumArticlesHistogram) {
1507 auto service = MakeSnippetsService(); 1400 auto service = MakeSnippetsService();
1508 1401
1509 base::HistogramTester tester; 1402 base::HistogramTester tester;
1510 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1403 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1511 1404
1512 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), 1405 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
1513 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); 1406 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
1514 1407
1515 // Invalid JSON shouldn't contribute to NumArticlesFetched. 1408 // Invalid JSON shouldn't contribute to NumArticlesFetched.
1516 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), 1409 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"),
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
1573 // But if there's a non-dismissed snippet in the database, recreating it 1466 // But if there's a non-dismissed snippet in the database, recreating it
1574 // shouldn't trigger a fetch. 1467 // shouldn't trigger a fetch.
1575 LoadFromJSONString( 1468 LoadFromJSONString(
1576 service.get(), 1469 service.get(),
1577 GetTestJson({GetSnippetWithUrl("http://not-dismissed.com")})); 1470 GetTestJson({GetSnippetWithUrl("http://not-dismissed.com")}));
1578 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); 1471 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6);
1579 ResetSnippetsService(&service, /*set_empty_response=*/true); 1472 ResetSnippetsService(&service, /*set_empty_response=*/true);
1580 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); 1473 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6);
1581 } 1474 }
1582 1475
1583 TEST_F(RemoteSuggestionsProviderTest, DismissShouldRespectAllKnownUrls) { 1476 TEST_F(RemoteSuggestionsProviderImplTest, DismissShouldRespectAllKnownUrls) {
1584 auto service = MakeSnippetsService(); 1477 auto service = MakeSnippetsService();
1585 1478
1586 const base::Time creation = GetDefaultCreationTime(); 1479 const base::Time creation = GetDefaultCreationTime();
1587 const base::Time expiry = GetDefaultExpirationTime(); 1480 const base::Time expiry = GetDefaultExpirationTime();
1588 const std::vector<std::string> source_urls = { 1481 const std::vector<std::string> source_urls = {
1589 "http://mashable.com/2016/05/11/stolen", 1482 "http://mashable.com/2016/05/11/stolen",
1590 "http://www.aol.com/article/2016/05/stolen-doggie"}; 1483 "http://www.aol.com/article/2016/05/stolen-doggie"};
1591 const std::vector<std::string> publishers = {"Mashable", "AOL"}; 1484 const std::vector<std::string> publishers = {"Mashable", "AOL"};
1592 const std::vector<std::string> amp_urls = { 1485 const std::vector<std::string> amp_urls = {
1593 "http://mashable-amphtml.googleusercontent.com/1", 1486 "http://mashable-amphtml.googleusercontent.com/1",
(...skipping 10 matching lines...) Expand all
1604 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1497 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1605 1498
1606 // The same article from the AOL domain should now be detected as dismissed. 1499 // The same article from the AOL domain should now be detected as dismissed.
1607 LoadFromJSONString(service.get(), 1500 LoadFromJSONString(service.get(),
1608 GetTestJson({GetSnippetWithUrlAndTimesAndSource( 1501 GetTestJson({GetSnippetWithUrlAndTimesAndSource(
1609 source_urls, source_urls[1], creation, expiry, 1502 source_urls, source_urls[1], creation, expiry,
1610 publishers[1], amp_urls[1])})); 1503 publishers[1], amp_urls[1])}));
1611 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1504 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1612 } 1505 }
1613 1506
1614 TEST_F(RemoteSuggestionsProviderTest, StatusChanges) { 1507 TEST_F(RemoteSuggestionsProviderImplTest, StatusChanges) {
1615 auto service = MakeSnippetsService(); 1508 auto service = MakeSnippetsService();
1616 1509
1617 // Simulate user signed out 1510 // Simulate user signed out
1618 SetUpFetchResponse(GetTestJson({GetSnippet()})); 1511 SetUpFetchResponse(GetTestJson({GetSnippet()}));
1619 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN, 1512 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
1620 RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED); 1513 RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED);
1621 1514
1622 base::RunLoop().RunUntilIdle(); 1515 base::RunLoop().RunUntilIdle();
1623 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1516 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1624 Eq(CategoryStatus::SIGNED_OUT)); 1517 Eq(CategoryStatus::SIGNED_OUT));
1625 EXPECT_THAT(RemoteSuggestionsProvider::State::DISABLED, Eq(service->state_)); 1518 EXPECT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED,
1519 Eq(service->state_));
1626 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 1520 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1627 IsEmpty()); // No fetch should be made. 1521 IsEmpty()); // No fetch should be made.
1628 1522
1629 // Simulate user sign in. The service should be ready again and load snippets. 1523 // Simulate user sign in. The service should be ready again and load snippets.
1630 SetUpFetchResponse(GetTestJson({GetSnippet()})); 1524 SetUpFetchResponse(GetTestJson({GetSnippet()}));
1631 service->OnStatusChanged(RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED, 1525 service->OnStatusChanged(RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED,
1632 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN); 1526 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);
1633 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1527 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1634 Eq(CategoryStatus::AVAILABLE_LOADING)); 1528 Eq(CategoryStatus::AVAILABLE_LOADING));
1635 1529
1636 base::RunLoop().RunUntilIdle(); 1530 base::RunLoop().RunUntilIdle();
1637 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1531 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1638 Eq(CategoryStatus::AVAILABLE)); 1532 Eq(CategoryStatus::AVAILABLE));
1639 EXPECT_THAT(RemoteSuggestionsProvider::State::READY, Eq(service->state_)); 1533 EXPECT_THAT(RemoteSuggestionsProviderImpl::State::READY, Eq(service->state_));
1640 EXPECT_FALSE(service->GetSnippetsForTesting(articles_category()).empty()); 1534 EXPECT_FALSE(service->GetSnippetsForTesting(articles_category()).empty());
1641 } 1535 }
1642 1536
1643 TEST_F(RemoteSuggestionsProviderTest, ImageReturnedWithTheSameId) { 1537 TEST_F(RemoteSuggestionsProviderImplTest, ImageReturnedWithTheSameId) {
1644 auto service = MakeSnippetsService(); 1538 auto service = MakeSnippetsService();
1645 1539
1646 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1540 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1647 1541
1648 gfx::Image image; 1542 gfx::Image image;
1649 MockFunction<void(const gfx::Image&)> image_fetched; 1543 MockFunction<void(const gfx::Image&)> image_fetched;
1650 ServeImageCallback cb = 1544 ServeImageCallback cb =
1651 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1545 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
1652 { 1546 {
1653 InSequence s; 1547 InSequence s;
1654 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _)) 1548 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _))
1655 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run))); 1549 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run)));
1656 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1550 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1657 } 1551 }
1658 1552
1659 service->FetchSuggestionImage( 1553 service->FetchSuggestionImage(
1660 MakeArticleID(kSnippetUrl), 1554 MakeArticleID(kSnippetUrl),
1661 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1555 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1662 base::Unretained(&image_fetched))); 1556 base::Unretained(&image_fetched)));
1663 base::RunLoop().RunUntilIdle(); 1557 base::RunLoop().RunUntilIdle();
1664 // Check that the image by ServeOneByOneImage is really served. 1558 // Check that the image by ServeOneByOneImage is really served.
1665 EXPECT_EQ(1, image.Width()); 1559 EXPECT_EQ(1, image.Width());
1666 } 1560 }
1667 1561
1668 TEST_F(RemoteSuggestionsProviderTest, EmptyImageReturnedForNonExistentId) { 1562 TEST_F(RemoteSuggestionsProviderImplTest, EmptyImageReturnedForNonExistentId) {
1669 auto service = MakeSnippetsService(); 1563 auto service = MakeSnippetsService();
1670 1564
1671 // Create a non-empty image so that we can test the image gets updated. 1565 // Create a non-empty image so that we can test the image gets updated.
1672 gfx::Image image = gfx::test::CreateImage(1, 1); 1566 gfx::Image image = gfx::test::CreateImage(1, 1);
1673 MockFunction<void(const gfx::Image&)> image_fetched; 1567 MockFunction<void(const gfx::Image&)> image_fetched;
1674 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1568 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1675 1569
1676 service->FetchSuggestionImage( 1570 service->FetchSuggestionImage(
1677 MakeArticleID(kSnippetUrl2), 1571 MakeArticleID(kSnippetUrl2),
1678 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1572 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1679 base::Unretained(&image_fetched))); 1573 base::Unretained(&image_fetched)));
1680 1574
1681 base::RunLoop().RunUntilIdle(); 1575 base::RunLoop().RunUntilIdle();
1682 EXPECT_TRUE(image.IsEmpty()); 1576 EXPECT_TRUE(image.IsEmpty());
1683 } 1577 }
1684 1578
1685 TEST_F(RemoteSuggestionsProviderTest, 1579 TEST_F(RemoteSuggestionsProviderImplTest,
1686 FetchingUnknownImageIdShouldNotHitDatabase) { 1580 FetchingUnknownImageIdShouldNotHitDatabase) {
1687 // Testing that the provider is not accessing the database is tricky. 1581 // Testing that the provider is not accessing the database is tricky.
1688 // Therefore, we simply put in some data making sure that if the provider asks 1582 // Therefore, we simply put in some data making sure that if the provider asks
1689 // the database, it will get a wrong answer. 1583 // the database, it will get a wrong answer.
1690 auto service = MakeSnippetsService(); 1584 auto service = MakeSnippetsService();
1691 1585
1692 ContentSuggestion::ID unknown_id = MakeArticleID(kSnippetUrl2); 1586 ContentSuggestion::ID unknown_id = MakeArticleID(kSnippetUrl2);
1693 database()->SaveImage(unknown_id.id_within_category(), "some image blob"); 1587 database()->SaveImage(unknown_id.id_within_category(), "some image blob");
1694 // Set up the image decoder to always return the 1x1 test image. 1588 // Set up the image decoder to always return the 1x1 test image.
1695 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); 1589 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
1696 1590
1697 // Create a non-empty image so that we can test the image gets updated. 1591 // Create a non-empty image so that we can test the image gets updated.
1698 gfx::Image image = gfx::test::CreateImage(2, 2); 1592 gfx::Image image = gfx::test::CreateImage(2, 2);
1699 MockFunction<void(const gfx::Image&)> image_fetched; 1593 MockFunction<void(const gfx::Image&)> image_fetched;
1700 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1594 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1701 1595
1702 service->FetchSuggestionImage( 1596 service->FetchSuggestionImage(
1703 MakeArticleID(kSnippetUrl2), 1597 MakeArticleID(kSnippetUrl2),
1704 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1598 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1705 base::Unretained(&image_fetched))); 1599 base::Unretained(&image_fetched)));
1706 1600
1707 base::RunLoop().RunUntilIdle(); 1601 base::RunLoop().RunUntilIdle();
1708 EXPECT_TRUE(image.IsEmpty()) << "got image with width: " << image.Width(); 1602 EXPECT_TRUE(image.IsEmpty()) << "got image with width: " << image.Width();
1709 } 1603 }
1710 1604
1711 TEST_F(RemoteSuggestionsProviderTest, ClearHistoryRemovesAllSuggestions) { 1605 TEST_F(RemoteSuggestionsProviderImplTest, ClearHistoryRemovesAllSuggestions) {
1712 auto service = MakeSnippetsService(); 1606 auto service = MakeSnippetsService();
1713 1607
1714 std::string first_snippet = GetSnippetWithUrl("http://url1.com"); 1608 std::string first_snippet = GetSnippetWithUrl("http://url1.com");
1715 std::string second_snippet = GetSnippetWithUrl("http://url2.com"); 1609 std::string second_snippet = GetSnippetWithUrl("http://url2.com");
1716 std::string json_str = GetTestJson({first_snippet, second_snippet}); 1610 std::string json_str = GetTestJson({first_snippet, second_snippet});
1717 LoadFromJSONString(service.get(), json_str); 1611 LoadFromJSONString(service.get(), json_str);
1718 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2)); 1612 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2));
1719 1613
1720 service->DismissSuggestion(MakeArticleID("http://url1.com")); 1614 service->DismissSuggestion(MakeArticleID("http://url1.com"));
1721 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1615 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1722 ASSERT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1616 ASSERT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1723 SizeIs(1)); 1617 SizeIs(1));
1724 1618
1725 base::Time begin = base::Time::FromTimeT(123), 1619 base::Time begin = base::Time::FromTimeT(123),
1726 end = base::Time::FromTimeT(456); 1620 end = base::Time::FromTimeT(456);
1727 base::Callback<bool(const GURL& url)> filter; 1621 base::Callback<bool(const GURL& url)> filter;
1728 service->ClearHistory(begin, end, filter); 1622 service->ClearHistory(begin, end, filter);
1729 1623
1730 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1624 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1731 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1625 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1732 IsEmpty()); 1626 IsEmpty());
1733 } 1627 }
1734 1628
1735 TEST_F(RemoteSuggestionsProviderTest, SuggestionsFetchedOnSignInAndSignOut) { 1629 TEST_F(RemoteSuggestionsProviderImplTest,
1630 SuggestionsFetchedOnSignInAndSignOut) {
1736 auto service = MakeSnippetsService(); 1631 auto service = MakeSnippetsService();
1737 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1632 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1738 1633
1739 // |MakeSnippetsService()| creates a service where user is signed in already, 1634 // |MakeSnippetsService()| creates a service where user is signed in already,
1740 // so we start by signing out. 1635 // so we start by signing out.
1741 SetUpFetchResponse(GetTestJson({GetSnippetN(1)})); 1636 SetUpFetchResponse(GetTestJson({GetSnippetN(1)}));
1742 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN, 1637 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
1743 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT); 1638 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT);
1744 base::RunLoop().RunUntilIdle(); 1639 base::RunLoop().RunUntilIdle();
1745 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1640 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1746 1641
1747 // Sign in to check a transition from signed out to signed in. 1642 // Sign in to check a transition from signed out to signed in.
1748 SetUpFetchResponse(GetTestJson({GetSnippetN(1), GetSnippetN(2)})); 1643 SetUpFetchResponse(GetTestJson({GetSnippetN(1), GetSnippetN(2)}));
1749 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT, 1644 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT,
1750 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN); 1645 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);
1751 base::RunLoop().RunUntilIdle(); 1646 base::RunLoop().RunUntilIdle();
1752 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2)); 1647 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2));
1753 } 1648 }
1754 1649
1755 TEST_F(RemoteSuggestionsProviderTest, ShouldClearOrphanedImagesOnRestart) { 1650 TEST_F(RemoteSuggestionsProviderImplTest, ShouldClearOrphanedImagesOnRestart) {
1756 auto service = MakeSnippetsService(); 1651 auto service = MakeSnippetsService();
1757 1652
1758 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1653 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1759 ServeImageCallback cb = 1654 ServeImageCallback cb =
1760 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1655 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
1761 1656
1762 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _)) 1657 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _))
1763 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run))); 1658 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run)));
1764 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); 1659 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
1765 1660
1766 gfx::Image image = FetchImage(service.get(), MakeArticleID(kSnippetUrl)); 1661 gfx::Image image = FetchImage(service.get(), MakeArticleID(kSnippetUrl));
1767 EXPECT_EQ(1, image.Width()); 1662 EXPECT_EQ(1, image.Width());
1768 EXPECT_FALSE(image.IsEmpty()); 1663 EXPECT_FALSE(image.IsEmpty());
1769 1664
1770 // Send new suggestion which don't include the snippet referencing the image. 1665 // Send new suggestion which don't include the snippet referencing the image.
1771 LoadFromJSONString(service.get(), 1666 LoadFromJSONString(service.get(),
1772 GetTestJson({GetSnippetWithUrl( 1667 GetTestJson({GetSnippetWithUrl(
1773 "http://something.com/pletely/unrelated")})); 1668 "http://something.com/pletely/unrelated")}));
1774 // The image should still be available until a restart happens. 1669 // The image should still be available until a restart happens.
1775 EXPECT_FALSE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1670 EXPECT_FALSE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1776 ResetSnippetsService(&service, /*set_empty_response=*/true); 1671 ResetSnippetsService(&service, /*set_empty_response=*/true);
1777 // After the restart, the image should be garbage collected. 1672 // After the restart, the image should be garbage collected.
1778 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1673 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1779 } 1674 }
1780 1675
1781 TEST_F(RemoteSuggestionsProviderTest, 1676 TEST_F(RemoteSuggestionsProviderImplTest,
1782 ShouldHandleMoreThanMaxSnippetsInResponse) { 1677 ShouldHandleMoreThanMaxSnippetsInResponse) {
1783 auto service = MakeSnippetsService(); 1678 auto service = MakeSnippetsService();
1784 1679
1785 std::vector<std::string> suggestions; 1680 std::vector<std::string> suggestions;
1786 for (int i = 0; i < service->GetMaxSnippetCountForTesting() + 1; ++i) { 1681 for (int i = 0; i < service->GetMaxSnippetCountForTesting() + 1; ++i) {
1787 suggestions.push_back(GetSnippetWithUrl( 1682 suggestions.push_back(GetSnippetWithUrl(
1788 base::StringPrintf("http://localhost/snippet-id-%d", i))); 1683 base::StringPrintf("http://localhost/snippet-id-%d", i)));
1789 } 1684 }
1790 LoadFromJSONString(service.get(), GetTestJson(suggestions)); 1685 LoadFromJSONString(service.get(), GetTestJson(suggestions));
1791 // TODO(tschumann): We should probably trim out any additional results and 1686 // TODO(tschumann): We should probably trim out any additional results and
1792 // only serve the MaxSnippetCount items. 1687 // only serve the MaxSnippetCount items.
1793 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 1688 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1794 SizeIs(service->GetMaxSnippetCountForTesting() + 1)); 1689 SizeIs(service->GetMaxSnippetCountForTesting() + 1));
1795 } 1690 }
1796 1691
1797 TEST_F(RemoteSuggestionsProviderTest, StoreLastSuccessfullBackgroundFetchTime) { 1692 TEST_F(RemoteSuggestionsProviderImplTest,
1798 // On initialization of the RemoteSuggestionsProvider a background fetch is 1693 StoreLastSuccessfullBackgroundFetchTime) {
1799 // triggered since the snippets DB is empty. Therefore the service must not be 1694 // On initialization of the RemoteSuggestionsProviderImpl a background fetch
1800 // initialized until the test clock is set. 1695 // is triggered since the snippets DB is empty. Therefore the service must not
1696 // be initialized until the test clock is set.
1801 auto service = MakeSnippetsServiceWithoutInitialization(); 1697 auto service = MakeSnippetsServiceWithoutInitialization();
1802 1698
1803 auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>(); 1699 auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>();
1804 base::SimpleTestClock* simple_test_clock_ptr = simple_test_clock.get(); 1700 base::SimpleTestClock* simple_test_clock_ptr = simple_test_clock.get();
1805 service->SetClockForTesting(std::move(simple_test_clock)); 1701 service->SetClockForTesting(std::move(simple_test_clock));
1806 1702
1807 // Test that the preference is correctly initialized with the default value 0. 1703 // Test that the preference is correctly initialized with the default value 0.
1808 EXPECT_EQ( 1704 EXPECT_EQ(
1809 0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1705 0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1810 1706
1811 WaitForSnippetsServiceInitialization(service.get(), 1707 WaitForSnippetsServiceInitialization(service.get(),
1812 /*set_empty_response=*/true); 1708 /*set_empty_response=*/true);
1813 EXPECT_EQ( 1709 EXPECT_EQ(
1814 simple_test_clock_ptr->Now().ToInternalValue(), 1710 simple_test_clock_ptr->Now().ToInternalValue(),
1815 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1711 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1816 1712
1817 // Advance the time and check whether the time was updated correctly after the 1713 // Advance the time and check whether the time was updated correctly after the
1818 // background fetch. 1714 // background fetch.
1819 simple_test_clock_ptr->Advance(TimeDelta::FromHours(1)); 1715 simple_test_clock_ptr->Advance(TimeDelta::FromHours(1));
1820 service->FetchSnippetsInTheBackground(); 1716 service->RefetchInTheBackground(
1717 std::unique_ptr<RemoteSuggestionsProvider::FetchStatusCallback>(nullptr));
1821 base::RunLoop().RunUntilIdle(); 1718 base::RunLoop().RunUntilIdle();
1719 // TODO(jkrcal): Move together with the pref storage into the scheduler.
1822 EXPECT_EQ( 1720 EXPECT_EQ(
1823 simple_test_clock_ptr->Now().ToInternalValue(), 1721 simple_test_clock_ptr->Now().ToInternalValue(),
1824 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1722 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1825 // TODO(markusheintz): Add a test that simulates a browser restart once the 1723 // TODO(markusheintz): Add a test that simulates a browser restart once the
1826 // scheduler refactoring is done (crbug.com/672434). 1724 // scheduler refactoring is done (crbug.com/672434).
1827 } 1725 }
1828 1726
1727 TEST_F(RemoteSuggestionsProviderImplTest, CallsProviderStatusCallbackIfReady) {
1728 // Initiate the service so that it is already READY.
1729 auto service = MakeSnippetsService();
1730
1731 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1732 status_callback;
1733 // The callback should be called on registering.
1734 EXPECT_CALL(status_callback,
1735 Call(RemoteSuggestionsProvider::ProviderStatus::ACTIVE));
1736 service->SetProviderStatusCallback(
1737 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1738 base::Bind(&MockFunction<void(
1739 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1740 base::Unretained(&status_callback))));
1741 }
1742
1743 TEST_F(RemoteSuggestionsProviderImplTest,
1744 DoesNotCallProviderStatusCallbackIfNotInited) {
1745 auto service = MakeSnippetsServiceWithoutInitialization();
1746
1747 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1748 status_callback;
1749 // The provider is not initialized yet, no callback should be called on
1750 // registering.
1751 service->SetProviderStatusCallback(
1752 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1753 base::Bind(&MockFunction<void(
1754 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1755 base::Unretained(&status_callback))));
1756 }
1757
1758 TEST_F(RemoteSuggestionsProviderImplTest,
1759 CallsProviderStatusCallbackWhenReady) {
1760 auto service = MakeSnippetsServiceWithoutInitialization();
1761 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1762 status_callback;
1763 service->SetProviderStatusCallback(
1764 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1765 base::Bind(&MockFunction<void(
1766 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1767 base::Unretained(&status_callback))));
1768
1769 // Should be called when becoming ready.
1770 EXPECT_CALL(status_callback,
1771 Call(RemoteSuggestionsProvider::ProviderStatus::ACTIVE));
1772 WaitForSnippetsServiceInitialization(service.get(),
1773 /*set_empty_response=*/true);
1774 }
1775
1776 TEST_F(RemoteSuggestionsProviderImplTest, CallsProviderStatusCallbackOnError) {
1777 auto service = MakeSnippetsServiceWithoutInitialization();
1778 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1779 status_callback;
1780 service->SetProviderStatusCallback(
1781 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1782 base::Bind(&MockFunction<void(
1783 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1784 base::Unretained(&status_callback))));
1785
1786 // Should be called on error.
1787 EXPECT_CALL(status_callback,
1788 Call(RemoteSuggestionsProvider::ProviderStatus::INACTIVE));
1789 service->EnterState(RemoteSuggestionsProviderImpl::State::ERROR_OCCURRED);
1790 }
1791
1792 TEST_F(RemoteSuggestionsProviderImplTest,
1793 CallsProviderStatusCallbackWhenDisabled) {
1794 auto service = MakeSnippetsServiceWithoutInitialization();
1795 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1796 status_callback;
1797 service->SetProviderStatusCallback(
1798 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1799 base::Bind(&MockFunction<void(
1800 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1801 base::Unretained(&status_callback))));
1802
1803 // Should be called when becoming disabled.
1804 EXPECT_CALL(status_callback,
1805 Call(RemoteSuggestionsProvider::ProviderStatus::INACTIVE));
1806 service->EnterState(RemoteSuggestionsProviderImpl::State::DISABLED);
1807 }
1808
1829 } // namespace ntp_snippets 1809 } // namespace ntp_snippets
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698