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

Side by Side Diff: components/ntp_snippets/remote/ntp_snippets_fetcher_unittest.cc

Issue 2578173002: NTP: Extract JSON requests from Fetcher. (Closed)
Patch Set: Updating comments. Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 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.h" 21 #include "components/ntp_snippets/category.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
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
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
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
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
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 22 matching lines...) Expand all
441 : public NTPSnippetsFetcherTestBase { 408 : public NTPSnippetsFetcherTestBase {
442 public: 409 public:
443 NTPSnippetsContentSuggestionsFetcherTest() 410 NTPSnippetsContentSuggestionsFetcherTest()
444 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) { 411 : NTPSnippetsFetcherTestBase(GURL(kTestChromeContentSuggestionsUrl)) {
445 SetDefaultVariationParam("content_suggestions_backend", 412 SetDefaultVariationParam("content_suggestions_backend",
446 kContentSuggestionsServer); 413 kContentSuggestionsServer);
447 ResetSnippetsFetcher(); 414 ResetSnippetsFetcher();
448 } 415 }
449 }; 416 };
450 417
451 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestAuthenticated) {
452 NTPSnippetsFetcher::RequestBuilder builder;
453 NTPSnippetsFetcher::Params params;
454 params.excluded_ids = {"1234567890"};
455 params.count_to_fetch = 25;
456 params.interactive_request = false;
457 builder.SetParams(params)
458 .SetAuthentication("0BFUSGAIA", "headerstuff")
459 .SetPersonalization(NTPSnippetsFetcher::Personalization::kPersonal)
460 .SetUserClassForTesting("ACTIVE_NTP_USER")
461 .SetFetchAPI(NTPSnippetsFetcher::CHROME_READER_API);
462
463 EXPECT_THAT(builder.PreviewRequestHeadersForTesting(),
464 StrEq("Content-Type: application/json; charset=UTF-8\r\n"
465 "Authorization: headerstuff\r\n"
466 "\r\n"));
467 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
468 EqualsJSON("{"
469 " \"response_detail_level\": \"STANDARD\","
470 " \"obfuscated_gaia_id\": \"0BFUSGAIA\","
471 " \"advanced_options\": {"
472 " \"local_scoring_params\": {"
473 " \"content_params\": {"
474 " \"only_return_personalized_results\": true"
475 " },"
476 " \"content_restricts\": ["
477 " {"
478 " \"type\": \"METADATA\","
479 " \"value\": \"TITLE\""
480 " },"
481 " {"
482 " \"type\": \"METADATA\","
483 " \"value\": \"SNIPPET\""
484 " },"
485 " {"
486 " \"type\": \"METADATA\","
487 " \"value\": \"THUMBNAIL\""
488 " }"
489 " ]"
490 " },"
491 " \"global_scoring_params\": {"
492 " \"num_to_return\": 25,"
493 " \"sort_type\": 1"
494 " }"
495 " }"
496 "}"));
497
498 builder.SetFetchAPI(
499 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
500 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
501 EqualsJSON("{"
502 " \"priority\": \"BACKGROUND_PREFETCH\","
503 " \"excludedSuggestionIds\": ["
504 " \"1234567890\""
505 " ],"
506 " \"userActivenessClass\": \"ACTIVE_NTP_USER\""
507 "}"));
508 }
509
510 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestUnauthenticated) {
511 NTPSnippetsFetcher::RequestBuilder builder;
512 NTPSnippetsFetcher::Params params = test_params();
513 params.count_to_fetch = 10;
514 builder.SetParams(params)
515 .SetUserClassForTesting("ACTIVE_NTP_USER")
516 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal)
517 .SetFetchAPI(NTPSnippetsFetcher::CHROME_READER_API);
518
519 EXPECT_THAT(builder.PreviewRequestHeadersForTesting(),
520 StrEq("Content-Type: application/json; charset=UTF-8\r\n"
521 "\r\n"));
522 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
523 EqualsJSON("{"
524 " \"response_detail_level\": \"STANDARD\","
525 " \"advanced_options\": {"
526 " \"local_scoring_params\": {"
527 " \"content_params\": {"
528 " \"only_return_personalized_results\": false"
529 " },"
530 " \"content_restricts\": ["
531 " {"
532 " \"type\": \"METADATA\","
533 " \"value\": \"TITLE\""
534 " },"
535 " {"
536 " \"type\": \"METADATA\","
537 " \"value\": \"SNIPPET\""
538 " },"
539 " {"
540 " \"type\": \"METADATA\","
541 " \"value\": \"THUMBNAIL\""
542 " }"
543 " ]"
544 " },"
545 " \"global_scoring_params\": {"
546 " \"num_to_return\": 10,"
547 " \"sort_type\": 1"
548 " }"
549 " }"
550 "}"));
551
552 builder.SetFetchAPI(
553 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
554 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
555 EqualsJSON("{"
556 " \"priority\": \"USER_ACTION\","
557 " \"excludedSuggestionIds\": [],"
558 " \"userActivenessClass\": \"ACTIVE_NTP_USER\""
559 "}"));
560 }
561
562 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestExcludedIds) {
563 NTPSnippetsFetcher::RequestBuilder builder;
564 NTPSnippetsFetcher::Params params = test_params();
565 params.interactive_request = false;
566 for (int i = 0; i < 200; ++i) {
567 params.excluded_ids.insert(base::StringPrintf("%03d", i));
568 }
569 builder.SetParams(params)
570 .SetUserClassForTesting("ACTIVE_NTP_USER")
571 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal)
572 .SetFetchAPI(
573 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
574
575 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
576 EqualsJSON("{"
577 " \"priority\": \"BACKGROUND_PREFETCH\","
578 " \"excludedSuggestionIds\": ["
579 " \"000\", \"001\", \"002\", \"003\", \"004\","
580 " \"005\", \"006\", \"007\", \"008\", \"009\","
581 " \"010\", \"011\", \"012\", \"013\", \"014\","
582 " \"015\", \"016\", \"017\", \"018\", \"019\","
583 " \"020\", \"021\", \"022\", \"023\", \"024\","
584 " \"025\", \"026\", \"027\", \"028\", \"029\","
585 " \"030\", \"031\", \"032\", \"033\", \"034\","
586 " \"035\", \"036\", \"037\", \"038\", \"039\","
587 " \"040\", \"041\", \"042\", \"043\", \"044\","
588 " \"045\", \"046\", \"047\", \"048\", \"049\","
589 " \"050\", \"051\", \"052\", \"053\", \"054\","
590 " \"055\", \"056\", \"057\", \"058\", \"059\","
591 " \"060\", \"061\", \"062\", \"063\", \"064\","
592 " \"065\", \"066\", \"067\", \"068\", \"069\","
593 " \"070\", \"071\", \"072\", \"073\", \"074\","
594 " \"075\", \"076\", \"077\", \"078\", \"079\","
595 " \"080\", \"081\", \"082\", \"083\", \"084\","
596 " \"085\", \"086\", \"087\", \"088\", \"089\","
597 " \"090\", \"091\", \"092\", \"093\", \"094\","
598 " \"095\", \"096\", \"097\", \"098\", \"099\""
599 // Truncated to 100 entries. Currently, they happen to
600 // be those lexically first.
601 " ],"
602 " \"userActivenessClass\": \"ACTIVE_NTP_USER\""
603 "}"));
604 }
605
606 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestNoUserClass) {
607 NTPSnippetsFetcher::RequestBuilder builder;
608 NTPSnippetsFetcher::Params params = test_params();
609 params.interactive_request = false;
610 builder.SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal)
611 .SetParams(params)
612 .SetFetchAPI(
613 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
614
615 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
616 EqualsJSON("{"
617 " \"priority\": \"BACKGROUND_PREFETCH\","
618 " \"excludedSuggestionIds\": []"
619 "}"));
620 }
621
622 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestWithTwoLanguages) {
623 NTPSnippetsFetcher::RequestBuilder builder;
624 std::unique_ptr<translate::LanguageModel> language_model =
625 MakeLanguageModel({"de", "en"});
626 NTPSnippetsFetcher::Params params = test_params();
627 params.language_code = "en";
628 builder.SetParams(params)
629 .SetLanguageModel(language_model.get())
630 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal)
631 .SetFetchAPI(
632 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
633
634 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
635 EqualsJSON("{"
636 " \"priority\": \"USER_ACTION\","
637 " \"uiLanguage\": \"en\","
638 " \"excludedSuggestionIds\": [],"
639 " \"topLanguages\": ["
640 " {"
641 " \"language\" : \"en\","
642 " \"frequency\" : 0.5"
643 " },"
644 " {"
645 " \"language\" : \"de\","
646 " \"frequency\" : 0.5"
647 " }"
648 " ]"
649 "}"));
650 }
651
652 TEST_F(ChromeReaderSnippetsFetcherTest, BuildRequestWithUILanguageOnly) {
653 NTPSnippetsFetcher::RequestBuilder builder;
654 std::unique_ptr<translate::LanguageModel> language_model =
655 MakeLanguageModel({"en"});
656 NTPSnippetsFetcher::Params params = test_params();
657 params.language_code = "en";
658 builder.SetParams(params)
659 .SetLanguageModel(language_model.get())
660 .SetPersonalization(NTPSnippetsFetcher::Personalization::kNonPersonal)
661 .SetFetchAPI(
662 NTPSnippetsFetcher::FetchAPI::CHROME_CONTENT_SUGGESTIONS_API);
663
664 EXPECT_THAT(builder.PreviewRequestBodyForTesting(),
665 EqualsJSON("{"
666 " \"priority\": \"USER_ACTION\","
667 " \"uiLanguage\": \"en\","
668 " \"excludedSuggestionIds\": [],"
669 " \"topLanguages\": [{"
670 " \"language\" : \"en\","
671 " \"frequency\" : 1.0"
672 " }]"
673 "}"));
674 }
675
676 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) { 418 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldNotFetchOnCreation) {
677 // The lack of registered baked in responses would cause any fetch to fail. 419 // The lack of registered baked in responses would cause any fetch to fail.
678 FastForwardUntilNoTasksRemain(); 420 FastForwardUntilNoTasksRemain();
679 EXPECT_THAT(histogram_tester().GetAllSamples( 421 EXPECT_THAT(histogram_tester().GetAllSamples(
680 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 422 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
681 IsEmpty()); 423 IsEmpty());
682 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"), 424 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
683 IsEmpty()); 425 IsEmpty());
684 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty()); 426 EXPECT_THAT(snippets_fetcher().last_status(), IsEmpty());
685 } 427 }
(...skipping 247 matching lines...) Expand 10 before | Expand all | Expand 10 after
933 " \"ampUrl\" : \"http://localhost/amp\"," 675 " \"ampUrl\" : \"http://localhost/amp\","
934 " \"faviconUrl\" : \"http://localhost/favicon.ico\" " 676 " \"faviconUrl\" : \"http://localhost/favicon.ico\" "
935 " }]" 677 " }]"
936 "}]}"; 678 "}]}";
937 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 679 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK,
938 net::URLRequestStatus::SUCCESS); 680 net::URLRequestStatus::SUCCESS);
939 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories; 681 NTPSnippetsFetcher::OptionalFetchedCategories fetched_categories;
940 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _)) 682 EXPECT_CALL(mock_callback(), Run(IsSuccess(), _))
941 .WillOnce(MoveArgument1PointeeTo(&fetched_categories)); 683 .WillOnce(MoveArgument1PointeeTo(&fetched_categories));
942 684
943 NTPSnippetsFetcher::Params params = test_params(); 685 NTPSnippetsRequestParams params = test_params();
944 params.exclusive_category = 686 params.exclusive_category =
945 base::Optional<Category>(Category::FromRemoteCategory(2)); 687 base::Optional<Category>(Category::FromRemoteCategory(2));
688
946 snippets_fetcher().FetchSnippets( 689 snippets_fetcher().FetchSnippets(
947 params, ToSnippetsAvailableCallback(&mock_callback())); 690 params, ToSnippetsAvailableCallback(&mock_callback()));
948 FastForwardUntilNoTasksRemain(); 691 FastForwardUntilNoTasksRemain();
949 692
950 ASSERT_TRUE(fetched_categories); 693 ASSERT_TRUE(fetched_categories);
951 ASSERT_THAT(fetched_categories->size(), Eq(1u)); 694 ASSERT_THAT(fetched_categories->size(), Eq(1u));
952 const auto& category = (*fetched_categories)[0]; 695 const auto& category = (*fetched_categories)[0];
953 EXPECT_THAT(category.category.id(), Eq(Category::FromRemoteCategory(2).id())); 696 EXPECT_THAT(category.category.id(), Eq(Category::FromRemoteCategory(2).id()));
954 ASSERT_THAT(category.snippets.size(), Eq(1u)); 697 ASSERT_THAT(category.snippets.size(), Eq(1u));
955 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2")); 698 EXPECT_THAT(category.snippets[0]->url().spec(), Eq("http://localhost/foo2"));
956 } 699 }
957 700
701 // TODO(fhorschig): Check for behavioral changes instead of state.
958 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) { 702 TEST_F(ChromeReaderSnippetsFetcherTest, PersonalizesDependingOnVariations) {
959 // Default setting should be both personalization options. 703 // Default setting should be both personalization options.
960 EXPECT_THAT(snippets_fetcher().personalization(), 704 EXPECT_THAT(snippets_fetcher().personalization(), Eq(Personalization::kBoth));
961 Eq(NTPSnippetsFetcher::Personalization::kBoth));
962 705
963 SetVariationParam("fetching_personalization", "personal"); 706 SetVariationParam("fetching_personalization", "personal");
964 ResetSnippetsFetcher(); 707 ResetSnippetsFetcher();
965 EXPECT_THAT(snippets_fetcher().personalization(), 708 EXPECT_THAT(snippets_fetcher().personalization(),
966 Eq(NTPSnippetsFetcher::Personalization::kPersonal)); 709 Eq(Personalization::kPersonal));
967 710
968 SetVariationParam("fetching_personalization", "non_personal"); 711 SetVariationParam("fetching_personalization", "non_personal");
969 ResetSnippetsFetcher(); 712 ResetSnippetsFetcher();
970 EXPECT_THAT(snippets_fetcher().personalization(), 713 EXPECT_THAT(snippets_fetcher().personalization(),
971 Eq(NTPSnippetsFetcher::Personalization::kNonPersonal)); 714 Eq(Personalization::kNonPersonal));
972 715
973 SetVariationParam("fetching_personalization", "both"); 716 SetVariationParam("fetching_personalization", "both");
974 ResetSnippetsFetcher(); 717 ResetSnippetsFetcher();
975 EXPECT_THAT(snippets_fetcher().personalization(), 718 EXPECT_THAT(snippets_fetcher().personalization(), Eq(Personalization::kBoth));
976 Eq(NTPSnippetsFetcher::Personalization::kBoth));
977 } 719 }
978 720
979 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) { 721 TEST_F(ChromeReaderSnippetsFetcherTest, ShouldFetchSuccessfullyEmptyList) {
980 const std::string kJsonStr = "{\"recos\": []}"; 722 const std::string kJsonStr = "{\"recos\": []}";
981 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK, 723 SetFakeResponse(/*response_data=*/kJsonStr, net::HTTP_OK,
982 net::URLRequestStatus::SUCCESS); 724 net::URLRequestStatus::SUCCESS);
983 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList())); 725 EXPECT_CALL(mock_callback(), Run(IsSuccess(), IsEmptyArticleList()));
984 snippets_fetcher().FetchSnippets( 726 snippets_fetcher().FetchSnippets(
985 test_params(), ToSnippetsAvailableCallback(&mock_callback())); 727 test_params(), ToSnippetsAvailableCallback(&mock_callback()));
986 FastForwardUntilNoTasksRemain(); 728 FastForwardUntilNoTasksRemain();
987 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 729 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
988 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 730 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
989 EXPECT_THAT( 731 EXPECT_THAT(
990 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 732 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
991 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); 733 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
992 EXPECT_THAT(histogram_tester().GetAllSamples( 734 EXPECT_THAT(histogram_tester().GetAllSamples(
993 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 735 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
994 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 736 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
995 } 737 }
996 738
997 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) { 739 TEST_F(ChromeReaderSnippetsFetcherTest, RetryOnInteractiveRequests) {
998 DelegateCallingTestURLFetcherFactory fetcher_factory; 740 DelegateCallingTestURLFetcherFactory fetcher_factory;
999 NTPSnippetsFetcher::Params params = test_params(); 741 NTPSnippetsRequestParams params = test_params();
1000 params.interactive_request = true; 742 params.interactive_request = true;
1001 743
1002 snippets_fetcher().FetchSnippets( 744 snippets_fetcher().FetchSnippets(
1003 params, ToSnippetsAvailableCallback(&mock_callback())); 745 params, ToSnippetsAvailableCallback(&mock_callback()));
1004 746
1005 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher(); 747 net::TestURLFetcher* fetcher = fetcher_factory.GetLastCreatedFetcher();
1006 ASSERT_THAT(fetcher, NotNull()); 748 ASSERT_THAT(fetcher, NotNull());
1007 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2)); 749 EXPECT_THAT(fetcher->GetMaxRetriesOn5xx(), Eq(2));
1008 } 750 }
1009 751
1010 TEST_F(ChromeReaderSnippetsFetcherTest, 752 TEST_F(ChromeReaderSnippetsFetcherTest,
1011 RetriesConfigurableOnNonInteractiveRequests) { 753 RetriesConfigurableOnNonInteractiveRequests) {
1012 struct ExpectationForVariationParam { 754 struct ExpectationForVariationParam {
1013 std::string param_value; 755 std::string param_value;
1014 int expected_value; 756 int expected_value;
1015 std::string description; 757 std::string description;
1016 }; 758 };
1017 const std::vector<ExpectationForVariationParam> retry_config_expectation = { 759 const std::vector<ExpectationForVariationParam> retry_config_expectation = {
1018 {"", 0, "Do not retry by default"}, 760 {"", 0, "Do not retry by default"},
1019 {"0", 0, "Do not retry on param value 0"}, 761 {"0", 0, "Do not retry on param value 0"},
1020 {"-1", 0, "Do not retry on negative param values."}, 762 {"-1", 0, "Do not retry on negative param values."},
1021 {"4", 4, "Retry as set in param value."}}; 763 {"4", 4, "Retry as set in param value."}};
1022 764
1023 NTPSnippetsFetcher::Params params = test_params(); 765 NTPSnippetsRequestParams params = test_params();
1024 params.interactive_request = false; 766 params.interactive_request = false;
1025 767
1026 for (const auto& retry_config : retry_config_expectation) { 768 for (const auto& retry_config : retry_config_expectation) {
1027 DelegateCallingTestURLFetcherFactory fetcher_factory; 769 DelegateCallingTestURLFetcherFactory fetcher_factory;
1028 SetVariationParametersForFeatures( 770 SetVariationParametersForFeatures(
1029 {{"background_5xx_retries_count", retry_config.param_value}}, 771 {{"background_5xx_retries_count", retry_config.param_value}},
1030 {ntp_snippets::kArticleSuggestionsFeature.name}); 772 {ntp_snippets::kArticleSuggestionsFeature.name});
1031 773
1032 snippets_fetcher().FetchSnippets( 774 snippets_fetcher().FetchSnippets(
1033 params, ToSnippetsAvailableCallback(&mock_callback())); 775 params, ToSnippetsAvailableCallback(&mock_callback()));
(...skipping 158 matching lines...) Expand 10 before | Expand all | Expand 10 after
1192 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) { 934 const NTPSnippetsFetcher::OptionalFetchedCategories& fetched_categories) {
1193 if (fetched_categories) { 935 if (fetched_categories) {
1194 // Matchers above aren't any more precise than this, so this is sufficient 936 // Matchers above aren't any more precise than this, so this is sufficient
1195 // for test-failure diagnostics. 937 // for test-failure diagnostics.
1196 return os << "list with " << fetched_categories->size() << " elements"; 938 return os << "list with " << fetched_categories->size() << " elements";
1197 } 939 }
1198 return os << "null"; 940 return os << "null";
1199 } 941 }
1200 942
1201 } // namespace ntp_snippets 943 } // namespace ntp_snippets
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698