data_reduction_proxy_settings_test_utils.cc revision 116680a4aac90f2aa7413d9095a592090648e557
1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings_test_utils.h"
6
7#include "base/command_line.h"
8#include "base/message_loop/message_loop.h"
9#include "base/prefs/pref_registry_simple.h"
10#include "base/prefs/scoped_user_pref_update.h"
11#include "base/strings/string_number_conversions.h"
12#include "components/data_reduction_proxy/common/data_reduction_proxy_pref_names.h"
13#include "components/data_reduction_proxy/common/data_reduction_proxy_switches.h"
14
15using testing::_;
16using testing::AnyNumber;
17using testing::Return;
18
19namespace {
20
21const char kProbeURLWithOKResponse[] = "http://ok.org/";
22const char kWarmupURLWithNoContentResponse[] = "http://warm.org/";
23
24const char kProxy[] = "proxy";
25
26}  // namespace
27
28namespace data_reduction_proxy {
29
30// Transform "normal"-looking headers (\n-separated) to the appropriate
31// input format for ParseRawHeaders (\0-separated).
32void HeadersToRaw(std::string* headers) {
33  std::replace(headers->begin(), headers->end(), '\n', '\0');
34  if (!headers->empty())
35    *headers += '\0';
36}
37
38ProbeURLFetchResult FetchResult(bool enabled, bool success) {
39  if (enabled) {
40    if (success)
41      return SUCCEEDED_PROXY_ALREADY_ENABLED;
42    return FAILED_PROXY_DISABLED;
43  }
44  if (success)
45    return SUCCEEDED_PROXY_ENABLED;
46  return FAILED_PROXY_ALREADY_DISABLED;
47}
48
49TestDataReductionProxyConfig::TestDataReductionProxyConfig()
50    : enabled_(false),
51      restricted_(false),
52      fallback_restricted_(false) {}
53
54void TestDataReductionProxyConfig::Enable(
55    bool restricted,
56    bool fallback_restricted,
57    const std::string& primary_origin,
58    const std::string& fallback_origin,
59    const std::string& ssl_origin) {
60  enabled_ = true;
61  restricted_ = restricted;
62  fallback_restricted_ = fallback_restricted;
63  origin_ = primary_origin;
64  fallback_origin_ = fallback_origin;
65  ssl_origin_ = ssl_origin;
66}
67
68void TestDataReductionProxyConfig::Disable() {
69  enabled_ = false;
70  restricted_ = false;
71  fallback_restricted_ = false;
72  origin_ = "";
73  fallback_origin_ = "";
74  ssl_origin_ = "";
75}
76
77DataReductionProxySettingsTestBase::DataReductionProxySettingsTestBase()
78    : testing::Test() {
79}
80
81DataReductionProxySettingsTestBase::~DataReductionProxySettingsTestBase() {}
82
83// testing::Test implementation:
84void DataReductionProxySettingsTestBase::SetUp() {
85  PrefRegistrySimple* registry = pref_service_.registry();
86  registry->RegisterListPref(prefs::kDailyHttpOriginalContentLength);
87  registry->RegisterListPref(prefs::kDailyHttpReceivedContentLength);
88  registry->RegisterInt64Pref(prefs::kDailyHttpContentLengthLastUpdateDate,
89                              0L);
90  registry->RegisterDictionaryPref(kProxy);
91  registry->RegisterBooleanPref(prefs::kDataReductionProxyEnabled, false);
92  registry->RegisterBooleanPref(prefs::kDataReductionProxyAltEnabled, false);
93  registry->RegisterBooleanPref(prefs::kDataReductionProxyWasEnabledBefore,
94                                false);
95  //AddProxyToCommandLine();
96  ResetSettings(true, true, false, true, false);
97
98  ListPrefUpdate original_update(&pref_service_,
99                                 prefs::kDailyHttpOriginalContentLength);
100  ListPrefUpdate received_update(&pref_service_,
101                                 prefs::kDailyHttpReceivedContentLength);
102  for (int64 i = 0; i < kNumDaysInHistory; i++) {
103    original_update->Insert(0,
104                            new base::StringValue(base::Int64ToString(2 * i)));
105    received_update->Insert(0, new base::StringValue(base::Int64ToString(i)));
106  }
107  last_update_time_ = base::Time::Now().LocalMidnight();
108  pref_service_.SetInt64(
109      prefs::kDailyHttpContentLengthLastUpdateDate,
110      last_update_time_.ToInternalValue());
111  expected_params_.reset(new TestDataReductionProxyParams(
112      DataReductionProxyParams::kAllowed |
113      DataReductionProxyParams::kFallbackAllowed |
114      DataReductionProxyParams::kPromoAllowed,
115      TestDataReductionProxyParams::HAS_EVERYTHING &
116      ~TestDataReductionProxyParams::HAS_DEV_ORIGIN));
117}
118
119template <class C>
120void DataReductionProxySettingsTestBase::ResetSettings(bool allowed,
121                                                       bool fallback_allowed,
122                                                       bool alt_allowed,
123                                                       bool promo_allowed,
124                                                       bool holdback) {
125  int flags = 0;
126  if (allowed)
127    flags |= DataReductionProxyParams::kAllowed;
128  if (fallback_allowed)
129    flags |= DataReductionProxyParams::kFallbackAllowed;
130  if (alt_allowed)
131    flags |= DataReductionProxyParams::kAlternativeAllowed;
132  if (promo_allowed)
133    flags |= DataReductionProxyParams::kPromoAllowed;
134  if (holdback)
135    flags |= DataReductionProxyParams::kHoldback;
136  MockDataReductionProxySettings<C>* settings =
137      new MockDataReductionProxySettings<C>(flags);
138  EXPECT_CALL(*settings, GetOriginalProfilePrefs())
139      .Times(AnyNumber())
140      .WillRepeatedly(Return(&pref_service_));
141  EXPECT_CALL(*settings, GetLocalStatePrefs())
142      .Times(AnyNumber())
143      .WillRepeatedly(Return(&pref_service_));
144  EXPECT_CALL(*settings, GetURLFetcherForAvailabilityCheck()).Times(0);
145  EXPECT_CALL(*settings, GetURLFetcherForWarmup()).Times(0);
146  EXPECT_CALL(*settings, LogProxyState(_, _, _)).Times(0);
147  settings_.reset(settings);
148  settings_->configurator_.reset(new TestDataReductionProxyConfig());
149}
150
151// Explicitly generate required instantiations.
152template void
153DataReductionProxySettingsTestBase::ResetSettings<DataReductionProxySettings>(
154    bool allowed,
155    bool fallback_allowed,
156    bool alt_allowed,
157    bool promo_allowed,
158    bool holdback);
159
160template <class C>
161void DataReductionProxySettingsTestBase::SetProbeResult(
162    const std::string& test_url,
163    const std::string& warmup_test_url,
164    const std::string& response,
165    ProbeURLFetchResult result,
166    bool success,
167    int expected_calls)  {
168  MockDataReductionProxySettings<C>* settings =
169      static_cast<MockDataReductionProxySettings<C>*>(settings_.get());
170  if (0 == expected_calls) {
171    EXPECT_CALL(*settings, GetURLFetcherForAvailabilityCheck()).Times(0);
172    EXPECT_CALL(*settings, GetURLFetcherForWarmup()).Times(0);
173    EXPECT_CALL(*settings, RecordProbeURLFetchResult(_)).Times(0);
174  } else {
175    EXPECT_CALL(*settings, RecordProbeURLFetchResult(result)).Times(1);
176    EXPECT_CALL(*settings, GetURLFetcherForAvailabilityCheck())
177        .Times(expected_calls)
178        .WillRepeatedly(Return(new net::FakeURLFetcher(
179            GURL(test_url),
180            settings,
181            response,
182            success ? net::HTTP_OK : net::HTTP_INTERNAL_SERVER_ERROR,
183            success ? net::URLRequestStatus::SUCCESS :
184                      net::URLRequestStatus::FAILED)));
185    EXPECT_CALL(*settings, GetURLFetcherForWarmup())
186        .Times(expected_calls)
187        .WillRepeatedly(Return(new net::FakeURLFetcher(
188            GURL(warmup_test_url),
189            settings,
190            "",
191            success ? net::HTTP_NO_CONTENT : net::HTTP_INTERNAL_SERVER_ERROR,
192                success ? net::URLRequestStatus::SUCCESS :
193                          net::URLRequestStatus::FAILED)));
194  }
195}
196
197// Explicitly generate required instantiations.
198template void
199DataReductionProxySettingsTestBase::SetProbeResult<DataReductionProxySettings>(
200    const std::string& test_url,
201    const std::string& warmup_test_url,
202    const std::string& response,
203    ProbeURLFetchResult result,
204    bool success,
205    int expected_calls);
206
207void DataReductionProxySettingsTestBase::CheckProxyConfigs(
208    bool expected_enabled,
209    bool expected_restricted,
210    bool expected_fallback_restricted) {
211  TestDataReductionProxyConfig* config =
212      static_cast<TestDataReductionProxyConfig*>(
213          settings_->configurator_.get());
214  ASSERT_EQ(expected_restricted, config->restricted_);
215  ASSERT_EQ(expected_fallback_restricted, config->fallback_restricted_);
216  ASSERT_EQ(expected_enabled, config->enabled_);
217}
218
219void DataReductionProxySettingsTestBase::CheckProbe(
220    bool initially_enabled,
221    const std::string& probe_url,
222    const std::string& warmup_url,
223    const std::string& response,
224    bool request_succeeded,
225    bool expected_enabled,
226    bool expected_restricted,
227    bool expected_fallback_restricted) {
228  pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled,
229                           initially_enabled);
230  if (initially_enabled)
231    settings_->enabled_by_user_ = true;
232  settings_->restricted_by_carrier_ = false;
233  SetProbeResult(probe_url,
234                 warmup_url,
235                 response,
236                 FetchResult(initially_enabled,
237                             request_succeeded && (response == "OK")),
238                 request_succeeded,
239                 initially_enabled ? 1 : 0);
240  settings_->MaybeActivateDataReductionProxy(false);
241  base::MessageLoop::current()->RunUntilIdle();
242  CheckProxyConfigs(expected_enabled,
243                    expected_restricted,
244                    expected_fallback_restricted);
245}
246
247void DataReductionProxySettingsTestBase::CheckProbeOnIPChange(
248    const std::string& probe_url,
249    const std::string& warmup_url,
250    const std::string& response,
251    bool request_succeeded,
252    bool expected_restricted,
253    bool expected_fallback_restricted) {
254  SetProbeResult(probe_url,
255                 warmup_url,
256                 response,
257                 FetchResult(!settings_->restricted_by_carrier_,
258                             request_succeeded && (response == "OK")),
259                 request_succeeded,
260                 1);
261  settings_->OnIPAddressChanged();
262  base::MessageLoop::current()->RunUntilIdle();
263  CheckProxyConfigs(true, expected_restricted, expected_fallback_restricted);
264}
265
266void DataReductionProxySettingsTestBase::CheckOnPrefChange(
267    bool enabled,
268    bool expected_enabled,
269    bool managed) {
270  // Always have a sucessful probe for pref change tests.
271  SetProbeResult(kProbeURLWithOKResponse,
272                 kWarmupURLWithNoContentResponse,
273                 "OK",
274                 FetchResult(enabled, true),
275                 true,
276                 expected_enabled ? 1 : 0);
277  if (managed) {
278    pref_service_.SetManagedPref(prefs::kDataReductionProxyEnabled,
279                                 new base::FundamentalValue(enabled));
280  } else {
281    pref_service_.SetBoolean(prefs::kDataReductionProxyEnabled, enabled);
282  }
283  base::MessageLoop::current()->RunUntilIdle();
284  // Never expect the proxy to be restricted for pref change tests.
285  CheckProxyConfigs(expected_enabled, false, false);
286}
287
288void DataReductionProxySettingsTestBase::CheckInitDataReductionProxy(
289    bool enabled_at_startup) {
290  base::MessageLoopForUI loop;
291  SetProbeResult(kProbeURLWithOKResponse,
292                 kWarmupURLWithNoContentResponse,
293                 "OK",
294                 FetchResult(enabled_at_startup, true),
295                 true,
296                 enabled_at_startup ? 1 : 0);
297  scoped_ptr<DataReductionProxyConfigurator> configurator(
298      new TestDataReductionProxyConfig());
299  settings_->SetProxyConfigurator(configurator.Pass());
300  scoped_refptr<net::TestURLRequestContextGetter> request_context =
301      new net::TestURLRequestContextGetter(base::MessageLoopProxy::current());
302  settings_->InitDataReductionProxySettings(&pref_service_,
303                                            &pref_service_,
304                                            request_context.get());
305
306  base::MessageLoop::current()->RunUntilIdle();
307  CheckProxyConfigs(enabled_at_startup, false, false);
308}
309
310}  // namespace data_reduction_proxy
311