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

Side by Side Diff: components/suggestions/suggestions_service_impl_unittest.cc

Issue 2869013004: Test SuggestionsServiceImpl without friending anything (Closed)
Patch Set: Fix comments Created 3 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « components/suggestions/suggestions_service_impl.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "components/suggestions/suggestions_service_impl.h" 5 #include "components/suggestions/suggestions_service_impl.h"
6 6
7 #include <stdint.h> 7 #include <stdint.h>
8 8
9 #include <memory> 9 #include <memory>
10 #include <utility> 10 #include <utility>
(...skipping 17 matching lines...) Expand all
28 #include "net/http/http_response_headers.h" 28 #include "net/http/http_response_headers.h"
29 #include "net/http/http_status_code.h" 29 #include "net/http/http_status_code.h"
30 #include "net/url_request/test_url_fetcher_factory.h" 30 #include "net/url_request/test_url_fetcher_factory.h"
31 #include "net/url_request/url_request_status.h" 31 #include "net/url_request/url_request_status.h"
32 #include "net/url_request/url_request_test_util.h" 32 #include "net/url_request/url_request_test_util.h"
33 #include "testing/gmock/include/gmock/gmock.h" 33 #include "testing/gmock/include/gmock/gmock.h"
34 #include "testing/gtest/include/gtest/gtest.h" 34 #include "testing/gtest/include/gtest/gtest.h"
35 #include "ui/gfx/image/image.h" 35 #include "ui/gfx/image/image.h"
36 36
37 using sync_preferences::TestingPrefServiceSyncable; 37 using sync_preferences::TestingPrefServiceSyncable;
38 using syncer::SyncServiceObserver;
38 using testing::_; 39 using testing::_;
39 using testing::AnyNumber; 40 using testing::AnyNumber;
40 using testing::DoAll; 41 using testing::DoAll;
41 using testing::Eq; 42 using testing::Eq;
43 using testing::Mock;
42 using testing::Return; 44 using testing::Return;
43 using testing::SetArgPointee; 45 using testing::SetArgPointee;
44 using testing::StrictMock; 46 using testing::StrictMock;
45 47
46 namespace { 48 namespace {
47 49
48 const char kAccountId[] = "account"; 50 const char kAccountId[] = "account";
51 const char kSuggestionsUrlPath[] = "/chromesuggestions";
52 const char kBlacklistUrlPath[] = "/chromesuggestions/blacklist";
53 const char kBlacklistClearUrlPath[] = "/chromesuggestions/blacklist/clear";
49 const char kTestTitle[] = "a title"; 54 const char kTestTitle[] = "a title";
50 const char kTestUrl[] = "http://go.com"; 55 const char kTestUrl[] = "http://go.com";
51 const char kTestFaviconUrl[] = 56 const char kTestFaviconUrl[] =
52 "https://s2.googleusercontent.com/s2/favicons?domain_url=" 57 "https://s2.googleusercontent.com/s2/favicons?domain_url="
53 "http://go.com&alt=s&sz=32"; 58 "http://go.com&alt=s&sz=32";
54 const char kBlacklistedUrl[] = "http://blacklist.com"; 59 const char kBlacklistedUrl[] = "http://blacklist.com";
55 const char kBlacklistedUrlAlt[] = "http://blacklist-atl.com"; 60 const int64_t kTestSetExpiry = 12121212; // This timestamp lies in the past.
56 const int64_t kTestDefaultExpiry = 1402200000000000;
57 const int64_t kTestSetExpiry = 1404792000000000;
58
59 std::unique_ptr<net::FakeURLFetcher> CreateURLFetcher(
60 const GURL& url,
61 net::URLFetcherDelegate* delegate,
62 const std::string& response_data,
63 net::HttpStatusCode response_code,
64 net::URLRequestStatus::Status status) {
65 std::unique_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher(
66 url, delegate, response_data, response_code, status));
67
68 if (response_code == net::HTTP_OK) {
69 scoped_refptr<net::HttpResponseHeaders> download_headers(
70 new net::HttpResponseHeaders(""));
71 download_headers->AddHeader("Content-Type: text/html");
72 fetcher->set_response_headers(download_headers);
73 }
74 return fetcher;
75 }
76 61
77 // GMock matcher for protobuf equality. 62 // GMock matcher for protobuf equality.
78 MATCHER_P(EqualsProto, message, "") { 63 MATCHER_P(EqualsProto, message, "") {
79 // This implementation assumes protobuf serialization is deterministic, which 64 // This implementation assumes protobuf serialization is deterministic, which
80 // is true in practice but technically not something that code is supposed 65 // is true in practice but technically not something that code is supposed
81 // to rely on. However, it vastly simplifies the implementation. 66 // to rely on. However, it vastly simplifies the implementation.
82 std::string expected_serialized, actual_serialized; 67 std::string expected_serialized, actual_serialized;
83 message.SerializeToString(&expected_serialized); 68 message.SerializeToString(&expected_serialized);
84 arg.SerializeToString(&actual_serialized); 69 arg.SerializeToString(&actual_serialized);
85 return expected_serialized == actual_serialized; 70 return expected_serialized == actual_serialized;
86 } 71 }
87 72
88 } // namespace 73 } // namespace
89 74
90 namespace suggestions { 75 namespace suggestions {
91 76
92 SuggestionsProfile CreateSuggestionsProfile() { 77 SuggestionsProfile CreateSuggestionsProfile() {
93 SuggestionsProfile profile; 78 SuggestionsProfile profile;
94 profile.set_timestamp(123); 79 profile.set_timestamp(123);
95 ChromeSuggestion* suggestion = profile.add_suggestions(); 80 ChromeSuggestion* suggestion = profile.add_suggestions();
96 suggestion->set_title(kTestTitle); 81 suggestion->set_title(kTestTitle);
97 suggestion->set_url(kTestUrl); 82 suggestion->set_url(kTestUrl);
98 suggestion->set_expiry_ts(kTestSetExpiry);
99 return profile; 83 return profile;
100 } 84 }
101 85
102 // Creates one suggestion with expiry timestamp and one without.
103 SuggestionsProfile CreateSuggestionsProfileWithExpiryTimestamps() {
104 SuggestionsProfile profile;
105 profile.set_timestamp(123);
106 ChromeSuggestion* suggestion = profile.add_suggestions();
107 suggestion->set_title(kTestTitle);
108 suggestion->set_url(kTestUrl);
109 suggestion->set_expiry_ts(kTestSetExpiry);
110
111 suggestion = profile.add_suggestions();
112 suggestion->set_title(kTestTitle);
113 suggestion->set_url(kTestUrl);
114
115 return profile;
116 }
117
118 class MockSyncService : public syncer::FakeSyncService { 86 class MockSyncService : public syncer::FakeSyncService {
119 public: 87 public:
120 MockSyncService() {} 88 MockSyncService() {}
121 virtual ~MockSyncService() {} 89 virtual ~MockSyncService() {}
122 MOCK_CONST_METHOD0(CanSyncStart, bool()); 90 MOCK_CONST_METHOD0(CanSyncStart, bool());
123 MOCK_CONST_METHOD0(IsSyncActive, bool()); 91 MOCK_CONST_METHOD0(IsSyncActive, bool());
124 MOCK_CONST_METHOD0(ConfigurationDone, bool()); 92 MOCK_CONST_METHOD0(ConfigurationDone, bool());
125 MOCK_CONST_METHOD0(GetActiveDataTypes, syncer::ModelTypeSet()); 93 MOCK_CONST_METHOD0(GetActiveDataTypes, syncer::ModelTypeSet());
126 }; 94 };
127 95
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
164 MOCK_METHOD1(GetCandidateForUpload, bool(GURL*)); 132 MOCK_METHOD1(GetCandidateForUpload, bool(GURL*));
165 MOCK_METHOD1(RemoveUrl, bool(const GURL&)); 133 MOCK_METHOD1(RemoveUrl, bool(const GURL&));
166 MOCK_METHOD1(FilterSuggestions, void(SuggestionsProfile*)); 134 MOCK_METHOD1(FilterSuggestions, void(SuggestionsProfile*));
167 }; 135 };
168 136
169 class SuggestionsServiceTest : public testing::Test { 137 class SuggestionsServiceTest : public testing::Test {
170 protected: 138 protected:
171 SuggestionsServiceTest() 139 SuggestionsServiceTest()
172 : signin_client_(&pref_service_), 140 : signin_client_(&pref_service_),
173 signin_manager_(&signin_client_, &account_tracker_), 141 signin_manager_(&signin_client_, &account_tracker_),
174 factory_(nullptr, base::Bind(&CreateURLFetcher)), 142 request_context_(new net::TestURLRequestContextGetter(
143 io_message_loop_.task_runner())),
175 mock_thumbnail_manager_(nullptr), 144 mock_thumbnail_manager_(nullptr),
176 mock_blacklist_store_(nullptr), 145 mock_blacklist_store_(nullptr),
177 test_suggestions_store_(nullptr) { 146 test_suggestions_store_(nullptr) {
178 SigninManagerBase::RegisterProfilePrefs(pref_service_.registry()); 147 SigninManagerBase::RegisterProfilePrefs(pref_service_.registry());
179 SigninManagerBase::RegisterPrefs(pref_service_.registry()); 148 SigninManagerBase::RegisterPrefs(pref_service_.registry());
180 149
181 signin_manager_.SignIn(kAccountId); 150 signin_manager_.SignIn(kAccountId);
182 token_service_.UpdateCredentials(kAccountId, "refresh_token"); 151 token_service_.UpdateCredentials(kAccountId, "refresh_token");
183 token_service_.set_auto_post_fetch_response_on_message_loop(true); 152 token_service_.set_auto_post_fetch_response_on_message_loop(true);
184 } 153 }
185 154
186 ~SuggestionsServiceTest() override {} 155 ~SuggestionsServiceTest() override {}
187 156
188 void SetUp() override { 157 void SetUp() override {
189 request_context_ = 158 EXPECT_CALL(*sync_service(), CanSyncStart())
190 new net::TestURLRequestContextGetter(io_message_loop_.task_runner());
191
192 EXPECT_CALL(mock_sync_service_, CanSyncStart())
193 .Times(AnyNumber()) 159 .Times(AnyNumber())
194 .WillRepeatedly(Return(true)); 160 .WillRepeatedly(Return(true));
195 EXPECT_CALL(mock_sync_service_, IsSyncActive()) 161 EXPECT_CALL(*sync_service(), IsSyncActive())
196 .Times(AnyNumber()) 162 .Times(AnyNumber())
197 .WillRepeatedly(Return(true)); 163 .WillRepeatedly(Return(true));
198 EXPECT_CALL(mock_sync_service_, ConfigurationDone()) 164 EXPECT_CALL(*sync_service(), ConfigurationDone())
199 .Times(AnyNumber()) 165 .Times(AnyNumber())
200 .WillRepeatedly(Return(true)); 166 .WillRepeatedly(Return(true));
201 EXPECT_CALL(mock_sync_service_, GetActiveDataTypes()) 167 EXPECT_CALL(*sync_service(), GetActiveDataTypes())
202 .Times(AnyNumber()) 168 .Times(AnyNumber())
203 .WillRepeatedly( 169 .WillRepeatedly(
204 Return(syncer::ModelTypeSet(syncer::HISTORY_DELETE_DIRECTIVES))); 170 Return(syncer::ModelTypeSet(syncer::HISTORY_DELETE_DIRECTIVES)));
205
206 // These objects are owned by the SuggestionsService, but we keep the 171 // These objects are owned by the SuggestionsService, but we keep the
207 // pointers around for testing. 172 // pointers around for testing.
208 test_suggestions_store_ = new TestSuggestionsStore(); 173 test_suggestions_store_ = new TestSuggestionsStore();
209 mock_thumbnail_manager_ = new StrictMock<MockImageManager>(); 174 mock_thumbnail_manager_ = new StrictMock<MockImageManager>();
210 mock_blacklist_store_ = new StrictMock<MockBlacklistStore>(); 175 mock_blacklist_store_ = new StrictMock<MockBlacklistStore>();
211 suggestions_service_ = base::MakeUnique<SuggestionsServiceImpl>( 176 suggestions_service_ = base::MakeUnique<SuggestionsServiceImpl>(
212 &signin_manager_, &token_service_, &mock_sync_service_, 177 &signin_manager_, &token_service_, &mock_sync_service_,
213 request_context_.get(), base::WrapUnique(test_suggestions_store_), 178 request_context_.get(), base::WrapUnique(test_suggestions_store_),
214 base::WrapUnique(mock_thumbnail_manager_), 179 base::WrapUnique(mock_thumbnail_manager_),
215 base::WrapUnique(mock_blacklist_store_)); 180 base::WrapUnique(mock_blacklist_store_));
216 } 181 }
217 182
218 bool HasPendingSuggestionsRequest() const { 183 GURL GetCurrentlyQueriedUrl() {
219 return !!suggestions_service_->pending_request_.get(); 184 net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
185 if (!fetcher) {
186 return GURL();
187 }
188 return fetcher->GetOriginalURL();
220 } 189 }
221 190
222 protected: 191 void RespondToFetch(const std::string& response_body,
192 net::HttpStatusCode response_code,
193 net::URLRequestStatus status) {
194 net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
195 ASSERT_TRUE(fetcher) << "Tried to respond to fetch that is not ongoing!";
196 fetcher->SetResponseString(response_body);
197 fetcher->set_response_code(response_code);
198 fetcher->set_status(status);
199 fetcher->delegate()->OnURLFetchComplete(fetcher);
200 }
201
202 void RespondToFetchWithProfile(const SuggestionsProfile& suggestions) {
203 RespondToFetch(
204 suggestions.SerializeAsString(), net::HTTP_OK,
205 net::URLRequestStatus(net::URLRequestStatus::SUCCESS, net::OK));
206 }
207
208 FakeProfileOAuth2TokenService* token_service() { return &token_service_; }
209
210 MockSyncService* sync_service() { return &mock_sync_service_; }
211
212 MockImageManager* thumbnail_manager() { return mock_thumbnail_manager_; }
213
214 MockBlacklistStore* blacklist_store() { return mock_blacklist_store_; }
215
216 TestSuggestionsStore* suggestions_store() { return test_suggestions_store_; }
217
218 SuggestionsServiceImpl* suggestions_service() {
219 return suggestions_service_.get();
220 }
221
222 private:
223 base::MessageLoopForIO io_message_loop_; 223 base::MessageLoopForIO io_message_loop_;
224 TestingPrefServiceSyncable pref_service_; 224 TestingPrefServiceSyncable pref_service_;
225 AccountTrackerService account_tracker_; 225 AccountTrackerService account_tracker_;
226 TestSigninClient signin_client_; 226 TestSigninClient signin_client_;
227 FakeSigninManagerBase signin_manager_; 227 FakeSigninManagerBase signin_manager_;
228 net::FakeURLFetcherFactory factory_; 228 net::TestURLFetcherFactory factory_;
229 FakeProfileOAuth2TokenService token_service_; 229 FakeProfileOAuth2TokenService token_service_;
230 MockSyncService mock_sync_service_; 230 MockSyncService mock_sync_service_;
231 scoped_refptr<net::TestURLRequestContextGetter> request_context_; 231 scoped_refptr<net::TestURLRequestContextGetter> request_context_;
232 // Owned by the SuggestionsService. 232 // Owned by the SuggestionsService.
233 MockImageManager* mock_thumbnail_manager_; 233 MockImageManager* mock_thumbnail_manager_;
234 MockBlacklistStore* mock_blacklist_store_; 234 MockBlacklistStore* mock_blacklist_store_;
235 TestSuggestionsStore* test_suggestions_store_; 235 TestSuggestionsStore* test_suggestions_store_;
236 236
237 std::unique_ptr<SuggestionsServiceImpl> suggestions_service_; 237 std::unique_ptr<SuggestionsServiceImpl> suggestions_service_;
238 238
239 private:
240 DISALLOW_COPY_AND_ASSIGN(SuggestionsServiceTest); 239 DISALLOW_COPY_AND_ASSIGN(SuggestionsServiceTest);
241 }; 240 };
242 241
243 TEST_F(SuggestionsServiceTest, FetchSuggestionsData) { 242 TEST_F(SuggestionsServiceTest, FetchSuggestionsData) {
244 base::MockCallback<SuggestionsService::ResponseCallback> callback; 243 base::MockCallback<SuggestionsService::ResponseCallback> callback;
245 auto subscription = suggestions_service_->AddCallback(callback.Get()); 244 auto subscription = suggestions_service()->AddCallback(callback.Get());
246 245
247 // Set up net::FakeURLFetcherFactory. 246 EXPECT_CALL(*thumbnail_manager(), Initialize(_));
248 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(), 247 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
249 CreateSuggestionsProfile().SerializeAsString(), 248 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
250 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
251
252 EXPECT_CALL(*mock_thumbnail_manager_, Initialize(_));
253 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_));
254 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_))
255 .WillOnce(Return(false)); 249 .WillOnce(Return(false));
256 250
257 // Send the request. The data should be returned to the callback. 251 // Send the request. The data should be returned to the callback.
258 suggestions_service_->FetchSuggestionsData(); 252 suggestions_service()->FetchSuggestionsData();
259 253
260 EXPECT_CALL(callback, Run(_)); 254 EXPECT_CALL(callback, Run(_));
261 255
262 // Let the network request run. 256 // Wait for the eventual network request.
263 base::RunLoop().RunUntilIdle(); 257 base::RunLoop().RunUntilIdle();
258 ASSERT_TRUE(GetCurrentlyQueriedUrl().is_valid());
259 EXPECT_EQ(GetCurrentlyQueriedUrl().path(), kSuggestionsUrlPath);
260 RespondToFetchWithProfile(CreateSuggestionsProfile());
264 261
265 SuggestionsProfile suggestions; 262 SuggestionsProfile suggestions;
266 test_suggestions_store_->LoadSuggestions(&suggestions); 263 suggestions_store()->LoadSuggestions(&suggestions);
267 ASSERT_EQ(1, suggestions.suggestions_size()); 264 ASSERT_EQ(1, suggestions.suggestions_size());
268 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title()); 265 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title());
269 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url()); 266 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url());
270 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url()); 267 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url());
271 } 268 }
272 269
273 TEST_F(SuggestionsServiceTest, IgnoresNoopSyncChange) { 270 TEST_F(SuggestionsServiceTest, IgnoresNoopSyncChange) {
274 base::MockCallback<SuggestionsService::ResponseCallback> callback; 271 base::MockCallback<SuggestionsService::ResponseCallback> callback;
275 EXPECT_CALL(callback, Run(_)).Times(0); 272 EXPECT_CALL(callback, Run(_)).Times(0);
276 auto subscription = suggestions_service_->AddCallback(callback.Get()); 273 auto subscription = suggestions_service()->AddCallback(callback.Get());
277
278 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(),
279 CreateSuggestionsProfile().SerializeAsString(),
280 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
281 274
282 // An no-op change should not result in a suggestions refresh. 275 // An no-op change should not result in a suggestions refresh.
283 suggestions_service_->OnStateChanged(&mock_sync_service_); 276 static_cast<SyncServiceObserver*>(suggestions_service())
277 ->OnStateChanged(sync_service());
284 278
285 // Let any network request run (there shouldn't be one). 279 // Wait for eventual (but unexpected) network requests.
286 base::RunLoop().RunUntilIdle(); 280 base::RunLoop().RunUntilIdle();
281 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
287 } 282 }
288 283
289 TEST_F(SuggestionsServiceTest, IgnoresUninterestingSyncChange) { 284 TEST_F(SuggestionsServiceTest, IgnoresUninterestingSyncChange) {
290 base::MockCallback<SuggestionsService::ResponseCallback> callback; 285 base::MockCallback<SuggestionsService::ResponseCallback> callback;
291 EXPECT_CALL(callback, Run(_)).Times(0); 286 EXPECT_CALL(callback, Run(_)).Times(0);
292 auto subscription = suggestions_service_->AddCallback(callback.Get()); 287 auto subscription = suggestions_service()->AddCallback(callback.Get());
293
294 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(),
295 CreateSuggestionsProfile().SerializeAsString(),
296 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
297 288
298 // An uninteresting change should not result in a network request (the 289 // An uninteresting change should not result in a network request (the
299 // SyncState is INITIALIZED_ENABLED_HISTORY before and after). 290 // SyncState is INITIALIZED_ENABLED_HISTORY before and after).
300 EXPECT_CALL(mock_sync_service_, GetActiveDataTypes()) 291 EXPECT_CALL(*sync_service(), GetActiveDataTypes())
301 .Times(AnyNumber()) 292 .Times(AnyNumber())
302 .WillRepeatedly(Return(syncer::ModelTypeSet( 293 .WillRepeatedly(Return(syncer::ModelTypeSet(
303 syncer::HISTORY_DELETE_DIRECTIVES, syncer::BOOKMARKS))); 294 syncer::HISTORY_DELETE_DIRECTIVES, syncer::BOOKMARKS)));
304 suggestions_service_->OnStateChanged(&mock_sync_service_); 295 static_cast<SyncServiceObserver*>(suggestions_service())
296 ->OnStateChanged(sync_service());
305 297
306 // Let any network request run (there shouldn't be one). 298 // Wait for eventual (but unexpected) network requests.
307 base::RunLoop().RunUntilIdle(); 299 base::RunLoop().RunUntilIdle();
300 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
308 } 301 }
309 302
310 // During startup, the state changes from NOT_INITIALIZED_ENABLED to 303 // During startup, the state changes from NOT_INITIALIZED_ENABLED to
311 // INITIALIZED_ENABLED_HISTORY (for a signed-in user with history sync enabled). 304 // INITIALIZED_ENABLED_HISTORY (for a signed-in user with history sync enabled).
312 // This should *not* result in an automatic fetch. 305 // This should *not* result in an automatic fetch.
313 TEST_F(SuggestionsServiceTest, DoesNotFetchOnStartup) { 306 TEST_F(SuggestionsServiceTest, DoesNotFetchOnStartup) {
314 // The sync service starts out inactive. 307 // The sync service starts out inactive.
315 EXPECT_CALL(mock_sync_service_, IsSyncActive()).WillRepeatedly(Return(false)); 308 EXPECT_CALL(*sync_service(), IsSyncActive()).WillRepeatedly(Return(false));
316 suggestions_service_->OnStateChanged(&mock_sync_service_); 309 static_cast<SyncServiceObserver*>(suggestions_service())
310 ->OnStateChanged(sync_service());
317 311
318 ASSERT_EQ(SuggestionsServiceImpl::NOT_INITIALIZED_ENABLED, 312 base::RunLoop().RunUntilIdle();
319 suggestions_service_->ComputeSyncState()); 313 ASSERT_FALSE(suggestions_service()->has_pending_request_for_testing());
314
315 // Sync getting enabled should not result in a fetch.
316 EXPECT_CALL(*sync_service(), IsSyncActive()).WillRepeatedly(Return(true));
317 static_cast<SyncServiceObserver*>(suggestions_service())
318 ->OnStateChanged(sync_service());
319
320 // Wait for eventual (but unexpected) network requests.
321 base::RunLoop().RunUntilIdle();
322 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
323 }
324
325 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataSyncNotInitializedEnabled) {
326 EXPECT_CALL(*sync_service(), IsSyncActive()).WillRepeatedly(Return(false));
327 static_cast<SyncServiceObserver*>(suggestions_service())
328 ->OnStateChanged(sync_service());
320 329
321 base::MockCallback<SuggestionsService::ResponseCallback> callback; 330 base::MockCallback<SuggestionsService::ResponseCallback> callback;
322 EXPECT_CALL(callback, Run(_)).Times(0); 331 EXPECT_CALL(callback, Run(_)).Times(0);
323 auto subscription = suggestions_service_->AddCallback(callback.Get()); 332 auto subscription = suggestions_service()->AddCallback(callback.Get());
324
325 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(),
326 CreateSuggestionsProfile().SerializeAsString(),
327 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
328
329 // Sync getting enabled should not result in a fetch.
330 EXPECT_CALL(mock_sync_service_, IsSyncActive()).WillRepeatedly(Return(true));
331 suggestions_service_->OnStateChanged(&mock_sync_service_);
332
333 ASSERT_EQ(SuggestionsServiceImpl::INITIALIZED_ENABLED_HISTORY,
334 suggestions_service_->ComputeSyncState());
335
336 // Let any network request run (there shouldn't be one).
337 base::RunLoop().RunUntilIdle();
338 }
339
340 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataSyncNotInitializedEnabled) {
341 EXPECT_CALL(mock_sync_service_, IsSyncActive()).WillRepeatedly(Return(false));
342 suggestions_service_->OnStateChanged(&mock_sync_service_);
343
344 base::MockCallback<SuggestionsService::ResponseCallback> callback;
345 EXPECT_CALL(callback, Run(_)).Times(0);
346 auto subscription = suggestions_service_->AddCallback(callback.Get());
347 333
348 // Try to fetch suggestions. Since sync is not active, no network request 334 // Try to fetch suggestions. Since sync is not active, no network request
349 // should be sent. 335 // should be sent.
350 suggestions_service_->FetchSuggestionsData(); 336 suggestions_service()->FetchSuggestionsData();
351 337
352 // Let any network request run (there shouldn't be one). 338 // Wait for eventual (but unexpected) network requests.
353 base::RunLoop().RunUntilIdle(); 339 base::RunLoop().RunUntilIdle();
340 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
354 341
355 // |test_suggestions_store_| should still contain the default values. 342 // |suggestions_store()| should still contain the default values.
356 SuggestionsProfile suggestions; 343 SuggestionsProfile suggestions;
357 test_suggestions_store_->LoadSuggestions(&suggestions); 344 suggestions_store()->LoadSuggestions(&suggestions);
358 EXPECT_THAT(suggestions, EqualsProto(CreateSuggestionsProfile())); 345 EXPECT_THAT(suggestions, EqualsProto(CreateSuggestionsProfile()));
359 } 346 }
360 347
361 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataSyncDisabled) { 348 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataSyncDisabled) {
362 EXPECT_CALL(mock_sync_service_, CanSyncStart()).WillRepeatedly(Return(false)); 349 EXPECT_CALL(*sync_service(), CanSyncStart()).WillRepeatedly(Return(false));
363 350
364 base::MockCallback<SuggestionsService::ResponseCallback> callback; 351 base::MockCallback<SuggestionsService::ResponseCallback> callback;
365 auto subscription = suggestions_service_->AddCallback(callback.Get()); 352 auto subscription = suggestions_service()->AddCallback(callback.Get());
366 353
367 // Tell SuggestionsService that the sync state changed. The cache should be 354 // Tell SuggestionsService that the sync state changed. The cache should be
368 // cleared and empty data returned to the callback. 355 // cleared and empty data returned to the callback.
369 EXPECT_CALL(callback, Run(EqualsProto(SuggestionsProfile()))); 356 EXPECT_CALL(callback, Run(EqualsProto(SuggestionsProfile())));
370 suggestions_service_->OnStateChanged(&mock_sync_service_); 357 static_cast<SyncServiceObserver*>(suggestions_service())
358 ->OnStateChanged(sync_service());
371 359
372 // Try to fetch suggestions. Since sync is not active, no network request 360 // Try to fetch suggestions. Since sync is not active, no network request
373 // should be sent. 361 // should be sent.
374 suggestions_service_->FetchSuggestionsData(); 362 suggestions_service()->FetchSuggestionsData();
375 363
376 // Let any network request run. 364 // Wait for eventual (but unexpected) network requests.
377 base::RunLoop().RunUntilIdle(); 365 base::RunLoop().RunUntilIdle();
366 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
378 } 367 }
379 368
380 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataNoAccessToken) { 369 TEST_F(SuggestionsServiceTest, FetchSuggestionsDataNoAccessToken) {
381 token_service_.set_auto_post_fetch_response_on_message_loop(false); 370 token_service()->set_auto_post_fetch_response_on_message_loop(false);
382 371
383 base::MockCallback<SuggestionsService::ResponseCallback> callback; 372 base::MockCallback<SuggestionsService::ResponseCallback> callback;
384 EXPECT_CALL(callback, Run(_)).Times(0); 373 EXPECT_CALL(callback, Run(_)).Times(0);
385 auto subscription = suggestions_service_->AddCallback(callback.Get()); 374 auto subscription = suggestions_service()->AddCallback(callback.Get());
386 375
387 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 376 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
388 .WillOnce(Return(false)); 377 .WillOnce(Return(false));
389 378
390 suggestions_service_->FetchSuggestionsData(); 379 suggestions_service()->FetchSuggestionsData();
391 380
392 token_service_.IssueErrorForAllPendingRequests(GoogleServiceAuthError( 381 token_service()->IssueErrorForAllPendingRequests(GoogleServiceAuthError(
393 GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS)); 382 GoogleServiceAuthError::State::INVALID_GAIA_CREDENTIALS));
394 383
395 // No network request should be sent. 384 // Wait for eventual (but unexpected) network requests.
396 base::RunLoop().RunUntilIdle(); 385 base::RunLoop().RunUntilIdle();
397 EXPECT_FALSE(HasPendingSuggestionsRequest()); 386 EXPECT_FALSE(suggestions_service()->has_pending_request_for_testing());
398 } 387 }
399 388
400 TEST_F(SuggestionsServiceTest, IssueRequestIfNoneOngoingError) { 389 TEST_F(SuggestionsServiceTest, FetchingSuggestionsIgnoresRequestFailure) {
401 // Fake a request error. 390 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
402 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(), 391 .WillOnce(Return(false));
403 "irrelevant", net::HTTP_OK,
404 net::URLRequestStatus::FAILED);
405 392
406 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 393 suggestions_service()->FetchSuggestionsData();
394
395 // Wait for the eventual network request.
396 base::RunLoop().RunUntilIdle();
397 RespondToFetch("irrelevant", net::HTTP_OK,
398 net::URLRequestStatus(net::URLRequestStatus::FAILED,
399 net::ERR_INVALID_RESPONSE));
400 }
401
402 TEST_F(SuggestionsServiceTest, FetchingSuggestionsClearsStoreIfResponseNotOK) {
403 suggestions_store()->StoreSuggestions(CreateSuggestionsProfile());
404
405 // Expect that an upload to the blacklist is scheduled.
406 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
407 .WillOnce(Return(false)); 407 .WillOnce(Return(false));
408 408
409 // Send the request. Empty data will be returned to the callback. 409 // Send the request. Empty data will be returned to the callback.
410 suggestions_service_->IssueRequestIfNoneOngoing( 410 suggestions_service()->FetchSuggestionsData();
411 SuggestionsServiceImpl::BuildSuggestionsURL());
412 411
413 // (Testing only) wait until suggestion fetch is complete. 412 // Wait for the eventual network request.
414 base::RunLoop().RunUntilIdle(); 413 base::RunLoop().RunUntilIdle();
415 } 414 RespondToFetch(
415 "irrelevant", net::HTTP_BAD_REQUEST,
416 net::URLRequestStatus(net::URLRequestStatus::SUCCESS, net::OK));
416 417
417 TEST_F(SuggestionsServiceTest, IssueRequestIfNoneOngoingResponseNotOK) {
418 // Fake a non-200 response code.
419 factory_.SetFakeResponse(SuggestionsServiceImpl::BuildSuggestionsURL(),
420 "irrelevant", net::HTTP_BAD_REQUEST,
421 net::URLRequestStatus::SUCCESS);
422
423 // Expect that an upload to the blacklist is scheduled.
424 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_))
425 .WillOnce(Return(false));
426
427 // Send the request. Empty data will be returned to the callback.
428 suggestions_service_->IssueRequestIfNoneOngoing(
429 SuggestionsServiceImpl::BuildSuggestionsURL());
430
431 // (Testing only) wait until suggestion fetch is complete.
432 base::RunLoop().RunUntilIdle();
433
434 // Expect no suggestions in the cache.
435 SuggestionsProfile empty_suggestions; 418 SuggestionsProfile empty_suggestions;
436 EXPECT_FALSE(test_suggestions_store_->LoadSuggestions(&empty_suggestions)); 419 EXPECT_FALSE(suggestions_store()->LoadSuggestions(&empty_suggestions));
437 } 420 }
438 421
439 TEST_F(SuggestionsServiceTest, BlacklistURL) { 422 TEST_F(SuggestionsServiceTest, BlacklistURL) {
423 // Calling RunUntilIdle on the RunLoop only works when the task is not posted
424 // for the future.
440 const base::TimeDelta no_delay = base::TimeDelta::FromSeconds(0); 425 const base::TimeDelta no_delay = base::TimeDelta::FromSeconds(0);
441 suggestions_service_->set_blacklist_delay(no_delay); 426 suggestions_service()->set_blacklist_delay_for_testing(no_delay);
442 427
443 base::MockCallback<SuggestionsService::ResponseCallback> callback; 428 base::MockCallback<SuggestionsService::ResponseCallback> callback;
444 auto subscription = suggestions_service_->AddCallback(callback.Get()); 429 auto subscription = suggestions_service()->AddCallback(callback.Get());
445 430
446 const GURL blacklisted_url(kBlacklistedUrl); 431 EXPECT_CALL(*thumbnail_manager(), Initialize(_)).Times(2);
447 const GURL request_url( 432 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
448 SuggestionsServiceImpl::BuildSuggestionsBlacklistURL(blacklisted_url));
449 factory_.SetFakeResponse(request_url,
450 CreateSuggestionsProfile().SerializeAsString(),
451 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
452 EXPECT_CALL(*mock_thumbnail_manager_, Initialize(_)).Times(2);
453
454 // Expected calls to the blacklist store.
455 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url)))
456 .WillOnce(Return(true)); 433 .WillOnce(Return(true));
457 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)).Times(2); 434 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_)).Times(2);
458 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 435 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
459 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true))) 436 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true)))
460 .WillOnce(Return(false)); 437 .WillOnce(Return(false));
461 EXPECT_CALL(*mock_blacklist_store_, GetCandidateForUpload(_)) 438 EXPECT_CALL(*blacklist_store(), GetCandidateForUpload(_))
462 .WillOnce(DoAll(SetArgPointee<0>(blacklisted_url), Return(true))); 439 .WillOnce(DoAll(SetArgPointee<0>(GURL(kBlacklistedUrl)), Return(true)));
463 EXPECT_CALL(*mock_blacklist_store_, RemoveUrl(Eq(blacklisted_url))) 440 EXPECT_CALL(*blacklist_store(), RemoveUrl(Eq(GURL(kBlacklistedUrl))))
464 .WillOnce(Return(true)); 441 .WillOnce(Return(true));
465 442
466 EXPECT_CALL(callback, Run(_)).Times(2); 443 EXPECT_CALL(callback, Run(_)).Times(2);
467 444
468 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 445 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
469 446
470 // Wait on the upload task, the blacklist request and the next blacklist 447 // Wait on the upload task, the blacklist request and the next blacklist
471 // scheduling task. This only works when the scheduling task is not for future 448 // scheduling task. This only works when the scheduling task is not for future
472 // execution (note how both the SuggestionsService's scheduling delay and the 449 // execution (note how both the SuggestionsService's scheduling delay and the
473 // BlacklistStore's candidacy delay are zero). 450 // BlacklistStore's candidacy delay are zero).
474 base::RunLoop().RunUntilIdle(); 451 base::RunLoop().RunUntilIdle();
475 452
453 EXPECT_EQ(GetCurrentlyQueriedUrl().path(), kBlacklistUrlPath);
454 RespondToFetchWithProfile(CreateSuggestionsProfile());
455
476 SuggestionsProfile suggestions; 456 SuggestionsProfile suggestions;
477 test_suggestions_store_->LoadSuggestions(&suggestions); 457 suggestions_store()->LoadSuggestions(&suggestions);
478 ASSERT_EQ(1, suggestions.suggestions_size()); 458 ASSERT_EQ(1, suggestions.suggestions_size());
479 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title()); 459 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title());
480 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url()); 460 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url());
481 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url()); 461 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url());
482 } 462 }
483 463
484 TEST_F(SuggestionsServiceTest, BlacklistURLFails) { 464 TEST_F(SuggestionsServiceTest, BlacklistURLFails) {
485 base::MockCallback<SuggestionsService::ResponseCallback> callback; 465 base::MockCallback<SuggestionsService::ResponseCallback> callback;
486 EXPECT_CALL(callback, Run(_)).Times(0); 466 EXPECT_CALL(callback, Run(_)).Times(0);
487 auto subscription = suggestions_service_->AddCallback(callback.Get()); 467 auto subscription = suggestions_service()->AddCallback(callback.Get());
488 468
489 const GURL blacklisted_url(kBlacklistedUrl); 469 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
490 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url)))
491 .WillOnce(Return(false)); 470 .WillOnce(Return(false));
492 EXPECT_FALSE(suggestions_service_->BlacklistURL(blacklisted_url)); 471
472 EXPECT_FALSE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
493 } 473 }
494 474
495 // Initial blacklist request fails, triggering a second which succeeds. 475 TEST_F(SuggestionsServiceTest, RetryBlacklistURLRequestAfterFailure) {
496 TEST_F(SuggestionsServiceTest, BlacklistURLRequestFails) { 476 // Calling RunUntilIdle on the RunLoop only works when the task is not
477 // posted for the future.
497 const base::TimeDelta no_delay = base::TimeDelta::FromSeconds(0); 478 const base::TimeDelta no_delay = base::TimeDelta::FromSeconds(0);
498 suggestions_service_->set_blacklist_delay(no_delay); 479 suggestions_service()->set_blacklist_delay_for_testing(no_delay);
499 480
500 base::MockCallback<SuggestionsService::ResponseCallback> callback; 481 base::MockCallback<SuggestionsService::ResponseCallback> callback;
501 auto subscription = suggestions_service_->AddCallback(callback.Get()); 482 auto subscription = suggestions_service()->AddCallback(callback.Get());
502 483
503 const GURL blacklisted_url(kBlacklistedUrl); 484 // Set expectations for first, failing request.
504 const GURL request_url( 485 EXPECT_CALL(*thumbnail_manager(), Initialize(_));
505 SuggestionsServiceImpl::BuildSuggestionsBlacklistURL(blacklisted_url)); 486 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
506 const GURL blacklisted_url_alt(kBlacklistedUrlAlt);
507 const GURL request_url_alt(
508 SuggestionsServiceImpl::BuildSuggestionsBlacklistURL(
509 blacklisted_url_alt));
510
511 // Note: we want to set the response for the blacklist URL to first
512 // succeed, then fail. This doesn't seem possible. For simplicity of testing,
513 // we'll pretend the URL changed in the BlacklistStore between the first and
514 // the second request, and adjust expectations accordingly.
515 factory_.SetFakeResponse(request_url, "irrelevant", net::HTTP_OK,
516 net::URLRequestStatus::FAILED);
517 factory_.SetFakeResponse(request_url_alt,
518 CreateSuggestionsProfile().SerializeAsString(),
519 net::HTTP_OK, net::URLRequestStatus::SUCCESS);
520
521 // Expectations.
522 EXPECT_CALL(*mock_thumbnail_manager_, Initialize(_)).Times(2);
523 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url)))
524 .WillOnce(Return(true)); 487 .WillOnce(Return(true));
525 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)).Times(2); 488 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
526 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 489 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
527 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true))) 490 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true)))
528 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true))) 491 .WillOnce(DoAll(SetArgPointee<0>(no_delay), Return(true)));
529 .WillOnce(Return(false)); 492 EXPECT_CALL(*blacklist_store(), GetCandidateForUpload(_))
530 EXPECT_CALL(*mock_blacklist_store_, GetCandidateForUpload(_)) 493 .WillOnce(DoAll(SetArgPointee<0>(GURL(kBlacklistedUrl)), Return(true)));
531 .WillOnce(DoAll(SetArgPointee<0>(blacklisted_url), Return(true)))
532 .WillOnce(DoAll(SetArgPointee<0>(blacklisted_url_alt), Return(true)));
533 EXPECT_CALL(*mock_blacklist_store_, RemoveUrl(Eq(blacklisted_url_alt)))
534 .WillOnce(Return(true));
535 494
536 EXPECT_CALL(callback, Run(_)).Times(2); 495 EXPECT_CALL(callback, Run(_)).Times(2);
537 496
538 // Blacklist call, first request attempt. 497 // Blacklist call, first request attempt.
539 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 498 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
540 499
541 // Wait for the first scheduling, the first request, the second scheduling, 500 // Wait for the first scheduling receiving a failing response.
542 // second request and the third scheduling. Again, note that calling
543 // RunUntilIdle on the MessageLoop only works when the task is not posted for
544 // the future.
545 base::RunLoop().RunUntilIdle(); 501 base::RunLoop().RunUntilIdle();
502 ASSERT_TRUE(GetCurrentlyQueriedUrl().is_valid());
503 EXPECT_EQ(GetCurrentlyQueriedUrl().path(), kBlacklistUrlPath);
504 RespondToFetch("irrelevant", net::HTTP_OK,
505 net::URLRequestStatus(net::URLRequestStatus::FAILED,
506 net::ERR_INVALID_RESPONSE));
507
508 // Assert that the failure was processed as expected.
509 Mock::VerifyAndClearExpectations(thumbnail_manager());
510 Mock::VerifyAndClearExpectations(blacklist_store());
511
512 // Now expect the retried request to succeed.
513 EXPECT_CALL(*thumbnail_manager(), Initialize(_));
514 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
515 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
516 .WillOnce(Return(false));
517 EXPECT_CALL(*blacklist_store(), GetCandidateForUpload(_))
518 .WillOnce(DoAll(SetArgPointee<0>(GURL(kBlacklistedUrl)), Return(true)));
519 EXPECT_CALL(*blacklist_store(), RemoveUrl(Eq(GURL(kBlacklistedUrl))))
520 .WillOnce(Return(true));
521
522 // Wait for the second scheduling followed by a successful response.
523 base::RunLoop().RunUntilIdle();
524 ASSERT_TRUE(GetCurrentlyQueriedUrl().is_valid());
525 EXPECT_EQ(GetCurrentlyQueriedUrl().path(), kBlacklistUrlPath);
526 RespondToFetchWithProfile(CreateSuggestionsProfile());
546 527
547 SuggestionsProfile suggestions; 528 SuggestionsProfile suggestions;
548 test_suggestions_store_->LoadSuggestions(&suggestions); 529 suggestions_store()->LoadSuggestions(&suggestions);
549 ASSERT_EQ(1, suggestions.suggestions_size()); 530 ASSERT_EQ(1, suggestions.suggestions_size());
550 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title()); 531 EXPECT_EQ(kTestTitle, suggestions.suggestions(0).title());
551 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url()); 532 EXPECT_EQ(kTestUrl, suggestions.suggestions(0).url());
552 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url()); 533 EXPECT_EQ(kTestFaviconUrl, suggestions.suggestions(0).favicon_url());
553 } 534 }
554 535
555 TEST_F(SuggestionsServiceTest, UndoBlacklistURL) { 536 TEST_F(SuggestionsServiceTest, UndoBlacklistURL) {
556 // Ensure scheduling the request doesn't happen before undo. 537 // Ensure scheduling the request doesn't happen before undo.
557 const base::TimeDelta delay = base::TimeDelta::FromHours(1); 538 const base::TimeDelta delay = base::TimeDelta::FromHours(1);
558 suggestions_service_->set_blacklist_delay(delay); 539 suggestions_service()->set_blacklist_delay_for_testing(delay);
559 540
560 base::MockCallback<SuggestionsService::ResponseCallback> callback; 541 base::MockCallback<SuggestionsService::ResponseCallback> callback;
561 auto subscription = suggestions_service_->AddCallback(callback.Get()); 542 auto subscription = suggestions_service()->AddCallback(callback.Get());
562
563 const GURL blacklisted_url(kBlacklistedUrl);
564 543
565 // Blacklist expectations. 544 // Blacklist expectations.
566 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url))) 545 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
567 .WillOnce(Return(true)); 546 .WillOnce(Return(true));
568 EXPECT_CALL(*mock_thumbnail_manager_, 547 EXPECT_CALL(*thumbnail_manager(),
569 Initialize(EqualsProto(CreateSuggestionsProfile()))) 548 Initialize(EqualsProto(CreateSuggestionsProfile())))
570 .Times(AnyNumber()); 549 .Times(AnyNumber());
571 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)).Times(AnyNumber()); 550 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_)).Times(AnyNumber());
572 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 551 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
573 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true))); 552 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true)));
574 // Undo expectations. 553 // Undo expectations.
575 EXPECT_CALL(*mock_blacklist_store_, 554 EXPECT_CALL(*blacklist_store(),
576 GetTimeUntilURLReadyForUpload(Eq(blacklisted_url), _)) 555 GetTimeUntilURLReadyForUpload(Eq(GURL(kBlacklistedUrl)), _))
577 .WillOnce(DoAll(SetArgPointee<1>(delay), Return(true))); 556 .WillOnce(DoAll(SetArgPointee<1>(delay), Return(true)));
578 EXPECT_CALL(*mock_blacklist_store_, RemoveUrl(Eq(blacklisted_url))) 557 EXPECT_CALL(*blacklist_store(), RemoveUrl(Eq(GURL(kBlacklistedUrl))))
579 .WillOnce(Return(true)); 558 .WillOnce(Return(true));
580 559
581 EXPECT_CALL(callback, Run(_)).Times(2); 560 EXPECT_CALL(callback, Run(_)).Times(2);
582 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 561 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
583 EXPECT_TRUE(suggestions_service_->UndoBlacklistURL(blacklisted_url)); 562 EXPECT_TRUE(suggestions_service()->UndoBlacklistURL(GURL(kBlacklistedUrl)));
584 } 563 }
585 564
586 TEST_F(SuggestionsServiceTest, ClearBlacklist) { 565 TEST_F(SuggestionsServiceTest, ClearBlacklist) {
587 // Ensure scheduling the request doesn't happen before undo.
588 const base::TimeDelta delay = base::TimeDelta::FromHours(1); 566 const base::TimeDelta delay = base::TimeDelta::FromHours(1);
589 suggestions_service_->set_blacklist_delay(delay); 567 suggestions_service()->set_blacklist_delay_for_testing(delay);
590 568
591 base::MockCallback<SuggestionsService::ResponseCallback> callback; 569 base::MockCallback<SuggestionsService::ResponseCallback> callback;
592 auto subscription = suggestions_service_->AddCallback(callback.Get()); 570 auto subscription = suggestions_service()->AddCallback(callback.Get());
593
594 const SuggestionsProfile suggestions_profile = CreateSuggestionsProfile();
595 const GURL blacklisted_url(kBlacklistedUrl);
596
597 factory_.SetFakeResponse(
598 SuggestionsServiceImpl::BuildSuggestionsBlacklistClearURL(),
599 suggestions_profile.SerializeAsString(), net::HTTP_OK,
600 net::URLRequestStatus::SUCCESS);
601 571
602 // Blacklist expectations. 572 // Blacklist expectations.
603 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url))) 573 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
604 .WillOnce(Return(true)); 574 .WillOnce(Return(true));
605 EXPECT_CALL(*mock_thumbnail_manager_, 575 EXPECT_CALL(*thumbnail_manager(),
606 Initialize(EqualsProto(suggestions_profile))) 576 Initialize(EqualsProto(CreateSuggestionsProfile())))
607 .Times(AnyNumber()); 577 .Times(AnyNumber());
608 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)).Times(AnyNumber()); 578 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_)).Times(AnyNumber());
609 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 579 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
610 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true))); 580 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true)));
611 EXPECT_CALL(*mock_blacklist_store_, ClearBlacklist()); 581 EXPECT_CALL(*blacklist_store(), ClearBlacklist());
612 582
613 EXPECT_CALL(callback, Run(_)).Times(2); 583 EXPECT_CALL(callback, Run(_)).Times(2);
614 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 584 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
615 suggestions_service_->ClearBlacklist(); 585 suggestions_service()->ClearBlacklist();
586
587 // Wait for the eventual network request.
588 base::RunLoop().RunUntilIdle();
589 EXPECT_EQ(GetCurrentlyQueriedUrl().path(), kBlacklistClearUrlPath);
616 } 590 }
617 591
618 TEST_F(SuggestionsServiceTest, UndoBlacklistURLFailsIfNotInBlacklist) { 592 TEST_F(SuggestionsServiceTest, UndoBlacklistURLFailsIfNotInBlacklist) {
619 // Ensure scheduling the request doesn't happen before undo. 593 // Ensure scheduling the request doesn't happen before undo.
620 const base::TimeDelta delay = base::TimeDelta::FromHours(1); 594 const base::TimeDelta delay = base::TimeDelta::FromHours(1);
621 suggestions_service_->set_blacklist_delay(delay); 595 suggestions_service()->set_blacklist_delay_for_testing(delay);
622 596
623 base::MockCallback<SuggestionsService::ResponseCallback> callback; 597 base::MockCallback<SuggestionsService::ResponseCallback> callback;
624 auto subscription = suggestions_service_->AddCallback(callback.Get()); 598 auto subscription = suggestions_service()->AddCallback(callback.Get());
625
626 const GURL blacklisted_url(kBlacklistedUrl);
627 599
628 // Blacklist expectations. 600 // Blacklist expectations.
629 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url))) 601 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
630 .WillOnce(Return(true)); 602 .WillOnce(Return(true));
631 EXPECT_CALL(*mock_thumbnail_manager_, 603 EXPECT_CALL(*thumbnail_manager(),
632 Initialize(EqualsProto(CreateSuggestionsProfile()))); 604 Initialize(EqualsProto(CreateSuggestionsProfile())));
633 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)); 605 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
634 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 606 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
635 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true))); 607 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true)));
636 608 // Undo expectations.
637 // URL is not in local blacklist. 609 // URL is not in local blacklist.
638 EXPECT_CALL(*mock_blacklist_store_, 610 EXPECT_CALL(*blacklist_store(),
639 GetTimeUntilURLReadyForUpload(Eq(blacklisted_url), _)) 611 GetTimeUntilURLReadyForUpload(Eq(GURL(kBlacklistedUrl)), _))
640 .WillOnce(Return(false)); 612 .WillOnce(Return(false));
641 613
642 EXPECT_CALL(callback, Run(_)); 614 EXPECT_CALL(callback, Run(_));
643 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 615
644 EXPECT_FALSE(suggestions_service_->UndoBlacklistURL(blacklisted_url)); 616 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
617 EXPECT_FALSE(suggestions_service()->UndoBlacklistURL(GURL(kBlacklistedUrl)));
645 } 618 }
646 619
647 TEST_F(SuggestionsServiceTest, UndoBlacklistURLFailsIfAlreadyCandidate) { 620 TEST_F(SuggestionsServiceTest, UndoBlacklistURLFailsIfAlreadyCandidate) {
648 // Ensure scheduling the request doesn't happen before undo. 621 // Ensure scheduling the request doesn't happen before undo.
649 const base::TimeDelta delay = base::TimeDelta::FromHours(1); 622 const base::TimeDelta delay = base::TimeDelta::FromHours(1);
650 suggestions_service_->set_blacklist_delay(delay); 623 suggestions_service()->set_blacklist_delay_for_testing(delay);
651 624
652 base::MockCallback<SuggestionsService::ResponseCallback> callback; 625 base::MockCallback<SuggestionsService::ResponseCallback> callback;
653 auto subscription = suggestions_service_->AddCallback(callback.Get()); 626 auto subscription = suggestions_service()->AddCallback(callback.Get());
654
655 const GURL blacklisted_url(kBlacklistedUrl);
656 627
657 // Blacklist expectations. 628 // Blacklist expectations.
658 EXPECT_CALL(*mock_blacklist_store_, BlacklistUrl(Eq(blacklisted_url))) 629 EXPECT_CALL(*blacklist_store(), BlacklistUrl(Eq(GURL(kBlacklistedUrl))))
659 .WillOnce(Return(true)); 630 .WillOnce(Return(true));
660 EXPECT_CALL(*mock_thumbnail_manager_, 631 EXPECT_CALL(*thumbnail_manager(),
661 Initialize(EqualsProto(CreateSuggestionsProfile()))); 632 Initialize(EqualsProto(CreateSuggestionsProfile())));
662 EXPECT_CALL(*mock_blacklist_store_, FilterSuggestions(_)); 633 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
663 EXPECT_CALL(*mock_blacklist_store_, GetTimeUntilReadyForUpload(_)) 634 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
664 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true))); 635 .WillOnce(DoAll(SetArgPointee<0>(delay), Return(true)));
665 636
666 // URL is not yet candidate for upload. 637 // URL is not yet candidate for upload.
667 base::TimeDelta negative_delay = base::TimeDelta::FromHours(-1); 638 const base::TimeDelta negative_delay = base::TimeDelta::FromHours(-1);
668 EXPECT_CALL(*mock_blacklist_store_, 639 EXPECT_CALL(*blacklist_store(),
669 GetTimeUntilURLReadyForUpload(Eq(blacklisted_url), _)) 640 GetTimeUntilURLReadyForUpload(Eq(GURL(kBlacklistedUrl)), _))
670 .WillOnce(DoAll(SetArgPointee<1>(negative_delay), Return(true))); 641 .WillOnce(DoAll(SetArgPointee<1>(negative_delay), Return(true)));
671 642
672 EXPECT_CALL(callback, Run(_)); 643 EXPECT_CALL(callback, Run(_));
673 EXPECT_TRUE(suggestions_service_->BlacklistURL(blacklisted_url)); 644
674 EXPECT_FALSE(suggestions_service_->UndoBlacklistURL(blacklisted_url)); 645 EXPECT_TRUE(suggestions_service()->BlacklistURL(GURL(kBlacklistedUrl)));
646 EXPECT_FALSE(suggestions_service()->UndoBlacklistURL(GURL(kBlacklistedUrl)));
675 } 647 }
676 648
677 TEST_F(SuggestionsServiceTest, GetBlacklistedUrlNotBlacklistRequest) { 649 TEST_F(SuggestionsServiceTest, TemporarilyIncreasesBlacklistDelayOnFailure) {
678 // Not a blacklist request. 650 EXPECT_CALL(*thumbnail_manager(), Initialize(_)).Times(AnyNumber());
679 std::unique_ptr<net::FakeURLFetcher> fetcher( 651 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_)).Times(AnyNumber());
680 CreateURLFetcher(GURL("http://not-blacklisting.com/a?b=c"), nullptr, "", 652 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
681 net::HTTP_OK, net::URLRequestStatus::SUCCESS)); 653 .Times(AnyNumber())
682 GURL retrieved_url; 654 .WillRepeatedly(Return(false));
683 EXPECT_FALSE( 655 const base::TimeDelta initial_delay =
684 SuggestionsServiceImpl::GetBlacklistedUrl(*fetcher, &retrieved_url)); 656 suggestions_service()->blacklist_delay_for_testing();
657
658 // Delay unchanged on success.
659 suggestions_service()->FetchSuggestionsData();
660 base::RunLoop().RunUntilIdle();
661 RespondToFetchWithProfile(CreateSuggestionsProfile());
662 EXPECT_EQ(initial_delay,
663 suggestions_service()->blacklist_delay_for_testing());
664
665 // Delay increases on failure.
666 suggestions_service()->FetchSuggestionsData();
667 base::RunLoop().RunUntilIdle();
668 RespondToFetch(
669 "irrelevant", net::HTTP_BAD_REQUEST,
670 net::URLRequestStatus(net::URLRequestStatus::SUCCESS, net::OK));
671 EXPECT_GT(suggestions_service()->blacklist_delay_for_testing(),
672 initial_delay);
673
674 // Delay resets on success.
675 suggestions_service()->FetchSuggestionsData();
676 base::RunLoop().RunUntilIdle();
677 RespondToFetchWithProfile(CreateSuggestionsProfile());
678 EXPECT_EQ(initial_delay,
679 suggestions_service()->blacklist_delay_for_testing());
685 } 680 }
686 681
687 TEST_F(SuggestionsServiceTest, GetBlacklistedUrlBlacklistRequest) { 682 TEST_F(SuggestionsServiceTest, DoesNotOverrideDefaultExpiryTime) {
688 // An actual blacklist request. 683 EXPECT_CALL(*thumbnail_manager(), Initialize(_));
689 const GURL blacklisted_url("http://blacklisted.com/a?b=c&d=e"); 684 EXPECT_CALL(*blacklist_store(), FilterSuggestions(_));
690 const std::string encoded_blacklisted_url = 685 EXPECT_CALL(*blacklist_store(), GetTimeUntilReadyForUpload(_))
691 "http%3A%2F%2Fblacklisted.com%2Fa%3Fb%3Dc%26d%3De"; 686 .WillOnce(Return(false));
692 const std::string blacklist_request_prefix(
693 SuggestionsServiceImpl::BuildSuggestionsBlacklistURLPrefix());
694 std::unique_ptr<net::FakeURLFetcher> fetcher(CreateURLFetcher(
695 GURL(blacklist_request_prefix + encoded_blacklisted_url), nullptr, "",
696 net::HTTP_OK, net::URLRequestStatus::SUCCESS));
697 GURL retrieved_url;
698 EXPECT_TRUE(
699 SuggestionsServiceImpl::GetBlacklistedUrl(*fetcher, &retrieved_url));
700 EXPECT_EQ(blacklisted_url, retrieved_url);
701 }
702 687
703 TEST_F(SuggestionsServiceTest, UpdateBlacklistDelay) { 688 suggestions_service()->FetchSuggestionsData();
704 const base::TimeDelta initial_delay = suggestions_service_->blacklist_delay();
705 689
706 // Delay unchanged on success. 690 base::RunLoop().RunUntilIdle();
707 suggestions_service_->UpdateBlacklistDelay(true); 691 // Creates one suggestion without timestamp and adds a second with timestamp.
708 EXPECT_EQ(initial_delay, suggestions_service_->blacklist_delay()); 692 SuggestionsProfile profile = CreateSuggestionsProfile();
693 ChromeSuggestion* suggestion = profile.add_suggestions();
694 suggestion->set_title(kTestTitle);
695 suggestion->set_url(kTestUrl);
696 suggestion->set_expiry_ts(kTestSetExpiry);
697 RespondToFetchWithProfile(profile);
709 698
710 // Delay increases on failure. 699 SuggestionsProfile suggestions;
711 suggestions_service_->UpdateBlacklistDelay(false); 700 suggestions_store()->LoadSuggestions(&suggestions);
712 EXPECT_GT(suggestions_service_->blacklist_delay(), initial_delay); 701 ASSERT_EQ(2, suggestions.suggestions_size());
713 702 // Suggestion[0] had no time stamp and should be ahead of the old suggestion.
714 // Delay resets on success. 703 EXPECT_LT(kTestSetExpiry, suggestions.suggestions(0).expiry_ts());
715 suggestions_service_->UpdateBlacklistDelay(true); 704 // Suggestion[1] had a very old time stamp but should not be updated.
716 EXPECT_EQ(initial_delay, suggestions_service_->blacklist_delay()); 705 EXPECT_EQ(kTestSetExpiry, suggestions.suggestions(1).expiry_ts());
717 }
718
719 TEST_F(SuggestionsServiceTest, CheckDefaultTimeStamps) {
720 SuggestionsProfile suggestions =
721 CreateSuggestionsProfileWithExpiryTimestamps();
722 suggestions_service_->SetDefaultExpiryTimestamp(&suggestions,
723 kTestDefaultExpiry);
724 EXPECT_EQ(kTestSetExpiry, suggestions.suggestions(0).expiry_ts());
725 EXPECT_EQ(kTestDefaultExpiry, suggestions.suggestions(1).expiry_ts());
726 } 706 }
727 707
728 TEST_F(SuggestionsServiceTest, GetPageThumbnail) { 708 TEST_F(SuggestionsServiceTest, GetPageThumbnail) {
729 const GURL test_url(kTestUrl); 709 const GURL test_url(kTestUrl);
730 const GURL thumbnail_url("https://www.thumbnails.com/thumb.jpg"); 710 const GURL thumbnail_url("https://www.thumbnails.com/thumb.jpg");
731 base::Callback<void(const GURL&, const gfx::Image&)> dummy_callback; 711 base::Callback<void(const GURL&, const gfx::Image&)> dummy_callback;
732 712
733 EXPECT_CALL(*mock_thumbnail_manager_, GetImageForURL(test_url, _)); 713 EXPECT_CALL(*thumbnail_manager(), GetImageForURL(test_url, _));
734 suggestions_service_->GetPageThumbnail(test_url, dummy_callback); 714 suggestions_service()->GetPageThumbnail(test_url, dummy_callback);
735 715
736 EXPECT_CALL(*mock_thumbnail_manager_, AddImageURL(test_url, thumbnail_url)); 716 EXPECT_CALL(*thumbnail_manager(), AddImageURL(test_url, thumbnail_url));
737 EXPECT_CALL(*mock_thumbnail_manager_, GetImageForURL(test_url, _)); 717 EXPECT_CALL(*thumbnail_manager(), GetImageForURL(test_url, _));
738 suggestions_service_->GetPageThumbnailWithURL(test_url, thumbnail_url, 718 suggestions_service()->GetPageThumbnailWithURL(test_url, thumbnail_url,
739 dummy_callback); 719 dummy_callback);
740 } 720 }
741 721
742 } // namespace suggestions 722 } // namespace suggestions
OLDNEW
« no previous file with comments | « components/suggestions/suggestions_service_impl.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698