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

Side by Side Diff: content/browser/loader/async_revalidation_manager_unittest.cc

Issue 1041993004: content::ResourceDispatcherHostImpl changes for stale-while-revalidate (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@s-w-r-yhirano-patch
Patch Set: Remove unnecessary copied comment. Created 5 years, 1 month 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
(Empty)
1 // Copyright 2015 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 "content/browser/loader/async_revalidation_manager.h"
6
7 #include <queue>
8 #include <set>
9
10 #include "base/bind.h"
11 #include "base/callback.h"
12 #include "base/macros.h"
13 #include "base/memory/shared_memory_handle.h"
14 #include "base/pickle.h"
15 #include "base/run_loop.h"
16 #include "content/browser/child_process_security_policy_impl.h"
17 #include "content/browser/loader/resource_dispatcher_host_impl.h"
18 #include "content/browser/loader/resource_message_filter.h"
19 #include "content/common/child_process_host_impl.h"
20 #include "content/common/resource_messages.h"
21 #include "content/public/browser/resource_context.h"
22 #include "content/public/common/appcache_info.h"
23 #include "content/public/common/process_type.h"
24 #include "content/public/common/resource_type.h"
25 #include "content/public/test/test_browser_context.h"
26 #include "content/public/test/test_browser_thread_bundle.h"
27 #include "ipc/ipc_param_traits.h"
28 #include "net/base/load_flags.h"
29 #include "net/base/network_delegate.h"
30 #include "net/http/http_util.h"
31 #include "net/url_request/url_request.h"
32 #include "net/url_request/url_request_job.h"
33 #include "net/url_request/url_request_job_factory.h"
34 #include "net/url_request/url_request_test_job.h"
35 #include "net/url_request/url_request_test_util.h"
36 #include "testing/gtest/include/gtest/gtest.h"
37 #include "ui/base/page_transition_types.h"
38 #include "url/gurl.h"
39
40 namespace content {
41
42 namespace {
43
44 // This class is a variation on URLRequestTestJob that
45 // returns ERR_IO_PENDING before every read, not just the first one.
46 class URLRequestTestDelayedCompletionJob : public net::URLRequestTestJob {
47 public:
48 URLRequestTestDelayedCompletionJob(net::URLRequest* request,
49 net::NetworkDelegate* network_delegate,
50 const std::string& response_headers,
51 const std::string& response_data)
52 : net::URLRequestTestJob(request,
53 network_delegate,
54 response_headers,
55 response_data,
56 false) {}
57
58 private:
59 ~URLRequestTestDelayedCompletionJob() override {}
60
61 bool NextReadAsync() override { return true; }
62
63 DISALLOW_COPY_AND_ASSIGN(URLRequestTestDelayedCompletionJob);
64 };
65
66 class TestURLRequestJobFactory : public net::URLRequestJobFactory {
67 public:
68 TestURLRequestJobFactory() = default;
69
70 void HandleScheme(const std::string& scheme) {
71 supported_schemes_.insert(scheme);
72 }
73
74 // Sets the contents of the response. |headers| should have "\n" as line
75 // breaks and end in "\n\n".
76 void SetResponse(const std::string& headers, const std::string& data) {
77 response_headers_ =
78 net::HttpUtil::AssembleRawHeaders(headers.data(), headers.size());
79 response_data_ = data;
80 }
81
82 using URLRequestJobCreateCallback =
83 base::Callback<net::URLRequestJob*(net::URLRequest*,
84 net::NetworkDelegate*)>;
85
86 void SetCustomURLRequestJobCreateCallback(
87 const URLRequestJobCreateCallback& callback) {
88 custom_url_request_job_create_callback_ = callback;
89 }
90
91 net::URLRequestJob* MaybeCreateJobWithProtocolHandler(
92 const std::string& scheme,
93 net::URLRequest* request,
94 net::NetworkDelegate* network_delegate) const override {
95 if (!custom_url_request_job_create_callback_.is_null()) {
96 return custom_url_request_job_create_callback_.Run(request,
97 network_delegate);
98 }
99
100 return new URLRequestTestDelayedCompletionJob(
101 request, network_delegate, response_headers_, response_data_);
102 }
103
104 net::URLRequestJob* MaybeInterceptRedirect(
105 net::URLRequest* request,
106 net::NetworkDelegate* network_delegate,
107 const GURL& location) const override {
108 return nullptr;
109 }
110
111 net::URLRequestJob* MaybeInterceptResponse(
112 net::URLRequest* request,
113 net::NetworkDelegate* network_delegate) const override {
114 return nullptr;
115 }
116
117 bool IsHandledProtocol(const std::string& scheme) const override {
118 return supported_schemes_.count(scheme) > 0;
119 }
120
121 bool IsHandledURL(const GURL& url) const override {
122 return supported_schemes_.count(url.scheme()) > 0;
123 }
124
125 bool IsSafeRedirectTarget(const GURL& location) const override {
126 return false;
127 }
128
129 private:
130 std::string response_headers_;
131 std::string response_data_;
132 std::set<std::string> supported_schemes_;
133 URLRequestJobCreateCallback custom_url_request_job_create_callback_;
134
135 DISALLOW_COPY_AND_ASSIGN(TestURLRequestJobFactory);
136 };
137
138 // On Windows, ResourceMsg_SetDataBuffer supplies a HANDLE which is not
139 // automatically released.
140 //
141 // See ResourceDispatcher::ReleaseResourcesInDataMessage.
142 //
143 // TODO(ricea): Maybe share this implementation with
144 // resource_dispatcher_host_unittest.cc
145 void ReleaseHandlesInMessage(const IPC::Message& message) {
146 if (message.type() == ResourceMsg_SetDataBuffer::ID) {
147 base::PickleIterator iter(message);
148 int request_id;
149 CHECK(iter.ReadInt(&request_id));
150 base::SharedMemoryHandle shm_handle;
151 if (IPC::ParamTraits<base::SharedMemoryHandle>::Read(&message, &iter,
152 &shm_handle)) {
153 if (base::SharedMemory::IsHandleValid(shm_handle))
154 base::SharedMemory::CloseHandle(shm_handle);
155 }
156 }
157 }
158
159 // This filter just deletes any messages that are sent through it.
160 class BlackholeFilter : public ResourceMessageFilter {
161 public:
162 explicit BlackholeFilter(ResourceContext* resource_context)
163 : ResourceMessageFilter(
164 ChildProcessHostImpl::GenerateChildProcessUniqueId(),
165 PROCESS_TYPE_RENDERER,
166 nullptr,
167 nullptr,
168 nullptr,
169 nullptr,
170 nullptr,
171 base::Bind(&BlackholeFilter::GetContexts, base::Unretained(this))),
172 resource_context_(resource_context) {
173 ChildProcessSecurityPolicyImpl::GetInstance()->Add(child_id());
174 }
175
176 bool Send(IPC::Message* msg) override {
177 ReleaseHandlesInMessage(*msg);
178 delete msg;
179 return true;
180 }
181
182 private:
183 ~BlackholeFilter() override {
184 ChildProcessSecurityPolicyImpl::GetInstance()->Remove(child_id());
185 }
186
187 void GetContexts(const ResourceHostMsg_Request& request,
188 ResourceContext** resource_context,
189 net::URLRequestContext** request_context) {
190 *resource_context = resource_context_;
191 *request_context = resource_context_->GetRequestContext();
192 }
193
194 ResourceContext* resource_context_;
195
196 DISALLOW_COPY_AND_ASSIGN(BlackholeFilter);
197 };
198
199 ResourceHostMsg_Request CreateResourceRequest(const char* method,
200 ResourceType type,
201 const GURL& url) {
202 ResourceHostMsg_Request request;
203 request.method = std::string(method);
204 request.url = url;
205 request.first_party_for_cookies = url; // bypass third-party cookie blocking
206 request.referrer_policy = blink::WebReferrerPolicyDefault;
207 request.load_flags = 0;
208 request.origin_pid = 0;
209 request.resource_type = type;
210 request.request_context = 0;
211 request.appcache_host_id = kAppCacheNoHostId;
212 request.download_to_file = false;
213 request.should_reset_appcache = false;
214 request.is_main_frame = true;
215 request.parent_is_main_frame = false;
216 request.parent_render_frame_id = -1;
217 request.transition_type = ui::PAGE_TRANSITION_LINK;
218 request.allow_download = true;
219 return request;
220 }
221
222 } // namespace
223
224 class AsyncRevalidationManagerTest : public ::testing::Test {
225 protected:
226 AsyncRevalidationManagerTest(
227 scoped_ptr<net::TestNetworkDelegate> network_delegate)
228 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
229 network_delegate_(network_delegate.Pass()) {
230 browser_context_.reset(new TestBrowserContext());
231 BrowserContext::EnsureResourceContextInitialized(browser_context_.get());
232 base::RunLoop().RunUntilIdle();
233 ResourceContext* resource_context = browser_context_->GetResourceContext();
234 filter_ = new BlackholeFilter(resource_context);
235 net::URLRequestContext* request_context =
236 resource_context->GetRequestContext();
237 job_factory_.reset(new TestURLRequestJobFactory);
238 request_context->set_job_factory(job_factory_.get());
239 request_context->set_network_delegate(network_delegate_.get());
240 host_.EnableStaleWhileRevalidateForTesting();
241 }
242
243 AsyncRevalidationManagerTest()
244 : AsyncRevalidationManagerTest(
245 make_scoped_ptr(new net::TestNetworkDelegate)) {}
246
247 void TearDown() override {
248 host_.CancelRequestsForProcess(filter_->child_id());
249 host_.Shutdown();
250 host_.CancelRequestsForContext(browser_context_->GetResourceContext());
251 browser_context_.reset();
252 base::RunLoop().RunUntilIdle();
253 }
254
255 void HandleScheme(const std::string& scheme) {
256 job_factory_->HandleScheme(scheme);
257 EnsureSchemeIsAllowed(scheme);
258 }
259
260 void SetResponse(const std::string& headers, const std::string& data) {
261 job_factory_->SetResponse(headers, data);
262 }
263
264 void SetCustomURLRequestJobCreateCallback(
265 const TestURLRequestJobFactory::URLRequestJobCreateCallback& callback) {
266 job_factory_->SetCustomURLRequestJobCreateCallback(callback);
267 }
268
269 // Creates a request using the current test object as the filter and
270 // SubResource as the resource type.
271 void MakeTestRequest(int render_view_id, int request_id, const GURL& url) {
272 ResourceHostMsg_Request request =
273 CreateResourceRequest("GET", RESOURCE_TYPE_SUB_RESOURCE, url);
274 ResourceHostMsg_RequestResource msg(render_view_id, request_id, request);
275 host_.OnMessageReceived(msg, filter_.get());
276 base::RunLoop().RunUntilIdle();
277 }
278
279 void EnsureSchemeIsAllowed(const std::string& scheme) {
280 ChildProcessSecurityPolicyImpl* policy =
281 ChildProcessSecurityPolicyImpl::GetInstance();
282 if (!policy->IsWebSafeScheme(scheme))
283 policy->RegisterWebSafeScheme(scheme);
284 }
285
286 net::TestNetworkDelegate* network_delegate() {
287 return network_delegate_.get();
288 }
289
290 content::TestBrowserThreadBundle thread_bundle_;
291 scoped_ptr<TestBrowserContext> browser_context_;
292 scoped_ptr<TestURLRequestJobFactory> job_factory_;
293 scoped_refptr<BlackholeFilter> filter_;
294 scoped_ptr<net::TestNetworkDelegate> network_delegate_;
295 ResourceDispatcherHostImpl host_;
296 };
297
298 TEST_F(AsyncRevalidationManagerTest, SupportsAsyncRevalidation) {
299 // Scheme has to be HTTP or HTTPS to support async revalidation.
300 HandleScheme("http");
301 SetResponse(net::URLRequestTestJob::test_headers(), "delay complete");
302 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
303
304 net::URLRequest* url_request(
305 host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
306 ASSERT_TRUE(url_request);
307
308 EXPECT_TRUE(url_request->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION);
309 }
310
311 TEST_F(AsyncRevalidationManagerTest, AsyncRevalidationNotSupportedForPOST) {
312 // Scheme has to be HTTP or HTTPS to support async revalidation.
313 HandleScheme("http");
314 SetResponse(net::URLRequestTestJob::test_headers(), "delay complete");
315 // Create POST request.
316 ResourceHostMsg_Request request = CreateResourceRequest(
317 "POST", RESOURCE_TYPE_SUB_RESOURCE, GURL("http://example.com/baz.php"));
318 ResourceHostMsg_RequestResource msg(0, 1, request);
319 host_.OnMessageReceived(msg, filter_.get());
320 base::RunLoop().RunUntilIdle();
321
322 net::URLRequest* url_request(
323 host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
324 ASSERT_TRUE(url_request);
325
326 EXPECT_FALSE(url_request->load_flags() &
327 net::LOAD_SUPPORT_ASYNC_REVALIDATION);
328 }
329
330 TEST_F(AsyncRevalidationManagerTest, AsyncRevalidationNotSupportedForRedirect) {
331 static const char kRedirectHeaders[] =
332 "HTTP/1.1 302 MOVED\n"
333 "Location: http://example.com/var\n"
334 "\n";
335 // Scheme has to be HTTP or HTTPS to support async revalidation.
336 HandleScheme("http");
337 SetResponse(kRedirectHeaders, "");
338
339 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
340
341 net::URLRequest* url_request(
342 host_.GetURLRequest(GlobalRequestID(filter_->child_id(), 1)));
343 ASSERT_TRUE(url_request);
344
345 EXPECT_FALSE(url_request->load_flags() &
346 net::LOAD_SUPPORT_ASYNC_REVALIDATION);
347 }
348
349 // A URLRequestJob implementation which sets the |async_revalidation_required|
350 // flag on the HttpResponseInfo object to true if the request has the
351 // LOAD_SUPPORT_ASYNC_REVALIDATION flag.
352 class AsyncRevalidationRequiredURLRequestTestJob
353 : public net::URLRequestTestJob {
354 public:
355 // The Create() method is useful for wrapping the construction of the object
356 // in a Callback.
357 static net::URLRequestJob* Create(net::URLRequest* request,
358 net::NetworkDelegate* network_delegate) {
359 return new AsyncRevalidationRequiredURLRequestTestJob(request,
360 network_delegate);
361 }
362
363 void GetResponseInfo(net::HttpResponseInfo* info) override {
364 if (request()->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION)
365 info->async_revalidation_required = true;
366 }
367
368 private:
369 AsyncRevalidationRequiredURLRequestTestJob(
370 net::URLRequest* request,
371 net::NetworkDelegate* network_delegate)
372 : URLRequestTestJob(request,
373 network_delegate,
374 net::URLRequestTestJob::test_headers(),
375 std::string(),
376 false) {}
377
378 ~AsyncRevalidationRequiredURLRequestTestJob() override {}
379
380 DISALLOW_COPY_AND_ASSIGN(AsyncRevalidationRequiredURLRequestTestJob);
381 };
382
383 // A URLRequestJob implementation which serves a redirect and sets the
384 // |async_revalidation_required| flag on the HttpResponseInfo object to true if
385 // the request has the LOAD_SUPPORT_ASYNC_REVALIDATION flag.
386 class RedirectAndRevalidateURLRequestTestJob : public net::URLRequestTestJob {
387 public:
388 // The Create() method is useful for wrapping the construction of the object
389 // in a Callback.
390 static net::URLRequestJob* Create(net::URLRequest* request,
391 net::NetworkDelegate* network_delegate) {
392 return new RedirectAndRevalidateURLRequestTestJob(request,
393 network_delegate);
394 }
395
396 void GetResponseInfo(net::HttpResponseInfo* info) override {
397 URLRequestTestJob::GetResponseInfo(info);
398 if (request()->load_flags() & net::LOAD_SUPPORT_ASYNC_REVALIDATION)
399 info->async_revalidation_required = true;
400 }
401
402 private:
403 RedirectAndRevalidateURLRequestTestJob(net::URLRequest* request,
404 net::NetworkDelegate* network_delegate)
405 : URLRequestTestJob(request,
406 network_delegate,
407 std::string(CreateRedirectHeaders()),
408 std::string(),
409 false) {}
410
411 ~RedirectAndRevalidateURLRequestTestJob() override {}
412
413 static std::string CreateRedirectHeaders() {
414 static const char kRedirectHeaders[] =
415 "HTTP/1.1 302 MOVED\0"
416 "Location: http://example.com/var\0"
417 "\0";
418 return std::string(kRedirectHeaders, arraysize(kRedirectHeaders));
419 }
420
421 DISALLOW_COPY_AND_ASSIGN(RedirectAndRevalidateURLRequestTestJob);
422 };
423
424 // A NetworkDelegate that records the URLRequests as they are created.
425 class URLRequestRecordingNetworkDelegate : public net::TestNetworkDelegate {
426 public:
427 URLRequestRecordingNetworkDelegate() : requests_() {}
428
429 net::URLRequest* NextRequest() {
430 if (requests_.empty())
431 return nullptr;
432 net::URLRequest* request = requests_.front();
433 requests_.pop();
434 return request;
435 }
436
437 bool IsEmpty() { return requests_.empty(); }
438
439 int OnBeforeURLRequest(net::URLRequest* request,
440 const net::CompletionCallback& callback,
441 GURL* new_url) override {
442 requests_.push(request);
443 return TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
444 }
445
446 private:
447 std::queue<net::URLRequest*> requests_;
448
449 DISALLOW_COPY_AND_ASSIGN(URLRequestRecordingNetworkDelegate);
450 };
451
452 class AsyncRevalidationManagerRecordingTest
453 : public AsyncRevalidationManagerTest {
454 public:
455 AsyncRevalidationManagerRecordingTest()
456 : AsyncRevalidationManagerTest(
457 make_scoped_ptr(new URLRequestRecordingNetworkDelegate)) {
458 // Scheme has to be HTTP or HTTPS to support async revalidation.
459 HandleScheme("http");
460 // Use the AsyncRevalidationRequiredURLRequestTestJob.
461 SetCustomURLRequestJobCreateCallback(
462 base::Bind(&AsyncRevalidationRequiredURLRequestTestJob::Create));
463 }
464
465 URLRequestRecordingNetworkDelegate* recording_network_delegate() {
466 return static_cast<URLRequestRecordingNetworkDelegate*>(network_delegate());
467 }
468
469 net::URLRequest* NextRequest() {
470 return recording_network_delegate()->NextRequest();
471 }
472
473 bool IsEmpty() { return recording_network_delegate()->IsEmpty(); }
474 };
475
476 // Verify that an async revalidation is actually created when needed.
477 TEST_F(AsyncRevalidationManagerRecordingTest, Issued) {
478 // Create the original request.
479 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
480
481 net::URLRequest* initial_request = NextRequest();
482 ASSERT_TRUE(initial_request);
483 EXPECT_TRUE(initial_request->load_flags() &
484 net::LOAD_SUPPORT_ASYNC_REVALIDATION);
485
486 net::URLRequest* async_request = NextRequest();
487 ASSERT_TRUE(async_request);
488 }
489
490 // Verify the the URL of the async revalidation matches the original request.
491 TEST_F(AsyncRevalidationManagerRecordingTest, URLMatches) {
492 // Create the original request.
493 MakeTestRequest(0, 1, GURL("http://example.com/special-baz"));
494
495 // Discard the original request.
496 NextRequest();
497
498 net::URLRequest* async_request = NextRequest();
499 ASSERT_TRUE(async_request);
500 EXPECT_EQ(GURL("http://example.com/special-baz"), async_request->url());
501 }
502
503 TEST_F(AsyncRevalidationManagerRecordingTest,
504 AsyncRevalidationsDoNotSupportAsyncRevalidation) {
505 // Create the original request.
506 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
507
508 // Discard the original request.
509 NextRequest();
510
511 // Get the async revalidation request.
512 net::URLRequest* async_request = NextRequest();
513 ASSERT_TRUE(async_request);
514 EXPECT_FALSE(async_request->load_flags() &
515 net::LOAD_SUPPORT_ASYNC_REVALIDATION);
516 }
517
518 TEST_F(AsyncRevalidationManagerRecordingTest, AsyncRevalidationsNotDuplicated) {
519 // Create the original request.
520 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
521
522 // Discard the original request.
523 NextRequest();
524
525 // Get the async revalidation request.
526 net::URLRequest* async_request = NextRequest();
527 EXPECT_TRUE(async_request);
528
529 // Start a second request to the same URL.
530 MakeTestRequest(0, 2, GURL("http://example.com/baz"));
531
532 // Discard the second request.
533 NextRequest();
534
535 // There should not be another async revalidation request.
536 EXPECT_TRUE(IsEmpty());
537 }
538
539 // Async revalidation to different URLs should not be treated as duplicates.
540 TEST_F(AsyncRevalidationManagerRecordingTest,
541 AsyncRevalidationsToSeparateURLsAreSeparate) {
542 // Create two requests to two URLs.
543 MakeTestRequest(0, 1, GURL("http://example.com/baz"));
544 MakeTestRequest(0, 2, GURL("http://example.com/far"));
545
546 net::URLRequest* initial_request = NextRequest();
547 ASSERT_TRUE(initial_request);
548 net::URLRequest* initial_async_revalidation = NextRequest();
549 ASSERT_TRUE(initial_async_revalidation);
550 net::URLRequest* second_request = NextRequest();
551 ASSERT_TRUE(second_request);
552 net::URLRequest* second_async_revalidation = NextRequest();
553 ASSERT_TRUE(second_async_revalidation);
554
555 EXPECT_EQ("http://example.com/baz", initial_request->url().spec());
556 EXPECT_EQ("http://example.com/baz", initial_async_revalidation->url().spec());
557 EXPECT_EQ("http://example.com/far", second_request->url().spec());
558 EXPECT_EQ("http://example.com/far", second_async_revalidation->url().spec());
559 }
560
561 // A stale-while-revalidate applicable redirect response should not result in an
562 // async revalidation.
563 TEST_F(AsyncRevalidationManagerRecordingTest, RedirectNotApplicable) {
564 // Use the appropriate URLRequestJob for the test.
565 SetCustomURLRequestJobCreateCallback(
566 base::Bind(&RedirectAndRevalidateURLRequestTestJob::Create));
567 MakeTestRequest(0, 1, GURL("http://example.com/redirect"));
568
569 net::URLRequest* initial_request = NextRequest();
570 EXPECT_TRUE(initial_request);
571
572 // There should not be an async revalidation request.
573 EXPECT_TRUE(IsEmpty());
574 }
575
576 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698