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

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

Powered by Google App Engine
This is Rietveld 408576698