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

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: Fixing the last changes :) Created 4 years 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(/*interactive_request=*/true,
561 /*callback=*/nullptr);
565 base::RunLoop().RunUntilIdle(); 562 base::RunLoop().RunUntilIdle();
566 } 563 }
567 564
568 void LoadMoreFromJSONString(RemoteSuggestionsProvider* service, 565 void LoadMoreFromJSONString(RemoteSuggestionsProviderImpl* service,
569 const Category& category, 566 const Category& category,
570 const std::string& json, 567 const std::string& json,
571 const std::set<std::string>& known_ids, 568 const std::set<std::string>& known_ids,
572 FetchDoneCallback callback) { 569 FetchDoneCallback callback) {
573 SetUpFetchResponse(json); 570 SetUpFetchResponse(json);
574 service->Fetch(category, known_ids, callback); 571 service->Fetch(category, known_ids, callback);
575 base::RunLoop().RunUntilIdle(); 572 base::RunLoop().RunUntilIdle();
576 } 573 }
577 574
578 private: 575 private:
579 variations::testing::VariationParamsManager params_manager_; 576 variations::testing::VariationParamsManager params_manager_;
580 test::RemoteSuggestionsTestUtils utils_; 577 test::RemoteSuggestionsTestUtils utils_;
581 base::MessageLoop message_loop_; 578 base::MessageLoop message_loop_;
582 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; 579 FailingFakeURLFetcherFactory failing_url_fetcher_factory_;
583 // Instantiation of factory automatically sets itself as URLFetcher's factory. 580 // Instantiation of factory automatically sets itself as URLFetcher's factory.
584 net::FakeURLFetcherFactory fake_url_fetcher_factory_; 581 net::FakeURLFetcherFactory fake_url_fetcher_factory_;
585 const GURL test_url_; 582 const GURL test_url_;
586 std::unique_ptr<OAuth2TokenService> fake_token_service_; 583 std::unique_ptr<OAuth2TokenService> fake_token_service_;
587 std::unique_ptr<CategoryRanker> category_ranker_; 584 std::unique_ptr<CategoryRanker> category_ranker_;
588 UserClassifier user_classifier_; 585 UserClassifier user_classifier_;
589 NiceMock<MockScheduler> scheduler_;
590 std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_; 586 std::unique_ptr<FakeContentSuggestionsProviderObserver> observer_;
591 NiceMock<MockImageFetcher>* image_fetcher_; 587 NiceMock<MockImageFetcher>* image_fetcher_;
592 FakeImageDecoder* image_decoder_; 588 FakeImageDecoder* image_decoder_;
593 589
594 base::ScopedTempDir database_dir_; 590 base::ScopedTempDir database_dir_;
595 RemoteSuggestionsDatabase* database_; 591 RemoteSuggestionsDatabase* database_;
596 592
597 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsProviderTest); 593 DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsProviderImplTest);
598 }; 594 };
599 595
600 TEST_F(RemoteSuggestionsProviderTest, ScheduleOnStart) { 596 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()})); 597 std::string json_str(GetTestJson({GetSnippet()}));
719 598
720 auto service = MakeSnippetsService(); 599 auto service = MakeSnippetsService();
721 600
722 LoadFromJSONString(service.get(), json_str); 601 LoadFromJSONString(service.get(), json_str);
723 602
724 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 603 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
725 SizeIs(1)); 604 SizeIs(1));
726 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 605 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
727 606
728 const ContentSuggestion& suggestion = 607 const ContentSuggestion& suggestion =
729 observer().SuggestionsForCategory(articles_category()).front(); 608 observer().SuggestionsForCategory(articles_category()).front();
730 609
731 EXPECT_EQ(MakeArticleID(kSnippetUrl), suggestion.id()); 610 EXPECT_EQ(MakeArticleID(kSnippetUrl), suggestion.id());
732 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); 611 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title()));
733 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); 612 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text()));
734 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); 613 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
735 EXPECT_EQ(kSnippetPublisherName, 614 EXPECT_EQ(kSnippetPublisherName,
736 base::UTF16ToUTF8(suggestion.publisher_name())); 615 base::UTF16ToUTF8(suggestion.publisher_name()));
737 } 616 }
738 617
739 TEST_F(RemoteSuggestionsProviderTest, CategoryTitle) { 618 TEST_F(RemoteSuggestionsProviderImplTest, CategoryTitle) {
740 const base::string16 test_default_title = 619 const base::string16 test_default_title =
741 base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle); 620 base::UTF8ToUTF16(kTestJsonDefaultCategoryTitle);
742 621
743 // Don't send an initial response -- we want to test what happens without any 622 // Don't send an initial response -- we want to test what happens without any
744 // server status. 623 // server status.
745 auto service = MakeSnippetsService(/*set_empty_response=*/false); 624 auto service = MakeSnippetsService(/*set_empty_response=*/false);
746 625
747 // The articles category should be there by default, and have a title. 626 // The articles category should be there by default, and have a title.
748 CategoryInfo info_before = service->GetCategoryInfo(articles_category()); 627 CategoryInfo info_before = service->GetCategoryInfo(articles_category());
749 ASSERT_THAT(info_before.title(), Not(IsEmpty())); 628 ASSERT_THAT(info_before.title(), Not(IsEmpty()));
(...skipping 14 matching lines...) Expand all
764 // Make sure we updated the title in the CategoryInfo. 643 // Make sure we updated the title in the CategoryInfo.
765 CategoryInfo info_with_title = service->GetCategoryInfo(articles_category()); 644 CategoryInfo info_with_title = service->GetCategoryInfo(articles_category());
766 EXPECT_THAT(info_before.title(), Not(Eq(info_with_title.title()))); 645 EXPECT_THAT(info_before.title(), Not(Eq(info_with_title.title())));
767 EXPECT_THAT(test_default_title, Eq(info_with_title.title())); 646 EXPECT_THAT(test_default_title, Eq(info_with_title.title()));
768 EXPECT_THAT(info_before.has_more_action(), Eq(true)); 647 EXPECT_THAT(info_before.has_more_action(), Eq(true));
769 EXPECT_THAT(info_before.has_reload_action(), Eq(true)); 648 EXPECT_THAT(info_before.has_reload_action(), Eq(true));
770 EXPECT_THAT(info_before.has_view_all_action(), Eq(false)); 649 EXPECT_THAT(info_before.has_view_all_action(), Eq(false));
771 EXPECT_THAT(info_before.show_if_empty(), Eq(true)); 650 EXPECT_THAT(info_before.show_if_empty(), Eq(true));
772 } 651 }
773 652
774 TEST_F(RemoteSuggestionsProviderTest, MultipleCategories) { 653 TEST_F(RemoteSuggestionsProviderImplTest, MultipleCategories) {
775 auto service = MakeSnippetsService(); 654 auto service = MakeSnippetsService();
776 std::string json_str = 655 std::string json_str =
777 MultiCategoryJsonBuilder() 656 MultiCategoryJsonBuilder()
778 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 657 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
779 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2) 658 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2)
780 .Build(); 659 .Build();
781 LoadFromJSONString(service.get(), json_str); 660 LoadFromJSONString(service.get(), json_str);
782 661
783 ASSERT_THAT(observer().statuses(), 662 ASSERT_THAT(observer().statuses(),
784 Eq(std::map<Category, CategoryStatus, Category::CompareByID>{ 663 Eq(std::map<Category, CategoryStatus, Category::CompareByID>{
(...skipping 25 matching lines...) Expand all
810 observer().SuggestionsForCategory(other_category()).front(); 689 observer().SuggestionsForCategory(other_category()).front();
811 EXPECT_EQ(MakeOtherID(std::string(kSnippetUrl) + "/1"), suggestion.id()); 690 EXPECT_EQ(MakeOtherID(std::string(kSnippetUrl) + "/1"), suggestion.id());
812 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title())); 691 EXPECT_EQ(kSnippetTitle, base::UTF16ToUTF8(suggestion.title()));
813 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text())); 692 EXPECT_EQ(kSnippetText, base::UTF16ToUTF8(suggestion.snippet_text()));
814 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date()); 693 EXPECT_EQ(GetDefaultCreationTime(), suggestion.publish_date());
815 EXPECT_EQ(kSnippetPublisherName, 694 EXPECT_EQ(kSnippetPublisherName,
816 base::UTF16ToUTF8(suggestion.publisher_name())); 695 base::UTF16ToUTF8(suggestion.publisher_name()));
817 } 696 }
818 } 697 }
819 698
820 TEST_F(RemoteSuggestionsProviderTest, ArticleCategoryInfo) { 699 TEST_F(RemoteSuggestionsProviderImplTest, ArticleCategoryInfo) {
821 auto service = MakeSnippetsService(); 700 auto service = MakeSnippetsService();
822 CategoryInfo article_info = service->GetCategoryInfo(articles_category()); 701 CategoryInfo article_info = service->GetCategoryInfo(articles_category());
823 EXPECT_THAT(article_info.has_more_action(), Eq(true)); 702 EXPECT_THAT(article_info.has_more_action(), Eq(true));
824 EXPECT_THAT(article_info.has_reload_action(), Eq(true)); 703 EXPECT_THAT(article_info.has_reload_action(), Eq(true));
825 EXPECT_THAT(article_info.has_view_all_action(), Eq(false)); 704 EXPECT_THAT(article_info.has_view_all_action(), Eq(false));
826 EXPECT_THAT(article_info.show_if_empty(), Eq(true)); 705 EXPECT_THAT(article_info.show_if_empty(), Eq(true));
827 } 706 }
828 707
829 TEST_F(RemoteSuggestionsProviderTest, ExperimentalCategoryInfo) { 708 TEST_F(RemoteSuggestionsProviderImplTest, ExperimentalCategoryInfo) {
830 auto service = MakeSnippetsService(); 709 auto service = MakeSnippetsService();
831 std::string json_str = 710 std::string json_str =
832 MultiCategoryJsonBuilder() 711 MultiCategoryJsonBuilder()
833 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 712 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
834 .AddCategory({GetSnippetN(1)}, kUnknownRemoteCategoryId) 713 .AddCategory({GetSnippetN(1)}, kUnknownRemoteCategoryId)
835 .Build(); 714 .Build();
836 // Load data with multiple categories so that a new experimental category gets 715 // Load data with multiple categories so that a new experimental category gets
837 // registered. 716 // registered.
838 LoadFromJSONString(service.get(), json_str); 717 LoadFromJSONString(service.get(), json_str);
839 718
840 CategoryInfo info = service->GetCategoryInfo(unknown_category()); 719 CategoryInfo info = service->GetCategoryInfo(unknown_category());
841 EXPECT_THAT(info.has_more_action(), Eq(false)); 720 EXPECT_THAT(info.has_more_action(), Eq(false));
842 EXPECT_THAT(info.has_reload_action(), Eq(false)); 721 EXPECT_THAT(info.has_reload_action(), Eq(false));
843 EXPECT_THAT(info.has_view_all_action(), Eq(false)); 722 EXPECT_THAT(info.has_view_all_action(), Eq(false));
844 EXPECT_THAT(info.show_if_empty(), Eq(false)); 723 EXPECT_THAT(info.show_if_empty(), Eq(false));
845 } 724 }
846 725
847 TEST_F(RemoteSuggestionsProviderTest, AddRemoteCategoriesToCategoryRanker) { 726 TEST_F(RemoteSuggestionsProviderImplTest, AddRemoteCategoriesToCategoryRanker) {
848 auto mock_ranker = base::MakeUnique<MockCategoryRanker>(); 727 auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
849 MockCategoryRanker* raw_mock_ranker = mock_ranker.get(); 728 MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
850 SetCategoryRanker(std::move(mock_ranker)); 729 SetCategoryRanker(std::move(mock_ranker));
851 std::string json_str = 730 std::string json_str =
852 MultiCategoryJsonBuilder() 731 MultiCategoryJsonBuilder()
853 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11) 732 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11)
854 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13) 733 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13)
855 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12) 734 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12)
856 .Build(); 735 .Build();
857 SetUpFetchResponse(json_str); 736 SetUpFetchResponse(json_str);
858 { 737 {
859 // The order of categories is determined by the order in which they are 738 // The order of categories is determined by the order in which they are
860 // added. Thus, the latter is tested here. 739 // added. Thus, the latter is tested here.
861 InSequence s; 740 InSequence s;
862 EXPECT_CALL(*raw_mock_ranker, 741 EXPECT_CALL(*raw_mock_ranker,
863 AppendCategoryIfNecessary(Category::FromRemoteCategory(11))); 742 AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
864 EXPECT_CALL(*raw_mock_ranker, 743 EXPECT_CALL(*raw_mock_ranker,
865 AppendCategoryIfNecessary(Category::FromRemoteCategory(13))); 744 AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
866 EXPECT_CALL(*raw_mock_ranker, 745 EXPECT_CALL(*raw_mock_ranker,
867 AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); 746 AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
868 } 747 }
869 auto service = MakeSnippetsService(/*set_empty_response=*/false); 748 auto service = MakeSnippetsService(/*set_empty_response=*/false);
870 } 749 }
871 750
872 TEST_F(RemoteSuggestionsProviderTest, PersistCategoryInfos) { 751 TEST_F(RemoteSuggestionsProviderImplTest, PersistCategoryInfos) {
873 auto service = MakeSnippetsService(); 752 auto service = MakeSnippetsService();
874 // TODO(vitaliii): Use |articles_category()| instead of constant ID below. 753 // TODO(vitaliii): Use |articles_category()| instead of constant ID below.
875 std::string json_str = 754 std::string json_str =
876 MultiCategoryJsonBuilder() 755 MultiCategoryJsonBuilder()
877 .AddCategoryWithCustomTitle( 756 .AddCategoryWithCustomTitle(
878 {GetSnippetN(0)}, /*remote_category_id=*/1, "Articles for You") 757 {GetSnippetN(0)}, /*remote_category_id=*/1, "Articles for You")
879 .AddCategoryWithCustomTitle({GetSnippetN(1)}, 758 .AddCategoryWithCustomTitle({GetSnippetN(1)},
880 kUnknownRemoteCategoryId, "Other Things") 759 kUnknownRemoteCategoryId, "Other Things")
881 .Build(); 760 .Build();
882 LoadFromJSONString(service.get(), json_str); 761 LoadFromJSONString(service.get(), json_str);
(...skipping 24 matching lines...) Expand all
907 786
908 CategoryInfo info_articles_after = 787 CategoryInfo info_articles_after =
909 service->GetCategoryInfo(articles_category()); 788 service->GetCategoryInfo(articles_category());
910 CategoryInfo info_unknown_after = 789 CategoryInfo info_unknown_after =
911 service->GetCategoryInfo(unknown_category()); 790 service->GetCategoryInfo(unknown_category());
912 791
913 EXPECT_EQ(info_articles_before.title(), info_articles_after.title()); 792 EXPECT_EQ(info_articles_before.title(), info_articles_after.title());
914 EXPECT_EQ(info_unknown_before.title(), info_unknown_after.title()); 793 EXPECT_EQ(info_unknown_before.title(), info_unknown_after.title());
915 } 794 }
916 795
917 TEST_F(RemoteSuggestionsProviderTest, PersistRemoteCategoryOrder) { 796 TEST_F(RemoteSuggestionsProviderImplTest, PersistRemoteCategoryOrder) {
918 // We create a service with a normal ranker to store the order. 797 // We create a service with a normal ranker to store the order.
919 std::string json_str = 798 std::string json_str =
920 MultiCategoryJsonBuilder() 799 MultiCategoryJsonBuilder()
921 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11) 800 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/11)
922 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13) 801 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/13)
923 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12) 802 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/12)
924 .Build(); 803 .Build();
925 SetUpFetchResponse(json_str); 804 SetUpFetchResponse(json_str);
926 auto service = MakeSnippetsService(/*set_empty_response=*/false); 805 auto service = MakeSnippetsService(/*set_empty_response=*/false);
927 806
(...skipping 15 matching lines...) Expand all
943 EXPECT_CALL(*raw_mock_ranker, 822 EXPECT_CALL(*raw_mock_ranker,
944 AppendCategoryIfNecessary(Category::FromRemoteCategory(11))); 823 AppendCategoryIfNecessary(Category::FromRemoteCategory(11)));
945 EXPECT_CALL(*raw_mock_ranker, 824 EXPECT_CALL(*raw_mock_ranker,
946 AppendCategoryIfNecessary(Category::FromRemoteCategory(13))); 825 AppendCategoryIfNecessary(Category::FromRemoteCategory(13)));
947 EXPECT_CALL(*raw_mock_ranker, 826 EXPECT_CALL(*raw_mock_ranker,
948 AppendCategoryIfNecessary(Category::FromRemoteCategory(12))); 827 AppendCategoryIfNecessary(Category::FromRemoteCategory(12)));
949 } 828 }
950 ResetSnippetsService(&service, /*set_empty_response=*/false); 829 ResetSnippetsService(&service, /*set_empty_response=*/false);
951 } 830 }
952 831
953 TEST_F(RemoteSuggestionsProviderTest, PersistSuggestions) { 832 TEST_F(RemoteSuggestionsProviderImplTest, PersistSuggestions) {
954 auto service = MakeSnippetsService(); 833 auto service = MakeSnippetsService();
955 std::string json_str = 834 std::string json_str =
956 MultiCategoryJsonBuilder() 835 MultiCategoryJsonBuilder()
957 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1) 836 .AddCategory({GetSnippetN(0)}, /*remote_category_id=*/1)
958 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/2) 837 .AddCategory({GetSnippetN(2)}, /*remote_category_id=*/2)
959 .Build(); 838 .Build();
960 LoadFromJSONString(service.get(), json_str); 839 LoadFromJSONString(service.get(), json_str);
961 840
962 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 841 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
963 SizeIs(1)); 842 SizeIs(1));
964 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 843 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
965 844
966 // Recreate the service to simulate a Chrome restart. 845 // Recreate the service to simulate a Chrome restart.
967 ResetSnippetsService(&service, /*set_empty_response=*/true); 846 ResetSnippetsService(&service, /*set_empty_response=*/true);
968 847
969 // The suggestions in both categories should have been restored. 848 // The suggestions in both categories should have been restored.
970 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), 849 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
971 SizeIs(1)); 850 SizeIs(1));
972 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 851 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
973 } 852 }
974 853
975 TEST_F(RemoteSuggestionsProviderTest, DontNotifyIfNotAvailable) { 854 TEST_F(RemoteSuggestionsProviderImplTest, DontNotifyIfNotAvailable) {
976 // Get some suggestions into the database. 855 // Get some suggestions into the database.
977 auto service = MakeSnippetsService(); 856 auto service = MakeSnippetsService();
978 std::string json_str = 857 std::string json_str =
979 MultiCategoryJsonBuilder() 858 MultiCategoryJsonBuilder()
980 .AddCategory({GetSnippetN(0)}, 859 .AddCategory({GetSnippetN(0)},
981 /*remote_category_id=*/1) 860 /*remote_category_id=*/1)
982 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2) 861 .AddCategory({GetSnippetN(1)}, /*remote_category_id=*/2)
983 .Build(); 862 .Build();
984 LoadFromJSONString(service.get(), json_str); 863 LoadFromJSONString(service.get(), json_str);
985 864
986 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()), 865 ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
987 SizeIs(1)); 866 SizeIs(1));
988 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1)); 867 ASSERT_THAT(observer().SuggestionsForCategory(other_category()), SizeIs(1));
989 868
990 service.reset(); 869 service.reset();
991 870
992 // Set the pref that disables remote suggestions. 871 // Set the pref that disables remote suggestions.
993 pref_service()->SetBoolean(prefs::kEnableSnippets, false); 872 pref_service()->SetBoolean(prefs::kEnableSnippets, false);
994 873
995 // Recreate the service to simulate a Chrome start. 874 // Recreate the service to simulate a Chrome start.
996 ResetSnippetsService(&service, /*set_empty_response=*/true); 875 ResetSnippetsService(&service, /*set_empty_response=*/true);
997 876
998 ASSERT_THAT(RemoteSuggestionsProvider::State::DISABLED, Eq(service->state_)); 877 ASSERT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED,
878 Eq(service->state_));
999 879
1000 // Now the observer should not have received any suggestions. 880 // Now the observer should not have received any suggestions.
1001 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()), 881 EXPECT_THAT(observer().SuggestionsForCategory(articles_category()),
1002 IsEmpty()); 882 IsEmpty());
1003 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), IsEmpty()); 883 EXPECT_THAT(observer().SuggestionsForCategory(other_category()), IsEmpty());
1004 } 884 }
1005 885
1006 TEST_F(RemoteSuggestionsProviderTest, Clear) { 886 TEST_F(RemoteSuggestionsProviderImplTest, Clear) {
1007 auto service = MakeSnippetsService(); 887 auto service = MakeSnippetsService();
1008 888
1009 std::string json_str(GetTestJson({GetSnippet()})); 889 std::string json_str(GetTestJson({GetSnippet()}));
1010 890
1011 LoadFromJSONString(service.get(), json_str); 891 LoadFromJSONString(service.get(), json_str);
1012 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 892 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1013 893
1014 service->ClearCachedSuggestions(articles_category()); 894 service->ClearCachedSuggestions(articles_category());
1015 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 895 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1016 } 896 }
1017 897
1018 TEST_F(RemoteSuggestionsProviderTest, ReplaceSnippets) { 898 TEST_F(RemoteSuggestionsProviderImplTest, ReplaceSnippets) {
1019 auto service = MakeSnippetsService(); 899 auto service = MakeSnippetsService();
1020 900
1021 std::string first("http://first"); 901 std::string first("http://first");
1022 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(first)})); 902 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(first)}));
1023 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 903 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1024 ElementsAre(IdEq(first))); 904 ElementsAre(IdEq(first)));
1025 905
1026 std::string second("http://second"); 906 std::string second("http://second");
1027 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(second)})); 907 LoadFromJSONString(service.get(), GetTestJson({GetSnippetWithUrl(second)}));
1028 // The snippets loaded last replace all that was loaded previously. 908 // The snippets loaded last replace all that was loaded previously.
1029 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 909 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1030 ElementsAre(IdEq(second))); 910 ElementsAre(IdEq(second)));
1031 } 911 }
1032 912
1033 TEST_F(RemoteSuggestionsProviderTest, LoadsAdditionalSnippets) { 913 TEST_F(RemoteSuggestionsProviderImplTest, LoadsAdditionalSnippets) {
1034 auto service = MakeSnippetsService(); 914 auto service = MakeSnippetsService();
1035 915
1036 LoadFromJSONString(service.get(), 916 LoadFromJSONString(service.get(),
1037 GetTestJson({GetSnippetWithUrl("http://first")})); 917 GetTestJson({GetSnippetWithUrl("http://first")}));
1038 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 918 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1039 ElementsAre(IdEq("http://first"))); 919 ElementsAre(IdEq("http://first")));
1040 920
1041 auto expect_only_second_suggestion_received = base::Bind([]( 921 auto expect_only_second_suggestion_received = base::Bind([](
1042 Status status, std::vector<ContentSuggestion> suggestions) { 922 Status status, std::vector<ContentSuggestion> suggestions) {
1043 EXPECT_THAT(suggestions, SizeIs(1)); 923 EXPECT_THAT(suggestions, SizeIs(1));
(...skipping 29 matching lines...) Expand all
1073 // The tests TestMergingFetchedMoreSnippetsFillup and 953 // The tests TestMergingFetchedMoreSnippetsFillup and
1074 // TestMergingFetchedMoreSnippetsReplaceAll simulate the following user story: 954 // TestMergingFetchedMoreSnippetsReplaceAll simulate the following user story:
1075 // 1) fetch suggestions in NTP A 955 // 1) fetch suggestions in NTP A
1076 // 2) fetch more suggestions in NTP A. 956 // 2) fetch more suggestions in NTP A.
1077 // 3) open new NTP B: See the last 10 results visible in step 2). 957 // 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 958 // 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. 959 // 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 960 // 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 961 // internal 'dismissed' data. The proper check is to make sure we tell the
1082 // backend to exclude these snippets. 962 // backend to exclude these snippets.
1083 TEST_F(RemoteSuggestionsProviderTest, TestMergingFetchedMoreSnippetsFillup) { 963 TEST_F(RemoteSuggestionsProviderImplTest,
964 TestMergingFetchedMoreSnippetsFillup) {
1084 auto service = MakeSnippetsService(/*set_empty_response=*/false); 965 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1085 LoadFromJSONString( 966 LoadFromJSONString(
1086 service.get(), 967 service.get(),
1087 GetTestJson( 968 GetTestJson(
1088 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"), 969 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"),
1089 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"), 970 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"),
1090 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"), 971 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"),
1091 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"), 972 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"),
1092 GetSnippetWithUrl("http://id-9"), 973 GetSnippetWithUrl("http://id-9"),
1093 GetSnippetWithUrl("http://id-10")})); 974 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"), 1007 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"),
1127 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"), 1008 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"),
1128 IdWithinCategoryEq("http://id-9"), IdWithinCategoryEq("http://id-10"), 1009 IdWithinCategoryEq("http://id-9"), IdWithinCategoryEq("http://id-10"),
1129 IdWithinCategoryEq("http://more-id-1"), 1010 IdWithinCategoryEq("http://more-id-1"),
1130 IdWithinCategoryEq("http://more-id-2"))); 1011 IdWithinCategoryEq("http://more-id-2")));
1131 // Verify the superseded suggestions got marked as dismissed. 1012 // Verify the superseded suggestions got marked as dismissed.
1132 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1013 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1133 ElementsAre(IdEq("http://id-1"), IdEq("http://id-2"))); 1014 ElementsAre(IdEq("http://id-1"), IdEq("http://id-2")));
1134 } 1015 }
1135 1016
1136 TEST_F(RemoteSuggestionsProviderTest, 1017 TEST_F(RemoteSuggestionsProviderImplTest,
1137 TestMergingFetchedMoreSnippetsReplaceAll) { 1018 TestMergingFetchedMoreSnippetsReplaceAll) {
1138 auto service = MakeSnippetsService(/*set_empty_response=*/false); 1019 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1139 LoadFromJSONString( 1020 LoadFromJSONString(
1140 service.get(), 1021 service.get(),
1141 GetTestJson( 1022 GetTestJson(
1142 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"), 1023 {GetSnippetWithUrl("http://id-1"), GetSnippetWithUrl("http://id-2"),
1143 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"), 1024 GetSnippetWithUrl("http://id-3"), GetSnippetWithUrl("http://id-4"),
1144 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"), 1025 GetSnippetWithUrl("http://id-5"), GetSnippetWithUrl("http://id-6"),
1145 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"), 1026 GetSnippetWithUrl("http://id-7"), GetSnippetWithUrl("http://id-8"),
1146 GetSnippetWithUrl("http://id-9"), 1027 GetSnippetWithUrl("http://id-9"),
1147 GetSnippetWithUrl("http://id-10")})); 1028 GetSnippetWithUrl("http://id-10")}));
1148 EXPECT_THAT( 1029 EXPECT_THAT(
1149 observer().SuggestionsForCategory(articles_category()), 1030 observer().SuggestionsForCategory(articles_category()),
1150 ElementsAre( 1031 ElementsAre(
1151 IdWithinCategoryEq("http://id-1"), IdWithinCategoryEq("http://id-2"), 1032 IdWithinCategoryEq("http://id-1"), IdWithinCategoryEq("http://id-2"),
1152 IdWithinCategoryEq("http://id-3"), IdWithinCategoryEq("http://id-4"), 1033 IdWithinCategoryEq("http://id-3"), IdWithinCategoryEq("http://id-4"),
1153 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"), 1034 IdWithinCategoryEq("http://id-5"), IdWithinCategoryEq("http://id-6"),
1154 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"), 1035 IdWithinCategoryEq("http://id-7"), IdWithinCategoryEq("http://id-8"),
1155 IdWithinCategoryEq("http://id-9"), 1036 IdWithinCategoryEq("http://id-9"),
1156 IdWithinCategoryEq("http://id-10"))); 1037 IdWithinCategoryEq("http://id-10")));
1157 1038
1158 auto expect_receiving_ten_new_snippets = 1039 auto expect_receiving_ten_new_snippets =
1159 base::Bind([](Status status, std::vector<ContentSuggestion> suggestions) { 1040 base::Bind([](Status status, std::vector<ContentSuggestion> suggestions) {
1160 EXPECT_THAT(suggestions, ElementsAre( 1041 EXPECT_THAT(suggestions,
1161 IdWithinCategoryEq("http://more-id-1"), 1042 ElementsAre(IdWithinCategoryEq("http://more-id-1"),
1162 IdWithinCategoryEq("http://more-id-2"), 1043 IdWithinCategoryEq("http://more-id-2"),
1163 IdWithinCategoryEq("http://more-id-3"), 1044 IdWithinCategoryEq("http://more-id-3"),
1164 IdWithinCategoryEq("http://more-id-4"), 1045 IdWithinCategoryEq("http://more-id-4"),
1165 IdWithinCategoryEq("http://more-id-5"), 1046 IdWithinCategoryEq("http://more-id-5"),
1166 IdWithinCategoryEq("http://more-id-6"), 1047 IdWithinCategoryEq("http://more-id-6"),
1167 IdWithinCategoryEq("http://more-id-7"), 1048 IdWithinCategoryEq("http://more-id-7"),
1168 IdWithinCategoryEq("http://more-id-8"), 1049 IdWithinCategoryEq("http://more-id-8"),
1169 IdWithinCategoryEq("http://more-id-9"), 1050 IdWithinCategoryEq("http://more-id-9"),
1170 IdWithinCategoryEq("http://more-id-10"))); 1051 IdWithinCategoryEq("http://more-id-10")));
1171 }); 1052 });
1172 LoadMoreFromJSONString( 1053 LoadMoreFromJSONString(
1173 service.get(), articles_category(), 1054 service.get(), articles_category(),
1174 GetTestJson({GetSnippetWithUrl("http://more-id-1"), 1055 GetTestJson({GetSnippetWithUrl("http://more-id-1"),
1175 GetSnippetWithUrl("http://more-id-2"), 1056 GetSnippetWithUrl("http://more-id-2"),
1176 GetSnippetWithUrl("http://more-id-3"), 1057 GetSnippetWithUrl("http://more-id-3"),
1177 GetSnippetWithUrl("http://more-id-4"), 1058 GetSnippetWithUrl("http://more-id-4"),
1178 GetSnippetWithUrl("http://more-id-5"), 1059 GetSnippetWithUrl("http://more-id-5"),
1179 GetSnippetWithUrl("http://more-id-6"), 1060 GetSnippetWithUrl("http://more-id-6"),
1180 GetSnippetWithUrl("http://more-id-7"), 1061 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. 1096 // Workaround for gMock's lack of support for movable types.
1216 void SuggestionsLoaded( 1097 void SuggestionsLoaded(
1217 MockFunction<void(Status, const std::vector<ContentSuggestion>&)>* loaded, 1098 MockFunction<void(Status, const std::vector<ContentSuggestion>&)>* loaded,
1218 Status status, 1099 Status status,
1219 std::vector<ContentSuggestion> suggestions) { 1100 std::vector<ContentSuggestion> suggestions) {
1220 loaded->Call(status, suggestions); 1101 loaded->Call(status, suggestions);
1221 } 1102 }
1222 1103
1223 } // namespace 1104 } // namespace
1224 1105
1225 TEST_F(RemoteSuggestionsProviderTest, ReturnFetchRequestEmptyBeforeInit) { 1106 TEST_F(RemoteSuggestionsProviderImplTest, ReturnFetchRequestEmptyBeforeInit) {
1226 auto service = MakeSnippetsServiceWithoutInitialization(); 1107 auto service = MakeSnippetsServiceWithoutInitialization();
1227 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1108 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1228 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1109 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1229 service->Fetch(articles_category(), std::set<std::string>(), 1110 service->Fetch(articles_category(), std::set<std::string>(),
1230 base::Bind(&SuggestionsLoaded, &loaded)); 1111 base::Bind(&SuggestionsLoaded, &loaded));
1231 base::RunLoop().RunUntilIdle(); 1112 base::RunLoop().RunUntilIdle();
1232 } 1113 }
1233 1114
1234 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForInvalidJson) { 1115 TEST_F(RemoteSuggestionsProviderImplTest, ReturnTemporaryErrorForInvalidJson) {
1235 auto service = MakeSnippetsService(); 1116 auto service = MakeSnippetsService();
1236 1117
1237 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1118 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1238 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1119 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1239 LoadMoreFromJSONString(service.get(), articles_category(), 1120 LoadMoreFromJSONString(service.get(), articles_category(),
1240 "invalid json string}]}", 1121 "invalid json string}]}",
1241 /*known_ids=*/std::set<std::string>(), 1122 /*known_ids=*/std::set<std::string>(),
1242 base::Bind(&SuggestionsLoaded, &loaded)); 1123 base::Bind(&SuggestionsLoaded, &loaded));
1243 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1124 EXPECT_THAT(
1244 StartsWith("Received invalid JSON")); 1125 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1126 StartsWith("Received invalid JSON"));
1245 } 1127 }
1246 1128
1247 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForInvalidSnippet) { 1129 TEST_F(RemoteSuggestionsProviderImplTest,
1130 ReturnTemporaryErrorForInvalidSnippet) {
1248 auto service = MakeSnippetsService(); 1131 auto service = MakeSnippetsService();
1249 1132
1250 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1133 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1251 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1134 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1252 LoadMoreFromJSONString(service.get(), articles_category(), 1135 LoadMoreFromJSONString(service.get(), articles_category(),
1253 GetTestJson({GetIncompleteSnippet()}), 1136 GetTestJson({GetIncompleteSnippet()}),
1254 /*known_ids=*/std::set<std::string>(), 1137 /*known_ids=*/std::set<std::string>(),
1255 base::Bind(&SuggestionsLoaded, &loaded)); 1138 base::Bind(&SuggestionsLoaded, &loaded));
1256 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1139 EXPECT_THAT(
1257 StartsWith("Invalid / empty list")); 1140 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1141 StartsWith("Invalid / empty list"));
1258 } 1142 }
1259 1143
1260 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForRequestFailure) { 1144 TEST_F(RemoteSuggestionsProviderImplTest,
1145 ReturnTemporaryErrorForRequestFailure) {
1261 // Created SnippetsService will fail by default with unsuccessful request. 1146 // Created SnippetsService will fail by default with unsuccessful request.
1262 auto service = MakeSnippetsService(/*set_empty_response=*/false); 1147 auto service = MakeSnippetsService(/*set_empty_response=*/false);
1263 1148
1264 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1149 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1265 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1150 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1266 service->Fetch(articles_category(), 1151 service->Fetch(articles_category(),
1267 /*known_ids=*/std::set<std::string>(), 1152 /*known_ids=*/std::set<std::string>(),
1268 base::Bind(&SuggestionsLoaded, &loaded)); 1153 base::Bind(&SuggestionsLoaded, &loaded));
1269 base::RunLoop().RunUntilIdle(); 1154 base::RunLoop().RunUntilIdle();
1270 } 1155 }
1271 1156
1272 TEST_F(RemoteSuggestionsProviderTest, ReturnTemporaryErrorForHttpFailure) { 1157 TEST_F(RemoteSuggestionsProviderImplTest, ReturnTemporaryErrorForHttpFailure) {
1273 auto service = MakeSnippetsService(); 1158 auto service = MakeSnippetsService();
1274 SetUpHttpError(); 1159 SetUpHttpError();
1275 1160
1276 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded; 1161 MockFunction<void(Status, const std::vector<ContentSuggestion>&)> loaded;
1277 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty())); 1162 EXPECT_CALL(loaded, Call(HasCode(StatusCode::TEMPORARY_ERROR), IsEmpty()));
1278 service->Fetch(articles_category(), 1163 service->Fetch(articles_category(),
1279 /*known_ids=*/std::set<std::string>(), 1164 /*known_ids=*/std::set<std::string>(),
1280 base::Bind(&SuggestionsLoaded, &loaded)); 1165 base::Bind(&SuggestionsLoaded, &loaded));
1281 base::RunLoop().RunUntilIdle(); 1166 base::RunLoop().RunUntilIdle();
1282 } 1167 }
1283 1168
1284 TEST_F(RemoteSuggestionsProviderTest, LoadInvalidJson) { 1169 TEST_F(RemoteSuggestionsProviderImplTest, LoadInvalidJson) {
1285 auto service = MakeSnippetsService(); 1170 auto service = MakeSnippetsService();
1286 1171
1287 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1172 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1288 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1173 EXPECT_THAT(
1289 StartsWith("Received invalid JSON")); 1174 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1175 StartsWith("Received invalid JSON"));
1290 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1176 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1291 } 1177 }
1292 1178
1293 TEST_F(RemoteSuggestionsProviderTest, LoadInvalidJsonWithExistingSnippets) { 1179 TEST_F(RemoteSuggestionsProviderImplTest, LoadInvalidJsonWithExistingSnippets) {
1294 auto service = MakeSnippetsService(); 1180 auto service = MakeSnippetsService();
1295 1181
1296 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1182 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1297 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1183 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1298 ASSERT_EQ("OK", service->snippets_fetcher()->last_status()); 1184 ASSERT_EQ(
1185 "OK",
1186 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1299 1187
1300 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1188 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1301 EXPECT_THAT(service->snippets_fetcher()->last_status(), 1189 EXPECT_THAT(
1302 StartsWith("Received invalid JSON")); 1190 service->snippets_fetcher_for_testing_and_debugging()->last_status(),
1191 StartsWith("Received invalid JSON"));
1303 // This should not have changed the existing snippets. 1192 // This should not have changed the existing snippets.
1304 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1193 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1305 } 1194 }
1306 1195
1307 TEST_F(RemoteSuggestionsProviderTest, LoadIncompleteJson) { 1196 TEST_F(RemoteSuggestionsProviderImplTest, LoadIncompleteJson) {
1308 auto service = MakeSnippetsService(); 1197 auto service = MakeSnippetsService();
1309 1198
1310 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); 1199 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()}));
1311 EXPECT_EQ("Invalid / empty list.", 1200 EXPECT_EQ(
1312 service->snippets_fetcher()->last_status()); 1201 "Invalid / empty list.",
1202 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1313 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1203 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1314 } 1204 }
1315 1205
1316 TEST_F(RemoteSuggestionsProviderTest, LoadIncompleteJsonWithExistingSnippets) { 1206 TEST_F(RemoteSuggestionsProviderImplTest,
1207 LoadIncompleteJsonWithExistingSnippets) {
1317 auto service = MakeSnippetsService(); 1208 auto service = MakeSnippetsService();
1318 1209
1319 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1210 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1320 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1211 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1321 1212
1322 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()})); 1213 LoadFromJSONString(service.get(), GetTestJson({GetIncompleteSnippet()}));
1323 EXPECT_EQ("Invalid / empty list.", 1214 EXPECT_EQ(
1324 service->snippets_fetcher()->last_status()); 1215 "Invalid / empty list.",
1216 service->snippets_fetcher_for_testing_and_debugging()->last_status());
1325 // This should not have changed the existing snippets. 1217 // This should not have changed the existing snippets.
1326 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1218 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1327 } 1219 }
1328 1220
1329 TEST_F(RemoteSuggestionsProviderTest, Dismiss) { 1221 TEST_F(RemoteSuggestionsProviderImplTest, Dismiss) {
1330 auto service = MakeSnippetsService(); 1222 auto service = MakeSnippetsService();
1331 1223
1332 std::string json_str( 1224 std::string json_str(
1333 GetTestJson({GetSnippetWithSources("http://site.com", "Source 1", "")})); 1225 GetTestJson({GetSnippetWithSources("http://site.com", "Source 1", "")}));
1334 1226
1335 LoadFromJSONString(service.get(), json_str); 1227 LoadFromJSONString(service.get(), json_str);
1336 1228
1337 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1229 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1338 // Load the image to store it in the database. 1230 // Load the image to store it in the database.
1339 ServeImageCallback cb = 1231 ServeImageCallback cb =
(...skipping 30 matching lines...) Expand all
1370 LoadFromJSONString(service.get(), json_str); 1262 LoadFromJSONString(service.get(), json_str);
1371 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1263 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1372 1264
1373 // The snippet can be added again after clearing dismissed snippets. 1265 // The snippet can be added again after clearing dismissed snippets.
1374 service->ClearDismissedSuggestionsForDebugging(articles_category()); 1266 service->ClearDismissedSuggestionsForDebugging(articles_category());
1375 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1267 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1376 LoadFromJSONString(service.get(), json_str); 1268 LoadFromJSONString(service.get(), json_str);
1377 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1269 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1378 } 1270 }
1379 1271
1380 TEST_F(RemoteSuggestionsProviderTest, GetDismissed) { 1272 TEST_F(RemoteSuggestionsProviderImplTest, GetDismissed) {
1381 auto service = MakeSnippetsService(); 1273 auto service = MakeSnippetsService();
1382 1274
1383 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1275 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1384 1276
1385 service->DismissSuggestion(MakeArticleID(kSnippetUrl)); 1277 service->DismissSuggestion(MakeArticleID(kSnippetUrl));
1386 1278
1387 service->GetDismissedSuggestionsForDebugging( 1279 service->GetDismissedSuggestionsForDebugging(
1388 articles_category(), 1280 articles_category(),
1389 base::Bind( 1281 base::Bind(
1390 [](RemoteSuggestionsProvider* service, 1282 [](RemoteSuggestionsProviderImpl* service,
1391 RemoteSuggestionsProviderTest* test, 1283 RemoteSuggestionsProviderImplTest* test,
1392 std::vector<ContentSuggestion> dismissed_suggestions) { 1284 std::vector<ContentSuggestion> dismissed_suggestions) {
1393 EXPECT_EQ(1u, dismissed_suggestions.size()); 1285 EXPECT_EQ(1u, dismissed_suggestions.size());
1394 for (auto& suggestion : dismissed_suggestions) { 1286 for (auto& suggestion : dismissed_suggestions) {
1395 EXPECT_EQ(test->MakeArticleID(kSnippetUrl), suggestion.id()); 1287 EXPECT_EQ(test->MakeArticleID(kSnippetUrl), suggestion.id());
1396 } 1288 }
1397 }, 1289 },
1398 service.get(), this)); 1290 service.get(), this));
1399 base::RunLoop().RunUntilIdle(); 1291 base::RunLoop().RunUntilIdle();
1400 1292
1401 // There should be no dismissed snippet after clearing the list. 1293 // There should be no dismissed snippet after clearing the list.
1402 service->ClearDismissedSuggestionsForDebugging(articles_category()); 1294 service->ClearDismissedSuggestionsForDebugging(articles_category());
1403 service->GetDismissedSuggestionsForDebugging( 1295 service->GetDismissedSuggestionsForDebugging(
1404 articles_category(), 1296 articles_category(),
1405 base::Bind( 1297 base::Bind(
1406 [](RemoteSuggestionsProvider* service, 1298 [](RemoteSuggestionsProviderImpl* service,
1407 RemoteSuggestionsProviderTest* test, 1299 RemoteSuggestionsProviderImplTest* test,
1408 std::vector<ContentSuggestion> dismissed_suggestions) { 1300 std::vector<ContentSuggestion> dismissed_suggestions) {
1409 EXPECT_EQ(0u, dismissed_suggestions.size()); 1301 EXPECT_EQ(0u, dismissed_suggestions.size());
1410 }, 1302 },
1411 service.get(), this)); 1303 service.get(), this));
1412 base::RunLoop().RunUntilIdle(); 1304 base::RunLoop().RunUntilIdle();
1413 } 1305 }
1414 1306
1415 TEST_F(RemoteSuggestionsProviderTest, CreationTimestampParseFail) { 1307 TEST_F(RemoteSuggestionsProviderImplTest, CreationTimestampParseFail) {
1416 auto service = MakeSnippetsService(); 1308 auto service = MakeSnippetsService();
1417 1309
1418 std::string json = 1310 std::string json =
1419 GetSnippetWithTimes(GetDefaultCreationTime(), GetDefaultExpirationTime()); 1311 GetSnippetWithTimes(GetDefaultCreationTime(), GetDefaultExpirationTime());
1420 base::ReplaceFirstSubstringAfterOffset( 1312 base::ReplaceFirstSubstringAfterOffset(
1421 &json, 0, FormatTime(GetDefaultCreationTime()), "aaa1448459205"); 1313 &json, 0, FormatTime(GetDefaultCreationTime()), "aaa1448459205");
1422 std::string json_str(GetTestJson({json})); 1314 std::string json_str(GetTestJson({json}));
1423 1315
1424 LoadFromJSONString(service.get(), json_str); 1316 LoadFromJSONString(service.get(), json_str);
1425 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1317 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1426 } 1318 }
1427 1319
1428 TEST_F(RemoteSuggestionsProviderTest, RemoveExpiredDismissedContent) { 1320 TEST_F(RemoteSuggestionsProviderImplTest, RemoveExpiredDismissedContent) {
1429 auto service = MakeSnippetsService(); 1321 auto service = MakeSnippetsService();
1430 1322
1431 std::string json_str1(GetTestJson({GetExpiredSnippet()})); 1323 std::string json_str1(GetTestJson({GetExpiredSnippet()}));
1432 // Load it. 1324 // Load it.
1433 LoadFromJSONString(service.get(), json_str1); 1325 LoadFromJSONString(service.get(), json_str1);
1434 // Load the image to store it in the database. 1326 // Load the image to store it in the database.
1435 // TODO(tschumann): Introduce some abstraction to nicely work with image 1327 // TODO(tschumann): Introduce some abstraction to nicely work with image
1436 // fetching expectations. 1328 // fetching expectations.
1437 ServeImageCallback cb = 1329 ServeImageCallback cb =
1438 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1330 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
(...skipping 12 matching lines...) Expand all
1451 std::string json_str2(GetTestJson({GetSnippetWithUrl(kSnippetUrl2)})); 1343 std::string json_str2(GetTestJson({GetSnippetWithUrl(kSnippetUrl2)}));
1452 LoadFromJSONString(service.get(), json_str2); 1344 LoadFromJSONString(service.get(), json_str2);
1453 1345
1454 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1346 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1455 IsEmpty()); 1347 IsEmpty());
1456 1348
1457 // Verify the image got removed, too. 1349 // Verify the image got removed, too.
1458 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1350 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1459 } 1351 }
1460 1352
1461 TEST_F(RemoteSuggestionsProviderTest, ExpiredContentNotRemoved) { 1353 TEST_F(RemoteSuggestionsProviderImplTest, ExpiredContentNotRemoved) {
1462 auto service = MakeSnippetsService(); 1354 auto service = MakeSnippetsService();
1463 1355
1464 std::string json_str(GetTestJson({GetExpiredSnippet()})); 1356 std::string json_str(GetTestJson({GetExpiredSnippet()}));
1465 1357
1466 LoadFromJSONString(service.get(), json_str); 1358 LoadFromJSONString(service.get(), json_str);
1467 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1359 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1468 } 1360 }
1469 1361
1470 TEST_F(RemoteSuggestionsProviderTest, TestSingleSource) { 1362 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSource) {
1471 auto service = MakeSnippetsService(); 1363 auto service = MakeSnippetsService();
1472 1364
1473 std::string json_str(GetTestJson({GetSnippetWithSources( 1365 std::string json_str(GetTestJson({GetSnippetWithSources(
1474 "http://source1.com", "Source 1", "http://source1.amp.com")})); 1366 "http://source1.com", "Source 1", "http://source1.amp.com")}));
1475 1367
1476 LoadFromJSONString(service.get(), json_str); 1368 LoadFromJSONString(service.get(), json_str);
1477 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1369 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1478 const NTPSnippet& snippet = 1370 const NTPSnippet& snippet =
1479 *service->GetSnippetsForTesting(articles_category()).front(); 1371 *service->GetSnippetsForTesting(articles_category()).front();
1480 EXPECT_EQ(snippet.id(), kSnippetUrl); 1372 EXPECT_EQ(snippet.id(), kSnippetUrl);
1481 EXPECT_EQ(snippet.url(), GURL("http://source1.com")); 1373 EXPECT_EQ(snippet.url(), GURL("http://source1.com"));
1482 EXPECT_EQ(snippet.publisher_name(), std::string("Source 1")); 1374 EXPECT_EQ(snippet.publisher_name(), std::string("Source 1"));
1483 EXPECT_EQ(snippet.amp_url(), GURL("http://source1.amp.com")); 1375 EXPECT_EQ(snippet.amp_url(), GURL("http://source1.amp.com"));
1484 } 1376 }
1485 1377
1486 TEST_F(RemoteSuggestionsProviderTest, TestSingleSourceWithMalformedUrl) { 1378 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMalformedUrl) {
1487 auto service = MakeSnippetsService(); 1379 auto service = MakeSnippetsService();
1488 1380
1489 std::string json_str(GetTestJson({GetSnippetWithSources( 1381 std::string json_str(GetTestJson({GetSnippetWithSources(
1490 "ceci n'est pas un url", "Source 1", "http://source1.amp.com")})); 1382 "ceci n'est pas un url", "Source 1", "http://source1.amp.com")}));
1491 1383
1492 LoadFromJSONString(service.get(), json_str); 1384 LoadFromJSONString(service.get(), json_str);
1493 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1385 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1494 } 1386 }
1495 1387
1496 TEST_F(RemoteSuggestionsProviderTest, TestSingleSourceWithMissingData) { 1388 TEST_F(RemoteSuggestionsProviderImplTest, TestSingleSourceWithMissingData) {
1497 auto service = MakeSnippetsService(); 1389 auto service = MakeSnippetsService();
1498 1390
1499 std::string json_str( 1391 std::string json_str(
1500 GetTestJson({GetSnippetWithSources("http://source1.com", "", "")})); 1392 GetTestJson({GetSnippetWithSources("http://source1.com", "", "")}));
1501 1393
1502 LoadFromJSONString(service.get(), json_str); 1394 LoadFromJSONString(service.get(), json_str);
1503 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1395 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1504 } 1396 }
1505 1397
1506 TEST_F(RemoteSuggestionsProviderTest, LogNumArticlesHistogram) { 1398 TEST_F(RemoteSuggestionsProviderImplTest, LogNumArticlesHistogram) {
1507 auto service = MakeSnippetsService(); 1399 auto service = MakeSnippetsService();
1508 1400
1509 base::HistogramTester tester; 1401 base::HistogramTester tester;
1510 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()})); 1402 LoadFromJSONString(service.get(), GetTestJson({GetInvalidSnippet()}));
1511 1403
1512 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"), 1404 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticles"),
1513 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); 1405 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
1514 1406
1515 // Invalid JSON shouldn't contribute to NumArticlesFetched. 1407 // Invalid JSON shouldn't contribute to NumArticlesFetched.
1516 EXPECT_THAT(tester.GetAllSamples("NewTabPage.Snippets.NumArticlesFetched"), 1408 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 1465 // But if there's a non-dismissed snippet in the database, recreating it
1574 // shouldn't trigger a fetch. 1466 // shouldn't trigger a fetch.
1575 LoadFromJSONString( 1467 LoadFromJSONString(
1576 service.get(), 1468 service.get(),
1577 GetTestJson({GetSnippetWithUrl("http://not-dismissed.com")})); 1469 GetTestJson({GetSnippetWithUrl("http://not-dismissed.com")}));
1578 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); 1470 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6);
1579 ResetSnippetsService(&service, /*set_empty_response=*/true); 1471 ResetSnippetsService(&service, /*set_empty_response=*/true);
1580 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6); 1472 tester.ExpectTotalCount("NewTabPage.Snippets.NumArticlesFetched", 6);
1581 } 1473 }
1582 1474
1583 TEST_F(RemoteSuggestionsProviderTest, DismissShouldRespectAllKnownUrls) { 1475 TEST_F(RemoteSuggestionsProviderImplTest, DismissShouldRespectAllKnownUrls) {
1584 auto service = MakeSnippetsService(); 1476 auto service = MakeSnippetsService();
1585 1477
1586 const base::Time creation = GetDefaultCreationTime(); 1478 const base::Time creation = GetDefaultCreationTime();
1587 const base::Time expiry = GetDefaultExpirationTime(); 1479 const base::Time expiry = GetDefaultExpirationTime();
1588 const std::vector<std::string> source_urls = { 1480 const std::vector<std::string> source_urls = {
1589 "http://mashable.com/2016/05/11/stolen", 1481 "http://mashable.com/2016/05/11/stolen",
1590 "http://www.aol.com/article/2016/05/stolen-doggie"}; 1482 "http://www.aol.com/article/2016/05/stolen-doggie"};
1591 const std::vector<std::string> publishers = {"Mashable", "AOL"}; 1483 const std::vector<std::string> publishers = {"Mashable", "AOL"};
1592 const std::vector<std::string> amp_urls = { 1484 const std::vector<std::string> amp_urls = {
1593 "http://mashable-amphtml.googleusercontent.com/1", 1485 "http://mashable-amphtml.googleusercontent.com/1",
(...skipping 10 matching lines...) Expand all
1604 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1496 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1605 1497
1606 // The same article from the AOL domain should now be detected as dismissed. 1498 // The same article from the AOL domain should now be detected as dismissed.
1607 LoadFromJSONString(service.get(), 1499 LoadFromJSONString(service.get(),
1608 GetTestJson({GetSnippetWithUrlAndTimesAndSource( 1500 GetTestJson({GetSnippetWithUrlAndTimesAndSource(
1609 source_urls, source_urls[1], creation, expiry, 1501 source_urls, source_urls[1], creation, expiry,
1610 publishers[1], amp_urls[1])})); 1502 publishers[1], amp_urls[1])}));
1611 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1503 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1612 } 1504 }
1613 1505
1614 TEST_F(RemoteSuggestionsProviderTest, StatusChanges) { 1506 TEST_F(RemoteSuggestionsProviderImplTest, StatusChanges) {
1615 auto service = MakeSnippetsService(); 1507 auto service = MakeSnippetsService();
1616 1508
1617 // Simulate user signed out 1509 // Simulate user signed out
1618 SetUpFetchResponse(GetTestJson({GetSnippet()})); 1510 SetUpFetchResponse(GetTestJson({GetSnippet()}));
1619 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN, 1511 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
1620 RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED); 1512 RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED);
1621 1513
1622 base::RunLoop().RunUntilIdle(); 1514 base::RunLoop().RunUntilIdle();
1623 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1515 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1624 Eq(CategoryStatus::SIGNED_OUT)); 1516 Eq(CategoryStatus::SIGNED_OUT));
1625 EXPECT_THAT(RemoteSuggestionsProvider::State::DISABLED, Eq(service->state_)); 1517 EXPECT_THAT(RemoteSuggestionsProviderImpl::State::DISABLED,
1518 Eq(service->state_));
1626 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 1519 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1627 IsEmpty()); // No fetch should be made. 1520 IsEmpty()); // No fetch should be made.
1628 1521
1629 // Simulate user sign in. The service should be ready again and load snippets. 1522 // Simulate user sign in. The service should be ready again and load snippets.
1630 SetUpFetchResponse(GetTestJson({GetSnippet()})); 1523 SetUpFetchResponse(GetTestJson({GetSnippet()}));
1631 service->OnStatusChanged(RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED, 1524 service->OnStatusChanged(RemoteSuggestionsStatus::SIGNED_OUT_AND_DISABLED,
1632 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN); 1525 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);
1633 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1526 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1634 Eq(CategoryStatus::AVAILABLE_LOADING)); 1527 Eq(CategoryStatus::AVAILABLE_LOADING));
1635 1528
1636 base::RunLoop().RunUntilIdle(); 1529 base::RunLoop().RunUntilIdle();
1637 EXPECT_THAT(observer().StatusForCategory(articles_category()), 1530 EXPECT_THAT(observer().StatusForCategory(articles_category()),
1638 Eq(CategoryStatus::AVAILABLE)); 1531 Eq(CategoryStatus::AVAILABLE));
1639 EXPECT_THAT(RemoteSuggestionsProvider::State::READY, Eq(service->state_)); 1532 EXPECT_THAT(RemoteSuggestionsProviderImpl::State::READY, Eq(service->state_));
1640 EXPECT_FALSE(service->GetSnippetsForTesting(articles_category()).empty()); 1533 EXPECT_FALSE(service->GetSnippetsForTesting(articles_category()).empty());
1641 } 1534 }
1642 1535
1643 TEST_F(RemoteSuggestionsProviderTest, ImageReturnedWithTheSameId) { 1536 TEST_F(RemoteSuggestionsProviderImplTest, ImageReturnedWithTheSameId) {
1644 auto service = MakeSnippetsService(); 1537 auto service = MakeSnippetsService();
1645 1538
1646 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1539 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1647 1540
1648 gfx::Image image; 1541 gfx::Image image;
1649 MockFunction<void(const gfx::Image&)> image_fetched; 1542 MockFunction<void(const gfx::Image&)> image_fetched;
1650 ServeImageCallback cb = 1543 ServeImageCallback cb =
1651 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1544 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
1652 { 1545 {
1653 InSequence s; 1546 InSequence s;
1654 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _)) 1547 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _))
1655 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run))); 1548 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run)));
1656 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1549 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1657 } 1550 }
1658 1551
1659 service->FetchSuggestionImage( 1552 service->FetchSuggestionImage(
1660 MakeArticleID(kSnippetUrl), 1553 MakeArticleID(kSnippetUrl),
1661 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1554 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1662 base::Unretained(&image_fetched))); 1555 base::Unretained(&image_fetched)));
1663 base::RunLoop().RunUntilIdle(); 1556 base::RunLoop().RunUntilIdle();
1664 // Check that the image by ServeOneByOneImage is really served. 1557 // Check that the image by ServeOneByOneImage is really served.
1665 EXPECT_EQ(1, image.Width()); 1558 EXPECT_EQ(1, image.Width());
1666 } 1559 }
1667 1560
1668 TEST_F(RemoteSuggestionsProviderTest, EmptyImageReturnedForNonExistentId) { 1561 TEST_F(RemoteSuggestionsProviderImplTest, EmptyImageReturnedForNonExistentId) {
1669 auto service = MakeSnippetsService(); 1562 auto service = MakeSnippetsService();
1670 1563
1671 // Create a non-empty image so that we can test the image gets updated. 1564 // Create a non-empty image so that we can test the image gets updated.
1672 gfx::Image image = gfx::test::CreateImage(1, 1); 1565 gfx::Image image = gfx::test::CreateImage(1, 1);
1673 MockFunction<void(const gfx::Image&)> image_fetched; 1566 MockFunction<void(const gfx::Image&)> image_fetched;
1674 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1567 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1675 1568
1676 service->FetchSuggestionImage( 1569 service->FetchSuggestionImage(
1677 MakeArticleID(kSnippetUrl2), 1570 MakeArticleID(kSnippetUrl2),
1678 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1571 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1679 base::Unretained(&image_fetched))); 1572 base::Unretained(&image_fetched)));
1680 1573
1681 base::RunLoop().RunUntilIdle(); 1574 base::RunLoop().RunUntilIdle();
1682 EXPECT_TRUE(image.IsEmpty()); 1575 EXPECT_TRUE(image.IsEmpty());
1683 } 1576 }
1684 1577
1685 TEST_F(RemoteSuggestionsProviderTest, 1578 TEST_F(RemoteSuggestionsProviderImplTest,
1686 FetchingUnknownImageIdShouldNotHitDatabase) { 1579 FetchingUnknownImageIdShouldNotHitDatabase) {
1687 // Testing that the provider is not accessing the database is tricky. 1580 // 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 1581 // Therefore, we simply put in some data making sure that if the provider asks
1689 // the database, it will get a wrong answer. 1582 // the database, it will get a wrong answer.
1690 auto service = MakeSnippetsService(); 1583 auto service = MakeSnippetsService();
1691 1584
1692 ContentSuggestion::ID unknown_id = MakeArticleID(kSnippetUrl2); 1585 ContentSuggestion::ID unknown_id = MakeArticleID(kSnippetUrl2);
1693 database()->SaveImage(unknown_id.id_within_category(), "some image blob"); 1586 database()->SaveImage(unknown_id.id_within_category(), "some image blob");
1694 // Set up the image decoder to always return the 1x1 test image. 1587 // Set up the image decoder to always return the 1x1 test image.
1695 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); 1588 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
1696 1589
1697 // Create a non-empty image so that we can test the image gets updated. 1590 // Create a non-empty image so that we can test the image gets updated.
1698 gfx::Image image = gfx::test::CreateImage(2, 2); 1591 gfx::Image image = gfx::test::CreateImage(2, 2);
1699 MockFunction<void(const gfx::Image&)> image_fetched; 1592 MockFunction<void(const gfx::Image&)> image_fetched;
1700 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image)); 1593 EXPECT_CALL(image_fetched, Call(_)).WillOnce(SaveArg<0>(&image));
1701 1594
1702 service->FetchSuggestionImage( 1595 service->FetchSuggestionImage(
1703 MakeArticleID(kSnippetUrl2), 1596 MakeArticleID(kSnippetUrl2),
1704 base::Bind(&MockFunction<void(const gfx::Image&)>::Call, 1597 base::Bind(&MockFunction<void(const gfx::Image&)>::Call,
1705 base::Unretained(&image_fetched))); 1598 base::Unretained(&image_fetched)));
1706 1599
1707 base::RunLoop().RunUntilIdle(); 1600 base::RunLoop().RunUntilIdle();
1708 EXPECT_TRUE(image.IsEmpty()) << "got image with width: " << image.Width(); 1601 EXPECT_TRUE(image.IsEmpty()) << "got image with width: " << image.Width();
1709 } 1602 }
1710 1603
1711 TEST_F(RemoteSuggestionsProviderTest, ClearHistoryRemovesAllSuggestions) { 1604 TEST_F(RemoteSuggestionsProviderImplTest, ClearHistoryRemovesAllSuggestions) {
1712 auto service = MakeSnippetsService(); 1605 auto service = MakeSnippetsService();
1713 1606
1714 std::string first_snippet = GetSnippetWithUrl("http://url1.com"); 1607 std::string first_snippet = GetSnippetWithUrl("http://url1.com");
1715 std::string second_snippet = GetSnippetWithUrl("http://url2.com"); 1608 std::string second_snippet = GetSnippetWithUrl("http://url2.com");
1716 std::string json_str = GetTestJson({first_snippet, second_snippet}); 1609 std::string json_str = GetTestJson({first_snippet, second_snippet});
1717 LoadFromJSONString(service.get(), json_str); 1610 LoadFromJSONString(service.get(), json_str);
1718 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2)); 1611 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2));
1719 1612
1720 service->DismissSuggestion(MakeArticleID("http://url1.com")); 1613 service->DismissSuggestion(MakeArticleID("http://url1.com"));
1721 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1614 ASSERT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1722 ASSERT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1615 ASSERT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1723 SizeIs(1)); 1616 SizeIs(1));
1724 1617
1725 base::Time begin = base::Time::FromTimeT(123), 1618 base::Time begin = base::Time::FromTimeT(123),
1726 end = base::Time::FromTimeT(456); 1619 end = base::Time::FromTimeT(456);
1727 base::Callback<bool(const GURL& url)> filter; 1620 base::Callback<bool(const GURL& url)> filter;
1728 service->ClearHistory(begin, end, filter); 1621 service->ClearHistory(begin, end, filter);
1729 1622
1730 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1623 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1731 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()), 1624 EXPECT_THAT(service->GetDismissedSnippetsForTesting(articles_category()),
1732 IsEmpty()); 1625 IsEmpty());
1733 } 1626 }
1734 1627
1735 TEST_F(RemoteSuggestionsProviderTest, SuggestionsFetchedOnSignInAndSignOut) { 1628 TEST_F(RemoteSuggestionsProviderImplTest,
1629 SuggestionsFetchedOnSignInAndSignOut) {
1736 auto service = MakeSnippetsService(); 1630 auto service = MakeSnippetsService();
1737 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty()); 1631 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), IsEmpty());
1738 1632
1739 // |MakeSnippetsService()| creates a service where user is signed in already, 1633 // |MakeSnippetsService()| creates a service where user is signed in already,
1740 // so we start by signing out. 1634 // so we start by signing out.
1741 SetUpFetchResponse(GetTestJson({GetSnippetN(1)})); 1635 SetUpFetchResponse(GetTestJson({GetSnippetN(1)}));
1742 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN, 1636 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
1743 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT); 1637 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT);
1744 base::RunLoop().RunUntilIdle(); 1638 base::RunLoop().RunUntilIdle();
1745 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1)); 1639 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(1));
1746 1640
1747 // Sign in to check a transition from signed out to signed in. 1641 // Sign in to check a transition from signed out to signed in.
1748 SetUpFetchResponse(GetTestJson({GetSnippetN(1), GetSnippetN(2)})); 1642 SetUpFetchResponse(GetTestJson({GetSnippetN(1), GetSnippetN(2)}));
1749 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT, 1643 service->OnStatusChanged(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT,
1750 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN); 1644 RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN);
1751 base::RunLoop().RunUntilIdle(); 1645 base::RunLoop().RunUntilIdle();
1752 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2)); 1646 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), SizeIs(2));
1753 } 1647 }
1754 1648
1755 TEST_F(RemoteSuggestionsProviderTest, ShouldClearOrphanedImagesOnRestart) { 1649 TEST_F(RemoteSuggestionsProviderImplTest, ShouldClearOrphanedImagesOnRestart) {
1756 auto service = MakeSnippetsService(); 1650 auto service = MakeSnippetsService();
1757 1651
1758 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()})); 1652 LoadFromJSONString(service.get(), GetTestJson({GetSnippet()}));
1759 ServeImageCallback cb = 1653 ServeImageCallback cb =
1760 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting()); 1654 base::Bind(&ServeOneByOneImage, &service->GetImageFetcherForTesting());
1761 1655
1762 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _)) 1656 EXPECT_CALL(*image_fetcher(), StartOrQueueNetworkRequest(_, _, _))
1763 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run))); 1657 .WillOnce(WithArgs<0, 2>(Invoke(&cb, &ServeImageCallback::Run)));
1764 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1)); 1658 image_decoder()->SetDecodedImage(gfx::test::CreateImage(1, 1));
1765 1659
1766 gfx::Image image = FetchImage(service.get(), MakeArticleID(kSnippetUrl)); 1660 gfx::Image image = FetchImage(service.get(), MakeArticleID(kSnippetUrl));
1767 EXPECT_EQ(1, image.Width()); 1661 EXPECT_EQ(1, image.Width());
1768 EXPECT_FALSE(image.IsEmpty()); 1662 EXPECT_FALSE(image.IsEmpty());
1769 1663
1770 // Send new suggestion which don't include the snippet referencing the image. 1664 // Send new suggestion which don't include the snippet referencing the image.
1771 LoadFromJSONString(service.get(), 1665 LoadFromJSONString(service.get(),
1772 GetTestJson({GetSnippetWithUrl( 1666 GetTestJson({GetSnippetWithUrl(
1773 "http://something.com/pletely/unrelated")})); 1667 "http://something.com/pletely/unrelated")}));
1774 // The image should still be available until a restart happens. 1668 // The image should still be available until a restart happens.
1775 EXPECT_FALSE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1669 EXPECT_FALSE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1776 ResetSnippetsService(&service, /*set_empty_response=*/true); 1670 ResetSnippetsService(&service, /*set_empty_response=*/true);
1777 // After the restart, the image should be garbage collected. 1671 // After the restart, the image should be garbage collected.
1778 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty()); 1672 EXPECT_TRUE(FetchImage(service.get(), MakeArticleID(kSnippetUrl)).IsEmpty());
1779 } 1673 }
1780 1674
1781 TEST_F(RemoteSuggestionsProviderTest, 1675 TEST_F(RemoteSuggestionsProviderImplTest,
1782 ShouldHandleMoreThanMaxSnippetsInResponse) { 1676 ShouldHandleMoreThanMaxSnippetsInResponse) {
1783 auto service = MakeSnippetsService(); 1677 auto service = MakeSnippetsService();
1784 1678
1785 std::vector<std::string> suggestions; 1679 std::vector<std::string> suggestions;
1786 for (int i = 0; i < service->GetMaxSnippetCountForTesting() + 1; ++i) { 1680 for (int i = 0; i < service->GetMaxSnippetCountForTesting() + 1; ++i) {
1787 suggestions.push_back(GetSnippetWithUrl( 1681 suggestions.push_back(GetSnippetWithUrl(
1788 base::StringPrintf("http://localhost/snippet-id-%d", i))); 1682 base::StringPrintf("http://localhost/snippet-id-%d", i)));
1789 } 1683 }
1790 LoadFromJSONString(service.get(), GetTestJson(suggestions)); 1684 LoadFromJSONString(service.get(), GetTestJson(suggestions));
1791 // TODO(tschumann): We should probably trim out any additional results and 1685 // TODO(tschumann): We should probably trim out any additional results and
1792 // only serve the MaxSnippetCount items. 1686 // only serve the MaxSnippetCount items.
1793 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()), 1687 EXPECT_THAT(service->GetSnippetsForTesting(articles_category()),
1794 SizeIs(service->GetMaxSnippetCountForTesting() + 1)); 1688 SizeIs(service->GetMaxSnippetCountForTesting() + 1));
1795 } 1689 }
1796 1690
1797 TEST_F(RemoteSuggestionsProviderTest, StoreLastSuccessfullBackgroundFetchTime) { 1691 TEST_F(RemoteSuggestionsProviderImplTest,
1798 // On initialization of the RemoteSuggestionsProvider a background fetch is 1692 StoreLastSuccessfullBackgroundFetchTime) {
1799 // triggered since the snippets DB is empty. Therefore the service must not be 1693 // On initialization of the RemoteSuggestionsProviderImpl a background fetch
1800 // initialized until the test clock is set. 1694 // is triggered since the snippets DB is empty. Therefore the service must not
1695 // be initialized until the test clock is set.
1801 auto service = MakeSnippetsServiceWithoutInitialization(); 1696 auto service = MakeSnippetsServiceWithoutInitialization();
1802 1697
1803 auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>(); 1698 auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>();
1804 base::SimpleTestClock* simple_test_clock_ptr = simple_test_clock.get(); 1699 base::SimpleTestClock* simple_test_clock_ptr = simple_test_clock.get();
1805 service->SetClockForTesting(std::move(simple_test_clock)); 1700 service->SetClockForTesting(std::move(simple_test_clock));
1806 1701
1807 // Test that the preference is correctly initialized with the default value 0. 1702 // Test that the preference is correctly initialized with the default value 0.
1808 EXPECT_EQ( 1703 EXPECT_EQ(
1809 0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1704 0, pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1810 1705
1811 WaitForSnippetsServiceInitialization(service.get(), 1706 WaitForSnippetsServiceInitialization(service.get(),
1812 /*set_empty_response=*/true); 1707 /*set_empty_response=*/true);
1813 EXPECT_EQ( 1708 EXPECT_EQ(
1814 simple_test_clock_ptr->Now().ToInternalValue(), 1709 simple_test_clock_ptr->Now().ToInternalValue(),
1815 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1710 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1816 1711
1817 // Advance the time and check whether the time was updated correctly after the 1712 // Advance the time and check whether the time was updated correctly after the
1818 // background fetch. 1713 // background fetch.
1819 simple_test_clock_ptr->Advance(TimeDelta::FromHours(1)); 1714 simple_test_clock_ptr->Advance(TimeDelta::FromHours(1));
1820 service->FetchSnippetsInTheBackground(); 1715
1716 service->RefetchInTheBackground(/*callback=*/nullptr);
1821 base::RunLoop().RunUntilIdle(); 1717 base::RunLoop().RunUntilIdle();
1718 // TODO(jkrcal): Move together with the pref storage into the scheduler.
1822 EXPECT_EQ( 1719 EXPECT_EQ(
1823 simple_test_clock_ptr->Now().ToInternalValue(), 1720 simple_test_clock_ptr->Now().ToInternalValue(),
1824 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime)); 1721 pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
1825 // TODO(markusheintz): Add a test that simulates a browser restart once the 1722 // TODO(markusheintz): Add a test that simulates a browser restart once the
1826 // scheduler refactoring is done (crbug.com/672434). 1723 // scheduler refactoring is done (crbug.com/672434).
1827 } 1724 }
1828 1725
1726 TEST_F(RemoteSuggestionsProviderImplTest, CallsProviderStatusCallbackIfReady) {
1727 // Initiate the service so that it is already READY.
1728 auto service = MakeSnippetsService();
1729
1730 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1731 status_callback;
1732 // The callback should be called on registering.
1733 EXPECT_CALL(status_callback,
1734 Call(RemoteSuggestionsProvider::ProviderStatus::ACTIVE));
1735 service->SetProviderStatusCallback(
1736 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1737 base::Bind(&MockFunction<void(
1738 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1739 base::Unretained(&status_callback))));
1740 }
1741
1742 TEST_F(RemoteSuggestionsProviderImplTest,
1743 DoesNotCallProviderStatusCallbackIfNotInited) {
1744 auto service = MakeSnippetsServiceWithoutInitialization();
1745
1746 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1747 status_callback;
1748 // The provider is not initialized yet, no callback should be called on
1749 // registering.
1750 service->SetProviderStatusCallback(
1751 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1752 base::Bind(&MockFunction<void(
1753 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1754 base::Unretained(&status_callback))));
1755 }
1756
1757 TEST_F(RemoteSuggestionsProviderImplTest,
1758 CallsProviderStatusCallbackWhenReady) {
1759 auto service = MakeSnippetsServiceWithoutInitialization();
1760 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1761 status_callback;
1762 service->SetProviderStatusCallback(
1763 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1764 base::Bind(&MockFunction<void(
1765 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1766 base::Unretained(&status_callback))));
1767
1768 // Should be called when becoming ready.
1769 EXPECT_CALL(status_callback,
1770 Call(RemoteSuggestionsProvider::ProviderStatus::ACTIVE));
1771 WaitForSnippetsServiceInitialization(service.get(),
1772 /*set_empty_response=*/true);
1773 }
1774
1775 TEST_F(RemoteSuggestionsProviderImplTest, CallsProviderStatusCallbackOnError) {
1776 auto service = MakeSnippetsServiceWithoutInitialization();
1777 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1778 status_callback;
1779 service->SetProviderStatusCallback(
1780 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1781 base::Bind(&MockFunction<void(
1782 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1783 base::Unretained(&status_callback))));
1784
1785 // Should be called on error.
1786 EXPECT_CALL(status_callback,
1787 Call(RemoteSuggestionsProvider::ProviderStatus::INACTIVE));
1788 service->EnterState(RemoteSuggestionsProviderImpl::State::ERROR_OCCURRED);
1789 }
1790
1791 TEST_F(RemoteSuggestionsProviderImplTest,
1792 CallsProviderStatusCallbackWhenDisabled) {
1793 auto service = MakeSnippetsServiceWithoutInitialization();
1794 StrictMock<MockFunction<void(RemoteSuggestionsProvider::ProviderStatus)>>
1795 status_callback;
1796 service->SetProviderStatusCallback(
1797 base::MakeUnique<RemoteSuggestionsProvider::ProviderStatusCallback>(
1798 base::Bind(&MockFunction<void(
1799 RemoteSuggestionsProvider::ProviderStatus)>::Call,
1800 base::Unretained(&status_callback))));
1801
1802 // Should be called when becoming disabled.
1803 EXPECT_CALL(status_callback,
1804 Call(RemoteSuggestionsProvider::ProviderStatus::INACTIVE));
1805 service->EnterState(RemoteSuggestionsProviderImpl::State::DISABLED);
1806 }
1807
1829 } // namespace ntp_snippets 1808 } // namespace ntp_snippets
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698