OLD | NEW |
1 // Copyright 2016 The Chromium Authors. All rights reserved. | 1 // Copyright 2016 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "components/ntp_snippets/remote/ntp_snippets_fetcher.h" | 5 #include "components/ntp_snippets/remote/ntp_snippets_fetcher.h" |
6 | 6 |
7 #include <deque> | 7 #include <deque> |
8 #include <map> | 8 #include <map> |
| 9 #include <set> |
9 #include <utility> | 10 #include <utility> |
| 11 #include <vector> |
10 | 12 |
11 #include "base/json/json_reader.h" | 13 #include "base/json/json_reader.h" |
12 #include "base/memory/ptr_util.h" | 14 #include "base/memory/ptr_util.h" |
13 #include "base/strings/stringprintf.h" | 15 #include "base/strings/stringprintf.h" |
14 #include "base/test/histogram_tester.h" | 16 #include "base/test/histogram_tester.h" |
15 #include "base/test/test_mock_time_task_runner.h" | 17 #include "base/test/test_mock_time_task_runner.h" |
16 #include "base/threading/thread_task_runner_handle.h" | 18 #include "base/threading/thread_task_runner_handle.h" |
17 #include "base/time/time.h" | 19 #include "base/time/time.h" |
18 #include "base/values.h" | 20 #include "base/values.h" |
19 #include "components/ntp_snippets/category_factory.h" | 21 #include "components/ntp_snippets/category_factory.h" |
20 #include "components/ntp_snippets/features.h" | 22 #include "components/ntp_snippets/features.h" |
21 #include "components/ntp_snippets/ntp_snippets_constants.h" | 23 #include "components/ntp_snippets/ntp_snippets_constants.h" |
22 #include "components/ntp_snippets/remote/ntp_snippet.h" | 24 #include "components/ntp_snippets/remote/ntp_snippet.h" |
| 25 #include "components/ntp_snippets/remote/ntp_snippets_request_params.h" |
23 #include "components/ntp_snippets/user_classifier.h" | 26 #include "components/ntp_snippets/user_classifier.h" |
24 #include "components/prefs/testing_pref_service.h" | 27 #include "components/prefs/testing_pref_service.h" |
25 #include "components/signin/core/browser/account_tracker_service.h" | 28 #include "components/signin/core/browser/account_tracker_service.h" |
26 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" | 29 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h" |
27 #include "components/signin/core/browser/fake_signin_manager.h" | 30 #include "components/signin/core/browser/fake_signin_manager.h" |
28 #include "components/signin/core/browser/test_signin_client.h" | 31 #include "components/signin/core/browser/test_signin_client.h" |
29 #include "components/variations/entropy_provider.h" | 32 #include "components/variations/entropy_provider.h" |
30 #include "components/variations/variations_params_manager.h" | 33 #include "components/variations/variations_params_manager.h" |
31 #include "net/url_request/test_url_fetcher_factory.h" | 34 #include "net/url_request/test_url_fetcher_factory.h" |
32 #include "net/url_request/url_request_test_util.h" | 35 #include "net/url_request/url_request_test_util.h" |
33 #include "testing/gmock/include/gmock/gmock.h" | 36 #include "testing/gmock/include/gmock/gmock.h" |
34 #include "testing/gtest/include/gtest/gtest.h" | 37 #include "testing/gtest/include/gtest/gtest.h" |
35 | 38 |
36 namespace ntp_snippets { | 39 namespace ntp_snippets { |
37 | 40 |
38 namespace { | 41 namespace { |
39 | 42 |
40 using testing::_; | 43 using testing::_; |
41 using testing::AllOf; | 44 using testing::AllOf; |
42 using testing::ElementsAre; | 45 using testing::ElementsAre; |
43 using testing::Eq; | 46 using testing::Eq; |
44 using testing::Field; | 47 using testing::Field; |
45 using testing::IsEmpty; | 48 using testing::IsEmpty; |
46 using testing::Not; | 49 using testing::Not; |
47 using testing::NotNull; | 50 using testing::NotNull; |
48 using testing::Pointee; | 51 using testing::Pointee; |
49 using testing::PrintToString; | 52 using testing::PrintToString; |
50 using testing::Return; | 53 using testing::Return; |
51 using testing::StartsWith; | 54 using testing::StartsWith; |
52 using testing::StrEq; | |
53 using testing::WithArg; | 55 using testing::WithArg; |
54 | 56 |
55 const char kAPIKey[] = "fakeAPIkey"; | 57 const char kAPIKey[] = "fakeAPIkey"; |
56 const char kTestChromeReaderUrl[] = | 58 const char kTestChromeReaderUrl[] = |
57 "https://chromereader-pa.googleapis.com/v1/fetch?key=fakeAPIkey"; | 59 "https://chromereader-pa.googleapis.com/v1/fetch?key=fakeAPIkey"; |
58 const char kTestChromeContentSuggestionsUrl[] = | 60 const char kTestChromeContentSuggestionsUrl[] = |
59 "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/" | 61 "https://chromecontentsuggestions-pa.googleapis.com/v1/suggestions/" |
60 "fetch?key=fakeAPIkey"; | 62 "fetch?key=fakeAPIkey"; |
61 | 63 |
62 // Artificial time delay for JSON parsing. | 64 // Artificial time delay for JSON parsing. |
(...skipping 68 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
131 } | 133 } |
132 | 134 |
133 MATCHER_P(FirstCategoryHasInfo, info_matcher, "") { | 135 MATCHER_P(FirstCategoryHasInfo, info_matcher, "") { |
134 if (!arg->has_value() || arg->value().size() == 0) { | 136 if (!arg->has_value() || arg->value().size() == 0) { |
135 *result_listener << "No category found."; | 137 *result_listener << "No category found."; |
136 } | 138 } |
137 return testing::ExplainMatchResult( | 139 return testing::ExplainMatchResult( |
138 info_matcher, arg->value().front().info, result_listener); | 140 info_matcher, arg->value().front().info, result_listener); |
139 } | 141 } |
140 | 142 |
141 MATCHER_P(EqualsJSON, json, "equals JSON") { | |
142 std::unique_ptr<base::Value> expected = base::JSONReader::Read(json); | |
143 if (!expected) { | |
144 *result_listener << "INTERNAL ERROR: couldn't parse expected JSON"; | |
145 return false; | |
146 } | |
147 | |
148 std::string err_msg; | |
149 int err_line, err_col; | |
150 std::unique_ptr<base::Value> actual = base::JSONReader::ReadAndReturnError( | |
151 arg, base::JSON_PARSE_RFC, nullptr, &err_msg, &err_line, &err_col); | |
152 if (!actual) { | |
153 *result_listener << "input:" << err_line << ":" << err_col << ": " | |
154 << "parse error: " << err_msg; | |
155 return false; | |
156 } | |
157 return base::Value::Equals(actual.get(), expected.get()); | |
158 } | |
159 | |
160 class MockSnippetsAvailableCallback { | 143 class MockSnippetsAvailableCallback { |
161 public: | 144 public: |
162 // Workaround for gMock's lack of support for movable arguments. | 145 // Workaround for gMock's lack of support for movable arguments. |
163 void WrappedRun( | 146 void WrappedRun( |
164 Status status, | 147 Status status, |
165 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { | 148 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories) { |
166 Run(status, &fetched_categories); | 149 Run(status, &fetched_categories); |
167 } | 150 } |
168 | 151 |
169 MOCK_METHOD2( | 152 MOCK_METHOD2( |
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
256 int id, const GURL& url, net::URLFetcher::RequestType request_type, | 239 int id, const GURL& url, net::URLFetcher::RequestType request_type, |
257 net::URLFetcherDelegate* d) override { | 240 net::URLFetcherDelegate* d) override { |
258 return base::MakeUnique<net::FakeURLFetcher>( | 241 return base::MakeUnique<net::FakeURLFetcher>( |
259 url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND, | 242 url, d, /*response_data=*/std::string(), net::HTTP_NOT_FOUND, |
260 net::URLRequestStatus::FAILED); | 243 net::URLRequestStatus::FAILED); |
261 } | 244 } |
262 }; | 245 }; |
263 | 246 |
264 void ParseJson( | 247 void ParseJson( |
265 const std::string& json, | 248 const std::string& json, |
266 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, | 249 const internal::NTPSnippetsJsonRequest::SuccessCallback& success_callback, |
267 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { | 250 const internal::NTPSnippetsJsonRequest::ErrorCallback& error_callback) { |
268 base::JSONReader json_reader; | 251 base::JSONReader json_reader; |
269 std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); | 252 std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); |
270 if (value) { | 253 if (value) { |
271 success_callback.Run(std::move(value)); | 254 success_callback.Run(std::move(value)); |
272 } else { | 255 } else { |
273 error_callback.Run(json_reader.GetErrorMessage()); | 256 error_callback.Run(json_reader.GetErrorMessage()); |
274 } | 257 } |
275 } | 258 } |
276 | 259 |
277 void ParseJsonDelayed( | 260 void ParseJsonDelayed( |
278 const std::string& json, | 261 const std::string& json, |
279 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, | 262 const internal::NTPSnippetsJsonRequest::SuccessCallback& success_callback, |
280 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { | 263 const internal::NTPSnippetsJsonRequest::ErrorCallback& error_callback) { |
281 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( | 264 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( |
282 FROM_HERE, base::Bind(&ParseJson, json, std::move(success_callback), | 265 FROM_HERE, base::Bind(&ParseJson, json, std::move(success_callback), |
283 std::move(error_callback)), | 266 std::move(error_callback)), |
284 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); | 267 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); |
285 } | 268 } |
286 | 269 |
287 } // namespace | 270 } // namespace |
288 | 271 |
289 class NTPSnippetsFetcherTestBase : public testing::Test { | 272 class NTPSnippetsFetcherTestBase : public testing::Test { |
290 public: | 273 public: |
(...skipping 11 matching lines...) Expand all Loading... |
302 signin_client_(base::MakeUnique<TestSigninClient>(nullptr)), | 285 signin_client_(base::MakeUnique<TestSigninClient>(nullptr)), |
303 account_tracker_(base::MakeUnique<AccountTrackerService>()), | 286 account_tracker_(base::MakeUnique<AccountTrackerService>()), |
304 fake_signin_manager_( | 287 fake_signin_manager_( |
305 base::MakeUnique<FakeSigninManagerBase>(signin_client_.get(), | 288 base::MakeUnique<FakeSigninManagerBase>(signin_client_.get(), |
306 account_tracker_.get())), | 289 account_tracker_.get())), |
307 fake_token_service_(base::MakeUnique<FakeProfileOAuth2TokenService>()), | 290 fake_token_service_(base::MakeUnique<FakeProfileOAuth2TokenService>()), |
308 pref_service_(base::MakeUnique<TestingPrefServiceSimple>()), | 291 pref_service_(base::MakeUnique<TestingPrefServiceSimple>()), |
309 test_url_(gurl) { | 292 test_url_(gurl) { |
310 RequestThrottler::RegisterProfilePrefs(pref_service_->registry()); | 293 RequestThrottler::RegisterProfilePrefs(pref_service_->registry()); |
311 UserClassifier::RegisterProfilePrefs(pref_service_->registry()); | 294 UserClassifier::RegisterProfilePrefs(pref_service_->registry()); |
312 translate::LanguageModel::RegisterProfilePrefs(pref_service()->registry()); | |
313 user_classifier_ = base::MakeUnique<UserClassifier>(pref_service_.get()); | 295 user_classifier_ = base::MakeUnique<UserClassifier>(pref_service_.get()); |
314 // Increase initial time such that ticks are non-zero. | 296 // Increase initial time such that ticks are non-zero. |
315 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234)); | 297 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234)); |
316 ResetSnippetsFetcher(); | 298 ResetSnippetsFetcher(); |
317 } | 299 } |
318 | 300 |
319 void ResetSnippetsFetcher() { | 301 void ResetSnippetsFetcher() { |
320 snippets_fetcher_ = base::MakeUnique<NTPSnippetsFetcher>( | 302 snippets_fetcher_ = base::MakeUnique<NTPSnippetsFetcher>( |
321 fake_signin_manager_.get(), fake_token_service_.get(), | 303 fake_signin_manager_.get(), fake_token_service_.get(), |
322 scoped_refptr<net::TestURLRequestContextGetter>( | 304 scoped_refptr<net::TestURLRequestContextGetter>( |
(...skipping 11 matching lines...) Expand all Loading... |
334 base::Unretained(callback)); | 316 base::Unretained(callback)); |
335 } | 317 } |
336 | 318 |
337 NTPSnippetsFetcher& snippets_fetcher() { return *snippets_fetcher_; } | 319 NTPSnippetsFetcher& snippets_fetcher() { return *snippets_fetcher_; } |
338 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; } | 320 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; } |
339 void FastForwardUntilNoTasksRemain() { | 321 void FastForwardUntilNoTasksRemain() { |
340 mock_task_runner_->FastForwardUntilNoTasksRemain(); | 322 mock_task_runner_->FastForwardUntilNoTasksRemain(); |
341 } | 323 } |
342 base::HistogramTester& histogram_tester() { return histogram_tester_; } | 324 base::HistogramTester& histogram_tester() { return histogram_tester_; } |
343 | 325 |
344 NTPSnippetsFetcher::Params test_params() { | 326 NTPSnippetsRequestParams test_params() { |
345 NTPSnippetsFetcher::Params result; | 327 NTPSnippetsRequestParams result; |
346 result.count_to_fetch = 1; | 328 result.count_to_fetch = 1; |
347 result.interactive_request = true; | 329 result.interactive_request = true; |
348 return result; | 330 return result; |
349 } | 331 } |
350 | 332 |
351 void InitFakeURLFetcherFactory() { | 333 void InitFakeURLFetcherFactory() { |
352 if (fake_url_fetcher_factory_) { | 334 if (fake_url_fetcher_factory_) { |
353 return; | 335 return; |
354 } | 336 } |
355 // Instantiation of factory automatically sets itself as URLFetcher's | 337 // Instantiation of factory automatically sets itself as URLFetcher's |
(...skipping 30 matching lines...) Expand all Loading... |
386 } | 368 } |
387 | 369 |
388 void SetFakeResponse(const std::string& response_data, | 370 void SetFakeResponse(const std::string& response_data, |
389 net::HttpStatusCode response_code, | 371 net::HttpStatusCode response_code, |
390 net::URLRequestStatus::Status status) { | 372 net::URLRequestStatus::Status status) { |
391 InitFakeURLFetcherFactory(); | 373 InitFakeURLFetcherFactory(); |
392 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, | 374 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, |
393 response_code, status); | 375 response_code, status); |
394 } | 376 } |
395 | 377 |
396 std::unique_ptr<translate::LanguageModel> MakeLanguageModel( | |
397 const std::vector<std::string>& codes) { | |
398 std::unique_ptr<translate::LanguageModel> language_model = | |
399 base::MakeUnique<translate::LanguageModel>(pref_service()); | |
400 // There must be at least 10 visits before the top languages are defined. | |
401 for (int i = 0; i < 10; i++) { | |
402 for (const auto& code : codes) { | |
403 language_model->OnPageVisited(code); | |
404 } | |
405 } | |
406 return language_model; | |
407 } | |
408 | |
409 TestingPrefServiceSimple* pref_service() const { return pref_service_.get(); } | 378 TestingPrefServiceSimple* pref_service() const { return pref_service_.get(); } |
410 | 379 |
411 private: | 380 private: |
412 std::map<std::string, std::string> default_variation_params_; | 381 std::map<std::string, std::string> default_variation_params_; |
413 // TODO(fhorschig): Make it a simple member when crbug.com/672010 is resolved. | 382 // TODO(fhorschig): Make it a simple member when crbug.com/672010 is resolved. |
414 std::unique_ptr<variations::testing::VariationParamsManager> params_manager_; | 383 std::unique_ptr<variations::testing::VariationParamsManager> params_manager_; |
415 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; | 384 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; |
416 base::ThreadTaskRunnerHandle mock_task_runner_handle_; | 385 base::ThreadTaskRunnerHandle mock_task_runner_handle_; |
417 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; | 386 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; |
418 // Initialized lazily in SetFakeResponse(). | 387 // Initialized lazily in SetFakeResponse(). |
(...skipping 23 matching lines...) Expand all Loading... |
442 : public NTPSnippetsFetcherTestBase { | 411 : public NTPSnippetsFetcherTestBase { |
443 public: | 412 public: |
444 NTPSnippetsContentSuggestionsFetcherTest() | 413 NTPSnippetsContentSuggestionsFetcherTest() |
445 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) { | 414 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) { |
446 SetDefaultVariationParam("content_suggestions_backend", | 415 SetDefaultVariationParam("content_suggestions_backend", |
447 kContentSuggestionsServer); | 416 kContentSuggestionsServer); |
448 ResetSnippetsFetcher(); | 417 ResetSnippetsFetcher(); |
449 } | 418 } |
450 }; | 419 }; |
451 | 420 |
452 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestAuthenticated) { | |
453 NTPSnippetsFetcher::RequestBuilder builder; | |
454 NTPSnippetsFetcher::Params params; | |
455 params.excluded_ids = {"1234567890"}; | |
456 params.count_to_fetch = 25; | |
457 params.interactive_request = false; | |
458 builder.SetParams(params) | |
459 .SetAuthentication("0BFUSGAIA", "headerstuff") | |
460 .SetPersonalization(NTPSnippetsFetcher::Personalization::kPersonal) | |
461 .SetUserClassForTesting("ACTIVE_NTP_USER") | |
462 .SetFetchAPI(NTPSnippetsFetcher::CHROME_READER_API); | |
463 | |
464 EXPECT_THAT(builder.PreviewRequestHeadersForTesting(), | |
465 StrEq("Content-Type: application/json; charset=UTF-8\r\n" | |
466 "Authorization: headerstuff\r\n" | |
467 "\r\n")); | |
468 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
469 EqualsJSON("{" | |
470 " \"response_detail_level\": \"STANDARD\"," | |
471 " \"obfuscated_gaia_id\": \"0BFUSGAIA\"," | |
472 " \"advanced_options\": {" | |
473 " \"local_scoring_params\": {" | |
474 " \"content_params\": {" | |
475 " \"only_return_personalized_results\": true" | |
476 " }," | |
477 " \"content_restricts\": [" | |
478 " {" | |
479 " \"type\": \"METADATA\"," | |
480 " \"value\": \"TITLE\"" | |
481 " }," | |
482 " {" | |
483 " \"type\": \"METADATA\"," | |
484 " \"value\": \"SNIPPET\"" | |
485 " }," | |
486 " {" | |
487 " \"type\": \"METADATA\"," | |
488 " \"value\": \"THUMBNAIL\"" | |
489 " }" | |
490 " ]" | |
491 " }," | |
492 " \"global_scoring_params\": {" | |
493 " \"num_to_return\": 25," | |
494 " \"sort_type\": 1" | |
495 " }" | |
496 " }" | |
497 "}")); | |
498 | |
499 builder.SetFetchAPI( | |
500 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
501 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
502 EqualsJSON("{" | |
503 " \"priority\": \"BACKGROUND_PREFETCH\"," | |
504 " \"excludedSuggestionIds\": [" | |
505 " \"1234567890\"" | |
506 " ]," | |
507 " \"userActivenessClass\": \"ACTIVE_NTP_USER\"" | |
508 "}")); | |
509 } | |
510 | |
511 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestUnauthenticated) { | |
512 NTPSnippetsFetcher::RequestBuilder builder; | |
513 NTPSnippetsFetcher::Params params = test_params(); | |
514 params.count_to_fetch = 10; | |
515 builder.SetParams(params) | |
516 .SetUserClassForTesting("ACTIVE_NTP_USER") | |
517 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal) | |
518 .SetFetchAPI(NTPSnippetsFetcher::CHROME_READER_API); | |
519 | |
520 EXPECT_THAT(builder.PreviewRequestHeadersForTesting(), | |
521 StrEq("Content-Type: application/json; charset=UTF-8\r\n" | |
522 "\r\n")); | |
523 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
524 EqualsJSON("{" | |
525 " \"response_detail_level\": \"STANDARD\"," | |
526 " \"advanced_options\": {" | |
527 " \"local_scoring_params\": {" | |
528 " \"content_params\": {" | |
529 " \"only_return_personalized_results\": false" | |
530 " }," | |
531 " \"content_restricts\": [" | |
532 " {" | |
533 " \"type\": \"METADATA\"," | |
534 " \"value\": \"TITLE\"" | |
535 " }," | |
536 " {" | |
537 " \"type\": \"METADATA\"," | |
538 " \"value\": \"SNIPPET\"" | |
539 " }," | |
540 " {" | |
541 " \"type\": \"METADATA\"," | |
542 " \"value\": \"THUMBNAIL\"" | |
543 " }" | |
544 " ]" | |
545 " }," | |
546 " \"global_scoring_params\": {" | |
547 " \"num_to_return\": 10," | |
548 " \"sort_type\": 1" | |
549 " }" | |
550 " }" | |
551 "}")); | |
552 | |
553 builder.SetFetchAPI( | |
554 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
555 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
556 EqualsJSON("{" | |
557 " \"priority\": \"USER_ACTION\"," | |
558 " \"excludedSuggestionIds\": []," | |
559 " \"userActivenessClass\": \"ACTIVE_NTP_USER\"" | |
560 "}")); | |
561 } | |
562 | |
563 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestExcludedIds) { | |
564 NTPSnippetsFetcher::RequestBuilder builder; | |
565 NTPSnippetsFetcher::Params params = test_params(); | |
566 params.interactive_request = false; | |
567 for (int i = 0; i < 200; ++i) { | |
568 params.excluded_ids.insert(base::StringPrintf("%03d", i)); | |
569 } | |
570 builder.SetParams(params) | |
571 .SetUserClassForTesting("ACTIVE_NTP_USER") | |
572 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal) | |
573 .SetFetchAPI( | |
574 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
575 | |
576 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
577 EqualsJSON("{" | |
578 " \"priority\": \"BACKGROUND_PREFETCH\"," | |
579 " \"excludedSuggestionIds\": [" | |
580 " \"000\", \"001\", \"002\", \"003\", \"004\"," | |
581 " \"005\", \"006\", \"007\", \"008\", \"009\"," | |
582 " \"010\", \"011\", \"012\", \"013\", \"014\"," | |
583 " \"015\", \"016\", \"017\", \"018\", \"019\"," | |
584 " \"020\", \"021\", \"022\", \"023\", \"024\"," | |
585 " \"025\", \"026\", \"027\", \"028\", \"029\"," | |
586 " \"030\", \"031\", \"032\", \"033\", \"034\"," | |
587 " \"035\", \"036\", \"037\", \"038\", \"039\"," | |
588 " \"040\", \"041\", \"042\", \"043\", \"044\"," | |
589 " \"045\", \"046\", \"047\", \"048\", \"049\"," | |
590 " \"050\", \"051\", \"052\", \"053\", \"054\"," | |
591 " \"055\", \"056\", \"057\", \"058\", \"059\"," | |
592 " \"060\", \"061\", \"062\", \"063\", \"064\"," | |
593 " \"065\", \"066\", \"067\", \"068\", \"069\"," | |
594 " \"070\", \"071\", \"072\", \"073\", \"074\"," | |
595 " \"075\", \"076\", \"077\", \"078\", \"079\"," | |
596 " \"080\", \"081\", \"082\", \"083\", \"084\"," | |
597 " \"085\", \"086\", \"087\", \"088\", \"089\"," | |
598 " \"090\", \"091\", \"092\", \"093\", \"094\"," | |
599 " \"095\", \"096\", \"097\", \"098\", \"099\"" | |
600 // Truncated to 100 entries. Currently, they happen to | |
601 // be those lexically first. | |
602 " ]," | |
603 " \"userActivenessClass\": \"ACTIVE_NTP_USER\"" | |
604 "}")); | |
605 } | |
606 | |
607 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestNoUserClass) { | |
608 NTPSnippetsFetcher::RequestBuilder builder; | |
609 NTPSnippetsFetcher::Params params = test_params(); | |
610 params.interactive_request = false; | |
611 builder.SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal) | |
612 .SetParams(params) | |
613 .SetFetchAPI( | |
614 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
615 | |
616 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
617 EqualsJSON("{" | |
618 " \"priority\": \"BACKGROUND_PREFETCH\"," | |
619 " \"excludedSuggestionIds\": []" | |
620 "}")); | |
621 } | |
622 | |
623 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestWithTwoLanguages) { | |
624 NTPSnippetsFetcher::RequestBuilder builder; | |
625 std::unique_ptr<translate::LanguageModel> language_model = | |
626 MakeLanguageModel({"de", "en"}); | |
627 NTPSnippetsFetcher::Params params = test_params(); | |
628 params.language_code = "en"; | |
629 builder.SetParams(params) | |
630 .SetLanguageModel(language_model.get()) | |
631 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal) | |
632 .SetFetchAPI( | |
633 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
634 | |
635 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
636 EqualsJSON("{" | |
637 " \"priority\": \"USER_ACTION\"," | |
638 " \"uiLanguage\": \"en\"," | |
639 " \"excludedSuggestionIds\": []," | |
640 " \"topLanguages\": [" | |
641 " {" | |
642 " \"language\" : \"en\"," | |
643 " \"frequency\" : 0.5" | |
644 " }," | |
645 " {" | |
646 " \"language\" : \"de\"," | |
647 " \"frequency\" : 0.5" | |
648 " }" | |
649 " ]" | |
650 "}")); | |
651 } | |
652 | |
653 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestWithUILanguageOnly) { | |
654 NTPSnippetsFetcher::RequestBuilder builder; | |
655 std::unique_ptr<translate::LanguageModel> language_model = | |
656 MakeLanguageModel({"en"}); | |
657 NTPSnippetsFetcher::Params params = test_params(); | |
658 params.language_code = "en"; | |
659 builder.SetParams(params) | |
660 .SetLanguageModel(language_model.get()) | |
661 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal) | |
662 .SetFetchAPI( | |
663 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API); | |
664 | |
665 EXPECT_THAT(builder.PreviewRequestBodyForTesting(), | |
666 EqualsJSON("{" | |
667 " \"priority\": \"USER_ACTION\"," | |
668 " \"uiLanguage\": \"en\"," | |
669 " \"excludedSuggestionIds\": []," | |
670 " \"topLanguages\": [{" | |
671 " \"language\" : \"en\"," | |
672 " \"frequency\" : 1.0" | |
673 " }]" | |
674 "}")); | |
675 } | |
676 | |
677 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) { | 421 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) { |
678 // The lack of registered baked in responses would cause any fetch to fail. | 422 // The lack of registered baked in responses would cause any fetch to fail. |
679 FastForwardUntilNoTasksRemain(); | 423 FastForwardUntilNoTasksRemain(); |
680 EXPECT_THAT(histogram_tester().GetAllSamples( | 424 EXPECT_THAT(histogram_tester().GetAllSamples( |
681 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), | 425 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), |
682 IsEmpty()); | 426 IsEmpty()); |
683 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), | 427 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), |
684 IsEmpty()); | 428 IsEmpty()); |
685 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); | 429 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); |
686 } | 430 } |
(...skipping 247 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
934 " \"ampUrl\" : \"http://localhost/amp\"," | 678 " \"ampUrl\" : \"http://localhost/amp\"," |
935 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " | 679 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " |
936 " }]" | 680 " }]" |
937 "}]}"; | 681 "}]}"; |
938 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, | 682 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, |
939 net::URLRequestStatus::SUCCESS); | 683 net::URLRequestStatus::SUCCESS); |
940 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories; | 684 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories; |
941 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) | 685 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) |
942 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); | 686 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); |
943 | 687 |
944 NTPSnippetsFetcher::Params params = test_params(); | 688 NTPSnippetsRequestParams params = test_params(); |
945 params.exclusive_category = base::Optional<Category>( | 689 params.exclusive_category = base::Optional<Category>( |
946 CategoryFactory().FromRemoteCategory(2)); | 690 CategoryFactory().FromRemoteCategory(2)); |
947 snippets_fetcher().FetchSnippets( | 691 snippets_fetcher().FetchSnippets( |
948 params, ToSnippetsAvailableCallback(&mock_callback())); | 692 params, ToSnippetsAvailableCallback(&mock_callback())); |
949 FastForwardUntilNoTasksRemain(); | 693 FastForwardUntilNoTasksRemain(); |
950 | 694 |
951 ASSERT_TRUE(fetched_categories); | 695 ASSERT_TRUE(fetched_categories); |
952 ASSERT_THAT(fetched_categories->size(), Eq(1u)); | 696 ASSERT_THAT(fetched_categories->size(), Eq(1u)); |
953 const auto& category = (*fetched_categories)[0]; | 697 const auto& category = (*fetched_categories)[0]; |
954 EXPECT_THAT(category.category.id(), | 698 EXPECT_THAT(category.category.id(), |
955 Eq(CategoryFactory().FromRemoteCategory(2).id())); | 699 Eq(CategoryFactory().FromRemoteCategory(2).id())); |
956 ASSERT_THAT(category.snippets.size(), Eq(1u)); | 700 ASSERT_THAT(category.snippets.size(), Eq(1u)); |
957 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2")); | 701 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2")); |
958 } | 702 } |
959 | 703 |
960 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) { | 704 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) { |
961 // Default setting should be both personalization options. | 705 // Default setting should be both personalization options. |
962 EXPECT_THAT(snippets_fetcher().personalization(), | 706 EXPECT_THAT(snippets_fetcher().personalization(), |
963 Eq(NTPSnippetsFetcher::Personalization::kBoth)); | 707 Eq(internal::Personalization::kBoth)); |
964 | 708 |
965 SetVariationParam("fetching_personalization", "personal"); | 709 SetVariationParam("fetching_personalization", "personal"); |
966 ResetSnippetsFetcher(); | 710 ResetSnippetsFetcher(); |
967 EXPECT_THAT(snippets_fetcher().personalization(), | 711 EXPECT_THAT(snippets_fetcher().personalization(), |
968 Eq(NTPSnippetsFetcher::Personalization::kPersonal)); | 712 Eq(internal::Personalization::kPersonal)); |
969 | 713 |
970 SetVariationParam("fetching_personalization", "non_personal"); | 714 SetVariationParam("fetching_personalization", "non_personal"); |
971 ResetSnippetsFetcher(); | 715 ResetSnippetsFetcher(); |
972 EXPECT_THAT(snippets_fetcher().personalization(), | 716 EXPECT_THAT(snippets_fetcher().personalization(), |
973 Eq(NTPSnippetsFetcher::Personalization::kNonPersonal)); | 717 Eq(internal::Personalization::kNonPersonal)); |
974 | 718 |
975 SetVariationParam("fetching_personalization", "both"); | 719 SetVariationParam("fetching_personalization", "both"); |
976 ResetSnippetsFetcher(); | 720 ResetSnippetsFetcher(); |
977 EXPECT_THAT(snippets_fetcher().personalization(), | 721 EXPECT_THAT(snippets_fetcher().personalization(), |
978 Eq(NTPSnippetsFetcher::Personalization::kBoth)); | 722 Eq(internal::Personalization::kBoth)); |
979 } | 723 } |
980 | 724 |
981 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { | 725 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { |
982 const std::string kJsonStr = "{\"recos\": []}"; | 726 const std::string kJsonStr = "{\"recos\": []}"; |
983 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, | 727 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, |
984 net::URLRequestStatus::SUCCESS); | 728 net::URLRequestStatus::SUCCESS); |
985 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); | 729 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); |
986 snippets_fetcher().FetchSnippets( | 730 snippets_fetcher().FetchSnippets( |
987 test_params(), ToSnippetsAvailableCallback(&mock_callback())); | 731 test_params(), ToSnippetsAvailableCallback(&mock_callback())); |
988 FastForwardUntilNoTasksRemain(); | 732 FastForwardUntilNoTasksRemain(); |
989 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); | 733 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); |
990 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); | 734 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); |
991 EXPECT_THAT( | 735 EXPECT_THAT( |
992 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), | 736 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), |
993 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); | 737 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); |
994 EXPECT_THAT(histogram_tester().GetAllSamples( | 738 EXPECT_THAT(histogram_tester().GetAllSamples( |
995 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), | 739 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), |
996 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); | 740 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); |
997 } | 741 } |
998 | 742 |
999 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) { | 743 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) { |
1000 DelegateCallingTestURLFetcherFactory fetcher_factory; | 744 DelegateCallingTestURLFetcherFactory fetcher_factory; |
1001 NTPSnippetsFetcher::Params params = test_params(); | 745 NTPSnippetsRequestParams params = test_params(); |
1002 params.interactive_request = true; | 746 params.interactive_request = true; |
1003 | 747 |
1004 snippets_fetcher().FetchSnippets( | 748 snippets_fetcher().FetchSnippets( |
1005 params, ToSnippetsAvailableCallback(&mock_callback())); | 749 params, ToSnippetsAvailableCallback(&mock_callback())); |
1006 | 750 |
1007 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); | 751 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); |
1008 ASSERT_THAT(fetcher, NotNull()); | 752 ASSERT_THAT(fetcher, NotNull()); |
1009 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2)); | 753 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2)); |
1010 } | 754 } |
1011 | 755 |
1012 TEST_F(ChromeReaderSnippetsFetcherTest, | 756 TEST_F(ChromeReaderSnippetsFetcherTest, |
1013 RetriesConfigurableOnNonInteractiveRequests) { | 757 RetriesConfigurableOnNonInteractiveRequests) { |
1014 struct ExpectationForVariationParam { | 758 struct ExpectationForVariationParam { |
1015 std::string param_value; | 759 std::string param_value; |
1016 int expected_value; | 760 int expected_value; |
1017 std::string description; | 761 std::string description; |
1018 }; | 762 }; |
1019 const std::vector<ExpectationForVariationParam> retry_config_expectation = { | 763 const std::vector<ExpectationForVariationParam> retry_config_expectation = { |
1020 {"", 0, "Do not retry by default"}, | 764 {"", 0, "Do not retry by default"}, |
1021 {"0", 0, "Do not retry on param value 0"}, | 765 {"0", 0, "Do not retry on param value 0"}, |
1022 {"-1", 0, "Do not retry on negative param values."}, | 766 {"-1", 0, "Do not retry on negative param values."}, |
1023 {"4", 4, "Retry as set in param value."}}; | 767 {"4", 4, "Retry as set in param value."}}; |
1024 | 768 |
1025 NTPSnippetsFetcher::Params params = test_params(); | 769 NTPSnippetsRequestParams params = test_params(); |
1026 params.interactive_request = false; | 770 params.interactive_request = false; |
1027 | 771 |
1028 for (const auto& retry_config : retry_config_expectation) { | 772 for (const auto& retry_config : retry_config_expectation) { |
1029 DelegateCallingTestURLFetcherFactory fetcher_factory; | 773 DelegateCallingTestURLFetcherFactory fetcher_factory; |
1030 SetVariationParametersForFeatures( | 774 SetVariationParametersForFeatures( |
1031 {{"background_5xx_retries_count", retry_config.param_value}}, | 775 {{"background_5xx_retries_count", retry_config.param_value}}, |
1032 {ntp_snippets::kArticleSuggestionsFeature.name}); | 776 {ntp_snippets::kArticleSuggestionsFeature.name}); |
1033 | 777 |
1034 snippets_fetcher().FetchSnippets( | 778 snippets_fetcher().FetchSnippets( |
1035 params, ToSnippetsAvailableCallback(&mock_callback())); | 779 params, ToSnippetsAvailableCallback(&mock_callback())); |
(...skipping 158 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1194 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) { | 938 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) { |
1195 if (fetched_categories) { | 939 if (fetched_categories) { |
1196 // Matchers above aren't any more precise than this, so this is sufficient | 940 // Matchers above aren't any more precise than this, so this is sufficient |
1197 // for test-failure diagnostics. | 941 // for test-failure diagnostics. |
1198 return os << "list with " << fetched_categories->size() << " elements"; | 942 return os << "list with " << fetched_categories->size() << " elements"; |
1199 } | 943 } |
1200 return os << "null"; | 944 return os << "null"; |
1201 } | 945 } |
1202 | 946 |
1203 } // namespace ntp_snippets | 947 } // namespace ntp_snippets |
OLD | NEW |