diff options
Diffstat (limited to 'chromium/components/variations/service')
10 files changed, 219 insertions, 179 deletions
diff --git a/chromium/components/variations/service/BUILD.gn b/chromium/components/variations/service/BUILD.gn index 80544d0a373..e3c0c1e0db3 100644 --- a/chromium/components/variations/service/BUILD.gn +++ b/chromium/components/variations/service/BUILD.gn @@ -29,6 +29,7 @@ static_library("service") { "//components/version_info", "//components/web_resource", "//net", + "//services/network/public/cpp", "//ui/base", ] } @@ -54,6 +55,8 @@ source_set("unit_tests") { "//components/web_resource:test_support", "//net", "//net:test_support", + "//services/network:test_support", + "//services/network/public/cpp", "//testing/gtest", ] } diff --git a/chromium/components/variations/service/DEPS b/chromium/components/variations/service/DEPS index 179d34cec6b..7d4e98a9107 100644 --- a/chromium/components/variations/service/DEPS +++ b/chromium/components/variations/service/DEPS @@ -7,5 +7,7 @@ include_rules = [ "+components/version_info", "+components/web_resource", "+net", + "+services/network/public", + "+services/network/test", "+ui/base", ] diff --git a/chromium/components/variations/service/safe_seed_manager_unittest.cc b/chromium/components/variations/service/safe_seed_manager_unittest.cc index 0ae6b5c6e3f..28f28d605d8 100644 --- a/chromium/components/variations/service/safe_seed_manager_unittest.cc +++ b/chromium/components/variations/service/safe_seed_manager_unittest.cc @@ -10,7 +10,7 @@ #include "base/base_switches.h" #include "base/command_line.h" #include "base/macros.h" -#include "base/test/histogram_tester.h" +#include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "components/prefs/testing_pref_service.h" #include "components/variations/client_filterable_state.h" diff --git a/chromium/components/variations/service/variations_field_trial_creator.cc b/chromium/components/variations/service/variations_field_trial_creator.cc index 966d21d16b1..5f33665f28a 100644 --- a/chromium/components/variations/service/variations_field_trial_creator.cc +++ b/chromium/components/variations/service/variations_field_trial_creator.cc @@ -250,9 +250,7 @@ VariationsFieldTrialCreator::GetClientFilterableStateForVersion( state->version = version; state->channel = GetChannelForVariations(client_->GetChannel()); state->form_factor = GetCurrentFormFactor(); - state->platform = (has_platform_override_) - ? platform_override_ - : ClientFilterableState::GetCurrentPlatform(); + state->platform = GetPlatform(); state->hardware_class = GetShortHardwareClass(); #if defined(OS_ANDROID) // This is set on Android only currently, because the IsLowEndDevice() API @@ -493,7 +491,7 @@ bool VariationsFieldTrialCreator::SetupFieldTrials( if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) && !command_line->HasSwitch(::switches::kForceFieldTrials) && !command_line->HasSwitch(switches::kVariationsServerURL)) { - AssociateDefaultFieldTrialConfig(feature_list.get()); + AssociateDefaultFieldTrialConfig(feature_list.get(), GetPlatform()); } #endif // defined(FIELDTRIAL_TESTING_ENABLED) @@ -515,4 +513,10 @@ VariationsSeedStore* VariationsFieldTrialCreator::GetSeedStore() { return &seed_store_; } +Study::Platform VariationsFieldTrialCreator::GetPlatform() { + if (has_platform_override_) + return platform_override_; + return ClientFilterableState::GetCurrentPlatform(); +} + } // namespace variations diff --git a/chromium/components/variations/service/variations_field_trial_creator.h b/chromium/components/variations/service/variations_field_trial_creator.h index ae9cc954104..6d6ff5db494 100644 --- a/chromium/components/variations/service/variations_field_trial_creator.h +++ b/chromium/components/variations/service/variations_field_trial_creator.h @@ -14,6 +14,7 @@ #include "base/macros.h" #include "base/metrics/field_trial.h" #include "components/variations/client_filterable_state.h" +#include "components/variations/proto/study.pb.h" #include "components/variations/seed_response.h" #include "components/variations/service/ui_string_overrider.h" #include "components/variations/variations_seed_store.h" @@ -133,6 +134,9 @@ class VariationsFieldTrialCreator { // Returns the seed store. Virtual for testing. virtual VariationsSeedStore* GetSeedStore(); + // Get the platform we're running on, respecting OverrideVariationsPlatform(). + Study::Platform GetPlatform(); + PrefService* local_state() { return seed_store_.local_state(); } const PrefService* local_state() const { return seed_store_.local_state(); } diff --git a/chromium/components/variations/service/variations_field_trial_creator_unittest.cc b/chromium/components/variations/service/variations_field_trial_creator_unittest.cc index 46f2c3e9127..aea3a8911ea 100644 --- a/chromium/components/variations/service/variations_field_trial_creator_unittest.cc +++ b/chromium/components/variations/service/variations_field_trial_creator_unittest.cc @@ -11,7 +11,7 @@ #include "base/feature_list.h" #include "base/macros.h" #include "base/strings/stringprintf.h" -#include "base/test/histogram_tester.h" +#include "base/test/metrics/histogram_tester.h" #include "base/version.h" #include "build/build_config.h" #include "components/prefs/testing_pref_service.h" @@ -21,6 +21,7 @@ #include "components/variations/service/safe_seed_manager.h" #include "components/variations/service/variations_service.h" #include "components/variations/service/variations_service_client.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -159,7 +160,8 @@ class TestVariationsServiceClient : public VariationsServiceClient { override { return base::Callback<base::Version(void)>(); } - net::URLRequestContextGetter* GetURLRequestContext() override { + scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() + override { return nullptr; } network_time::NetworkTimeTracker* GetNetworkTimeTracker() override { diff --git a/chromium/components/variations/service/variations_service.cc b/chromium/components/variations/service/variations_service.cc index 2c298489fee..7bfce363ec1 100644 --- a/chromium/components/variations/service/variations_service.cc +++ b/chromium/components/variations/service/variations_service.cc @@ -51,8 +51,9 @@ #include "net/http/http_status_code.h" #include "net/http/http_util.h" #include "net/traffic_annotation/network_traffic_annotation.h" -#include "net/url_request/url_fetcher.h" -#include "net/url_request/url_request_status.h" +#include "services/network/public/cpp/resource_request.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/simple_url_loader.h" #include "ui/base/device_form_factor.h" #include "url/gurl.h" @@ -271,8 +272,8 @@ VariationsService::VariationsService( ui_string_overrider, MaybeImportFirstRunSeed(local_state)), weak_ptr_factory_(this) { - DCHECK(client_.get()); - DCHECK(resource_request_allowed_notifier_.get()); + DCHECK(client_); + DCHECK(resource_request_allowed_notifier_); } VariationsService::~VariationsService() { @@ -513,15 +514,11 @@ bool VariationsService::DoFetchFromURL(const GURL& url, bool is_http_retry) { policy_exception_justification: "Not implemented, considered not required." })"); - pending_seed_request_ = net::URLFetcher::Create(0, url, net::URLFetcher::GET, - this, traffic_annotation); - data_use_measurement::DataUseUserData::AttachToFetcher( - pending_seed_request_.get(), - data_use_measurement::DataUseUserData::VARIATIONS); - pending_seed_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | - net::LOAD_DO_NOT_SEND_AUTH_DATA | - net::LOAD_DO_NOT_SAVE_COOKIES); - pending_seed_request_->SetRequestContext(client_->GetURLRequestContext()); + auto resource_request = std::make_unique<network::ResourceRequest>(); + resource_request->url = url; + resource_request->load_flags = net::LOAD_DO_NOT_SEND_COOKIES | + net::LOAD_DO_NOT_SEND_AUTH_DATA | + net::LOAD_DO_NOT_SAVE_COOKIES; bool enable_deltas = false; std::string serial_number = field_trial_creator_.seed_store()->GetLatestSerialNumber(); @@ -532,19 +529,29 @@ bool VariationsService::DoFetchFromURL(const GURL& url, bool is_http_retry) { // If the fetch is an HTTP retry, encrypt the If-None-Match header. if (is_http_retry) { if (!EncryptString(serial_number, &serial_number)) { - pending_seed_request_.reset(); return false; } base::Base64Encode(serial_number, &serial_number); } - pending_seed_request_->AddExtraRequestHeader("If-None-Match:" + - serial_number); + resource_request->headers.SetHeader("If-None-Match", serial_number); } // Tell the server that delta-compressed and gzipped seeds are supported. - const char* supported_im = enable_deltas ? "A-IM:x-bm,gzip" : "A-IM:gzip"; - pending_seed_request_->AddExtraRequestHeader(supported_im); - - pending_seed_request_->Start(); + const char* supported_im = enable_deltas ? "x-bm,gzip" : "gzip"; + resource_request->headers.SetHeader("A-IM", supported_im); + + // TODO(https://crbug.com/808498): Re-add data use measurement once + // SimpleURLLoader supports it. + // ID=data_use_measurement::DataUseUserData::VARIATIONS + pending_seed_request_ = network::SimpleURLLoader::Create( + std::move(resource_request), traffic_annotation); + // Ensure our callback is called even with "304 Not Modified" responses. + pending_seed_request_->SetAllowHttpErrorResults(true); + // base::Unretained is safe here since this class owns + // |pending_seed_request_|'s lifetime. + pending_seed_request_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( + client_->GetURLLoaderFactory().get(), + base::BindOnce(&VariationsService::OnSimpleLoaderComplete, + base::Unretained(this))); const base::TimeTicks now = base::TimeTicks::Now(); base::TimeDelta time_since_last_fetch; @@ -574,7 +581,7 @@ void VariationsService::StartRepeatedVariationsSeedFetch() { GetVariationsServerURL(policy_pref_service_, restrict_mode_, USE_HTTP); } - DCHECK(!request_scheduler_.get()); + DCHECK(!request_scheduler_); request_scheduler_.reset(VariationsRequestScheduler::Create( base::Bind(&VariationsService::FetchVariationsSeed, weak_ptr_factory_.GetWeakPtr()), @@ -611,31 +618,35 @@ void VariationsService::NotifyObservers( } } -void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) { +void VariationsService::OnSimpleLoaderComplete( + std::unique_ptr<std::string> response_body) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); - DCHECK_EQ(pending_seed_request_.get(), source); const bool is_first_request = !initial_request_completed_; initial_request_completed_ = true; - // The fetcher will be deleted when the request is handled. - std::unique_ptr<const net::URLFetcher> request( - pending_seed_request_.release()); - const net::URLRequestStatus& status = request->GetStatus(); - const int response_code = request->GetResponseCode(); - bool was_https = request->GetURL().SchemeIs(url::kHttpsScheme); + int net_error = pending_seed_request_->NetError(); + int response_code = -1; + scoped_refptr<net::HttpResponseHeaders> headers; + if (pending_seed_request_->ResponseInfo() && + pending_seed_request_->ResponseInfo()->headers) { + headers = pending_seed_request_->ResponseInfo()->headers; + response_code = headers->response_code(); + } + bool is_success = headers && (net_error == net::OK); + bool was_https = + pending_seed_request_->GetFinalURL().SchemeIs(url::kHttpsScheme); + pending_seed_request_.reset(); if (was_https) { - base::UmaHistogramSparse( - "Variations.SeedFetchResponseOrErrorCode", - status.is_success() ? response_code : status.error()); + base::UmaHistogramSparse("Variations.SeedFetchResponseOrErrorCode", + is_success ? response_code : net_error); } else { - base::UmaHistogramSparse( - "Variations.SeedFetchResponseOrErrorCode.HTTP", - status.is_success() ? response_code : status.error()); + base::UmaHistogramSparse("Variations.SeedFetchResponseOrErrorCode.HTTP", + is_success ? response_code : net_error); } - if (status.status() != net::URLRequestStatus::SUCCESS) { - DVLOG(1) << "Variations server request failed with error: " - << status.error() << ": " << net::ErrorToString(status.error()); + if (!is_success) { + DVLOG(1) << "Variations server request failed with error: " << net_error + << ": " << net::ErrorToString(net_error); // If the current fetch attempt was over an HTTPS connection, retry the // fetch immediately over an HTTP connection. // Currently we only do this if if the 'VariationsHttpRetry' feature is @@ -649,7 +660,8 @@ void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) { // It's common for the very first fetch attempt to fail (e.g. the network // may not yet be available). In such a case, try again soon, rather than // waiting the full time interval. - if (is_first_request) + // |request_scheduler_| will be null during unit tests. + if (is_first_request && request_scheduler_) request_scheduler_->ScheduleFetchShortly(); return; } @@ -660,7 +672,7 @@ void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) { base::Time response_date; if (response_code == net::HTTP_OK || response_code == net::HTTP_NOT_MODIFIED) { - bool success = request->GetResponseHeaders()->GetDateValue(&response_date); + bool success = headers->GetDateValue(&response_date); DCHECK(success || response_date.is_null()); if (!response_date.is_null()) { @@ -688,14 +700,9 @@ void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) { return; } - std::string seed_data; - bool success = request->GetResponseAsString(&seed_data); - DCHECK(success); - - net::HttpResponseHeaders* headers = request->GetResponseHeaders(); bool is_delta_compressed; bool is_gzip_compressed; - if (!GetInstanceManipulations(headers, &is_delta_compressed, + if (!GetInstanceManipulations(headers.get(), &is_delta_compressed, &is_gzip_compressed)) { // The header does not specify supported instance manipulations, unable to // process data. Details of errors were logged by GetInstanceManipulations. @@ -703,14 +710,17 @@ void VariationsService::OnURLFetchComplete(const net::URLFetcher* source) { return; } - const std::string signature = GetHeaderValue(headers, "X-Seed-Signature"); - const std::string country_code = GetHeaderValue(headers, "X-Country"); + const std::string signature = + GetHeaderValue(headers.get(), "X-Seed-Signature"); + const std::string country_code = GetHeaderValue(headers.get(), "X-Country"); const bool store_success = - StoreSeed(seed_data, signature, country_code, response_date, + StoreSeed(*response_body, signature, country_code, response_date, is_delta_compressed, is_gzip_compressed, !was_https); if (!store_success && is_delta_compressed) { disable_deltas_for_next_request_ = true; - request_scheduler_->ScheduleFetchShortly(); + // |request_scheduler_| will be null during unit tests. + if (request_scheduler_) + request_scheduler_->ScheduleFetchShortly(); } } @@ -728,7 +738,7 @@ void VariationsService::OnResourceRequestsAllowed() { DoActualFetch(); // This service must have created a scheduler in order for this to be called. - DCHECK(request_scheduler_.get()); + DCHECK(request_scheduler_); request_scheduler_->Reset(); } diff --git a/chromium/components/variations/service/variations_service.h b/chromium/components/variations/service/variations_service.h index 7c689858e6e..f136b5bfb16 100644 --- a/chromium/components/variations/service/variations_service.h +++ b/chromium/components/variations/service/variations_service.h @@ -27,7 +27,6 @@ #include "components/variations/variations_seed_store.h" #include "components/version_info/version_info.h" #include "components/web_resource/resource_request_allowed_notifier.h" -#include "net/url_request/url_fetcher_delegate.h" #include "url/gurl.h" class PrefService; @@ -42,6 +41,10 @@ namespace metrics { class MetricsStateManager; } +namespace network { +class SimpleURLLoader; +} + namespace user_prefs { class PrefRegistrySyncable; } @@ -55,8 +58,7 @@ namespace variations { // Used to setup field trials based on stored variations seed data, and fetch // new seed data from the variations server. class VariationsService - : public net::URLFetcherDelegate, - public web_resource::ResourceRequestAllowedNotifier::Observer { + : public web_resource::ResourceRequestAllowedNotifier::Observer { public: class Observer { public: @@ -149,7 +151,7 @@ class VariationsService // Enables fetching the seed for testing, even for unofficial builds. This // should be used along with overriding |DoActualFetch| or using - // |net::TestURLFetcherFactory|. + // |net::TestURLLoaderFactory|. static void EnableFetchForTesting(); // Set the PrefService responsible for getting policy-related preferences, @@ -210,6 +212,16 @@ class VariationsService variations_server_url_ = url; } + // The client that provides access to the embedder's environment. + // Protected so testing subclasses can access it. + VariationsServiceClient* client() { return client_.get(); } + + // Records a successful fetch: + // (1) Resets failure streaks for Safe Mode. + // (2) Records the time of this fetch as the most recent successful fetch. + // Protected so testing subclasses can call it. + void RecordSuccessfulFetch(); + private: FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, Observer); FRIEND_TEST_ALL_PREFIXES(VariationsServiceTest, SeedStoredWhenOKStatus); @@ -266,8 +278,8 @@ class VariationsService void NotifyObservers( const variations::VariationsSeedSimulator::Result& result); - // net::URLFetcherDelegate implementation: - void OnURLFetchComplete(const net::URLFetcher* source) override; + // Called by SimpleURLLoader when |pending_seed_request_| load completes. + void OnSimpleLoaderComplete(std::unique_ptr<std::string> response_body); // ResourceRequestAllowedNotifier::Observer implementation: void OnResourceRequestsAllowed() override; @@ -278,11 +290,6 @@ class VariationsService std::unique_ptr<variations::VariationsSeed> seed, const base::Version& version); - // Records a successful fetch: - // (1) Resets failure streaks for Safe Mode. - // (2) Records the time of this fetch as the most recent successful fetch. - void RecordSuccessfulFetch(); - // Encrypts a string using the encrypted_messages component, input is passed // in as |plaintext|, outputs a serialized EncryptedMessage protobuf as // |encrypted|. Returns true on success, false on failure. The encryption can @@ -318,7 +325,7 @@ class VariationsService // Contains the current seed request. Will only have a value while a request // is pending, and will be reset by |OnURLFetchComplete|. - std::unique_ptr<net::URLFetcher> pending_seed_request_; + std::unique_ptr<network::SimpleURLLoader> pending_seed_request_; // The value of the "restrict" URL param to the variations server that has // been specified via |SetRestrictMode|. If empty, the URL param will be set diff --git a/chromium/components/variations/service/variations_service_client.h b/chromium/components/variations/service/variations_service_client.h index 91182c2a2fc..2b466bbf91c 100644 --- a/chromium/components/variations/service/variations_service_client.h +++ b/chromium/components/variations/service/variations_service_client.h @@ -8,12 +8,13 @@ #include <string> #include "base/callback.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string16.h" #include "base/version.h" #include "components/version_info/version_info.h" -namespace net { -class URLRequestContextGetter; +namespace network { +class SharedURLLoaderFactory; } namespace network_time { @@ -37,7 +38,8 @@ class VariationsServiceClient { virtual base::Callback<base::Version(void)> GetVersionForSimulationCallback() = 0; - virtual net::URLRequestContextGetter* GetURLRequestContext() = 0; + virtual scoped_refptr<network::SharedURLLoaderFactory> + GetURLLoaderFactory() = 0; virtual network_time::NetworkTimeTracker* GetNetworkTimeTracker() = 0; // Gets the channel of the embedder. diff --git a/chromium/components/variations/service/variations_service_unittest.cc b/chromium/components/variations/service/variations_service_unittest.cc index 1c2feed8843..2c101254ed1 100644 --- a/chromium/components/variations/service/variations_service_unittest.cc +++ b/chromium/components/variations/service/variations_service_unittest.cc @@ -15,11 +15,13 @@ #include "base/json/json_string_value_serializer.h" #include "base/macros.h" #include "base/memory/ptr_util.h" +#include "base/run_loop.h" #include "base/sha1.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/test/histogram_tester.h" +#include "base/test/bind_test_util.h" +#include "base/test/metrics/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "base/version.h" #include "components/metrics/clean_exit_beacon.h" @@ -36,7 +38,11 @@ #include "net/base/url_util.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" +#include "net/http/http_util.h" #include "net/url_request/test_url_fetcher_factory.h" +#include "services/network/public/cpp/shared_url_loader_factory.h" +#include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" +#include "services/network/test/test_url_loader_factory.h" #include "testing/gtest/include/gtest/gtest.h" namespace variations { @@ -56,7 +62,11 @@ base::Version StubGetVersionForSimulation() { class TestVariationsServiceClient : public VariationsServiceClient { public: - TestVariationsServiceClient() {} + TestVariationsServiceClient() { + test_shared_loader_factory_ = + base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( + &test_url_loader_factory_); + } ~TestVariationsServiceClient() override {} // VariationsServiceClient: @@ -65,8 +75,9 @@ class TestVariationsServiceClient : public VariationsServiceClient { override { return base::Bind(&StubGetVersionForSimulation); } - net::URLRequestContextGetter* GetURLRequestContext() override { - return nullptr; + scoped_refptr<network::SharedURLLoaderFactory> GetURLLoaderFactory() + override { + return test_shared_loader_factory_; } network_time::NetworkTimeTracker* GetNetworkTimeTracker() override { return nullptr; @@ -85,9 +96,15 @@ class TestVariationsServiceClient : public VariationsServiceClient { void set_channel(version_info::Channel channel) { channel_ = channel; } + network::TestURLLoaderFactory* test_url_loader_factory() { + return &test_url_loader_factory_; + } + private: std::string restrict_parameter_; version_info::Channel channel_ = version_info::Channel::UNKNOWN; + network::TestURLLoaderFactory test_url_loader_factory_; + scoped_refptr<network::SharedURLLoaderFactory> test_shared_loader_factory_; DISALLOW_COPY_AND_ASSIGN(TestVariationsServiceClient); }; @@ -111,16 +128,17 @@ class TestVariationsService : public VariationsService { delta_compressed_seed_(false), gzip_compressed_seed_(false), insecurely_fetched_seed_(false) { - set_variations_server_url(GetVariationsServerURL( - local_state, std::string(), use_secure_url ? USE_HTTPS : USE_HTTP)); + interception_url_ = GetVariationsServerURL( + local_state, std::string(), use_secure_url ? USE_HTTPS : USE_HTTP); + set_variations_server_url(interception_url_); } ~TestVariationsService() override {} + GURL interception_url() { return interception_url_; } void set_intercepts_fetch(bool value) { intercepts_fetch_ = value; } - bool fetch_attempted() const { return fetch_attempted_; } bool seed_stored() const { return seed_stored_; } const std::string& stored_country() const { return stored_country_; } @@ -135,6 +153,7 @@ class TestVariationsService : public VariationsService { } VariationsService::DoActualFetch(); + base::RunLoop().RunUntilIdle(); } bool StoreSeed(const std::string& seed_data, @@ -150,6 +169,7 @@ class TestVariationsService : public VariationsService { delta_compressed_seed_ = is_delta_compressed; gzip_compressed_seed_ = is_gzip_compressed; insecurely_fetched_seed_ = fetched_insecurely; + RecordSuccessfulFetch(); return true; } @@ -158,8 +178,17 @@ class TestVariationsService : public VariationsService { return std::unique_ptr<const base::FieldTrial::EntropyProvider>(nullptr); } - private: + TestVariationsServiceClient* client() { + return static_cast<TestVariationsServiceClient*>( + VariationsService::client()); + } + network::TestURLLoaderFactory* test_url_loader_factory() { + return client()->test_url_loader_factory(); + } + + private: + GURL interception_url_; bool intercepts_fetch_; bool fetch_attempted_; bool seed_stored_; @@ -236,31 +265,6 @@ std::string SerializeSeed(const VariationsSeed& seed) { return serialized_seed; } -// Simulates a variations service response by setting a date header and the -// specified HTTP |response_code| on |fetcher|. Sets additional header |header| -// if it is not null. -scoped_refptr<net::HttpResponseHeaders> SimulateServerResponseWithHeader( - int response_code, - net::TestURLFetcher* fetcher, - const std::string* header) { - EXPECT_TRUE(fetcher); - scoped_refptr<net::HttpResponseHeaders> headers( - new net::HttpResponseHeaders("date:Wed, 13 Feb 2013 00:25:24 GMT\0\0")); - if (header) - headers->AddHeader(*header); - fetcher->set_response_headers(headers); - fetcher->set_response_code(response_code); - return headers; -} - -// Simulates a variations service response by setting a date header and the -// specified HTTP |response_code| on |fetcher|. -scoped_refptr<net::HttpResponseHeaders> SimulateServerResponse( - int response_code, - net::TestURLFetcher* fetcher) { - return SimulateServerResponseWithHeader(response_code, fetcher, nullptr); -} - // Converts |list_value| to a string, to make it easier for debugging. std::string ListValueToString(const base::ListValue& list_value) { std::string json; @@ -416,31 +420,27 @@ TEST_F(VariationsServiceTest, RequestsInitiallyAllowed) { } TEST_F(VariationsServiceTest, SeedStoredWhenOKStatus) { - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); + + EXPECT_FALSE(service.seed_stored()); + + service.test_url_loader_factory()->AddResponse( + service.interception_url().spec(), SerializeSeed(CreateTestSeed())); service.set_intercepts_fetch(false); service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - SimulateServerResponse(net::HTTP_OK, fetcher); - fetcher->SetResponseString(SerializeSeed(CreateTestSeed())); - - EXPECT_FALSE(service.seed_stored()); - service.OnURLFetchComplete(fetcher); EXPECT_TRUE(service.seed_stored()); } TEST_F(VariationsServiceTest, SeedNotStoredWhenNonOKStatus) { - const int non_ok_status_codes[] = { - net::HTTP_NO_CONTENT, - net::HTTP_NOT_MODIFIED, - net::HTTP_NOT_FOUND, - net::HTTP_INTERNAL_SERVER_ERROR, - net::HTTP_SERVICE_UNAVAILABLE, + const net::HttpStatusCode non_ok_status_codes[] = { + net::HTTP_NO_CONTENT, net::HTTP_NOT_MODIFIED, + net::HTTP_NOT_FOUND, net::HTTP_INTERNAL_SERVER_ERROR, + net::HTTP_SERVICE_UNAVAILABLE, }; VariationsService::EnableFetchForTesting(); @@ -450,14 +450,12 @@ TEST_F(VariationsServiceTest, SeedNotStoredWhenNonOKStatus) { &prefs_, GetMetricsStateManager(), true); service.set_intercepts_fetch(false); for (size_t i = 0; i < arraysize(non_ok_status_codes); ++i) { - net::TestURLFetcherFactory factory; - service.DoActualFetch(); EXPECT_TRUE(prefs_.FindPreference(prefs::kVariationsCompressedSeed) ->IsDefaultValue()); - - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - SimulateServerResponse(non_ok_status_codes[i], fetcher); - service.OnURLFetchComplete(fetcher); + service.test_url_loader_factory()->ClearResponses(); + service.test_url_loader_factory()->AddResponse( + service.interception_url().spec(), "", non_ok_status_codes[i]); + service.DoActualFetch(); EXPECT_TRUE(prefs_.FindPreference(prefs::kVariationsCompressedSeed) ->IsDefaultValue()); @@ -465,20 +463,23 @@ TEST_F(VariationsServiceTest, SeedNotStoredWhenNonOKStatus) { } TEST_F(VariationsServiceTest, RequestGzipCompressedSeed) { - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); service.set_intercepts_fetch(false); + net::HttpRequestHeaders intercepted_headers; + service.test_url_loader_factory()->AddResponse( + service.interception_url().spec(), ""); + service.test_url_loader_factory()->SetInterceptor( + base::BindLambdaForTesting([&](const network::ResourceRequest& request) { + intercepted_headers = request.headers; + })); service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - net::HttpRequestHeaders headers; - fetcher->GetExtraRequestHeaders(&headers); std::string field; - ASSERT_TRUE(headers.GetHeader("A-IM", &field)); + ASSERT_TRUE(intercepted_headers.GetHeader("A-IM", &field)); EXPECT_EQ("gzip", field); } @@ -499,23 +500,25 @@ TEST_F(VariationsServiceTest, InstanceManipulations) { }; std::string serialized_seed = SerializeSeed(CreateTestSeed()); - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); - for (size_t i = 0; i < arraysize(cases); ++i) { TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); service.set_intercepts_fetch(false); - service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - if (cases[i].im.empty()) - SimulateServerResponse(net::HTTP_OK, fetcher); - else - SimulateServerResponseWithHeader(net::HTTP_OK, fetcher, &cases[i].im); - fetcher->SetResponseString(serialized_seed); - service.OnURLFetchComplete(fetcher); + std::string headers("HTTP/1.1 200 OK\n\n"); + network::ResourceResponseHead head; + head.headers = new net::HttpResponseHeaders( + net::HttpUtil::AssembleRawHeaders(headers.c_str(), headers.size())); + if (!cases[i].im.empty()) + head.headers->AddHeader(cases[i].im); + network::URLLoaderCompletionStatus status; + status.decoded_body_length = serialized_seed.size(); + service.test_url_loader_factory()->AddResponse( + service.interception_url(), head, serialized_seed, status); + + service.DoActualFetch(); EXPECT_EQ(cases[i].seed_stored, service.seed_stored()); EXPECT_EQ(cases[i].delta_compressed, service.delta_compressed_seed()); @@ -524,23 +527,27 @@ TEST_F(VariationsServiceTest, InstanceManipulations) { } TEST_F(VariationsServiceTest, CountryHeader) { - net::TestURLFetcherFactory factory; + std::string serialized_seed = SerializeSeed(CreateTestSeed()); VariationsService::EnableFetchForTesting(); TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); + EXPECT_FALSE(service.seed_stored()); service.set_intercepts_fetch(false); - service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - scoped_refptr<net::HttpResponseHeaders> headers = - SimulateServerResponse(net::HTTP_OK, fetcher); - headers->AddHeader("X-Country: test"); - fetcher->SetResponseString(SerializeSeed(CreateTestSeed())); + std::string headers("HTTP/1.1 200 OK\n\n"); + network::ResourceResponseHead head; + head.headers = new net::HttpResponseHeaders( + net::HttpUtil::AssembleRawHeaders(headers.c_str(), headers.size())); + head.headers->AddHeader("X-Country: test"); + network::URLLoaderCompletionStatus status; + status.decoded_body_length = serialized_seed.size(); + service.test_url_loader_factory()->AddResponse(service.interception_url(), + head, serialized_seed, status); + + service.DoActualFetch(); - EXPECT_FALSE(service.seed_stored()); - service.OnURLFetchComplete(fetcher); EXPECT_TRUE(service.seed_stored()); EXPECT_EQ("test", service.stored_country()); } @@ -755,7 +762,6 @@ TEST_F(VariationsServiceTest, OverrideStoredPermanentCountry) { TEST_F(VariationsServiceTest, SafeMode_StartingRequestIncrementsFetchFailures) { prefs_.SetInteger(prefs::kVariationsFailedToFetchSeedStreak, 1); - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); // Create a variations service and start the fetch. @@ -777,14 +783,10 @@ TEST_F(VariationsServiceTest, SafeMode_SuccessfulFetchClearsFailureStreaks) { net::test::MockNetworkChangeNotifier network_change_notifier; // Create a variations service and perform a successful fetch. - VariationsService service( - std::make_unique<TestVariationsServiceClient>(), + TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), - &prefs_, GetMetricsStateManager(), UIStringOverrider()); - - net::TestURLFetcherFactory factory; - // This will actually start the fetch. - service.PerformPreMainMessageLoopStartup(); + &prefs_, GetMetricsStateManager(), true); + service.set_intercepts_fetch(false); // The below seed and signature pair were generated using the server's // private key. @@ -800,12 +802,20 @@ TEST_F(VariationsServiceTest, SafeMode_SuccessfulFetchClearsFailureStreaks) { std::string response; ASSERT_TRUE(base::Base64Decode(base64_seed_data, &response)); - const std::string header = "X-Seed-Signature:" + base64_seed_signature; + const std::string seed_signature_header = + "X-Seed-Signature:" + base64_seed_signature; + + std::string headers("HTTP/1.1 200 OK\n\n"); + network::ResourceResponseHead head; + head.headers = new net::HttpResponseHeaders( + net::HttpUtil::AssembleRawHeaders(headers.c_str(), headers.size())); + head.headers->AddHeader(seed_signature_header); + network::URLLoaderCompletionStatus status; + status.decoded_body_length = response.size(); + service.test_url_loader_factory()->AddResponse(service.interception_url(), + head, response, status); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - SimulateServerResponseWithHeader(net::HTTP_OK, fetcher, &header); - fetcher->SetResponseString(response); - service.OnURLFetchComplete(fetcher); + service.DoActualFetch(); // Verify that the streaks were reset. EXPECT_EQ(0, prefs_.GetInteger(prefs::kVariationsCrashStreak)); @@ -816,7 +826,6 @@ TEST_F(VariationsServiceTest, SafeMode_NotModifiedFetchClearsFailureStreaks) { prefs_.SetInteger(prefs::kVariationsCrashStreak, 2); prefs_.SetInteger(prefs::kVariationsFailedToFetchSeedStreak, 1); - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); // Create a variations service and perform a successful fetch. @@ -824,11 +833,16 @@ TEST_F(VariationsServiceTest, SafeMode_NotModifiedFetchClearsFailureStreaks) { std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); service.set_intercepts_fetch(false); - service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - SimulateServerResponse(net::HTTP_NOT_MODIFIED, fetcher); - service.OnURLFetchComplete(fetcher); + std::string headers("HTTP/1.1 304 Not Modified\n\n"); + network::ResourceResponseHead head; + head.headers = new net::HttpResponseHeaders( + net::HttpUtil::AssembleRawHeaders(headers.c_str(), headers.size())); + network::URLLoaderCompletionStatus status; + service.test_url_loader_factory()->AddResponse(service.interception_url(), + head, "", status); + + service.DoActualFetch(); EXPECT_EQ(0, prefs_.GetInteger(prefs::kVariationsCrashStreak)); EXPECT_EQ(0, prefs_.GetInteger(prefs::kVariationsFailedToFetchSeedStreak)); @@ -846,35 +860,27 @@ TEST_F(VariationsServiceTest, FieldTrialCreatorInitializedCorrectly) { TEST_F(VariationsServiceTest, InsecurelyFetchedSetWhenHTTP) { std::string serialized_seed = SerializeSeed(CreateTestSeed()); - net::TestURLFetcherFactory factory; VariationsService::EnableFetchForTesting(); TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), false); service.set_intercepts_fetch(false); + service.test_url_loader_factory()->AddResponse( + service.interception_url().spec(), serialized_seed); service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - fetcher->set_url(service.variations_server_url_); - SimulateServerResponse(net::HTTP_OK, fetcher); - fetcher->SetResponseString(serialized_seed); - service.OnURLFetchComplete(fetcher); EXPECT_TRUE(service.insecurely_fetched_seed()); } TEST_F(VariationsServiceTest, InsecurelyFetchedNotSetWhenHTTPS) { std::string serialized_seed = SerializeSeed(CreateTestSeed()); - net::TestURLFetcherFactory factory; TestVariationsService service( std::make_unique<web_resource::TestRequestAllowedNotifier>(&prefs_), &prefs_, GetMetricsStateManager(), true); VariationsService::EnableFetchForTesting(); service.set_intercepts_fetch(false); + service.test_url_loader_factory()->AddResponse( + service.interception_url().spec(), serialized_seed); service.DoActualFetch(); - net::TestURLFetcher* fetcher = factory.GetFetcherByID(0); - fetcher->set_url(service.variations_server_url_); - SimulateServerResponse(net::HTTP_OK, fetcher); - fetcher->SetResponseString(serialized_seed); - service.OnURLFetchComplete(fetcher); EXPECT_FALSE(service.insecurely_fetched_seed()); } |