| 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 84 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 254 public: | 237 public: |
| 255 std::unique_ptr<net::URLFetcher> CreateURLFetcher( | 238 std::unique_ptr<net::URLFetcher> CreateURLFetcher( |
| 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(const std::string& json, |
| 265 const std::string& json, | 248 const SuccessCallback& success_callback, |
| 266 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, | 249 const ErrorCallback& error_callback) { |
| 267 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { | |
| 268 base::JSONReader json_reader; | 250 base::JSONReader json_reader; |
| 269 std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); | 251 std::unique_ptr<base::Value> value = json_reader.ReadToValue(json); |
| 270 if (value) { | 252 if (value) { |
| 271 success_callback.Run(std::move(value)); | 253 success_callback.Run(std::move(value)); |
| 272 } else { | 254 } else { |
| 273 error_callback.Run(json_reader.GetErrorMessage()); | 255 error_callback.Run(json_reader.GetErrorMessage()); |
| 274 } | 256 } |
| 275 } | 257 } |
| 276 | 258 |
| 277 void ParseJsonDelayed( | 259 void ParseJsonDelayed(const std::string& json, |
| 278 const std::string& json, | 260 const SuccessCallback& success_callback, |
| 279 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, | 261 const ErrorCallback& error_callback) { |
| 280 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { | |
| 281 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( | 262 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( |
| 282 FROM_HERE, base::Bind(&ParseJson, json, std::move(success_callback), | 263 FROM_HERE, base::Bind(&ParseJson, json, std::move(success_callback), |
| 283 std::move(error_callback)), | 264 std::move(error_callback)), |
| 284 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); | 265 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); |
| 285 } | 266 } |
| 286 | 267 |
| 287 } // namespace | 268 } // namespace |
| 288 | 269 |
| 289 class NTPSnippetsFetcherTestBase : public testing::Test { | 270 class NTPSnippetsFetcherTestBase : public testing::Test { |
| 290 public: | 271 public: |
| (...skipping 11 matching lines...) Expand all Loading... |
| 302 signin_client_(base::MakeUnique<TestSigninClient>(nullptr)), | 283 signin_client_(base::MakeUnique<TestSigninClient>(nullptr)), |
| 303 account_tracker_(base::MakeUnique<AccountTrackerService>()), | 284 account_tracker_(base::MakeUnique<AccountTrackerService>()), |
| 304 fake_signin_manager_( | 285 fake_signin_manager_( |
| 305 base::MakeUnique<FakeSigninManagerBase>(signin_client_.get(), | 286 base::MakeUnique<FakeSigninManagerBase>(signin_client_.get(), |
| 306 account_tracker_.get())), | 287 account_tracker_.get())), |
| 307 fake_token_service_(base::MakeUnique<FakeProfileOAuth2TokenService>()), | 288 fake_token_service_(base::MakeUnique<FakeProfileOAuth2TokenService>()), |
| 308 pref_service_(base::MakeUnique<TestingPrefServiceSimple>()), | 289 pref_service_(base::MakeUnique<TestingPrefServiceSimple>()), |
| 309 test_url_(gurl) { | 290 test_url_(gurl) { |
| 310 RequestThrottler::RegisterProfilePrefs(pref_service_->registry()); | 291 RequestThrottler::RegisterProfilePrefs(pref_service_->registry()); |
| 311 UserClassifier::RegisterProfilePrefs(pref_service_->registry()); | 292 UserClassifier::RegisterProfilePrefs(pref_service_->registry()); |
| 312 translate::LanguageModel::RegisterProfilePrefs(pref_service()->registry()); | |
| 313 user_classifier_ = base::MakeUnique<UserClassifier>(pref_service_.get()); | 293 user_classifier_ = base::MakeUnique<UserClassifier>(pref_service_.get()); |
| 314 // Increase initial time such that ticks are non-zero. | 294 // Increase initial time such that ticks are non-zero. |
| 315 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234)); | 295 mock_task_runner_->FastForwardBy(base::TimeDelta::FromMilliseconds(1234)); |
| 316 ResetSnippetsFetcher(); | 296 ResetSnippetsFetcher(); |
| 317 } | 297 } |
| 318 | 298 |
| 319 void ResetSnippetsFetcher() { | 299 void ResetSnippetsFetcher() { |
| 320 snippets_fetcher_ = base::MakeUnique<NTPSnippetsFetcher>( | 300 snippets_fetcher_ = base::MakeUnique<NTPSnippetsFetcher>( |
| 321 fake_signin_manager_.get(), fake_token_service_.get(), | 301 fake_signin_manager_.get(), fake_token_service_.get(), |
| 322 scoped_refptr<net::TestURLRequestContextGetter>( | 302 scoped_refptr<net::TestURLRequestContextGetter>( |
| (...skipping 11 matching lines...) Expand all Loading... |
| 334 base::Unretained(callback)); | 314 base::Unretained(callback)); |
| 335 } | 315 } |
| 336 | 316 |
| 337 NTPSnippetsFetcher& snippets_fetcher() { return *snippets_fetcher_; } | 317 NTPSnippetsFetcher& snippets_fetcher() { return *snippets_fetcher_; } |
| 338 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; } | 318 MockSnippetsAvailableCallback& mock_callback() { return mock_callback_; } |
| 339 void FastForwardUntilNoTasksRemain() { | 319 void FastForwardUntilNoTasksRemain() { |
| 340 mock_task_runner_->FastForwardUntilNoTasksRemain(); | 320 mock_task_runner_->FastForwardUntilNoTasksRemain(); |
| 341 } | 321 } |
| 342 base::HistogramTester& histogram_tester() { return histogram_tester_; } | 322 base::HistogramTester& histogram_tester() { return histogram_tester_; } |
| 343 | 323 |
| 344 NTPSnippetsFetcher::Params test_params() { | 324 NTPSnippetsRequestParams test_params() { |
| 345 NTPSnippetsFetcher::Params result; | 325 NTPSnippetsRequestParams result; |
| 346 result.count_to_fetch = 1; | 326 result.count_to_fetch = 1; |
| 347 result.interactive_request = true; | 327 result.interactive_request = true; |
| 348 return result; | 328 return result; |
| 349 } | 329 } |
| 350 | 330 |
| 351 void InitFakeURLFetcherFactory() { | 331 void InitFakeURLFetcherFactory() { |
| 352 if (fake_url_fetcher_factory_) { | 332 if (fake_url_fetcher_factory_) { |
| 353 return; | 333 return; |
| 354 } | 334 } |
| 355 // Instantiation of factory automatically sets itself as URLFetcher's | 335 // Instantiation of factory automatically sets itself as URLFetcher's |
| (...skipping 30 matching lines...) Expand all Loading... |
| 386 } | 366 } |
| 387 | 367 |
| 388 void SetFakeResponse(const std::string& response_data, | 368 void SetFakeResponse(const std::string& response_data, |
| 389 net::HttpStatusCode response_code, | 369 net::HttpStatusCode response_code, |
| 390 net::URLRequestStatus::Status status) { | 370 net::URLRequestStatus::Status status) { |
| 391 InitFakeURLFetcherFactory(); | 371 InitFakeURLFetcherFactory(); |
| 392 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, | 372 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, |
| 393 response_code, status); | 373 response_code, status); |
| 394 } | 374 } |
| 395 | 375 |
| 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(); } | 376 TestingPrefServiceSimple* pref_service() const { return pref_service_.get(); } |
| 410 | 377 |
| 411 private: | 378 private: |
| 412 std::map<std::string, std::string> default_variation_params_; | 379 std::map<std::string, std::string> default_variation_params_; |
| 413 // TODO(fhorschig): Make it a simple member when crbug.com/672010 is resolved. | 380 // TODO(fhorschig): Make it a simple member when crbug.com/672010 is resolved. |
| 414 std::unique_ptr<variations::testing::VariationParamsManager> params_manager_; | 381 std::unique_ptr<variations::testing::VariationParamsManager> params_manager_; |
| 415 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; | 382 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; |
| 416 base::ThreadTaskRunnerHandle mock_task_runner_handle_; | 383 base::ThreadTaskRunnerHandle mock_task_runner_handle_; |
| 417 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; | 384 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; |
| 418 // Initialized lazily in SetFakeResponse(). | 385 // Initialized lazily in SetFakeResponse(). |
| (...skipping 23 matching lines...) Expand all Loading... |
| 442 : public NTPSnippetsFetcherTestBase { | 409 : public NTPSnippetsFetcherTestBase { |
| 443 public: | 410 public: |
| 444 NTPSnippetsContentSuggestionsFetcherTest() | 411 NTPSnippetsContentSuggestionsFetcherTest() |
| 445 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) { | 412 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) { |
| 446 SetDefaultVariationParam("content_suggestions_backend", | 413 SetDefaultVariationParam("content_suggestions_backend", |
| 447 kContentSuggestionsServer); | 414 kContentSuggestionsServer); |
| 448 ResetSnippetsFetcher(); | 415 ResetSnippetsFetcher(); |
| 449 } | 416 } |
| 450 }; | 417 }; |
| 451 | 418 |
| 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) { | 419 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) { |
| 678 // The lack of registered baked in responses would cause any fetch to fail. | 420 // The lack of registered baked in responses would cause any fetch to fail. |
| 679 FastForwardUntilNoTasksRemain(); | 421 FastForwardUntilNoTasksRemain(); |
| 680 EXPECT_THAT(histogram_tester().GetAllSamples( | 422 EXPECT_THAT(histogram_tester().GetAllSamples( |
| 681 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), | 423 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), |
| 682 IsEmpty()); | 424 IsEmpty()); |
| 683 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), | 425 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), |
| 684 IsEmpty()); | 426 IsEmpty()); |
| 685 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); | 427 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); |
| 686 } | 428 } |
| (...skipping 247 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 934 " \"ampUrl\" : \"http://localhost/amp\"," | 676 " \"ampUrl\" : \"http://localhost/amp\"," |
| 935 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " | 677 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " |
| 936 " }]" | 678 " }]" |
| 937 "}]}"; | 679 "}]}"; |
| 938 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, | 680 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, |
| 939 net::URLRequestStatus::SUCCESS); | 681 net::URLRequestStatus::SUCCESS); |
| 940 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories; | 682 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories; |
| 941 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) | 683 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) |
| 942 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); | 684 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); |
| 943 | 685 |
| 944 NTPSnippetsFetcher::Params params = test_params(); | 686 NTPSnippetsRequestParams params = test_params(); |
| 945 params.exclusive_category = base::Optional<Category>( | 687 params.exclusive_category = base::Optional<Category>( |
| 946 CategoryFactory().FromRemoteCategory(2)); | 688 CategoryFactory().FromRemoteCategory(2)); |
| 947 snippets_fetcher().FetchSnippets( | 689 snippets_fetcher().FetchSnippets( |
| 948 params, ToSnippetsAvailableCallback(&mock_callback())); | 690 params, ToSnippetsAvailableCallback(&mock_callback())); |
| 949 FastForwardUntilNoTasksRemain(); | 691 FastForwardUntilNoTasksRemain(); |
| 950 | 692 |
| 951 ASSERT_TRUE(fetched_categories); | 693 ASSERT_TRUE(fetched_categories); |
| 952 ASSERT_THAT(fetched_categories->size(), Eq(1u)); | 694 ASSERT_THAT(fetched_categories->size(), Eq(1u)); |
| 953 const auto& category = (*fetched_categories)[0]; | 695 const auto& category = (*fetched_categories)[0]; |
| 954 EXPECT_THAT(category.category.id(), | 696 EXPECT_THAT(category.category.id(), |
| 955 Eq(CategoryFactory().FromRemoteCategory(2).id())); | 697 Eq(CategoryFactory().FromRemoteCategory(2).id())); |
| 956 ASSERT_THAT(category.snippets.size(), Eq(1u)); | 698 ASSERT_THAT(category.snippets.size(), Eq(1u)); |
| 957 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2")); | 699 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2")); |
| 958 } | 700 } |
| 959 | 701 |
| 702 // TODO(fhorschig): Check for behavioral changes instead of state. |
| 960 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) { | 703 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) { |
| 961 // Default setting should be both personalization options. | 704 // Default setting should be both personalization options. |
| 962 EXPECT_THAT(snippets_fetcher().personalization(), | 705 EXPECT_THAT(snippets_fetcher().personalization(), Eq(Personalization::kBoth)); |
| 963 Eq(NTPSnippetsFetcher::Personalization::kBoth)); | |
| 964 | 706 |
| 965 SetVariationParam("fetching_personalization", "personal"); | 707 SetVariationParam("fetching_personalization", "personal"); |
| 966 ResetSnippetsFetcher(); | 708 ResetSnippetsFetcher(); |
| 967 EXPECT_THAT(snippets_fetcher().personalization(), | 709 EXPECT_THAT(snippets_fetcher().personalization(), |
| 968 Eq(NTPSnippetsFetcher::Personalization::kPersonal)); | 710 Eq(Personalization::kPersonal)); |
| 969 | 711 |
| 970 SetVariationParam("fetching_personalization", "non_personal"); | 712 SetVariationParam("fetching_personalization", "non_personal"); |
| 971 ResetSnippetsFetcher(); | 713 ResetSnippetsFetcher(); |
| 972 EXPECT_THAT(snippets_fetcher().personalization(), | 714 EXPECT_THAT(snippets_fetcher().personalization(), |
| 973 Eq(NTPSnippetsFetcher::Personalization::kNonPersonal)); | 715 Eq(Personalization::kNonPersonal)); |
| 974 | 716 |
| 975 SetVariationParam("fetching_personalization", "both"); | 717 SetVariationParam("fetching_personalization", "both"); |
| 976 ResetSnippetsFetcher(); | 718 ResetSnippetsFetcher(); |
| 977 EXPECT_THAT(snippets_fetcher().personalization(), | 719 EXPECT_THAT(snippets_fetcher().personalization(), Eq(Personalization::kBoth)); |
| 978 Eq(NTPSnippetsFetcher::Personalization::kBoth)); | |
| 979 } | 720 } |
| 980 | 721 |
| 981 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { | 722 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { |
| 982 const std::string kJsonStr = "{\"recos\": []}"; | 723 const std::string kJsonStr = "{\"recos\": []}"; |
| 983 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, | 724 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, |
| 984 net::URLRequestStatus::SUCCESS); | 725 net::URLRequestStatus::SUCCESS); |
| 985 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); | 726 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); |
| 986 snippets_fetcher().FetchSnippets( | 727 snippets_fetcher().FetchSnippets( |
| 987 test_params(), ToSnippetsAvailableCallback(&mock_callback())); | 728 test_params(), ToSnippetsAvailableCallback(&mock_callback())); |
| 988 FastForwardUntilNoTasksRemain(); | 729 FastForwardUntilNoTasksRemain(); |
| 989 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); | 730 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); |
| 990 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); | 731 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); |
| 991 EXPECT_THAT( | 732 EXPECT_THAT( |
| 992 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), | 733 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), |
| 993 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); | 734 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); |
| 994 EXPECT_THAT(histogram_tester().GetAllSamples( | 735 EXPECT_THAT(histogram_tester().GetAllSamples( |
| 995 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), | 736 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), |
| 996 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); | 737 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); |
| 997 } | 738 } |
| 998 | 739 |
| 999 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) { | 740 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) { |
| 1000 DelegateCallingTestURLFetcherFactory fetcher_factory; | 741 DelegateCallingTestURLFetcherFactory fetcher_factory; |
| 1001 NTPSnippetsFetcher::Params params = test_params(); | 742 NTPSnippetsRequestParams params = test_params(); |
| 1002 params.interactive_request = true; | 743 params.interactive_request = true; |
| 1003 | 744 |
| 1004 snippets_fetcher().FetchSnippets( | 745 snippets_fetcher().FetchSnippets( |
| 1005 params, ToSnippetsAvailableCallback(&mock_callback())); | 746 params, ToSnippetsAvailableCallback(&mock_callback())); |
| 1006 | 747 |
| 1007 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); | 748 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); |
| 1008 ASSERT_THAT(fetcher, NotNull()); | 749 ASSERT_THAT(fetcher, NotNull()); |
| 1009 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2)); | 750 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2)); |
| 1010 } | 751 } |
| 1011 | 752 |
| 1012 TEST_F(ChromeReaderSnippetsFetcherTest, | 753 TEST_F(ChromeReaderSnippetsFetcherTest, |
| 1013 RetriesConfigurableOnNonInteractiveRequests) { | 754 RetriesConfigurableOnNonInteractiveRequests) { |
| 1014 struct ExpectationForVariationParam { | 755 struct ExpectationForVariationParam { |
| 1015 std::string param_value; | 756 std::string param_value; |
| 1016 int expected_value; | 757 int expected_value; |
| 1017 std::string description; | 758 std::string description; |
| 1018 }; | 759 }; |
| 1019 const std::vector<ExpectationForVariationParam> retry_config_expectation = { | 760 const std::vector<ExpectationForVariationParam> retry_config_expectation = { |
| 1020 {"", 0, "Do not retry by default"}, | 761 {"", 0, "Do not retry by default"}, |
| 1021 {"0", 0, "Do not retry on param value 0"}, | 762 {"0", 0, "Do not retry on param value 0"}, |
| 1022 {"-1", 0, "Do not retry on negative param values."}, | 763 {"-1", 0, "Do not retry on negative param values."}, |
| 1023 {"4", 4, "Retry as set in param value."}}; | 764 {"4", 4, "Retry as set in param value."}}; |
| 1024 | 765 |
| 1025 NTPSnippetsFetcher::Params params = test_params(); | 766 NTPSnippetsRequestParams params = test_params(); |
| 1026 params.interactive_request = false; | 767 params.interactive_request = false; |
| 1027 | 768 |
| 1028 for (const auto& retry_config : retry_config_expectation) { | 769 for (const auto& retry_config : retry_config_expectation) { |
| 1029 DelegateCallingTestURLFetcherFactory fetcher_factory; | 770 DelegateCallingTestURLFetcherFactory fetcher_factory; |
| 1030 SetVariationParametersForFeatures( | 771 SetVariationParametersForFeatures( |
| 1031 {{"background_5xx_retries_count", retry_config.param_value}}, | 772 {{"background_5xx_retries_count", retry_config.param_value}}, |
| 1032 {ntp_snippets::kArticleSuggestionsFeature.name}); | 773 {ntp_snippets::kArticleSuggestionsFeature.name}); |
| 1033 | 774 |
| 1034 snippets_fetcher().FetchSnippets( | 775 snippets_fetcher().FetchSnippets( |
| 1035 params, ToSnippetsAvailableCallback(&mock_callback())); | 776 params, ToSnippetsAvailableCallback(&mock_callback())); |
| (...skipping 158 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 1194 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) { | 935 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) { |
| 1195 if (fetched_categories) { | 936 if (fetched_categories) { |
| 1196 // Matchers above aren't any more precise than this, so this is sufficient | 937 // Matchers above aren't any more precise than this, so this is sufficient |
| 1197 // for test-failure diagnostics. | 938 // for test-failure diagnostics. |
| 1198 return os << "list with " << fetched_categories->size() << " elements"; | 939 return os << "list with " << fetched_categories->size() << " elements"; |
| 1199 } | 940 } |
| 1200 return os << "null"; | 941 return os << "null"; |
| 1201 } | 942 } |
| 1202 | 943 |
| 1203 } // namespace ntp_snippets | 944 } // namespace ntp_snippets |
| OLD | NEW |