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

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

Issue 2146863002: More unittests of ntp_snippets_fetcher that depend on trial param value. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@finch-parameters-test
Patch Set: Rebase Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 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/ntp_snippets_fetcher.h" 5 #include "components/ntp_snippets/ntp_snippets_fetcher.h"
6 6
7 #include "base/json/json_reader.h" 7 #include "base/json/json_reader.h"
8 #include "base/memory/ptr_util.h" 8 #include "base/memory/ptr_util.h"
9 #include "base/strings/stringprintf.h" 9 #include "base/strings/stringprintf.h"
10 #include "base/test/histogram_tester.h" 10 #include "base/test/histogram_tester.h"
(...skipping 105 matching lines...) Expand 10 before | Expand all | Expand 10 after
116 116
117 void ParseJsonDelayed( 117 void ParseJsonDelayed(
118 const std::string& json, 118 const std::string& json,
119 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback, 119 const ntp_snippets::NTPSnippetsFetcher::SuccessCallback& success_callback,
120 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) { 120 const ntp_snippets::NTPSnippetsFetcher::ErrorCallback& error_callback) {
121 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( 121 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
122 FROM_HERE, base::Bind(&ParseJson, json, success_callback, error_callback), 122 FROM_HERE, base::Bind(&ParseJson, json, success_callback, error_callback),
123 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs)); 123 base::TimeDelta::FromMilliseconds(kTestJsonParsingLatencyMs));
124 } 124 }
125 125
126 class VariationParams { 126 GURL GetFetcherUrl(const char* url_format) {
127 public: 127 return GURL(base::StringPrintf(url_format, google_apis::GetAPIKey().c_str()));
128 VariationParams(const std::string& trial_name, 128 }
129 const std::map<std::string, std::string>& params)
130 : field_trial_list_(new metrics::SHA1EntropyProvider("foo")) {
131 variations::AssociateVariationParams(trial_name, "Group1", params);
132 base::FieldTrialList::CreateFieldTrial(trial_name, "Group1");
133 }
134
135 ~VariationParams() { variations::testing::ClearAllVariationParams(); }
136
137 private:
138 base::FieldTrialList field_trial_list_;
139 };
140 129
141 } // namespace 130 } // namespace
142 131
143 class NTPSnippetsFetcherTest : public testing::Test { 132 class NTPSnippetsFetcherTest : public testing::Test {
144 public: 133 public:
145 NTPSnippetsFetcherTest() 134 NTPSnippetsFetcherTest()
146 : NTPSnippetsFetcherTest( 135 : NTPSnippetsFetcherTest(
147 GURL(base::StringPrintf(kTestChromeReaderUrlFormat, 136 GetFetcherUrl(kTestChromeReaderUrlFormat),
148 google_apis::GetAPIKey().c_str())),
149 std::map<std::string, std::string>()) {} 137 std::map<std::string, std::string>()) {}
150 138
151 NTPSnippetsFetcherTest(const GURL& gurl, 139 NTPSnippetsFetcherTest(const GURL& gurl,
152 const std::map<std::string, std::string>& params) 140 const std::map<std::string, std::string>& params)
153 : params_(ntp_snippets::kStudyName, params), 141 : params_manager_(ntp_snippets::kStudyName, params),
154 mock_task_runner_(new base::TestMockTimeTaskRunner()), 142 mock_task_runner_(new base::TestMockTimeTaskRunner()),
155 mock_task_runner_handle_(mock_task_runner_), 143 mock_task_runner_handle_(mock_task_runner_),
156 signin_client_(new TestSigninClient(nullptr)), 144 signin_client_(new TestSigninClient(nullptr)),
157 account_tracker_(new AccountTrackerService()), 145 account_tracker_(new AccountTrackerService()),
158 fake_signin_manager_(new FakeSigninManagerBase(signin_client_.get(), 146 fake_signin_manager_(new FakeSigninManagerBase(signin_client_.get(),
159 account_tracker_.get())), 147 account_tracker_.get())),
160 fake_token_service_(new FakeProfileOAuth2TokenService()), 148 fake_token_service_(new FakeProfileOAuth2TokenService()),
161 snippets_fetcher_( 149 snippets_fetcher_(
162 fake_signin_manager_.get(), 150 fake_signin_manager_.get(),
163 fake_token_service_.get(), 151 fake_token_service_.get(),
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
198 186
199 void SetFakeResponse(const std::string& response_data, 187 void SetFakeResponse(const std::string& response_data,
200 net::HttpStatusCode response_code, 188 net::HttpStatusCode response_code,
201 net::URLRequestStatus::Status status) { 189 net::URLRequestStatus::Status status) {
202 InitFakeURLFetcherFactory(); 190 InitFakeURLFetcherFactory();
203 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data, 191 fake_url_fetcher_factory_->SetFakeResponse(test_url_, response_data,
204 response_code, status); 192 response_code, status);
205 } 193 }
206 194
207 private: 195 private:
208 VariationParams params_; 196 variations::testing::VariationParamsManager params_manager_;
209 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_; 197 scoped_refptr<base::TestMockTimeTaskRunner> mock_task_runner_;
210 base::ThreadTaskRunnerHandle mock_task_runner_handle_; 198 base::ThreadTaskRunnerHandle mock_task_runner_handle_;
211 FailingFakeURLFetcherFactory failing_url_fetcher_factory_; 199 FailingFakeURLFetcherFactory failing_url_fetcher_factory_;
212 // Initialized lazily in SetFakeResponse(). 200 // Initialized lazily in SetFakeResponse().
213 std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_; 201 std::unique_ptr<net::FakeURLFetcherFactory> fake_url_fetcher_factory_;
214 std::unique_ptr<TestSigninClient> signin_client_; 202 std::unique_ptr<TestSigninClient> signin_client_;
215 std::unique_ptr<AccountTrackerService> account_tracker_; 203 std::unique_ptr<AccountTrackerService> account_tracker_;
216 std::unique_ptr<SigninManagerBase> fake_signin_manager_; 204 std::unique_ptr<SigninManagerBase> fake_signin_manager_;
217 std::unique_ptr<OAuth2TokenService> fake_token_service_; 205 std::unique_ptr<OAuth2TokenService> fake_token_service_;
218 NTPSnippetsFetcher snippets_fetcher_; 206 NTPSnippetsFetcher snippets_fetcher_;
219 MockSnippetsAvailableCallback mock_callback_; 207 MockSnippetsAvailableCallback mock_callback_;
220 const std::string test_lang_; 208 const std::string test_lang_;
221 const GURL test_url_; 209 const GURL test_url_;
222 std::set<std::string> test_hosts_; 210 std::set<std::string> test_hosts_;
223 base::HistogramTester histogram_tester_; 211 base::HistogramTester histogram_tester_;
224 212
225 DISALLOW_COPY_AND_ASSIGN(NTPSnippetsFetcherTest); 213 DISALLOW_COPY_AND_ASSIGN(NTPSnippetsFetcherTest);
226 }; 214 };
227 215
228 class NTPSnippetsContentSuggestionsFetcherTest : public NTPSnippetsFetcherTest { 216 class NTPSnippetsContentSuggestionsFetcherTest : public NTPSnippetsFetcherTest {
229 public: 217 public:
230 NTPSnippetsContentSuggestionsFetcherTest() 218 NTPSnippetsContentSuggestionsFetcherTest()
231 : NTPSnippetsFetcherTest( 219 : NTPSnippetsFetcherTest(
232 GURL(base::StringPrintf(kTestChromeContentSuggestionsUrlFormat, 220 GetFetcherUrl(kTestChromeContentSuggestionsUrlFormat),
233 google_apis::GetAPIKey().c_str())),
234 std::map<std::string, std::string>{ 221 std::map<std::string, std::string>{
235 {"content_suggestions_backend", kContentSuggestionsBackend}}) {} 222 {"content_suggestions_backend", kContentSuggestionsBackend}}) {}
236 }; 223 };
237 224
225 class NTPSnippetsFetcherHostRestrictedTest : public NTPSnippetsFetcherTest {
226 public:
227 NTPSnippetsFetcherHostRestrictedTest()
228 : NTPSnippetsFetcherTest(
229 GetFetcherUrl(kTestChromeReaderUrlFormat),
230 std::map<std::string, std::string>{
231 {"fetching_host_restrict", "on"}}) {}
Marc Treib 2016/07/20 08:34:45 Out of curiosity: Is the "std::map<...>" required
jkrcal 2016/07/20 12:17:31 You are right, not needed. Thanks!
232 };
233
238 TEST_F(NTPSnippetsFetcherTest, BuildRequestAuthenticated) { 234 TEST_F(NTPSnippetsFetcherTest, BuildRequestAuthenticated) {
239 NTPSnippetsFetcher::RequestParams params; 235 NTPSnippetsFetcher::RequestParams params;
240 params.obfuscated_gaia_id = "0BFUSGAIA"; 236 params.obfuscated_gaia_id = "0BFUSGAIA";
241 params.only_return_personalized_results = true; 237 params.only_return_personalized_results = true;
242 params.user_locale = "en"; 238 params.user_locale = "en";
243 params.host_restricts = {"chromium.org"}; 239 params.host_restricts = {"chromium.org"};
244 params.count_to_fetch = 25; 240 params.count_to_fetch = 25;
245 241
246 params.fetch_api = NTPSnippetsFetcher::CHROME_READER_API; 242 params.fetch_api = NTPSnippetsFetcher::CHROME_READER_API;
247 EXPECT_THAT(params.BuildRequest(), 243 EXPECT_THAT(params.BuildRequest(),
(...skipping 169 matching lines...) Expand 10 before | Expand all | Expand 10 after
417 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK")); 413 EXPECT_THAT(snippets_fetcher().last_status(), Eq("OK"));
418 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr)); 414 EXPECT_THAT(snippets_fetcher().last_json(), Eq(kJsonStr));
419 EXPECT_THAT( 415 EXPECT_THAT(
420 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"), 416 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
421 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1))); 417 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
422 EXPECT_THAT(histogram_tester().GetAllSamples( 418 EXPECT_THAT(histogram_tester().GetAllSamples(
423 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"), 419 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
424 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1))); 420 ElementsAre(base::Bucket(/*min=*/200, /*count=*/1)));
425 } 421 }
426 422
427 // TODO(jkrcal) Return the tests ShouldReportEmptyHostsError and 423 TEST_F(NTPSnippetsFetcherHostRestrictedTest, ShouldReportEmptyHostsError) {
428 // ShouldRestrictToHosts once we have a way to change variation parameters from 424 EXPECT_CALL(mock_callback(), Run(/*snippets=*/Not(HasValue()))).Times(1);
429 // unittests. The tests were tailored to previous default value of the parameter 425 snippets_fetcher().FetchSnippetsFromHosts(/*hosts=*/std::set<std::string>(),
430 // fetching_host_restrict, which changed now. 426 /*language_code=*/"en-US",
427 /*count=*/1);
428 FastForwardUntilNoTasksRemain();
429 EXPECT_THAT(snippets_fetcher().last_status(),
430 Eq("Cannot fetch for empty hosts list."));
431 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty());
432 EXPECT_THAT(
433 histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchResult"),
434 ElementsAre(base::Bucket(/*min=*/1, /*count=*/1)));
435 EXPECT_THAT(histogram_tester().GetAllSamples(
436 "NewTabPage.Snippets.FetchHttpResponseOrErrorCode"),
437 IsEmpty());
438 // This particular error gets triggered prior to JSON parsing and hence tests
439 // observe no fetch latency.
440 EXPECT_THAT(histogram_tester().GetAllSamples("NewTabPage.Snippets.FetchTime"),
441 ElementsAre(base::Bucket(/*min=*/0, /*count=*/1)));
442 }
443
444 TEST_F(NTPSnippetsFetcherHostRestrictedTest, ShouldRestrictToHosts) {
445 net::TestURLFetcherFactory test_url_fetcher_factory;
446 snippets_fetcher().FetchSnippetsFromHosts(
447 {"www.somehost1.com", "www.somehost2.com"}, test_lang(), /*count=*/17);
448 net::TestURLFetcher* fetcher = test_url_fetcher_factory.GetFetcherByID(0);
449 ASSERT_THAT(fetcher, NotNull());
450 std::unique_ptr<base::Value> value =
451 base::JSONReader::Read(fetcher->upload_data());
452 ASSERT_TRUE(value) << " failed to parse JSON: "
453 << PrintToString(fetcher->upload_data());
454 const base::DictionaryValue* dict = nullptr;
455 ASSERT_TRUE(value->GetAsDictionary(&dict));
456 const base::DictionaryValue* local_scoring_params = nullptr;
457 ASSERT_TRUE(dict->GetDictionary("advanced_options.local_scoring_params",
458 &local_scoring_params));
459 const base::ListValue* content_selectors = nullptr;
460 ASSERT_TRUE(
461 local_scoring_params->GetList("content_selectors", &content_selectors));
462 ASSERT_THAT(content_selectors->GetSize(), Eq(static_cast<size_t>(2)));
463 const base::DictionaryValue* content_selector = nullptr;
464 ASSERT_TRUE(content_selectors->GetDictionary(0, &content_selector));
465 std::string content_selector_value;
466 EXPECT_TRUE(content_selector->GetString("value", &content_selector_value));
467 EXPECT_THAT(content_selector_value, Eq("www.somehost1.com"));
468 ASSERT_TRUE(content_selectors->GetDictionary(1, &content_selector));
469 EXPECT_TRUE(content_selector->GetString("value", &content_selector_value));
470 EXPECT_THAT(content_selector_value, Eq("www.somehost2.com"));
471 }
472
431 TEST_F(NTPSnippetsFetcherTest, ShouldReportUrlStatusError) { 473 TEST_F(NTPSnippetsFetcherTest, ShouldReportUrlStatusError) {
432 SetFakeResponse(/*data=*/std::string(), net::HTTP_NOT_FOUND, 474 SetFakeResponse(/*data=*/std::string(), net::HTTP_NOT_FOUND,
433 net::URLRequestStatus::FAILED); 475 net::URLRequestStatus::FAILED);
434 EXPECT_CALL(mock_callback(), Run(/*snippets=*/Not(HasValue()))).Times(1); 476 EXPECT_CALL(mock_callback(), Run(/*snippets=*/Not(HasValue()))).Times(1);
435 snippets_fetcher().FetchSnippetsFromHosts(test_hosts(), test_lang(), 477 snippets_fetcher().FetchSnippetsFromHosts(test_hosts(), test_lang(),
436 /*count=*/1); 478 /*count=*/1);
437 FastForwardUntilNoTasksRemain(); 479 FastForwardUntilNoTasksRemain();
438 EXPECT_THAT(snippets_fetcher().last_status(), 480 EXPECT_THAT(snippets_fetcher().last_status(),
439 Eq("URLRequestStatus error -2")); 481 Eq("URLRequestStatus error -2"));
440 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty()); 482 EXPECT_THAT(snippets_fetcher().last_json(), IsEmpty());
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
563 if (snippets) { 605 if (snippets) {
564 // Matchers above aren't any more precise than this, so this is sufficient 606 // Matchers above aren't any more precise than this, so this is sufficient
565 // for test-failure diagnostics. 607 // for test-failure diagnostics.
566 return os << "list with " << snippets->size() << " elements"; 608 return os << "list with " << snippets->size() << " elements";
567 } else { 609 } else {
568 return os << "null"; 610 return os << "null";
569 } 611 }
570 } 612 }
571 613
572 } // namespace ntp_snippets 614 } // namespace ntp_snippets
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698