summaryrefslogtreecommitdiff
path: root/chromium/components/ntp_snippets
diff options
context:
space:
mode:
authorAllan Sandfeld Jensen <allan.jensen@qt.io>2018-01-31 16:33:43 +0100
committerAllan Sandfeld Jensen <allan.jensen@qt.io>2018-02-06 16:33:22 +0000
commitda51f56cc21233c2d30f0fe0d171727c3102b2e0 (patch)
tree4e579ab70ce4b19bee7984237f3ce05a96d59d83 /chromium/components/ntp_snippets
parentc8c2d1901aec01e934adf561a9fdf0cc776cdef8 (diff)
downloadqtwebengine-chromium-da51f56cc21233c2d30f0fe0d171727c3102b2e0.tar.gz
BASELINE: Update Chromium to 65.0.3525.40
Also imports missing submodules Change-Id: I36901b7c6a325cda3d2c10cedb2186c25af3b79b Reviewed-by: Alexandru Croitor <alexandru.croitor@qt.io>
Diffstat (limited to 'chromium/components/ntp_snippets')
-rw-r--r--chromium/components/ntp_snippets/BUILD.gn2
-rw-r--r--chromium/components/ntp_snippets/DEPS1
-rw-r--r--chromium/components/ntp_snippets/bookmarks/bookmark_suggestions_provider_unittest.cc3
-rw-r--r--chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.cc22
-rw-r--r--chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.h4
-rw-r--r--chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc172
-rw-r--r--chromium/components/ntp_snippets/breaking_news/subscription_json_request.cc11
-rw-r--r--chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc15
-rw-r--r--chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.h8
-rw-r--r--chromium/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc37
-rw-r--r--chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.cc10
-rw-r--r--chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.h4
-rw-r--r--chromium/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc51
-rw-r--r--chromium/components/ntp_snippets/content_suggestions_provider.h6
-rw-r--r--chromium/components/ntp_snippets/content_suggestions_service.cc8
-rw-r--r--chromium/components/ntp_snippets/content_suggestions_service.h2
-rw-r--r--chromium/components/ntp_snippets/content_suggestions_service_unittest.cc21
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_content_suggestions_service_unittest.cc7
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_json_request.cc18
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_suggestion.h2
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.cc12
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h7
-rw-r--r--chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl_unittest.cc59
-rw-r--r--chromium/components/ntp_snippets/features.cc8
-rw-r--r--chromium/components/ntp_snippets/features.h2
-rw-r--r--chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc26
-rw-r--r--chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h5
-rw-r--r--chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider_unittest.cc23
-rw-r--r--chromium/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider_unittest.cc5
-rw-r--r--chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc4
-rw-r--r--chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider_unittest.cc9
-rw-r--r--chromium/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc9
-rw-r--r--chromium/components/ntp_snippets/remote/json_request.cc32
-rw-r--r--chromium/components/ntp_snippets/remote/json_request_unittest.cc5
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestion.cc2
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestion.h2
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_database.cc11
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc39
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h22
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc105
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc25
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.h8
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc77
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.cc17
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.h4
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc26
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_status_service.h2
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.cc13
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.h7
-rw-r--r--chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl_unittest.cc34
-rw-r--r--chromium/components/ntp_snippets/remote/test_utils.cc15
-rw-r--r--chromium/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider_unittest.cc11
-rw-r--r--chromium/components/ntp_snippets/user_classifier.cc11
-rw-r--r--chromium/components/ntp_snippets/user_classifier.h4
-rw-r--r--chromium/components/ntp_snippets/user_classifier_unittest.cc14
55 files changed, 652 insertions, 407 deletions
diff --git a/chromium/components/ntp_snippets/BUILD.gn b/chromium/components/ntp_snippets/BUILD.gn
index 85afd4a5ff8..6129de984c8 100644
--- a/chromium/components/ntp_snippets/BUILD.gn
+++ b/chromium/components/ntp_snippets/BUILD.gn
@@ -161,6 +161,7 @@ static_library("ntp_snippets") {
"//components/variations/net",
"//components/variations/service",
"//components/web_resource",
+ "//services/identity/public/cpp",
"//third_party/icu/",
"//ui/gfx",
]
@@ -249,6 +250,7 @@ source_set("unit_tests") {
"//components/web_resource:web_resource",
"//google_apis/gcm",
"//net:test_support",
+ "//services/identity/public/cpp",
"//testing/gtest",
"//third_party/icu/",
"//ui/gfx:test_support",
diff --git a/chromium/components/ntp_snippets/DEPS b/chromium/components/ntp_snippets/DEPS
index 9e6b868768e..1fbc017dcb0 100644
--- a/chromium/components/ntp_snippets/DEPS
+++ b/chromium/components/ntp_snippets/DEPS
@@ -25,6 +25,7 @@ include_rules = [
"+net/traffic_annotation",
"+net/url_request",
"+google_apis",
+ "+services/identity/public/cpp",
"+ui/base",
"+ui/gfx",
]
diff --git a/chromium/components/ntp_snippets/bookmarks/bookmark_suggestions_provider_unittest.cc b/chromium/components/ntp_snippets/bookmarks/bookmark_suggestions_provider_unittest.cc
index 901ae4d7b5a..4be409f1013 100644
--- a/chromium/components/ntp_snippets/bookmarks/bookmark_suggestions_provider_unittest.cc
+++ b/chromium/components/ntp_snippets/bookmarks/bookmark_suggestions_provider_unittest.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_task_environment.h"
#include "components/bookmarks/browser/bookmark_model.h"
@@ -54,7 +53,7 @@ class BookmarkSuggestionsProviderTest : public ::testing::Test {
CategoryStatus::AVAILABLE))
.RetiresOnSaturation();
provider_ =
- base::MakeUnique<BookmarkSuggestionsProvider>(&observer_, model_.get());
+ std::make_unique<BookmarkSuggestionsProvider>(&observer_, model_.get());
scoped_task_environment_.RunUntilIdle();
}
diff --git a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.cc b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.cc
index 8357900d6d7..cd346d4635f 100644
--- a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.cc
+++ b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.cc
@@ -95,7 +95,7 @@ BreakingNewsGCMAppHandler::BreakingNewsGCMAppHandler(
PrefService* pref_service,
std::unique_ptr<SubscriptionManager> subscription_manager,
const ParseJSONCallback& parse_json_callback,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
std::unique_ptr<base::OneShotTimer> token_validation_timer,
std::unique_ptr<base::OneShotTimer> forced_subscription_timer)
: gcm_driver_(gcm_driver),
@@ -103,7 +103,7 @@ BreakingNewsGCMAppHandler::BreakingNewsGCMAppHandler(
pref_service_(pref_service),
subscription_manager_(std::move(subscription_manager)),
parse_json_callback_(parse_json_callback),
- clock_(std::move(clock)),
+ clock_(clock),
token_validation_timer_(std::move(token_validation_timer)),
forced_subscription_timer_(std::move(forced_subscription_timer)),
weak_ptr_factory_(this) {
@@ -112,6 +112,8 @@ BreakingNewsGCMAppHandler::BreakingNewsGCMAppHandler(
#endif // !OS_ANDROID
DCHECK(token_validation_timer_);
DCHECK(!token_validation_timer_->IsRunning());
+ DCHECK(forced_subscription_timer_);
+ DCHECK(!forced_subscription_timer_->IsRunning());
}
BreakingNewsGCMAppHandler::~BreakingNewsGCMAppHandler() {
@@ -170,6 +172,8 @@ void BreakingNewsGCMAppHandler::Subscribe(bool force_token_retrieval) {
return;
}
+ // TODO(vitaliii): Use |BindOnce| instead of |Bind|, because the callback is
+ // meant to be run only once.
instance_id_driver_->GetInstanceID(kBreakingNewsGCMAppID)
->GetToken(kBreakingNewsGCMSenderId, kGCMScope,
/*options=*/std::map<std::string, std::string>(),
@@ -180,6 +184,12 @@ void BreakingNewsGCMAppHandler::Subscribe(bool force_token_retrieval) {
void BreakingNewsGCMAppHandler::DidRetrieveToken(
const std::string& subscription_token,
InstanceID::Result result) {
+ if (!IsListening()) {
+ // After we requested the token, |StopListening| has been called. Thus,
+ // ignore the token.
+ return;
+ }
+
metrics::OnTokenRetrieved(result);
switch (result) {
@@ -215,6 +225,8 @@ void BreakingNewsGCMAppHandler::ResubscribeIfInvalidToken() {
// InstanceIDAndroid::ValidateToken just returns |true| on Android. Instead it
// is ok to retrieve a token, because it is cached.
+ // TODO(vitaliii): Use |BindOnce| instead of |Bind|, because the callback is
+ // meant to be run only once.
instance_id_driver_->GetInstanceID(kBreakingNewsGCMAppID)
->GetToken(
kBreakingNewsGCMSenderId, kGCMScope,
@@ -226,6 +238,12 @@ void BreakingNewsGCMAppHandler::ResubscribeIfInvalidToken() {
void BreakingNewsGCMAppHandler::DidReceiveTokenForValidation(
const std::string& new_token,
InstanceID::Result result) {
+ if (!IsListening()) {
+ // After we requested the token, |StopListening| has been called. Thus,
+ // ignore the token.
+ return;
+ }
+
metrics::OnTokenRetrieved(result);
base::Optional<base::TimeDelta> time_since_last_validation;
diff --git a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.h b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.h
index 49a510d07e3..0aa27adfdda 100644
--- a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.h
+++ b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler.h
@@ -53,7 +53,7 @@ class BreakingNewsGCMAppHandler : public BreakingNewsListener,
PrefService* pref_service_,
std::unique_ptr<SubscriptionManager> subscription_manager,
const ParseJSONCallback& parse_json_callback,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
std::unique_ptr<base::OneShotTimer> token_validation_timer,
std::unique_ptr<base::OneShotTimer> forced_subscription_timer);
@@ -128,7 +128,7 @@ class BreakingNewsGCMAppHandler : public BreakingNewsListener,
PrefService* const pref_service_;
const std::unique_ptr<SubscriptionManager> subscription_manager_;
const ParseJSONCallback parse_json_callback_;
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
// Called every time a push-by-value message is received to notify the
// observer.
diff --git a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc
index ab9bf7edf3e..c339057e57b 100644
--- a/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc
+++ b/chromium/components/ntp_snippets/breaking_news/breaking_news_gcm_app_handler_unittest.cc
@@ -8,7 +8,6 @@
#include <string>
#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/test/histogram_tester.h"
#include "base/test/mock_callback.h"
@@ -32,6 +31,7 @@
#include "google_apis/gcm/engine/account_mapping.h"
#include "testing/gmock/include/gmock/gmock.h"
+using base::Clock;
using base::TestMockTimeTaskRunner;
using base::TickClock;
using base::TimeTicks;
@@ -44,6 +44,7 @@ using testing::AtMost;
using testing::ElementsAre;
using testing::IsEmpty;
using testing::NiceMock;
+using testing::SaveArg;
using testing::StrictMock;
namespace ntp_snippets {
@@ -239,9 +240,9 @@ class BreakingNewsGCMAppHandlerTest : public testing::Test {
// Our app handler obtains InstanceID through InstanceIDDriver. We mock
// InstanceIDDriver and return MockInstanceID through it.
mock_instance_id_driver_ =
- base::MakeUnique<StrictMock<MockInstanceIDDriver>>();
- mock_instance_id_ = base::MakeUnique<StrictMock<MockInstanceID>>();
- mock_gcm_driver_ = base::MakeUnique<StrictMock<MockGCMDriver>>();
+ std::make_unique<StrictMock<MockInstanceIDDriver>>();
+ mock_instance_id_ = std::make_unique<StrictMock<MockInstanceID>>();
+ mock_gcm_driver_ = std::make_unique<StrictMock<MockGCMDriver>>();
BreakingNewsGCMAppHandler::RegisterProfilePrefs(
utils_.pref_service()->registry());
@@ -253,27 +254,28 @@ class BreakingNewsGCMAppHandlerTest : public testing::Test {
std::unique_ptr<BreakingNewsGCMAppHandler> MakeHandler(
scoped_refptr<TestMockTimeTaskRunner> timer_mock_task_runner) {
tick_clock_ = timer_mock_task_runner->GetMockTickClock();
+ clock_ = timer_mock_task_runner->GetMockClock();
+
message_loop_.SetTaskRunner(timer_mock_task_runner);
// TODO(vitaliii): Initialize MockSubscriptionManager in the constructor, so
// that one could set up expectations before creating the handler.
auto wrapped_mock_subscription_manager =
- base::MakeUnique<NiceMock<MockSubscriptionManager>>();
+ std::make_unique<NiceMock<MockSubscriptionManager>>();
mock_subscription_manager_ = wrapped_mock_subscription_manager.get();
auto token_validation_timer =
- base::MakeUnique<base::OneShotTimer>(tick_clock_.get());
+ std::make_unique<base::OneShotTimer>(tick_clock_.get());
token_validation_timer->SetTaskRunner(timer_mock_task_runner);
auto forced_subscription_timer =
- base::MakeUnique<base::OneShotTimer>(tick_clock_.get());
+ std::make_unique<base::OneShotTimer>(tick_clock_.get());
forced_subscription_timer->SetTaskRunner(timer_mock_task_runner);
- return base::MakeUnique<BreakingNewsGCMAppHandler>(
+ return std::make_unique<BreakingNewsGCMAppHandler>(
mock_gcm_driver_.get(), mock_instance_id_driver_.get(), pref_service(),
std::move(wrapped_mock_subscription_manager), base::Bind(&ParseJson),
- timer_mock_task_runner->GetMockClock(),
- std::move(token_validation_timer),
+ clock_.get(), std::move(token_validation_timer),
std::move(forced_subscription_timer));
}
@@ -310,6 +312,7 @@ class BreakingNewsGCMAppHandlerTest : public testing::Test {
std::unique_ptr<StrictMock<MockInstanceIDDriver>> mock_instance_id_driver_;
std::unique_ptr<StrictMock<MockInstanceID>> mock_instance_id_;
std::unique_ptr<TickClock> tick_clock_;
+ std::unique_ptr<Clock> clock_;
};
TEST_F(BreakingNewsGCMAppHandlerTest,
@@ -327,7 +330,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
"token");
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
// Check that the handler validates the token through GetToken. ValidateToken
// always returns true on Android, so it's not useful. Instead, the handler
@@ -359,7 +362,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
// Check that handler does not validate the token yet.
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _)).Times(0);
@@ -394,7 +397,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldNotValidateTokenBeforeListening) {
// though a validation is due.
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _)).Times(0);
EXPECT_CALL(*mock_instance_id(), ValidateToken(_, _, _, _)).Times(0);
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
task_runner->FastForwardBy(10 * GetTokenValidationPeriod());
}
@@ -420,7 +423,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
// though a validation is due.
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _)).Times(0);
EXPECT_CALL(*mock_instance_id(), ValidateToken(_, _, _, _)).Times(0);
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -442,7 +445,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
// There is no token yet, thus, handler retrieves it on StartListening.
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
@@ -482,7 +485,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -521,7 +524,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -553,7 +556,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -570,13 +573,108 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
}
TEST_F(BreakingNewsGCMAppHandlerTest,
+ ShouldIgnoreTokenReceivedAfterStopListening) {
+ // The last validation time is used to ensure that GetToken callback is
+ // ignored. Thus, enable validation.
+ SetFeatureParams(/*enable_token_validation=*/true,
+ /*enable_forced_subscription=*/false);
+
+ // The next validation won't be soon.
+ const base::TimeDelta time_to_validation = base::TimeDelta::FromDays(5);
+ const base::Time last_validation =
+ GetDummyNow() - (GetTokenValidationPeriod() - time_to_validation);
+ pref_service()->SetInt64(prefs::kBreakingNewsGCMLastTokenValidationTime,
+ SerializeTime(last_validation));
+
+ scoped_refptr<TestMockTimeTaskRunner> task_runner(
+ new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
+
+ // Save the GetToken callback during the subscription.
+ base::RepeatingCallback<void(const std::string&, InstanceID::Result)>
+ get_token_callback;
+ EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
+ .WillOnce(SaveArg<3>(&get_token_callback));
+ handler->StartListening(
+ base::BindRepeating(
+ [](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
+ base::BindRepeating([]() {}));
+
+ // The client stops listening for the push updates.
+ handler->StopListening();
+
+ // The GCM returns the new token (it does not know that we are not interested
+ // anymore). Imitate an asynchronous call via time delay.
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
+ get_token_callback.Run("new_token", InstanceID::Result::SUCCESS);
+
+ // The new token must be completely ignored. It should not be saved.
+ EXPECT_EQ("", pref_service()->GetString(
+ prefs::kBreakingNewsGCMSubscriptionTokenCache));
+ // The validation should not be rescheduled.
+ EXPECT_EQ(last_validation,
+ DeserializeTime(pref_service()->GetInt64(
+ prefs::kBreakingNewsGCMLastTokenValidationTime)));
+}
+
+TEST_F(BreakingNewsGCMAppHandlerTest,
+ ShouldIgnoreTokenReceivedForValidationAfterStopListening) {
+ SetFeatureParams(/*enable_token_validation=*/true,
+ /*enable_forced_subscription=*/false);
+
+ // The next validation will be soon.
+ const base::TimeDelta time_to_validation = base::TimeDelta::FromHours(1);
+ const base::Time last_validation =
+ GetDummyNow() - (GetTokenValidationPeriod() - time_to_validation);
+ pref_service()->SetInt64(prefs::kBreakingNewsGCMLastTokenValidationTime,
+ SerializeTime(last_validation));
+ // Omit receiving the token by putting it there directly.
+ pref_service()->SetString(prefs::kBreakingNewsGCMSubscriptionTokenCache,
+ "old_token");
+
+ scoped_refptr<TestMockTimeTaskRunner> task_runner(
+ new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
+ handler->StartListening(
+ base::BindRepeating(
+ [](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
+ base::BindRepeating([]() {}));
+
+ task_runner->FastForwardBy(time_to_validation -
+ base::TimeDelta::FromSeconds(1));
+
+ // Save the GetToken callback during the validation.
+ base::RepeatingCallback<void(const std::string&, InstanceID::Result)>
+ get_token_callback;
+ EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
+ .WillOnce(SaveArg<3>(&get_token_callback));
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
+
+ // The client stops listening for the push updates.
+ handler->StopListening();
+
+ // The GCM returns the new token (it does not know that we are not interested
+ // anymore).
+ task_runner->FastForwardBy(base::TimeDelta::FromSeconds(1));
+ get_token_callback.Run("new_token", InstanceID::Result::SUCCESS);
+
+ // The new token must be completely ignored. It should not be saved.
+ EXPECT_EQ("old_token", pref_service()->GetString(
+ prefs::kBreakingNewsGCMSubscriptionTokenCache));
+ // The validation should not occur.
+ EXPECT_EQ(last_validation,
+ DeserializeTime(pref_service()->GetInt64(
+ prefs::kBreakingNewsGCMLastTokenValidationTime)));
+}
+
+TEST_F(BreakingNewsGCMAppHandlerTest,
IsListeningShouldReturnFalseBeforeListening) {
SetFeatureParams(/*enable_token_validation=*/false,
/*enable_forced_subscription=*/false);
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
EXPECT_FALSE(handler->IsListening());
}
@@ -588,7 +686,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
ASSERT_FALSE(handler->IsListening());
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
@@ -608,7 +706,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
ASSERT_FALSE(handler->IsListening());
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
@@ -631,7 +729,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
ASSERT_FALSE(handler->IsListening());
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
@@ -666,7 +764,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldForceSubscribeImmediatelyIfDue) {
"token");
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
@@ -691,7 +789,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
"token");
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
// Check that handler does not force subscribe yet.
handler->StartListening(
@@ -727,7 +825,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldNotForceSubscribeBeforeListening) {
// Check that handler does not force subscribe before StartListening even
// though a forced subscription is due.
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
EXPECT_CALL(*mock_subscription_manager(), Subscribe("token")).Times(0);
task_runner->FastForwardBy(10 * GetForcedSubscriptionPeriod());
}
@@ -751,7 +849,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
// Check that handler does not force subscribe after StopListening even
// though a forced subscription is due.
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -777,7 +875,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -820,7 +918,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -855,7 +953,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportMissingAction) {
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -880,7 +978,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportInvalidAction) {
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -909,7 +1007,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportPushToRefreshAction) {
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -938,7 +1036,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportPushByValueAction) {
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -984,7 +1082,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
MockOnNewRemoteSuggestionCallback mock_on_new_remote_suggestion_callback;
@@ -1010,7 +1108,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
base::MockCallback<BreakingNewsListener::OnRefreshRequestedCallback>
on_refresh_requested_callback;
@@ -1033,7 +1131,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest, ShouldReportTokenRetrievalResult) {
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
EXPECT_CALL(*mock_instance_id(), GetToken(_, _, _, _))
.WillOnce(InvokeCallbackArgument<3>(/*token=*/"",
@@ -1068,7 +1166,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
@@ -1115,7 +1213,7 @@ TEST_F(BreakingNewsGCMAppHandlerTest,
scoped_refptr<TestMockTimeTaskRunner> task_runner(
new TestMockTimeTaskRunner(GetDummyNow(), TimeTicks::Now()));
- auto handler = MakeHandler(task_runner);
+ std::unique_ptr<BreakingNewsGCMAppHandler> handler = MakeHandler(task_runner);
handler->StartListening(
base::Bind([](std::unique_ptr<RemoteSuggestion> remote_suggestion) {}),
base::Bind([]() {}));
diff --git a/chromium/components/ntp_snippets/breaking_news/subscription_json_request.cc b/chromium/components/ntp_snippets/breaking_news/subscription_json_request.cc
index b28ea54e1bc..7e000ca70b2 100644
--- a/chromium/components/ntp_snippets/breaking_news/subscription_json_request.cc
+++ b/chromium/components/ntp_snippets/breaking_news/subscription_json_request.cc
@@ -125,13 +125,10 @@ std::string SubscriptionJsonRequest::Builder::BuildHeaders() const {
headers.SetHeader(HttpRequestHeaders::kAuthorization, auth_header_);
}
// Add X-Client-Data header with experiment IDs from field trials.
- // Note: It's OK to pass |is_signed_in| false if it's unknown, as it does
- // not affect transmission of experiments coming from the variations server.
- variations::AppendVariationHeaders(url_,
- false, // incognito
- false, // uma_enabled
- false, // is_signed_in
- &headers);
+ // Note: It's OK to pass SignedIn::kNo if it's unknown, as it does not affect
+ // transmission of experiments coming from the variations server.
+ variations::AppendVariationHeaders(url_, variations::InIncognito::kNo,
+ variations::SignedIn::kNo, &headers);
return headers.ToString();
}
diff --git a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc
index 4eb5bca0f6b..49a84fad3c5 100644
--- a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc
+++ b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.cc
@@ -5,7 +5,6 @@
#include "components/ntp_snippets/breaking_news/subscription_manager_impl.h"
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial_params.h"
#include "base/strings/stringprintf.h"
#include "components/ntp_snippets/breaking_news/breaking_news_metrics.h"
@@ -15,10 +14,10 @@
#include "components/ntp_snippets/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/access_token_fetcher.h"
#include "components/signin/core/browser/signin_manager_base.h"
#include "components/variations/service/variations_service.h"
#include "net/base/url_util.h"
+#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
namespace ntp_snippets {
@@ -73,7 +72,7 @@ SubscriptionManagerImpl::SubscriptionManagerImpl(
pref_service_(pref_service),
variations_service_(variations_service),
signin_manager_(signin_manager),
- signin_observer_(base::MakeUnique<SigninObserver>(
+ signin_observer_(std::make_unique<SigninObserver>(
signin_manager,
base::Bind(&SubscriptionManagerImpl::SigninStatusChanged,
base::Unretained(this)))),
@@ -133,10 +132,12 @@ void SubscriptionManagerImpl::StartAccessTokenRequest(
}
OAuth2TokenService::ScopeSet scopes = {kContentSuggestionsApiScope};
- access_token_fetcher_ = base::MakeUnique<AccessTokenFetcher>(
+ access_token_fetcher_ = std::make_unique<
+ identity::PrimaryAccountAccessTokenFetcher>(
"ntp_snippets", signin_manager_, access_token_service_, scopes,
base::BindOnce(&SubscriptionManagerImpl::AccessTokenFetchFinished,
- base::Unretained(this), subscription_token));
+ base::Unretained(this), subscription_token),
+ identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable);
}
void SubscriptionManagerImpl::AccessTokenFetchFinished(
@@ -145,8 +146,8 @@ void SubscriptionManagerImpl::AccessTokenFetchFinished(
const std::string& access_token) {
// Delete the fetcher only after we leave this method (which is called from
// the fetcher itself).
- std::unique_ptr<AccessTokenFetcher> access_token_fetcher_deleter(
- std::move(access_token_fetcher_));
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher>
+ access_token_fetcher_deleter(std::move(access_token_fetcher_));
if (error.state() != GoogleServiceAuthError::NONE) {
// In case of error, we will retry on next Chrome restart.
diff --git a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.h b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.h
index 40874fa844a..fbaf1600d8b 100644
--- a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.h
+++ b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl.h
@@ -15,11 +15,14 @@
#include "net/url_request/url_request_context_getter.h"
#include "url/gurl.h"
-class AccessTokenFetcher;
class OAuth2TokenService;
class PrefRegistrySimple;
class PrefService;
+namespace identity {
+class PrimaryAccountAccessTokenFetcher;
+}
+
namespace variations {
class VariationsService;
}
@@ -88,7 +91,8 @@ class SubscriptionManagerImpl : public SubscriptionManager {
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
std::unique_ptr<internal::SubscriptionJsonRequest> request_;
- std::unique_ptr<AccessTokenFetcher> access_token_fetcher_;
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher>
+ access_token_fetcher_;
PrefService* pref_service_;
diff --git a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc
index c6acac363fb..7c39b7db937 100644
--- a/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/breaking_news/subscription_manager_impl_unittest.cc
@@ -38,7 +38,9 @@ const char kUnsubscriptionUrlSignedIn[] = "http://valid-url.test/unsubscribe";
const char kUnsubscriptionUrlSignedOut[] =
"http://valid-url.test/unsubscribe?key=fakeAPIkey";
-class SubscriptionManagerImplTest : public testing::Test {
+class SubscriptionManagerImplTest
+ : public testing::Test,
+ public OAuth2TokenService::DiagnosticsObserver {
public:
SubscriptionManagerImplTest()
: request_context_getter_(
@@ -51,6 +53,11 @@ class SubscriptionManagerImplTest : public testing::Test {
signin::RegisterAccountConsistencyProfilePrefs(
utils_.pref_service()->registry());
signin::SetGaiaOriginIsolatedCallback(base::Bind([] { return true; }));
+ utils_.token_service()->AddDiagnosticsObserver(this);
+ }
+
+ void TearDown() override {
+ utils_.token_service()->RemoveDiagnosticsObserver(this);
}
scoped_refptr<net::URLRequestContextGetter> GetRequestContext() {
@@ -133,6 +140,10 @@ class SubscriptionManagerImplTest : public testing::Test {
base::Time::Max());
}
+ void set_on_access_token_request_callback(base::OnceClosure callback) {
+ on_access_token_request_callback_ = std::move(callback);
+ }
+
private:
void RespondSuccessfully() {
net::TestURLFetcher* url_fetcher = GetRunningFetcher();
@@ -151,10 +162,20 @@ class SubscriptionManagerImplTest : public testing::Test {
url_fetcher->delegate()->OnURLFetchComplete(url_fetcher);
}
+ // OAuth2TokenService::DiagnosticsObserver:
+ void OnAccessTokenRequested(
+ const std::string& account_id,
+ const std::string& consumer_id,
+ const OAuth2TokenService::ScopeSet& scopes) override {
+ if (on_access_token_request_callback_)
+ std::move(on_access_token_request_callback_).Run();
+ }
+
base::MessageLoop message_loop_;
test::RemoteSuggestionsTestUtils utils_;
scoped_refptr<net::TestURLRequestContextGetter> request_context_getter_;
net::TestURLFetcherFactory url_fetcher_factory_;
+ base::OnceClosure on_access_token_request_callback_;
};
TEST_F(SubscriptionManagerImplTest, SubscribeSuccessfully) {
@@ -179,6 +200,9 @@ TEST_F(SubscriptionManagerImplTest, SubscribeSuccessfully) {
#if !defined(OS_CHROMEOS)
TEST_F(SubscriptionManagerImplTest,
ShouldSubscribeWithAuthenticationWhenAuthenticated) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
// Sign in.
FakeProfileOAuth2TokenService* auth_token_service = GetOAuth2TokenService();
SignIn();
@@ -192,6 +216,8 @@ TEST_F(SubscriptionManagerImplTest,
/*locale=*/"", kAPIKey, GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl));
manager.Subscribe(subscription_token);
+ run_loop.Run();
+
// Make sure that subscription is pending an access token.
ASSERT_FALSE(manager.IsSubscribed());
ASSERT_EQ(1u, auth_token_service->GetPendingRequests().size());
@@ -274,10 +300,15 @@ TEST_F(SubscriptionManagerImplTest,
RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/false);
ASSERT_FALSE(manager.NeedsToResubscribe());
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
// Sign in. This should trigger a resubscribe.
SignIn();
IssueRefreshToken(auth_token_service);
ASSERT_TRUE(manager.NeedsToResubscribe());
+
+ run_loop.Run();
ASSERT_EQ(1u, auth_token_service->GetPendingRequests().size());
IssueAccessToken(auth_token_service);
RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/true);
@@ -293,6 +324,9 @@ TEST_F(SubscriptionManagerImplTest,
#if !defined(OS_CHROMEOS)
TEST_F(SubscriptionManagerImplTest,
ShouldResubscribeIfSignOutAfterSubscription) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
// Signin and subscribe.
FakeProfileOAuth2TokenService* auth_token_service = GetOAuth2TokenService();
SignIn();
@@ -303,6 +337,7 @@ TEST_F(SubscriptionManagerImplTest,
/*variations_service=*/nullptr, GetSigninManager(), auth_token_service,
/*locale=*/"", kAPIKey, GURL(kSubscriptionUrl), GURL(kUnsubscriptionUrl));
manager.Subscribe(subscription_token);
+ run_loop.Run();
ASSERT_EQ(1u, auth_token_service->GetPendingRequests().size());
IssueAccessToken(auth_token_service);
RespondToSubscriptionRequestSuccessfully(/*is_signed_in=*/true);
diff --git a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.cc b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.cc
index 57a7e96acb2..a62443f5ecb 100644
--- a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.cc
+++ b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.cc
@@ -8,7 +8,6 @@
#include <string>
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/values.h"
@@ -143,10 +142,9 @@ std::string GetOptionalCategoryAsString(
} // namespace
-ClickBasedCategoryRanker::ClickBasedCategoryRanker(
- PrefService* pref_service,
- std::unique_ptr<base::Clock> clock)
- : pref_service_(pref_service), clock_(std::move(clock)) {
+ClickBasedCategoryRanker::ClickBasedCategoryRanker(PrefService* pref_service,
+ base::Clock* clock)
+ : pref_service_(pref_service), clock_(clock) {
if (!ReadOrderFromPrefs(&ordered_categories_)) {
// TODO(crbug.com/676273): Handle adding new hardcoded KnownCategories to
// existing order from prefs. Currently such new category is completely
@@ -507,7 +505,7 @@ void ClickBasedCategoryRanker::StoreOrderToPrefs(
const std::vector<RankedCategory>& ordered_categories) {
base::ListValue list;
for (const RankedCategory& category : ordered_categories) {
- auto dictionary = base::MakeUnique<base::DictionaryValue>();
+ auto dictionary = std::make_unique<base::DictionaryValue>();
dictionary->SetInteger(kCategoryIdKey, category.category.id());
dictionary->SetInteger(kClicksKey, category.clicks);
dictionary->SetString(
diff --git a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.h b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.h
index 1c69ec913d7..5f998d60220 100644
--- a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.h
+++ b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker.h
@@ -30,7 +30,7 @@ namespace ntp_snippets {
class ClickBasedCategoryRanker : public CategoryRanker {
public:
explicit ClickBasedCategoryRanker(PrefService* pref_service,
- std::unique_ptr<base::Clock> clock);
+ base::Clock* clock);
~ClickBasedCategoryRanker() override;
// CategoryRanker implementation.
@@ -93,7 +93,7 @@ class ClickBasedCategoryRanker : public CategoryRanker {
std::vector<RankedCategory> ordered_categories_;
PrefService* pref_service_;
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
base::Optional<Category> promoted_category_;
DISALLOW_COPY_AND_ASSIGN(ClickBasedCategoryRanker);
diff --git a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc
index ec0655011d2..8bd537e8404 100644
--- a/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc
+++ b/chromium/components/ntp_snippets/category_rankers/click_based_category_ranker_unittest.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/test/histogram_tester.h"
#include "base/test/simple_test_clock.h"
@@ -37,13 +36,13 @@ const char kHistogramMovedUpCategoryNewIndex[] =
class ClickBasedCategoryRankerTest : public testing::Test {
public:
ClickBasedCategoryRankerTest()
- : pref_service_(base::MakeUnique<TestingPrefServiceSimple>()),
+ : pref_service_(std::make_unique<TestingPrefServiceSimple>()),
unused_remote_category_id_(
static_cast<int>(KnownCategories::LAST_KNOWN_REMOTE_CATEGORY) + 1) {
ClickBasedCategoryRanker::RegisterProfilePrefs(pref_service_->registry());
- ranker_ = base::MakeUnique<ClickBasedCategoryRanker>(
- pref_service_.get(), base::MakeUnique<base::DefaultClock>());
+ ranker_ = std::make_unique<ClickBasedCategoryRanker>(
+ pref_service_.get(), base::DefaultClock::GetInstance());
}
int GetUnusedRemoteCategoryID() { return unused_remote_category_id_++; }
@@ -68,9 +67,9 @@ class ClickBasedCategoryRankerTest : public testing::Test {
}
}
- void ResetRanker(std::unique_ptr<base::Clock> clock) {
- ranker_ = base::MakeUnique<ClickBasedCategoryRanker>(pref_service_.get(),
- std::move(clock));
+ void ResetRanker(base::Clock* clock) {
+ ranker_ =
+ std::make_unique<ClickBasedCategoryRanker>(pref_service_.get(), clock);
}
void NotifyOnSuggestionOpened(int times, Category category) {
@@ -268,7 +267,7 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldPersistOrderAndClicksWhenRestarted) {
ASSERT_TRUE(CompareCategories(first, third));
// Simulate Chrome restart.
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
// The old order must be preserved.
EXPECT_TRUE(CompareCategories(third, second));
@@ -295,11 +294,10 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldDecayClickCountsWithTime) {
NotifyOnSuggestionOpened(/*times=*/first_clicks, first);
// Let multiple years pass by.
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- base::SimpleTestClock* raw_test_clock = test_clock.get();
- raw_test_clock->SetNow(base::Time::Now() + base::TimeDelta::FromDays(1000));
+ base::SimpleTestClock test_clock;
+ test_clock.SetNow(base::Time::Now() + base::TimeDelta::FromDays(1000));
// Reset the ranker to pick up the new clock.
- ResetRanker(std::move(test_clock));
+ ResetRanker(&test_clock);
// The user behavior changes and they start using the second category instead.
// According to our requirenments after such a long time it should take less
@@ -328,11 +326,10 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldDecayAfterClearHistory) {
NotifyOnSuggestionOpened(/*times=*/first_clicks, first);
// Let multiple years pass by.
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- base::SimpleTestClock* raw_test_clock = test_clock.get();
- raw_test_clock->SetNow(base::Time::Now() + base::TimeDelta::FromDays(1000));
+ base::SimpleTestClock test_clock;
+ test_clock.SetNow(base::Time::Now() + base::TimeDelta::FromDays(1000));
// Reset the ranker to pick up the new clock.
- ResetRanker(std::move(test_clock));
+ ResetRanker(&test_clock);
// It should take less than |first_clicks| for the second category to
// overtake because of decays.
@@ -359,9 +356,9 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldPersistLastDecayTimeWhenRestarted) {
ASSERT_NE(before, DeserializeTime(0));
// Ensure that |Now()| is different from |before| by injecting our clock.
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- test_clock->SetNow(base::Time::Now() + base::TimeDelta::FromSeconds(10));
- ResetRanker(std::move(test_clock));
+ base::SimpleTestClock test_clock;
+ test_clock.SetNow(base::Time::Now() + base::TimeDelta::FromSeconds(10));
+ ResetRanker(&test_clock);
EXPECT_EQ(before, ranker()->GetLastDecayTime());
}
@@ -596,7 +593,7 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldPromoteCategory) {
ASSERT_TRUE(CompareCategories(downloads, bookmarks));
ASSERT_TRUE(CompareCategories(bookmarks, articles));
SetPromotedCategoryVariationParam(articles.id());
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
EXPECT_TRUE(CompareCategories(articles, downloads));
EXPECT_TRUE(CompareCategories(articles, bookmarks));
EXPECT_FALSE(CompareCategories(downloads, articles));
@@ -608,7 +605,7 @@ TEST_F(ClickBasedCategoryRankerTest,
ShouldHandleInvalidCategoryIDForPromotion) {
SetPromotedCategoryVariationParam(
static_cast<int>(KnownCategories::LOCAL_CATEGORIES_COUNT));
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
// Make sure we have the default order.
EXPECT_TRUE(CompareCategories(
Category::FromKnownCategory(KnownCategories::PHYSICAL_WEB_PAGES),
@@ -635,7 +632,7 @@ TEST_F(ClickBasedCategoryRankerTest, ShouldEndPromotionOnSectionDismissal) {
ASSERT_TRUE(CompareCategories(physical_web, articles));
SetPromotedCategoryVariationParam(articles.id());
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
ASSERT_TRUE(CompareCategories(articles, physical_web));
@@ -653,16 +650,16 @@ TEST_F(ClickBasedCategoryRankerTest,
ASSERT_TRUE(CompareCategories(downloads, recent_tabs));
SetPromotedCategoryVariationParam(recent_tabs.id());
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
ASSERT_TRUE(CompareCategories(recent_tabs, downloads));
ranker()->OnCategoryDismissed(recent_tabs);
ASSERT_FALSE(CompareCategories(recent_tabs, downloads));
// Simulate a little over 2 weeks of time passing.
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- test_clock->SetNow(base::Time::Now() + base::TimeDelta::FromDays(15));
- ResetRanker(std::move(test_clock));
+ base::SimpleTestClock test_clock;
+ test_clock.SetNow(base::Time::Now() + base::TimeDelta::FromDays(15));
+ ResetRanker(&test_clock);
EXPECT_TRUE(CompareCategories(recent_tabs, downloads));
}
@@ -748,7 +745,7 @@ TEST_F(ClickBasedCategoryRankerTest,
IsEmpty());
SetPromotedCategoryVariationParam(second.id());
- ResetRanker(base::MakeUnique<base::DefaultClock>());
+ ResetRanker(base::DefaultClock::GetInstance());
ASSERT_FALSE(CompareCategories(first, second));
diff --git a/chromium/components/ntp_snippets/content_suggestions_provider.h b/chromium/components/ntp_snippets/content_suggestions_provider.h
index 71aeb10e15f..c22826f8880 100644
--- a/chromium/components/ntp_snippets/content_suggestions_provider.h
+++ b/chromium/components/ntp_snippets/content_suggestions_provider.h
@@ -130,8 +130,10 @@ class ContentSuggestionsProvider {
// Called when the sign in state has changed. Should be used instead of
// directly registering with the SignInManager so that the
// ContentSuggestionService can control the order of the updates between
- // the providers and the observers.
- virtual void OnSignInStateChanged() {}
+ // the providers and the observers. |has_signed_in| is true if the state
+ // change was due to the user signin in and false if the state change was due
+ // to the user signing out.
+ virtual void OnSignInStateChanged(bool has_signed_in) {}
// Used only for debugging purposes. Retrieves suggestions for the given
// |category| that have previously been dismissed and are still stored in the
diff --git a/chromium/components/ntp_snippets/content_suggestions_service.cc b/chromium/components/ntp_snippets/content_suggestions_service.cc
index 2fafcfc3fab..8acf41e78f7 100644
--- a/chromium/components/ntp_snippets/content_suggestions_service.cc
+++ b/chromium/components/ntp_snippets/content_suggestions_service.cc
@@ -526,12 +526,12 @@ void ContentSuggestionsService::OnSuggestionInvalidated(
void ContentSuggestionsService::GoogleSigninSucceeded(
const std::string& account_id,
const std::string& username) {
- OnSignInStateChanged();
+ OnSignInStateChanged(/*has_signed_in=*/true);
}
void ContentSuggestionsService::GoogleSignedOut(const std::string& account_id,
const std::string& username) {
- OnSignInStateChanged();
+ OnSignInStateChanged(/*has_signed_in=*/false);
}
// history::HistoryServiceObserver implementation.
@@ -659,10 +659,10 @@ void ContentSuggestionsService::NotifyCategoryStatusChanged(Category category) {
}
}
-void ContentSuggestionsService::OnSignInStateChanged() {
+void ContentSuggestionsService::OnSignInStateChanged(bool has_signed_in) {
// First notify the providers, so they can make the required changes.
for (const auto& provider : providers_) {
- provider->OnSignInStateChanged();
+ provider->OnSignInStateChanged(has_signed_in);
}
// Finally notify the observers so they refresh only after the backend is
diff --git a/chromium/components/ntp_snippets/content_suggestions_service.h b/chromium/components/ntp_snippets/content_suggestions_service.h
index e9c46044271..212298b0695 100644
--- a/chromium/components/ntp_snippets/content_suggestions_service.h
+++ b/chromium/components/ntp_snippets/content_suggestions_service.h
@@ -315,7 +315,7 @@ class ContentSuggestionsService : public KeyedService,
// Fires the OnCategoryStatusChanged event for the given |category|.
void NotifyCategoryStatusChanged(Category category);
- void OnSignInStateChanged();
+ void OnSignInStateChanged(bool has_signed_in);
// Re-enables a dismissed category, making querying its provider possible.
void RestoreDismissedCategory(Category category);
diff --git a/chromium/components/ntp_snippets/content_suggestions_service_unittest.cc b/chromium/components/ntp_snippets/content_suggestions_service_unittest.cc
index ea86f395395..53cf0f6be14 100644
--- a/chromium/components/ntp_snippets/content_suggestions_service_unittest.cc
+++ b/chromium/components/ntp_snippets/content_suggestions_service_unittest.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
@@ -70,8 +69,8 @@ class MockServiceObserver : public ContentSuggestionsService::Observer {
class ContentSuggestionsServiceTest : public testing::Test {
public:
ContentSuggestionsServiceTest()
- : pref_service_(base::MakeUnique<TestingPrefServiceSimple>()),
- category_ranker_(base::MakeUnique<ConstantCategoryRanker>()) {}
+ : pref_service_(std::make_unique<TestingPrefServiceSimple>()),
+ category_ranker_(std::make_unique<ConstantCategoryRanker>()) {}
void SetUp() override {
RegisterPrefs();
@@ -129,7 +128,7 @@ class ContentSuggestionsServiceTest : public testing::Test {
MockContentSuggestionsProvider* MakeRegisteredMockProvider(
const std::vector<Category>& provided_categories) {
auto provider =
- base::MakeUnique<testing::StrictMock<MockContentSuggestionsProvider>>(
+ std::make_unique<testing::StrictMock<MockContentSuggestionsProvider>>(
service(), provided_categories);
MockContentSuggestionsProvider* result = provider.get();
service()->RegisterProvider(std::move(provider));
@@ -155,14 +154,14 @@ class ContentSuggestionsServiceTest : public testing::Test {
ASSERT_FALSE(service_);
// TODO(jkrcal): Replace by a mock.
- auto user_classifier = base::MakeUnique<UserClassifier>(
- pref_service_.get(), base::MakeUnique<base::DefaultClock>());
+ auto user_classifier = std::make_unique<UserClassifier>(
+ pref_service_.get(), base::DefaultClock::GetInstance());
- service_ = base::MakeUnique<ContentSuggestionsService>(
+ service_ = std::make_unique<ContentSuggestionsService>(
enabled, /*signin_manager=*/nullptr, /*history_service=*/nullptr,
/*large_icon_service=*/nullptr, pref_service_.get(),
std::move(category_ranker_), std::move(user_classifier),
- /*scheduler=*/nullptr, /*debug_logger=*/base::MakeUnique<Logger>());
+ /*scheduler=*/nullptr, /*debug_logger=*/std::make_unique<Logger>());
}
void ResetService() {
@@ -553,7 +552,7 @@ TEST_F(ContentSuggestionsServiceTest, ShouldForwardClearHistoryToProviders) {
TEST_F(ContentSuggestionsServiceTest,
ShouldForwardClearHistoryToCategoryRanker) {
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
@@ -777,7 +776,7 @@ TEST_F(ContentSuggestionsServiceTest, ShouldReturnCategoriesInOrderToDisplay) {
const Category first_category = Category::FromRemoteCategory(1);
const Category second_category = Category::FromRemoteCategory(2);
- auto fake_ranker = base::MakeUnique<FakeCategoryRanker>();
+ auto fake_ranker = std::make_unique<FakeCategoryRanker>();
FakeCategoryRanker* raw_fake_ranker = fake_ranker.get();
SetCategoryRanker(std::move(fake_ranker));
@@ -804,7 +803,7 @@ TEST_F(ContentSuggestionsServiceTest, ShouldReturnCategoriesInOrderToDisplay) {
TEST_F(ContentSuggestionsServiceTest,
ShouldForwardDismissedCategoryToCategoryRanker) {
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
diff --git a/chromium/components/ntp_snippets/contextual/contextual_content_suggestions_service_unittest.cc b/chromium/components/ntp_snippets/contextual/contextual_content_suggestions_service_unittest.cc
index 1305a8d9efd..9c3e7dc67d4 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_content_suggestions_service_unittest.cc
+++ b/chromium/components/ntp_snippets/contextual/contextual_content_suggestions_service_unittest.cc
@@ -10,7 +10,6 @@
#include "base/bind.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/test/mock_callback.h"
@@ -123,11 +122,11 @@ class ContextualContentSuggestionsServiceTest : public testing::Test {
ContextualContentSuggestionsServiceTest() {
RequestThrottler::RegisterProfilePrefs(pref_service_.registry());
std::unique_ptr<FakeContextualSuggestionsFetcher> fetcher =
- base::MakeUnique<FakeContextualSuggestionsFetcher>();
+ std::make_unique<FakeContextualSuggestionsFetcher>();
fetcher_ = fetcher.get();
- source_ = base::MakeUnique<ContextualContentSuggestionsService>(
+ source_ = std::make_unique<ContextualContentSuggestionsService>(
std::move(fetcher),
- base::MakeUnique<FakeCachedImageFetcher>(&pref_service_),
+ std::make_unique<FakeCachedImageFetcher>(&pref_service_),
std::unique_ptr<RemoteSuggestionsDatabase>());
}
diff --git a/chromium/components/ntp_snippets/contextual/contextual_json_request.cc b/chromium/components/ntp_snippets/contextual/contextual_json_request.cc
index 2aba9e5f150..cd7d29cfd8f 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_json_request.cc
+++ b/chromium/components/ntp_snippets/contextual/contextual_json_request.cc
@@ -9,7 +9,6 @@
#include <vector>
#include "base/json/json_writer.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "components/data_use_measurement/core/data_use_user_data.h"
@@ -122,7 +121,7 @@ ContextualJsonRequest::Builder::~Builder() = default;
std::unique_ptr<ContextualJsonRequest> ContextualJsonRequest::Builder::Build()
const {
DCHECK(url_request_context_getter_);
- auto request = base::MakeUnique<ContextualJsonRequest>(parse_json_callback_);
+ auto request = std::make_unique<ContextualJsonRequest>(parse_json_callback_);
std::string body = BuildBody();
std::string headers = BuildHeaders();
request->url_fetcher_ = BuildURLFetcher(request.get(), headers, body);
@@ -176,21 +175,18 @@ std::string ContextualJsonRequest::Builder::BuildHeaders() const {
headers.SetHeader("Authorization", auth_header_);
}
// Add X-Client-Data header with experiment IDs from field trials.
- // Note: It's OK to pass |is_signed_in| false if it's unknown, as it does
- // not affect transmission of experiments coming from the variations server.
- bool is_signed_in = false;
- variations::AppendVariationHeaders(url_,
- false, // incognito
- false, // uma_enabled
- is_signed_in, &headers);
+ // Note: It's OK to pass SignedIn::kNo if it's unknown, as it does not affect
+ // transmission of experiments coming from the variations server.
+ variations::AppendVariationHeaders(url_, variations::InIncognito::kNo,
+ variations::SignedIn::kNo, &headers);
return headers.ToString();
}
std::string ContextualJsonRequest::Builder::BuildBody() const {
- auto request = base::MakeUnique<base::DictionaryValue>();
+ auto request = std::make_unique<base::DictionaryValue>();
request->SetString("url", content_url_.spec());
- auto categories = base::MakeUnique<base::ListValue>();
+ auto categories = std::make_unique<base::ListValue>();
categories->AppendString("RELATED_ARTICLES");
categories->AppendString("PUBLIC_DEBATE");
request->Set("categories", std::move(categories));
diff --git a/chromium/components/ntp_snippets/contextual/contextual_suggestion.h b/chromium/components/ntp_snippets/contextual/contextual_suggestion.h
index a7a9472e1b7..eb48dbe8fd0 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_suggestion.h
+++ b/chromium/components/ntp_snippets/contextual/contextual_suggestion.h
@@ -63,7 +63,7 @@ class ContextualSuggestion {
private:
ContextualSuggestion(const std::string& id);
- // base::MakeUnique doesn't work if the ctor is private.
+ // std::make_unique doesn't work if the ctor is private.
static std::unique_ptr<ContextualSuggestion> MakeUnique(
const std::string& id);
diff --git a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.cc b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.cc
index dfbbc8f57a2..cd45f3894b2 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.cc
+++ b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.cc
@@ -4,17 +4,16 @@
#include "components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/default_clock.h"
#include "base/time/time.h"
#include "base/values.h"
#include "components/ntp_snippets/category.h"
-#include "components/signin/core/browser/access_token_fetcher.h"
#include "components/strings/grit/components_strings.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_status.h"
+#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
#include "ui/base/l10n/l10n_util.h"
using net::HttpRequestHeaders;
@@ -171,11 +170,12 @@ void ContextualSuggestionsFetcherImpl::StartTokenRequest() {
}
OAuth2TokenService::ScopeSet scopes{kContentSuggestionsApiScope};
- token_fetcher_ = base::MakeUnique<AccessTokenFetcher>(
+ token_fetcher_ = std::make_unique<identity::PrimaryAccountAccessTokenFetcher>(
"ntp_snippets", signin_manager_, token_service_, scopes,
base::BindOnce(
&ContextualSuggestionsFetcherImpl::AccessTokenFetchFinished,
- base::Unretained(this)));
+ base::Unretained(this)),
+ identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable);
}
void ContextualSuggestionsFetcherImpl::AccessTokenFetchFinished(
@@ -184,8 +184,8 @@ void ContextualSuggestionsFetcherImpl::AccessTokenFetchFinished(
// Delete the fetcher only after we leave this method (which is called from
// the fetcher itself).
DCHECK(token_fetcher_);
- std::unique_ptr<AccessTokenFetcher> token_fetcher_deleter(
- std::move(token_fetcher_));
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher>
+ token_fetcher_deleter(std::move(token_fetcher_));
if (error.state() != GoogleServiceAuthError::NONE) {
AccessTokenError(error);
diff --git a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h
index e430c6b53bb..76bd1c849e6 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h
+++ b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl.h
@@ -21,11 +21,14 @@
#include "components/ntp_snippets/status.h"
#include "net/url_request/url_request_context_getter.h"
-class AccessTokenFetcher;
class OAuth2TokenService;
class PrefService;
class SigninManagerBase;
+namespace identity {
+class PrimaryAccountAccessTokenFetcher;
+}
+
namespace ntp_snippets {
// TODO(gaschler): Move authentication that is in common with
@@ -77,7 +80,7 @@ class ContextualSuggestionsFetcherImpl : public ContextualSuggestionsFetcher {
SigninManagerBase* signin_manager_;
OAuth2TokenService* token_service_;
- std::unique_ptr<AccessTokenFetcher> token_fetcher_;
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_;
// Holds the URL request context.
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
diff --git a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl_unittest.cc b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl_unittest.cc
index 0fed25d641b..a9615ec1094 100644
--- a/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/contextual/contextual_suggestions_fetcher_impl_unittest.cc
@@ -8,7 +8,6 @@
#include <vector>
#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
#include "base/optional.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -105,21 +104,28 @@ void ParseJson(const std::string& json,
} // namespace
-class ContextualSuggestionsFetcherTest : public testing::Test {
+class ContextualSuggestionsFetcherTest
+ : public testing::Test,
+ public OAuth2TokenService::DiagnosticsObserver {
public:
ContextualSuggestionsFetcherTest()
: fake_url_fetcher_factory_(new net::FakeURLFetcherFactory(nullptr)),
- mock_task_runner_(new base::TestMockTimeTaskRunner()),
- mock_task_runner_handle_(mock_task_runner_) {
+ mock_task_runner_(new base::TestMockTimeTaskRunner(
+ base::TestMockTimeTaskRunner::Type::kBoundToThread)) {
scoped_refptr<net::TestURLRequestContextGetter> request_context_getter =
new net::TestURLRequestContextGetter(mock_task_runner_.get());
- fake_token_service_ = base::MakeUnique<FakeProfileOAuth2TokenService>(
- base::MakeUnique<FakeOAuth2TokenServiceDelegate>(
+ fake_token_service_ = std::make_unique<FakeProfileOAuth2TokenService>(
+ std::make_unique<FakeOAuth2TokenServiceDelegate>(
request_context_getter.get()));
- fetcher_ = base::MakeUnique<ContextualSuggestionsFetcherImpl>(
+ fetcher_ = std::make_unique<ContextualSuggestionsFetcherImpl>(
test_utils_.fake_signin_manager(), fake_token_service_.get(),
std::move(request_context_getter), test_utils_.pref_service(),
base::Bind(&ParseJson));
+ fake_token_service_->AddDiagnosticsObserver(this);
+ }
+
+ ~ContextualSuggestionsFetcherTest() override {
+ fake_token_service_->RemoveDiagnosticsObserver(this);
}
void FastForwardUntilNoTasksRemain() {
@@ -159,14 +165,27 @@ class ContextualSuggestionsFetcherTest : public testing::Test {
return mock_suggestions_available_callback_;
}
+ void set_on_access_token_request_callback(base::OnceClosure callback) {
+ on_access_token_request_callback_ = std::move(callback);
+ }
+
private:
+ // OAuth2TokenService::DiagnosticsObserver:
+ void OnAccessTokenRequested(
+ const std::string& account_id,
+ const std::string& consumer_id,
+ const OAuth2TokenService::ScopeSet& scopes) override {
+ if (on_access_token_request_callback_)
+ std::move(on_access_token_request_callback_).Run();
+ }
+
std::unique_ptr<FakeProfileOAuth2TokenService> fake_token_service_;
std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_;
std::unique_ptr<ContextualSuggestionsFetcherImpl> fetcher_;
MockSuggestionsAvailableCallback mock_suggestions_available_callback_;
scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_;
- base::ThreadTaskRunnerHandle mock_task_runner_handle_;
test::RemoteSuggestionsTestUtils test_utils_;
+ base::OnceClosure on_access_token_request_callback_;
DISALLOW_COPY_AND_ASSIGN(ContextualSuggestionsFetcherTest);
};
@@ -177,6 +196,9 @@ TEST_F(ContextualSuggestionsFetcherTest, ShouldCreateFetcher) {
}
TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchSuggestion) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
InitializeFakeCredentials();
const std::string kValidResponseData =
"{\"categories\" : [{"
@@ -197,6 +219,9 @@ TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchSuggestion) {
fetcher().FetchContextualSuggestions(
GURL(kValidURL),
ToSuggestionsAvailableCallback(&mock_suggestions_available_callback()));
+
+ run_loop.Run();
+
IssueOAuth2Token();
FastForwardUntilNoTasksRemain();
EXPECT_THAT(fetcher().GetLastStatusForTesting(), Eq("OK"));
@@ -204,6 +229,9 @@ TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchSuggestion) {
}
TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchEmptySuggestionsList) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
InitializeFakeCredentials();
const std::string kValidEmptyCategoryResponseData =
"{\"categories\" : [{"
@@ -219,6 +247,9 @@ TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchEmptySuggestionsList) {
fetcher().FetchContextualSuggestions(
GURL(kValidURL),
ToSuggestionsAvailableCallback(&mock_suggestions_available_callback()));
+
+ run_loop.Run();
+
IssueOAuth2Token();
FastForwardUntilNoTasksRemain();
EXPECT_THAT(fetcher().GetLastStatusForTesting(), Eq("OK"));
@@ -228,6 +259,9 @@ TEST_F(ContextualSuggestionsFetcherTest, ShouldFetchEmptySuggestionsList) {
TEST_F(ContextualSuggestionsFetcherTest,
ShouldReportErrorForEmptyResponseData) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
InitializeFakeCredentials();
SetFakeResponse(/*response_data=*/std::string(), net::HTTP_NOT_FOUND,
net::URLRequestStatus::SUCCESS);
@@ -237,12 +271,18 @@ TEST_F(ContextualSuggestionsFetcherTest,
fetcher().FetchContextualSuggestions(
GURL(kValidURL),
ToSuggestionsAvailableCallback(&mock_suggestions_available_callback()));
+
+ run_loop.Run();
+
IssueOAuth2Token();
FastForwardUntilNoTasksRemain();
}
TEST_F(ContextualSuggestionsFetcherTest,
ShouldReportErrorForInvalidResponseData) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
InitializeFakeCredentials();
const std::string kInvalidResponseData = "{ \"recos\": []";
SetFakeResponse(/*response_data=*/kInvalidResponseData, net::HTTP_OK,
@@ -257,6 +297,9 @@ TEST_F(ContextualSuggestionsFetcherTest,
fetcher().FetchContextualSuggestions(
GURL(kValidURL),
ToSuggestionsAvailableCallback(&mock_suggestions_available_callback()));
+
+ run_loop.Run();
+
IssueOAuth2Token();
FastForwardUntilNoTasksRemain();
EXPECT_THAT(fetcher().GetLastStatusForTesting(),
diff --git a/chromium/components/ntp_snippets/features.cc b/chromium/components/ntp_snippets/features.cc
index 31823bbc963..371bfb066d7 100644
--- a/chromium/components/ntp_snippets/features.cc
+++ b/chromium/components/ntp_snippets/features.cc
@@ -5,7 +5,6 @@
#include "components/ntp_snippets/features.h"
#include "base/feature_list.h"
-#include "base/memory/ptr_util.h"
#include "base/time/clock.h"
#include "components/ntp_snippets/category_rankers/click_based_category_ranker.h"
#include "components/ntp_snippets/category_rankers/constant_category_ranker.h"
@@ -99,17 +98,16 @@ CategoryRankerChoice GetSelectedCategoryRanker(bool is_chrome_home_enabled) {
std::unique_ptr<CategoryRanker> BuildSelectedCategoryRanker(
PrefService* pref_service,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
bool is_chrome_home_enabled) {
CategoryRankerChoice choice =
ntp_snippets::GetSelectedCategoryRanker(is_chrome_home_enabled);
switch (choice) {
case CategoryRankerChoice::CONSTANT:
- return base::MakeUnique<ConstantCategoryRanker>();
+ return std::make_unique<ConstantCategoryRanker>();
case CategoryRankerChoice::CLICK_BASED:
- return base::MakeUnique<ClickBasedCategoryRanker>(pref_service,
- std::move(clock));
+ return std::make_unique<ClickBasedCategoryRanker>(pref_service, clock);
}
return nullptr;
}
diff --git a/chromium/components/ntp_snippets/features.h b/chromium/components/ntp_snippets/features.h
index 998934b08b3..09fa9d3ebb5 100644
--- a/chromium/components/ntp_snippets/features.h
+++ b/chromium/components/ntp_snippets/features.h
@@ -78,7 +78,7 @@ CategoryRankerChoice GetSelectedCategoryRanker(bool is_chrome_home_enabled);
// Builds a CategoryRanker according to kCategoryRanker feature and Chrome Home.
std::unique_ptr<CategoryRanker> BuildSelectedCategoryRanker(
PrefService* pref_service,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
bool is_chrome_home_enabled);
// Feature to choose a default category order.
diff --git a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc
index 84adf71c0c0..26ae3c53665 100644
--- a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc
+++ b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.cc
@@ -5,10 +5,10 @@
#include "components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h"
#include <algorithm>
+#include <memory>
#include <utility>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
@@ -143,12 +143,17 @@ void RecentTabSuggestionsProvider::GetDismissedSuggestionsForDebugging(
Category category,
DismissedSuggestionsCallback callback) {
DCHECK_EQ(provided_category_, category);
+ recent_tabs_ui_adapter_->GetAllItems(base::BindOnce(
+ &RecentTabSuggestionsProvider::OnGetDismissedSuggestionsForDebuggingDone,
+ weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
+}
- std::vector<OfflineItem> items = recent_tabs_ui_adapter_->GetAllItems();
-
+void RecentTabSuggestionsProvider::OnGetDismissedSuggestionsForDebuggingDone(
+ DismissedSuggestionsCallback callback,
+ const std::vector<OfflineItem>& offline_items) {
std::set<std::string> dismissed_ids = ReadDismissedIDsFromPrefs();
std::vector<ContentSuggestion> suggestions;
- for (const OfflineItem& item : items) {
+ for (const OfflineItem& item : offline_items) {
int64_t offline_page_id =
recent_tabs_ui_adapter_->GetOfflineIdByGuid(item.id.id);
if (!dismissed_ids.count(base::IntToString(offline_page_id))) {
@@ -157,6 +162,7 @@ void RecentTabSuggestionsProvider::GetDismissedSuggestionsForDebugging(
suggestions.push_back(ConvertUIItem(item));
}
+
std::move(callback).Run(std::move(suggestions));
}
@@ -200,13 +206,19 @@ void RecentTabSuggestionsProvider::OnItemRemoved(const ContentId& id) {
}
void RecentTabSuggestionsProvider::FetchRecentTabs() {
- std::vector<OfflineItem> ui_items = recent_tabs_ui_adapter_->GetAllItems();
+ recent_tabs_ui_adapter_->GetAllItems(
+ base::BindOnce(&RecentTabSuggestionsProvider::OnFetchRecentTabsDone,
+ weak_ptr_factory_.GetWeakPtr()));
+}
+
+void RecentTabSuggestionsProvider::OnFetchRecentTabsDone(
+ const std::vector<OfflineItem>& offline_items) {
NotifyStatusChanged(CategoryStatus::AVAILABLE);
std::set<std::string> old_dismissed_ids = ReadDismissedIDsFromPrefs();
std::set<std::string> new_dismissed_ids;
std::vector<OfflineItem> non_dismissed_items;
- for (const OfflineItem& item : ui_items) {
+ for (const OfflineItem& item : offline_items) {
std::string offline_page_id = base::IntToString(
recent_tabs_ui_adapter_->GetOfflineIdByGuid(item.id.id));
if (old_dismissed_ids.count(offline_page_id)) {
@@ -245,7 +257,7 @@ ContentSuggestion RecentTabSuggestionsProvider::ConvertUIItem(
suggestion.set_title(base::UTF8ToUTF16(ui_item.title));
suggestion.set_publish_date(ui_item.creation_time);
suggestion.set_publisher_name(base::UTF8ToUTF16(ui_item.page_url.host()));
- auto extra = base::MakeUnique<RecentTabSuggestionExtra>();
+ auto extra = std::make_unique<RecentTabSuggestionExtra>();
int tab_id;
bool success = base::StringToInt(ui_item.id.id, &tab_id);
DCHECK(success);
diff --git a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h
index 0dd05266ff0..2fb467ffe6b 100644
--- a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h
+++ b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h
@@ -74,6 +74,11 @@ class RecentTabSuggestionsProvider : public ContentSuggestionsProvider,
// Manually requests all Recent Tabs UI items and updates the suggestions.
void FetchRecentTabs();
+ void OnFetchRecentTabsDone(const std::vector<OfflineItem>& offline_items);
+
+ void OnGetDismissedSuggestionsForDebuggingDone(
+ DismissedSuggestionsCallback callback,
+ const std::vector<OfflineItem>& offline_items);
// Converts an OfflineItem to a ContentSuggestion for the
// |provided_category_|.
diff --git a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider_unittest.cc b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider_unittest.cc
index c43ad141d2b..e5055d8c3de 100644
--- a/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider_unittest.cc
+++ b/chromium/components/ntp_snippets/offline_pages/recent_tab_suggestions_provider_unittest.cc
@@ -4,6 +4,7 @@
#include "components/ntp_snippets/offline_pages/recent_tab_suggestions_provider.h"
+#include <memory>
#include <string>
#include <vector>
@@ -78,7 +79,7 @@ class RecentTabSuggestionsProviderTestNoLoad : public testing::Test {
RecentTabSuggestionsProvider::RegisterProfilePrefs(
pref_service()->registry());
- taco_ = base::MakeUnique<offline_pages::RequestCoordinatorStubTaco>();
+ taco_ = std::make_unique<offline_pages::RequestCoordinatorStubTaco>();
taco_->CreateRequestCoordinator();
ui_adapter_ = offline_pages::RecentTabsUIAdapterDelegate::
@@ -86,7 +87,7 @@ class RecentTabSuggestionsProviderTestNoLoad : public testing::Test {
delegate_ =
offline_pages::RecentTabsUIAdapterDelegate::FromDownloadUIAdapter(
ui_adapter_);
- provider_ = base::MakeUnique<RecentTabSuggestionsProvider>(
+ provider_ = std::make_unique<RecentTabSuggestionsProvider>(
&observer_, ui_adapter_, pref_service());
}
@@ -178,6 +179,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldConvertToSuggestions) {
for (OfflinePageItem& recent_tab : recent_tabs_list) {
AddTabAndOfflinePageToModel(recent_tab);
}
+ task_runner()->RunUntilIdle();
}
TEST_F(RecentTabSuggestionsProviderTest, ShouldSortByCreationTime) {
@@ -195,6 +197,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldSortByCreationTime) {
ElementsAre(Property(&ContentSuggestion::url,
GURL("http://dummy.com/1")))));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(1, now));
+ task_runner()->RunUntilIdle();
EXPECT_CALL(
*observer(),
@@ -204,6 +207,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldSortByCreationTime) {
Property(&ContentSuggestion::url, GURL("http://dummy.com/1")),
Property(&ContentSuggestion::url, GURL("http://dummy.com/2")))));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(2, yesterday));
+ task_runner()->RunUntilIdle();
offline_pages[1].last_access_time =
offline_pages[0].last_access_time + base::TimeDelta::FromHours(1);
@@ -217,6 +221,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldSortByCreationTime) {
Property(&ContentSuggestion::url, GURL("http://dummy.com/1")),
Property(&ContentSuggestion::url, GURL("http://dummy.com/2")))));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(3, tomorrow));
+ task_runner()->RunUntilIdle();
}
TEST_F(RecentTabSuggestionsProviderTest, ShouldDeliverCorrectCategoryInfo) {
@@ -233,6 +238,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldDismiss) {
for (OfflinePageItem& recent_tab : recent_tabs_list) {
AddTabAndOfflinePageToModel(recent_tab);
}
+ task_runner()->RunUntilIdle();
// Dismiss 2 and 3.
EXPECT_CALL(*observer(), OnNewSuggestions(_, _, _)).Times(0);
@@ -250,6 +256,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldDismiss) {
Property(&ContentSuggestion::url, GURL("http://dummy.com/4")))));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(4));
+ task_runner()->RunUntilIdle();
Mock::VerifyAndClearExpectations(observer());
// And appear in the dismissed suggestions.
@@ -257,6 +264,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldDismiss) {
provider()->GetDismissedSuggestionsForDebugging(
recent_tabs_category(),
base::Bind(&CaptureDismissedSuggestions, &dismissed_suggestions));
+ task_runner()->RunUntilIdle();
EXPECT_THAT(
dismissed_suggestions,
UnorderedElementsAre(
@@ -265,18 +273,21 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldDismiss) {
// Clear dismissed suggestions.
provider()->ClearDismissedSuggestionsForDebugging(recent_tabs_category());
+ task_runner()->RunUntilIdle();
// They should be gone from the dismissed suggestions.
dismissed_suggestions.clear();
provider()->GetDismissedSuggestionsForDebugging(
recent_tabs_category(),
base::Bind(&CaptureDismissedSuggestions, &dismissed_suggestions));
+ task_runner()->RunUntilIdle();
EXPECT_THAT(dismissed_suggestions, IsEmpty());
// And appear in the reported suggestions for the category again.
EXPECT_CALL(*observer(),
OnNewSuggestions(_, recent_tabs_category(), SizeIs(5)));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(5));
+ task_runner()->RunUntilIdle();
Mock::VerifyAndClearExpectations(observer());
}
@@ -286,6 +297,7 @@ TEST_F(RecentTabSuggestionsProviderTest,
std::vector<OfflinePageItem> offline_pages = CreateDummyRecentTabs({1, 2, 3});
for (OfflinePageItem& recent_tab : offline_pages)
AddTabAndOfflinePageToModel(recent_tab);
+ task_runner()->RunUntilIdle();
// Invalidation of suggestion 2 should be forwarded.
EXPECT_CALL(*observer(), OnSuggestionInvalidated(_, GetDummySuggestionId(2)));
@@ -297,6 +309,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldClearDismissedOnInvalidate) {
std::vector<OfflinePageItem> offline_pages = CreateDummyRecentTabs({1, 2, 3});
for (OfflinePageItem& recent_tab : offline_pages)
AddTabAndOfflinePageToModel(recent_tab);
+ task_runner()->RunUntilIdle();
EXPECT_THAT(ReadDismissedIDsFromPrefs(), IsEmpty());
provider()->DismissSuggestion(GetDummySuggestionId(2));
@@ -311,6 +324,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldClearDismissedOnFetch) {
std::vector<OfflinePageItem> offline_pages = CreateDummyRecentTabs({1, 2, 3});
for (OfflinePageItem& recent_tab : offline_pages)
AddTabAndOfflinePageToModel(recent_tab);
+ task_runner()->RunUntilIdle();
provider()->DismissSuggestion(GetDummySuggestionId(2));
provider()->DismissSuggestion(GetDummySuggestionId(3));
@@ -337,6 +351,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldNotShowSameUrlMutlipleTimes) {
AddTabAndOfflinePageToModel(offline_pages[0]);
AddTabAndOfflinePageToModel(offline_pages[1]);
+ task_runner()->RunUntilIdle();
Mock::VerifyAndClearExpectations(observer());
EXPECT_CALL(*observer(),
OnNewSuggestions(
@@ -346,6 +361,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldNotShowSameUrlMutlipleTimes) {
Property(&ContentSuggestion::publish_date, tomorrow))));
AddTabAndOfflinePageToModel(offline_pages[2]);
+ task_runner()->RunUntilIdle();
}
TEST_F(RecentTabSuggestionsProviderTest,
@@ -361,6 +377,7 @@ TEST_F(RecentTabSuggestionsProviderTest,
ShouldInvalidateSuggestionWhenTabGone) {
OfflinePageItem first_tab = CreateDummyRecentTab(1);
AddTabAndOfflinePageToModel(first_tab);
+ task_runner()->RunUntilIdle();
Mock::VerifyAndClearExpectations(observer());
EXPECT_CALL(*observer(), OnSuggestionInvalidated(_, GetDummySuggestionId(1)))
@@ -391,6 +408,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldNotShowPagesWithoutTab) {
first_tab.client_id));
OfflinePageItem second_tab = CreateDummyRecentTab(2);
AddTabAndOfflinePageToModel(second_tab);
+ task_runner()->RunUntilIdle();
Mock::VerifyAndClearExpectations(observer());
@@ -410,6 +428,7 @@ TEST_F(RecentTabSuggestionsProviderTest, ShouldNotShowPagesWithoutTab) {
Property(&ContentSuggestion::url, GURL("http://dummy.com/3")))));
AddTabAndOfflinePageToModel(CreateDummyRecentTab(3));
+ task_runner()->RunUntilIdle();
}
// The following test uses a different fixture that does not automatically pump
diff --git a/chromium/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider_unittest.cc b/chromium/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider_unittest.cc
index 588eed81e30..0a2f069f2c3 100644
--- a/chromium/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider_unittest.cc
+++ b/chromium/components/ntp_snippets/physical_web_pages/physical_web_page_suggestions_provider_unittest.cc
@@ -9,7 +9,6 @@
#include <vector>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
@@ -67,7 +66,7 @@ void CompareFetchMoreResult(
class PhysicalWebPageSuggestionsProviderTest : public testing::Test {
public:
PhysicalWebPageSuggestionsProviderTest()
- : pref_service_(base::MakeUnique<TestingPrefServiceSimple>()) {
+ : pref_service_(std::make_unique<TestingPrefServiceSimple>()) {
PhysicalWebPageSuggestionsProvider::RegisterProfilePrefs(
pref_service_->registry());
}
@@ -93,7 +92,7 @@ class PhysicalWebPageSuggestionsProviderTest : public testing::Test {
PhysicalWebPageSuggestionsProvider* CreateProvider() {
DCHECK(!provider_);
- provider_ = base::MakeUnique<PhysicalWebPageSuggestionsProvider>(
+ provider_ = std::make_unique<PhysicalWebPageSuggestionsProvider>(
&observer_, &physical_web_data_source_, pref_service_.get());
return provider_.get();
}
diff --git a/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc b/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc
index 57a715f4ac1..b8a12e1d3ac 100644
--- a/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc
+++ b/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider.cc
@@ -5,10 +5,10 @@
#include "components/ntp_snippets/reading_list/reading_list_suggestions_provider.h"
#include <algorithm>
+#include <memory>
#include <vector>
#include "base/bind.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
@@ -227,7 +227,7 @@ ContentSuggestion ReadingListSuggestionsProvider::ConvertEntry(
suggestion.set_publish_date(
base::Time::FromDoubleT(entry_time / base::Time::kMicrosecondsPerSecond));
- auto extra = base::MakeUnique<ReadingListSuggestionExtra>();
+ auto extra = std::make_unique<ReadingListSuggestionExtra>();
extra->favicon_page_url =
entry->DistilledURL().is_valid() ? entry->DistilledURL() : entry->URL();
suggestion.set_reading_list_suggestion_extra(std::move(extra));
diff --git a/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider_unittest.cc b/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider_unittest.cc
index 3ed07071891..cc6065ecc9c 100644
--- a/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider_unittest.cc
+++ b/chromium/components/ntp_snippets/reading_list/reading_list_suggestions_provider_unittest.cc
@@ -4,7 +4,8 @@
#include "components/ntp_snippets/reading_list/reading_list_suggestions_provider.h"
-#include "base/memory/ptr_util.h"
+#include <memory>
+
#include "base/test/simple_test_clock.h"
#include "components/ntp_snippets/mock_content_suggestions_provider_observer.h"
#include "components/reading_list/core/reading_list_model_impl.h"
@@ -30,9 +31,9 @@ class ReadingListSuggestionsProviderTest : public ::testing::Test {
public:
ReadingListSuggestionsProviderTest() {
std::unique_ptr<base::SimpleTestClock> clock =
- base::MakeUnique<base::SimpleTestClock>();
+ std::make_unique<base::SimpleTestClock>();
clock_ = clock.get();
- model_ = base::MakeUnique<ReadingListModelImpl>(
+ model_ = std::make_unique<ReadingListModelImpl>(
/*storage_layer=*/nullptr, /*pref_service=*/nullptr, std::move(clock));
}
@@ -44,7 +45,7 @@ class ReadingListSuggestionsProviderTest : public ::testing::Test {
EXPECT_CALL(observer_, OnCategoryStatusChanged(_, ReadingListCategory(),
CategoryStatus::AVAILABLE))
.RetiresOnSaturation();
- provider_ = base::MakeUnique<ReadingListSuggestionsProvider>(&observer_,
+ provider_ = std::make_unique<ReadingListSuggestionsProvider>(&observer_,
model_.get());
}
diff --git a/chromium/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc b/chromium/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc
index b673c3c3270..48e47227776 100644
--- a/chromium/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/cached_image_fetcher_unittest.cc
@@ -10,7 +10,6 @@
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
-#include "base/memory/ptr_util.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_task_environment.h"
#include "components/image_fetcher/core/image_decoder.h"
@@ -63,15 +62,15 @@ class CachedImageFetcherTest : public testing::Test {
RequestThrottler::RegisterProfilePrefs(pref_service_.registry());
database_ =
- base::MakeUnique<RemoteSuggestionsDatabase>(database_dir_.GetPath());
+ std::make_unique<RemoteSuggestionsDatabase>(database_dir_.GetPath());
request_context_getter_ = scoped_refptr<net::TestURLRequestContextGetter>(
new net::TestURLRequestContextGetter(
scoped_task_environment_.GetMainThreadTaskRunner()));
- auto decoder = base::MakeUnique<FakeImageDecoder>();
+ auto decoder = std::make_unique<FakeImageDecoder>();
fake_image_decoder_ = decoder.get();
- cached_image_fetcher_ = base::MakeUnique<ntp_snippets::CachedImageFetcher>(
- base::MakeUnique<image_fetcher::ImageFetcherImpl>(
+ cached_image_fetcher_ = std::make_unique<ntp_snippets::CachedImageFetcher>(
+ std::make_unique<image_fetcher::ImageFetcherImpl>(
std::move(decoder), request_context_getter_.get()),
&pref_service_, database_.get());
RunUntilIdle();
diff --git a/chromium/components/ntp_snippets/remote/json_request.cc b/chromium/components/ntp_snippets/remote/json_request.cc
index b334545b4c5..fea0ee0327a 100644
--- a/chromium/components/ntp_snippets/remote/json_request.cc
+++ b/chromium/components/ntp_snippets/remote/json_request.cc
@@ -10,9 +10,8 @@
#include "base/command_line.h"
#include "base/json/json_writer.h"
-#include "base/memory/ptr_util.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
-#include "base/metrics/sparse_histogram.h"
#include "base/strings/stringprintf.h"
#include "base/time/clock.h"
#include "base/values.h"
@@ -21,9 +20,6 @@
#include "components/ntp_snippets/features.h"
#include "components/ntp_snippets/remote/request_params.h"
#include "components/ntp_snippets/user_classifier.h"
-#include "components/signin/core/browser/profile_oauth2_token_service.h"
-#include "components/signin/core/browser/signin_manager.h"
-#include "components/signin/core/browser/signin_manager_base.h"
#include "components/strings/grit/components_strings.h"
#include "components/variations/net/variations_http_headers.h"
#include "components/variations/variations_associated_data.h"
@@ -109,7 +105,7 @@ std::string ISO639FromPosixLocale(const std::string& locale) {
void AppendLanguageInfoToList(base::ListValue* list,
const UrlLanguageHistogram::LanguageInfo& info) {
- auto lang = base::MakeUnique<base::DictionaryValue>();
+ auto lang = std::make_unique<base::DictionaryValue>();
lang->SetString("language", info.language_code);
lang->SetDouble("frequency", info.frequency);
list->Append(std::move(lang));
@@ -167,9 +163,8 @@ void JsonRequest::OnURLFetchComplete(const net::URLFetcher* source) {
DCHECK_EQ(url_fetcher_.get(), source);
const URLRequestStatus& status = url_fetcher_->GetStatus();
int response = url_fetcher_->GetResponseCode();
- UMA_HISTOGRAM_SPARSE_SLOWLY(
- "NewTabPage.Snippets.FetchHttpResponseOrErrorCode",
- status.is_success() ? response : status.error());
+ base::UmaHistogramSparse("NewTabPage.Snippets.FetchHttpResponseOrErrorCode",
+ status.is_success() ? response : status.error());
if (!status.is_success()) {
std::move(request_completed_callback_)
@@ -224,7 +219,7 @@ std::unique_ptr<JsonRequest> JsonRequest::Builder::Build() const {
DCHECK(!url_.is_empty());
DCHECK(url_request_context_getter_);
DCHECK(clock_);
- auto request = base::MakeUnique<JsonRequest>(params_.exclusive_category,
+ auto request = std::make_unique<JsonRequest>(params_.exclusive_category,
clock_, parse_json_callback_);
std::string body = BuildBody();
std::string headers = BuildHeaders();
@@ -295,18 +290,15 @@ std::string JsonRequest::Builder::BuildHeaders() const {
headers.SetHeader("Authorization", auth_header_);
}
// Add X-Client-Data header with experiment IDs from field trials.
- // Note: It's OK to pass |is_signed_in| false if it's unknown, as it does
- // not affect transmission of experiments coming from the variations server.
- bool is_signed_in = false;
- variations::AppendVariationHeaders(url_,
- false, // incognito
- false, // uma_enabled
- is_signed_in, &headers);
+ // Note: It's OK to pass SignedIn::kNo if it's unknown, as it does not affect
+ // transmission of experiments coming from the variations server.
+ variations::AppendVariationHeaders(url_, variations::InIncognito::kNo,
+ variations::SignedIn::kNo, &headers);
return headers.ToString();
}
std::string JsonRequest::Builder::BuildBody() const {
- auto request = base::MakeUnique<base::DictionaryValue>();
+ auto request = std::make_unique<base::DictionaryValue>();
std::string user_locale = PosixLocaleFromBCP47Language(params_.language_code);
if (!user_locale.empty()) {
request->SetString("uiLanguage", user_locale);
@@ -316,7 +308,7 @@ std::string JsonRequest::Builder::BuildBody() const {
? "USER_ACTION"
: "BACKGROUND_PREFETCH");
- auto excluded = base::MakeUnique<base::ListValue>();
+ auto excluded = std::make_unique<base::ListValue>();
for (const auto& id : params_.excluded_ids) {
excluded->AppendString(id);
}
@@ -330,7 +322,7 @@ std::string JsonRequest::Builder::BuildBody() const {
language::UrlLanguageHistogram::LanguageInfo other_top_language;
PrepareLanguages(&ui_language, &other_top_language);
if (ui_language.frequency != 0 || other_top_language.frequency != 0) {
- auto language_list = base::MakeUnique<base::ListValue>();
+ auto language_list = std::make_unique<base::ListValue>();
if (ui_language.frequency > 0) {
AppendLanguageInfoToList(language_list.get(), ui_language);
}
diff --git a/chromium/components/ntp_snippets/remote/json_request_unittest.cc b/chromium/components/ntp_snippets/remote/json_request_unittest.cc
index a5bb3860ee7..08af1967adb 100644
--- a/chromium/components/ntp_snippets/remote/json_request_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/json_request_unittest.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/test/test_mock_time_task_runner.h"
#include "base/time/tick_clock.h"
@@ -64,7 +63,7 @@ class JsonRequestTest : public testing::Test {
ntp_snippets::kArticleSuggestionsFeature.name,
{{"send_top_languages", "true"}, {"send_user_class", "true"}},
{ntp_snippets::kArticleSuggestionsFeature.name}),
- pref_service_(base::MakeUnique<TestingPrefServiceSimple>()),
+ pref_service_(std::make_unique<TestingPrefServiceSimple>()),
mock_task_runner_(new base::TestMockTimeTaskRunner()),
clock_(mock_task_runner_->GetMockClock()),
request_context_getter_(
@@ -76,7 +75,7 @@ class JsonRequestTest : public testing::Test {
std::unique_ptr<language::UrlLanguageHistogram> MakeLanguageHistogram(
const std::set<std::string>& codes) {
std::unique_ptr<language::UrlLanguageHistogram> language_histogram =
- base::MakeUnique<language::UrlLanguageHistogram>(pref_service_.get());
+ std::make_unique<language::UrlLanguageHistogram>(pref_service_.get());
// There must be at least 10 visits before the top languages are defined.
for (int i = 0; i < 10; i++) {
for (const std::string& code : codes) {
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestion.cc b/chromium/components/ntp_snippets/remote/remote_suggestion.cc
index ccb76bcc7f1..192edcebffb 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestion.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestion.cc
@@ -309,7 +309,7 @@ ContentSuggestion RemoteSuggestion::ToContentSuggestion(
NotificationExtra extra;
extra.deadline = notification_deadline_;
suggestion.set_notification_extra(
- base::MakeUnique<NotificationExtra>(extra));
+ std::make_unique<NotificationExtra>(extra));
}
suggestion.set_fetch_date(fetch_date_);
if (content_type_ == ContentType::VIDEO) {
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestion.h b/chromium/components/ntp_snippets/remote/remote_suggestion.h
index 2ae2bcf53ba..7aef0b66549 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestion.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestion.h
@@ -128,7 +128,7 @@ class RemoteSuggestion {
private:
RemoteSuggestion(const std::vector<std::string>& ids, int remote_category_id);
- // base::MakeUnique doesn't work if the ctor is private.
+ // std::make_unique doesn't work if the ctor is private.
static std::unique_ptr<RemoteSuggestion> MakeUnique(
const std::vector<std::string>& ids,
int remote_category_id);
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_database.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_database.cc
index 6cdcaa053c8..a126ee24a12 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_database.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_database.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/files/file_path.h"
-#include "base/memory/ptr_util.h"
#include "base/sys_info.h"
#include "base/task_scheduler/post_task.h"
#include "components/leveldb_proto/proto_database_impl.h"
@@ -122,7 +121,7 @@ void RemoteSuggestionsDatabase::SaveSnippets(
}
void RemoteSuggestionsDatabase::DeleteSnippet(const std::string& snippet_id) {
- DeleteSnippets(base::MakeUnique<std::vector<std::string>>(1, snippet_id));
+ DeleteSnippets(std::make_unique<std::vector<std::string>>(1, snippet_id));
}
void RemoteSuggestionsDatabase::DeleteSnippets(
@@ -158,20 +157,20 @@ void RemoteSuggestionsDatabase::SaveImage(const std::string& snippet_id,
entries_to_save->emplace_back(snippet_id, std::move(image_proto));
image_database_->UpdateEntries(
- std::move(entries_to_save), base::MakeUnique<std::vector<std::string>>(),
+ std::move(entries_to_save), std::make_unique<std::vector<std::string>>(),
base::Bind(&RemoteSuggestionsDatabase::OnImageDatabaseSaved,
weak_ptr_factory_.GetWeakPtr()));
}
void RemoteSuggestionsDatabase::DeleteImage(const std::string& snippet_id) {
- DeleteImages(base::MakeUnique<std::vector<std::string>>(1, snippet_id));
+ DeleteImages(std::make_unique<std::vector<std::string>>(1, snippet_id));
}
void RemoteSuggestionsDatabase::DeleteImages(
std::unique_ptr<std::vector<std::string>> snippet_ids) {
DCHECK(IsInitialized());
image_database_->UpdateEntries(
- base::MakeUnique<ImageKeyEntryVector>(), std::move(snippet_ids),
+ std::make_unique<ImageKeyEntryVector>(), std::move(snippet_ids),
base::Bind(&RemoteSuggestionsDatabase::OnImageDatabaseSaved,
weak_ptr_factory_.GetWeakPtr()));
}
@@ -343,7 +342,7 @@ void RemoteSuggestionsDatabase::DeleteUnreferencedImages(
OnDatabaseError();
return;
}
- auto keys_to_remove = base::MakeUnique<std::vector<std::string>>();
+ auto keys_to_remove = std::make_unique<std::vector<std::string>>();
for (const std::string& key : *image_keys) {
if (references->count(key) == 0) {
keys_to_remove->emplace_back(key);
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc
index 5817f94fd36..d33d3f03224 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.cc
@@ -4,7 +4,7 @@
#include "components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h"
-#include "base/memory/ptr_util.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
@@ -15,10 +15,10 @@
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/ntp_snippets_constants.h"
#include "components/ntp_snippets/user_classifier.h"
-#include "components/signin/core/browser/access_token_fetcher.h"
-#include "components/signin/core/browser/signin_manager_base.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_status.h"
+#include "services/identity/public/cpp/identity_manager.h"
+#include "services/identity/public/cpp/primary_account_access_token_fetcher.h"
using language::UrlLanguageHistogram;
using net::HttpRequestHeaders;
@@ -124,8 +124,7 @@ void FilterCategories(FetchedCategoriesVector* categories,
} // namespace
RemoteSuggestionsFetcherImpl::RemoteSuggestionsFetcherImpl(
- SigninManagerBase* signin_manager,
- OAuth2TokenService* token_service,
+ identity::IdentityManager* identity_manager,
scoped_refptr<URLRequestContextGetter> url_request_context_getter,
PrefService* pref_service,
UrlLanguageHistogram* language_histogram,
@@ -133,14 +132,13 @@ RemoteSuggestionsFetcherImpl::RemoteSuggestionsFetcherImpl(
const GURL& api_endpoint,
const std::string& api_key,
const UserClassifier* user_classifier)
- : signin_manager_(signin_manager),
- token_service_(token_service),
+ : identity_manager_(identity_manager),
url_request_context_getter_(std::move(url_request_context_getter)),
language_histogram_(language_histogram),
parse_json_callback_(parse_json_callback),
fetch_url_(api_endpoint),
api_key_(api_key),
- clock_(new base::DefaultClock()),
+ clock_(base::DefaultClock::GetInstance()),
user_classifier_(user_classifier) {}
RemoteSuggestionsFetcherImpl::~RemoteSuggestionsFetcherImpl() = default;
@@ -161,25 +159,25 @@ void RemoteSuggestionsFetcherImpl::FetchSnippets(
const RequestParams& params,
SnippetsAvailableCallback callback) {
if (!params.interactive_request) {
- UMA_HISTOGRAM_SPARSE_SLOWLY(
+ base::UmaHistogramSparse(
"NewTabPage.Snippets.FetchTimeLocal",
GetMinuteOfTheDay(/*local_time=*/true,
- /*reduced_resolution=*/true, clock_.get()));
- UMA_HISTOGRAM_SPARSE_SLOWLY(
+ /*reduced_resolution=*/true, clock_));
+ base::UmaHistogramSparse(
"NewTabPage.Snippets.FetchTimeUTC",
GetMinuteOfTheDay(/*local_time=*/false,
- /*reduced_resolution=*/true, clock_.get()));
+ /*reduced_resolution=*/true, clock_));
}
JsonRequest::Builder builder;
builder.SetLanguageHistogram(language_histogram_)
.SetParams(params)
.SetParseJsonCallback(parse_json_callback_)
- .SetClock(clock_.get())
+ .SetClock(clock_)
.SetUrlRequestContextGetter(url_request_context_getter_)
.SetUserClassifier(*user_classifier_);
- if (signin_manager_->IsAuthenticated() || signin_manager_->AuthInProgress()) {
+ if (identity_manager_->HasPrimaryAccount()) {
// Signed-in: get OAuth token --> fetch suggestions.
pending_requests_.emplace(std::move(builder), std::move(callback));
StartTokenRequest();
@@ -211,7 +209,7 @@ void RemoteSuggestionsFetcherImpl::FetchSnippetsAuthenticated(
const std::string& oauth_access_token) {
// TODO(jkrcal, treib): Add unit-tests for authenticated fetches.
builder.SetUrl(fetch_url_)
- .SetAuthentication(signin_manager_->GetAuthenticatedAccountId(),
+ .SetAuthentication(identity_manager_->GetPrimaryAccountInfo().account_id,
base::StringPrintf(kAuthorizationRequestHeaderFormat,
oauth_access_token.c_str()));
StartRequest(std::move(builder), std::move(callback));
@@ -234,10 +232,11 @@ void RemoteSuggestionsFetcherImpl::StartTokenRequest() {
}
OAuth2TokenService::ScopeSet scopes{kContentSuggestionsApiScope};
- token_fetcher_ = base::MakeUnique<AccessTokenFetcher>(
- "ntp_snippets", signin_manager_, token_service_, scopes,
+ token_fetcher_ = identity_manager_->CreateAccessTokenFetcherForPrimaryAccount(
+ "ntp_snippets", scopes,
base::BindOnce(&RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished,
- base::Unretained(this)));
+ base::Unretained(this)),
+ identity::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable);
}
void RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished(
@@ -246,8 +245,8 @@ void RemoteSuggestionsFetcherImpl::AccessTokenFetchFinished(
// Delete the fetcher only after we leave this method (which is called from
// the fetcher itself).
DCHECK(token_fetcher_);
- std::unique_ptr<AccessTokenFetcher> token_fetcher_deleter(
- std::move(token_fetcher_));
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher>
+ token_fetcher_deleter(std::move(token_fetcher_));
if (error.state() != GoogleServiceAuthError::NONE) {
AccessTokenError(error);
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h
index 068e01b8bf3..f5a33841bb3 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl.h
@@ -20,15 +20,17 @@
#include "components/ntp_snippets/remote/request_params.h"
#include "net/url_request/url_request_context_getter.h"
-class AccessTokenFetcher;
-class OAuth2TokenService;
class PrefService;
-class SigninManagerBase;
namespace base {
class Value;
} // namespace base
+namespace identity {
+class IdentityManager;
+class PrimaryAccountAccessTokenFetcher;
+}
+
namespace language {
class UrlLanguageHistogram;
} // namespace language
@@ -40,8 +42,7 @@ class UserClassifier;
class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher {
public:
RemoteSuggestionsFetcherImpl(
- SigninManagerBase* signin_manager,
- OAuth2TokenService* token_service,
+ identity::IdentityManager* identity_manager,
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
PrefService* pref_service,
language::UrlLanguageHistogram* language_histogram,
@@ -59,9 +60,7 @@ class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher {
const GURL& GetFetchUrlForDebugging() const override;
// Overrides internal clock for testing purposes.
- void SetClockForTesting(std::unique_ptr<base::Clock> clock) {
- clock_ = std::move(clock);
- }
+ void SetClockForTesting(base::Clock* clock) { clock_ = clock; }
private:
void FetchSnippetsNonAuthenticated(internal::JsonRequest::Builder builder,
@@ -89,10 +88,9 @@ class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher {
const std::string& error_details);
// Authentication for signed-in users.
- SigninManagerBase* signin_manager_;
- OAuth2TokenService* token_service_;
+ identity::IdentityManager* identity_manager_;
- std::unique_ptr<AccessTokenFetcher> token_fetcher_;
+ std::unique_ptr<identity::PrimaryAccountAccessTokenFetcher> token_fetcher_;
// Holds the URL request context.
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
@@ -114,7 +112,7 @@ class RemoteSuggestionsFetcherImpl : public RemoteSuggestionsFetcher {
const std::string api_key_;
// Allow for an injectable clock for testing.
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
// Classifier that tells us how active the user is. Not owned.
const UserClassifier* user_classifier_;
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc
index da04ecefcc7..3df8a732140 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_fetcher_impl_unittest.cc
@@ -10,7 +10,7 @@
#include "base/containers/circular_deque.h"
#include "base/json/json_reader.h"
-#include "base/memory/ptr_util.h"
+#include "base/message_loop/message_loop.h"
#include "base/optional.h"
#include "base/test/histogram_tester.h"
#include "base/test/test_mock_time_task_runner.h"
@@ -35,6 +35,7 @@
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "net/url_request/test_url_fetcher_factory.h"
#include "net/url_request/url_request_test_util.h"
+#include "services/identity/public/cpp/identity_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
@@ -60,7 +61,7 @@ const char kTestChromeContentSuggestionsSignedOutUrl[] =
const char kTestChromeContentSuggestionsSignedInUrl[] =
"https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/fetch";
-const char kTestEmail[] = "foo@bar.com";
+const char kTestAccount[] = "foo@bar.com";
// Artificial time delay for JSON parsing.
const int64_t kTestJsonParsingLatencyMs = 20;
@@ -230,7 +231,7 @@ class FailingFakeURLFetcherFactory : public net::URLFetcherFactory {
net::URLFetcher::RequestType request_type,
net::URLFetcherDelegate* delegate,
net::NetworkTrafficAnnotationTag traffic_annotation) override {
- return base::MakeUnique<net::FakeURLFetcher>(
+ return std::make_unique<net::FakeURLFetcher>(
url, delegate, /*response_data=*/std::string(), net::HTTP_NOT_FOUND,
net::URLRequestStatus::FAILED);
}
@@ -260,7 +261,9 @@ void ParseJsonDelayed(const std::string& json,
} // namespace
-class RemoteSuggestionsFetcherImplTestBase : public testing::Test {
+class RemoteSuggestionsFetcherImplTestBase
+ : public testing::Test,
+ public OAuth2TokenService::DiagnosticsObserver {
public:
explicit RemoteSuggestionsFetcherImplTestBase(const GURL& gurl)
: default_variation_params_(
@@ -268,58 +271,73 @@ class RemoteSuggestionsFetcherImplTestBase : public testing::Test {
params_manager_(ntp_snippets::kArticleSuggestionsFeature.name,
default_variation_params_,
{ntp_snippets::kArticleSuggestionsFeature.name}),
- mock_task_runner_(new base::TestMockTimeTaskRunner()),
- mock_task_runner_handle_(mock_task_runner_),
+ mock_task_runner_(new base::TestMockTimeTaskRunner(
+ base::TestMockTimeTaskRunner::Type::kBoundToThread)),
test_url_(gurl) {
UserClassifier::RegisterProfilePrefs(utils_.pref_service()->registry());
- user_classifier_ = base::MakeUnique<UserClassifier>(
- utils_.pref_service(), base::MakeUnique<base::DefaultClock>());
+ user_classifier_ = std::make_unique<UserClassifier>(
+ utils_.pref_service(), base::DefaultClock::GetInstance());
// Increase initial time such that ticks are non-zero.
mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234));
ResetFetcher();
}
+ ~RemoteSuggestionsFetcherImplTestBase() override {
+ if (fake_token_service_)
+ fake_token_service_->RemoveDiagnosticsObserver(this);
+ }
+
void ResetFetcher() { ResetFetcherWithAPIKey(kAPIKey); }
void ResetFetcherWithAPIKey(const std::string& api_key) {
scoped_refptr<net::TestURLRequestContextGetter> request_context_getter =
new net::TestURLRequestContextGetter(mock_task_runner_.get());
- fake_token_service_ = base::MakeUnique<FakeProfileOAuth2TokenService>(
- base::MakeUnique<FakeOAuth2TokenServiceDelegate>(
+ if (fake_token_service_) {
+ fake_token_service_->RemoveDiagnosticsObserver(this);
+ identity_manager_.reset();
+ }
+
+ fake_token_service_ = std::make_unique<FakeProfileOAuth2TokenService>(
+ std::make_unique<FakeOAuth2TokenServiceDelegate>(
request_context_getter.get()));
- fetcher_ = base::MakeUnique<RemoteSuggestionsFetcherImpl>(
- utils_.fake_signin_manager(), fake_token_service_.get(),
- std::move(request_context_getter), utils_.pref_service(), nullptr,
- base::Bind(&ParseJsonDelayed),
+ fake_token_service_->AddDiagnosticsObserver(this);
+
+ // TODO(blundell): Convert this test to use IdentityTestEnvironment once
+ // that infrastructure lands in the codebase.
+ identity_manager_ = std::make_unique<identity::IdentityManager>(
+ utils_.fake_signin_manager(), fake_token_service_.get());
+
+ fetcher_ = std::make_unique<RemoteSuggestionsFetcherImpl>(
+ identity_manager_.get(), std::move(request_context_getter),
+ utils_.pref_service(), nullptr, base::BindRepeating(&ParseJsonDelayed),
GetFetchEndpoint(version_info::Channel::STABLE), api_key,
user_classifier_.get());
- fetcher_->SetClockForTesting(mock_task_runner_->GetMockClock());
+ clock_ = mock_task_runner_->GetMockClock();
+ fetcher_->SetClockForTesting(clock_.get());
}
void SignIn() {
-#if defined(OS_CHROMEOS)
- utils_.fake_signin_manager()->SignIn(kTestEmail);
-#else
- utils_.fake_signin_manager()->SignIn(kTestEmail, "user", "password");
-#endif
+ identity_manager_->SetPrimaryAccountSynchronouslyForTests(kTestAccount,
+ kTestAccount, "");
}
void IssueRefreshToken() {
- fake_token_service_->GetDelegate()->UpdateCredentials(kTestEmail, "token");
+ fake_token_service_->GetDelegate()->UpdateCredentials(kTestAccount,
+ "token");
}
void IssueOAuth2Token() {
- fake_token_service_->IssueAllTokensForAccount(kTestEmail, "access_token",
+ fake_token_service_->IssueAllTokensForAccount(kTestAccount, "access_token",
base::Time::Max());
}
void CancelOAuth2TokenRequests() {
fake_token_service_->IssueErrorForAllPendingRequestsForAccount(
- kTestEmail, GoogleServiceAuthError(
- GoogleServiceAuthError::State::REQUEST_CANCELED));
+ kTestAccount, GoogleServiceAuthError(
+ GoogleServiceAuthError::State::REQUEST_CANCELED));
}
RemoteSuggestionsFetcher::SnippetsAvailableCallback
@@ -369,24 +387,41 @@ class RemoteSuggestionsFetcherImplTestBase : public testing::Test {
fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data,
response_code, status);
}
+ void set_on_access_token_request_callback(base::OnceClosure callback) {
+ on_access_token_request_callback_ = std::move(callback);
+ }
protected:
std::map<std::string, std::string> default_variation_params_;
private:
+ // OAuth2TokenService::DiagnosticsObserver:
+ void OnAccessTokenRequested(
+ const std::string& account_id,
+ const std::string& consumer_id,
+ const OAuth2TokenService::ScopeSet& scopes) override {
+ if (on_access_token_request_callback_)
+ std::move(on_access_token_request_callback_).Run();
+ }
+
+ // TODO(tzik): Remove |clock_| after updating GetMockTickClock to own the
+ // instance. http://crbug.com/789079
+ std::unique_ptr<base::Clock> clock_;
+
test::RemoteSuggestionsTestUtils utils_;
variations::testing::VariationParamsManager params_manager_;
scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_;
- base::ThreadTaskRunnerHandle mock_task_runner_handle_;
FailingFakeURLFetcherFactory failing_url_fetcher_factory_;
// Initialized lazily in SetFakeResponse().
std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_;
std::unique_ptr<FakeProfileOAuth2TokenService> fake_token_service_;
+ std::unique_ptr<identity::IdentityManager> identity_manager_;
std::unique_ptr<RemoteSuggestionsFetcherImpl> fetcher_;
std::unique_ptr<UserClassifier> user_classifier_;
MockSnippetsAvailableCallback mock_callback_;
const GURL test_url_;
base::HistogramTester histogram_tester_;
+ base::OnceClosure on_access_token_request_callback_;
DISALLOW_COPY_AND_ASSIGN(RemoteSuggestionsFetcherImplTestBase);
};
@@ -462,6 +497,9 @@ TEST_F(RemoteSuggestionsSignedOutFetcherTest, ShouldFetchSuccessfully) {
}
TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldFetchSuccessfully) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
SignIn();
IssueRefreshToken();
@@ -493,6 +531,8 @@ TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldFetchSuccessfully) {
fetcher().FetchSnippets(test_params(),
ToSnippetsAvailableCallback(&mock_callback()));
+ run_loop.Run();
+
IssueOAuth2Token();
// Wait for the fake response.
FastForwardUntilNoTasksRemain();
@@ -508,6 +548,9 @@ TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldFetchSuccessfully) {
}
TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldRetryWhenOAuthCancelled) {
+ base::RunLoop run_loop;
+ set_on_access_token_request_callback(run_loop.QuitClosure());
+
SignIn();
IssueRefreshToken();
@@ -539,7 +582,19 @@ TEST_F(RemoteSuggestionsSignedInFetcherTest, ShouldRetryWhenOAuthCancelled) {
fetcher().FetchSnippets(test_params(),
ToSnippetsAvailableCallback(&mock_callback()));
+ // Wait for the first access token request to be made.
+ run_loop.Run();
+
+ // Before cancelling the outstanding access token request, prepare to wait for
+ // the second access token request to be made in response to the cancellation.
+ base::RunLoop run_loop2;
+ set_on_access_token_request_callback(run_loop2.QuitClosure());
+
CancelOAuth2TokenRequests();
+
+ // Wait for the second access token request to be made.
+ run_loop2.Run();
+
IssueOAuth2Token();
// Wait for the fake response.
FastForwardUntilNoTasksRemain();
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
index 2c9246b1899..4b922596626 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.cc
@@ -11,10 +11,9 @@
#include "base/bind.h"
#include "base/command_line.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial_params.h"
+#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
-#include "base/metrics/sparse_histogram.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
@@ -236,7 +235,7 @@ base::TimeDelta GetTimeoutForLoadingIndicator() {
template <typename SuggestionPtrContainer>
std::unique_ptr<std::vector<std::string>> GetSuggestionIDVector(
const SuggestionPtrContainer& suggestions) {
- auto result = base::MakeUnique<std::vector<std::string>>();
+ auto result = std::make_unique<std::vector<std::string>>();
for (const auto& suggestion : suggestions) {
result->push_back(suggestion->id());
}
@@ -301,8 +300,8 @@ void RemoveIncompleteSuggestions(RemoteSuggestion::PtrVector* suggestions) {
UMA_HISTOGRAM_BOOLEAN("NewTabPage.Snippets.IncompleteSnippetsAfterFetch",
num_suggestions_removed > 0);
if (num_suggestions_removed > 0) {
- UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumIncompleteSnippets",
- num_suggestions_removed);
+ base::UmaHistogramSparse("NewTabPage.Snippets.NumIncompleteSnippets",
+ num_suggestions_removed);
}
}
@@ -386,7 +385,7 @@ RemoteSuggestionsProviderImpl::RemoteSuggestionsProviderImpl(
status_service_(std::move(status_service)),
clear_history_dependent_state_when_initialized_(false),
clear_cached_suggestions_when_initialized_(false),
- clock_(base::MakeUnique<base::DefaultClock>()),
+ clock_(base::DefaultClock::GetInstance()),
prefetched_pages_tracker_(std::move(prefetched_pages_tracker)),
breaking_news_raw_data_provider_(
std::move(breaking_news_raw_data_provider)),
@@ -727,14 +726,14 @@ void RemoteSuggestionsProviderImpl::ClearHistory(
ClearHistoryDependentState();
}
-void RemoteSuggestionsProviderImpl::OnSignInStateChanged() {
+void RemoteSuggestionsProviderImpl::OnSignInStateChanged(bool has_signed_in) {
// Make sure the status service is registered and we already initialised its
// start state.
if (!initialized()) {
return;
}
- status_service_->OnSignInStateChanged();
+ status_service_->OnSignInStateChanged(has_signed_in);
}
void RemoteSuggestionsProviderImpl::GetDismissedSuggestionsForDebugging(
@@ -971,7 +970,7 @@ void RemoteSuggestionsProviderImpl::OnFetchFinished(
bool response_includes_article_category = false;
for (FetchedCategory& fetched_category : *fetched_categories) {
if (fetched_category.category == articles_category_) {
- UMA_HISTOGRAM_SPARSE_SLOWLY(
+ base::UmaHistogramSparse(
"NewTabPage.Snippets.NumArticlesFetched",
std::min(fetched_category.suggestions.size(),
static_cast<size_t>(kMaxNormalFetchSuggestionCount)));
@@ -1041,8 +1040,8 @@ void RemoteSuggestionsProviderImpl::OnFetchFinished(
auto content_it = category_contents_.find(articles_category_);
DCHECK(content_it != category_contents_.end());
const CategoryContent& content = content_it->second;
- UMA_HISTOGRAM_SPARSE_SLOWLY("NewTabPage.Snippets.NumArticles",
- content.suggestions.size());
+ base::UmaHistogramSparse("NewTabPage.Snippets.NumArticles",
+ content.suggestions.size());
if (content.suggestions.empty() && !content.dismissed.empty()) {
UMA_HISTOGRAM_COUNTS("NewTabPage.Snippets.NumArticlesZeroDueToDiscarded",
content.dismissed.size());
@@ -1315,7 +1314,7 @@ void RemoteSuggestionsProviderImpl::ClearExpiredDismissedSuggestions() {
}
void RemoteSuggestionsProviderImpl::ClearOrphanedImages() {
- auto alive_suggestions = base::MakeUnique<std::set<std::string>>();
+ auto alive_suggestions = std::make_unique<std::set<std::string>>();
for (const auto& entry : category_contents_) {
const CategoryContent& content = entry.second;
for (const auto& suggestion_ptr : content.suggestions) {
@@ -1749,7 +1748,7 @@ void RemoteSuggestionsProviderImpl::StoreCategoriesToPrefs() {
for (const auto& entry : to_store) {
const Category& category = entry.first;
const CategoryContent& content = *entry.second;
- auto dict = base::MakeUnique<base::DictionaryValue>();
+ auto dict = std::make_unique<base::DictionaryValue>();
dict->SetInteger(kCategoryContentId, category.id());
// TODO(tschumann): Persist other properties of the CategoryInfo.
dict->SetString(kCategoryContentTitle, content.info.title());
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.h b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.h
index c8292e0aa36..a8e67b8aa31 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl.h
@@ -111,7 +111,7 @@ class RemoteSuggestionsProviderImpl final : public RemoteSuggestionsProvider {
base::Time end,
const base::Callback<bool(const GURL& url)>& filter) override;
void ClearCachedSuggestions() override;
- void OnSignInStateChanged() override;
+ void OnSignInStateChanged(bool has_signed_in) override;
void GetDismissedSuggestionsForDebugging(
Category category,
DismissedSuggestionsCallback callback) override;
@@ -135,9 +135,7 @@ class RemoteSuggestionsProviderImpl final : public RemoteSuggestionsProvider {
}
// Overrides internal clock for testing purposes.
- void SetClockForTesting(std::unique_ptr<base::Clock> clock) {
- clock_ = std::move(clock);
- }
+ void SetClockForTesting(base::Clock* clock) { clock_ = clock; }
// TODO(tschumann): remove this method as soon as we inject the fetcher into
// the constructor.
@@ -434,7 +432,7 @@ class RemoteSuggestionsProviderImpl final : public RemoteSuggestionsProvider {
bool clear_cached_suggestions_when_initialized_;
// A clock for getting the time. This allows to inject a clock in tests.
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
// Prefetched pages tracker to query which urls have been prefetched.
// |nullptr| is handled gracefully and just disables the functionality.
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
index 2c8651ff0f9..78fccc3d984 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_provider_impl_unittest.cc
@@ -16,7 +16,6 @@
#include "base/files/scoped_temp_dir.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -317,7 +316,7 @@ class MockRemoteSuggestionsStatusService
~MockRemoteSuggestionsStatusService() override = default;
MOCK_METHOD1(Init, void(const StatusChangeCallback& callback));
- MOCK_METHOD0(OnSignInStateChanged, void());
+ MOCK_METHOD1(OnSignInStateChanged, void(bool));
};
std::string BoolToString(bool value) {
@@ -335,12 +334,12 @@ base::Time GetDummyNow() {
class RemoteSuggestionsProviderImplTest : public ::testing::Test {
public:
RemoteSuggestionsProviderImplTest()
- : category_ranker_(base::MakeUnique<ConstantCategoryRanker>()),
+ : category_ranker_(std::make_unique<ConstantCategoryRanker>()),
user_classifier_(/*pref_service=*/nullptr,
- base::MakeUnique<base::DefaultClock>()),
+ base::DefaultClock::GetInstance()),
mock_suggestions_fetcher_(nullptr),
image_fetcher_(nullptr),
- scheduler_(base::MakeUnique<NiceMock<MockScheduler>>()),
+ scheduler_(std::make_unique<NiceMock<MockScheduler>>()),
database_(nullptr),
timer_mock_task_runner_(
(new TestMockTimeTaskRunner(GetDummyNow(),
@@ -380,21 +379,21 @@ class RemoteSuggestionsProviderImplTest : public ::testing::Test {
bool use_mock_remote_suggestions_status_service) {
utils_.ResetSigninManager();
auto mock_suggestions_fetcher =
- base::MakeUnique<StrictMock<MockRemoteSuggestionsFetcher>>();
+ std::make_unique<StrictMock<MockRemoteSuggestionsFetcher>>();
mock_suggestions_fetcher_ = mock_suggestions_fetcher.get();
std::unique_ptr<StrictMock<MockPrefetchedPagesTracker>>
mock_prefetched_pages_tracker;
if (use_mock_prefetched_pages_tracker) {
mock_prefetched_pages_tracker =
- base::MakeUnique<StrictMock<MockPrefetchedPagesTracker>>();
+ std::make_unique<StrictMock<MockPrefetchedPagesTracker>>();
}
mock_prefetched_pages_tracker_ = mock_prefetched_pages_tracker.get();
std::unique_ptr<FakeBreakingNewsListener> fake_breaking_news_listener;
if (use_fake_breaking_news_listener) {
fake_breaking_news_listener =
- base::MakeUnique<FakeBreakingNewsListener>();
+ std::make_unique<FakeBreakingNewsListener>();
}
fake_breaking_news_listener_ = fake_breaking_news_listener.get();
@@ -402,37 +401,36 @@ class RemoteSuggestionsProviderImplTest : public ::testing::Test {
remote_suggestions_status_service;
if (use_mock_remote_suggestions_status_service) {
auto mock_remote_suggestions_status_service =
- base::MakeUnique<StrictMock<MockRemoteSuggestionsStatusService>>();
+ std::make_unique<StrictMock<MockRemoteSuggestionsStatusService>>();
EXPECT_CALL(*mock_remote_suggestions_status_service, Init(_))
.WillOnce(SaveArg<0>(&status_change_callback_));
remote_suggestions_status_service =
std::move(mock_remote_suggestions_status_service);
} else {
remote_suggestions_status_service =
- base::MakeUnique<RemoteSuggestionsStatusServiceImpl>(
- utils_.fake_signin_manager(), utils_.pref_service(),
- std::string());
+ std::make_unique<RemoteSuggestionsStatusServiceImpl>(
+ /*has_signed_in=*/false, utils_.pref_service(), std::string());
}
remote_suggestions_status_service_ =
remote_suggestions_status_service.get();
- auto image_fetcher = base::MakeUnique<NiceMock<MockImageFetcher>>();
+ auto image_fetcher = std::make_unique<NiceMock<MockImageFetcher>>();
image_fetcher_ = image_fetcher.get();
EXPECT_CALL(*image_fetcher, SetImageFetcherDelegate(_));
ON_CALL(*image_fetcher, GetImageDecoder())
.WillByDefault(Return(&image_decoder_));
EXPECT_FALSE(observer_);
- observer_ = base::MakeUnique<FakeContentSuggestionsProviderObserver>();
+ observer_ = std::make_unique<FakeContentSuggestionsProviderObserver>();
auto database =
- base::MakeUnique<RemoteSuggestionsDatabase>(database_dir_.GetPath());
+ std::make_unique<RemoteSuggestionsDatabase>(database_dir_.GetPath());
database_ = database.get();
auto fetch_timeout_timer =
- base::MakeUnique<base::OneShotTimer>(tick_clock_.get());
+ std::make_unique<base::OneShotTimer>(tick_clock_.get());
fetch_timeout_timer->SetTaskRunner(timer_mock_task_runner_);
- return base::MakeUnique<RemoteSuggestionsProviderImpl>(
+ return std::make_unique<RemoteSuggestionsProviderImpl>(
observer_.get(), utils_.pref_service(), "fr", category_ranker_.get(),
scheduler_.get(), std::move(mock_suggestions_fetcher),
std::move(image_fetcher), std::move(database),
@@ -444,7 +442,7 @@ class RemoteSuggestionsProviderImplTest : public ::testing::Test {
std::unique_ptr<RemoteSuggestionsProviderImpl>
MakeSuggestionsProviderWithoutInitializationWithStrictScheduler() {
- scheduler_ = base::MakeUnique<StrictMock<MockScheduler>>();
+ scheduler_ = std::make_unique<StrictMock<MockScheduler>>();
return MakeSuggestionsProviderWithoutInitialization(
/*use_mock_prefetched_pages_tracker=*/false,
/*use_fake_breaking_news_listener=*/false,
@@ -712,6 +710,9 @@ class RemoteSuggestionsProviderImplTest : public ::testing::Test {
RemoteSuggestionsDatabase* database_;
Logger debug_logger_;
+
+ // TODO(tzik): Remove |mock_tick_clock_| after updating GetMockTickClock to
+ // own the instance. http://crbug.com/789079
std::unique_ptr<base::TickClock> tick_clock_;
scoped_refptr<TestMockTimeTaskRunner> timer_mock_task_runner_;
@@ -909,7 +910,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, ExperimentalCategoryInfo) {
}
TEST_F(RemoteSuggestionsProviderImplTest, AddRemoteCategoriesToCategoryRanker) {
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
std::vector<FetchedCategory> fetched_categories;
@@ -950,7 +951,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, AddRemoteCategoriesToCategoryRanker) {
TEST_F(RemoteSuggestionsProviderImplTest,
AddRemoteCategoriesToCategoryRankerRelativeToArticles) {
SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(true);
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
std::vector<FetchedCategory> fetched_categories;
@@ -1006,7 +1007,7 @@ TEST_F(
RemoteSuggestionsProviderImplTest,
AddRemoteCategoriesToCategoryRankerRelativeToArticlesWithArticlesAbsent) {
SetOrderNewRemoteCategoriesBasedOnArticlesCategoryParam(true);
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
std::vector<FetchedCategory> fetched_categories;
@@ -1113,7 +1114,7 @@ TEST_F(RemoteSuggestionsProviderImplTest, PersistRemoteCategoryOrder) {
// We manually recreate the provider to simulate Chrome restart and enforce a
// mock ranker.
- auto mock_ranker = base::MakeUnique<MockCategoryRanker>();
+ auto mock_ranker = std::make_unique<MockCategoryRanker>();
MockCategoryRanker* raw_mock_ranker = mock_ranker.get();
SetCategoryRanker(std::move(mock_ranker));
// Ensure that the order is not fetched.
@@ -2346,9 +2347,8 @@ TEST_F(RemoteSuggestionsProviderImplTest,
/*use_fake_breaking_news_listener=*/false,
/*use_mock_remote_suggestions_status_service=*/false);
- auto simple_test_clock = base::MakeUnique<base::SimpleTestClock>();
- base::SimpleTestClock* simple_test_clock_ptr = simple_test_clock.get();
- provider->SetClockForTesting(std::move(simple_test_clock));
+ base::SimpleTestClock simple_test_clock;
+ provider->SetClockForTesting(&simple_test_clock);
// Test that the preference is correctly initialized with the default value 0.
EXPECT_EQ(
@@ -2356,12 +2356,12 @@ TEST_F(RemoteSuggestionsProviderImplTest,
WaitForSuggestionsProviderInitialization(provider.get());
EXPECT_EQ(
- SerializeTime(simple_test_clock_ptr->Now()),
+ SerializeTime(simple_test_clock.Now()),
pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
// Advance the time and check whether the time was updated correctly after the
// background fetch.
- simple_test_clock_ptr->Advance(base::TimeDelta::FromHours(1));
+ simple_test_clock.Advance(base::TimeDelta::FromHours(1));
RemoteSuggestionsFetcher::SnippetsAvailableCallback snippets_callback;
EXPECT_CALL(*mock_suggestions_fetcher(), FetchSnippets(_, _))
@@ -2373,7 +2373,7 @@ TEST_F(RemoteSuggestionsProviderImplTest,
std::move(snippets_callback).Run(Status::Success(), base::nullopt);
// TODO(jkrcal): Move together with the pref storage into the scheduler.
EXPECT_EQ(
- SerializeTime(simple_test_clock_ptr->Now()),
+ SerializeTime(simple_test_clock.Now()),
pref_service()->GetInt64(prefs::kLastSuccessfulBackgroundFetchTime));
// TODO(markusheintz): Add a test that simulates a browser restart once the
// scheduler refactoring is done (crbug.com/672434).
@@ -3122,12 +3122,11 @@ TEST_F(RemoteSuggestionsProviderImplTest,
StrictMock<MockPrefetchedPagesTracker>* mock_tracker =
mock_prefetched_pages_tracker();
- auto wrapped_provider_clock = base::MakeUnique<base::SimpleTestClock>();
- base::SimpleTestClock* provider_clock = wrapped_provider_clock.get();
- provider->SetClockForTesting(std::move(wrapped_provider_clock));
+ base::SimpleTestClock provider_clock;
+ provider->SetClockForTesting(&provider_clock);
- provider_clock->SetNow(GetDefaultCreationTime() +
- base::TimeDelta::FromHours(10));
+ provider_clock.SetNow(GetDefaultCreationTime() +
+ base::TimeDelta::FromHours(10));
WaitForSuggestionsProviderInitialization(provider.get());
std::vector<FetchedCategory> fetched_categories;
@@ -3139,7 +3138,7 @@ TEST_F(RemoteSuggestionsProviderImplTest,
.AddId("http://prefetched.com")
.SetUrl("http://prefetched.com")
.SetAmpUrl("http://amp.prefetched.com")
- .SetFetchDate(provider_clock->Now())
+ .SetFetchDate(provider_clock.Now())
.SetPublishDate(GetDefaultCreationTime()))
.Build());
EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true));
@@ -3148,8 +3147,8 @@ TEST_F(RemoteSuggestionsProviderImplTest,
ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
SizeIs(1));
- provider_clock->Advance(kMaxAgeForAdditionalPrefetchedSuggestion -
- base::TimeDelta::FromSeconds(1));
+ provider_clock.Advance(kMaxAgeForAdditionalPrefetchedSuggestion -
+ base::TimeDelta::FromSeconds(1));
fetched_categories.clear();
fetched_categories.push_back(
@@ -3160,7 +3159,7 @@ TEST_F(RemoteSuggestionsProviderImplTest,
.AddId("http://other.com")
.SetUrl("http://other.com")
.SetAmpUrl("http://amp.other.com")
- .SetFetchDate(provider_clock->Now())
+ .SetFetchDate(provider_clock.Now())
.SetPublishDate(GetDefaultCreationTime()))
.Build());
EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true));
@@ -3173,7 +3172,7 @@ TEST_F(RemoteSuggestionsProviderImplTest,
ASSERT_THAT(observer().SuggestionsForCategory(articles_category()),
SizeIs(2));
- provider_clock->Advance(base::TimeDelta::FromSeconds(2));
+ provider_clock.Advance(base::TimeDelta::FromSeconds(2));
fetched_categories.clear();
fetched_categories.push_back(
@@ -3184,7 +3183,7 @@ TEST_F(RemoteSuggestionsProviderImplTest,
.AddId("http://other.com")
.SetUrl("http://other.com")
.SetAmpUrl("http://amp.other.com")
- .SetFetchDate(provider_clock->Now())
+ .SetFetchDate(provider_clock.Now())
.SetPublishDate(GetDefaultCreationTime()))
.Build());
EXPECT_CALL(*mock_tracker, IsInitialized()).WillRepeatedly(Return(true));
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.cc
index c01443712f8..20310aa2400 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.cc
@@ -12,7 +12,6 @@
#include "base/bind.h"
#include "base/feature_list.h"
#include "base/location.h"
-#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_split.h"
@@ -66,12 +65,12 @@ enum class FetchingInterval {
// The values of each array specify a default time interval for the intervals
// defined by the enum FetchingInterval. The default time intervals defined in
// the arrays can be overridden using different variation parameters.
-const double kDefaultFetchingIntervalHoursRareNtpUser[] = {192.0, 96.0, 48.0,
- 48.0, 10.0, 10.0};
-const double kDefaultFetchingIntervalHoursActiveNtpUser[] = {96.0, 48.0, 24.0,
- 24.0, 10.0, 10.0};
+const double kDefaultFetchingIntervalHoursRareNtpUser[] = {96.0, 96.0, 24.0,
+ 24.0, 4.0, 4.0};
+const double kDefaultFetchingIntervalHoursActiveNtpUser[] = {48.0, 48.0, 24.0,
+ 24.0, 4.0, 4.0};
const double kDefaultFetchingIntervalHoursActiveSuggestionsConsumer[] = {
- 48.0, 24.0, 12.0, 12.0, 1.0, 1.0};
+ 24.0, 24.0, 12.0, 12.0, 1.0, 1.0};
// For a simple comparison: fetching intervals that emulate the state really
// rolled out to 100% M58 Stable. Used for evaluation of later changes. DBL_MAX
@@ -444,7 +443,7 @@ RemoteSuggestionsSchedulerImpl::RemoteSuggestionsSchedulerImpl(
const UserClassifier* user_classifier,
PrefService* profile_prefs,
PrefService* local_state_prefs,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
Logger* debug_logger)
: persistent_scheduler_(persistent_scheduler),
provider_(nullptr),
@@ -464,12 +463,12 @@ RemoteSuggestionsSchedulerImpl::RemoteSuggestionsSchedulerImpl(
CONTENT_SUGGESTION_FETCHER_ACTIVE_SUGGESTIONS_CONSUMER),
time_until_first_shown_trigger_reported_(false),
time_until_first_startup_trigger_reported_(false),
- eula_state_(base::MakeUnique<EulaState>(
+ eula_state_(std::make_unique<EulaState>(
local_state_prefs,
base::Bind(&RemoteSuggestionsSchedulerImpl::RunQueuedTriggersIfReady,
base::Unretained(this)))),
profile_prefs_(profile_prefs),
- clock_(std::move(clock)),
+ clock_(clock),
enabled_triggers_(GetEnabledTriggerTypes()),
debug_logger_(debug_logger) {
DCHECK(user_classifier);
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.h b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.h
index c82749e60cc..37741ef4f9c 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl.h
@@ -41,7 +41,7 @@ class RemoteSuggestionsSchedulerImpl : public RemoteSuggestionsScheduler {
const UserClassifier* user_classifier,
PrefService* profile_prefs,
PrefService* local_state_prefs,
- std::unique_ptr<base::Clock> clock,
+ base::Clock* clock,
Logger* debug_logger);
~RemoteSuggestionsSchedulerImpl() override;
@@ -169,7 +169,7 @@ class RemoteSuggestionsSchedulerImpl : public RemoteSuggestionsScheduler {
std::unique_ptr<EulaState> eula_state_;
PrefService* profile_prefs_;
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
std::set<TriggerType> enabled_triggers_;
std::set<TriggerType> queued_triggers_;
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc
index 92891d5deaa..0dd76c852bb 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_scheduler_impl_unittest.cc
@@ -12,7 +12,6 @@
#include "base/command_line.h"
#include "base/macros.h"
-#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
@@ -153,7 +152,7 @@ class MockRemoteSuggestionsProvider : public RemoteSuggestionsProvider {
}
MOCK_METHOD2(GetDismissedSuggestionsForDebugging,
void(Category category, DismissedSuggestionsCallback* callback));
- MOCK_METHOD0(OnSignInStateChanged, void());
+ MOCK_METHOD1(OnSignInStateChanged, void(bool));
};
class FakeOfflineNetworkChangeNotifier : public net::NetworkChangeNotifier {
@@ -176,7 +175,7 @@ class RemoteSuggestionsSchedulerImplTest : public ::testing::Test {
default_variation_params_,
{kArticleSuggestionsFeature.name}),
user_classifier_(/*pref_service=*/nullptr,
- base::MakeUnique<base::DefaultClock>()) {
+ base::DefaultClock::GetInstance()) {
RemoteSuggestionsSchedulerImpl::RegisterProfilePrefs(
utils_.pref_service()->registry());
RequestThrottler::RegisterProfilePrefs(utils_.pref_service()->registry());
@@ -191,16 +190,14 @@ class RemoteSuggestionsSchedulerImplTest : public ::testing::Test {
}
void ResetProvider() {
- provider_ = base::MakeUnique<StrictMock<MockRemoteSuggestionsProvider>>(
+ provider_ = std::make_unique<StrictMock<MockRemoteSuggestionsProvider>>(
/*observer=*/nullptr);
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- test_clock_ = test_clock.get();
- test_clock_->SetNow(base::Time::Now());
+ test_clock_.SetNow(base::Time::Now());
- scheduler_ = base::MakeUnique<RemoteSuggestionsSchedulerImpl>(
+ scheduler_ = std::make_unique<RemoteSuggestionsSchedulerImpl>(
&persistent_scheduler_, &user_classifier_, utils_.pref_service(),
- &local_state_, std::move(test_clock), &debug_logger_);
+ &local_state_, &test_clock_, &debug_logger_);
scheduler_->SetProvider(provider_.get());
}
@@ -271,7 +268,7 @@ class RemoteSuggestionsSchedulerImplTest : public ::testing::Test {
return &persistent_scheduler_;
}
- base::SimpleTestClock* test_clock() { return test_clock_; }
+ base::SimpleTestClock* test_clock() { return &test_clock_; }
MockRemoteSuggestionsProvider* provider() { return provider_.get(); }
RemoteSuggestionsSchedulerImpl* scheduler() { return scheduler_.get(); }
@@ -280,7 +277,7 @@ class RemoteSuggestionsSchedulerImplTest : public ::testing::Test {
UserClassifier user_classifier_;
TestingPrefServiceSimple local_state_;
StrictMock<MockPersistentScheduler> persistent_scheduler_;
- base::SimpleTestClock* test_clock_;
+ base::SimpleTestClock test_clock_;
std::unique_ptr<MockRemoteSuggestionsProvider> provider_;
std::unique_ptr<RemoteSuggestionsSchedulerImpl> scheduler_;
Logger debug_logger_;
@@ -908,7 +905,7 @@ TEST_F(RemoteSuggestionsSchedulerImplTest, FetchIntervalForShownTriggerOnWifi) {
// Open NTP again after too short delay (one minute missing). UserClassifier
// defaults to UserClass::ACTIVE_NTP_USER - we work with the default interval
// for this class here. This time no fetch is executed.
- test_clock()->Advance(base::TimeDelta::FromHours(10) -
+ test_clock()->Advance(base::TimeDelta::FromHours(4) -
base::TimeDelta::FromMinutes(1));
scheduler()->OnSuggestionsSurfaceOpened();
@@ -973,11 +970,12 @@ TEST_F(RemoteSuggestionsSchedulerImplTest,
std::move(signal_fetch_done).Run(Status::Success());
// Open NTP again after too short delay. This time no fetch is executed.
- test_clock()->Advance(base::TimeDelta::FromHours(5));
+ test_clock()->Advance(base::TimeDelta::FromHours(4) -
+ base::TimeDelta::FromMinutes(1));
scheduler()->OnSuggestionsSurfaceOpened();
// Open NTP after another delay, now together long enough to issue a fetch.
- test_clock()->Advance(base::TimeDelta::FromHours(7));
+ test_clock()->Advance(base::TimeDelta::FromMinutes(2));
EXPECT_CALL(*provider(), RefetchInTheBackground(_));
scheduler()->OnSuggestionsSurfaceOpened();
}
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service.h b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service.h
index a3b6e8eb0ab..665695bf655 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service.h
@@ -36,7 +36,7 @@ class RemoteSuggestionsStatusService {
// To be called when the signin state changed. Will compute the new
// state considering the initialisation configuration and the preferences,
// and notify via the registered callback if appropriate.
- virtual void OnSignInStateChanged() = 0;
+ virtual void OnSignInStateChanged(bool has_signed_in) = 0;
};
} // namespace ntp_snippets
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.cc
index e4d6576d761..ea8bf5bf208 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.cc
@@ -11,18 +11,17 @@
#include "components/ntp_snippets/pref_names.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
-#include "components/signin/core/browser/signin_manager.h"
#include "components/variations/variations_associated_data.h"
namespace ntp_snippets {
RemoteSuggestionsStatusServiceImpl::RemoteSuggestionsStatusServiceImpl(
- SigninManagerBase* signin_manager,
+ bool is_signed_in,
PrefService* pref_service,
const std::string& additional_toggle_pref)
: status_(RemoteSuggestionsStatus::EXPLICITLY_DISABLED),
additional_toggle_pref_(additional_toggle_pref),
- signin_manager_(signin_manager),
+ is_signed_in_(is_signed_in),
pref_service_(pref_service) {
ntp_snippets::metrics::RecordRemoteSuggestionsProviderState(
!IsExplicitlyDisabled());
@@ -79,12 +78,12 @@ void RemoteSuggestionsStatusServiceImpl::OnStateChanged(
}
bool RemoteSuggestionsStatusServiceImpl::IsSignedIn() const {
- // TODO(dgn): remove the SigninManager dependency. It should be possible to
- // replace it by passing the new state via OnSignInStateChanged().
- return signin_manager_ && signin_manager_->IsAuthenticated();
+ return is_signed_in_;
}
-void RemoteSuggestionsStatusServiceImpl::OnSignInStateChanged() {
+void RemoteSuggestionsStatusServiceImpl::OnSignInStateChanged(
+ bool has_signed_in) {
+ is_signed_in_ = has_signed_in;
OnStateChanged(GetStatusFromDeps());
}
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.h b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.h
index dd74af7bffa..fcf2a9a1cee 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.h
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl.h
@@ -13,14 +13,13 @@
class PrefRegistrySimple;
class PrefService;
-class SigninManagerBase;
namespace ntp_snippets {
class RemoteSuggestionsStatusServiceImpl
: public RemoteSuggestionsStatusService {
public:
- RemoteSuggestionsStatusServiceImpl(SigninManagerBase* signin_manager,
+ RemoteSuggestionsStatusServiceImpl(bool is_signed_in,
PrefService* pref_service,
const std::string& additional_toggle_pref);
@@ -30,7 +29,7 @@ class RemoteSuggestionsStatusServiceImpl
// RemoteSuggestionsStatusService implementation.
void Init(const StatusChangeCallback& callback) override;
- void OnSignInStateChanged() override;
+ void OnSignInStateChanged(bool has_signed_in) override;
private:
// TODO(jkrcal): Rewrite the tests using the public API - observing status
@@ -62,7 +61,7 @@ class RemoteSuggestionsStatusServiceImpl
// remote suggestions provider.
std::string additional_toggle_pref_;
- SigninManagerBase* signin_manager_;
+ bool is_signed_in_;
PrefService* pref_service_;
PrefChangeRegistrar pref_change_registrar_;
diff --git a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl_unittest.cc b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl_unittest.cc
index ce4f870a2e6..ab55963ca32 100644
--- a/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl_unittest.cc
+++ b/chromium/components/ntp_snippets/remote/remote_suggestions_status_service_impl_unittest.cc
@@ -6,17 +6,12 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "build/build_config.h"
#include "components/ntp_snippets/features.h"
#include "components/ntp_snippets/ntp_snippets_constants.h"
#include "components/ntp_snippets/pref_names.h"
#include "components/ntp_snippets/remote/test_utils.h"
#include "components/prefs/testing_pref_service.h"
-#include "components/signin/core/browser/account_tracker_service.h"
-#include "components/signin/core/browser/fake_signin_manager.h"
-#include "components/signin/core/browser/signin_pref_names.h"
-#include "components/signin/core/browser/test_signin_client.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "components/variations/variations_params_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
@@ -24,6 +19,13 @@
namespace ntp_snippets {
+namespace {
+
+void OnStatusChange(RemoteSuggestionsStatus old_status,
+ RemoteSuggestionsStatus new_status) {}
+
+} // namespace
+
class RemoteSuggestionsStatusServiceImplTest : public ::testing::Test {
public:
RemoteSuggestionsStatusServiceImplTest() {
@@ -32,8 +34,10 @@ class RemoteSuggestionsStatusServiceImplTest : public ::testing::Test {
}
std::unique_ptr<RemoteSuggestionsStatusServiceImpl> MakeService() {
- return base::MakeUnique<RemoteSuggestionsStatusServiceImpl>(
- utils_.fake_signin_manager(), utils_.pref_service(), std::string());
+ auto service = std::make_unique<RemoteSuggestionsStatusServiceImpl>(
+ false, utils_.pref_service(), std::string());
+ service->Init(base::BindRepeating(&OnStatusChange));
+ return service;
}
protected:
@@ -48,12 +52,8 @@ TEST_F(RemoteSuggestionsStatusServiceImplTest, NoSigninNeeded) {
EXPECT_EQ(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_OUT,
service->GetStatusFromDeps());
-// One can still sign in.
-#if defined(OS_CHROMEOS)
- utils_.fake_signin_manager()->SignIn("foo@bar.com");
-#else
- utils_.fake_signin_manager()->SignIn("foo@bar.com", "user", "pass");
-#endif
+ // Signin should cause a state change.
+ service->OnSignInStateChanged(/*has_signed_in=*/true);
EXPECT_EQ(RemoteSuggestionsStatus::ENABLED_AND_SIGNED_IN,
service->GetStatusFromDeps());
}
@@ -70,12 +70,8 @@ TEST_F(RemoteSuggestionsStatusServiceImplTest, DisabledViaPref) {
EXPECT_EQ(RemoteSuggestionsStatus::EXPLICITLY_DISABLED,
service->GetStatusFromDeps());
-// The other dependencies shouldn't matter anymore.
-#if defined(OS_CHROMEOS)
- utils_.fake_signin_manager()->SignIn("foo@bar.com");
-#else
- utils_.fake_signin_manager()->SignIn("foo@bar.com", "user", "pass");
-#endif
+ // The state should not change, even though a signin has occurred.
+ service->OnSignInStateChanged(/*has_signed_in=*/true);
EXPECT_EQ(RemoteSuggestionsStatus::EXPLICITLY_DISABLED,
service->GetStatusFromDeps());
}
diff --git a/chromium/components/ntp_snippets/remote/test_utils.cc b/chromium/components/ntp_snippets/remote/test_utils.cc
index 061005ddc0a..0048f5d5944 100644
--- a/chromium/components/ntp_snippets/remote/test_utils.cc
+++ b/chromium/components/ntp_snippets/remote/test_utils.cc
@@ -6,7 +6,6 @@
#include <memory>
-#include "base/memory/ptr_util.h"
#include "components/prefs/testing_pref_service.h"
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
@@ -48,7 +47,7 @@ syncer::ModelTypeSet FakeSyncService::GetActiveDataTypes() const {
}
RemoteSuggestionsTestUtils::RemoteSuggestionsTestUtils()
- : pref_service_(base::MakeUnique<TestingPrefServiceSyncable>()) {
+ : pref_service_(std::make_unique<TestingPrefServiceSyncable>()) {
AccountTrackerService::RegisterPrefs(pref_service_->registry());
#if defined(OS_CHROMEOS)
@@ -59,11 +58,11 @@ RemoteSuggestionsTestUtils::RemoteSuggestionsTestUtils()
SigninManager::RegisterPrefs(pref_service_->registry());
#endif // OS_CHROMEOS
- token_service_ = base::MakeUnique<FakeProfileOAuth2TokenService>();
- signin_client_ = base::MakeUnique<TestSigninClient>(pref_service_.get());
- account_tracker_ = base::MakeUnique<AccountTrackerService>();
+ token_service_ = std::make_unique<FakeProfileOAuth2TokenService>();
+ signin_client_ = std::make_unique<TestSigninClient>(pref_service_.get());
+ account_tracker_ = std::make_unique<AccountTrackerService>();
account_tracker_->Initialize(signin_client_.get());
- fake_sync_service_ = base::MakeUnique<FakeSyncService>();
+ fake_sync_service_ = std::make_unique<FakeSyncService>();
ResetSigninManager();
}
@@ -72,10 +71,10 @@ RemoteSuggestionsTestUtils::~RemoteSuggestionsTestUtils() = default;
void RemoteSuggestionsTestUtils::ResetSigninManager() {
#if defined(OS_CHROMEOS)
- fake_signin_manager_ = base::MakeUnique<FakeSigninManagerBase>(
+ fake_signin_manager_ = std::make_unique<FakeSigninManagerBase>(
signin_client_.get(), account_tracker_.get());
#else
- fake_signin_manager_ = base::MakeUnique<FakeSigninManager>(
+ fake_signin_manager_ = std::make_unique<FakeSigninManager>(
signin_client_.get(), token_service_.get(), account_tracker_.get(),
/*cookie_manager_service=*/nullptr);
#endif
diff --git a/chromium/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider_unittest.cc b/chromium/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider_unittest.cc
index 0d9071ee4e8..aad3fdb7b50 100644
--- a/chromium/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider_unittest.cc
+++ b/chromium/components/ntp_snippets/sessions/foreign_sessions_suggestions_provider_unittest.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/callback_forward.h"
-#include "base/memory/ptr_util.h"
#include "base/strings/string_number_conversions.h"
#include "components/ntp_snippets/category.h"
#include "components/ntp_snippets/content_suggestions_provider.h"
@@ -52,7 +51,7 @@ const char kTitle[] = "title is ignored";
SessionWindow* GetOrCreateWindow(SyncedSession* session, int window_id) {
if (session->windows.find(window_id) == session->windows.end()) {
- session->windows[window_id] = base::MakeUnique<SyncedSessionWindow>();
+ session->windows[window_id] = std::make_unique<SyncedSessionWindow>();
}
return &session->windows[window_id]->wrapped_window;
@@ -66,7 +65,7 @@ void AddTabToSession(SyncedSession* session,
sessions::SerializedNavigationEntryTestHelper::CreateNavigation(url,
kTitle);
- std::unique_ptr<SessionTab> tab = base::MakeUnique<SessionTab>();
+ std::unique_ptr<SessionTab> tab = std::make_unique<SessionTab>();
tab->timestamp = Time::Now() - age;
tab->navigations.push_back(navigation);
@@ -108,7 +107,7 @@ class ForeignSessionsSuggestionsProviderTest : public Test {
std::unique_ptr<FakeForeignSessionsProvider>
fake_foreign_sessions_provider =
- base::MakeUnique<FakeForeignSessionsProvider>();
+ std::make_unique<FakeForeignSessionsProvider>();
fake_foreign_sessions_provider_ = fake_foreign_sessions_provider.get();
// During the provider's construction the following mock calls occur.
@@ -116,7 +115,7 @@ class ForeignSessionsSuggestionsProviderTest : public Test {
EXPECT_CALL(*observer(), OnCategoryStatusChanged(
_, category(), CategoryStatus::AVAILABLE));
- provider_ = base::MakeUnique<ForeignSessionsSuggestionsProvider>(
+ provider_ = std::make_unique<ForeignSessionsSuggestionsProvider>(
&observer_, std::move(fake_foreign_sessions_provider), &pref_service_);
}
@@ -125,7 +124,7 @@ class ForeignSessionsSuggestionsProviderTest : public Test {
if (sessions_map_.find(session_id) == sessions_map_.end()) {
std::string id_as_string = base::IntToString(session_id);
std::unique_ptr<SyncedSession> owned_session =
- base::MakeUnique<SyncedSession>();
+ std::make_unique<SyncedSession>();
owned_session->session_tag = id_as_string;
owned_session->session_name = id_as_string;
sessions_map_[session_id] = std::move(owned_session);
diff --git a/chromium/components/ntp_snippets/user_classifier.cc b/chromium/components/ntp_snippets/user_classifier.cc
index cc5c34ffd5b..8c001243265 100644
--- a/chromium/components/ntp_snippets/user_classifier.cc
+++ b/chromium/components/ntp_snippets/user_classifier.cc
@@ -46,9 +46,9 @@ const double kActiveConsumerClicksAtLeastOncePerHours = 96;
const char kActiveConsumerClicksAtLeastOncePerHoursParam[] =
"user_classifier_active_consumer_clicks_at_least_once_per_hours";
-// The previous value in production was 72, i.e. 3 days. The new value is a
-// cautios shift in the direction we want (having slightly more rare users).
-const double kRareUserOpensNTPAtMostOncePerHours = 66;
+// The previous value in production was 66, i.e. 2.75 days. The new value is a
+// shift in the direction we want (having more active users).
+const double kRareUserOpensNTPAtMostOncePerHours = 96;
const char kRareUserOpensNTPAtMostOncePerHoursParam[] =
"user_classifier_rare_user_opens_ntp_at_most_once_per_hours";
@@ -184,10 +184,9 @@ double GetMetricValueForEstimateHoursBetweenEvents(
} // namespace
-UserClassifier::UserClassifier(PrefService* pref_service,
- std::unique_ptr<base::Clock> clock)
+UserClassifier::UserClassifier(PrefService* pref_service, base::Clock* clock)
: pref_service_(pref_service),
- clock_(std::move(clock)),
+ clock_(clock),
discount_rate_per_hour_(GetDiscountRatePerHour()),
min_hours_(GetMinHours()),
max_hours_(GetMaxHours()),
diff --git a/chromium/components/ntp_snippets/user_classifier.h b/chromium/components/ntp_snippets/user_classifier.h
index 93be8fa42e0..f5e9683cb11 100644
--- a/chromium/components/ntp_snippets/user_classifier.h
+++ b/chromium/components/ntp_snippets/user_classifier.h
@@ -56,7 +56,7 @@ class UserClassifier {
};
// The provided |pref_service| may be nullptr in unit-tests.
- UserClassifier(PrefService* pref_service, std::unique_ptr<base::Clock> clock);
+ UserClassifier(PrefService* pref_service, base::Clock* clock);
~UserClassifier();
// Registers profile prefs for all metrics. Called from browser_prefs.cc.
@@ -97,7 +97,7 @@ class UserClassifier {
void ClearMetricValue(Metric metric);
PrefService* pref_service_;
- std::unique_ptr<base::Clock> clock_;
+ base::Clock* clock_;
// Params of the metric.
const double discount_rate_per_hour_;
diff --git a/chromium/components/ntp_snippets/user_classifier_unittest.cc b/chromium/components/ntp_snippets/user_classifier_unittest.cc
index 882e7e6682b..af5464265eb 100644
--- a/chromium/components/ntp_snippets/user_classifier_unittest.cc
+++ b/chromium/components/ntp_snippets/user_classifier_unittest.cc
@@ -8,7 +8,6 @@
#include <string>
#include <utility>
-#include "base/memory/ptr_util.h"
#include "base/test/histogram_tester.h"
#include "base/test/simple_test_clock.h"
#include "base/time/time.h"
@@ -38,26 +37,21 @@ class UserClassifierTest : public testing::Test {
}
UserClassifier* CreateUserClassifier() {
- auto test_clock = base::MakeUnique<base::SimpleTestClock>();
- test_clock_ = test_clock.get();
-
base::Time now;
CHECK(base::Time::FromUTCString(kNowString, &now));
- test_clock_->SetNow(now);
+ test_clock_.SetNow(now);
user_classifier_ =
- base::MakeUnique<UserClassifier>(&test_prefs_, std::move(test_clock));
+ std::make_unique<UserClassifier>(&test_prefs_, &test_clock_);
return user_classifier_.get();
}
- base::SimpleTestClock* test_clock() { return test_clock_; }
+ base::SimpleTestClock* test_clock() { return &test_clock_; }
private:
TestingPrefServiceSimple test_prefs_;
std::unique_ptr<UserClassifier> user_classifier_;
-
- // Owned by the UserClassifier.
- base::SimpleTestClock* test_clock_;
+ base::SimpleTestClock test_clock_;
DISALLOW_COPY_AND_ASSIGN(UserClassifierTest);
};