Dismiss autofill popup on screen orientation change.
[chromium-blink-merge.git] / net / proxy / proxy_script_fetcher_impl_unittest.cc
blob8d42514a957ff55cf136306cbc7ae61d095f258a
1 // Copyright (c) 2012 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.
5 #include "net/proxy/proxy_script_fetcher_impl.h"
7 #include <string>
9 #include "base/compiler_specific.h"
10 #include "base/files/file_path.h"
11 #include "base/path_service.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "net/base/load_flags.h"
14 #include "net/base/net_util.h"
15 #include "net/base/test_completion_callback.h"
16 #include "net/cert/mock_cert_verifier.h"
17 #include "net/disk_cache/disk_cache.h"
18 #include "net/dns/mock_host_resolver.h"
19 #include "net/http/http_cache.h"
20 #include "net/http/http_network_session.h"
21 #include "net/http/http_server_properties_impl.h"
22 #include "net/http/transport_security_state.h"
23 #include "net/ssl/ssl_config_service_defaults.h"
24 #include "net/test/spawned_test_server/spawned_test_server.h"
25 #include "net/url_request/file_protocol_handler.h"
26 #include "net/url_request/url_request_context_storage.h"
27 #include "net/url_request/url_request_file_job.h"
28 #include "net/url_request/url_request_job_factory_impl.h"
29 #include "net/url_request/url_request_test_util.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31 #include "testing/platform_test.h"
33 namespace net {
35 // TODO(eroman):
36 // - Test canceling an outstanding request.
37 // - Test deleting ProxyScriptFetcher while a request is in progress.
39 namespace {
41 const base::FilePath::CharType kDocRoot[] =
42 FILE_PATH_LITERAL("net/data/proxy_script_fetcher_unittest");
44 struct FetchResult {
45 int code;
46 base::string16 text;
49 // A non-mock URL request which can access http:// and file:// urls.
50 class RequestContext : public URLRequestContext {
51 public:
52 RequestContext() : storage_(this) {
53 ProxyConfig no_proxy;
54 storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver));
55 storage_.set_cert_verifier(new MockCertVerifier);
56 storage_.set_transport_security_state(new TransportSecurityState);
57 storage_.set_proxy_service(ProxyService::CreateFixed(no_proxy));
58 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
59 storage_.set_http_server_properties(
60 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
62 HttpNetworkSession::Params params;
63 params.host_resolver = host_resolver();
64 params.cert_verifier = cert_verifier();
65 params.transport_security_state = transport_security_state();
66 params.proxy_service = proxy_service();
67 params.ssl_config_service = ssl_config_service();
68 params.http_server_properties = http_server_properties();
69 scoped_refptr<HttpNetworkSession> network_session(
70 new HttpNetworkSession(params));
71 storage_.set_http_transaction_factory(new HttpCache(
72 network_session.get(), HttpCache::DefaultBackend::InMemory(0)));
73 URLRequestJobFactoryImpl* job_factory = new URLRequestJobFactoryImpl();
74 job_factory->SetProtocolHandler("file", new FileProtocolHandler());
75 storage_.set_job_factory(job_factory);
78 virtual ~RequestContext() {
81 private:
82 URLRequestContextStorage storage_;
85 // Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest.
86 GURL GetTestFileUrl(const std::string& relpath) {
87 base::FilePath path;
88 PathService::Get(base::DIR_SOURCE_ROOT, &path);
89 path = path.AppendASCII("net");
90 path = path.AppendASCII("data");
91 path = path.AppendASCII("proxy_script_fetcher_unittest");
92 GURL base_url = FilePathToFileURL(path);
93 return GURL(base_url.spec() + "/" + relpath);
96 // Really simple NetworkDelegate so we can allow local file access on ChromeOS
97 // without introducing layering violations. Also causes a test failure if a
98 // request is seen that doesn't set a load flag to bypass revocation checking.
100 class BasicNetworkDelegate : public NetworkDelegate {
101 public:
102 BasicNetworkDelegate() {}
103 virtual ~BasicNetworkDelegate() {}
105 private:
106 virtual int OnBeforeURLRequest(URLRequest* request,
107 const CompletionCallback& callback,
108 GURL* new_url) OVERRIDE {
109 EXPECT_TRUE(request->load_flags() & LOAD_DISABLE_CERT_REVOCATION_CHECKING);
110 return OK;
113 virtual int OnBeforeSendHeaders(URLRequest* request,
114 const CompletionCallback& callback,
115 HttpRequestHeaders* headers) OVERRIDE {
116 return OK;
119 virtual void OnSendHeaders(URLRequest* request,
120 const HttpRequestHeaders& headers) OVERRIDE {}
122 virtual int OnHeadersReceived(
123 URLRequest* request,
124 const CompletionCallback& callback,
125 const HttpResponseHeaders* original_response_headers,
126 scoped_refptr<HttpResponseHeaders>* override_response_headers)
127 OVERRIDE {
128 return OK;
131 virtual void OnBeforeRedirect(URLRequest* request,
132 const GURL& new_location) OVERRIDE {}
134 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {}
136 virtual void OnRawBytesRead(const URLRequest& request,
137 int bytes_read) OVERRIDE {}
139 virtual void OnCompleted(URLRequest* request, bool started) OVERRIDE {}
141 virtual void OnURLRequestDestroyed(URLRequest* request) OVERRIDE {}
143 virtual void OnPACScriptError(int line_number,
144 const base::string16& error) OVERRIDE {}
146 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
147 URLRequest* request,
148 const AuthChallengeInfo& auth_info,
149 const AuthCallback& callback,
150 AuthCredentials* credentials) OVERRIDE {
151 return NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
154 virtual bool OnCanGetCookies(const URLRequest& request,
155 const CookieList& cookie_list) OVERRIDE {
156 return true;
159 virtual bool OnCanSetCookie(const URLRequest& request,
160 const std::string& cookie_line,
161 CookieOptions* options) OVERRIDE {
162 return true;
165 virtual bool OnCanAccessFile(const net::URLRequest& request,
166 const base::FilePath& path) const OVERRIDE {
167 return true;
169 virtual bool OnCanThrottleRequest(const URLRequest& request) const OVERRIDE {
170 return false;
173 virtual int OnBeforeSocketStreamConnect(
174 SocketStream* stream,
175 const CompletionCallback& callback) OVERRIDE {
176 return OK;
179 virtual void OnRequestWaitStateChange(const net::URLRequest& request,
180 RequestWaitState state) OVERRIDE {
183 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
186 } // namespace
188 class ProxyScriptFetcherImplTest : public PlatformTest {
189 public:
190 ProxyScriptFetcherImplTest()
191 : test_server_(SpawnedTestServer::TYPE_HTTP,
192 net::SpawnedTestServer::kLocalhost,
193 base::FilePath(kDocRoot)) {
194 context_.set_network_delegate(&network_delegate_);
197 protected:
198 SpawnedTestServer test_server_;
199 BasicNetworkDelegate network_delegate_;
200 RequestContext context_;
203 TEST_F(ProxyScriptFetcherImplTest, FileUrl) {
204 ProxyScriptFetcherImpl pac_fetcher(&context_);
206 { // Fetch a non-existent file.
207 base::string16 text;
208 TestCompletionCallback callback;
209 int result = pac_fetcher.Fetch(GetTestFileUrl("does-not-exist"),
210 &text, callback.callback());
211 EXPECT_EQ(ERR_IO_PENDING, result);
212 EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult());
213 EXPECT_TRUE(text.empty());
215 { // Fetch a file that exists.
216 base::string16 text;
217 TestCompletionCallback callback;
218 int result = pac_fetcher.Fetch(GetTestFileUrl("pac.txt"),
219 &text, callback.callback());
220 EXPECT_EQ(ERR_IO_PENDING, result);
221 EXPECT_EQ(OK, callback.WaitForResult());
222 EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text);
226 // Note that all mime types are allowed for PAC file, to be consistent
227 // with other browsers.
228 TEST_F(ProxyScriptFetcherImplTest, HttpMimeType) {
229 ASSERT_TRUE(test_server_.Start());
231 ProxyScriptFetcherImpl pac_fetcher(&context_);
233 { // Fetch a PAC with mime type "text/plain"
234 GURL url(test_server_.GetURL("files/pac.txt"));
235 base::string16 text;
236 TestCompletionCallback callback;
237 int result = pac_fetcher.Fetch(url, &text, callback.callback());
238 EXPECT_EQ(ERR_IO_PENDING, result);
239 EXPECT_EQ(OK, callback.WaitForResult());
240 EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text);
242 { // Fetch a PAC with mime type "text/html"
243 GURL url(test_server_.GetURL("files/pac.html"));
244 base::string16 text;
245 TestCompletionCallback callback;
246 int result = pac_fetcher.Fetch(url, &text, callback.callback());
247 EXPECT_EQ(ERR_IO_PENDING, result);
248 EXPECT_EQ(OK, callback.WaitForResult());
249 EXPECT_EQ(ASCIIToUTF16("-pac.html-\n"), text);
251 { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig"
252 GURL url(test_server_.GetURL("files/pac.nsproxy"));
253 base::string16 text;
254 TestCompletionCallback callback;
255 int result = pac_fetcher.Fetch(url, &text, callback.callback());
256 EXPECT_EQ(ERR_IO_PENDING, result);
257 EXPECT_EQ(OK, callback.WaitForResult());
258 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
262 TEST_F(ProxyScriptFetcherImplTest, HttpStatusCode) {
263 ASSERT_TRUE(test_server_.Start());
265 ProxyScriptFetcherImpl pac_fetcher(&context_);
267 { // Fetch a PAC which gives a 500 -- FAIL
268 GURL url(test_server_.GetURL("files/500.pac"));
269 base::string16 text;
270 TestCompletionCallback callback;
271 int result = pac_fetcher.Fetch(url, &text, callback.callback());
272 EXPECT_EQ(ERR_IO_PENDING, result);
273 EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
274 EXPECT_TRUE(text.empty());
276 { // Fetch a PAC which gives a 404 -- FAIL
277 GURL url(test_server_.GetURL("files/404.pac"));
278 base::string16 text;
279 TestCompletionCallback callback;
280 int result = pac_fetcher.Fetch(url, &text, callback.callback());
281 EXPECT_EQ(ERR_IO_PENDING, result);
282 EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
283 EXPECT_TRUE(text.empty());
287 TEST_F(ProxyScriptFetcherImplTest, ContentDisposition) {
288 ASSERT_TRUE(test_server_.Start());
290 ProxyScriptFetcherImpl pac_fetcher(&context_);
292 // Fetch PAC scripts via HTTP with a Content-Disposition header -- should
293 // have no effect.
294 GURL url(test_server_.GetURL("files/downloadable.pac"));
295 base::string16 text;
296 TestCompletionCallback callback;
297 int result = pac_fetcher.Fetch(url, &text, callback.callback());
298 EXPECT_EQ(ERR_IO_PENDING, result);
299 EXPECT_EQ(OK, callback.WaitForResult());
300 EXPECT_EQ(ASCIIToUTF16("-downloadable.pac-\n"), text);
303 // Verifies that PAC scripts are not being cached.
304 TEST_F(ProxyScriptFetcherImplTest, NoCache) {
305 ASSERT_TRUE(test_server_.Start());
307 ProxyScriptFetcherImpl pac_fetcher(&context_);
309 // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour.
310 GURL url(test_server_.GetURL("files/cacheable_1hr.pac"));
312 base::string16 text;
313 TestCompletionCallback callback;
314 int result = pac_fetcher.Fetch(url, &text, callback.callback());
315 EXPECT_EQ(ERR_IO_PENDING, result);
316 EXPECT_EQ(OK, callback.WaitForResult());
317 EXPECT_EQ(ASCIIToUTF16("-cacheable_1hr.pac-\n"), text);
320 // Kill the HTTP server.
321 ASSERT_TRUE(test_server_.Stop());
323 // Try to fetch the file again. Since the server is not running anymore, the
324 // call should fail, thus indicating that the file was not fetched from the
325 // local cache.
327 base::string16 text;
328 TestCompletionCallback callback;
329 int result = pac_fetcher.Fetch(url, &text, callback.callback());
330 EXPECT_EQ(ERR_IO_PENDING, result);
332 // Expect any error. The exact error varies by platform.
333 EXPECT_NE(OK, callback.WaitForResult());
337 TEST_F(ProxyScriptFetcherImplTest, TooLarge) {
338 ASSERT_TRUE(test_server_.Start());
340 ProxyScriptFetcherImpl pac_fetcher(&context_);
342 // Set the maximum response size to 50 bytes.
343 int prev_size = pac_fetcher.SetSizeConstraint(50);
345 // These two URLs are the same file, but are http:// vs file://
346 GURL urls[] = {
347 test_server_.GetURL("files/large-pac.nsproxy"),
348 GetTestFileUrl("large-pac.nsproxy")
351 // Try fetching URLs that are 101 bytes large. We should abort the request
352 // after 50 bytes have been read, and fail with a too large error.
353 for (size_t i = 0; i < arraysize(urls); ++i) {
354 const GURL& url = urls[i];
355 base::string16 text;
356 TestCompletionCallback callback;
357 int result = pac_fetcher.Fetch(url, &text, callback.callback());
358 EXPECT_EQ(ERR_IO_PENDING, result);
359 EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult());
360 EXPECT_TRUE(text.empty());
363 // Restore the original size bound.
364 pac_fetcher.SetSizeConstraint(prev_size);
366 { // Make sure we can still fetch regular URLs.
367 GURL url(test_server_.GetURL("files/pac.nsproxy"));
368 base::string16 text;
369 TestCompletionCallback callback;
370 int result = pac_fetcher.Fetch(url, &text, callback.callback());
371 EXPECT_EQ(ERR_IO_PENDING, result);
372 EXPECT_EQ(OK, callback.WaitForResult());
373 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
377 TEST_F(ProxyScriptFetcherImplTest, Hang) {
378 ASSERT_TRUE(test_server_.Start());
380 ProxyScriptFetcherImpl pac_fetcher(&context_);
382 // Set the timeout period to 0.5 seconds.
383 base::TimeDelta prev_timeout = pac_fetcher.SetTimeoutConstraint(
384 base::TimeDelta::FromMilliseconds(500));
386 // Try fetching a URL which takes 1.2 seconds. We should abort the request
387 // after 500 ms, and fail with a timeout error.
389 GURL url(test_server_.GetURL("slow/proxy.pac?1.2"));
390 base::string16 text;
391 TestCompletionCallback callback;
392 int result = pac_fetcher.Fetch(url, &text, callback.callback());
393 EXPECT_EQ(ERR_IO_PENDING, result);
394 EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult());
395 EXPECT_TRUE(text.empty());
398 // Restore the original timeout period.
399 pac_fetcher.SetTimeoutConstraint(prev_timeout);
401 { // Make sure we can still fetch regular URLs.
402 GURL url(test_server_.GetURL("files/pac.nsproxy"));
403 base::string16 text;
404 TestCompletionCallback callback;
405 int result = pac_fetcher.Fetch(url, &text, callback.callback());
406 EXPECT_EQ(ERR_IO_PENDING, result);
407 EXPECT_EQ(OK, callback.WaitForResult());
408 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
412 // The ProxyScriptFetcher should decode any content-codings
413 // (like gzip, bzip, etc.), and apply any charset conversions to yield
414 // UTF8.
415 TEST_F(ProxyScriptFetcherImplTest, Encodings) {
416 ASSERT_TRUE(test_server_.Start());
418 ProxyScriptFetcherImpl pac_fetcher(&context_);
420 // Test a response that is gzip-encoded -- should get inflated.
422 GURL url(test_server_.GetURL("files/gzipped_pac"));
423 base::string16 text;
424 TestCompletionCallback callback;
425 int result = pac_fetcher.Fetch(url, &text, callback.callback());
426 EXPECT_EQ(ERR_IO_PENDING, result);
427 EXPECT_EQ(OK, callback.WaitForResult());
428 EXPECT_EQ(ASCIIToUTF16("This data was gzipped.\n"), text);
431 // Test a response that was served as UTF-16 (BE). It should
432 // be converted to UTF8.
434 GURL url(test_server_.GetURL("files/utf16be_pac"));
435 base::string16 text;
436 TestCompletionCallback callback;
437 int result = pac_fetcher.Fetch(url, &text, callback.callback());
438 EXPECT_EQ(ERR_IO_PENDING, result);
439 EXPECT_EQ(OK, callback.WaitForResult());
440 EXPECT_EQ(ASCIIToUTF16("This was encoded as UTF-16BE.\n"), text);
444 TEST_F(ProxyScriptFetcherImplTest, DataURLs) {
445 ProxyScriptFetcherImpl pac_fetcher(&context_);
447 const char kEncodedUrl[] =
448 "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R"
449 "m9yVVJMKHVybCwgaG9zdCkgewogIGlmIChob3N0ID09ICdmb29iYXIuY29tJykKICAgIHJl"
450 "dHVybiAnUFJPWFkgYmxhY2tob2xlOjgwJzsKICByZXR1cm4gJ0RJUkVDVCc7Cn0=";
451 const char kPacScript[] =
452 "function FindProxyForURL(url, host) {\n"
453 " if (host == 'foobar.com')\n"
454 " return 'PROXY blackhole:80';\n"
455 " return 'DIRECT';\n"
456 "}";
458 // Test fetching a "data:"-url containing a base64 encoded PAC script.
460 GURL url(kEncodedUrl);
461 base::string16 text;
462 TestCompletionCallback callback;
463 int result = pac_fetcher.Fetch(url, &text, callback.callback());
464 EXPECT_EQ(OK, result);
465 EXPECT_EQ(ASCIIToUTF16(kPacScript), text);
468 const char kEncodedUrlBroken[] =
469 "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R";
471 // Test a broken "data:"-url containing a base64 encoded PAC script.
473 GURL url(kEncodedUrlBroken);
474 base::string16 text;
475 TestCompletionCallback callback;
476 int result = pac_fetcher.Fetch(url, &text, callback.callback());
477 EXPECT_EQ(ERR_FAILED, result);
481 } // namespace net