Include all dupe types (event when value is zero) in scan stats.
[chromium-blink-merge.git] / net / http / http_cache_unittest.cc
blob62a3d6ad8f26fb9321d12c17183b53ef94a8d971
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/http/http_cache.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/memory/scoped_vector.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/run_loop.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/test/simple_test_clock.h"
17 #include "net/base/cache_type.h"
18 #include "net/base/elements_upload_data_stream.h"
19 #include "net/base/host_port_pair.h"
20 #include "net/base/load_flags.h"
21 #include "net/base/load_timing_info.h"
22 #include "net/base/load_timing_info_test_util.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/upload_bytes_element_reader.h"
25 #include "net/cert/cert_status_flags.h"
26 #include "net/disk_cache/disk_cache.h"
27 #include "net/http/http_byte_range.h"
28 #include "net/http/http_cache_transaction.h"
29 #include "net/http/http_request_headers.h"
30 #include "net/http/http_request_info.h"
31 #include "net/http/http_response_headers.h"
32 #include "net/http/http_response_info.h"
33 #include "net/http/http_transaction.h"
34 #include "net/http/http_transaction_test_util.h"
35 #include "net/http/http_util.h"
36 #include "net/http/mock_http_cache.h"
37 #include "net/log/test_net_log.h"
38 #include "net/log/test_net_log_entry.h"
39 #include "net/log/test_net_log_util.h"
40 #include "net/socket/client_socket_handle.h"
41 #include "net/ssl/ssl_cert_request_info.h"
42 #include "net/websockets/websocket_handshake_stream_base.h"
43 #include "testing/gtest/include/gtest/gtest.h"
45 using base::Time;
47 namespace net {
49 namespace {
51 // Tests the load timing values of a request that goes through a
52 // MockNetworkTransaction.
53 void TestLoadTimingNetworkRequest(const LoadTimingInfo& load_timing_info) {
54 EXPECT_FALSE(load_timing_info.socket_reused);
55 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
57 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
58 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
60 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
61 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
62 EXPECT_LE(load_timing_info.connect_timing.connect_end,
63 load_timing_info.send_start);
65 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
67 // Set by URLRequest / URLRequestHttpJob, at a higher level.
68 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
69 EXPECT_TRUE(load_timing_info.request_start.is_null());
70 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
73 // Tests the load timing values of a request that receives a cached response.
74 void TestLoadTimingCachedResponse(const LoadTimingInfo& load_timing_info) {
75 EXPECT_FALSE(load_timing_info.socket_reused);
76 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
78 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
79 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
81 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
83 // Only the send start / end times should be sent, and they should have the
84 // same value.
85 EXPECT_FALSE(load_timing_info.send_start.is_null());
86 EXPECT_EQ(load_timing_info.send_start, load_timing_info.send_end);
88 // Set by URLRequest / URLRequestHttpJob, at a higher level.
89 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
90 EXPECT_TRUE(load_timing_info.request_start.is_null());
91 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
94 class DeleteCacheCompletionCallback : public TestCompletionCallbackBase {
95 public:
96 explicit DeleteCacheCompletionCallback(MockHttpCache* cache)
97 : cache_(cache),
98 callback_(base::Bind(&DeleteCacheCompletionCallback::OnComplete,
99 base::Unretained(this))) {
102 const CompletionCallback& callback() const { return callback_; }
104 private:
105 void OnComplete(int result) {
106 delete cache_;
107 SetResult(result);
110 MockHttpCache* cache_;
111 CompletionCallback callback_;
113 DISALLOW_COPY_AND_ASSIGN(DeleteCacheCompletionCallback);
116 //-----------------------------------------------------------------------------
117 // helpers
119 void ReadAndVerifyTransaction(HttpTransaction* trans,
120 const MockTransaction& trans_info) {
121 std::string content;
122 int rv = ReadTransaction(trans, &content);
124 EXPECT_EQ(OK, rv);
125 std::string expected(trans_info.data);
126 EXPECT_EQ(expected, content);
129 void RunTransactionTestBase(HttpCache* cache,
130 const MockTransaction& trans_info,
131 const MockHttpRequest& request,
132 HttpResponseInfo* response_info,
133 const BoundNetLog& net_log,
134 LoadTimingInfo* load_timing_info,
135 int64* received_bytes) {
136 TestCompletionCallback callback;
138 // write to the cache
140 scoped_ptr<HttpTransaction> trans;
141 int rv = cache->CreateTransaction(DEFAULT_PRIORITY, &trans);
142 EXPECT_EQ(OK, rv);
143 ASSERT_TRUE(trans.get());
145 rv = trans->Start(&request, callback.callback(), net_log);
146 if (rv == ERR_IO_PENDING)
147 rv = callback.WaitForResult();
148 ASSERT_EQ(trans_info.return_code, rv);
150 if (OK != rv)
151 return;
153 const HttpResponseInfo* response = trans->GetResponseInfo();
154 ASSERT_TRUE(response);
156 if (response_info)
157 *response_info = *response;
159 if (load_timing_info) {
160 // If a fake network connection is used, need a NetLog to get a fake socket
161 // ID.
162 EXPECT_TRUE(net_log.net_log());
163 *load_timing_info = LoadTimingInfo();
164 trans->GetLoadTimingInfo(load_timing_info);
167 ReadAndVerifyTransaction(trans.get(), trans_info);
169 if (received_bytes)
170 *received_bytes = trans->GetTotalReceivedBytes();
173 void RunTransactionTestWithRequest(HttpCache* cache,
174 const MockTransaction& trans_info,
175 const MockHttpRequest& request,
176 HttpResponseInfo* response_info) {
177 RunTransactionTestBase(cache, trans_info, request, response_info,
178 BoundNetLog(), NULL, NULL);
181 void RunTransactionTestAndGetTiming(HttpCache* cache,
182 const MockTransaction& trans_info,
183 const BoundNetLog& log,
184 LoadTimingInfo* load_timing_info) {
185 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
186 NULL, log, load_timing_info, NULL);
189 void RunTransactionTest(HttpCache* cache, const MockTransaction& trans_info) {
190 RunTransactionTestAndGetTiming(cache, trans_info, BoundNetLog(), NULL);
193 void RunTransactionTestWithLog(HttpCache* cache,
194 const MockTransaction& trans_info,
195 const BoundNetLog& log) {
196 RunTransactionTestAndGetTiming(cache, trans_info, log, NULL);
199 void RunTransactionTestWithResponseInfo(HttpCache* cache,
200 const MockTransaction& trans_info,
201 HttpResponseInfo* response) {
202 RunTransactionTestWithRequest(cache, trans_info, MockHttpRequest(trans_info),
203 response);
206 void RunTransactionTestWithResponseInfoAndGetTiming(
207 HttpCache* cache,
208 const MockTransaction& trans_info,
209 HttpResponseInfo* response,
210 const BoundNetLog& log,
211 LoadTimingInfo* load_timing_info) {
212 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
213 response, log, load_timing_info, NULL);
216 void RunTransactionTestWithResponse(HttpCache* cache,
217 const MockTransaction& trans_info,
218 std::string* response_headers) {
219 HttpResponseInfo response;
220 RunTransactionTestWithResponseInfo(cache, trans_info, &response);
221 response.headers->GetNormalizedHeaders(response_headers);
224 void RunTransactionTestWithResponseAndGetTiming(
225 HttpCache* cache,
226 const MockTransaction& trans_info,
227 std::string* response_headers,
228 const BoundNetLog& log,
229 LoadTimingInfo* load_timing_info) {
230 HttpResponseInfo response;
231 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
232 &response, log, load_timing_info, NULL);
233 response.headers->GetNormalizedHeaders(response_headers);
236 // This class provides a handler for kFastNoStoreGET_Transaction so that the
237 // no-store header can be included on demand.
238 class FastTransactionServer {
239 public:
240 FastTransactionServer() {
241 no_store = false;
243 ~FastTransactionServer() {}
245 void set_no_store(bool value) { no_store = value; }
247 static void FastNoStoreHandler(const HttpRequestInfo* request,
248 std::string* response_status,
249 std::string* response_headers,
250 std::string* response_data) {
251 if (no_store)
252 *response_headers = "Cache-Control: no-store\n";
255 private:
256 static bool no_store;
257 DISALLOW_COPY_AND_ASSIGN(FastTransactionServer);
259 bool FastTransactionServer::no_store;
261 const MockTransaction kFastNoStoreGET_Transaction = {
262 "http://www.google.com/nostore",
263 "GET",
264 base::Time(),
266 LOAD_VALIDATE_CACHE,
267 "HTTP/1.1 200 OK",
268 "Cache-Control: max-age=10000\n",
269 base::Time(),
270 "<html><body>Google Blah Blah</body></html>",
271 TEST_MODE_SYNC_NET_START,
272 &FastTransactionServer::FastNoStoreHandler,
274 OK};
276 // This class provides a handler for kRangeGET_TransactionOK so that the range
277 // request can be served on demand.
278 class RangeTransactionServer {
279 public:
280 RangeTransactionServer() {
281 not_modified_ = false;
282 modified_ = false;
283 bad_200_ = false;
285 ~RangeTransactionServer() {
286 not_modified_ = false;
287 modified_ = false;
288 bad_200_ = false;
291 // Returns only 416 or 304 when set.
292 void set_not_modified(bool value) { not_modified_ = value; }
294 // Returns 206 when revalidating a range (instead of 304).
295 void set_modified(bool value) { modified_ = value; }
297 // Returns 200 instead of 206 (a malformed response overall).
298 void set_bad_200(bool value) { bad_200_ = value; }
300 // Other than regular range related behavior (and the flags mentioned above),
301 // the server reacts to requests headers like so:
302 // X-Require-Mock-Auth -> return 401.
303 // X-Require-Mock-Auth-Alt -> return 401.
304 // X-Return-Default-Range -> assume 40-49 was requested.
305 // The -Alt variant doesn't cause the MockNetworkTransaction to
306 // report that it IsReadyToRestartForAuth().
307 static void RangeHandler(const HttpRequestInfo* request,
308 std::string* response_status,
309 std::string* response_headers,
310 std::string* response_data);
312 private:
313 static bool not_modified_;
314 static bool modified_;
315 static bool bad_200_;
316 DISALLOW_COPY_AND_ASSIGN(RangeTransactionServer);
318 bool RangeTransactionServer::not_modified_ = false;
319 bool RangeTransactionServer::modified_ = false;
320 bool RangeTransactionServer::bad_200_ = false;
322 // A dummy extra header that must be preserved on a given request.
324 // EXTRA_HEADER_LINE doesn't include a line terminator because it
325 // will be passed to AddHeaderFromString() which doesn't accept them.
326 #define EXTRA_HEADER_LINE "Extra: header"
328 // EXTRA_HEADER contains a line terminator, as expected by
329 // AddHeadersFromString() (_not_ AddHeaderFromString()).
330 #define EXTRA_HEADER EXTRA_HEADER_LINE "\r\n"
332 static const char kExtraHeaderKey[] = "Extra";
334 // Static.
335 void RangeTransactionServer::RangeHandler(const HttpRequestInfo* request,
336 std::string* response_status,
337 std::string* response_headers,
338 std::string* response_data) {
339 if (request->extra_headers.IsEmpty()) {
340 response_status->assign("HTTP/1.1 416 Requested Range Not Satisfiable");
341 response_data->clear();
342 return;
345 // We want to make sure we don't delete extra headers.
346 EXPECT_TRUE(request->extra_headers.HasHeader(kExtraHeaderKey));
348 bool require_auth =
349 request->extra_headers.HasHeader("X-Require-Mock-Auth") ||
350 request->extra_headers.HasHeader("X-Require-Mock-Auth-Alt");
352 if (require_auth && !request->extra_headers.HasHeader("Authorization")) {
353 response_status->assign("HTTP/1.1 401 Unauthorized");
354 response_data->assign("WWW-Authenticate: Foo\n");
355 return;
358 if (not_modified_) {
359 response_status->assign("HTTP/1.1 304 Not Modified");
360 response_data->clear();
361 return;
364 std::vector<HttpByteRange> ranges;
365 std::string range_header;
366 if (!request->extra_headers.GetHeader(HttpRequestHeaders::kRange,
367 &range_header) ||
368 !HttpUtil::ParseRangeHeader(range_header, &ranges) || bad_200_ ||
369 ranges.size() != 1) {
370 // This is not a byte range request. We return 200.
371 response_status->assign("HTTP/1.1 200 OK");
372 response_headers->assign("Date: Wed, 28 Nov 2007 09:40:09 GMT");
373 response_data->assign("Not a range");
374 return;
377 // We can handle this range request.
378 HttpByteRange byte_range = ranges[0];
380 if (request->extra_headers.HasHeader("X-Return-Default-Range")) {
381 byte_range.set_first_byte_position(40);
382 byte_range.set_last_byte_position(49);
385 if (byte_range.first_byte_position() > 79) {
386 response_status->assign("HTTP/1.1 416 Requested Range Not Satisfiable");
387 response_data->clear();
388 return;
391 EXPECT_TRUE(byte_range.ComputeBounds(80));
392 int start = static_cast<int>(byte_range.first_byte_position());
393 int end = static_cast<int>(byte_range.last_byte_position());
395 EXPECT_LT(end, 80);
397 std::string content_range = base::StringPrintf(
398 "Content-Range: bytes %d-%d/80\n", start, end);
399 response_headers->append(content_range);
401 if (!request->extra_headers.HasHeader("If-None-Match") || modified_) {
402 std::string data;
403 if (end == start) {
404 EXPECT_EQ(0, end % 10);
405 data = "r";
406 } else {
407 EXPECT_EQ(9, (end - start) % 10);
408 for (int block_start = start; block_start < end; block_start += 10) {
409 base::StringAppendF(&data, "rg: %02d-%02d ",
410 block_start, block_start + 9);
413 *response_data = data;
415 if (end - start != 9) {
416 // We also have to fix content-length.
417 int len = end - start + 1;
418 std::string content_length = base::StringPrintf("Content-Length: %d\n",
419 len);
420 response_headers->replace(response_headers->find("Content-Length:"),
421 content_length.size(), content_length);
423 } else {
424 response_status->assign("HTTP/1.1 304 Not Modified");
425 response_data->clear();
429 const MockTransaction kRangeGET_TransactionOK = {
430 "http://www.google.com/range",
431 "GET",
432 base::Time(),
433 "Range: bytes = 40-49\r\n" EXTRA_HEADER,
434 LOAD_NORMAL,
435 "HTTP/1.1 206 Partial Content",
436 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
437 "ETag: \"foo\"\n"
438 "Accept-Ranges: bytes\n"
439 "Content-Length: 10\n",
440 base::Time(),
441 "rg: 40-49 ",
442 TEST_MODE_NORMAL,
443 &RangeTransactionServer::RangeHandler,
445 OK};
447 const char kFullRangeData[] =
448 "rg: 00-09 rg: 10-19 rg: 20-29 rg: 30-39 "
449 "rg: 40-49 rg: 50-59 rg: 60-69 rg: 70-79 ";
451 // Verifies the response headers (|response|) match a partial content
452 // response for the range starting at |start| and ending at |end|.
453 void Verify206Response(std::string response, int start, int end) {
454 std::string raw_headers(
455 HttpUtil::AssembleRawHeaders(response.data(), response.size()));
456 scoped_refptr<HttpResponseHeaders> headers(
457 new HttpResponseHeaders(raw_headers));
459 ASSERT_EQ(206, headers->response_code());
461 int64 range_start, range_end, object_size;
462 ASSERT_TRUE(
463 headers->GetContentRange(&range_start, &range_end, &object_size));
464 int64 content_length = headers->GetContentLength();
466 int length = end - start + 1;
467 ASSERT_EQ(length, content_length);
468 ASSERT_EQ(start, range_start);
469 ASSERT_EQ(end, range_end);
472 // Creates a truncated entry that can be resumed using byte ranges.
473 void CreateTruncatedEntry(std::string raw_headers, MockHttpCache* cache) {
474 // Create a disk cache entry that stores an incomplete resource.
475 disk_cache::Entry* entry;
476 ASSERT_TRUE(cache->CreateBackendEntry(kRangeGET_TransactionOK.url, &entry,
477 NULL));
479 raw_headers =
480 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
482 HttpResponseInfo response;
483 response.response_time = base::Time::Now();
484 response.request_time = base::Time::Now();
485 response.headers = new HttpResponseHeaders(raw_headers);
486 // Set the last argument for this to be an incomplete request.
487 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, true));
489 scoped_refptr<IOBuffer> buf(new IOBuffer(100));
490 int len = static_cast<int>(base::strlcpy(buf->data(),
491 "rg: 00-09 rg: 10-19 ", 100));
492 TestCompletionCallback cb;
493 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
494 EXPECT_EQ(len, cb.GetResult(rv));
495 entry->Close();
498 // Helper to represent a network HTTP response.
499 struct Response {
500 // Set this response into |trans|.
501 void AssignTo(MockTransaction* trans) const {
502 trans->status = status;
503 trans->response_headers = headers;
504 trans->data = body;
507 std::string status_and_headers() const {
508 return std::string(status) + "\n" + std::string(headers);
511 const char* status;
512 const char* headers;
513 const char* body;
516 struct Context {
517 Context() : result(ERR_IO_PENDING) {}
519 int result;
520 TestCompletionCallback callback;
521 scoped_ptr<HttpTransaction> trans;
524 class FakeWebSocketHandshakeStreamCreateHelper
525 : public WebSocketHandshakeStreamBase::CreateHelper {
526 public:
527 ~FakeWebSocketHandshakeStreamCreateHelper() override {}
528 WebSocketHandshakeStreamBase* CreateBasicStream(
529 scoped_ptr<ClientSocketHandle> connect,
530 bool using_proxy) override {
531 return NULL;
533 WebSocketHandshakeStreamBase* CreateSpdyStream(
534 const base::WeakPtr<SpdySession>& session,
535 bool use_relative_url) override {
536 return NULL;
540 // Returns true if |entry| is not one of the log types paid attention to in this
541 // test. Note that TYPE_HTTP_CACHE_WRITE_INFO and TYPE_HTTP_CACHE_*_DATA are
542 // ignored.
543 bool ShouldIgnoreLogEntry(const TestNetLogEntry& entry) {
544 switch (entry.type) {
545 case NetLog::TYPE_HTTP_CACHE_GET_BACKEND:
546 case NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY:
547 case NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY:
548 case NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY:
549 case NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY:
550 case NetLog::TYPE_HTTP_CACHE_READ_INFO:
551 return false;
552 default:
553 return true;
557 // Modifies |entries| to only include log entries created by the cache layer and
558 // asserted on in these tests.
559 void FilterLogEntries(TestNetLogEntry::List* entries) {
560 entries->erase(std::remove_if(entries->begin(), entries->end(),
561 &ShouldIgnoreLogEntry),
562 entries->end());
565 bool LogContainsEventType(const BoundTestNetLog& log,
566 NetLog::EventType expected) {
567 TestNetLogEntry::List entries;
568 log.GetEntries(&entries);
569 for (size_t i = 0; i < entries.size(); i++) {
570 if (entries[i].type == expected)
571 return true;
573 return false;
576 } // namespace
579 //-----------------------------------------------------------------------------
580 // Tests.
582 TEST(HttpCache, CreateThenDestroy) {
583 MockHttpCache cache;
585 scoped_ptr<HttpTransaction> trans;
586 EXPECT_EQ(OK, cache.CreateTransaction(&trans));
587 ASSERT_TRUE(trans.get());
590 TEST(HttpCache, GetBackend) {
591 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(0));
593 disk_cache::Backend* backend;
594 TestCompletionCallback cb;
595 // This will lazily initialize the backend.
596 int rv = cache.http_cache()->GetBackend(&backend, cb.callback());
597 EXPECT_EQ(OK, cb.GetResult(rv));
600 TEST(HttpCache, SimpleGET) {
601 MockHttpCache cache;
602 BoundTestNetLog log;
603 LoadTimingInfo load_timing_info;
605 // Write to the cache.
606 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
607 log.bound(), &load_timing_info);
609 EXPECT_EQ(1, cache.network_layer()->transaction_count());
610 EXPECT_EQ(0, cache.disk_cache()->open_count());
611 EXPECT_EQ(1, cache.disk_cache()->create_count());
612 TestLoadTimingNetworkRequest(load_timing_info);
615 TEST(HttpCache, SimpleGETNoDiskCache) {
616 MockHttpCache cache;
618 cache.disk_cache()->set_fail_requests();
620 BoundTestNetLog log;
621 LoadTimingInfo load_timing_info;
623 // Read from the network, and don't use the cache.
624 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
625 log.bound(), &load_timing_info);
627 // Check that the NetLog was filled as expected.
628 // (We attempted to both Open and Create entries, but both failed).
629 TestNetLogEntry::List entries;
630 log.GetEntries(&entries);
631 FilterLogEntries(&entries);
633 EXPECT_EQ(6u, entries.size());
634 EXPECT_TRUE(
635 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
636 EXPECT_TRUE(
637 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
638 EXPECT_TRUE(
639 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
640 EXPECT_TRUE(
641 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
642 EXPECT_TRUE(
643 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
644 EXPECT_TRUE(
645 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
647 EXPECT_EQ(1, cache.network_layer()->transaction_count());
648 EXPECT_EQ(0, cache.disk_cache()->open_count());
649 EXPECT_EQ(0, cache.disk_cache()->create_count());
650 TestLoadTimingNetworkRequest(load_timing_info);
653 TEST(HttpCache, SimpleGETNoDiskCache2) {
654 // This will initialize a cache object with NULL backend.
655 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
656 factory->set_fail(true);
657 factory->FinishCreation(); // We'll complete synchronously.
658 MockHttpCache cache(factory);
660 // Read from the network, and don't use the cache.
661 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
663 EXPECT_EQ(1, cache.network_layer()->transaction_count());
664 EXPECT_FALSE(cache.http_cache()->GetCurrentBackend());
667 // Tests that IOBuffers are not referenced after IO completes.
668 TEST(HttpCache, ReleaseBuffer) {
669 MockHttpCache cache;
671 // Write to the cache.
672 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
674 MockHttpRequest request(kSimpleGET_Transaction);
675 scoped_ptr<HttpTransaction> trans;
676 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
678 const int kBufferSize = 10;
679 scoped_refptr<IOBuffer> buffer(new IOBuffer(kBufferSize));
680 ReleaseBufferCompletionCallback cb(buffer.get());
682 int rv = trans->Start(&request, cb.callback(), BoundNetLog());
683 EXPECT_EQ(OK, cb.GetResult(rv));
685 rv = trans->Read(buffer.get(), kBufferSize, cb.callback());
686 EXPECT_EQ(kBufferSize, cb.GetResult(rv));
689 TEST(HttpCache, SimpleGETWithDiskFailures) {
690 MockHttpCache cache;
692 cache.disk_cache()->set_soft_failures(true);
694 // Read from the network, and fail to write to the cache.
695 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
697 EXPECT_EQ(1, cache.network_layer()->transaction_count());
698 EXPECT_EQ(0, cache.disk_cache()->open_count());
699 EXPECT_EQ(1, cache.disk_cache()->create_count());
701 // This one should see an empty cache again.
702 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
704 EXPECT_EQ(2, cache.network_layer()->transaction_count());
705 EXPECT_EQ(0, cache.disk_cache()->open_count());
706 EXPECT_EQ(2, cache.disk_cache()->create_count());
709 // Tests that disk failures after the transaction has started don't cause the
710 // request to fail.
711 TEST(HttpCache, SimpleGETWithDiskFailures2) {
712 MockHttpCache cache;
714 MockHttpRequest request(kSimpleGET_Transaction);
716 scoped_ptr<Context> c(new Context());
717 int rv = cache.CreateTransaction(&c->trans);
718 ASSERT_EQ(OK, rv);
720 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
721 EXPECT_EQ(ERR_IO_PENDING, rv);
722 rv = c->callback.WaitForResult();
724 // Start failing request now.
725 cache.disk_cache()->set_soft_failures(true);
727 // We have to open the entry again to propagate the failure flag.
728 disk_cache::Entry* en;
729 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &en));
730 en->Close();
732 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
733 c.reset();
735 EXPECT_EQ(1, cache.network_layer()->transaction_count());
736 EXPECT_EQ(1, cache.disk_cache()->open_count());
737 EXPECT_EQ(1, cache.disk_cache()->create_count());
739 // This one should see an empty cache again.
740 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
742 EXPECT_EQ(2, cache.network_layer()->transaction_count());
743 EXPECT_EQ(1, cache.disk_cache()->open_count());
744 EXPECT_EQ(2, cache.disk_cache()->create_count());
747 // Tests that we handle failures to read from the cache.
748 TEST(HttpCache, SimpleGETWithDiskFailures3) {
749 MockHttpCache cache;
751 // Read from the network, and write to the cache.
752 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
754 EXPECT_EQ(1, cache.network_layer()->transaction_count());
755 EXPECT_EQ(0, cache.disk_cache()->open_count());
756 EXPECT_EQ(1, cache.disk_cache()->create_count());
758 cache.disk_cache()->set_soft_failures(true);
760 // Now fail to read from the cache.
761 scoped_ptr<Context> c(new Context());
762 int rv = cache.CreateTransaction(&c->trans);
763 ASSERT_EQ(OK, rv);
765 MockHttpRequest request(kSimpleGET_Transaction);
766 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
767 EXPECT_EQ(OK, c->callback.GetResult(rv));
769 // Now verify that the entry was removed from the cache.
770 cache.disk_cache()->set_soft_failures(false);
772 EXPECT_EQ(2, cache.network_layer()->transaction_count());
773 EXPECT_EQ(1, cache.disk_cache()->open_count());
774 EXPECT_EQ(2, cache.disk_cache()->create_count());
776 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
778 EXPECT_EQ(3, cache.network_layer()->transaction_count());
779 EXPECT_EQ(1, cache.disk_cache()->open_count());
780 EXPECT_EQ(3, cache.disk_cache()->create_count());
783 TEST(HttpCache, SimpleGET_LoadOnlyFromCache_Hit) {
784 MockHttpCache cache;
786 BoundTestNetLog log;
787 LoadTimingInfo load_timing_info;
789 // Write to the cache.
790 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
791 log.bound(), &load_timing_info);
793 // Check that the NetLog was filled as expected.
794 TestNetLogEntry::List entries;
795 log.GetEntries(&entries);
796 FilterLogEntries(&entries);
798 EXPECT_EQ(8u, entries.size());
799 EXPECT_TRUE(
800 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
801 EXPECT_TRUE(
802 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
803 EXPECT_TRUE(
804 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
805 EXPECT_TRUE(
806 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
807 EXPECT_TRUE(
808 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
809 EXPECT_TRUE(
810 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
811 EXPECT_TRUE(
812 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
813 EXPECT_TRUE(
814 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
816 TestLoadTimingNetworkRequest(load_timing_info);
818 // Force this transaction to read from the cache.
819 MockTransaction transaction(kSimpleGET_Transaction);
820 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
822 log.Clear();
824 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
825 &load_timing_info);
827 // Check that the NetLog was filled as expected.
828 log.GetEntries(&entries);
829 FilterLogEntries(&entries);
831 EXPECT_EQ(8u, entries.size());
832 EXPECT_TRUE(
833 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
834 EXPECT_TRUE(
835 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
836 EXPECT_TRUE(
837 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
838 EXPECT_TRUE(
839 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
840 EXPECT_TRUE(
841 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
842 EXPECT_TRUE(
843 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
844 EXPECT_TRUE(
845 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_READ_INFO));
846 EXPECT_TRUE(
847 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_READ_INFO));
849 EXPECT_EQ(1, cache.network_layer()->transaction_count());
850 EXPECT_EQ(1, cache.disk_cache()->open_count());
851 EXPECT_EQ(1, cache.disk_cache()->create_count());
852 TestLoadTimingCachedResponse(load_timing_info);
855 TEST(HttpCache, SimpleGET_LoadOnlyFromCache_Miss) {
856 MockHttpCache cache;
858 // force this transaction to read from the cache
859 MockTransaction transaction(kSimpleGET_Transaction);
860 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
862 MockHttpRequest request(transaction);
863 TestCompletionCallback callback;
865 scoped_ptr<HttpTransaction> trans;
866 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
868 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
869 if (rv == ERR_IO_PENDING)
870 rv = callback.WaitForResult();
871 ASSERT_EQ(ERR_CACHE_MISS, rv);
873 trans.reset();
875 EXPECT_EQ(0, cache.network_layer()->transaction_count());
876 EXPECT_EQ(0, cache.disk_cache()->open_count());
877 EXPECT_EQ(0, cache.disk_cache()->create_count());
880 TEST(HttpCache, SimpleGET_LoadPreferringCache_Hit) {
881 MockHttpCache cache;
883 // write to the cache
884 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
886 // force this transaction to read from the cache if valid
887 MockTransaction transaction(kSimpleGET_Transaction);
888 transaction.load_flags |= LOAD_PREFERRING_CACHE;
890 RunTransactionTest(cache.http_cache(), transaction);
892 EXPECT_EQ(1, cache.network_layer()->transaction_count());
893 EXPECT_EQ(1, cache.disk_cache()->open_count());
894 EXPECT_EQ(1, cache.disk_cache()->create_count());
897 TEST(HttpCache, SimpleGET_LoadPreferringCache_Miss) {
898 MockHttpCache cache;
900 // force this transaction to read from the cache if valid
901 MockTransaction transaction(kSimpleGET_Transaction);
902 transaction.load_flags |= LOAD_PREFERRING_CACHE;
904 RunTransactionTest(cache.http_cache(), transaction);
906 EXPECT_EQ(1, cache.network_layer()->transaction_count());
907 EXPECT_EQ(0, cache.disk_cache()->open_count());
908 EXPECT_EQ(1, cache.disk_cache()->create_count());
911 // Tests LOAD_PREFERRING_CACHE in the presence of vary headers.
912 TEST(HttpCache, SimpleGET_LoadPreferringCache_VaryMatch) {
913 MockHttpCache cache;
915 // Write to the cache.
916 MockTransaction transaction(kSimpleGET_Transaction);
917 transaction.request_headers = "Foo: bar\r\n";
918 transaction.response_headers = "Cache-Control: max-age=10000\n"
919 "Vary: Foo\n";
920 AddMockTransaction(&transaction);
921 RunTransactionTest(cache.http_cache(), transaction);
923 // Read from the cache.
924 transaction.load_flags |= LOAD_PREFERRING_CACHE;
925 RunTransactionTest(cache.http_cache(), transaction);
927 EXPECT_EQ(1, cache.network_layer()->transaction_count());
928 EXPECT_EQ(1, cache.disk_cache()->open_count());
929 EXPECT_EQ(1, cache.disk_cache()->create_count());
930 RemoveMockTransaction(&transaction);
933 // Tests LOAD_PREFERRING_CACHE in the presence of vary headers.
934 TEST(HttpCache, SimpleGET_LoadPreferringCache_VaryMismatch) {
935 MockHttpCache cache;
937 // Write to the cache.
938 MockTransaction transaction(kSimpleGET_Transaction);
939 transaction.request_headers = "Foo: bar\r\n";
940 transaction.response_headers = "Cache-Control: max-age=10000\n"
941 "Vary: Foo\n";
942 AddMockTransaction(&transaction);
943 RunTransactionTest(cache.http_cache(), transaction);
945 // Attempt to read from the cache... this is a vary mismatch that must reach
946 // the network again.
947 transaction.load_flags |= LOAD_PREFERRING_CACHE;
948 transaction.request_headers = "Foo: none\r\n";
949 BoundTestNetLog log;
950 LoadTimingInfo load_timing_info;
951 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
952 &load_timing_info);
954 EXPECT_EQ(2, cache.network_layer()->transaction_count());
955 EXPECT_EQ(1, cache.disk_cache()->open_count());
956 EXPECT_EQ(1, cache.disk_cache()->create_count());
957 TestLoadTimingNetworkRequest(load_timing_info);
958 RemoveMockTransaction(&transaction);
961 // Tests that was_cached was set properly on a failure, even if the cached
962 // response wasn't returned.
963 TEST(HttpCache, SimpleGET_CacheSignal_Failure) {
964 MockHttpCache cache;
966 // Prime cache.
967 MockTransaction transaction(kSimpleGET_Transaction);
968 transaction.response_headers = "Cache-Control: no-cache\n";
970 AddMockTransaction(&transaction);
971 RunTransactionTest(cache.http_cache(), transaction);
972 EXPECT_EQ(1, cache.network_layer()->transaction_count());
973 EXPECT_EQ(1, cache.disk_cache()->create_count());
974 RemoveMockTransaction(&transaction);
976 // Network failure with error; should fail but have was_cached set.
977 transaction.return_code = ERR_FAILED;
978 AddMockTransaction(&transaction);
980 MockHttpRequest request(transaction);
981 TestCompletionCallback callback;
982 scoped_ptr<HttpTransaction> trans;
983 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
984 EXPECT_EQ(OK, rv);
985 ASSERT_TRUE(trans.get());
986 rv = trans->Start(&request, callback.callback(), BoundNetLog());
987 EXPECT_EQ(ERR_FAILED, callback.GetResult(rv));
989 const HttpResponseInfo* response_info = trans->GetResponseInfo();
990 ASSERT_TRUE(response_info);
991 EXPECT_TRUE(response_info->was_cached);
992 EXPECT_EQ(2, cache.network_layer()->transaction_count());
994 RemoveMockTransaction(&transaction);
997 // Confirm if we have an empty cache, a read is marked as network verified.
998 TEST(HttpCache, SimpleGET_NetworkAccessed_Network) {
999 MockHttpCache cache;
1001 // write to the cache
1002 HttpResponseInfo response_info;
1003 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
1004 &response_info);
1006 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1007 EXPECT_EQ(0, cache.disk_cache()->open_count());
1008 EXPECT_EQ(1, cache.disk_cache()->create_count());
1009 EXPECT_TRUE(response_info.network_accessed);
1012 // Confirm if we have a fresh entry in cache, it isn't marked as
1013 // network verified.
1014 TEST(HttpCache, SimpleGET_NetworkAccessed_Cache) {
1015 MockHttpCache cache;
1017 // Prime cache.
1018 MockTransaction transaction(kSimpleGET_Transaction);
1020 RunTransactionTest(cache.http_cache(), transaction);
1021 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1022 EXPECT_EQ(1, cache.disk_cache()->create_count());
1024 // Re-run transaction; make sure we don't mark the network as accessed.
1025 HttpResponseInfo response_info;
1026 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
1027 &response_info);
1029 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1030 EXPECT_FALSE(response_info.server_data_unavailable);
1031 EXPECT_FALSE(response_info.network_accessed);
1034 TEST(HttpCache, SimpleGET_LoadBypassCache) {
1035 MockHttpCache cache;
1037 // Write to the cache.
1038 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1040 // Force this transaction to write to the cache again.
1041 MockTransaction transaction(kSimpleGET_Transaction);
1042 transaction.load_flags |= LOAD_BYPASS_CACHE;
1044 BoundTestNetLog log;
1045 LoadTimingInfo load_timing_info;
1047 // Write to the cache.
1048 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
1049 &load_timing_info);
1051 // Check that the NetLog was filled as expected.
1052 TestNetLogEntry::List entries;
1053 log.GetEntries(&entries);
1054 FilterLogEntries(&entries);
1056 EXPECT_EQ(8u, entries.size());
1057 EXPECT_TRUE(
1058 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
1059 EXPECT_TRUE(
1060 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
1061 EXPECT_TRUE(
1062 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY));
1063 EXPECT_TRUE(
1064 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY));
1065 EXPECT_TRUE(
1066 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
1067 EXPECT_TRUE(
1068 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
1069 EXPECT_TRUE(
1070 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
1071 EXPECT_TRUE(
1072 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
1074 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1075 EXPECT_EQ(0, cache.disk_cache()->open_count());
1076 EXPECT_EQ(2, cache.disk_cache()->create_count());
1077 TestLoadTimingNetworkRequest(load_timing_info);
1080 TEST(HttpCache, SimpleGET_LoadBypassCache_Implicit) {
1081 MockHttpCache cache;
1083 // write to the cache
1084 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1086 // force this transaction to write to the cache again
1087 MockTransaction transaction(kSimpleGET_Transaction);
1088 transaction.request_headers = "pragma: no-cache\r\n";
1090 RunTransactionTest(cache.http_cache(), transaction);
1092 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1093 EXPECT_EQ(0, cache.disk_cache()->open_count());
1094 EXPECT_EQ(2, cache.disk_cache()->create_count());
1097 TEST(HttpCache, SimpleGET_LoadBypassCache_Implicit2) {
1098 MockHttpCache cache;
1100 // write to the cache
1101 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1103 // force this transaction to write to the cache again
1104 MockTransaction transaction(kSimpleGET_Transaction);
1105 transaction.request_headers = "cache-control: no-cache\r\n";
1107 RunTransactionTest(cache.http_cache(), transaction);
1109 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1110 EXPECT_EQ(0, cache.disk_cache()->open_count());
1111 EXPECT_EQ(2, cache.disk_cache()->create_count());
1114 TEST(HttpCache, SimpleGET_LoadValidateCache) {
1115 MockHttpCache cache;
1117 // Write to the cache.
1118 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1120 // Read from the cache.
1121 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1123 // Force this transaction to validate the cache.
1124 MockTransaction transaction(kSimpleGET_Transaction);
1125 transaction.load_flags |= LOAD_VALIDATE_CACHE;
1127 HttpResponseInfo response_info;
1128 BoundTestNetLog log;
1129 LoadTimingInfo load_timing_info;
1130 RunTransactionTestWithResponseInfoAndGetTiming(
1131 cache.http_cache(), transaction, &response_info, log.bound(),
1132 &load_timing_info);
1134 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1135 EXPECT_EQ(1, cache.disk_cache()->open_count());
1136 EXPECT_EQ(1, cache.disk_cache()->create_count());
1137 EXPECT_TRUE(response_info.network_accessed);
1138 TestLoadTimingNetworkRequest(load_timing_info);
1141 TEST(HttpCache, SimpleGET_LoadValidateCache_Implicit) {
1142 MockHttpCache cache;
1144 // write to the cache
1145 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1147 // read from the cache
1148 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1150 // force this transaction to validate the cache
1151 MockTransaction transaction(kSimpleGET_Transaction);
1152 transaction.request_headers = "cache-control: max-age=0\r\n";
1154 RunTransactionTest(cache.http_cache(), transaction);
1156 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1157 EXPECT_EQ(1, cache.disk_cache()->open_count());
1158 EXPECT_EQ(1, cache.disk_cache()->create_count());
1161 static void PreserveRequestHeaders_Handler(const HttpRequestInfo* request,
1162 std::string* response_status,
1163 std::string* response_headers,
1164 std::string* response_data) {
1165 EXPECT_TRUE(request->extra_headers.HasHeader(kExtraHeaderKey));
1168 // Tests that we don't remove extra headers for simple requests.
1169 TEST(HttpCache, SimpleGET_PreserveRequestHeaders) {
1170 MockHttpCache cache;
1172 MockTransaction transaction(kSimpleGET_Transaction);
1173 transaction.handler = PreserveRequestHeaders_Handler;
1174 transaction.request_headers = EXTRA_HEADER;
1175 transaction.response_headers = "Cache-Control: max-age=0\n";
1176 AddMockTransaction(&transaction);
1178 // Write, then revalidate the entry.
1179 RunTransactionTest(cache.http_cache(), transaction);
1180 RunTransactionTest(cache.http_cache(), transaction);
1182 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1183 EXPECT_EQ(1, cache.disk_cache()->open_count());
1184 EXPECT_EQ(1, cache.disk_cache()->create_count());
1185 RemoveMockTransaction(&transaction);
1188 // Tests that we don't remove extra headers for conditionalized requests.
1189 TEST(HttpCache, ConditionalizedGET_PreserveRequestHeaders) {
1190 MockHttpCache cache;
1192 // Write to the cache.
1193 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
1195 MockTransaction transaction(kETagGET_Transaction);
1196 transaction.handler = PreserveRequestHeaders_Handler;
1197 transaction.request_headers = "If-None-Match: \"foopy\"\r\n"
1198 EXTRA_HEADER;
1199 AddMockTransaction(&transaction);
1201 RunTransactionTest(cache.http_cache(), transaction);
1203 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1204 EXPECT_EQ(1, cache.disk_cache()->open_count());
1205 EXPECT_EQ(1, cache.disk_cache()->create_count());
1206 RemoveMockTransaction(&transaction);
1209 TEST(HttpCache, SimpleGET_ManyReaders) {
1210 MockHttpCache cache;
1212 MockHttpRequest request(kSimpleGET_Transaction);
1214 std::vector<Context*> context_list;
1215 const int kNumTransactions = 5;
1217 for (int i = 0; i < kNumTransactions; ++i) {
1218 context_list.push_back(new Context());
1219 Context* c = context_list[i];
1221 c->result = cache.CreateTransaction(&c->trans);
1222 ASSERT_EQ(OK, c->result);
1223 EXPECT_EQ(LOAD_STATE_IDLE, c->trans->GetLoadState());
1225 c->result =
1226 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1229 // All requests are waiting for the active entry.
1230 for (int i = 0; i < kNumTransactions; ++i) {
1231 Context* c = context_list[i];
1232 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, c->trans->GetLoadState());
1235 // Allow all requests to move from the Create queue to the active entry.
1236 base::MessageLoop::current()->RunUntilIdle();
1238 // The first request should be a writer at this point, and the subsequent
1239 // requests should be pending.
1241 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1242 EXPECT_EQ(0, cache.disk_cache()->open_count());
1243 EXPECT_EQ(1, cache.disk_cache()->create_count());
1245 // All requests depend on the writer, and the writer is between Start and
1246 // Read, i.e. idle.
1247 for (int i = 0; i < kNumTransactions; ++i) {
1248 Context* c = context_list[i];
1249 EXPECT_EQ(LOAD_STATE_IDLE, c->trans->GetLoadState());
1252 for (int i = 0; i < kNumTransactions; ++i) {
1253 Context* c = context_list[i];
1254 if (c->result == ERR_IO_PENDING)
1255 c->result = c->callback.WaitForResult();
1256 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1259 // We should not have had to re-open the disk entry
1261 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1262 EXPECT_EQ(0, cache.disk_cache()->open_count());
1263 EXPECT_EQ(1, cache.disk_cache()->create_count());
1265 for (int i = 0; i < kNumTransactions; ++i) {
1266 Context* c = context_list[i];
1267 delete c;
1271 // This is a test for http://code.google.com/p/chromium/issues/detail?id=4769.
1272 // If cancelling a request is racing with another request for the same resource
1273 // finishing, we have to make sure that we remove both transactions from the
1274 // entry.
1275 TEST(HttpCache, SimpleGET_RacingReaders) {
1276 MockHttpCache cache;
1278 MockHttpRequest request(kSimpleGET_Transaction);
1279 MockHttpRequest reader_request(kSimpleGET_Transaction);
1280 reader_request.load_flags = LOAD_ONLY_FROM_CACHE;
1282 std::vector<Context*> context_list;
1283 const int kNumTransactions = 5;
1285 for (int i = 0; i < kNumTransactions; ++i) {
1286 context_list.push_back(new Context());
1287 Context* c = context_list[i];
1289 c->result = cache.CreateTransaction(&c->trans);
1290 ASSERT_EQ(OK, c->result);
1292 MockHttpRequest* this_request = &request;
1293 if (i == 1 || i == 2)
1294 this_request = &reader_request;
1296 c->result =
1297 c->trans->Start(this_request, c->callback.callback(), BoundNetLog());
1300 // Allow all requests to move from the Create queue to the active entry.
1301 base::MessageLoop::current()->RunUntilIdle();
1303 // The first request should be a writer at this point, and the subsequent
1304 // requests should be pending.
1306 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1307 EXPECT_EQ(0, cache.disk_cache()->open_count());
1308 EXPECT_EQ(1, cache.disk_cache()->create_count());
1310 Context* c = context_list[0];
1311 ASSERT_EQ(ERR_IO_PENDING, c->result);
1312 c->result = c->callback.WaitForResult();
1313 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1315 // Now we have 2 active readers and two queued transactions.
1317 EXPECT_EQ(LOAD_STATE_IDLE, context_list[2]->trans->GetLoadState());
1318 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE,
1319 context_list[3]->trans->GetLoadState());
1321 c = context_list[1];
1322 ASSERT_EQ(ERR_IO_PENDING, c->result);
1323 c->result = c->callback.WaitForResult();
1324 if (c->result == OK)
1325 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1327 // At this point we have one reader, two pending transactions and a task on
1328 // the queue to move to the next transaction. Now we cancel the request that
1329 // is the current reader, and expect the queued task to be able to start the
1330 // next request.
1332 c = context_list[2];
1333 c->trans.reset();
1335 for (int i = 3; i < kNumTransactions; ++i) {
1336 Context* c = context_list[i];
1337 if (c->result == ERR_IO_PENDING)
1338 c->result = c->callback.WaitForResult();
1339 if (c->result == OK)
1340 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1343 // We should not have had to re-open the disk entry.
1345 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1346 EXPECT_EQ(0, cache.disk_cache()->open_count());
1347 EXPECT_EQ(1, cache.disk_cache()->create_count());
1349 for (int i = 0; i < kNumTransactions; ++i) {
1350 Context* c = context_list[i];
1351 delete c;
1355 // Tests that we can doom an entry with pending transactions and delete one of
1356 // the pending transactions before the first one completes.
1357 // See http://code.google.com/p/chromium/issues/detail?id=25588
1358 TEST(HttpCache, SimpleGET_DoomWithPending) {
1359 // We need simultaneous doomed / not_doomed entries so let's use a real cache.
1360 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(1024 * 1024));
1362 MockHttpRequest request(kSimpleGET_Transaction);
1363 MockHttpRequest writer_request(kSimpleGET_Transaction);
1364 writer_request.load_flags = LOAD_BYPASS_CACHE;
1366 ScopedVector<Context> context_list;
1367 const int kNumTransactions = 4;
1369 for (int i = 0; i < kNumTransactions; ++i) {
1370 context_list.push_back(new Context());
1371 Context* c = context_list[i];
1373 c->result = cache.CreateTransaction(&c->trans);
1374 ASSERT_EQ(OK, c->result);
1376 MockHttpRequest* this_request = &request;
1377 if (i == 3)
1378 this_request = &writer_request;
1380 c->result =
1381 c->trans->Start(this_request, c->callback.callback(), BoundNetLog());
1384 // The first request should be a writer at this point, and the two subsequent
1385 // requests should be pending. The last request doomed the first entry.
1387 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1389 // Cancel the first queued transaction.
1390 delete context_list[1];
1391 context_list.get()[1] = NULL;
1393 for (int i = 0; i < kNumTransactions; ++i) {
1394 if (i == 1)
1395 continue;
1396 Context* c = context_list[i];
1397 ASSERT_EQ(ERR_IO_PENDING, c->result);
1398 c->result = c->callback.WaitForResult();
1399 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1403 // This is a test for http://code.google.com/p/chromium/issues/detail?id=4731.
1404 // We may attempt to delete an entry synchronously with the act of adding a new
1405 // transaction to said entry.
1406 TEST(HttpCache, FastNoStoreGET_DoneWithPending) {
1407 MockHttpCache cache;
1409 // The headers will be served right from the call to Start() the request.
1410 MockHttpRequest request(kFastNoStoreGET_Transaction);
1411 FastTransactionServer request_handler;
1412 AddMockTransaction(&kFastNoStoreGET_Transaction);
1414 std::vector<Context*> context_list;
1415 const int kNumTransactions = 3;
1417 for (int i = 0; i < kNumTransactions; ++i) {
1418 context_list.push_back(new Context());
1419 Context* c = context_list[i];
1421 c->result = cache.CreateTransaction(&c->trans);
1422 ASSERT_EQ(OK, c->result);
1424 c->result =
1425 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1428 // Allow all requests to move from the Create queue to the active entry.
1429 base::MessageLoop::current()->RunUntilIdle();
1431 // The first request should be a writer at this point, and the subsequent
1432 // requests should be pending.
1434 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1435 EXPECT_EQ(0, cache.disk_cache()->open_count());
1436 EXPECT_EQ(1, cache.disk_cache()->create_count());
1438 // Now, make sure that the second request asks for the entry not to be stored.
1439 request_handler.set_no_store(true);
1441 for (int i = 0; i < kNumTransactions; ++i) {
1442 Context* c = context_list[i];
1443 if (c->result == ERR_IO_PENDING)
1444 c->result = c->callback.WaitForResult();
1445 ReadAndVerifyTransaction(c->trans.get(), kFastNoStoreGET_Transaction);
1446 delete c;
1449 EXPECT_EQ(3, cache.network_layer()->transaction_count());
1450 EXPECT_EQ(0, cache.disk_cache()->open_count());
1451 EXPECT_EQ(2, cache.disk_cache()->create_count());
1453 RemoveMockTransaction(&kFastNoStoreGET_Transaction);
1456 TEST(HttpCache, SimpleGET_ManyWriters_CancelFirst) {
1457 MockHttpCache cache;
1459 MockHttpRequest request(kSimpleGET_Transaction);
1461 std::vector<Context*> context_list;
1462 const int kNumTransactions = 2;
1464 for (int i = 0; i < kNumTransactions; ++i) {
1465 context_list.push_back(new Context());
1466 Context* c = context_list[i];
1468 c->result = cache.CreateTransaction(&c->trans);
1469 ASSERT_EQ(OK, c->result);
1471 c->result =
1472 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1475 // Allow all requests to move from the Create queue to the active entry.
1476 base::MessageLoop::current()->RunUntilIdle();
1478 // The first request should be a writer at this point, and the subsequent
1479 // requests should be pending.
1481 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1482 EXPECT_EQ(0, cache.disk_cache()->open_count());
1483 EXPECT_EQ(1, cache.disk_cache()->create_count());
1485 for (int i = 0; i < kNumTransactions; ++i) {
1486 Context* c = context_list[i];
1487 if (c->result == ERR_IO_PENDING)
1488 c->result = c->callback.WaitForResult();
1489 // Destroy only the first transaction.
1490 if (i == 0) {
1491 delete c;
1492 context_list[i] = NULL;
1496 // Complete the rest of the transactions.
1497 for (int i = 1; i < kNumTransactions; ++i) {
1498 Context* c = context_list[i];
1499 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1502 // We should have had to re-open the disk entry.
1504 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1505 EXPECT_EQ(0, cache.disk_cache()->open_count());
1506 EXPECT_EQ(2, cache.disk_cache()->create_count());
1508 for (int i = 1; i < kNumTransactions; ++i) {
1509 Context* c = context_list[i];
1510 delete c;
1514 // Tests that we can cancel requests that are queued waiting to open the disk
1515 // cache entry.
1516 TEST(HttpCache, SimpleGET_ManyWriters_CancelCreate) {
1517 MockHttpCache cache;
1519 MockHttpRequest request(kSimpleGET_Transaction);
1521 std::vector<Context*> context_list;
1522 const int kNumTransactions = 5;
1524 for (int i = 0; i < kNumTransactions; i++) {
1525 context_list.push_back(new Context());
1526 Context* c = context_list[i];
1528 c->result = cache.CreateTransaction(&c->trans);
1529 ASSERT_EQ(OK, c->result);
1531 c->result =
1532 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1535 // The first request should be creating the disk cache entry and the others
1536 // should be pending.
1538 EXPECT_EQ(0, cache.network_layer()->transaction_count());
1539 EXPECT_EQ(0, cache.disk_cache()->open_count());
1540 EXPECT_EQ(1, cache.disk_cache()->create_count());
1542 // Cancel a request from the pending queue.
1543 delete context_list[3];
1544 context_list[3] = NULL;
1546 // Cancel the request that is creating the entry. This will force the pending
1547 // operations to restart.
1548 delete context_list[0];
1549 context_list[0] = NULL;
1551 // Complete the rest of the transactions.
1552 for (int i = 1; i < kNumTransactions; i++) {
1553 Context* c = context_list[i];
1554 if (c) {
1555 c->result = c->callback.GetResult(c->result);
1556 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1560 // We should have had to re-create the disk entry.
1562 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1563 EXPECT_EQ(0, cache.disk_cache()->open_count());
1564 EXPECT_EQ(2, cache.disk_cache()->create_count());
1566 for (int i = 1; i < kNumTransactions; ++i) {
1567 delete context_list[i];
1571 // Tests that we can cancel a single request to open a disk cache entry.
1572 TEST(HttpCache, SimpleGET_CancelCreate) {
1573 MockHttpCache cache;
1575 MockHttpRequest request(kSimpleGET_Transaction);
1577 Context* c = new Context();
1579 c->result = cache.CreateTransaction(&c->trans);
1580 ASSERT_EQ(OK, c->result);
1582 c->result = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1583 EXPECT_EQ(ERR_IO_PENDING, c->result);
1585 // Release the reference that the mock disk cache keeps for this entry, so
1586 // that we test that the http cache handles the cancellation correctly.
1587 cache.disk_cache()->ReleaseAll();
1588 delete c;
1590 base::MessageLoop::current()->RunUntilIdle();
1591 EXPECT_EQ(1, cache.disk_cache()->create_count());
1594 // Tests that we delete/create entries even if multiple requests are queued.
1595 TEST(HttpCache, SimpleGET_ManyWriters_BypassCache) {
1596 MockHttpCache cache;
1598 MockHttpRequest request(kSimpleGET_Transaction);
1599 request.load_flags = LOAD_BYPASS_CACHE;
1601 std::vector<Context*> context_list;
1602 const int kNumTransactions = 5;
1604 for (int i = 0; i < kNumTransactions; i++) {
1605 context_list.push_back(new Context());
1606 Context* c = context_list[i];
1608 c->result = cache.CreateTransaction(&c->trans);
1609 ASSERT_EQ(OK, c->result);
1611 c->result =
1612 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1615 // The first request should be deleting the disk cache entry and the others
1616 // should be pending.
1618 EXPECT_EQ(0, cache.network_layer()->transaction_count());
1619 EXPECT_EQ(0, cache.disk_cache()->open_count());
1620 EXPECT_EQ(0, cache.disk_cache()->create_count());
1622 // Complete the transactions.
1623 for (int i = 0; i < kNumTransactions; i++) {
1624 Context* c = context_list[i];
1625 c->result = c->callback.GetResult(c->result);
1626 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1629 // We should have had to re-create the disk entry multiple times.
1631 EXPECT_EQ(5, cache.network_layer()->transaction_count());
1632 EXPECT_EQ(0, cache.disk_cache()->open_count());
1633 EXPECT_EQ(5, cache.disk_cache()->create_count());
1635 for (int i = 0; i < kNumTransactions; ++i) {
1636 delete context_list[i];
1640 // Tests that a (simulated) timeout allows transactions waiting on the cache
1641 // lock to continue.
1642 TEST(HttpCache, SimpleGET_WriterTimeout) {
1643 MockHttpCache cache;
1644 cache.BypassCacheLock();
1646 MockHttpRequest request(kSimpleGET_Transaction);
1647 Context c1, c2;
1648 ASSERT_EQ(OK, cache.CreateTransaction(&c1.trans));
1649 ASSERT_EQ(ERR_IO_PENDING,
1650 c1.trans->Start(&request, c1.callback.callback(), BoundNetLog()));
1651 ASSERT_EQ(OK, cache.CreateTransaction(&c2.trans));
1652 ASSERT_EQ(ERR_IO_PENDING,
1653 c2.trans->Start(&request, c2.callback.callback(), BoundNetLog()));
1655 // The second request is queued after the first one.
1657 c2.callback.WaitForResult();
1658 ReadAndVerifyTransaction(c2.trans.get(), kSimpleGET_Transaction);
1660 // Complete the first transaction.
1661 c1.callback.WaitForResult();
1662 ReadAndVerifyTransaction(c1.trans.get(), kSimpleGET_Transaction);
1665 TEST(HttpCache, SimpleGET_AbandonedCacheRead) {
1666 MockHttpCache cache;
1668 // write to the cache
1669 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1671 MockHttpRequest request(kSimpleGET_Transaction);
1672 TestCompletionCallback callback;
1674 scoped_ptr<HttpTransaction> trans;
1675 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
1676 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1677 if (rv == ERR_IO_PENDING)
1678 rv = callback.WaitForResult();
1679 ASSERT_EQ(OK, rv);
1681 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
1682 rv = trans->Read(buf.get(), 256, callback.callback());
1683 EXPECT_EQ(ERR_IO_PENDING, rv);
1685 // Test that destroying the transaction while it is reading from the cache
1686 // works properly.
1687 trans.reset();
1689 // Make sure we pump any pending events, which should include a call to
1690 // HttpCache::Transaction::OnCacheReadCompleted.
1691 base::MessageLoop::current()->RunUntilIdle();
1694 // Tests that we can delete the HttpCache and deal with queued transactions
1695 // ("waiting for the backend" as opposed to Active or Doomed entries).
1696 TEST(HttpCache, SimpleGET_ManyWriters_DeleteCache) {
1697 scoped_ptr<MockHttpCache> cache(new MockHttpCache(
1698 new MockBackendNoCbFactory()));
1700 MockHttpRequest request(kSimpleGET_Transaction);
1702 std::vector<Context*> context_list;
1703 const int kNumTransactions = 5;
1705 for (int i = 0; i < kNumTransactions; i++) {
1706 context_list.push_back(new Context());
1707 Context* c = context_list[i];
1709 c->result = cache->CreateTransaction(&c->trans);
1710 ASSERT_EQ(OK, c->result);
1712 c->result =
1713 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1716 // The first request should be creating the disk cache entry and the others
1717 // should be pending.
1719 EXPECT_EQ(0, cache->network_layer()->transaction_count());
1720 EXPECT_EQ(0, cache->disk_cache()->open_count());
1721 EXPECT_EQ(0, cache->disk_cache()->create_count());
1723 cache.reset();
1725 // There is not much to do with the transactions at this point... they are
1726 // waiting for a callback that will not fire.
1727 for (int i = 0; i < kNumTransactions; ++i) {
1728 delete context_list[i];
1732 // Tests that we queue requests when initializing the backend.
1733 TEST(HttpCache, SimpleGET_WaitForBackend) {
1734 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1735 MockHttpCache cache(factory);
1737 MockHttpRequest request0(kSimpleGET_Transaction);
1738 MockHttpRequest request1(kTypicalGET_Transaction);
1739 MockHttpRequest request2(kETagGET_Transaction);
1741 std::vector<Context*> context_list;
1742 const int kNumTransactions = 3;
1744 for (int i = 0; i < kNumTransactions; i++) {
1745 context_list.push_back(new Context());
1746 Context* c = context_list[i];
1748 c->result = cache.CreateTransaction(&c->trans);
1749 ASSERT_EQ(OK, c->result);
1752 context_list[0]->result = context_list[0]->trans->Start(
1753 &request0, context_list[0]->callback.callback(), BoundNetLog());
1754 context_list[1]->result = context_list[1]->trans->Start(
1755 &request1, context_list[1]->callback.callback(), BoundNetLog());
1756 context_list[2]->result = context_list[2]->trans->Start(
1757 &request2, context_list[2]->callback.callback(), BoundNetLog());
1759 // Just to make sure that everything is still pending.
1760 base::MessageLoop::current()->RunUntilIdle();
1762 // The first request should be creating the disk cache.
1763 EXPECT_FALSE(context_list[0]->callback.have_result());
1765 factory->FinishCreation();
1767 base::MessageLoop::current()->RunUntilIdle();
1768 EXPECT_EQ(3, cache.network_layer()->transaction_count());
1769 EXPECT_EQ(3, cache.disk_cache()->create_count());
1771 for (int i = 0; i < kNumTransactions; ++i) {
1772 EXPECT_TRUE(context_list[i]->callback.have_result());
1773 delete context_list[i];
1777 // Tests that we can cancel requests that are queued waiting for the backend
1778 // to be initialized.
1779 TEST(HttpCache, SimpleGET_WaitForBackend_CancelCreate) {
1780 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1781 MockHttpCache cache(factory);
1783 MockHttpRequest request0(kSimpleGET_Transaction);
1784 MockHttpRequest request1(kTypicalGET_Transaction);
1785 MockHttpRequest request2(kETagGET_Transaction);
1787 std::vector<Context*> context_list;
1788 const int kNumTransactions = 3;
1790 for (int i = 0; i < kNumTransactions; i++) {
1791 context_list.push_back(new Context());
1792 Context* c = context_list[i];
1794 c->result = cache.CreateTransaction(&c->trans);
1795 ASSERT_EQ(OK, c->result);
1798 context_list[0]->result = context_list[0]->trans->Start(
1799 &request0, context_list[0]->callback.callback(), BoundNetLog());
1800 context_list[1]->result = context_list[1]->trans->Start(
1801 &request1, context_list[1]->callback.callback(), BoundNetLog());
1802 context_list[2]->result = context_list[2]->trans->Start(
1803 &request2, context_list[2]->callback.callback(), BoundNetLog());
1805 // Just to make sure that everything is still pending.
1806 base::MessageLoop::current()->RunUntilIdle();
1808 // The first request should be creating the disk cache.
1809 EXPECT_FALSE(context_list[0]->callback.have_result());
1811 // Cancel a request from the pending queue.
1812 delete context_list[1];
1813 context_list[1] = NULL;
1815 // Cancel the request that is creating the entry.
1816 delete context_list[0];
1817 context_list[0] = NULL;
1819 // Complete the last transaction.
1820 factory->FinishCreation();
1822 context_list[2]->result =
1823 context_list[2]->callback.GetResult(context_list[2]->result);
1824 ReadAndVerifyTransaction(context_list[2]->trans.get(), kETagGET_Transaction);
1826 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1827 EXPECT_EQ(1, cache.disk_cache()->create_count());
1829 delete context_list[2];
1832 // Tests that we can delete the cache while creating the backend.
1833 TEST(HttpCache, DeleteCacheWaitingForBackend) {
1834 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1835 scoped_ptr<MockHttpCache> cache(new MockHttpCache(factory));
1837 MockHttpRequest request(kSimpleGET_Transaction);
1839 scoped_ptr<Context> c(new Context());
1840 c->result = cache->CreateTransaction(&c->trans);
1841 ASSERT_EQ(OK, c->result);
1843 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1845 // Just to make sure that everything is still pending.
1846 base::MessageLoop::current()->RunUntilIdle();
1848 // The request should be creating the disk cache.
1849 EXPECT_FALSE(c->callback.have_result());
1851 // We cannot call FinishCreation because the factory itself will go away with
1852 // the cache, so grab the callback and attempt to use it.
1853 CompletionCallback callback = factory->callback();
1854 scoped_ptr<disk_cache::Backend>* backend = factory->backend();
1856 cache.reset();
1857 base::MessageLoop::current()->RunUntilIdle();
1859 backend->reset();
1860 callback.Run(ERR_ABORTED);
1863 // Tests that we can delete the cache while creating the backend, from within
1864 // one of the callbacks.
1865 TEST(HttpCache, DeleteCacheWaitingForBackend2) {
1866 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1867 MockHttpCache* cache = new MockHttpCache(factory);
1869 DeleteCacheCompletionCallback cb(cache);
1870 disk_cache::Backend* backend;
1871 int rv = cache->http_cache()->GetBackend(&backend, cb.callback());
1872 EXPECT_EQ(ERR_IO_PENDING, rv);
1874 // Now let's queue a regular transaction
1875 MockHttpRequest request(kSimpleGET_Transaction);
1877 scoped_ptr<Context> c(new Context());
1878 c->result = cache->CreateTransaction(&c->trans);
1879 ASSERT_EQ(OK, c->result);
1881 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1883 // And another direct backend request.
1884 TestCompletionCallback cb2;
1885 rv = cache->http_cache()->GetBackend(&backend, cb2.callback());
1886 EXPECT_EQ(ERR_IO_PENDING, rv);
1888 // Just to make sure that everything is still pending.
1889 base::MessageLoop::current()->RunUntilIdle();
1891 // The request should be queued.
1892 EXPECT_FALSE(c->callback.have_result());
1894 // Generate the callback.
1895 factory->FinishCreation();
1896 rv = cb.WaitForResult();
1898 // The cache should be gone by now.
1899 base::MessageLoop::current()->RunUntilIdle();
1900 EXPECT_EQ(OK, c->callback.GetResult(c->result));
1901 EXPECT_FALSE(cb2.have_result());
1904 TEST(HttpCache, TypicalGET_ConditionalRequest) {
1905 MockHttpCache cache;
1907 // write to the cache
1908 RunTransactionTest(cache.http_cache(), kTypicalGET_Transaction);
1910 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1911 EXPECT_EQ(0, cache.disk_cache()->open_count());
1912 EXPECT_EQ(1, cache.disk_cache()->create_count());
1914 // Get the same URL again, but this time we expect it to result
1915 // in a conditional request.
1916 BoundTestNetLog log;
1917 LoadTimingInfo load_timing_info;
1918 RunTransactionTestAndGetTiming(cache.http_cache(), kTypicalGET_Transaction,
1919 log.bound(), &load_timing_info);
1921 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1922 EXPECT_EQ(1, cache.disk_cache()->open_count());
1923 EXPECT_EQ(1, cache.disk_cache()->create_count());
1924 TestLoadTimingNetworkRequest(load_timing_info);
1927 static void ETagGet_ConditionalRequest_Handler(const HttpRequestInfo* request,
1928 std::string* response_status,
1929 std::string* response_headers,
1930 std::string* response_data) {
1931 EXPECT_TRUE(
1932 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
1933 response_status->assign("HTTP/1.1 304 Not Modified");
1934 response_headers->assign(kETagGET_Transaction.response_headers);
1935 response_data->clear();
1938 TEST(HttpCache, ETagGET_ConditionalRequest_304) {
1939 MockHttpCache cache;
1941 ScopedMockTransaction transaction(kETagGET_Transaction);
1943 // write to the cache
1944 RunTransactionTest(cache.http_cache(), transaction);
1946 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1947 EXPECT_EQ(0, cache.disk_cache()->open_count());
1948 EXPECT_EQ(1, cache.disk_cache()->create_count());
1950 // Get the same URL again, but this time we expect it to result
1951 // in a conditional request.
1952 transaction.load_flags = LOAD_VALIDATE_CACHE;
1953 transaction.handler = ETagGet_ConditionalRequest_Handler;
1954 BoundTestNetLog log;
1955 LoadTimingInfo load_timing_info;
1956 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
1957 &load_timing_info);
1959 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1960 EXPECT_EQ(1, cache.disk_cache()->open_count());
1961 EXPECT_EQ(1, cache.disk_cache()->create_count());
1962 TestLoadTimingNetworkRequest(load_timing_info);
1965 class RevalidationServer {
1966 public:
1967 RevalidationServer() {
1968 s_etag_used_ = false;
1969 s_last_modified_used_ = false;
1972 bool EtagUsed() { return s_etag_used_; }
1973 bool LastModifiedUsed() { return s_last_modified_used_; }
1975 static void Handler(const HttpRequestInfo* request,
1976 std::string* response_status,
1977 std::string* response_headers,
1978 std::string* response_data);
1980 private:
1981 static bool s_etag_used_;
1982 static bool s_last_modified_used_;
1984 bool RevalidationServer::s_etag_used_ = false;
1985 bool RevalidationServer::s_last_modified_used_ = false;
1987 void RevalidationServer::Handler(const HttpRequestInfo* request,
1988 std::string* response_status,
1989 std::string* response_headers,
1990 std::string* response_data) {
1991 if (request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch))
1992 s_etag_used_ = true;
1994 if (request->extra_headers.HasHeader(HttpRequestHeaders::kIfModifiedSince)) {
1995 s_last_modified_used_ = true;
1998 if (s_etag_used_ || s_last_modified_used_) {
1999 response_status->assign("HTTP/1.1 304 Not Modified");
2000 response_headers->assign(kTypicalGET_Transaction.response_headers);
2001 response_data->clear();
2002 } else {
2003 response_status->assign(kTypicalGET_Transaction.status);
2004 response_headers->assign(kTypicalGET_Transaction.response_headers);
2005 response_data->assign(kTypicalGET_Transaction.data);
2009 // Tests revalidation after a vary match.
2010 TEST(HttpCache, GET_ValidateCache_VaryMatch) {
2011 MockHttpCache cache;
2013 // Write to the cache.
2014 MockTransaction transaction(kTypicalGET_Transaction);
2015 transaction.request_headers = "Foo: bar\r\n";
2016 transaction.response_headers =
2017 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2018 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2019 "Etag: \"foopy\"\n"
2020 "Cache-Control: max-age=0\n"
2021 "Vary: Foo\n";
2022 AddMockTransaction(&transaction);
2023 RunTransactionTest(cache.http_cache(), transaction);
2025 // Read from the cache.
2026 RevalidationServer server;
2027 transaction.handler = server.Handler;
2028 BoundTestNetLog log;
2029 LoadTimingInfo load_timing_info;
2030 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2031 &load_timing_info);
2033 EXPECT_TRUE(server.EtagUsed());
2034 EXPECT_TRUE(server.LastModifiedUsed());
2035 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2036 EXPECT_EQ(1, cache.disk_cache()->open_count());
2037 EXPECT_EQ(1, cache.disk_cache()->create_count());
2038 TestLoadTimingNetworkRequest(load_timing_info);
2039 RemoveMockTransaction(&transaction);
2042 // Tests revalidation after a vary mismatch if etag is present.
2043 TEST(HttpCache, GET_ValidateCache_VaryMismatch) {
2044 MockHttpCache cache;
2046 // Write to the cache.
2047 MockTransaction transaction(kTypicalGET_Transaction);
2048 transaction.request_headers = "Foo: bar\r\n";
2049 transaction.response_headers =
2050 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2051 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2052 "Etag: \"foopy\"\n"
2053 "Cache-Control: max-age=0\n"
2054 "Vary: Foo\n";
2055 AddMockTransaction(&transaction);
2056 RunTransactionTest(cache.http_cache(), transaction);
2058 // Read from the cache and revalidate the entry.
2059 RevalidationServer server;
2060 transaction.handler = server.Handler;
2061 transaction.request_headers = "Foo: none\r\n";
2062 BoundTestNetLog log;
2063 LoadTimingInfo load_timing_info;
2064 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2065 &load_timing_info);
2067 EXPECT_TRUE(server.EtagUsed());
2068 EXPECT_FALSE(server.LastModifiedUsed());
2069 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2070 EXPECT_EQ(1, cache.disk_cache()->open_count());
2071 EXPECT_EQ(1, cache.disk_cache()->create_count());
2072 TestLoadTimingNetworkRequest(load_timing_info);
2073 RemoveMockTransaction(&transaction);
2076 // Tests lack of revalidation after a vary mismatch and no etag.
2077 TEST(HttpCache, GET_DontValidateCache_VaryMismatch) {
2078 MockHttpCache cache;
2080 // Write to the cache.
2081 MockTransaction transaction(kTypicalGET_Transaction);
2082 transaction.request_headers = "Foo: bar\r\n";
2083 transaction.response_headers =
2084 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2085 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2086 "Cache-Control: max-age=0\n"
2087 "Vary: Foo\n";
2088 AddMockTransaction(&transaction);
2089 RunTransactionTest(cache.http_cache(), transaction);
2091 // Read from the cache and don't revalidate the entry.
2092 RevalidationServer server;
2093 transaction.handler = server.Handler;
2094 transaction.request_headers = "Foo: none\r\n";
2095 BoundTestNetLog log;
2096 LoadTimingInfo load_timing_info;
2097 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2098 &load_timing_info);
2100 EXPECT_FALSE(server.EtagUsed());
2101 EXPECT_FALSE(server.LastModifiedUsed());
2102 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2103 EXPECT_EQ(1, cache.disk_cache()->open_count());
2104 EXPECT_EQ(1, cache.disk_cache()->create_count());
2105 TestLoadTimingNetworkRequest(load_timing_info);
2106 RemoveMockTransaction(&transaction);
2109 // Tests that a new vary header provided when revalidating an entry is saved.
2110 TEST(HttpCache, GET_ValidateCache_VaryMatch_UpdateVary) {
2111 MockHttpCache cache;
2113 // Write to the cache.
2114 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2115 transaction.request_headers = "Foo: bar\r\n Name: bar\r\n";
2116 transaction.response_headers =
2117 "Etag: \"foopy\"\n"
2118 "Cache-Control: max-age=0\n"
2119 "Vary: Foo\n";
2120 RunTransactionTest(cache.http_cache(), transaction);
2122 // Validate the entry and change the vary field in the response.
2123 transaction.request_headers = "Foo: bar\r\n Name: none\r\n";
2124 transaction.status = "HTTP/1.1 304 Not Modified";
2125 transaction.response_headers =
2126 "Etag: \"foopy\"\n"
2127 "Cache-Control: max-age=3600\n"
2128 "Vary: Name\n";
2129 RunTransactionTest(cache.http_cache(), transaction);
2131 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2132 EXPECT_EQ(1, cache.disk_cache()->open_count());
2133 EXPECT_EQ(1, cache.disk_cache()->create_count());
2135 // Make sure that the ActiveEntry is gone.
2136 base::RunLoop().RunUntilIdle();
2138 // Generate a vary mismatch.
2139 transaction.request_headers = "Foo: bar\r\n Name: bar\r\n";
2140 RunTransactionTest(cache.http_cache(), transaction);
2142 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2143 EXPECT_EQ(2, cache.disk_cache()->open_count());
2144 EXPECT_EQ(1, cache.disk_cache()->create_count());
2147 // Tests that new request headers causing a vary mismatch are paired with the
2148 // new response when the server says the old response can be used.
2149 TEST(HttpCache, GET_ValidateCache_VaryMismatch_UpdateRequestHeader) {
2150 MockHttpCache cache;
2152 // Write to the cache.
2153 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2154 transaction.request_headers = "Foo: bar\r\n";
2155 transaction.response_headers =
2156 "Etag: \"foopy\"\n"
2157 "Cache-Control: max-age=3600\n"
2158 "Vary: Foo\n";
2159 RunTransactionTest(cache.http_cache(), transaction);
2161 // Vary-mismatch validation receives 304.
2162 transaction.request_headers = "Foo: none\r\n";
2163 transaction.status = "HTTP/1.1 304 Not Modified";
2164 RunTransactionTest(cache.http_cache(), transaction);
2166 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2167 EXPECT_EQ(1, cache.disk_cache()->open_count());
2168 EXPECT_EQ(1, cache.disk_cache()->create_count());
2170 // Make sure that the ActiveEntry is gone.
2171 base::RunLoop().RunUntilIdle();
2173 // Generate a vary mismatch.
2174 transaction.request_headers = "Foo: bar\r\n";
2175 RunTransactionTest(cache.http_cache(), transaction);
2177 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2178 EXPECT_EQ(2, cache.disk_cache()->open_count());
2179 EXPECT_EQ(1, cache.disk_cache()->create_count());
2182 // Tests that a 304 without vary headers doesn't delete the previously stored
2183 // vary data after a vary match revalidation.
2184 TEST(HttpCache, GET_ValidateCache_VaryMatch_DontDeleteVary) {
2185 MockHttpCache cache;
2187 // Write to the cache.
2188 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2189 transaction.request_headers = "Foo: bar\r\n";
2190 transaction.response_headers =
2191 "Etag: \"foopy\"\n"
2192 "Cache-Control: max-age=0\n"
2193 "Vary: Foo\n";
2194 RunTransactionTest(cache.http_cache(), transaction);
2196 // Validate the entry and remove the vary field in the response.
2197 transaction.status = "HTTP/1.1 304 Not Modified";
2198 transaction.response_headers =
2199 "Etag: \"foopy\"\n"
2200 "Cache-Control: max-age=3600\n";
2201 RunTransactionTest(cache.http_cache(), transaction);
2203 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2204 EXPECT_EQ(1, cache.disk_cache()->open_count());
2205 EXPECT_EQ(1, cache.disk_cache()->create_count());
2207 // Make sure that the ActiveEntry is gone.
2208 base::RunLoop().RunUntilIdle();
2210 // Generate a vary mismatch.
2211 transaction.request_headers = "Foo: none\r\n";
2212 RunTransactionTest(cache.http_cache(), transaction);
2214 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2215 EXPECT_EQ(2, cache.disk_cache()->open_count());
2216 EXPECT_EQ(1, cache.disk_cache()->create_count());
2219 // Tests that a 304 without vary headers doesn't delete the previously stored
2220 // vary data after a vary mismatch.
2221 TEST(HttpCache, GET_ValidateCache_VaryMismatch_DontDeleteVary) {
2222 MockHttpCache cache;
2224 // Write to the cache.
2225 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2226 transaction.request_headers = "Foo: bar\r\n";
2227 transaction.response_headers =
2228 "Etag: \"foopy\"\n"
2229 "Cache-Control: max-age=3600\n"
2230 "Vary: Foo\n";
2231 RunTransactionTest(cache.http_cache(), transaction);
2233 // Vary-mismatch validation receives 304 and no vary header.
2234 transaction.request_headers = "Foo: none\r\n";
2235 transaction.status = "HTTP/1.1 304 Not Modified";
2236 transaction.response_headers =
2237 "Etag: \"foopy\"\n"
2238 "Cache-Control: max-age=3600\n";
2239 RunTransactionTest(cache.http_cache(), transaction);
2241 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2242 EXPECT_EQ(1, cache.disk_cache()->open_count());
2243 EXPECT_EQ(1, cache.disk_cache()->create_count());
2245 // Make sure that the ActiveEntry is gone.
2246 base::RunLoop().RunUntilIdle();
2248 // Generate a vary mismatch.
2249 transaction.request_headers = "Foo: bar\r\n";
2250 RunTransactionTest(cache.http_cache(), transaction);
2252 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2253 EXPECT_EQ(2, cache.disk_cache()->open_count());
2254 EXPECT_EQ(1, cache.disk_cache()->create_count());
2257 static void ETagGet_UnconditionalRequest_Handler(const HttpRequestInfo* request,
2258 std::string* response_status,
2259 std::string* response_headers,
2260 std::string* response_data) {
2261 EXPECT_FALSE(
2262 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
2265 TEST(HttpCache, ETagGET_Http10) {
2266 MockHttpCache cache;
2268 ScopedMockTransaction transaction(kETagGET_Transaction);
2269 transaction.status = "HTTP/1.0 200 OK";
2271 // Write to the cache.
2272 RunTransactionTest(cache.http_cache(), transaction);
2274 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2275 EXPECT_EQ(0, cache.disk_cache()->open_count());
2276 EXPECT_EQ(1, cache.disk_cache()->create_count());
2278 // Get the same URL again, without generating a conditional request.
2279 transaction.load_flags = LOAD_VALIDATE_CACHE;
2280 transaction.handler = ETagGet_UnconditionalRequest_Handler;
2281 RunTransactionTest(cache.http_cache(), transaction);
2283 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2284 EXPECT_EQ(1, cache.disk_cache()->open_count());
2285 EXPECT_EQ(1, cache.disk_cache()->create_count());
2288 TEST(HttpCache, ETagGET_Http10_Range) {
2289 MockHttpCache cache;
2291 ScopedMockTransaction transaction(kETagGET_Transaction);
2292 transaction.status = "HTTP/1.0 200 OK";
2294 // Write to the cache.
2295 RunTransactionTest(cache.http_cache(), transaction);
2297 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2298 EXPECT_EQ(0, cache.disk_cache()->open_count());
2299 EXPECT_EQ(1, cache.disk_cache()->create_count());
2301 // Get the same URL again, but use a byte range request.
2302 transaction.load_flags = LOAD_VALIDATE_CACHE;
2303 transaction.handler = ETagGet_UnconditionalRequest_Handler;
2304 transaction.request_headers = "Range: bytes = 5-\r\n";
2305 RunTransactionTest(cache.http_cache(), transaction);
2307 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2308 EXPECT_EQ(1, cache.disk_cache()->open_count());
2309 EXPECT_EQ(2, cache.disk_cache()->create_count());
2312 static void ETagGet_ConditionalRequest_NoStore_Handler(
2313 const HttpRequestInfo* request,
2314 std::string* response_status,
2315 std::string* response_headers,
2316 std::string* response_data) {
2317 EXPECT_TRUE(
2318 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
2319 response_status->assign("HTTP/1.1 304 Not Modified");
2320 response_headers->assign("Cache-Control: no-store\n");
2321 response_data->clear();
2324 TEST(HttpCache, ETagGET_ConditionalRequest_304_NoStore) {
2325 MockHttpCache cache;
2327 ScopedMockTransaction transaction(kETagGET_Transaction);
2329 // Write to the cache.
2330 RunTransactionTest(cache.http_cache(), transaction);
2332 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2333 EXPECT_EQ(0, cache.disk_cache()->open_count());
2334 EXPECT_EQ(1, cache.disk_cache()->create_count());
2336 // Get the same URL again, but this time we expect it to result
2337 // in a conditional request.
2338 transaction.load_flags = LOAD_VALIDATE_CACHE;
2339 transaction.handler = ETagGet_ConditionalRequest_NoStore_Handler;
2340 RunTransactionTest(cache.http_cache(), transaction);
2342 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2343 EXPECT_EQ(1, cache.disk_cache()->open_count());
2344 EXPECT_EQ(1, cache.disk_cache()->create_count());
2346 ScopedMockTransaction transaction2(kETagGET_Transaction);
2348 // Write to the cache again. This should create a new entry.
2349 RunTransactionTest(cache.http_cache(), transaction2);
2351 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2352 EXPECT_EQ(1, cache.disk_cache()->open_count());
2353 EXPECT_EQ(2, cache.disk_cache()->create_count());
2356 // Helper that does 4 requests using HttpCache:
2358 // (1) loads |kUrl| -- expects |net_response_1| to be returned.
2359 // (2) loads |kUrl| from cache only -- expects |net_response_1| to be returned.
2360 // (3) loads |kUrl| using |extra_request_headers| -- expects |net_response_2| to
2361 // be returned.
2362 // (4) loads |kUrl| from cache only -- expects |cached_response_2| to be
2363 // returned.
2364 static void ConditionalizedRequestUpdatesCacheHelper(
2365 const Response& net_response_1,
2366 const Response& net_response_2,
2367 const Response& cached_response_2,
2368 const char* extra_request_headers) {
2369 MockHttpCache cache;
2371 // The URL we will be requesting.
2372 const char kUrl[] = "http://foobar.com/main.css";
2374 // Junk network response.
2375 static const Response kUnexpectedResponse = {
2376 "HTTP/1.1 500 Unexpected",
2377 "Server: unexpected_header",
2378 "unexpected body"
2381 // We will control the network layer's responses for |kUrl| using
2382 // |mock_network_response|.
2383 MockTransaction mock_network_response = { 0 };
2384 mock_network_response.url = kUrl;
2385 AddMockTransaction(&mock_network_response);
2387 // Request |kUrl| for the first time. It should hit the network and
2388 // receive |kNetResponse1|, which it saves into the HTTP cache.
2390 MockTransaction request = { 0 };
2391 request.url = kUrl;
2392 request.method = "GET";
2393 request.request_headers = "";
2395 net_response_1.AssignTo(&mock_network_response); // Network mock.
2396 net_response_1.AssignTo(&request); // Expected result.
2398 std::string response_headers;
2399 RunTransactionTestWithResponse(
2400 cache.http_cache(), request, &response_headers);
2402 EXPECT_EQ(net_response_1.status_and_headers(), response_headers);
2403 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2404 EXPECT_EQ(0, cache.disk_cache()->open_count());
2405 EXPECT_EQ(1, cache.disk_cache()->create_count());
2407 // Request |kUrl| a second time. Now |kNetResponse1| it is in the HTTP
2408 // cache, so we don't hit the network.
2410 request.load_flags = LOAD_ONLY_FROM_CACHE;
2412 kUnexpectedResponse.AssignTo(&mock_network_response); // Network mock.
2413 net_response_1.AssignTo(&request); // Expected result.
2415 RunTransactionTestWithResponse(
2416 cache.http_cache(), request, &response_headers);
2418 EXPECT_EQ(net_response_1.status_and_headers(), response_headers);
2419 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2420 EXPECT_EQ(1, cache.disk_cache()->open_count());
2421 EXPECT_EQ(1, cache.disk_cache()->create_count());
2423 // Request |kUrl| yet again, but this time give the request an
2424 // "If-Modified-Since" header. This will cause the request to re-hit the
2425 // network. However now the network response is going to be
2426 // different -- this simulates a change made to the CSS file.
2428 request.request_headers = extra_request_headers;
2429 request.load_flags = LOAD_NORMAL;
2431 net_response_2.AssignTo(&mock_network_response); // Network mock.
2432 net_response_2.AssignTo(&request); // Expected result.
2434 RunTransactionTestWithResponse(
2435 cache.http_cache(), request, &response_headers);
2437 EXPECT_EQ(net_response_2.status_and_headers(), response_headers);
2438 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2439 EXPECT_EQ(1, cache.disk_cache()->open_count());
2440 EXPECT_EQ(1, cache.disk_cache()->create_count());
2442 // Finally, request |kUrl| again. This request should be serviced from
2443 // the cache. Moreover, the value in the cache should be |kNetResponse2|
2444 // and NOT |kNetResponse1|. The previous step should have replaced the
2445 // value in the cache with the modified response.
2447 request.request_headers = "";
2448 request.load_flags = LOAD_ONLY_FROM_CACHE;
2450 kUnexpectedResponse.AssignTo(&mock_network_response); // Network mock.
2451 cached_response_2.AssignTo(&request); // Expected result.
2453 RunTransactionTestWithResponse(
2454 cache.http_cache(), request, &response_headers);
2456 EXPECT_EQ(cached_response_2.status_and_headers(), response_headers);
2457 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2458 EXPECT_EQ(2, cache.disk_cache()->open_count());
2459 EXPECT_EQ(1, cache.disk_cache()->create_count());
2461 RemoveMockTransaction(&mock_network_response);
2464 // Check that when an "if-modified-since" header is attached
2465 // to the request, the result still updates the cached entry.
2466 TEST(HttpCache, ConditionalizedRequestUpdatesCache1) {
2467 // First network response for |kUrl|.
2468 static const Response kNetResponse1 = {
2469 "HTTP/1.1 200 OK",
2470 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2471 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2472 "body1"
2475 // Second network response for |kUrl|.
2476 static const Response kNetResponse2 = {
2477 "HTTP/1.1 200 OK",
2478 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2479 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2480 "body2"
2483 const char extra_headers[] =
2484 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2486 ConditionalizedRequestUpdatesCacheHelper(
2487 kNetResponse1, kNetResponse2, kNetResponse2, extra_headers);
2490 // Check that when an "if-none-match" header is attached
2491 // to the request, the result updates the cached entry.
2492 TEST(HttpCache, ConditionalizedRequestUpdatesCache2) {
2493 // First network response for |kUrl|.
2494 static const Response kNetResponse1 = {
2495 "HTTP/1.1 200 OK",
2496 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2497 "Etag: \"ETAG1\"\n"
2498 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n", // Should never expire.
2499 "body1"
2502 // Second network response for |kUrl|.
2503 static const Response kNetResponse2 = {
2504 "HTTP/1.1 200 OK",
2505 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2506 "Etag: \"ETAG2\"\n"
2507 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n", // Should never expire.
2508 "body2"
2511 const char extra_headers[] = "If-None-Match: \"ETAG1\"\r\n";
2513 ConditionalizedRequestUpdatesCacheHelper(
2514 kNetResponse1, kNetResponse2, kNetResponse2, extra_headers);
2517 // Check that when an "if-modified-since" header is attached
2518 // to a request, the 304 (not modified result) result updates the cached
2519 // headers, and the 304 response is returned rather than the cached response.
2520 TEST(HttpCache, ConditionalizedRequestUpdatesCache3) {
2521 // First network response for |kUrl|.
2522 static const Response kNetResponse1 = {
2523 "HTTP/1.1 200 OK",
2524 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2525 "Server: server1\n"
2526 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2527 "body1"
2530 // Second network response for |kUrl|.
2531 static const Response kNetResponse2 = {
2532 "HTTP/1.1 304 Not Modified",
2533 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2534 "Server: server2\n"
2535 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2539 static const Response kCachedResponse2 = {
2540 "HTTP/1.1 200 OK",
2541 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2542 "Server: server2\n"
2543 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2544 "body1"
2547 const char extra_headers[] =
2548 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2550 ConditionalizedRequestUpdatesCacheHelper(
2551 kNetResponse1, kNetResponse2, kCachedResponse2, extra_headers);
2554 // Test that when doing an externally conditionalized if-modified-since
2555 // and there is no corresponding cache entry, a new cache entry is NOT
2556 // created (304 response).
2557 TEST(HttpCache, ConditionalizedRequestUpdatesCache4) {
2558 MockHttpCache cache;
2560 const char kUrl[] = "http://foobar.com/main.css";
2562 static const Response kNetResponse = {
2563 "HTTP/1.1 304 Not Modified",
2564 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2565 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2569 const char kExtraRequestHeaders[] =
2570 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2572 // We will control the network layer's responses for |kUrl| using
2573 // |mock_network_response|.
2574 MockTransaction mock_network_response = { 0 };
2575 mock_network_response.url = kUrl;
2576 AddMockTransaction(&mock_network_response);
2578 MockTransaction request = { 0 };
2579 request.url = kUrl;
2580 request.method = "GET";
2581 request.request_headers = kExtraRequestHeaders;
2583 kNetResponse.AssignTo(&mock_network_response); // Network mock.
2584 kNetResponse.AssignTo(&request); // Expected result.
2586 std::string response_headers;
2587 RunTransactionTestWithResponse(
2588 cache.http_cache(), request, &response_headers);
2590 EXPECT_EQ(kNetResponse.status_and_headers(), response_headers);
2591 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2592 EXPECT_EQ(0, cache.disk_cache()->open_count());
2593 EXPECT_EQ(0, cache.disk_cache()->create_count());
2595 RemoveMockTransaction(&mock_network_response);
2598 // Test that when doing an externally conditionalized if-modified-since
2599 // and there is no corresponding cache entry, a new cache entry is NOT
2600 // created (200 response).
2601 TEST(HttpCache, ConditionalizedRequestUpdatesCache5) {
2602 MockHttpCache cache;
2604 const char kUrl[] = "http://foobar.com/main.css";
2606 static const Response kNetResponse = {
2607 "HTTP/1.1 200 OK",
2608 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2609 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2610 "foobar!!!"
2613 const char kExtraRequestHeaders[] =
2614 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2616 // We will control the network layer's responses for |kUrl| using
2617 // |mock_network_response|.
2618 MockTransaction mock_network_response = { 0 };
2619 mock_network_response.url = kUrl;
2620 AddMockTransaction(&mock_network_response);
2622 MockTransaction request = { 0 };
2623 request.url = kUrl;
2624 request.method = "GET";
2625 request.request_headers = kExtraRequestHeaders;
2627 kNetResponse.AssignTo(&mock_network_response); // Network mock.
2628 kNetResponse.AssignTo(&request); // Expected result.
2630 std::string response_headers;
2631 RunTransactionTestWithResponse(
2632 cache.http_cache(), request, &response_headers);
2634 EXPECT_EQ(kNetResponse.status_and_headers(), response_headers);
2635 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2636 EXPECT_EQ(0, cache.disk_cache()->open_count());
2637 EXPECT_EQ(0, cache.disk_cache()->create_count());
2639 RemoveMockTransaction(&mock_network_response);
2642 // Test that when doing an externally conditionalized if-modified-since
2643 // if the date does not match the cache entry's last-modified date,
2644 // then we do NOT use the response (304) to update the cache.
2645 // (the if-modified-since date is 2 days AFTER the cache's modification date).
2646 TEST(HttpCache, ConditionalizedRequestUpdatesCache6) {
2647 static const Response kNetResponse1 = {
2648 "HTTP/1.1 200 OK",
2649 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2650 "Server: server1\n"
2651 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2652 "body1"
2655 // Second network response for |kUrl|.
2656 static const Response kNetResponse2 = {
2657 "HTTP/1.1 304 Not Modified",
2658 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2659 "Server: server2\n"
2660 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2664 // This is two days in the future from the original response's last-modified
2665 // date!
2666 const char kExtraRequestHeaders[] =
2667 "If-Modified-Since: Fri, 08 Feb 2008 22:38:21 GMT\r\n";
2669 ConditionalizedRequestUpdatesCacheHelper(
2670 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2673 // Test that when doing an externally conditionalized if-none-match
2674 // if the etag does not match the cache entry's etag, then we do not use the
2675 // response (304) to update the cache.
2676 TEST(HttpCache, ConditionalizedRequestUpdatesCache7) {
2677 static const Response kNetResponse1 = {
2678 "HTTP/1.1 200 OK",
2679 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2680 "Etag: \"Foo1\"\n"
2681 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2682 "body1"
2685 // Second network response for |kUrl|.
2686 static const Response kNetResponse2 = {
2687 "HTTP/1.1 304 Not Modified",
2688 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2689 "Etag: \"Foo2\"\n"
2690 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2694 // Different etag from original response.
2695 const char kExtraRequestHeaders[] = "If-None-Match: \"Foo2\"\r\n";
2697 ConditionalizedRequestUpdatesCacheHelper(
2698 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2701 // Test that doing an externally conditionalized request with both if-none-match
2702 // and if-modified-since updates the cache.
2703 TEST(HttpCache, ConditionalizedRequestUpdatesCache8) {
2704 static const Response kNetResponse1 = {
2705 "HTTP/1.1 200 OK",
2706 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2707 "Etag: \"Foo1\"\n"
2708 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2709 "body1"
2712 // Second network response for |kUrl|.
2713 static const Response kNetResponse2 = {
2714 "HTTP/1.1 200 OK",
2715 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2716 "Etag: \"Foo2\"\n"
2717 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2718 "body2"
2721 const char kExtraRequestHeaders[] =
2722 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n"
2723 "If-None-Match: \"Foo1\"\r\n";
2725 ConditionalizedRequestUpdatesCacheHelper(
2726 kNetResponse1, kNetResponse2, kNetResponse2, kExtraRequestHeaders);
2729 // Test that doing an externally conditionalized request with both if-none-match
2730 // and if-modified-since does not update the cache with only one match.
2731 TEST(HttpCache, ConditionalizedRequestUpdatesCache9) {
2732 static const Response kNetResponse1 = {
2733 "HTTP/1.1 200 OK",
2734 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2735 "Etag: \"Foo1\"\n"
2736 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2737 "body1"
2740 // Second network response for |kUrl|.
2741 static const Response kNetResponse2 = {
2742 "HTTP/1.1 200 OK",
2743 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2744 "Etag: \"Foo2\"\n"
2745 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2746 "body2"
2749 // The etag doesn't match what we have stored.
2750 const char kExtraRequestHeaders[] =
2751 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n"
2752 "If-None-Match: \"Foo2\"\r\n";
2754 ConditionalizedRequestUpdatesCacheHelper(
2755 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2758 // Test that doing an externally conditionalized request with both if-none-match
2759 // and if-modified-since does not update the cache with only one match.
2760 TEST(HttpCache, ConditionalizedRequestUpdatesCache10) {
2761 static const Response kNetResponse1 = {
2762 "HTTP/1.1 200 OK",
2763 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2764 "Etag: \"Foo1\"\n"
2765 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2766 "body1"
2769 // Second network response for |kUrl|.
2770 static const Response kNetResponse2 = {
2771 "HTTP/1.1 200 OK",
2772 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2773 "Etag: \"Foo2\"\n"
2774 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2775 "body2"
2778 // The modification date doesn't match what we have stored.
2779 const char kExtraRequestHeaders[] =
2780 "If-Modified-Since: Fri, 08 Feb 2008 22:38:21 GMT\r\n"
2781 "If-None-Match: \"Foo1\"\r\n";
2783 ConditionalizedRequestUpdatesCacheHelper(
2784 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2787 TEST(HttpCache, UrlContainingHash) {
2788 MockHttpCache cache;
2790 // Do a typical GET request -- should write an entry into our cache.
2791 MockTransaction trans(kTypicalGET_Transaction);
2792 RunTransactionTest(cache.http_cache(), trans);
2794 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2795 EXPECT_EQ(0, cache.disk_cache()->open_count());
2796 EXPECT_EQ(1, cache.disk_cache()->create_count());
2798 // Request the same URL, but this time with a reference section (hash).
2799 // Since the cache key strips the hash sections, this should be a cache hit.
2800 std::string url_with_hash = std::string(trans.url) + "#multiple#hashes";
2801 trans.url = url_with_hash.c_str();
2802 trans.load_flags = LOAD_ONLY_FROM_CACHE;
2804 RunTransactionTest(cache.http_cache(), trans);
2806 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2807 EXPECT_EQ(1, cache.disk_cache()->open_count());
2808 EXPECT_EQ(1, cache.disk_cache()->create_count());
2811 // Tests that we skip the cache for POST requests that do not have an upload
2812 // identifier.
2813 TEST(HttpCache, SimplePOST_SkipsCache) {
2814 MockHttpCache cache;
2816 RunTransactionTest(cache.http_cache(), kSimplePOST_Transaction);
2818 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2819 EXPECT_EQ(0, cache.disk_cache()->open_count());
2820 EXPECT_EQ(0, cache.disk_cache()->create_count());
2823 // Tests POST handling with a disabled cache (no DCHECK).
2824 TEST(HttpCache, SimplePOST_DisabledCache) {
2825 MockHttpCache cache;
2826 cache.http_cache()->set_mode(HttpCache::Mode::DISABLE);
2828 RunTransactionTest(cache.http_cache(), kSimplePOST_Transaction);
2830 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2831 EXPECT_EQ(0, cache.disk_cache()->open_count());
2832 EXPECT_EQ(0, cache.disk_cache()->create_count());
2835 TEST(HttpCache, SimplePOST_LoadOnlyFromCache_Miss) {
2836 MockHttpCache cache;
2838 MockTransaction transaction(kSimplePOST_Transaction);
2839 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
2841 MockHttpRequest request(transaction);
2842 TestCompletionCallback callback;
2844 scoped_ptr<HttpTransaction> trans;
2845 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
2846 ASSERT_TRUE(trans.get());
2848 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2849 ASSERT_EQ(ERR_CACHE_MISS, callback.GetResult(rv));
2851 trans.reset();
2853 EXPECT_EQ(0, cache.network_layer()->transaction_count());
2854 EXPECT_EQ(0, cache.disk_cache()->open_count());
2855 EXPECT_EQ(0, cache.disk_cache()->create_count());
2858 TEST(HttpCache, SimplePOST_LoadOnlyFromCache_Hit) {
2859 MockHttpCache cache;
2861 // Test that we hit the cache for POST requests.
2863 MockTransaction transaction(kSimplePOST_Transaction);
2865 const int64 kUploadId = 1; // Just a dummy value.
2867 ScopedVector<UploadElementReader> element_readers;
2868 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2869 ElementsUploadDataStream upload_data_stream(element_readers.Pass(),
2870 kUploadId);
2871 MockHttpRequest request(transaction);
2872 request.upload_data_stream = &upload_data_stream;
2874 // Populate the cache.
2875 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2877 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2878 EXPECT_EQ(0, cache.disk_cache()->open_count());
2879 EXPECT_EQ(1, cache.disk_cache()->create_count());
2881 // Load from cache.
2882 request.load_flags |= LOAD_ONLY_FROM_CACHE;
2883 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2885 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2886 EXPECT_EQ(1, cache.disk_cache()->open_count());
2887 EXPECT_EQ(1, cache.disk_cache()->create_count());
2890 // Test that we don't hit the cache for POST requests if there is a byte range.
2891 TEST(HttpCache, SimplePOST_WithRanges) {
2892 MockHttpCache cache;
2894 MockTransaction transaction(kSimplePOST_Transaction);
2895 transaction.request_headers = "Range: bytes = 0-4\r\n";
2897 const int64 kUploadId = 1; // Just a dummy value.
2899 ScopedVector<UploadElementReader> element_readers;
2900 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2901 ElementsUploadDataStream upload_data_stream(element_readers.Pass(),
2902 kUploadId);
2904 MockHttpRequest request(transaction);
2905 request.upload_data_stream = &upload_data_stream;
2907 // Attempt to populate the cache.
2908 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2910 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2911 EXPECT_EQ(0, cache.disk_cache()->open_count());
2912 EXPECT_EQ(0, cache.disk_cache()->create_count());
2915 // Tests that a POST is cached separately from a previously cached GET.
2916 TEST(HttpCache, SimplePOST_SeparateCache) {
2917 MockHttpCache cache;
2919 ScopedVector<UploadElementReader> element_readers;
2920 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2921 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
2923 MockTransaction transaction(kSimplePOST_Transaction);
2924 MockHttpRequest req1(transaction);
2925 req1.upload_data_stream = &upload_data_stream;
2927 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2929 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2930 EXPECT_EQ(0, cache.disk_cache()->open_count());
2931 EXPECT_EQ(1, cache.disk_cache()->create_count());
2933 transaction.method = "GET";
2934 MockHttpRequest req2(transaction);
2936 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
2938 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2939 EXPECT_EQ(0, cache.disk_cache()->open_count());
2940 EXPECT_EQ(2, cache.disk_cache()->create_count());
2943 // Tests that a successful POST invalidates a previously cached GET.
2944 TEST(HttpCache, SimplePOST_Invalidate_205) {
2945 MockHttpCache cache;
2947 MockTransaction transaction(kSimpleGET_Transaction);
2948 AddMockTransaction(&transaction);
2949 MockHttpRequest req1(transaction);
2951 // Attempt to populate the cache.
2952 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2954 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2955 EXPECT_EQ(0, cache.disk_cache()->open_count());
2956 EXPECT_EQ(1, cache.disk_cache()->create_count());
2958 ScopedVector<UploadElementReader> element_readers;
2959 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2960 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
2962 transaction.method = "POST";
2963 transaction.status = "HTTP/1.1 205 No Content";
2964 MockHttpRequest req2(transaction);
2965 req2.upload_data_stream = &upload_data_stream;
2967 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
2969 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2970 EXPECT_EQ(0, cache.disk_cache()->open_count());
2971 EXPECT_EQ(2, cache.disk_cache()->create_count());
2973 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2975 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2976 EXPECT_EQ(0, cache.disk_cache()->open_count());
2977 EXPECT_EQ(3, cache.disk_cache()->create_count());
2978 RemoveMockTransaction(&transaction);
2981 // Tests that a successful POST invalidates a previously cached GET, even when
2982 // there is no upload identifier.
2983 TEST(HttpCache, SimplePOST_NoUploadId_Invalidate_205) {
2984 MockHttpCache cache;
2986 MockTransaction transaction(kSimpleGET_Transaction);
2987 AddMockTransaction(&transaction);
2988 MockHttpRequest req1(transaction);
2990 // Attempt to populate the cache.
2991 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2993 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2994 EXPECT_EQ(0, cache.disk_cache()->open_count());
2995 EXPECT_EQ(1, cache.disk_cache()->create_count());
2997 ScopedVector<UploadElementReader> element_readers;
2998 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2999 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3001 transaction.method = "POST";
3002 transaction.status = "HTTP/1.1 205 No Content";
3003 MockHttpRequest req2(transaction);
3004 req2.upload_data_stream = &upload_data_stream;
3006 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3008 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3009 EXPECT_EQ(0, cache.disk_cache()->open_count());
3010 EXPECT_EQ(1, cache.disk_cache()->create_count());
3012 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3014 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3015 EXPECT_EQ(0, cache.disk_cache()->open_count());
3016 EXPECT_EQ(2, cache.disk_cache()->create_count());
3017 RemoveMockTransaction(&transaction);
3020 // Tests that processing a POST before creating the backend doesn't crash.
3021 TEST(HttpCache, SimplePOST_NoUploadId_NoBackend) {
3022 // This will initialize a cache object with NULL backend.
3023 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
3024 factory->set_fail(true);
3025 factory->FinishCreation();
3026 MockHttpCache cache(factory);
3028 ScopedVector<UploadElementReader> element_readers;
3029 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3030 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3032 MockTransaction transaction(kSimplePOST_Transaction);
3033 AddMockTransaction(&transaction);
3034 MockHttpRequest req(transaction);
3035 req.upload_data_stream = &upload_data_stream;
3037 RunTransactionTestWithRequest(cache.http_cache(), transaction, req, NULL);
3039 RemoveMockTransaction(&transaction);
3042 // Tests that we don't invalidate entries as a result of a failed POST.
3043 TEST(HttpCache, SimplePOST_DontInvalidate_100) {
3044 MockHttpCache cache;
3046 MockTransaction transaction(kSimpleGET_Transaction);
3047 AddMockTransaction(&transaction);
3048 MockHttpRequest req1(transaction);
3050 // Attempt to populate the cache.
3051 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3053 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3054 EXPECT_EQ(0, cache.disk_cache()->open_count());
3055 EXPECT_EQ(1, cache.disk_cache()->create_count());
3057 ScopedVector<UploadElementReader> element_readers;
3058 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3059 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
3061 transaction.method = "POST";
3062 transaction.status = "HTTP/1.1 100 Continue";
3063 MockHttpRequest req2(transaction);
3064 req2.upload_data_stream = &upload_data_stream;
3066 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3068 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3069 EXPECT_EQ(0, cache.disk_cache()->open_count());
3070 EXPECT_EQ(2, cache.disk_cache()->create_count());
3072 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3074 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3075 EXPECT_EQ(1, cache.disk_cache()->open_count());
3076 EXPECT_EQ(2, cache.disk_cache()->create_count());
3077 RemoveMockTransaction(&transaction);
3080 // Tests that a HEAD request is not cached by itself.
3081 TEST(HttpCache, SimpleHEAD_LoadOnlyFromCache_Miss) {
3082 MockHttpCache cache;
3083 MockTransaction transaction(kSimplePOST_Transaction);
3084 AddMockTransaction(&transaction);
3085 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3086 transaction.method = "HEAD";
3088 MockHttpRequest request(transaction);
3089 TestCompletionCallback callback;
3091 scoped_ptr<HttpTransaction> trans;
3092 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
3093 ASSERT_TRUE(trans.get());
3095 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
3096 ASSERT_EQ(ERR_CACHE_MISS, callback.GetResult(rv));
3098 trans.reset();
3100 EXPECT_EQ(0, cache.network_layer()->transaction_count());
3101 EXPECT_EQ(0, cache.disk_cache()->open_count());
3102 EXPECT_EQ(0, cache.disk_cache()->create_count());
3103 RemoveMockTransaction(&transaction);
3106 // Tests that a HEAD request is served from a cached GET.
3107 TEST(HttpCache, SimpleHEAD_LoadOnlyFromCache_Hit) {
3108 MockHttpCache cache;
3109 MockTransaction transaction(kSimpleGET_Transaction);
3110 AddMockTransaction(&transaction);
3112 // Populate the cache.
3113 RunTransactionTest(cache.http_cache(), transaction);
3115 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3116 EXPECT_EQ(0, cache.disk_cache()->open_count());
3117 EXPECT_EQ(1, cache.disk_cache()->create_count());
3119 // Load from cache.
3120 transaction.method = "HEAD";
3121 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3122 transaction.data = "";
3123 RunTransactionTest(cache.http_cache(), transaction);
3125 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3126 EXPECT_EQ(1, cache.disk_cache()->open_count());
3127 EXPECT_EQ(1, cache.disk_cache()->create_count());
3128 RemoveMockTransaction(&transaction);
3131 // Tests that a read-only request served from the cache preserves CL.
3132 TEST(HttpCache, SimpleHEAD_ContentLengthOnHit_Read) {
3133 MockHttpCache cache;
3134 MockTransaction transaction(kSimpleGET_Transaction);
3135 AddMockTransaction(&transaction);
3136 transaction.response_headers = "Content-Length: 42\n";
3138 // Populate the cache.
3139 RunTransactionTest(cache.http_cache(), transaction);
3141 // Load from cache.
3142 transaction.method = "HEAD";
3143 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3144 transaction.data = "";
3145 std::string headers;
3147 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3149 EXPECT_EQ("HTTP/1.1 200 OK\nContent-Length: 42\n", headers);
3150 RemoveMockTransaction(&transaction);
3153 // Tests that a read-write request served from the cache preserves CL.
3154 TEST(HttpCache, ETagHEAD_ContentLengthOnHit_ReadWrite) {
3155 MockHttpCache cache;
3156 MockTransaction transaction(kETagGET_Transaction);
3157 AddMockTransaction(&transaction);
3158 std::string server_headers(kETagGET_Transaction.response_headers);
3159 server_headers.append("Content-Length: 42\n");
3160 transaction.response_headers = server_headers.data();
3162 // Populate the cache.
3163 RunTransactionTest(cache.http_cache(), transaction);
3165 // Load from cache.
3166 transaction.method = "HEAD";
3167 transaction.data = "";
3168 std::string headers;
3170 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3172 EXPECT_NE(std::string::npos, headers.find("Content-Length: 42\n"));
3173 RemoveMockTransaction(&transaction);
3176 // Tests that a HEAD request that includes byte ranges bypasses the cache.
3177 TEST(HttpCache, SimpleHEAD_WithRanges) {
3178 MockHttpCache cache;
3179 MockTransaction transaction(kSimpleGET_Transaction);
3180 AddMockTransaction(&transaction);
3182 // Populate the cache.
3183 RunTransactionTest(cache.http_cache(), transaction);
3185 // Load from cache.
3186 transaction.method = "HEAD";
3187 transaction.request_headers = "Range: bytes = 0-4\r\n";
3188 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3189 transaction.return_code = ERR_CACHE_MISS;
3190 RunTransactionTest(cache.http_cache(), transaction);
3192 EXPECT_EQ(0, cache.disk_cache()->open_count());
3193 EXPECT_EQ(1, cache.disk_cache()->create_count());
3194 RemoveMockTransaction(&transaction);
3197 // Tests that a HEAD request can be served from a partialy cached resource.
3198 TEST(HttpCache, SimpleHEAD_WithCachedRanges) {
3199 MockHttpCache cache;
3200 AddMockTransaction(&kRangeGET_TransactionOK);
3202 // Write to the cache (40-49).
3203 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
3204 RemoveMockTransaction(&kRangeGET_TransactionOK);
3206 MockTransaction transaction(kSimpleGET_Transaction);
3208 transaction.url = kRangeGET_TransactionOK.url;
3209 transaction.method = "HEAD";
3210 transaction.data = "";
3211 AddMockTransaction(&transaction);
3212 std::string headers;
3214 // Load from cache.
3215 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3217 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3218 EXPECT_NE(std::string::npos, headers.find("Content-Length: 80\n"));
3219 EXPECT_EQ(std::string::npos, headers.find("Content-Range"));
3220 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3221 EXPECT_EQ(1, cache.disk_cache()->open_count());
3222 EXPECT_EQ(1, cache.disk_cache()->create_count());
3223 RemoveMockTransaction(&transaction);
3226 // Tests that a HEAD request can be served from a truncated resource.
3227 TEST(HttpCache, SimpleHEAD_WithTruncatedEntry) {
3228 MockHttpCache cache;
3229 AddMockTransaction(&kRangeGET_TransactionOK);
3231 std::string raw_headers("HTTP/1.1 200 OK\n"
3232 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
3233 "ETag: \"foo\"\n"
3234 "Accept-Ranges: bytes\n"
3235 "Content-Length: 80\n");
3236 CreateTruncatedEntry(raw_headers, &cache);
3237 RemoveMockTransaction(&kRangeGET_TransactionOK);
3239 MockTransaction transaction(kSimpleGET_Transaction);
3241 transaction.url = kRangeGET_TransactionOK.url;
3242 transaction.method = "HEAD";
3243 transaction.data = "";
3244 AddMockTransaction(&transaction);
3245 std::string headers;
3247 // Load from cache.
3248 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3250 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3251 EXPECT_NE(std::string::npos, headers.find("Content-Length: 80\n"));
3252 EXPECT_EQ(std::string::npos, headers.find("Content-Range"));
3253 EXPECT_EQ(0, cache.network_layer()->transaction_count());
3254 EXPECT_EQ(1, cache.disk_cache()->open_count());
3255 EXPECT_EQ(1, cache.disk_cache()->create_count());
3256 RemoveMockTransaction(&transaction);
3259 // Tests that a HEAD request updates the cached response.
3260 TEST(HttpCache, TypicalHEAD_UpdatesResponse) {
3261 MockHttpCache cache;
3262 MockTransaction transaction(kTypicalGET_Transaction);
3263 AddMockTransaction(&transaction);
3265 // Populate the cache.
3266 RunTransactionTest(cache.http_cache(), transaction);
3268 // Update the cache.
3269 transaction.method = "HEAD";
3270 transaction.response_headers = "Foo: bar\n";
3271 transaction.data = "";
3272 transaction.status = "HTTP/1.1 304 Not Modified\n";
3273 std::string headers;
3274 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3275 RemoveMockTransaction(&transaction);
3277 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3278 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3280 MockTransaction transaction2(kTypicalGET_Transaction);
3281 AddMockTransaction(&transaction2);
3283 // Make sure we are done with the previous transaction.
3284 base::MessageLoop::current()->RunUntilIdle();
3286 // Load from the cache.
3287 transaction2.load_flags |= LOAD_ONLY_FROM_CACHE;
3288 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
3290 EXPECT_NE(std::string::npos, headers.find("Foo: bar\n"));
3291 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3292 EXPECT_EQ(2, cache.disk_cache()->open_count());
3293 EXPECT_EQ(1, cache.disk_cache()->create_count());
3294 RemoveMockTransaction(&transaction2);
3297 // Tests that an externally conditionalized HEAD request updates the cache.
3298 TEST(HttpCache, TypicalHEAD_ConditionalizedRequestUpdatesResponse) {
3299 MockHttpCache cache;
3300 MockTransaction transaction(kTypicalGET_Transaction);
3301 AddMockTransaction(&transaction);
3303 // Populate the cache.
3304 RunTransactionTest(cache.http_cache(), transaction);
3306 // Update the cache.
3307 transaction.method = "HEAD";
3308 transaction.request_headers =
3309 "If-Modified-Since: Wed, 28 Nov 2007 00:40:09 GMT\r\n";
3310 transaction.response_headers = "Foo: bar\n";
3311 transaction.data = "";
3312 transaction.status = "HTTP/1.1 304 Not Modified\n";
3313 std::string headers;
3314 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3315 RemoveMockTransaction(&transaction);
3317 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 304 Not Modified\n"));
3318 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3320 MockTransaction transaction2(kTypicalGET_Transaction);
3321 AddMockTransaction(&transaction2);
3323 // Make sure we are done with the previous transaction.
3324 base::MessageLoop::current()->RunUntilIdle();
3326 // Load from the cache.
3327 transaction2.load_flags |= LOAD_ONLY_FROM_CACHE;
3328 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
3330 EXPECT_NE(std::string::npos, headers.find("Foo: bar\n"));
3331 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3332 EXPECT_EQ(2, cache.disk_cache()->open_count());
3333 EXPECT_EQ(1, cache.disk_cache()->create_count());
3334 RemoveMockTransaction(&transaction2);
3337 // Tests that a HEAD request invalidates an old cached entry.
3338 TEST(HttpCache, SimpleHEAD_InvalidatesEntry) {
3339 MockHttpCache cache;
3340 MockTransaction transaction(kTypicalGET_Transaction);
3341 AddMockTransaction(&transaction);
3343 // Populate the cache.
3344 RunTransactionTest(cache.http_cache(), transaction);
3346 // Update the cache.
3347 transaction.method = "HEAD";
3348 transaction.data = "";
3349 RunTransactionTest(cache.http_cache(), transaction);
3350 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3352 // Load from the cache.
3353 transaction.method = "GET";
3354 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3355 transaction.return_code = ERR_CACHE_MISS;
3356 RunTransactionTest(cache.http_cache(), transaction);
3358 RemoveMockTransaction(&transaction);
3361 // Tests that we do not cache the response of a PUT.
3362 TEST(HttpCache, SimplePUT_Miss) {
3363 MockHttpCache cache;
3365 MockTransaction transaction(kSimplePOST_Transaction);
3366 transaction.method = "PUT";
3368 ScopedVector<UploadElementReader> element_readers;
3369 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3370 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3372 MockHttpRequest request(transaction);
3373 request.upload_data_stream = &upload_data_stream;
3375 // Attempt to populate the cache.
3376 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
3378 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3379 EXPECT_EQ(0, cache.disk_cache()->open_count());
3380 EXPECT_EQ(0, cache.disk_cache()->create_count());
3383 // Tests that we invalidate entries as a result of a PUT.
3384 TEST(HttpCache, SimplePUT_Invalidate) {
3385 MockHttpCache cache;
3387 MockTransaction transaction(kSimpleGET_Transaction);
3388 MockHttpRequest req1(transaction);
3390 // Attempt to populate the cache.
3391 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3393 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3394 EXPECT_EQ(0, cache.disk_cache()->open_count());
3395 EXPECT_EQ(1, cache.disk_cache()->create_count());
3397 ScopedVector<UploadElementReader> element_readers;
3398 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3399 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3401 transaction.method = "PUT";
3402 MockHttpRequest req2(transaction);
3403 req2.upload_data_stream = &upload_data_stream;
3405 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3407 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3408 EXPECT_EQ(1, cache.disk_cache()->open_count());
3409 EXPECT_EQ(1, cache.disk_cache()->create_count());
3411 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3413 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3414 EXPECT_EQ(1, cache.disk_cache()->open_count());
3415 EXPECT_EQ(2, cache.disk_cache()->create_count());
3418 // Tests that we invalidate entries as a result of a PUT.
3419 TEST(HttpCache, SimplePUT_Invalidate_305) {
3420 MockHttpCache cache;
3422 MockTransaction transaction(kSimpleGET_Transaction);
3423 AddMockTransaction(&transaction);
3424 MockHttpRequest req1(transaction);
3426 // Attempt to populate the cache.
3427 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3429 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3430 EXPECT_EQ(0, cache.disk_cache()->open_count());
3431 EXPECT_EQ(1, cache.disk_cache()->create_count());
3433 ScopedVector<UploadElementReader> element_readers;
3434 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3435 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3437 transaction.method = "PUT";
3438 transaction.status = "HTTP/1.1 305 Use Proxy";
3439 MockHttpRequest req2(transaction);
3440 req2.upload_data_stream = &upload_data_stream;
3442 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3444 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3445 EXPECT_EQ(1, cache.disk_cache()->open_count());
3446 EXPECT_EQ(1, cache.disk_cache()->create_count());
3448 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3450 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3451 EXPECT_EQ(1, cache.disk_cache()->open_count());
3452 EXPECT_EQ(2, cache.disk_cache()->create_count());
3453 RemoveMockTransaction(&transaction);
3456 // Tests that we don't invalidate entries as a result of a failed PUT.
3457 TEST(HttpCache, SimplePUT_DontInvalidate_404) {
3458 MockHttpCache cache;
3460 MockTransaction transaction(kSimpleGET_Transaction);
3461 AddMockTransaction(&transaction);
3462 MockHttpRequest req1(transaction);
3464 // Attempt to populate the cache.
3465 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3467 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3468 EXPECT_EQ(0, cache.disk_cache()->open_count());
3469 EXPECT_EQ(1, cache.disk_cache()->create_count());
3471 ScopedVector<UploadElementReader> element_readers;
3472 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3473 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3475 transaction.method = "PUT";
3476 transaction.status = "HTTP/1.1 404 Not Found";
3477 MockHttpRequest req2(transaction);
3478 req2.upload_data_stream = &upload_data_stream;
3480 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3482 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3483 EXPECT_EQ(1, cache.disk_cache()->open_count());
3484 EXPECT_EQ(1, cache.disk_cache()->create_count());
3486 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3488 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3489 EXPECT_EQ(2, cache.disk_cache()->open_count());
3490 EXPECT_EQ(1, cache.disk_cache()->create_count());
3491 RemoveMockTransaction(&transaction);
3494 // Tests that we do not cache the response of a DELETE.
3495 TEST(HttpCache, SimpleDELETE_Miss) {
3496 MockHttpCache cache;
3498 MockTransaction transaction(kSimplePOST_Transaction);
3499 transaction.method = "DELETE";
3501 ScopedVector<UploadElementReader> element_readers;
3502 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3503 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3505 MockHttpRequest request(transaction);
3506 request.upload_data_stream = &upload_data_stream;
3508 // Attempt to populate the cache.
3509 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
3511 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3512 EXPECT_EQ(0, cache.disk_cache()->open_count());
3513 EXPECT_EQ(0, cache.disk_cache()->create_count());
3516 // Tests that we invalidate entries as a result of a DELETE.
3517 TEST(HttpCache, SimpleDELETE_Invalidate) {
3518 MockHttpCache cache;
3520 MockTransaction transaction(kSimpleGET_Transaction);
3521 MockHttpRequest req1(transaction);
3523 // Attempt to populate the cache.
3524 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3526 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3527 EXPECT_EQ(0, cache.disk_cache()->open_count());
3528 EXPECT_EQ(1, cache.disk_cache()->create_count());
3530 ScopedVector<UploadElementReader> element_readers;
3531 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3532 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3534 transaction.method = "DELETE";
3535 MockHttpRequest req2(transaction);
3536 req2.upload_data_stream = &upload_data_stream;
3538 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3540 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3541 EXPECT_EQ(1, cache.disk_cache()->open_count());
3542 EXPECT_EQ(1, cache.disk_cache()->create_count());
3544 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3546 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3547 EXPECT_EQ(1, cache.disk_cache()->open_count());
3548 EXPECT_EQ(2, cache.disk_cache()->create_count());
3551 // Tests that we invalidate entries as a result of a DELETE.
3552 TEST(HttpCache, SimpleDELETE_Invalidate_301) {
3553 MockHttpCache cache;
3555 MockTransaction transaction(kSimpleGET_Transaction);
3556 AddMockTransaction(&transaction);
3558 // Attempt to populate the cache.
3559 RunTransactionTest(cache.http_cache(), transaction);
3561 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3562 EXPECT_EQ(0, cache.disk_cache()->open_count());
3563 EXPECT_EQ(1, cache.disk_cache()->create_count());
3565 transaction.method = "DELETE";
3566 transaction.status = "HTTP/1.1 301 Moved Permanently ";
3568 RunTransactionTest(cache.http_cache(), transaction);
3570 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3571 EXPECT_EQ(1, cache.disk_cache()->open_count());
3572 EXPECT_EQ(1, cache.disk_cache()->create_count());
3574 transaction.method = "GET";
3575 RunTransactionTest(cache.http_cache(), transaction);
3577 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3578 EXPECT_EQ(1, cache.disk_cache()->open_count());
3579 EXPECT_EQ(2, cache.disk_cache()->create_count());
3580 RemoveMockTransaction(&transaction);
3583 // Tests that we don't invalidate entries as a result of a failed DELETE.
3584 TEST(HttpCache, SimpleDELETE_DontInvalidate_416) {
3585 MockHttpCache cache;
3587 MockTransaction transaction(kSimpleGET_Transaction);
3588 AddMockTransaction(&transaction);
3590 // Attempt to populate the cache.
3591 RunTransactionTest(cache.http_cache(), transaction);
3593 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3594 EXPECT_EQ(0, cache.disk_cache()->open_count());
3595 EXPECT_EQ(1, cache.disk_cache()->create_count());
3597 transaction.method = "DELETE";
3598 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
3600 RunTransactionTest(cache.http_cache(), transaction);
3602 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3603 EXPECT_EQ(1, cache.disk_cache()->open_count());
3604 EXPECT_EQ(1, cache.disk_cache()->create_count());
3606 transaction.method = "GET";
3607 transaction.status = "HTTP/1.1 200 OK";
3608 RunTransactionTest(cache.http_cache(), transaction);
3610 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3611 EXPECT_EQ(2, cache.disk_cache()->open_count());
3612 EXPECT_EQ(1, cache.disk_cache()->create_count());
3613 RemoveMockTransaction(&transaction);
3616 // Tests that we don't invalidate entries after a failed network transaction.
3617 TEST(HttpCache, SimpleGET_DontInvalidateOnFailure) {
3618 MockHttpCache cache;
3620 // Populate the cache.
3621 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
3622 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3624 // Fail the network request.
3625 MockTransaction transaction(kSimpleGET_Transaction);
3626 transaction.return_code = ERR_FAILED;
3627 transaction.load_flags |= LOAD_VALIDATE_CACHE;
3629 AddMockTransaction(&transaction);
3630 RunTransactionTest(cache.http_cache(), transaction);
3631 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3632 RemoveMockTransaction(&transaction);
3634 transaction.load_flags = LOAD_ONLY_FROM_CACHE;
3635 transaction.return_code = OK;
3636 AddMockTransaction(&transaction);
3637 RunTransactionTest(cache.http_cache(), transaction);
3639 // Make sure the transaction didn't reach the network.
3640 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3641 RemoveMockTransaction(&transaction);
3644 TEST(HttpCache, RangeGET_SkipsCache) {
3645 MockHttpCache cache;
3647 // Test that we skip the cache for range GET requests. Eventually, we will
3648 // want to cache these, but we'll still have cases where skipping the cache
3649 // makes sense, so we want to make sure that it works properly.
3651 RunTransactionTest(cache.http_cache(), kRangeGET_Transaction);
3653 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3654 EXPECT_EQ(0, cache.disk_cache()->open_count());
3655 EXPECT_EQ(0, cache.disk_cache()->create_count());
3657 MockTransaction transaction(kSimpleGET_Transaction);
3658 transaction.request_headers = "If-None-Match: foo\r\n";
3659 RunTransactionTest(cache.http_cache(), transaction);
3661 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3662 EXPECT_EQ(0, cache.disk_cache()->open_count());
3663 EXPECT_EQ(0, cache.disk_cache()->create_count());
3665 transaction.request_headers =
3666 "If-Modified-Since: Wed, 28 Nov 2007 00:45:20 GMT\r\n";
3667 RunTransactionTest(cache.http_cache(), transaction);
3669 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3670 EXPECT_EQ(0, cache.disk_cache()->open_count());
3671 EXPECT_EQ(0, cache.disk_cache()->create_count());
3674 // Test that we skip the cache for range requests that include a validation
3675 // header.
3676 TEST(HttpCache, RangeGET_SkipsCache2) {
3677 MockHttpCache cache;
3679 MockTransaction transaction(kRangeGET_Transaction);
3680 transaction.request_headers = "If-None-Match: foo\r\n"
3681 EXTRA_HEADER
3682 "Range: bytes = 40-49\r\n";
3683 RunTransactionTest(cache.http_cache(), transaction);
3685 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3686 EXPECT_EQ(0, cache.disk_cache()->open_count());
3687 EXPECT_EQ(0, cache.disk_cache()->create_count());
3689 transaction.request_headers =
3690 "If-Modified-Since: Wed, 28 Nov 2007 00:45:20 GMT\r\n"
3691 EXTRA_HEADER
3692 "Range: bytes = 40-49\r\n";
3693 RunTransactionTest(cache.http_cache(), transaction);
3695 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3696 EXPECT_EQ(0, cache.disk_cache()->open_count());
3697 EXPECT_EQ(0, cache.disk_cache()->create_count());
3699 transaction.request_headers = "If-Range: bla\r\n"
3700 EXTRA_HEADER
3701 "Range: bytes = 40-49\r\n";
3702 RunTransactionTest(cache.http_cache(), transaction);
3704 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3705 EXPECT_EQ(0, cache.disk_cache()->open_count());
3706 EXPECT_EQ(0, cache.disk_cache()->create_count());
3709 TEST(HttpCache, SimpleGET_DoesntLogHeaders) {
3710 MockHttpCache cache;
3712 BoundTestNetLog log;
3713 RunTransactionTestWithLog(cache.http_cache(), kSimpleGET_Transaction,
3714 log.bound());
3716 EXPECT_FALSE(LogContainsEventType(
3717 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3720 TEST(HttpCache, RangeGET_LogsHeaders) {
3721 MockHttpCache cache;
3723 BoundTestNetLog log;
3724 RunTransactionTestWithLog(cache.http_cache(), kRangeGET_Transaction,
3725 log.bound());
3727 EXPECT_TRUE(LogContainsEventType(
3728 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3731 TEST(HttpCache, ExternalValidation_LogsHeaders) {
3732 MockHttpCache cache;
3734 BoundTestNetLog log;
3735 MockTransaction transaction(kSimpleGET_Transaction);
3736 transaction.request_headers = "If-None-Match: foo\r\n" EXTRA_HEADER;
3737 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
3739 EXPECT_TRUE(LogContainsEventType(
3740 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3743 TEST(HttpCache, SpecialHeaders_LogsHeaders) {
3744 MockHttpCache cache;
3746 BoundTestNetLog log;
3747 MockTransaction transaction(kSimpleGET_Transaction);
3748 transaction.request_headers = "cache-control: no-cache\r\n" EXTRA_HEADER;
3749 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
3751 EXPECT_TRUE(LogContainsEventType(
3752 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3755 // Tests that receiving 206 for a regular request is handled correctly.
3756 TEST(HttpCache, GET_Crazy206) {
3757 MockHttpCache cache;
3759 // Write to the cache.
3760 MockTransaction transaction(kRangeGET_TransactionOK);
3761 AddMockTransaction(&transaction);
3762 transaction.request_headers = EXTRA_HEADER;
3763 transaction.handler = NULL;
3764 RunTransactionTest(cache.http_cache(), transaction);
3766 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3767 EXPECT_EQ(0, cache.disk_cache()->open_count());
3768 EXPECT_EQ(1, cache.disk_cache()->create_count());
3770 // This should read again from the net.
3771 RunTransactionTest(cache.http_cache(), transaction);
3773 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3774 EXPECT_EQ(0, cache.disk_cache()->open_count());
3775 EXPECT_EQ(2, cache.disk_cache()->create_count());
3776 RemoveMockTransaction(&transaction);
3779 // Tests that receiving 416 for a regular request is handled correctly.
3780 TEST(HttpCache, GET_Crazy416) {
3781 MockHttpCache cache;
3783 // Write to the cache.
3784 MockTransaction transaction(kSimpleGET_Transaction);
3785 AddMockTransaction(&transaction);
3786 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
3787 RunTransactionTest(cache.http_cache(), transaction);
3789 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3790 EXPECT_EQ(0, cache.disk_cache()->open_count());
3791 EXPECT_EQ(1, cache.disk_cache()->create_count());
3793 RemoveMockTransaction(&transaction);
3796 // Tests that we don't store partial responses that can't be validated.
3797 TEST(HttpCache, RangeGET_NoStrongValidators) {
3798 MockHttpCache cache;
3799 std::string headers;
3801 // Attempt to write to the cache (40-49).
3802 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3803 transaction.response_headers = "Content-Length: 10\n"
3804 "Cache-Control: max-age=3600\n"
3805 "ETag: w/\"foo\"\n";
3806 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3808 Verify206Response(headers, 40, 49);
3809 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3810 EXPECT_EQ(0, cache.disk_cache()->open_count());
3811 EXPECT_EQ(1, cache.disk_cache()->create_count());
3813 // Now verify that there's no cached data.
3814 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3815 &headers);
3817 Verify206Response(headers, 40, 49);
3818 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3819 EXPECT_EQ(0, cache.disk_cache()->open_count());
3820 EXPECT_EQ(2, cache.disk_cache()->create_count());
3823 // Tests failures to conditionalize byte range requests.
3824 TEST(HttpCache, RangeGET_NoConditionalization) {
3825 MockHttpCache cache;
3826 cache.FailConditionalizations();
3827 std::string headers;
3829 // Write to the cache (40-49).
3830 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3831 transaction.response_headers = "Content-Length: 10\n"
3832 "ETag: \"foo\"\n";
3833 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3835 Verify206Response(headers, 40, 49);
3836 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3837 EXPECT_EQ(0, cache.disk_cache()->open_count());
3838 EXPECT_EQ(1, cache.disk_cache()->create_count());
3840 // Now verify that the cached data is not used.
3841 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3842 &headers);
3844 Verify206Response(headers, 40, 49);
3845 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3846 EXPECT_EQ(1, cache.disk_cache()->open_count());
3847 EXPECT_EQ(2, cache.disk_cache()->create_count());
3850 // Tests that restarting a partial request when the cached data cannot be
3851 // revalidated logs an event.
3852 TEST(HttpCache, RangeGET_NoValidation_LogsRestart) {
3853 MockHttpCache cache;
3854 cache.FailConditionalizations();
3856 // Write to the cache (40-49).
3857 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3858 transaction.response_headers = "Content-Length: 10\n"
3859 "ETag: \"foo\"\n";
3860 RunTransactionTest(cache.http_cache(), transaction);
3862 // Now verify that the cached data is not used.
3863 BoundTestNetLog log;
3864 RunTransactionTestWithLog(cache.http_cache(), kRangeGET_TransactionOK,
3865 log.bound());
3867 EXPECT_TRUE(LogContainsEventType(
3868 log, NetLog::TYPE_HTTP_CACHE_RESTART_PARTIAL_REQUEST));
3871 // Tests that a failure to conditionalize a regular request (no range) with a
3872 // sparse entry results in a full response.
3873 TEST(HttpCache, GET_NoConditionalization) {
3874 MockHttpCache cache;
3875 cache.FailConditionalizations();
3876 std::string headers;
3878 // Write to the cache (40-49).
3879 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3880 transaction.response_headers = "Content-Length: 10\n"
3881 "ETag: \"foo\"\n";
3882 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3884 Verify206Response(headers, 40, 49);
3885 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3886 EXPECT_EQ(0, cache.disk_cache()->open_count());
3887 EXPECT_EQ(1, cache.disk_cache()->create_count());
3889 // Now verify that the cached data is not used.
3890 // Don't ask for a range. The cache will attempt to use the cached data but
3891 // should discard it as it cannot be validated. A regular request should go
3892 // to the server and a new entry should be created.
3893 transaction.request_headers = EXTRA_HEADER;
3894 transaction.data = "Not a range";
3895 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3897 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
3898 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3899 EXPECT_EQ(1, cache.disk_cache()->open_count());
3900 EXPECT_EQ(2, cache.disk_cache()->create_count());
3902 // The last response was saved.
3903 RunTransactionTest(cache.http_cache(), transaction);
3904 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3905 EXPECT_EQ(2, cache.disk_cache()->open_count());
3906 EXPECT_EQ(2, cache.disk_cache()->create_count());
3909 // Verifies that conditionalization failures when asking for a range that would
3910 // require the cache to modify the range to ask, result in a network request
3911 // that matches the user's one.
3912 TEST(HttpCache, RangeGET_NoConditionalization2) {
3913 MockHttpCache cache;
3914 cache.FailConditionalizations();
3915 std::string headers;
3917 // Write to the cache (40-49).
3918 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3919 transaction.response_headers = "Content-Length: 10\n"
3920 "ETag: \"foo\"\n";
3921 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3923 Verify206Response(headers, 40, 49);
3924 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3925 EXPECT_EQ(0, cache.disk_cache()->open_count());
3926 EXPECT_EQ(1, cache.disk_cache()->create_count());
3928 // Now verify that the cached data is not used.
3929 // Ask for a range that extends before and after the cached data so that the
3930 // cache would normally mix data from three sources. After deleting the entry,
3931 // the response will come from a single network request.
3932 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
3933 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
3934 transaction.response_headers = kRangeGET_TransactionOK.response_headers;
3935 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3937 Verify206Response(headers, 20, 59);
3938 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3939 EXPECT_EQ(1, cache.disk_cache()->open_count());
3940 EXPECT_EQ(2, cache.disk_cache()->create_count());
3942 // The last response was saved.
3943 RunTransactionTest(cache.http_cache(), transaction);
3944 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3945 EXPECT_EQ(2, cache.disk_cache()->open_count());
3946 EXPECT_EQ(2, cache.disk_cache()->create_count());
3949 // Tests that we cache partial responses that lack content-length.
3950 TEST(HttpCache, RangeGET_NoContentLength) {
3951 MockHttpCache cache;
3952 std::string headers;
3954 // Attempt to write to the cache (40-49).
3955 MockTransaction transaction(kRangeGET_TransactionOK);
3956 AddMockTransaction(&transaction);
3957 transaction.response_headers = "ETag: \"foo\"\n"
3958 "Accept-Ranges: bytes\n"
3959 "Content-Range: bytes 40-49/80\n";
3960 transaction.handler = NULL;
3961 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3963 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3964 EXPECT_EQ(0, cache.disk_cache()->open_count());
3965 EXPECT_EQ(1, cache.disk_cache()->create_count());
3967 // Now verify that there's no cached data.
3968 transaction.handler = &RangeTransactionServer::RangeHandler;
3969 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3970 &headers);
3972 Verify206Response(headers, 40, 49);
3973 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3974 EXPECT_EQ(1, cache.disk_cache()->open_count());
3975 EXPECT_EQ(1, cache.disk_cache()->create_count());
3977 RemoveMockTransaction(&transaction);
3980 // Tests that we can cache range requests and fetch random blocks from the
3981 // cache and the network.
3982 TEST(HttpCache, RangeGET_OK) {
3983 MockHttpCache cache;
3984 AddMockTransaction(&kRangeGET_TransactionOK);
3985 std::string headers;
3987 // Write to the cache (40-49).
3988 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3989 &headers);
3991 Verify206Response(headers, 40, 49);
3992 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3993 EXPECT_EQ(0, cache.disk_cache()->open_count());
3994 EXPECT_EQ(1, cache.disk_cache()->create_count());
3996 // Read from the cache (40-49).
3997 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3998 &headers);
4000 Verify206Response(headers, 40, 49);
4001 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4002 EXPECT_EQ(1, cache.disk_cache()->open_count());
4003 EXPECT_EQ(1, cache.disk_cache()->create_count());
4005 // Make sure we are done with the previous transaction.
4006 base::MessageLoop::current()->RunUntilIdle();
4008 // Write to the cache (30-39).
4009 MockTransaction transaction(kRangeGET_TransactionOK);
4010 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
4011 transaction.data = "rg: 30-39 ";
4012 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4014 Verify206Response(headers, 30, 39);
4015 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4016 EXPECT_EQ(2, cache.disk_cache()->open_count());
4017 EXPECT_EQ(1, cache.disk_cache()->create_count());
4019 // Make sure we are done with the previous transaction.
4020 base::MessageLoop::current()->RunUntilIdle();
4022 // Write and read from the cache (20-59).
4023 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
4024 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
4025 BoundTestNetLog log;
4026 LoadTimingInfo load_timing_info;
4027 RunTransactionTestWithResponseAndGetTiming(
4028 cache.http_cache(), transaction, &headers, log.bound(),
4029 &load_timing_info);
4031 Verify206Response(headers, 20, 59);
4032 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4033 EXPECT_EQ(3, cache.disk_cache()->open_count());
4034 EXPECT_EQ(1, cache.disk_cache()->create_count());
4035 TestLoadTimingNetworkRequest(load_timing_info);
4037 RemoveMockTransaction(&kRangeGET_TransactionOK);
4040 // Tests that we can cache range requests and fetch random blocks from the
4041 // cache and the network, with synchronous responses.
4042 TEST(HttpCache, RangeGET_SyncOK) {
4043 MockHttpCache cache;
4045 MockTransaction transaction(kRangeGET_TransactionOK);
4046 transaction.test_mode = TEST_MODE_SYNC_ALL;
4047 AddMockTransaction(&transaction);
4049 // Write to the cache (40-49).
4050 std::string headers;
4051 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4053 Verify206Response(headers, 40, 49);
4054 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4055 EXPECT_EQ(0, cache.disk_cache()->open_count());
4056 EXPECT_EQ(1, cache.disk_cache()->create_count());
4058 // Read from the cache (40-49).
4059 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4061 Verify206Response(headers, 40, 49);
4062 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4063 EXPECT_EQ(0, cache.disk_cache()->open_count());
4064 EXPECT_EQ(1, cache.disk_cache()->create_count());
4066 // Make sure we are done with the previous transaction.
4067 base::MessageLoop::current()->RunUntilIdle();
4069 // Write to the cache (30-39).
4070 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
4071 transaction.data = "rg: 30-39 ";
4072 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4074 Verify206Response(headers, 30, 39);
4075 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4076 EXPECT_EQ(1, cache.disk_cache()->open_count());
4077 EXPECT_EQ(1, cache.disk_cache()->create_count());
4079 // Make sure we are done with the previous transaction.
4080 base::MessageLoop::current()->RunUntilIdle();
4082 // Write and read from the cache (20-59).
4083 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
4084 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
4085 BoundTestNetLog log;
4086 LoadTimingInfo load_timing_info;
4087 RunTransactionTestWithResponseAndGetTiming(
4088 cache.http_cache(), transaction, &headers, log.bound(),
4089 &load_timing_info);
4091 Verify206Response(headers, 20, 59);
4092 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4093 EXPECT_EQ(2, cache.disk_cache()->open_count());
4094 EXPECT_EQ(1, cache.disk_cache()->create_count());
4095 TestLoadTimingNetworkRequest(load_timing_info);
4097 RemoveMockTransaction(&transaction);
4100 // Tests that we don't revalidate an entry unless we are required to do so.
4101 TEST(HttpCache, RangeGET_Revalidate1) {
4102 MockHttpCache cache;
4103 std::string headers;
4105 // Write to the cache (40-49).
4106 MockTransaction transaction(kRangeGET_TransactionOK);
4107 transaction.response_headers =
4108 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
4109 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n" // Should never expire.
4110 "ETag: \"foo\"\n"
4111 "Accept-Ranges: bytes\n"
4112 "Content-Length: 10\n";
4113 AddMockTransaction(&transaction);
4114 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4116 Verify206Response(headers, 40, 49);
4117 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4118 EXPECT_EQ(0, cache.disk_cache()->open_count());
4119 EXPECT_EQ(1, cache.disk_cache()->create_count());
4121 // Read from the cache (40-49).
4122 BoundTestNetLog log;
4123 LoadTimingInfo load_timing_info;
4124 RunTransactionTestWithResponseAndGetTiming(
4125 cache.http_cache(), transaction, &headers, log.bound(),
4126 &load_timing_info);
4128 Verify206Response(headers, 40, 49);
4129 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4130 EXPECT_EQ(1, cache.disk_cache()->open_count());
4131 EXPECT_EQ(1, cache.disk_cache()->create_count());
4132 TestLoadTimingCachedResponse(load_timing_info);
4134 // Read again forcing the revalidation.
4135 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4136 RunTransactionTestWithResponseAndGetTiming(
4137 cache.http_cache(), transaction, &headers, log.bound(),
4138 &load_timing_info);
4140 Verify206Response(headers, 40, 49);
4141 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4142 EXPECT_EQ(1, cache.disk_cache()->open_count());
4143 EXPECT_EQ(1, cache.disk_cache()->create_count());
4144 TestLoadTimingNetworkRequest(load_timing_info);
4146 RemoveMockTransaction(&transaction);
4149 // Checks that we revalidate an entry when the headers say so.
4150 TEST(HttpCache, RangeGET_Revalidate2) {
4151 MockHttpCache cache;
4152 std::string headers;
4154 // Write to the cache (40-49).
4155 MockTransaction transaction(kRangeGET_TransactionOK);
4156 transaction.response_headers =
4157 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
4158 "Expires: Sat, 18 Apr 2009 01:10:43 GMT\n" // Expired.
4159 "ETag: \"foo\"\n"
4160 "Accept-Ranges: bytes\n"
4161 "Content-Length: 10\n";
4162 AddMockTransaction(&transaction);
4163 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4165 Verify206Response(headers, 40, 49);
4166 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4167 EXPECT_EQ(0, cache.disk_cache()->open_count());
4168 EXPECT_EQ(1, cache.disk_cache()->create_count());
4170 // Read from the cache (40-49).
4171 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4172 Verify206Response(headers, 40, 49);
4174 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4175 EXPECT_EQ(1, cache.disk_cache()->open_count());
4176 EXPECT_EQ(1, cache.disk_cache()->create_count());
4178 RemoveMockTransaction(&transaction);
4181 // Tests that we deal with 304s for range requests.
4182 TEST(HttpCache, RangeGET_304) {
4183 MockHttpCache cache;
4184 AddMockTransaction(&kRangeGET_TransactionOK);
4185 std::string headers;
4187 // Write to the cache (40-49).
4188 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4189 &headers);
4191 Verify206Response(headers, 40, 49);
4192 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4193 EXPECT_EQ(0, cache.disk_cache()->open_count());
4194 EXPECT_EQ(1, cache.disk_cache()->create_count());
4196 // Read from the cache (40-49).
4197 RangeTransactionServer handler;
4198 handler.set_not_modified(true);
4199 MockTransaction transaction(kRangeGET_TransactionOK);
4200 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4201 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4203 Verify206Response(headers, 40, 49);
4204 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4205 EXPECT_EQ(1, cache.disk_cache()->open_count());
4206 EXPECT_EQ(1, cache.disk_cache()->create_count());
4208 RemoveMockTransaction(&kRangeGET_TransactionOK);
4211 // Tests that we deal with 206s when revalidating range requests.
4212 TEST(HttpCache, RangeGET_ModifiedResult) {
4213 MockHttpCache cache;
4214 AddMockTransaction(&kRangeGET_TransactionOK);
4215 std::string headers;
4217 // Write to the cache (40-49).
4218 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4219 &headers);
4221 Verify206Response(headers, 40, 49);
4222 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4223 EXPECT_EQ(0, cache.disk_cache()->open_count());
4224 EXPECT_EQ(1, cache.disk_cache()->create_count());
4226 // Attempt to read from the cache (40-49).
4227 RangeTransactionServer handler;
4228 handler.set_modified(true);
4229 MockTransaction transaction(kRangeGET_TransactionOK);
4230 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4231 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4233 Verify206Response(headers, 40, 49);
4234 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4235 EXPECT_EQ(1, cache.disk_cache()->open_count());
4236 EXPECT_EQ(1, cache.disk_cache()->create_count());
4238 // And the entry should be gone.
4239 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4240 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4241 EXPECT_EQ(1, cache.disk_cache()->open_count());
4242 EXPECT_EQ(2, cache.disk_cache()->create_count());
4244 RemoveMockTransaction(&kRangeGET_TransactionOK);
4247 // Tests that when a server returns 206 with a sub-range of the requested range,
4248 // and there is nothing stored in the cache, the returned response is passed to
4249 // the caller as is. In this context, a subrange means a response that starts
4250 // with the same byte that was requested, but that is not the whole range that
4251 // was requested.
4252 TEST(HttpCache, RangeGET_206ReturnsSubrangeRange_NoCachedContent) {
4253 MockHttpCache cache;
4254 std::string headers;
4256 // Request a large range (40-59). The server sends 40-49.
4257 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4258 transaction.request_headers = "Range: bytes = 40-59\r\n" EXTRA_HEADER;
4259 transaction.response_headers =
4260 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4261 "ETag: \"foo\"\n"
4262 "Accept-Ranges: bytes\n"
4263 "Content-Length: 10\n"
4264 "Content-Range: bytes 40-49/80\n";
4265 transaction.handler = nullptr;
4266 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4268 Verify206Response(headers, 40, 49);
4269 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4270 EXPECT_EQ(0, cache.disk_cache()->open_count());
4271 EXPECT_EQ(1, cache.disk_cache()->create_count());
4274 // Tests that when a server returns 206 with a sub-range of the requested range,
4275 // and there was an entry stored in the cache, the cache gets out of the way.
4276 TEST(HttpCache, RangeGET_206ReturnsSubrangeRange_CachedContent) {
4277 MockHttpCache cache;
4278 std::string headers;
4280 // Write to the cache (70-79).
4281 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4282 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4283 transaction.data = "rg: 70-79 ";
4284 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4285 Verify206Response(headers, 70, 79);
4287 // Request a large range (40-79). The cache will ask the server for 40-59.
4288 // The server returns 40-49. The cache should consider the server confused and
4289 // abort caching, restarting the request without caching.
4290 transaction.request_headers = "Range: bytes = 40-79\r\n" EXTRA_HEADER;
4291 transaction.response_headers =
4292 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4293 "ETag: \"foo\"\n"
4294 "Accept-Ranges: bytes\n"
4295 "Content-Length: 10\n"
4296 "Content-Range: bytes 40-49/80\n";
4297 transaction.handler = nullptr;
4298 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4300 // Two new network requests were issued, one from the cache and another after
4301 // deleting the entry.
4302 Verify206Response(headers, 40, 49);
4303 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4304 EXPECT_EQ(1, cache.disk_cache()->open_count());
4305 EXPECT_EQ(1, cache.disk_cache()->create_count());
4307 // The entry was deleted.
4308 RunTransactionTest(cache.http_cache(), transaction);
4309 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4310 EXPECT_EQ(1, cache.disk_cache()->open_count());
4311 EXPECT_EQ(2, cache.disk_cache()->create_count());
4314 // Tests that when a server returns 206 with a sub-range of the requested range,
4315 // and there was an entry stored in the cache, the cache gets out of the way,
4316 // when the caller is not using ranges.
4317 TEST(HttpCache, GET_206ReturnsSubrangeRange_CachedContent) {
4318 MockHttpCache cache;
4319 std::string headers;
4321 // Write to the cache (70-79).
4322 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4323 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4324 transaction.data = "rg: 70-79 ";
4325 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4326 Verify206Response(headers, 70, 79);
4328 // Don't ask for a range. The cache will ask the server for 0-69.
4329 // The server returns 40-49. The cache should consider the server confused and
4330 // abort caching, restarting the request.
4331 // The second network request should not be a byte range request so the server
4332 // should return 200 + "Not a range"
4333 transaction.request_headers = "X-Return-Default-Range:\r\n" EXTRA_HEADER;
4334 transaction.data = "Not a range";
4335 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4337 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4338 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4339 EXPECT_EQ(1, cache.disk_cache()->open_count());
4340 EXPECT_EQ(1, cache.disk_cache()->create_count());
4342 // The entry was deleted.
4343 RunTransactionTest(cache.http_cache(), transaction);
4344 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4345 EXPECT_EQ(1, cache.disk_cache()->open_count());
4346 EXPECT_EQ(2, cache.disk_cache()->create_count());
4349 // Tests that when a server returns 206 with a random range and there is
4350 // nothing stored in the cache, the returned response is passed to the caller
4351 // as is. In this context, a WrongRange means that the returned range may or may
4352 // not have any relationship with the requested range (may or may not be
4353 // contained). The important part is that the first byte doesn't match the first
4354 // requested byte.
4355 TEST(HttpCache, RangeGET_206ReturnsWrongRange_NoCachedContent) {
4356 MockHttpCache cache;
4357 std::string headers;
4359 // Request a large range (30-59). The server sends (40-49).
4360 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4361 transaction.request_headers = "Range: bytes = 30-59\r\n" EXTRA_HEADER;
4362 transaction.response_headers =
4363 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4364 "ETag: \"foo\"\n"
4365 "Accept-Ranges: bytes\n"
4366 "Content-Length: 10\n"
4367 "Content-Range: bytes 40-49/80\n";
4368 transaction.handler = nullptr;
4369 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4371 Verify206Response(headers, 40, 49);
4372 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4373 EXPECT_EQ(0, cache.disk_cache()->open_count());
4374 EXPECT_EQ(1, cache.disk_cache()->create_count());
4376 // The entry was deleted.
4377 RunTransactionTest(cache.http_cache(), transaction);
4378 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4379 EXPECT_EQ(0, cache.disk_cache()->open_count());
4380 EXPECT_EQ(2, cache.disk_cache()->create_count());
4383 // Tests that when a server returns 206 with a random range and there is
4384 // an entry stored in the cache, the cache gets out of the way.
4385 TEST(HttpCache, RangeGET_206ReturnsWrongRange_CachedContent) {
4386 MockHttpCache cache;
4387 std::string headers;
4389 // Write to the cache (70-79).
4390 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4391 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4392 transaction.data = "rg: 70-79 ";
4393 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4394 Verify206Response(headers, 70, 79);
4396 // Request a large range (30-79). The cache will ask the server for 30-69.
4397 // The server returns 40-49. The cache should consider the server confused and
4398 // abort caching, returning the weird range to the caller.
4399 transaction.request_headers = "Range: bytes = 30-79\r\n" EXTRA_HEADER;
4400 transaction.response_headers =
4401 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4402 "ETag: \"foo\"\n"
4403 "Accept-Ranges: bytes\n"
4404 "Content-Length: 10\n"
4405 "Content-Range: bytes 40-49/80\n";
4406 transaction.handler = nullptr;
4407 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4409 Verify206Response(headers, 40, 49);
4410 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4411 EXPECT_EQ(1, cache.disk_cache()->open_count());
4412 EXPECT_EQ(1, cache.disk_cache()->create_count());
4414 // The entry was deleted.
4415 RunTransactionTest(cache.http_cache(), transaction);
4416 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4417 EXPECT_EQ(1, cache.disk_cache()->open_count());
4418 EXPECT_EQ(2, cache.disk_cache()->create_count());
4421 // Tests that when a caller asks for a range beyond EOF, with an empty cache,
4422 // the response matches the one provided by the server.
4423 TEST(HttpCache, RangeGET_206ReturnsSmallerFile_NoCachedContent) {
4424 MockHttpCache cache;
4425 std::string headers;
4427 // Request a large range (70-99). The server sends 70-79.
4428 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4429 transaction.request_headers = "Range: bytes = 70-99\r\n" EXTRA_HEADER;
4430 transaction.data = "rg: 70-79 ";
4431 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4433 Verify206Response(headers, 70, 79);
4434 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4435 EXPECT_EQ(0, cache.disk_cache()->open_count());
4436 EXPECT_EQ(1, cache.disk_cache()->create_count());
4438 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4439 EXPECT_EQ(1, cache.disk_cache()->open_count());
4442 // Tests that when a caller asks for a range beyond EOF, with a cached entry,
4443 // the cache automatically fixes the request.
4444 TEST(HttpCache, RangeGET_206ReturnsSmallerFile_CachedContent) {
4445 MockHttpCache cache;
4446 std::string headers;
4448 // Write to the cache (40-49).
4449 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4450 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4452 // Request a large range (70-99). The server sends 70-79.
4453 transaction.request_headers = "Range: bytes = 70-99\r\n" EXTRA_HEADER;
4454 transaction.data = "rg: 70-79 ";
4455 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4457 Verify206Response(headers, 70, 79);
4458 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4459 EXPECT_EQ(1, cache.disk_cache()->open_count());
4460 EXPECT_EQ(1, cache.disk_cache()->create_count());
4462 // The entry was not deleted (the range was automatically fixed).
4463 RunTransactionTest(cache.http_cache(), transaction);
4464 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4465 EXPECT_EQ(2, cache.disk_cache()->open_count());
4466 EXPECT_EQ(1, cache.disk_cache()->create_count());
4469 // Tests that when a caller asks for a not-satisfiable range, the server's
4470 // response is forwarded to the caller.
4471 TEST(HttpCache, RangeGET_416_NoCachedContent) {
4472 MockHttpCache cache;
4473 std::string headers;
4475 // Request a range beyond EOF (80-99).
4476 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4477 transaction.request_headers = "Range: bytes = 80-99\r\n" EXTRA_HEADER;
4478 transaction.data = "";
4479 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
4480 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4482 EXPECT_EQ(0U, headers.find(transaction.status));
4483 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4484 EXPECT_EQ(0, cache.disk_cache()->open_count());
4485 EXPECT_EQ(1, cache.disk_cache()->create_count());
4487 // The entry was deleted.
4488 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4489 EXPECT_EQ(2, cache.disk_cache()->create_count());
4492 // Tests that we cache 301s for range requests.
4493 TEST(HttpCache, RangeGET_301) {
4494 MockHttpCache cache;
4495 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4496 transaction.status = "HTTP/1.1 301 Moved Permanently";
4497 transaction.response_headers = "Location: http://www.bar.com/\n";
4498 transaction.data = "";
4499 transaction.handler = NULL;
4501 // Write to the cache.
4502 RunTransactionTest(cache.http_cache(), transaction);
4503 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4504 EXPECT_EQ(0, cache.disk_cache()->open_count());
4505 EXPECT_EQ(1, cache.disk_cache()->create_count());
4507 // Read from the cache.
4508 RunTransactionTest(cache.http_cache(), transaction);
4509 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4510 EXPECT_EQ(1, cache.disk_cache()->open_count());
4511 EXPECT_EQ(1, cache.disk_cache()->create_count());
4514 // Tests that we can cache range requests when the start or end is unknown.
4515 // We start with one suffix request, followed by a request from a given point.
4516 TEST(HttpCache, UnknownRangeGET_1) {
4517 MockHttpCache cache;
4518 AddMockTransaction(&kRangeGET_TransactionOK);
4519 std::string headers;
4521 // Write to the cache (70-79).
4522 MockTransaction transaction(kRangeGET_TransactionOK);
4523 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
4524 transaction.data = "rg: 70-79 ";
4525 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4527 Verify206Response(headers, 70, 79);
4528 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4529 EXPECT_EQ(0, cache.disk_cache()->open_count());
4530 EXPECT_EQ(1, cache.disk_cache()->create_count());
4532 // Make sure we are done with the previous transaction.
4533 base::MessageLoop::current()->RunUntilIdle();
4535 // Write and read from the cache (60-79).
4536 transaction.request_headers = "Range: bytes = 60-\r\n" EXTRA_HEADER;
4537 transaction.data = "rg: 60-69 rg: 70-79 ";
4538 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4540 Verify206Response(headers, 60, 79);
4541 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4542 EXPECT_EQ(1, cache.disk_cache()->open_count());
4543 EXPECT_EQ(1, cache.disk_cache()->create_count());
4545 RemoveMockTransaction(&kRangeGET_TransactionOK);
4548 // Tests that we can cache range requests when the start or end is unknown.
4549 // We start with one request from a given point, followed by a suffix request.
4550 // We'll also verify that synchronous cache responses work as intended.
4551 TEST(HttpCache, UnknownRangeGET_2) {
4552 MockHttpCache cache;
4553 std::string headers;
4555 MockTransaction transaction(kRangeGET_TransactionOK);
4556 transaction.test_mode = TEST_MODE_SYNC_CACHE_START |
4557 TEST_MODE_SYNC_CACHE_READ |
4558 TEST_MODE_SYNC_CACHE_WRITE;
4559 AddMockTransaction(&transaction);
4561 // Write to the cache (70-79).
4562 transaction.request_headers = "Range: bytes = 70-\r\n" EXTRA_HEADER;
4563 transaction.data = "rg: 70-79 ";
4564 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4566 Verify206Response(headers, 70, 79);
4567 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4568 EXPECT_EQ(0, cache.disk_cache()->open_count());
4569 EXPECT_EQ(1, cache.disk_cache()->create_count());
4571 // Make sure we are done with the previous transaction.
4572 base::MessageLoop::current()->RunUntilIdle();
4574 // Write and read from the cache (60-79).
4575 transaction.request_headers = "Range: bytes = -20\r\n" EXTRA_HEADER;
4576 transaction.data = "rg: 60-69 rg: 70-79 ";
4577 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4579 Verify206Response(headers, 60, 79);
4580 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4581 EXPECT_EQ(1, cache.disk_cache()->open_count());
4582 EXPECT_EQ(1, cache.disk_cache()->create_count());
4584 RemoveMockTransaction(&transaction);
4587 // Tests that receiving Not Modified when asking for an open range doesn't mess
4588 // up things.
4589 TEST(HttpCache, UnknownRangeGET_304) {
4590 MockHttpCache cache;
4591 std::string headers;
4593 MockTransaction transaction(kRangeGET_TransactionOK);
4594 AddMockTransaction(&transaction);
4596 RangeTransactionServer handler;
4597 handler.set_not_modified(true);
4599 // Ask for the end of the file, without knowing the length.
4600 transaction.request_headers = "Range: bytes = 70-\r\n" EXTRA_HEADER;
4601 transaction.data = "";
4602 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4604 // We just bypass the cache.
4605 EXPECT_EQ(0U, headers.find("HTTP/1.1 304 Not Modified\n"));
4606 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4607 EXPECT_EQ(0, cache.disk_cache()->open_count());
4608 EXPECT_EQ(1, cache.disk_cache()->create_count());
4610 RunTransactionTest(cache.http_cache(), transaction);
4611 EXPECT_EQ(2, cache.disk_cache()->create_count());
4613 RemoveMockTransaction(&transaction);
4616 // Tests that we can handle non-range requests when we have cached a range.
4617 TEST(HttpCache, GET_Previous206) {
4618 MockHttpCache cache;
4619 AddMockTransaction(&kRangeGET_TransactionOK);
4620 std::string headers;
4621 BoundTestNetLog log;
4622 LoadTimingInfo load_timing_info;
4624 // Write to the cache (40-49).
4625 RunTransactionTestWithResponseAndGetTiming(
4626 cache.http_cache(), kRangeGET_TransactionOK, &headers, log.bound(),
4627 &load_timing_info);
4629 Verify206Response(headers, 40, 49);
4630 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4631 EXPECT_EQ(0, cache.disk_cache()->open_count());
4632 EXPECT_EQ(1, cache.disk_cache()->create_count());
4633 TestLoadTimingNetworkRequest(load_timing_info);
4635 // Write and read from the cache (0-79), when not asked for a range.
4636 MockTransaction transaction(kRangeGET_TransactionOK);
4637 transaction.request_headers = EXTRA_HEADER;
4638 transaction.data = kFullRangeData;
4639 RunTransactionTestWithResponseAndGetTiming(
4640 cache.http_cache(), transaction, &headers, log.bound(),
4641 &load_timing_info);
4643 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4644 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4645 EXPECT_EQ(1, cache.disk_cache()->open_count());
4646 EXPECT_EQ(1, cache.disk_cache()->create_count());
4647 TestLoadTimingNetworkRequest(load_timing_info);
4649 RemoveMockTransaction(&kRangeGET_TransactionOK);
4652 // Tests that we can handle non-range requests when we have cached the first
4653 // part of the object and the server replies with 304 (Not Modified).
4654 TEST(HttpCache, GET_Previous206_NotModified) {
4655 MockHttpCache cache;
4657 MockTransaction transaction(kRangeGET_TransactionOK);
4658 AddMockTransaction(&transaction);
4659 std::string headers;
4660 BoundTestNetLog log;
4661 LoadTimingInfo load_timing_info;
4663 // Write to the cache (0-9).
4664 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
4665 transaction.data = "rg: 00-09 ";
4666 RunTransactionTestWithResponseAndGetTiming(
4667 cache.http_cache(), transaction, &headers, log.bound(),
4668 &load_timing_info);
4669 Verify206Response(headers, 0, 9);
4670 TestLoadTimingNetworkRequest(load_timing_info);
4672 // Write to the cache (70-79).
4673 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4674 transaction.data = "rg: 70-79 ";
4675 RunTransactionTestWithResponseAndGetTiming(
4676 cache.http_cache(), transaction, &headers, log.bound(),
4677 &load_timing_info);
4678 Verify206Response(headers, 70, 79);
4680 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4681 EXPECT_EQ(1, cache.disk_cache()->open_count());
4682 EXPECT_EQ(1, cache.disk_cache()->create_count());
4683 TestLoadTimingNetworkRequest(load_timing_info);
4685 // Read from the cache (0-9), write and read from cache (10 - 79).
4686 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4687 transaction.request_headers = "Foo: bar\r\n" EXTRA_HEADER;
4688 transaction.data = kFullRangeData;
4689 RunTransactionTestWithResponseAndGetTiming(
4690 cache.http_cache(), transaction, &headers, log.bound(),
4691 &load_timing_info);
4693 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4694 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4695 EXPECT_EQ(2, cache.disk_cache()->open_count());
4696 EXPECT_EQ(1, cache.disk_cache()->create_count());
4697 TestLoadTimingNetworkRequest(load_timing_info);
4699 RemoveMockTransaction(&transaction);
4702 // Tests that we can handle a regular request to a sparse entry, that results in
4703 // new content provided by the server (206).
4704 TEST(HttpCache, GET_Previous206_NewContent) {
4705 MockHttpCache cache;
4706 AddMockTransaction(&kRangeGET_TransactionOK);
4707 std::string headers;
4709 // Write to the cache (0-9).
4710 MockTransaction transaction(kRangeGET_TransactionOK);
4711 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
4712 transaction.data = "rg: 00-09 ";
4713 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4715 Verify206Response(headers, 0, 9);
4716 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4717 EXPECT_EQ(0, cache.disk_cache()->open_count());
4718 EXPECT_EQ(1, cache.disk_cache()->create_count());
4720 // Now we'll issue a request without any range that should result first in a
4721 // 206 (when revalidating), and then in a weird standard answer: the test
4722 // server will not modify the response so we'll get the default range... a
4723 // real server will answer with 200.
4724 MockTransaction transaction2(kRangeGET_TransactionOK);
4725 transaction2.request_headers = EXTRA_HEADER;
4726 transaction2.load_flags |= LOAD_VALIDATE_CACHE;
4727 transaction2.data = "Not a range";
4728 RangeTransactionServer handler;
4729 handler.set_modified(true);
4730 BoundTestNetLog log;
4731 LoadTimingInfo load_timing_info;
4732 RunTransactionTestWithResponseAndGetTiming(
4733 cache.http_cache(), transaction2, &headers, log.bound(),
4734 &load_timing_info);
4736 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4737 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4738 EXPECT_EQ(1, cache.disk_cache()->open_count());
4739 EXPECT_EQ(1, cache.disk_cache()->create_count());
4740 TestLoadTimingNetworkRequest(load_timing_info);
4742 // Verify that the previous request deleted the entry.
4743 RunTransactionTest(cache.http_cache(), transaction);
4744 EXPECT_EQ(2, cache.disk_cache()->create_count());
4746 RemoveMockTransaction(&transaction);
4749 // Tests that we can handle cached 206 responses that are not sparse.
4750 TEST(HttpCache, GET_Previous206_NotSparse) {
4751 MockHttpCache cache;
4753 // Create a disk cache entry that stores 206 headers while not being sparse.
4754 disk_cache::Entry* entry;
4755 ASSERT_TRUE(cache.CreateBackendEntry(kSimpleGET_Transaction.url, &entry,
4756 NULL));
4758 std::string raw_headers(kRangeGET_TransactionOK.status);
4759 raw_headers.append("\n");
4760 raw_headers.append(kRangeGET_TransactionOK.response_headers);
4761 raw_headers =
4762 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4764 HttpResponseInfo response;
4765 response.headers = new HttpResponseHeaders(raw_headers);
4766 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4768 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4769 int len = static_cast<int>(base::strlcpy(buf->data(),
4770 kRangeGET_TransactionOK.data, 500));
4771 TestCompletionCallback cb;
4772 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4773 EXPECT_EQ(len, cb.GetResult(rv));
4774 entry->Close();
4776 // Now see that we don't use the stored entry.
4777 std::string headers;
4778 BoundTestNetLog log;
4779 LoadTimingInfo load_timing_info;
4780 RunTransactionTestWithResponseAndGetTiming(
4781 cache.http_cache(), kSimpleGET_Transaction, &headers, log.bound(),
4782 &load_timing_info);
4784 // We are expecting a 200.
4785 std::string expected_headers(kSimpleGET_Transaction.status);
4786 expected_headers.append("\n");
4787 expected_headers.append(kSimpleGET_Transaction.response_headers);
4788 EXPECT_EQ(expected_headers, headers);
4789 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4790 EXPECT_EQ(1, cache.disk_cache()->open_count());
4791 EXPECT_EQ(2, cache.disk_cache()->create_count());
4792 TestLoadTimingNetworkRequest(load_timing_info);
4795 // Tests that we can handle cached 206 responses that are not sparse. This time
4796 // we issue a range request and expect to receive a range.
4797 TEST(HttpCache, RangeGET_Previous206_NotSparse_2) {
4798 MockHttpCache cache;
4799 AddMockTransaction(&kRangeGET_TransactionOK);
4801 // Create a disk cache entry that stores 206 headers while not being sparse.
4802 disk_cache::Entry* entry;
4803 ASSERT_TRUE(cache.CreateBackendEntry(kRangeGET_TransactionOK.url, &entry,
4804 NULL));
4806 std::string raw_headers(kRangeGET_TransactionOK.status);
4807 raw_headers.append("\n");
4808 raw_headers.append(kRangeGET_TransactionOK.response_headers);
4809 raw_headers =
4810 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4812 HttpResponseInfo response;
4813 response.headers = new HttpResponseHeaders(raw_headers);
4814 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4816 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4817 int len = static_cast<int>(base::strlcpy(buf->data(),
4818 kRangeGET_TransactionOK.data, 500));
4819 TestCompletionCallback cb;
4820 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4821 EXPECT_EQ(len, cb.GetResult(rv));
4822 entry->Close();
4824 // Now see that we don't use the stored entry.
4825 std::string headers;
4826 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4827 &headers);
4829 // We are expecting a 206.
4830 Verify206Response(headers, 40, 49);
4831 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4832 EXPECT_EQ(1, cache.disk_cache()->open_count());
4833 EXPECT_EQ(2, cache.disk_cache()->create_count());
4835 RemoveMockTransaction(&kRangeGET_TransactionOK);
4838 // Tests that we can handle cached 206 responses that can't be validated.
4839 TEST(HttpCache, GET_Previous206_NotValidation) {
4840 MockHttpCache cache;
4842 // Create a disk cache entry that stores 206 headers.
4843 disk_cache::Entry* entry;
4844 ASSERT_TRUE(cache.CreateBackendEntry(kSimpleGET_Transaction.url, &entry,
4845 NULL));
4847 // Make sure that the headers cannot be validated with the server.
4848 std::string raw_headers(kRangeGET_TransactionOK.status);
4849 raw_headers.append("\n");
4850 raw_headers.append("Content-Length: 80\n");
4851 raw_headers =
4852 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4854 HttpResponseInfo response;
4855 response.headers = new HttpResponseHeaders(raw_headers);
4856 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4858 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4859 int len = static_cast<int>(base::strlcpy(buf->data(),
4860 kRangeGET_TransactionOK.data, 500));
4861 TestCompletionCallback cb;
4862 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4863 EXPECT_EQ(len, cb.GetResult(rv));
4864 entry->Close();
4866 // Now see that we don't use the stored entry.
4867 std::string headers;
4868 RunTransactionTestWithResponse(cache.http_cache(), kSimpleGET_Transaction,
4869 &headers);
4871 // We are expecting a 200.
4872 std::string expected_headers(kSimpleGET_Transaction.status);
4873 expected_headers.append("\n");
4874 expected_headers.append(kSimpleGET_Transaction.response_headers);
4875 EXPECT_EQ(expected_headers, headers);
4876 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4877 EXPECT_EQ(1, cache.disk_cache()->open_count());
4878 EXPECT_EQ(2, cache.disk_cache()->create_count());
4881 // Tests that we can handle range requests with cached 200 responses.
4882 TEST(HttpCache, RangeGET_Previous200) {
4883 MockHttpCache cache;
4885 // Store the whole thing with status 200.
4886 MockTransaction transaction(kTypicalGET_Transaction);
4887 transaction.url = kRangeGET_TransactionOK.url;
4888 transaction.data = kFullRangeData;
4889 AddMockTransaction(&transaction);
4890 RunTransactionTest(cache.http_cache(), transaction);
4891 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4892 EXPECT_EQ(0, cache.disk_cache()->open_count());
4893 EXPECT_EQ(1, cache.disk_cache()->create_count());
4895 RemoveMockTransaction(&transaction);
4896 AddMockTransaction(&kRangeGET_TransactionOK);
4898 // Now see that we use the stored entry.
4899 std::string headers;
4900 MockTransaction transaction2(kRangeGET_TransactionOK);
4901 RangeTransactionServer handler;
4902 handler.set_not_modified(true);
4903 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
4905 // We are expecting a 206.
4906 Verify206Response(headers, 40, 49);
4907 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4908 EXPECT_EQ(1, cache.disk_cache()->open_count());
4909 EXPECT_EQ(1, cache.disk_cache()->create_count());
4911 // The last transaction has finished so make sure the entry is deactivated.
4912 base::MessageLoop::current()->RunUntilIdle();
4914 // Make a request for an invalid range.
4915 MockTransaction transaction3(kRangeGET_TransactionOK);
4916 transaction3.request_headers = "Range: bytes = 80-90\r\n" EXTRA_HEADER;
4917 transaction3.data = transaction.data;
4918 transaction3.load_flags = LOAD_PREFERRING_CACHE;
4919 RunTransactionTestWithResponse(cache.http_cache(), transaction3, &headers);
4920 EXPECT_EQ(2, cache.disk_cache()->open_count());
4921 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 "));
4922 EXPECT_EQ(std::string::npos, headers.find("Content-Range:"));
4923 EXPECT_EQ(std::string::npos, headers.find("Content-Length: 80"));
4925 // Make sure the entry is deactivated.
4926 base::MessageLoop::current()->RunUntilIdle();
4928 // Even though the request was invalid, we should have the entry.
4929 RunTransactionTest(cache.http_cache(), transaction2);
4930 EXPECT_EQ(3, cache.disk_cache()->open_count());
4932 // Make sure the entry is deactivated.
4933 base::MessageLoop::current()->RunUntilIdle();
4935 // Now we should receive a range from the server and drop the stored entry.
4936 handler.set_not_modified(false);
4937 transaction2.request_headers = kRangeGET_TransactionOK.request_headers;
4938 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
4939 Verify206Response(headers, 40, 49);
4940 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4941 EXPECT_EQ(4, cache.disk_cache()->open_count());
4942 EXPECT_EQ(1, cache.disk_cache()->create_count());
4944 RunTransactionTest(cache.http_cache(), transaction2);
4945 EXPECT_EQ(2, cache.disk_cache()->create_count());
4947 RemoveMockTransaction(&kRangeGET_TransactionOK);
4950 // Tests that we can handle a 200 response when dealing with sparse entries.
4951 TEST(HttpCache, RangeRequestResultsIn200) {
4952 MockHttpCache cache;
4953 AddMockTransaction(&kRangeGET_TransactionOK);
4954 std::string headers;
4956 // Write to the cache (70-79).
4957 MockTransaction transaction(kRangeGET_TransactionOK);
4958 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
4959 transaction.data = "rg: 70-79 ";
4960 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4962 Verify206Response(headers, 70, 79);
4963 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4964 EXPECT_EQ(0, cache.disk_cache()->open_count());
4965 EXPECT_EQ(1, cache.disk_cache()->create_count());
4967 // Now we'll issue a request that results in a plain 200 response, but to
4968 // the to the same URL that we used to store sparse data, and making sure
4969 // that we ask for a range.
4970 RemoveMockTransaction(&kRangeGET_TransactionOK);
4971 MockTransaction transaction2(kSimpleGET_Transaction);
4972 transaction2.url = kRangeGET_TransactionOK.url;
4973 transaction2.request_headers = kRangeGET_TransactionOK.request_headers;
4974 AddMockTransaction(&transaction2);
4976 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
4978 std::string expected_headers(kSimpleGET_Transaction.status);
4979 expected_headers.append("\n");
4980 expected_headers.append(kSimpleGET_Transaction.response_headers);
4981 EXPECT_EQ(expected_headers, headers);
4982 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4983 EXPECT_EQ(1, cache.disk_cache()->open_count());
4984 EXPECT_EQ(1, cache.disk_cache()->create_count());
4986 RemoveMockTransaction(&transaction2);
4989 // Tests that a range request that falls outside of the size that we know about
4990 // only deletes the entry if the resource has indeed changed.
4991 TEST(HttpCache, RangeGET_MoreThanCurrentSize) {
4992 MockHttpCache cache;
4993 AddMockTransaction(&kRangeGET_TransactionOK);
4994 std::string headers;
4996 // Write to the cache (40-49).
4997 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4998 &headers);
5000 Verify206Response(headers, 40, 49);
5001 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5002 EXPECT_EQ(0, cache.disk_cache()->open_count());
5003 EXPECT_EQ(1, cache.disk_cache()->create_count());
5005 // A weird request should not delete this entry. Ask for bytes 120-.
5006 MockTransaction transaction(kRangeGET_TransactionOK);
5007 transaction.request_headers = "Range: bytes = 120-\r\n" EXTRA_HEADER;
5008 transaction.data = "";
5009 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5011 EXPECT_EQ(0U, headers.find("HTTP/1.1 416 "));
5012 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5013 EXPECT_EQ(1, cache.disk_cache()->open_count());
5014 EXPECT_EQ(1, cache.disk_cache()->create_count());
5016 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5017 EXPECT_EQ(2, cache.disk_cache()->open_count());
5018 EXPECT_EQ(1, cache.disk_cache()->create_count());
5020 RemoveMockTransaction(&kRangeGET_TransactionOK);
5023 // Tests that we don't delete a sparse entry when we cancel a request.
5024 TEST(HttpCache, RangeGET_Cancel) {
5025 MockHttpCache cache;
5026 AddMockTransaction(&kRangeGET_TransactionOK);
5028 MockHttpRequest request(kRangeGET_TransactionOK);
5030 Context* c = new Context();
5031 int rv = cache.CreateTransaction(&c->trans);
5032 ASSERT_EQ(OK, rv);
5034 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5035 if (rv == ERR_IO_PENDING)
5036 rv = c->callback.WaitForResult();
5038 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5039 EXPECT_EQ(0, cache.disk_cache()->open_count());
5040 EXPECT_EQ(1, cache.disk_cache()->create_count());
5042 // Make sure that the entry has some data stored.
5043 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5044 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5045 if (rv == ERR_IO_PENDING)
5046 rv = c->callback.WaitForResult();
5047 EXPECT_EQ(buf->size(), rv);
5049 // Destroy the transaction.
5050 delete c;
5052 // Verify that the entry has not been deleted.
5053 disk_cache::Entry* entry;
5054 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5055 entry->Close();
5056 RemoveMockTransaction(&kRangeGET_TransactionOK);
5059 // Tests that we don't delete a sparse entry when we start a new request after
5060 // cancelling the previous one.
5061 TEST(HttpCache, RangeGET_Cancel2) {
5062 MockHttpCache cache;
5063 AddMockTransaction(&kRangeGET_TransactionOK);
5065 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5066 MockHttpRequest request(kRangeGET_TransactionOK);
5067 request.load_flags |= LOAD_VALIDATE_CACHE;
5069 Context* c = new Context();
5070 int rv = cache.CreateTransaction(&c->trans);
5071 ASSERT_EQ(OK, rv);
5073 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5074 if (rv == ERR_IO_PENDING)
5075 rv = c->callback.WaitForResult();
5077 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5078 EXPECT_EQ(1, cache.disk_cache()->open_count());
5079 EXPECT_EQ(1, cache.disk_cache()->create_count());
5081 // Make sure that we revalidate the entry and read from the cache (a single
5082 // read will return while waiting for the network).
5083 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5084 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5085 EXPECT_EQ(5, c->callback.GetResult(rv));
5086 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5087 EXPECT_EQ(ERR_IO_PENDING, rv);
5089 // Destroy the transaction before completing the read.
5090 delete c;
5092 // We have the read and the delete (OnProcessPendingQueue) waiting on the
5093 // message loop. This means that a new transaction will just reuse the same
5094 // active entry (no open or create).
5096 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5098 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5099 EXPECT_EQ(1, cache.disk_cache()->open_count());
5100 EXPECT_EQ(1, cache.disk_cache()->create_count());
5101 RemoveMockTransaction(&kRangeGET_TransactionOK);
5104 // A slight variation of the previous test, this time we cancel two requests in
5105 // a row, making sure that the second is waiting for the entry to be ready.
5106 TEST(HttpCache, RangeGET_Cancel3) {
5107 MockHttpCache cache;
5108 AddMockTransaction(&kRangeGET_TransactionOK);
5110 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5111 MockHttpRequest request(kRangeGET_TransactionOK);
5112 request.load_flags |= LOAD_VALIDATE_CACHE;
5114 Context* c = new Context();
5115 int rv = cache.CreateTransaction(&c->trans);
5116 ASSERT_EQ(OK, rv);
5118 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5119 EXPECT_EQ(ERR_IO_PENDING, rv);
5120 rv = c->callback.WaitForResult();
5122 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5123 EXPECT_EQ(1, cache.disk_cache()->open_count());
5124 EXPECT_EQ(1, cache.disk_cache()->create_count());
5126 // Make sure that we revalidate the entry and read from the cache (a single
5127 // read will return while waiting for the network).
5128 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5129 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5130 EXPECT_EQ(5, c->callback.GetResult(rv));
5131 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5132 EXPECT_EQ(ERR_IO_PENDING, rv);
5134 // Destroy the transaction before completing the read.
5135 delete c;
5137 // We have the read and the delete (OnProcessPendingQueue) waiting on the
5138 // message loop. This means that a new transaction will just reuse the same
5139 // active entry (no open or create).
5141 c = new Context();
5142 rv = cache.CreateTransaction(&c->trans);
5143 ASSERT_EQ(OK, rv);
5145 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5146 EXPECT_EQ(ERR_IO_PENDING, rv);
5148 MockDiskEntry::IgnoreCallbacks(true);
5149 base::MessageLoop::current()->RunUntilIdle();
5150 MockDiskEntry::IgnoreCallbacks(false);
5152 // The new transaction is waiting for the query range callback.
5153 delete c;
5155 // And we should not crash when the callback is delivered.
5156 base::MessageLoop::current()->RunUntilIdle();
5158 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5159 EXPECT_EQ(1, cache.disk_cache()->open_count());
5160 EXPECT_EQ(1, cache.disk_cache()->create_count());
5161 RemoveMockTransaction(&kRangeGET_TransactionOK);
5164 // Tests that an invalid range response results in no cached entry.
5165 TEST(HttpCache, RangeGET_InvalidResponse1) {
5166 MockHttpCache cache;
5167 std::string headers;
5169 MockTransaction transaction(kRangeGET_TransactionOK);
5170 transaction.handler = NULL;
5171 transaction.response_headers = "Content-Range: bytes 40-49/45\n"
5172 "Content-Length: 10\n";
5173 AddMockTransaction(&transaction);
5174 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5176 std::string expected(transaction.status);
5177 expected.append("\n");
5178 expected.append(transaction.response_headers);
5179 EXPECT_EQ(expected, headers);
5181 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5182 EXPECT_EQ(0, cache.disk_cache()->open_count());
5183 EXPECT_EQ(1, cache.disk_cache()->create_count());
5185 // Verify that we don't have a cached entry.
5186 disk_cache::Entry* entry;
5187 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5189 RemoveMockTransaction(&kRangeGET_TransactionOK);
5192 // Tests that we reject a range that doesn't match the content-length.
5193 TEST(HttpCache, RangeGET_InvalidResponse2) {
5194 MockHttpCache cache;
5195 std::string headers;
5197 MockTransaction transaction(kRangeGET_TransactionOK);
5198 transaction.handler = NULL;
5199 transaction.response_headers = "Content-Range: bytes 40-49/80\n"
5200 "Content-Length: 20\n";
5201 AddMockTransaction(&transaction);
5202 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5204 std::string expected(transaction.status);
5205 expected.append("\n");
5206 expected.append(transaction.response_headers);
5207 EXPECT_EQ(expected, headers);
5209 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5210 EXPECT_EQ(0, cache.disk_cache()->open_count());
5211 EXPECT_EQ(1, cache.disk_cache()->create_count());
5213 // Verify that we don't have a cached entry.
5214 disk_cache::Entry* entry;
5215 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5217 RemoveMockTransaction(&kRangeGET_TransactionOK);
5220 // Tests that if a server tells us conflicting information about a resource we
5221 // drop the entry.
5222 TEST(HttpCache, RangeGET_InvalidResponse3) {
5223 MockHttpCache cache;
5224 std::string headers;
5226 MockTransaction transaction(kRangeGET_TransactionOK);
5227 transaction.handler = NULL;
5228 transaction.request_headers = "Range: bytes = 50-59\r\n" EXTRA_HEADER;
5229 std::string response_headers(transaction.response_headers);
5230 response_headers.append("Content-Range: bytes 50-59/160\n");
5231 transaction.response_headers = response_headers.c_str();
5232 AddMockTransaction(&transaction);
5233 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5235 Verify206Response(headers, 50, 59);
5236 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5237 EXPECT_EQ(0, cache.disk_cache()->open_count());
5238 EXPECT_EQ(1, cache.disk_cache()->create_count());
5240 RemoveMockTransaction(&transaction);
5241 AddMockTransaction(&kRangeGET_TransactionOK);
5243 // This transaction will report a resource size of 80 bytes, and we think it's
5244 // 160 so we should ignore the response.
5245 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
5246 &headers);
5248 Verify206Response(headers, 40, 49);
5249 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5250 EXPECT_EQ(1, cache.disk_cache()->open_count());
5251 EXPECT_EQ(1, cache.disk_cache()->create_count());
5253 // Verify that the entry is gone.
5254 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5255 EXPECT_EQ(1, cache.disk_cache()->open_count());
5256 EXPECT_EQ(2, cache.disk_cache()->create_count());
5257 RemoveMockTransaction(&kRangeGET_TransactionOK);
5260 // Tests that we handle large range values properly.
5261 TEST(HttpCache, RangeGET_LargeValues) {
5262 // We need a real sparse cache for this test.
5263 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(1024 * 1024));
5264 std::string headers;
5266 MockTransaction transaction(kRangeGET_TransactionOK);
5267 transaction.handler = NULL;
5268 transaction.request_headers = "Range: bytes = 4294967288-4294967297\r\n"
5269 EXTRA_HEADER;
5270 transaction.response_headers =
5271 "ETag: \"foo\"\n"
5272 "Content-Range: bytes 4294967288-4294967297/4294967299\n"
5273 "Content-Length: 10\n";
5274 AddMockTransaction(&transaction);
5275 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5277 std::string expected(transaction.status);
5278 expected.append("\n");
5279 expected.append(transaction.response_headers);
5280 EXPECT_EQ(expected, headers);
5282 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5284 // Verify that we have a cached entry.
5285 disk_cache::Entry* en;
5286 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &en));
5287 en->Close();
5289 RemoveMockTransaction(&kRangeGET_TransactionOK);
5292 // Tests that we don't crash with a range request if the disk cache was not
5293 // initialized properly.
5294 TEST(HttpCache, RangeGET_NoDiskCache) {
5295 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
5296 factory->set_fail(true);
5297 factory->FinishCreation(); // We'll complete synchronously.
5298 MockHttpCache cache(factory);
5300 AddMockTransaction(&kRangeGET_TransactionOK);
5302 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5303 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5305 RemoveMockTransaction(&kRangeGET_TransactionOK);
5308 // Tests that we handle byte range requests that skip the cache.
5309 TEST(HttpCache, RangeHEAD) {
5310 MockHttpCache cache;
5311 AddMockTransaction(&kRangeGET_TransactionOK);
5313 MockTransaction transaction(kRangeGET_TransactionOK);
5314 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
5315 transaction.method = "HEAD";
5316 transaction.data = "rg: 70-79 ";
5318 std::string headers;
5319 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5321 Verify206Response(headers, 70, 79);
5322 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5323 EXPECT_EQ(0, cache.disk_cache()->open_count());
5324 EXPECT_EQ(0, cache.disk_cache()->create_count());
5326 RemoveMockTransaction(&kRangeGET_TransactionOK);
5329 // Tests that we don't crash when after reading from the cache we issue a
5330 // request for the next range and the server gives us a 200 synchronously.
5331 TEST(HttpCache, RangeGET_FastFlakyServer) {
5332 MockHttpCache cache;
5334 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
5335 transaction.request_headers = "Range: bytes = 40-\r\n" EXTRA_HEADER;
5336 transaction.test_mode = TEST_MODE_SYNC_NET_START;
5337 transaction.load_flags |= LOAD_VALIDATE_CACHE;
5339 // Write to the cache.
5340 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5342 // And now read from the cache and the network.
5343 RangeTransactionServer handler;
5344 handler.set_bad_200(true);
5345 transaction.data = "Not a range";
5346 BoundTestNetLog log;
5347 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
5349 EXPECT_EQ(3, cache.network_layer()->transaction_count());
5350 EXPECT_EQ(1, cache.disk_cache()->open_count());
5351 EXPECT_EQ(1, cache.disk_cache()->create_count());
5352 EXPECT_TRUE(LogContainsEventType(
5353 log, NetLog::TYPE_HTTP_CACHE_RE_SEND_PARTIAL_REQUEST));
5356 // Tests that when the server gives us less data than expected, we don't keep
5357 // asking for more data.
5358 TEST(HttpCache, RangeGET_FastFlakyServer2) {
5359 MockHttpCache cache;
5361 // First, check with an empty cache (WRITE mode).
5362 MockTransaction transaction(kRangeGET_TransactionOK);
5363 transaction.request_headers = "Range: bytes = 40-49\r\n" EXTRA_HEADER;
5364 transaction.data = "rg: 40-"; // Less than expected.
5365 transaction.handler = NULL;
5366 std::string headers(transaction.response_headers);
5367 headers.append("Content-Range: bytes 40-49/80\n");
5368 transaction.response_headers = headers.c_str();
5370 AddMockTransaction(&transaction);
5372 // Write to the cache.
5373 RunTransactionTest(cache.http_cache(), transaction);
5375 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5376 EXPECT_EQ(0, cache.disk_cache()->open_count());
5377 EXPECT_EQ(1, cache.disk_cache()->create_count());
5379 // Now verify that even in READ_WRITE mode, we forward the bad response to
5380 // the caller.
5381 transaction.request_headers = "Range: bytes = 60-69\r\n" EXTRA_HEADER;
5382 transaction.data = "rg: 60-"; // Less than expected.
5383 headers = kRangeGET_TransactionOK.response_headers;
5384 headers.append("Content-Range: bytes 60-69/80\n");
5385 transaction.response_headers = headers.c_str();
5387 RunTransactionTest(cache.http_cache(), transaction);
5389 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5390 EXPECT_EQ(1, cache.disk_cache()->open_count());
5391 EXPECT_EQ(1, cache.disk_cache()->create_count());
5393 RemoveMockTransaction(&transaction);
5396 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
5397 // This test hits a NOTREACHED so it is a release mode only test.
5398 TEST(HttpCache, RangeGET_OK_LoadOnlyFromCache) {
5399 MockHttpCache cache;
5400 AddMockTransaction(&kRangeGET_TransactionOK);
5402 // Write to the cache (40-49).
5403 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5404 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5405 EXPECT_EQ(0, cache.disk_cache()->open_count());
5406 EXPECT_EQ(1, cache.disk_cache()->create_count());
5408 // Force this transaction to read from the cache.
5409 MockTransaction transaction(kRangeGET_TransactionOK);
5410 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
5412 MockHttpRequest request(transaction);
5413 TestCompletionCallback callback;
5415 scoped_ptr<HttpTransaction> trans;
5416 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
5417 EXPECT_EQ(OK, rv);
5418 ASSERT_TRUE(trans.get());
5420 rv = trans->Start(&request, callback.callback(), BoundNetLog());
5421 if (rv == ERR_IO_PENDING)
5422 rv = callback.WaitForResult();
5423 ASSERT_EQ(ERR_CACHE_MISS, rv);
5425 trans.reset();
5427 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5428 EXPECT_EQ(1, cache.disk_cache()->open_count());
5429 EXPECT_EQ(1, cache.disk_cache()->create_count());
5431 RemoveMockTransaction(&kRangeGET_TransactionOK);
5433 #endif
5435 // Tests the handling of the "truncation" flag.
5436 TEST(HttpCache, WriteResponseInfo_Truncated) {
5437 MockHttpCache cache;
5438 disk_cache::Entry* entry;
5439 ASSERT_TRUE(cache.CreateBackendEntry("http://www.google.com", &entry,
5440 NULL));
5442 std::string headers("HTTP/1.1 200 OK");
5443 headers = HttpUtil::AssembleRawHeaders(headers.data(), headers.size());
5444 HttpResponseInfo response;
5445 response.headers = new HttpResponseHeaders(headers);
5447 // Set the last argument for this to be an incomplete request.
5448 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, true));
5449 bool truncated = false;
5450 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5451 EXPECT_TRUE(truncated);
5453 // And now test the opposite case.
5454 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
5455 truncated = true;
5456 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5457 EXPECT_FALSE(truncated);
5458 entry->Close();
5461 // Tests basic pickling/unpickling of HttpResponseInfo.
5462 TEST(HttpCache, PersistHttpResponseInfo) {
5463 // Set some fields (add more if needed.)
5464 HttpResponseInfo response1;
5465 response1.was_cached = false;
5466 response1.socket_address = HostPortPair("1.2.3.4", 80);
5467 response1.headers = new HttpResponseHeaders("HTTP/1.1 200 OK");
5469 // Pickle.
5470 base::Pickle pickle;
5471 response1.Persist(&pickle, false, false);
5473 // Unpickle.
5474 HttpResponseInfo response2;
5475 bool response_truncated;
5476 EXPECT_TRUE(response2.InitFromPickle(pickle, &response_truncated));
5477 EXPECT_FALSE(response_truncated);
5479 // Verify fields.
5480 EXPECT_TRUE(response2.was_cached); // InitFromPickle sets this flag.
5481 EXPECT_EQ("1.2.3.4", response2.socket_address.host());
5482 EXPECT_EQ(80, response2.socket_address.port());
5483 EXPECT_EQ("HTTP/1.1 200 OK", response2.headers->GetStatusLine());
5486 // Tests that we delete an entry when the request is cancelled before starting
5487 // to read from the network.
5488 TEST(HttpCache, DoomOnDestruction) {
5489 MockHttpCache cache;
5491 MockHttpRequest request(kSimpleGET_Transaction);
5493 Context* c = new Context();
5494 int rv = cache.CreateTransaction(&c->trans);
5495 ASSERT_EQ(OK, rv);
5497 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5498 if (rv == ERR_IO_PENDING)
5499 c->result = c->callback.WaitForResult();
5501 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5502 EXPECT_EQ(0, cache.disk_cache()->open_count());
5503 EXPECT_EQ(1, cache.disk_cache()->create_count());
5505 // Destroy the transaction. We only have the headers so we should delete this
5506 // entry.
5507 delete c;
5509 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5511 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5512 EXPECT_EQ(0, cache.disk_cache()->open_count());
5513 EXPECT_EQ(2, cache.disk_cache()->create_count());
5516 // Tests that we delete an entry when the request is cancelled if the response
5517 // does not have content-length and strong validators.
5518 TEST(HttpCache, DoomOnDestruction2) {
5519 MockHttpCache cache;
5521 MockHttpRequest request(kSimpleGET_Transaction);
5523 Context* c = new Context();
5524 int rv = cache.CreateTransaction(&c->trans);
5525 ASSERT_EQ(OK, rv);
5527 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5528 if (rv == ERR_IO_PENDING)
5529 rv = c->callback.WaitForResult();
5531 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5532 EXPECT_EQ(0, cache.disk_cache()->open_count());
5533 EXPECT_EQ(1, cache.disk_cache()->create_count());
5535 // Make sure that the entry has some data stored.
5536 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5537 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5538 if (rv == ERR_IO_PENDING)
5539 rv = c->callback.WaitForResult();
5540 EXPECT_EQ(buf->size(), rv);
5542 // Destroy the transaction.
5543 delete c;
5545 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5547 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5548 EXPECT_EQ(0, cache.disk_cache()->open_count());
5549 EXPECT_EQ(2, cache.disk_cache()->create_count());
5552 // Tests that we delete an entry when the request is cancelled if the response
5553 // has an "Accept-Ranges: none" header.
5554 TEST(HttpCache, DoomOnDestruction3) {
5555 MockHttpCache cache;
5557 MockTransaction transaction(kSimpleGET_Transaction);
5558 transaction.response_headers =
5559 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5560 "Content-Length: 22\n"
5561 "Accept-Ranges: none\n"
5562 "Etag: \"foopy\"\n";
5563 AddMockTransaction(&transaction);
5564 MockHttpRequest request(transaction);
5566 Context* c = new Context();
5567 int rv = cache.CreateTransaction(&c->trans);
5568 ASSERT_EQ(OK, rv);
5570 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5571 if (rv == ERR_IO_PENDING)
5572 rv = c->callback.WaitForResult();
5574 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5575 EXPECT_EQ(0, cache.disk_cache()->open_count());
5576 EXPECT_EQ(1, cache.disk_cache()->create_count());
5578 // Make sure that the entry has some data stored.
5579 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5580 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5581 if (rv == ERR_IO_PENDING)
5582 rv = c->callback.WaitForResult();
5583 EXPECT_EQ(buf->size(), rv);
5585 // Destroy the transaction.
5586 delete c;
5588 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5590 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5591 EXPECT_EQ(0, cache.disk_cache()->open_count());
5592 EXPECT_EQ(2, cache.disk_cache()->create_count());
5594 RemoveMockTransaction(&transaction);
5597 // Tests that we mark an entry as incomplete when the request is cancelled.
5598 TEST(HttpCache, SetTruncatedFlag) {
5599 MockHttpCache cache;
5601 MockTransaction transaction(kSimpleGET_Transaction);
5602 transaction.response_headers =
5603 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5604 "Content-Length: 22\n"
5605 "Etag: \"foopy\"\n";
5606 AddMockTransaction(&transaction);
5607 MockHttpRequest request(transaction);
5609 scoped_ptr<Context> c(new Context());
5611 int rv = cache.CreateTransaction(&c->trans);
5612 ASSERT_EQ(OK, rv);
5614 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5615 if (rv == ERR_IO_PENDING)
5616 rv = c->callback.WaitForResult();
5618 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5619 EXPECT_EQ(0, cache.disk_cache()->open_count());
5620 EXPECT_EQ(1, cache.disk_cache()->create_count());
5622 // Make sure that the entry has some data stored.
5623 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5624 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5625 if (rv == ERR_IO_PENDING)
5626 rv = c->callback.WaitForResult();
5627 EXPECT_EQ(buf->size(), rv);
5629 // We want to cancel the request when the transaction is busy.
5630 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5631 EXPECT_EQ(ERR_IO_PENDING, rv);
5632 EXPECT_FALSE(c->callback.have_result());
5634 MockHttpCache::SetTestMode(TEST_MODE_SYNC_ALL);
5636 // Destroy the transaction.
5637 c->trans.reset();
5638 MockHttpCache::SetTestMode(0);
5641 // Make sure that we don't invoke the callback. We may have an issue if the
5642 // UrlRequestJob is killed directly (without cancelling the UrlRequest) so we
5643 // could end up with the transaction being deleted twice if we send any
5644 // notification from the transaction destructor (see http://crbug.com/31723).
5645 EXPECT_FALSE(c->callback.have_result());
5647 // Verify that the entry is marked as incomplete.
5648 disk_cache::Entry* entry;
5649 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
5650 HttpResponseInfo response;
5651 bool truncated = false;
5652 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5653 EXPECT_TRUE(truncated);
5654 entry->Close();
5656 RemoveMockTransaction(&transaction);
5659 // Tests that we don't mark an entry as truncated when we read everything.
5660 TEST(HttpCache, DontSetTruncatedFlag) {
5661 MockHttpCache cache;
5663 MockTransaction transaction(kSimpleGET_Transaction);
5664 transaction.response_headers =
5665 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5666 "Content-Length: 22\n"
5667 "Etag: \"foopy\"\n";
5668 AddMockTransaction(&transaction);
5669 MockHttpRequest request(transaction);
5671 scoped_ptr<Context> c(new Context());
5672 int rv = cache.CreateTransaction(&c->trans);
5673 ASSERT_EQ(OK, rv);
5675 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5676 EXPECT_EQ(OK, c->callback.GetResult(rv));
5678 // Read everything.
5679 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(22));
5680 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5681 EXPECT_EQ(buf->size(), c->callback.GetResult(rv));
5683 // Destroy the transaction.
5684 c->trans.reset();
5686 // Verify that the entry is not marked as truncated.
5687 disk_cache::Entry* entry;
5688 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
5689 HttpResponseInfo response;
5690 bool truncated = true;
5691 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5692 EXPECT_FALSE(truncated);
5693 entry->Close();
5695 RemoveMockTransaction(&transaction);
5698 // Tests that we can continue with a request that was interrupted.
5699 TEST(HttpCache, GET_IncompleteResource) {
5700 MockHttpCache cache;
5701 AddMockTransaction(&kRangeGET_TransactionOK);
5703 std::string raw_headers("HTTP/1.1 200 OK\n"
5704 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5705 "ETag: \"foo\"\n"
5706 "Accept-Ranges: bytes\n"
5707 "Content-Length: 80\n");
5708 CreateTruncatedEntry(raw_headers, &cache);
5710 // Now make a regular request.
5711 std::string headers;
5712 MockTransaction transaction(kRangeGET_TransactionOK);
5713 transaction.request_headers = EXTRA_HEADER;
5714 transaction.data = kFullRangeData;
5715 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5717 // We update the headers with the ones received while revalidating.
5718 std::string expected_headers(
5719 "HTTP/1.1 200 OK\n"
5720 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5721 "Accept-Ranges: bytes\n"
5722 "ETag: \"foo\"\n"
5723 "Content-Length: 80\n");
5725 EXPECT_EQ(expected_headers, headers);
5726 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5727 EXPECT_EQ(1, cache.disk_cache()->open_count());
5728 EXPECT_EQ(1, cache.disk_cache()->create_count());
5730 // Verify that the disk entry was updated.
5731 disk_cache::Entry* entry;
5732 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5733 EXPECT_EQ(80, entry->GetDataSize(1));
5734 bool truncated = true;
5735 HttpResponseInfo response;
5736 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5737 EXPECT_FALSE(truncated);
5738 entry->Close();
5740 RemoveMockTransaction(&kRangeGET_TransactionOK);
5743 // Tests the handling of no-store when revalidating a truncated entry.
5744 TEST(HttpCache, GET_IncompleteResource_NoStore) {
5745 MockHttpCache cache;
5746 AddMockTransaction(&kRangeGET_TransactionOK);
5748 std::string raw_headers("HTTP/1.1 200 OK\n"
5749 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5750 "ETag: \"foo\"\n"
5751 "Accept-Ranges: bytes\n"
5752 "Content-Length: 80\n");
5753 CreateTruncatedEntry(raw_headers, &cache);
5754 RemoveMockTransaction(&kRangeGET_TransactionOK);
5756 // Now make a regular request.
5757 MockTransaction transaction(kRangeGET_TransactionOK);
5758 transaction.request_headers = EXTRA_HEADER;
5759 std::string response_headers(transaction.response_headers);
5760 response_headers += ("Cache-Control: no-store\n");
5761 transaction.response_headers = response_headers.c_str();
5762 transaction.data = kFullRangeData;
5763 AddMockTransaction(&transaction);
5765 std::string headers;
5766 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5768 // We update the headers with the ones received while revalidating.
5769 std::string expected_headers(
5770 "HTTP/1.1 200 OK\n"
5771 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5772 "Accept-Ranges: bytes\n"
5773 "Cache-Control: no-store\n"
5774 "ETag: \"foo\"\n"
5775 "Content-Length: 80\n");
5777 EXPECT_EQ(expected_headers, headers);
5778 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5779 EXPECT_EQ(1, cache.disk_cache()->open_count());
5780 EXPECT_EQ(1, cache.disk_cache()->create_count());
5782 // Verify that the disk entry was deleted.
5783 disk_cache::Entry* entry;
5784 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5785 RemoveMockTransaction(&transaction);
5788 // Tests cancelling a request after the server sent no-store.
5789 TEST(HttpCache, GET_IncompleteResource_Cancel) {
5790 MockHttpCache cache;
5791 AddMockTransaction(&kRangeGET_TransactionOK);
5793 std::string raw_headers("HTTP/1.1 200 OK\n"
5794 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5795 "ETag: \"foo\"\n"
5796 "Accept-Ranges: bytes\n"
5797 "Content-Length: 80\n");
5798 CreateTruncatedEntry(raw_headers, &cache);
5799 RemoveMockTransaction(&kRangeGET_TransactionOK);
5801 // Now make a regular request.
5802 MockTransaction transaction(kRangeGET_TransactionOK);
5803 transaction.request_headers = EXTRA_HEADER;
5804 std::string response_headers(transaction.response_headers);
5805 response_headers += ("Cache-Control: no-store\n");
5806 transaction.response_headers = response_headers.c_str();
5807 transaction.data = kFullRangeData;
5808 AddMockTransaction(&transaction);
5810 MockHttpRequest request(transaction);
5811 Context* c = new Context();
5813 int rv = cache.CreateTransaction(&c->trans);
5814 ASSERT_EQ(OK, rv);
5816 // Queue another request to this transaction. We have to start this request
5817 // before the first one gets the response from the server and dooms the entry,
5818 // otherwise it will just create a new entry without being queued to the first
5819 // request.
5820 Context* pending = new Context();
5821 ASSERT_EQ(OK, cache.CreateTransaction(&pending->trans));
5823 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5824 EXPECT_EQ(ERR_IO_PENDING,
5825 pending->trans->Start(&request, pending->callback.callback(),
5826 BoundNetLog()));
5827 EXPECT_EQ(OK, c->callback.GetResult(rv));
5829 // Make sure that the entry has some data stored.
5830 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5831 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5832 EXPECT_EQ(5, c->callback.GetResult(rv));
5834 // Cancel the requests.
5835 delete c;
5836 delete pending;
5838 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5839 EXPECT_EQ(1, cache.disk_cache()->open_count());
5840 EXPECT_EQ(2, cache.disk_cache()->create_count());
5842 base::MessageLoop::current()->RunUntilIdle();
5843 RemoveMockTransaction(&transaction);
5846 // Tests that we delete truncated entries if the server changes its mind midway.
5847 TEST(HttpCache, GET_IncompleteResource2) {
5848 MockHttpCache cache;
5849 AddMockTransaction(&kRangeGET_TransactionOK);
5851 // Content-length will be intentionally bad.
5852 std::string raw_headers("HTTP/1.1 200 OK\n"
5853 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5854 "ETag: \"foo\"\n"
5855 "Accept-Ranges: bytes\n"
5856 "Content-Length: 50\n");
5857 CreateTruncatedEntry(raw_headers, &cache);
5859 // Now make a regular request. We expect the code to fail the validation and
5860 // retry the request without using byte ranges.
5861 std::string headers;
5862 MockTransaction transaction(kRangeGET_TransactionOK);
5863 transaction.request_headers = EXTRA_HEADER;
5864 transaction.data = "Not a range";
5865 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5867 // The server will return 200 instead of a byte range.
5868 std::string expected_headers(
5869 "HTTP/1.1 200 OK\n"
5870 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n");
5872 EXPECT_EQ(expected_headers, headers);
5873 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5874 EXPECT_EQ(1, cache.disk_cache()->open_count());
5875 EXPECT_EQ(1, cache.disk_cache()->create_count());
5877 // Verify that the disk entry was deleted.
5878 disk_cache::Entry* entry;
5879 ASSERT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5880 RemoveMockTransaction(&kRangeGET_TransactionOK);
5883 // Tests that we always validate a truncated request.
5884 TEST(HttpCache, GET_IncompleteResource3) {
5885 MockHttpCache cache;
5886 AddMockTransaction(&kRangeGET_TransactionOK);
5888 // This should not require validation for 10 hours.
5889 std::string raw_headers("HTTP/1.1 200 OK\n"
5890 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
5891 "ETag: \"foo\"\n"
5892 "Cache-Control: max-age= 36000\n"
5893 "Accept-Ranges: bytes\n"
5894 "Content-Length: 80\n");
5895 CreateTruncatedEntry(raw_headers, &cache);
5897 // Now make a regular request.
5898 std::string headers;
5899 MockTransaction transaction(kRangeGET_TransactionOK);
5900 transaction.request_headers = EXTRA_HEADER;
5901 transaction.data = kFullRangeData;
5903 scoped_ptr<Context> c(new Context);
5904 int rv = cache.CreateTransaction(&c->trans);
5905 ASSERT_EQ(OK, rv);
5907 MockHttpRequest request(transaction);
5908 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5909 EXPECT_EQ(OK, c->callback.GetResult(rv));
5911 // We should have checked with the server before finishing Start().
5912 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5913 EXPECT_EQ(1, cache.disk_cache()->open_count());
5914 EXPECT_EQ(1, cache.disk_cache()->create_count());
5916 RemoveMockTransaction(&kRangeGET_TransactionOK);
5919 // Tests that we handle 401s for truncated resources.
5920 TEST(HttpCache, GET_IncompleteResourceWithAuth) {
5921 MockHttpCache cache;
5922 AddMockTransaction(&kRangeGET_TransactionOK);
5924 std::string raw_headers("HTTP/1.1 200 OK\n"
5925 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5926 "ETag: \"foo\"\n"
5927 "Accept-Ranges: bytes\n"
5928 "Content-Length: 80\n");
5929 CreateTruncatedEntry(raw_headers, &cache);
5931 // Now make a regular request.
5932 MockTransaction transaction(kRangeGET_TransactionOK);
5933 transaction.request_headers = "X-Require-Mock-Auth: dummy\r\n"
5934 EXTRA_HEADER;
5935 transaction.data = kFullRangeData;
5936 RangeTransactionServer handler;
5938 scoped_ptr<Context> c(new Context);
5939 int rv = cache.CreateTransaction(&c->trans);
5940 ASSERT_EQ(OK, rv);
5942 MockHttpRequest request(transaction);
5943 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5944 EXPECT_EQ(OK, c->callback.GetResult(rv));
5946 const HttpResponseInfo* response = c->trans->GetResponseInfo();
5947 ASSERT_TRUE(response);
5948 ASSERT_EQ(401, response->headers->response_code());
5949 rv = c->trans->RestartWithAuth(AuthCredentials(), c->callback.callback());
5950 EXPECT_EQ(OK, c->callback.GetResult(rv));
5951 response = c->trans->GetResponseInfo();
5952 ASSERT_TRUE(response);
5953 ASSERT_EQ(200, response->headers->response_code());
5955 ReadAndVerifyTransaction(c->trans.get(), transaction);
5956 c.reset(); // The destructor could delete the entry.
5957 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5959 // Verify that the entry was not deleted.
5960 disk_cache::Entry* entry;
5961 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5962 entry->Close();
5964 RemoveMockTransaction(&kRangeGET_TransactionOK);
5967 // Test that the transaction won't retry failed partial requests
5968 // after it starts reading data. http://crbug.com/474835
5969 TEST(HttpCache, TransactionRetryLimit) {
5970 MockHttpCache cache;
5972 // Cache 0-9, so that we have data to read before failing.
5973 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
5974 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
5975 transaction.data = "rg: 00-09 ";
5977 // Write to the cache.
5978 RunTransactionTest(cache.http_cache(), transaction);
5979 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5981 // And now read from the cache and the network. 10-19 will get a
5982 // 401, but will have already returned 0-9.
5983 // We do not set X-Require-Mock-Auth because that causes the mock
5984 // network transaction to become IsReadyToRestartForAuth().
5985 transaction.request_headers =
5986 "Range: bytes = 0-79\r\n"
5987 "X-Require-Mock-Auth-Alt: dummy\r\n" EXTRA_HEADER;
5989 scoped_ptr<Context> c(new Context);
5990 int rv = cache.CreateTransaction(&c->trans);
5991 ASSERT_EQ(OK, rv);
5993 MockHttpRequest request(transaction);
5995 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5996 if (rv == ERR_IO_PENDING)
5997 rv = c->callback.WaitForResult();
5998 std::string content;
5999 rv = ReadTransaction(c->trans.get(), &content);
6000 EXPECT_EQ(ERR_CACHE_AUTH_FAILURE_AFTER_READ, rv);
6003 // Tests that we cache a 200 response to the validation request.
6004 TEST(HttpCache, GET_IncompleteResource4) {
6005 MockHttpCache cache;
6006 AddMockTransaction(&kRangeGET_TransactionOK);
6008 std::string raw_headers("HTTP/1.1 200 OK\n"
6009 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
6010 "ETag: \"foo\"\n"
6011 "Accept-Ranges: bytes\n"
6012 "Content-Length: 80\n");
6013 CreateTruncatedEntry(raw_headers, &cache);
6015 // Now make a regular request.
6016 std::string headers;
6017 MockTransaction transaction(kRangeGET_TransactionOK);
6018 transaction.request_headers = EXTRA_HEADER;
6019 transaction.data = "Not a range";
6020 RangeTransactionServer handler;
6021 handler.set_bad_200(true);
6022 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
6024 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6025 EXPECT_EQ(1, cache.disk_cache()->open_count());
6026 EXPECT_EQ(1, cache.disk_cache()->create_count());
6028 // Verify that the disk entry was updated.
6029 disk_cache::Entry* entry;
6030 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6031 EXPECT_EQ(11, entry->GetDataSize(1));
6032 bool truncated = true;
6033 HttpResponseInfo response;
6034 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6035 EXPECT_FALSE(truncated);
6036 entry->Close();
6038 RemoveMockTransaction(&kRangeGET_TransactionOK);
6041 // Tests that when we cancel a request that was interrupted, we mark it again
6042 // as truncated.
6043 TEST(HttpCache, GET_CancelIncompleteResource) {
6044 MockHttpCache cache;
6045 AddMockTransaction(&kRangeGET_TransactionOK);
6047 std::string raw_headers("HTTP/1.1 200 OK\n"
6048 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
6049 "ETag: \"foo\"\n"
6050 "Accept-Ranges: bytes\n"
6051 "Content-Length: 80\n");
6052 CreateTruncatedEntry(raw_headers, &cache);
6054 // Now make a regular request.
6055 MockTransaction transaction(kRangeGET_TransactionOK);
6056 transaction.request_headers = EXTRA_HEADER;
6058 MockHttpRequest request(transaction);
6059 Context* c = new Context();
6060 int rv = cache.CreateTransaction(&c->trans);
6061 ASSERT_EQ(OK, rv);
6063 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
6064 EXPECT_EQ(OK, c->callback.GetResult(rv));
6066 // Read 20 bytes from the cache, and 10 from the net.
6067 scoped_refptr<IOBuffer> buf(new IOBuffer(100));
6068 rv = c->trans->Read(buf.get(), 20, c->callback.callback());
6069 EXPECT_EQ(20, c->callback.GetResult(rv));
6070 rv = c->trans->Read(buf.get(), 10, c->callback.callback());
6071 EXPECT_EQ(10, c->callback.GetResult(rv));
6073 // At this point, we are already reading so canceling the request should leave
6074 // a truncated one.
6075 delete c;
6077 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6078 EXPECT_EQ(1, cache.disk_cache()->open_count());
6079 EXPECT_EQ(1, cache.disk_cache()->create_count());
6081 // Verify that the disk entry was updated: now we have 30 bytes.
6082 disk_cache::Entry* entry;
6083 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6084 EXPECT_EQ(30, entry->GetDataSize(1));
6085 bool truncated = false;
6086 HttpResponseInfo response;
6087 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6088 EXPECT_TRUE(truncated);
6089 entry->Close();
6090 RemoveMockTransaction(&kRangeGET_TransactionOK);
6093 // Tests that we can handle range requests when we have a truncated entry.
6094 TEST(HttpCache, RangeGET_IncompleteResource) {
6095 MockHttpCache cache;
6096 AddMockTransaction(&kRangeGET_TransactionOK);
6098 // Content-length will be intentionally bogus.
6099 std::string raw_headers("HTTP/1.1 200 OK\n"
6100 "Last-Modified: something\n"
6101 "ETag: \"foo\"\n"
6102 "Accept-Ranges: bytes\n"
6103 "Content-Length: 10\n");
6104 CreateTruncatedEntry(raw_headers, &cache);
6106 // Now make a range request.
6107 std::string headers;
6108 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
6109 &headers);
6111 Verify206Response(headers, 40, 49);
6112 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6113 EXPECT_EQ(1, cache.disk_cache()->open_count());
6114 EXPECT_EQ(2, cache.disk_cache()->create_count());
6116 RemoveMockTransaction(&kRangeGET_TransactionOK);
6119 TEST(HttpCache, SyncRead) {
6120 MockHttpCache cache;
6122 // This test ensures that a read that completes synchronously does not cause
6123 // any problems.
6125 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6126 transaction.test_mode |= (TEST_MODE_SYNC_CACHE_START |
6127 TEST_MODE_SYNC_CACHE_READ |
6128 TEST_MODE_SYNC_CACHE_WRITE);
6130 MockHttpRequest r1(transaction),
6131 r2(transaction),
6132 r3(transaction);
6134 TestTransactionConsumer c1(DEFAULT_PRIORITY, cache.http_cache()),
6135 c2(DEFAULT_PRIORITY, cache.http_cache()),
6136 c3(DEFAULT_PRIORITY, cache.http_cache());
6138 c1.Start(&r1, BoundNetLog());
6140 r2.load_flags |= LOAD_ONLY_FROM_CACHE;
6141 c2.Start(&r2, BoundNetLog());
6143 r3.load_flags |= LOAD_ONLY_FROM_CACHE;
6144 c3.Start(&r3, BoundNetLog());
6146 base::MessageLoop::current()->Run();
6148 EXPECT_TRUE(c1.is_done());
6149 EXPECT_TRUE(c2.is_done());
6150 EXPECT_TRUE(c3.is_done());
6152 EXPECT_EQ(OK, c1.error());
6153 EXPECT_EQ(OK, c2.error());
6154 EXPECT_EQ(OK, c3.error());
6157 TEST(HttpCache, ValidationResultsIn200) {
6158 MockHttpCache cache;
6160 // This test ensures that a conditional request, which results in a 200
6161 // instead of a 304, properly truncates the existing response data.
6163 // write to the cache
6164 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
6166 // force this transaction to validate the cache
6167 MockTransaction transaction(kETagGET_Transaction);
6168 transaction.load_flags |= LOAD_VALIDATE_CACHE;
6169 RunTransactionTest(cache.http_cache(), transaction);
6171 // read from the cache
6172 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
6175 TEST(HttpCache, CachedRedirect) {
6176 MockHttpCache cache;
6178 ScopedMockTransaction kTestTransaction(kSimpleGET_Transaction);
6179 kTestTransaction.status = "HTTP/1.1 301 Moved Permanently";
6180 kTestTransaction.response_headers = "Location: http://www.bar.com/\n";
6182 MockHttpRequest request(kTestTransaction);
6183 TestCompletionCallback callback;
6185 // Write to the cache.
6187 scoped_ptr<HttpTransaction> trans;
6188 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6190 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6191 if (rv == ERR_IO_PENDING)
6192 rv = callback.WaitForResult();
6193 ASSERT_EQ(OK, rv);
6195 const HttpResponseInfo* info = trans->GetResponseInfo();
6196 ASSERT_TRUE(info);
6198 EXPECT_EQ(info->headers->response_code(), 301);
6200 std::string location;
6201 info->headers->EnumerateHeader(NULL, "Location", &location);
6202 EXPECT_EQ(location, "http://www.bar.com/");
6204 // Mark the transaction as completed so it is cached.
6205 trans->DoneReading();
6207 // Destroy transaction when going out of scope. We have not actually
6208 // read the response body -- want to test that it is still getting cached.
6210 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6211 EXPECT_EQ(0, cache.disk_cache()->open_count());
6212 EXPECT_EQ(1, cache.disk_cache()->create_count());
6214 // Active entries in the cache are not retired synchronously. Make
6215 // sure the next run hits the MockHttpCache and open_count is
6216 // correct.
6217 base::MessageLoop::current()->RunUntilIdle();
6219 // Read from the cache.
6221 scoped_ptr<HttpTransaction> trans;
6222 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6224 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6225 if (rv == ERR_IO_PENDING)
6226 rv = callback.WaitForResult();
6227 ASSERT_EQ(OK, rv);
6229 const HttpResponseInfo* info = trans->GetResponseInfo();
6230 ASSERT_TRUE(info);
6232 EXPECT_EQ(info->headers->response_code(), 301);
6234 std::string location;
6235 info->headers->EnumerateHeader(NULL, "Location", &location);
6236 EXPECT_EQ(location, "http://www.bar.com/");
6238 // Mark the transaction as completed so it is cached.
6239 trans->DoneReading();
6241 // Destroy transaction when going out of scope. We have not actually
6242 // read the response body -- want to test that it is still getting cached.
6244 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6245 EXPECT_EQ(1, cache.disk_cache()->open_count());
6246 EXPECT_EQ(1, cache.disk_cache()->create_count());
6249 // Verify that no-cache resources are stored in cache, but are not fetched from
6250 // cache during normal loads.
6251 TEST(HttpCache, CacheControlNoCacheNormalLoad) {
6252 MockHttpCache cache;
6254 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6255 transaction.response_headers = "cache-control: no-cache\n";
6257 // Initial load.
6258 RunTransactionTest(cache.http_cache(), transaction);
6260 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6261 EXPECT_EQ(0, cache.disk_cache()->open_count());
6262 EXPECT_EQ(1, cache.disk_cache()->create_count());
6264 // Try loading again; it should result in a network fetch.
6265 RunTransactionTest(cache.http_cache(), transaction);
6267 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6268 EXPECT_EQ(1, cache.disk_cache()->open_count());
6269 EXPECT_EQ(1, cache.disk_cache()->create_count());
6271 disk_cache::Entry* entry;
6272 EXPECT_TRUE(cache.OpenBackendEntry(transaction.url, &entry));
6273 entry->Close();
6276 // Verify that no-cache resources are stored in cache and fetched from cache
6277 // when the LOAD_PREFERRING_CACHE flag is set.
6278 TEST(HttpCache, CacheControlNoCacheHistoryLoad) {
6279 MockHttpCache cache;
6281 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6282 transaction.response_headers = "cache-control: no-cache\n";
6284 // Initial load.
6285 RunTransactionTest(cache.http_cache(), transaction);
6287 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6288 EXPECT_EQ(0, cache.disk_cache()->open_count());
6289 EXPECT_EQ(1, cache.disk_cache()->create_count());
6291 // Try loading again with LOAD_PREFERRING_CACHE.
6292 transaction.load_flags = LOAD_PREFERRING_CACHE;
6293 RunTransactionTest(cache.http_cache(), transaction);
6295 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6296 EXPECT_EQ(1, cache.disk_cache()->open_count());
6297 EXPECT_EQ(1, cache.disk_cache()->create_count());
6299 disk_cache::Entry* entry;
6300 EXPECT_TRUE(cache.OpenBackendEntry(transaction.url, &entry));
6301 entry->Close();
6304 TEST(HttpCache, CacheControlNoStore) {
6305 MockHttpCache cache;
6307 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6308 transaction.response_headers = "cache-control: no-store\n";
6310 // initial load
6311 RunTransactionTest(cache.http_cache(), transaction);
6313 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6314 EXPECT_EQ(0, cache.disk_cache()->open_count());
6315 EXPECT_EQ(1, cache.disk_cache()->create_count());
6317 // try loading again; it should result in a network fetch
6318 RunTransactionTest(cache.http_cache(), transaction);
6320 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6321 EXPECT_EQ(0, cache.disk_cache()->open_count());
6322 EXPECT_EQ(2, cache.disk_cache()->create_count());
6324 disk_cache::Entry* entry;
6325 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6328 TEST(HttpCache, CacheControlNoStore2) {
6329 // this test is similar to the above test, except that the initial response
6330 // is cachable, but when it is validated, no-store is received causing the
6331 // cached document to be deleted.
6332 MockHttpCache cache;
6334 ScopedMockTransaction transaction(kETagGET_Transaction);
6336 // initial load
6337 RunTransactionTest(cache.http_cache(), transaction);
6339 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6340 EXPECT_EQ(0, cache.disk_cache()->open_count());
6341 EXPECT_EQ(1, cache.disk_cache()->create_count());
6343 // try loading again; it should result in a network fetch
6344 transaction.load_flags = LOAD_VALIDATE_CACHE;
6345 transaction.response_headers = "cache-control: no-store\n";
6346 RunTransactionTest(cache.http_cache(), transaction);
6348 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6349 EXPECT_EQ(1, cache.disk_cache()->open_count());
6350 EXPECT_EQ(1, cache.disk_cache()->create_count());
6352 disk_cache::Entry* entry;
6353 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6356 TEST(HttpCache, CacheControlNoStore3) {
6357 // this test is similar to the above test, except that the response is a 304
6358 // instead of a 200. this should never happen in practice, but it seems like
6359 // a good thing to verify that we still destroy the cache entry.
6360 MockHttpCache cache;
6362 ScopedMockTransaction transaction(kETagGET_Transaction);
6364 // initial load
6365 RunTransactionTest(cache.http_cache(), transaction);
6367 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6368 EXPECT_EQ(0, cache.disk_cache()->open_count());
6369 EXPECT_EQ(1, cache.disk_cache()->create_count());
6371 // try loading again; it should result in a network fetch
6372 transaction.load_flags = LOAD_VALIDATE_CACHE;
6373 transaction.response_headers = "cache-control: no-store\n";
6374 transaction.status = "HTTP/1.1 304 Not Modified";
6375 RunTransactionTest(cache.http_cache(), transaction);
6377 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6378 EXPECT_EQ(1, cache.disk_cache()->open_count());
6379 EXPECT_EQ(1, cache.disk_cache()->create_count());
6381 disk_cache::Entry* entry;
6382 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6385 // Ensure that we don't cache requests served over bad HTTPS.
6386 TEST(HttpCache, SimpleGET_SSLError) {
6387 MockHttpCache cache;
6389 MockTransaction transaction = kSimpleGET_Transaction;
6390 transaction.cert_status = CERT_STATUS_REVOKED;
6391 ScopedMockTransaction scoped_transaction(transaction);
6393 // write to the cache
6394 RunTransactionTest(cache.http_cache(), transaction);
6396 // Test that it was not cached.
6397 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
6399 MockHttpRequest request(transaction);
6400 TestCompletionCallback callback;
6402 scoped_ptr<HttpTransaction> trans;
6403 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6405 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6406 if (rv == ERR_IO_PENDING)
6407 rv = callback.WaitForResult();
6408 ASSERT_EQ(ERR_CACHE_MISS, rv);
6411 // Ensure that we don't crash by if left-behind transactions.
6412 TEST(HttpCache, OutlivedTransactions) {
6413 MockHttpCache* cache = new MockHttpCache;
6415 scoped_ptr<HttpTransaction> trans;
6416 EXPECT_EQ(OK, cache->CreateTransaction(&trans));
6418 delete cache;
6419 trans.reset();
6422 // Test that the disabled mode works.
6423 TEST(HttpCache, CacheDisabledMode) {
6424 MockHttpCache cache;
6426 // write to the cache
6427 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6429 // go into disabled mode
6430 cache.http_cache()->set_mode(HttpCache::DISABLE);
6432 // force this transaction to write to the cache again
6433 MockTransaction transaction(kSimpleGET_Transaction);
6435 RunTransactionTest(cache.http_cache(), transaction);
6437 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6438 EXPECT_EQ(0, cache.disk_cache()->open_count());
6439 EXPECT_EQ(1, cache.disk_cache()->create_count());
6442 // Other tests check that the response headers of the cached response
6443 // get updated on 304. Here we specifically check that the
6444 // HttpResponseHeaders::request_time and HttpResponseHeaders::response_time
6445 // fields also gets updated.
6446 // http://crbug.com/20594.
6447 TEST(HttpCache, UpdatesRequestResponseTimeOn304) {
6448 MockHttpCache cache;
6450 const char kUrl[] = "http://foobar";
6451 const char kData[] = "body";
6453 MockTransaction mock_network_response = { 0 };
6454 mock_network_response.url = kUrl;
6456 AddMockTransaction(&mock_network_response);
6458 // Request |kUrl|, causing |kNetResponse1| to be written to the cache.
6460 MockTransaction request = { 0 };
6461 request.url = kUrl;
6462 request.method = "GET";
6463 request.request_headers = "\r\n";
6464 request.data = kData;
6466 static const Response kNetResponse1 = {
6467 "HTTP/1.1 200 OK",
6468 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
6469 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
6470 kData
6473 kNetResponse1.AssignTo(&mock_network_response);
6475 RunTransactionTest(cache.http_cache(), request);
6477 // Request |kUrl| again, this time validating the cache and getting
6478 // a 304 back.
6480 request.load_flags = LOAD_VALIDATE_CACHE;
6482 static const Response kNetResponse2 = {
6483 "HTTP/1.1 304 Not Modified",
6484 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n",
6488 kNetResponse2.AssignTo(&mock_network_response);
6490 base::Time request_time = base::Time() + base::TimeDelta::FromHours(1234);
6491 base::Time response_time = base::Time() + base::TimeDelta::FromHours(1235);
6493 mock_network_response.request_time = request_time;
6494 mock_network_response.response_time = response_time;
6496 HttpResponseInfo response;
6497 RunTransactionTestWithResponseInfo(cache.http_cache(), request, &response);
6499 // The request and response times should have been updated.
6500 EXPECT_EQ(request_time.ToInternalValue(),
6501 response.request_time.ToInternalValue());
6502 EXPECT_EQ(response_time.ToInternalValue(),
6503 response.response_time.ToInternalValue());
6505 std::string headers;
6506 response.headers->GetNormalizedHeaders(&headers);
6508 EXPECT_EQ("HTTP/1.1 200 OK\n"
6509 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
6510 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
6511 headers);
6513 RemoveMockTransaction(&mock_network_response);
6516 // Tests that we can write metadata to an entry.
6517 TEST(HttpCache, WriteMetadata_OK) {
6518 MockHttpCache cache;
6520 // Write to the cache
6521 HttpResponseInfo response;
6522 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6523 &response);
6524 EXPECT_TRUE(response.metadata.get() == NULL);
6526 // Trivial call.
6527 cache.http_cache()->WriteMetadata(GURL("foo"), DEFAULT_PRIORITY, Time::Now(),
6528 NULL, 0);
6530 // Write meta data to the same entry.
6531 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6532 memset(buf->data(), 0, buf->size());
6533 base::strlcpy(buf->data(), "Hi there", buf->size());
6534 cache.http_cache()->WriteMetadata(GURL(kSimpleGET_Transaction.url),
6535 DEFAULT_PRIORITY, response.response_time,
6536 buf.get(), buf->size());
6538 // Release the buffer before the operation takes place.
6539 buf = NULL;
6541 // Makes sure we finish pending operations.
6542 base::MessageLoop::current()->RunUntilIdle();
6544 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6545 &response);
6546 ASSERT_TRUE(response.metadata.get() != NULL);
6547 EXPECT_EQ(50, response.metadata->size());
6548 EXPECT_EQ(0, strcmp(response.metadata->data(), "Hi there"));
6550 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6551 EXPECT_EQ(2, cache.disk_cache()->open_count());
6552 EXPECT_EQ(1, cache.disk_cache()->create_count());
6555 // Tests that we only write metadata to an entry if the time stamp matches.
6556 TEST(HttpCache, WriteMetadata_Fail) {
6557 MockHttpCache cache;
6559 // Write to the cache
6560 HttpResponseInfo response;
6561 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6562 &response);
6563 EXPECT_TRUE(response.metadata.get() == NULL);
6565 // Attempt to write meta data to the same entry.
6566 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6567 memset(buf->data(), 0, buf->size());
6568 base::strlcpy(buf->data(), "Hi there", buf->size());
6569 base::Time expected_time = response.response_time -
6570 base::TimeDelta::FromMilliseconds(20);
6571 cache.http_cache()->WriteMetadata(GURL(kSimpleGET_Transaction.url),
6572 DEFAULT_PRIORITY, expected_time, buf.get(),
6573 buf->size());
6575 // Makes sure we finish pending operations.
6576 base::MessageLoop::current()->RunUntilIdle();
6578 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6579 &response);
6580 EXPECT_TRUE(response.metadata.get() == NULL);
6582 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6583 EXPECT_EQ(2, cache.disk_cache()->open_count());
6584 EXPECT_EQ(1, cache.disk_cache()->create_count());
6587 // Tests that we can read metadata after validating the entry and with READ mode
6588 // transactions.
6589 TEST(HttpCache, ReadMetadata) {
6590 MockHttpCache cache;
6592 // Write to the cache
6593 HttpResponseInfo response;
6594 RunTransactionTestWithResponseInfo(cache.http_cache(),
6595 kTypicalGET_Transaction, &response);
6596 EXPECT_TRUE(response.metadata.get() == NULL);
6598 // Write meta data to the same entry.
6599 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6600 memset(buf->data(), 0, buf->size());
6601 base::strlcpy(buf->data(), "Hi there", buf->size());
6602 cache.http_cache()->WriteMetadata(GURL(kTypicalGET_Transaction.url),
6603 DEFAULT_PRIORITY, response.response_time,
6604 buf.get(), buf->size());
6606 // Makes sure we finish pending operations.
6607 base::MessageLoop::current()->RunUntilIdle();
6609 // Start with a READ mode transaction.
6610 MockTransaction trans1(kTypicalGET_Transaction);
6611 trans1.load_flags = LOAD_ONLY_FROM_CACHE;
6613 RunTransactionTestWithResponseInfo(cache.http_cache(), trans1, &response);
6614 ASSERT_TRUE(response.metadata.get() != NULL);
6615 EXPECT_EQ(50, response.metadata->size());
6616 EXPECT_EQ(0, strcmp(response.metadata->data(), "Hi there"));
6618 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6619 EXPECT_EQ(2, cache.disk_cache()->open_count());
6620 EXPECT_EQ(1, cache.disk_cache()->create_count());
6621 base::MessageLoop::current()->RunUntilIdle();
6623 // Now make sure that the entry is re-validated with the server.
6624 trans1.load_flags = LOAD_VALIDATE_CACHE;
6625 trans1.status = "HTTP/1.1 304 Not Modified";
6626 AddMockTransaction(&trans1);
6628 response.metadata = NULL;
6629 RunTransactionTestWithResponseInfo(cache.http_cache(), trans1, &response);
6630 EXPECT_TRUE(response.metadata.get() != NULL);
6632 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6633 EXPECT_EQ(3, cache.disk_cache()->open_count());
6634 EXPECT_EQ(1, cache.disk_cache()->create_count());
6635 base::MessageLoop::current()->RunUntilIdle();
6636 RemoveMockTransaction(&trans1);
6638 // Now return 200 when validating the entry so the metadata will be lost.
6639 MockTransaction trans2(kTypicalGET_Transaction);
6640 trans2.load_flags = LOAD_VALIDATE_CACHE;
6641 RunTransactionTestWithResponseInfo(cache.http_cache(), trans2, &response);
6642 EXPECT_TRUE(response.metadata.get() == NULL);
6644 EXPECT_EQ(3, cache.network_layer()->transaction_count());
6645 EXPECT_EQ(4, cache.disk_cache()->open_count());
6646 EXPECT_EQ(1, cache.disk_cache()->create_count());
6649 // Tests that we don't mark entries as truncated when a filter detects the end
6650 // of the stream.
6651 TEST(HttpCache, FilterCompletion) {
6652 MockHttpCache cache;
6653 TestCompletionCallback callback;
6656 scoped_ptr<HttpTransaction> trans;
6657 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6659 MockHttpRequest request(kSimpleGET_Transaction);
6660 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6661 EXPECT_EQ(OK, callback.GetResult(rv));
6663 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6664 rv = trans->Read(buf.get(), 256, callback.callback());
6665 EXPECT_GT(callback.GetResult(rv), 0);
6667 // Now make sure that the entry is preserved.
6668 trans->DoneReading();
6671 // Make sure that the ActiveEntry is gone.
6672 base::MessageLoop::current()->RunUntilIdle();
6674 // Read from the cache.
6675 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6677 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6678 EXPECT_EQ(1, cache.disk_cache()->open_count());
6679 EXPECT_EQ(1, cache.disk_cache()->create_count());
6682 // Tests that we don't mark entries as truncated and release the cache
6683 // entry when DoneReading() is called before any Read() calls, such as
6684 // for a redirect.
6685 TEST(HttpCache, DoneReading) {
6686 MockHttpCache cache;
6687 TestCompletionCallback callback;
6689 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6690 transaction.data = "";
6692 scoped_ptr<HttpTransaction> trans;
6693 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6695 MockHttpRequest request(transaction);
6696 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6697 EXPECT_EQ(OK, callback.GetResult(rv));
6699 trans->DoneReading();
6700 // Leave the transaction around.
6702 // Make sure that the ActiveEntry is gone.
6703 base::MessageLoop::current()->RunUntilIdle();
6705 // Read from the cache. This should not deadlock.
6706 RunTransactionTest(cache.http_cache(), transaction);
6708 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6709 EXPECT_EQ(1, cache.disk_cache()->open_count());
6710 EXPECT_EQ(1, cache.disk_cache()->create_count());
6713 // Tests that we stop caching when told.
6714 TEST(HttpCache, StopCachingDeletesEntry) {
6715 MockHttpCache cache;
6716 TestCompletionCallback callback;
6717 MockHttpRequest request(kSimpleGET_Transaction);
6720 scoped_ptr<HttpTransaction> trans;
6721 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6723 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6724 EXPECT_EQ(OK, callback.GetResult(rv));
6726 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6727 rv = trans->Read(buf.get(), 10, callback.callback());
6728 EXPECT_EQ(10, callback.GetResult(rv));
6730 trans->StopCaching();
6732 // We should be able to keep reading.
6733 rv = trans->Read(buf.get(), 256, callback.callback());
6734 EXPECT_GT(callback.GetResult(rv), 0);
6735 rv = trans->Read(buf.get(), 256, callback.callback());
6736 EXPECT_EQ(0, callback.GetResult(rv));
6739 // Make sure that the ActiveEntry is gone.
6740 base::MessageLoop::current()->RunUntilIdle();
6742 // Verify that the entry is gone.
6743 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6745 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6746 EXPECT_EQ(0, cache.disk_cache()->open_count());
6747 EXPECT_EQ(2, cache.disk_cache()->create_count());
6750 // Tests that we stop caching when told, even if DoneReading is called
6751 // after StopCaching.
6752 TEST(HttpCache, StopCachingThenDoneReadingDeletesEntry) {
6753 MockHttpCache cache;
6754 TestCompletionCallback callback;
6755 MockHttpRequest request(kSimpleGET_Transaction);
6758 scoped_ptr<HttpTransaction> trans;
6759 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6761 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6762 EXPECT_EQ(OK, callback.GetResult(rv));
6764 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6765 rv = trans->Read(buf.get(), 10, callback.callback());
6766 EXPECT_EQ(10, callback.GetResult(rv));
6768 trans->StopCaching();
6770 // We should be able to keep reading.
6771 rv = trans->Read(buf.get(), 256, callback.callback());
6772 EXPECT_GT(callback.GetResult(rv), 0);
6773 rv = trans->Read(buf.get(), 256, callback.callback());
6774 EXPECT_EQ(0, callback.GetResult(rv));
6776 // We should be able to call DoneReading.
6777 trans->DoneReading();
6780 // Make sure that the ActiveEntry is gone.
6781 base::MessageLoop::current()->RunUntilIdle();
6783 // Verify that the entry is gone.
6784 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6786 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6787 EXPECT_EQ(0, cache.disk_cache()->open_count());
6788 EXPECT_EQ(2, cache.disk_cache()->create_count());
6791 // Tests that we stop caching when told, when using auth.
6792 TEST(HttpCache, StopCachingWithAuthDeletesEntry) {
6793 MockHttpCache cache;
6794 TestCompletionCallback callback;
6795 MockTransaction mock_transaction(kSimpleGET_Transaction);
6796 mock_transaction.status = "HTTP/1.1 401 Unauthorized";
6797 AddMockTransaction(&mock_transaction);
6798 MockHttpRequest request(mock_transaction);
6801 scoped_ptr<HttpTransaction> trans;
6802 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6804 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6805 EXPECT_EQ(OK, callback.GetResult(rv));
6807 trans->StopCaching();
6809 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6810 rv = trans->Read(buf.get(), 10, callback.callback());
6811 EXPECT_EQ(callback.GetResult(rv), 10);
6813 RemoveMockTransaction(&mock_transaction);
6815 // Make sure that the ActiveEntry is gone.
6816 base::MessageLoop::current()->RunUntilIdle();
6818 // Verify that the entry is gone.
6819 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6821 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6822 EXPECT_EQ(0, cache.disk_cache()->open_count());
6823 EXPECT_EQ(2, cache.disk_cache()->create_count());
6826 // Tests that when we are told to stop caching we don't throw away valid data.
6827 TEST(HttpCache, StopCachingSavesEntry) {
6828 MockHttpCache cache;
6829 TestCompletionCallback callback;
6830 MockHttpRequest request(kSimpleGET_Transaction);
6833 scoped_ptr<HttpTransaction> trans;
6834 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6836 // Force a response that can be resumed.
6837 MockTransaction mock_transaction(kSimpleGET_Transaction);
6838 AddMockTransaction(&mock_transaction);
6839 mock_transaction.response_headers = "Cache-Control: max-age=10000\n"
6840 "Content-Length: 42\n"
6841 "Etag: \"foo\"\n";
6843 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6844 EXPECT_EQ(OK, callback.GetResult(rv));
6846 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6847 rv = trans->Read(buf.get(), 10, callback.callback());
6848 EXPECT_EQ(callback.GetResult(rv), 10);
6850 trans->StopCaching();
6852 // We should be able to keep reading.
6853 rv = trans->Read(buf.get(), 256, callback.callback());
6854 EXPECT_GT(callback.GetResult(rv), 0);
6855 rv = trans->Read(buf.get(), 256, callback.callback());
6856 EXPECT_EQ(callback.GetResult(rv), 0);
6858 RemoveMockTransaction(&mock_transaction);
6861 // Verify that the entry is marked as incomplete.
6862 disk_cache::Entry* entry;
6863 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
6864 HttpResponseInfo response;
6865 bool truncated = false;
6866 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6867 EXPECT_TRUE(truncated);
6868 entry->Close();
6871 // Tests that we handle truncated enries when StopCaching is called.
6872 TEST(HttpCache, StopCachingTruncatedEntry) {
6873 MockHttpCache cache;
6874 TestCompletionCallback callback;
6875 MockHttpRequest request(kRangeGET_TransactionOK);
6876 request.extra_headers.Clear();
6877 request.extra_headers.AddHeaderFromString(EXTRA_HEADER_LINE);
6878 AddMockTransaction(&kRangeGET_TransactionOK);
6880 std::string raw_headers("HTTP/1.1 200 OK\n"
6881 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
6882 "ETag: \"foo\"\n"
6883 "Accept-Ranges: bytes\n"
6884 "Content-Length: 80\n");
6885 CreateTruncatedEntry(raw_headers, &cache);
6888 // Now make a regular request.
6889 scoped_ptr<HttpTransaction> trans;
6890 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6892 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6893 EXPECT_EQ(OK, callback.GetResult(rv));
6895 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6896 rv = trans->Read(buf.get(), 10, callback.callback());
6897 EXPECT_EQ(callback.GetResult(rv), 10);
6899 // This is actually going to do nothing.
6900 trans->StopCaching();
6902 // We should be able to keep reading.
6903 rv = trans->Read(buf.get(), 256, callback.callback());
6904 EXPECT_GT(callback.GetResult(rv), 0);
6905 rv = trans->Read(buf.get(), 256, callback.callback());
6906 EXPECT_GT(callback.GetResult(rv), 0);
6907 rv = trans->Read(buf.get(), 256, callback.callback());
6908 EXPECT_EQ(callback.GetResult(rv), 0);
6911 // Verify that the disk entry was updated.
6912 disk_cache::Entry* entry;
6913 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6914 EXPECT_EQ(80, entry->GetDataSize(1));
6915 bool truncated = true;
6916 HttpResponseInfo response;
6917 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6918 EXPECT_FALSE(truncated);
6919 entry->Close();
6921 RemoveMockTransaction(&kRangeGET_TransactionOK);
6924 // Tests that we detect truncated resources from the net when there is
6925 // a Content-Length header.
6926 TEST(HttpCache, TruncatedByContentLength) {
6927 MockHttpCache cache;
6928 TestCompletionCallback callback;
6930 MockTransaction transaction(kSimpleGET_Transaction);
6931 AddMockTransaction(&transaction);
6932 transaction.response_headers = "Cache-Control: max-age=10000\n"
6933 "Content-Length: 100\n";
6934 RunTransactionTest(cache.http_cache(), transaction);
6935 RemoveMockTransaction(&transaction);
6937 // Read from the cache.
6938 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6940 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6941 EXPECT_EQ(0, cache.disk_cache()->open_count());
6942 EXPECT_EQ(2, cache.disk_cache()->create_count());
6945 // Tests that we actually flag entries as truncated when we detect an error
6946 // from the net.
6947 TEST(HttpCache, TruncatedByContentLength2) {
6948 MockHttpCache cache;
6949 TestCompletionCallback callback;
6951 MockTransaction transaction(kSimpleGET_Transaction);
6952 AddMockTransaction(&transaction);
6953 transaction.response_headers = "Cache-Control: max-age=10000\n"
6954 "Content-Length: 100\n"
6955 "Etag: \"foo\"\n";
6956 RunTransactionTest(cache.http_cache(), transaction);
6957 RemoveMockTransaction(&transaction);
6959 // Verify that the entry is marked as incomplete.
6960 disk_cache::Entry* entry;
6961 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
6962 HttpResponseInfo response;
6963 bool truncated = false;
6964 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6965 EXPECT_TRUE(truncated);
6966 entry->Close();
6969 // Make sure that calling SetPriority on a cache transaction passes on
6970 // its priority updates to its underlying network transaction.
6971 TEST(HttpCache, SetPriority) {
6972 MockHttpCache cache;
6974 scoped_ptr<HttpTransaction> trans;
6975 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(IDLE, &trans));
6977 // Shouldn't crash, but doesn't do anything either.
6978 trans->SetPriority(LOW);
6980 EXPECT_FALSE(cache.network_layer()->last_transaction());
6981 EXPECT_EQ(DEFAULT_PRIORITY,
6982 cache.network_layer()->last_create_transaction_priority());
6984 HttpRequestInfo info;
6985 info.url = GURL(kSimpleGET_Transaction.url);
6986 TestCompletionCallback callback;
6987 EXPECT_EQ(ERR_IO_PENDING,
6988 trans->Start(&info, callback.callback(), BoundNetLog()));
6990 EXPECT_TRUE(cache.network_layer()->last_transaction());
6991 if (cache.network_layer()->last_transaction()) {
6992 EXPECT_EQ(LOW, cache.network_layer()->last_create_transaction_priority());
6993 EXPECT_EQ(LOW, cache.network_layer()->last_transaction()->priority());
6996 trans->SetPriority(HIGHEST);
6998 if (cache.network_layer()->last_transaction()) {
6999 EXPECT_EQ(LOW, cache.network_layer()->last_create_transaction_priority());
7000 EXPECT_EQ(HIGHEST, cache.network_layer()->last_transaction()->priority());
7003 EXPECT_EQ(OK, callback.WaitForResult());
7006 // Make sure that calling SetWebSocketHandshakeStreamCreateHelper on a cache
7007 // transaction passes on its argument to the underlying network transaction.
7008 TEST(HttpCache, SetWebSocketHandshakeStreamCreateHelper) {
7009 MockHttpCache cache;
7011 FakeWebSocketHandshakeStreamCreateHelper create_helper;
7012 scoped_ptr<HttpTransaction> trans;
7013 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(IDLE, &trans));
7015 EXPECT_FALSE(cache.network_layer()->last_transaction());
7017 HttpRequestInfo info;
7018 info.url = GURL(kSimpleGET_Transaction.url);
7019 TestCompletionCallback callback;
7020 EXPECT_EQ(ERR_IO_PENDING,
7021 trans->Start(&info, callback.callback(), BoundNetLog()));
7023 ASSERT_TRUE(cache.network_layer()->last_transaction());
7024 EXPECT_FALSE(cache.network_layer()->last_transaction()->
7025 websocket_handshake_stream_create_helper());
7026 trans->SetWebSocketHandshakeStreamCreateHelper(&create_helper);
7027 EXPECT_EQ(&create_helper,
7028 cache.network_layer()->last_transaction()->
7029 websocket_handshake_stream_create_helper());
7030 EXPECT_EQ(OK, callback.WaitForResult());
7033 // Make sure that a cache transaction passes on its priority to
7034 // newly-created network transactions.
7035 TEST(HttpCache, SetPriorityNewTransaction) {
7036 MockHttpCache cache;
7037 AddMockTransaction(&kRangeGET_TransactionOK);
7039 std::string raw_headers("HTTP/1.1 200 OK\n"
7040 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7041 "ETag: \"foo\"\n"
7042 "Accept-Ranges: bytes\n"
7043 "Content-Length: 80\n");
7044 CreateTruncatedEntry(raw_headers, &cache);
7046 // Now make a regular request.
7047 std::string headers;
7048 MockTransaction transaction(kRangeGET_TransactionOK);
7049 transaction.request_headers = EXTRA_HEADER;
7050 transaction.data = kFullRangeData;
7052 scoped_ptr<HttpTransaction> trans;
7053 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(MEDIUM, &trans));
7054 EXPECT_EQ(DEFAULT_PRIORITY,
7055 cache.network_layer()->last_create_transaction_priority());
7057 MockHttpRequest info(transaction);
7058 TestCompletionCallback callback;
7059 EXPECT_EQ(ERR_IO_PENDING,
7060 trans->Start(&info, callback.callback(), BoundNetLog()));
7061 EXPECT_EQ(OK, callback.WaitForResult());
7063 EXPECT_EQ(MEDIUM, cache.network_layer()->last_create_transaction_priority());
7065 trans->SetPriority(HIGHEST);
7066 // Should trigger a new network transaction and pick up the new
7067 // priority.
7068 ReadAndVerifyTransaction(trans.get(), transaction);
7070 EXPECT_EQ(HIGHEST, cache.network_layer()->last_create_transaction_priority());
7072 RemoveMockTransaction(&kRangeGET_TransactionOK);
7075 int64 RunTransactionAndGetReceivedBytes(
7076 MockHttpCache& cache,
7077 const MockTransaction& trans_info) {
7078 int64 received_bytes = -1;
7079 RunTransactionTestBase(cache.http_cache(), trans_info,
7080 MockHttpRequest(trans_info), NULL, BoundNetLog(), NULL,
7081 &received_bytes);
7082 return received_bytes;
7085 int64 TransactionSize(const MockTransaction& transaction) {
7086 return strlen(transaction.status) + strlen(transaction.response_headers) +
7087 strlen(transaction.data);
7090 TEST(HttpCache, ReceivedBytesCacheMissAndThenHit) {
7091 MockHttpCache cache;
7093 MockTransaction transaction(kSimpleGET_Transaction);
7094 int64 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7095 EXPECT_EQ(TransactionSize(transaction), received_bytes);
7097 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7098 EXPECT_EQ(0, received_bytes);
7101 TEST(HttpCache, ReceivedBytesConditionalRequest304) {
7102 MockHttpCache cache;
7104 ScopedMockTransaction transaction(kETagGET_Transaction);
7105 int64 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7106 EXPECT_EQ(TransactionSize(transaction), received_bytes);
7108 transaction.load_flags = LOAD_VALIDATE_CACHE;
7109 transaction.handler = ETagGet_ConditionalRequest_Handler;
7110 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7111 EXPECT_EQ(TransactionSize(transaction), received_bytes);
7114 TEST(HttpCache, ReceivedBytesConditionalRequest200) {
7115 MockHttpCache cache;
7117 MockTransaction transaction(kTypicalGET_Transaction);
7118 transaction.request_headers = "Foo: bar\r\n";
7119 transaction.response_headers =
7120 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
7121 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
7122 "Etag: \"foopy\"\n"
7123 "Cache-Control: max-age=0\n"
7124 "Vary: Foo\n";
7125 AddMockTransaction(&transaction);
7126 int64 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7127 EXPECT_EQ(TransactionSize(transaction), received_bytes);
7129 RevalidationServer server;
7130 transaction.handler = server.Handler;
7131 transaction.request_headers = "Foo: none\r\n";
7132 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7133 EXPECT_EQ(TransactionSize(transaction), received_bytes);
7135 RemoveMockTransaction(&transaction);
7138 TEST(HttpCache, ReceivedBytesRange) {
7139 MockHttpCache cache;
7140 AddMockTransaction(&kRangeGET_TransactionOK);
7141 MockTransaction transaction(kRangeGET_TransactionOK);
7143 // Read bytes 40-49 from the network.
7144 int64 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7145 int64 range_response_size = TransactionSize(transaction);
7146 EXPECT_EQ(range_response_size, received_bytes);
7148 // Read bytes 40-49 from the cache.
7149 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7150 EXPECT_EQ(0, received_bytes);
7151 base::MessageLoop::current()->RunUntilIdle();
7153 // Read bytes 30-39 from the network.
7154 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
7155 transaction.data = "rg: 30-39 ";
7156 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7157 EXPECT_EQ(range_response_size, received_bytes);
7158 base::MessageLoop::current()->RunUntilIdle();
7160 // Read bytes 20-29 and 50-59 from the network, bytes 30-49 from the cache.
7161 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
7162 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
7163 received_bytes = RunTransactionAndGetReceivedBytes(cache, transaction);
7164 EXPECT_EQ(range_response_size * 2, received_bytes);
7166 RemoveMockTransaction(&kRangeGET_TransactionOK);
7169 class HttpCachePrefetchValidationTest : public ::testing::Test {
7170 protected:
7171 static const int kMaxAgeSecs = 100;
7172 static const int kRequireValidationSecs = kMaxAgeSecs + 1;
7174 HttpCachePrefetchValidationTest() : transaction_(kSimpleGET_Transaction) {
7175 DCHECK_LT(kMaxAgeSecs, prefetch_reuse_mins() * kNumSecondsPerMinute);
7177 clock_ = new base::SimpleTestClock();
7178 cache_.http_cache()->SetClockForTesting(make_scoped_ptr(clock_));
7179 cache_.network_layer()->SetClock(clock_);
7181 transaction_.response_headers = "Cache-Control: max-age=100\n";
7184 bool TransactionRequiredNetwork(int load_flags) {
7185 int pre_transaction_count = transaction_count();
7186 transaction_.load_flags = load_flags;
7187 RunTransactionTest(cache_.http_cache(), transaction_);
7188 return pre_transaction_count != transaction_count();
7191 void AdvanceTime(int seconds) {
7192 clock_->Advance(base::TimeDelta::FromSeconds(seconds));
7195 int prefetch_reuse_mins() { return HttpCache::kPrefetchReuseMins; }
7197 // How many times this test has sent requests to the (fake) origin
7198 // server. Every test case needs to make at least one request to initialise
7199 // the cache.
7200 int transaction_count() {
7201 return cache_.network_layer()->transaction_count();
7204 MockHttpCache cache_;
7205 ScopedMockTransaction transaction_;
7206 std::string response_headers_;
7207 base::SimpleTestClock* clock_;
7210 TEST_F(HttpCachePrefetchValidationTest, SkipValidationShortlyAfterPrefetch) {
7211 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7212 AdvanceTime(kRequireValidationSecs);
7213 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7216 TEST_F(HttpCachePrefetchValidationTest, ValidateLongAfterPrefetch) {
7217 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7218 AdvanceTime(prefetch_reuse_mins() * kNumSecondsPerMinute);
7219 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7222 TEST_F(HttpCachePrefetchValidationTest, SkipValidationOnceOnly) {
7223 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7224 AdvanceTime(kRequireValidationSecs);
7225 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7226 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7229 TEST_F(HttpCachePrefetchValidationTest, SkipValidationOnceReadOnly) {
7230 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7231 AdvanceTime(kRequireValidationSecs);
7232 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_ONLY_FROM_CACHE));
7233 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7236 TEST_F(HttpCachePrefetchValidationTest, BypassCacheOverwritesPrefetch) {
7237 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7238 AdvanceTime(kRequireValidationSecs);
7239 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_BYPASS_CACHE));
7240 AdvanceTime(kRequireValidationSecs);
7241 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7244 TEST_F(HttpCachePrefetchValidationTest,
7245 SkipValidationOnExistingEntryThatNeedsValidation) {
7246 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7247 AdvanceTime(kRequireValidationSecs);
7248 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7249 AdvanceTime(kRequireValidationSecs);
7250 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7251 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7254 TEST_F(HttpCachePrefetchValidationTest,
7255 SkipValidationOnExistingEntryThatDoesNotNeedValidation) {
7256 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7257 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_PREFETCH));
7258 AdvanceTime(kRequireValidationSecs);
7259 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7260 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7263 TEST_F(HttpCachePrefetchValidationTest, PrefetchMultipleTimes) {
7264 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7265 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_PREFETCH));
7266 AdvanceTime(kRequireValidationSecs);
7267 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7270 TEST_F(HttpCachePrefetchValidationTest, ValidateOnDelayedSecondPrefetch) {
7271 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7272 AdvanceTime(kRequireValidationSecs);
7273 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7274 AdvanceTime(kRequireValidationSecs);
7275 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7278 // Framework for tests of stale-while-revalidate related functionality. With
7279 // the default settings (age=3601,stale-while-revalidate=7200,max-age=3600) it
7280 // will trigger the stale-while-revalidate asynchronous revalidation. Setting
7281 // |age_| to < 3600 will prevent any revalidation, and |age_| > 10800 will cause
7282 // synchronous revalidation.
7283 class HttpCacheStaleWhileRevalidateTest : public ::testing::Test {
7284 protected:
7285 HttpCacheStaleWhileRevalidateTest()
7286 : transaction_(kSimpleGET_Transaction),
7287 age_(3601),
7288 stale_while_revalidate_(7200),
7289 validator_("Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT") {
7290 cache_.http_cache()->set_use_stale_while_revalidate_for_testing(true);
7293 // RunTransactionTest() with the arguments from this fixture.
7294 void RunFixtureTransactionTest() {
7295 std::string response_headers = base::StringPrintf(
7296 "%s\n"
7297 "Age: %d\n"
7298 "Cache-Control: max-age=3600,stale-while-revalidate=%d\n",
7299 validator_.c_str(),
7300 age_,
7301 stale_while_revalidate_);
7302 transaction_.response_headers = response_headers.c_str();
7303 RunTransactionTest(cache_.http_cache(), transaction_);
7304 transaction_.response_headers = "";
7307 // How many times this test has sent requests to the (fake) origin
7308 // server. Every test case needs to make at least one request to initialise
7309 // the cache.
7310 int transaction_count() {
7311 return cache_.network_layer()->transaction_count();
7314 // How many times an existing cache entry was opened during the test case.
7315 int open_count() { return cache_.disk_cache()->open_count(); }
7317 MockHttpCache cache_;
7318 ScopedMockTransaction transaction_;
7319 int age_;
7320 int stale_while_revalidate_;
7321 std::string validator_;
7324 static void CheckResourceFreshnessHeader(const HttpRequestInfo* request,
7325 std::string* response_status,
7326 std::string* response_headers,
7327 std::string* response_data) {
7328 std::string value;
7329 EXPECT_TRUE(request->extra_headers.GetHeader("Resource-Freshness", &value));
7330 EXPECT_EQ("max-age=3600,stale-while-revalidate=7200,age=10801", value);
7333 // Verify that the Resource-Freshness header is sent on a revalidation if the
7334 // stale-while-revalidate directive was on the response.
7335 TEST_F(HttpCacheStaleWhileRevalidateTest, ResourceFreshnessHeaderSent) {
7336 age_ = 10801; // Outside the stale-while-revalidate window.
7338 // Write to the cache.
7339 RunFixtureTransactionTest();
7341 EXPECT_EQ(1, transaction_count());
7343 // Send the request again and check that Resource-Freshness header is added.
7344 transaction_.handler = CheckResourceFreshnessHeader;
7346 RunFixtureTransactionTest();
7348 EXPECT_EQ(2, transaction_count());
7351 static void CheckResourceFreshnessAbsent(const HttpRequestInfo* request,
7352 std::string* response_status,
7353 std::string* response_headers,
7354 std::string* response_data) {
7355 EXPECT_FALSE(request->extra_headers.HasHeader("Resource-Freshness"));
7358 // Verify that the Resource-Freshness header is not sent when
7359 // stale-while-revalidate is 0.
7360 TEST_F(HttpCacheStaleWhileRevalidateTest, ResourceFreshnessHeaderNotSent) {
7361 age_ = 10801;
7362 stale_while_revalidate_ = 0;
7364 // Write to the cache.
7365 RunFixtureTransactionTest();
7367 EXPECT_EQ(1, transaction_count());
7369 // Send the request again and check that Resource-Freshness header is absent.
7370 transaction_.handler = CheckResourceFreshnessAbsent;
7372 RunFixtureTransactionTest();
7374 EXPECT_EQ(2, transaction_count());
7377 // Verify that when stale-while-revalidate applies the response is read from
7378 // cache.
7379 TEST_F(HttpCacheStaleWhileRevalidateTest, ReadFromCache) {
7380 // Write to the cache.
7381 RunFixtureTransactionTest();
7383 EXPECT_EQ(0, open_count());
7384 EXPECT_EQ(1, transaction_count());
7386 // Read back from the cache.
7387 RunFixtureTransactionTest();
7389 EXPECT_EQ(1, open_count());
7390 EXPECT_EQ(1, transaction_count());
7393 // Verify that when stale-while-revalidate applies an asynchronous request is
7394 // sent.
7395 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncRequestSent) {
7396 // Write to the cache.
7397 RunFixtureTransactionTest();
7399 EXPECT_EQ(1, transaction_count());
7401 // Read back from the cache.
7402 RunFixtureTransactionTest();
7404 EXPECT_EQ(1, transaction_count());
7406 // Let the async request execute.
7407 base::RunLoop().RunUntilIdle();
7408 EXPECT_EQ(2, transaction_count());
7411 // Verify that tearing down the HttpCache with an async revalidation in progress
7412 // does not break anything (this test is most likely to find problems when run
7413 // with a memory checker such as AddressSanitizer).
7414 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncTearDown) {
7415 // Write to the cache.
7416 RunFixtureTransactionTest();
7418 // Read back from the cache.
7419 RunFixtureTransactionTest();
7422 static void CheckIfModifiedSinceHeader(const HttpRequestInfo* request,
7423 std::string* response_status,
7424 std::string* response_headers,
7425 std::string* response_data) {
7426 std::string value;
7427 EXPECT_TRUE(request->extra_headers.GetHeader("If-Modified-Since", &value));
7428 EXPECT_EQ("Sat, 18 Apr 2007 01:10:43 GMT", value);
7431 // Verify that the async revalidation contains an If-Modified-Since header.
7432 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncRequestIfModifiedSince) {
7433 // Write to the cache.
7434 RunFixtureTransactionTest();
7436 transaction_.handler = CheckIfModifiedSinceHeader;
7438 // Read back from the cache.
7439 RunFixtureTransactionTest();
7442 static void CheckIfNoneMatchHeader(const HttpRequestInfo* request,
7443 std::string* response_status,
7444 std::string* response_headers,
7445 std::string* response_data) {
7446 std::string value;
7447 EXPECT_TRUE(request->extra_headers.GetHeader("If-None-Match", &value));
7448 EXPECT_EQ("\"40a1-1320-4f6adefa22a40\"", value);
7451 // If the response had ETag rather than Last-Modified, then that is used to
7452 // conditionalise the response.
7453 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncRequestIfNoneMatch) {
7454 validator_ = "Etag: \"40a1-1320-4f6adefa22a40\"";
7456 // Write to the cache.
7457 RunFixtureTransactionTest();
7459 transaction_.handler = CheckIfNoneMatchHeader;
7461 // Read back from the cache.
7462 RunFixtureTransactionTest();
7465 static void CheckResourceFreshnessHeaderPresent(const HttpRequestInfo* request,
7466 std::string* response_status,
7467 std::string* response_headers,
7468 std::string* response_data) {
7469 EXPECT_TRUE(request->extra_headers.HasHeader("Resource-Freshness"));
7472 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncRequestHasResourceFreshness) {
7473 // Write to the cache.
7474 RunFixtureTransactionTest();
7476 transaction_.handler = CheckResourceFreshnessHeaderPresent;
7478 // Read back from the cache.
7479 RunFixtureTransactionTest();
7482 // Verify that when age > max-age + stale-while-revalidate stale results are
7483 // not returned.
7484 TEST_F(HttpCacheStaleWhileRevalidateTest, NotAppliedIfTooStale) {
7485 age_ = 10801;
7487 // Write to the cache.
7488 RunFixtureTransactionTest();
7490 EXPECT_EQ(0, open_count());
7491 EXPECT_EQ(1, transaction_count());
7493 // Reading back reads from the network.
7494 RunFixtureTransactionTest();
7496 EXPECT_EQ(1, open_count());
7497 EXPECT_EQ(2, transaction_count());
7500 // HEAD requests should be able to take advantage of stale-while-revalidate.
7501 TEST_F(HttpCacheStaleWhileRevalidateTest, WorksForHeadMethod) {
7502 // Write to the cache. This has to be a GET request; HEAD requests don't
7503 // create new cache entries.
7504 RunFixtureTransactionTest();
7506 EXPECT_EQ(0, open_count());
7507 EXPECT_EQ(1, transaction_count());
7509 // Read back from the cache, and trigger an asynchronous HEAD request.
7510 transaction_.method = "HEAD";
7511 transaction_.data = "";
7513 RunFixtureTransactionTest();
7515 EXPECT_EQ(1, open_count());
7516 EXPECT_EQ(1, transaction_count());
7518 // Let the network request proceed.
7519 base::RunLoop().RunUntilIdle();
7521 EXPECT_EQ(2, transaction_count());
7524 // POST requests should not use stale-while-revalidate.
7525 TEST_F(HttpCacheStaleWhileRevalidateTest, NotAppliedToPost) {
7526 transaction_ = ScopedMockTransaction(kSimplePOST_Transaction);
7528 // Write to the cache.
7529 RunFixtureTransactionTest();
7531 EXPECT_EQ(0, open_count());
7532 EXPECT_EQ(1, transaction_count());
7534 // Reading back reads from the network.
7535 RunFixtureTransactionTest();
7537 EXPECT_EQ(0, open_count());
7538 EXPECT_EQ(2, transaction_count());
7541 static void CheckUrlMatches(const HttpRequestInfo* request,
7542 std::string* response_status,
7543 std::string* response_headers,
7544 std::string* response_data) {
7545 EXPECT_EQ("http://www.google.com/", request->url.spec());
7548 // Async revalidation is issued to the original URL.
7549 TEST_F(HttpCacheStaleWhileRevalidateTest, AsyncRequestUrlMatches) {
7550 transaction_.url = "http://www.google.com/";
7551 // Write to the cache.
7552 RunFixtureTransactionTest();
7554 // Read back from the cache.
7555 RunFixtureTransactionTest();
7557 EXPECT_EQ(1, transaction_count());
7559 transaction_.handler = CheckUrlMatches;
7561 // Let the async request execute and perform the check.
7562 base::RunLoop().RunUntilIdle();
7563 EXPECT_EQ(2, transaction_count());
7566 class SyncLoadFlagTest : public HttpCacheStaleWhileRevalidateTest,
7567 public ::testing::WithParamInterface<int> {};
7569 // Flags which should always cause the request to be synchronous.
7570 TEST_P(SyncLoadFlagTest, MustBeSynchronous) {
7571 transaction_.load_flags |= GetParam();
7572 // Write to the cache.
7573 RunFixtureTransactionTest();
7575 EXPECT_EQ(1, transaction_count());
7577 // Reading back reads from the network.
7578 RunFixtureTransactionTest();
7580 EXPECT_EQ(2, transaction_count());
7583 INSTANTIATE_TEST_CASE_P(HttpCacheStaleWhileRevalidate,
7584 SyncLoadFlagTest,
7585 ::testing::Values(LOAD_VALIDATE_CACHE,
7586 LOAD_BYPASS_CACHE,
7587 LOAD_DISABLE_CACHE));
7589 TEST_F(HttpCacheStaleWhileRevalidateTest,
7590 PreferringCacheDoesNotTriggerAsyncRequest) {
7591 transaction_.load_flags |= LOAD_PREFERRING_CACHE;
7592 // Write to the cache.
7593 RunFixtureTransactionTest();
7595 EXPECT_EQ(1, transaction_count());
7597 // Reading back reads from the cache.
7598 RunFixtureTransactionTest();
7600 EXPECT_EQ(1, transaction_count());
7602 // If there was an async transaction created, it would run now.
7603 base::RunLoop().RunUntilIdle();
7605 // There was no async transaction.
7606 EXPECT_EQ(1, transaction_count());
7609 TEST_F(HttpCacheStaleWhileRevalidateTest, NotUsedWhenDisabled) {
7610 cache_.http_cache()->set_use_stale_while_revalidate_for_testing(false);
7611 // Write to the cache.
7612 RunFixtureTransactionTest();
7614 EXPECT_EQ(1, transaction_count());
7616 // A synchronous revalidation is performed.
7617 RunFixtureTransactionTest();
7619 EXPECT_EQ(2, transaction_count());
7622 TEST_F(HttpCacheStaleWhileRevalidateTest,
7623 OnlyFromCacheDoesNotTriggerAsyncRequest) {
7624 transaction_.load_flags |= LOAD_ONLY_FROM_CACHE;
7625 transaction_.return_code = ERR_CACHE_MISS;
7627 // Writing to the cache should fail, because we are avoiding the network.
7628 RunFixtureTransactionTest();
7630 EXPECT_EQ(0, transaction_count());
7632 base::RunLoop().RunUntilIdle();
7634 // Still nothing.
7635 EXPECT_EQ(0, transaction_count());
7638 // A certificate error during an asynchronous fetch should cause the next fetch
7639 // to proceed synchronously.
7640 // TODO(ricea): In future, only certificate errors which require user
7641 // interaction should fail the asynchronous revalidation, and they should cause
7642 // the next revalidation to be synchronous rather than requiring a total
7643 // refetch. This test will need to be updated appropriately.
7644 TEST_F(HttpCacheStaleWhileRevalidateTest, CertificateErrorCausesRefetch) {
7645 // Write to the cache.
7646 RunFixtureTransactionTest();
7648 EXPECT_EQ(1, transaction_count());
7650 // Now read back. RunTransactionTestBase() expects to receive the network
7651 // error back from the HttpCache::Transaction, but since the cache request
7652 // will return OK we need to duplicate some of its implementation here.
7653 transaction_.return_code = ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
7654 TestCompletionCallback callback;
7655 scoped_ptr<HttpTransaction> trans;
7656 int rv = cache_.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
7657 EXPECT_EQ(OK, rv);
7658 ASSERT_TRUE(trans.get());
7660 MockHttpRequest request(transaction_);
7661 rv = trans->Start(&request, callback.callback(), BoundNetLog());
7662 ASSERT_EQ(ERR_IO_PENDING, rv);
7663 ASSERT_EQ(OK, callback.WaitForResult());
7664 ReadAndVerifyTransaction(trans.get(), transaction_);
7666 EXPECT_EQ(1, transaction_count());
7668 // Allow the asynchronous fetch to run.
7669 base::RunLoop().RunUntilIdle();
7671 EXPECT_EQ(2, transaction_count());
7673 // Now run the transaction again. It should run synchronously.
7674 transaction_.return_code = OK;
7675 RunFixtureTransactionTest();
7677 EXPECT_EQ(3, transaction_count());
7680 // Ensure that the response cached by the asynchronous request is not truncated,
7681 // even if the server is slow.
7682 TEST_F(HttpCacheStaleWhileRevalidateTest, EntireResponseCached) {
7683 transaction_.test_mode = TEST_MODE_SLOW_READ;
7684 // Write to the cache.
7685 RunFixtureTransactionTest();
7687 // Read back from the cache.
7688 RunFixtureTransactionTest();
7690 // Let the async request execute.
7691 base::RunLoop().RunUntilIdle();
7693 // The cache entry should still be complete.
7694 transaction_.load_flags = LOAD_ONLY_FROM_CACHE;
7695 RunFixtureTransactionTest();
7698 // Verify that there are no race conditions in the completely synchronous case.
7699 TEST_F(HttpCacheStaleWhileRevalidateTest, SynchronousCaseWorks) {
7700 transaction_.test_mode = TEST_MODE_SYNC_ALL;
7701 // Write to the cache.
7702 RunFixtureTransactionTest();
7704 EXPECT_EQ(1, transaction_count());
7706 // Read back from the cache.
7707 RunFixtureTransactionTest();
7709 EXPECT_EQ(1, transaction_count());
7711 // Let the async request execute.
7712 base::RunLoop().RunUntilIdle();
7713 EXPECT_EQ(2, transaction_count());
7716 static void CheckLoadFlagsAsyncRevalidation(const HttpRequestInfo* request,
7717 std::string* response_status,
7718 std::string* response_headers,
7719 std::string* response_data) {
7720 EXPECT_EQ(LOAD_ASYNC_REVALIDATION, request->load_flags);
7723 // Check that the load flags on the async request are the same as the load flags
7724 // on the original request, plus LOAD_ASYNC_REVALIDATION.
7725 TEST_F(HttpCacheStaleWhileRevalidateTest, LoadFlagsAsyncRevalidation) {
7726 transaction_.load_flags = LOAD_NORMAL;
7727 // Write to the cache.
7728 RunFixtureTransactionTest();
7730 EXPECT_EQ(1, transaction_count());
7732 // Read back from the cache.
7733 RunFixtureTransactionTest();
7735 EXPECT_EQ(1, transaction_count());
7737 transaction_.handler = CheckLoadFlagsAsyncRevalidation;
7738 // Let the async request execute.
7739 base::RunLoop().RunUntilIdle();
7740 EXPECT_EQ(2, transaction_count());
7743 static void SimpleMockAuthHandler(const HttpRequestInfo* request,
7744 std::string* response_status,
7745 std::string* response_headers,
7746 std::string* response_data) {
7747 if (request->extra_headers.HasHeader("X-Require-Mock-Auth") &&
7748 !request->extra_headers.HasHeader("Authorization")) {
7749 response_status->assign("HTTP/1.1 401 Unauthorized");
7750 response_headers->assign("WWW-Authenticate: Basic realm=\"mars\"\n");
7751 return;
7753 response_status->assign("HTTP/1.1 200 OK");
7756 TEST_F(HttpCacheStaleWhileRevalidateTest, RestartForAuth) {
7757 // Write to the cache.
7758 RunFixtureTransactionTest();
7760 EXPECT_EQ(1, transaction_count());
7762 // Now make the transaction require auth.
7763 transaction_.request_headers = "X-Require-Mock-Auth: dummy\r\n\r\n";
7764 transaction_.handler = SimpleMockAuthHandler;
7766 // Read back from the cache.
7767 RunFixtureTransactionTest();
7769 EXPECT_EQ(1, transaction_count());
7771 // Let the async request execute.
7772 base::RunLoop().RunUntilIdle();
7774 EXPECT_EQ(2, transaction_count());
7777 // Tests that we allow multiple simultaneous, non-overlapping transactions to
7778 // take place on a sparse entry.
7779 TEST(HttpCache, RangeGET_MultipleRequests) {
7780 MockHttpCache cache;
7782 // Create a transaction for bytes 0-9.
7783 MockHttpRequest request(kRangeGET_TransactionOK);
7784 MockTransaction transaction(kRangeGET_TransactionOK);
7785 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
7786 transaction.data = "rg: 00-09 ";
7787 AddMockTransaction(&transaction);
7789 TestCompletionCallback callback;
7790 scoped_ptr<HttpTransaction> trans;
7791 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
7792 EXPECT_EQ(OK, rv);
7793 ASSERT_TRUE(trans.get());
7795 // Start our transaction.
7796 trans->Start(&request, callback.callback(), BoundNetLog());
7798 // A second transaction on a different part of the file (the default
7799 // kRangeGET_TransactionOK requests 40-49) should not be blocked by
7800 // the already pending transaction.
7801 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
7803 // Let the first transaction complete.
7804 callback.WaitForResult();
7806 RemoveMockTransaction(&transaction);
7809 // Makes sure that a request stops using the cache when the response headers
7810 // with "Cache-Control: no-store" arrives. That means that another request for
7811 // the same URL can be processed before the response body of the original
7812 // request arrives.
7813 TEST(HttpCache, NoStoreResponseShouldNotBlockFollowingRequests) {
7814 MockHttpCache cache;
7815 ScopedMockTransaction mock_transaction(kSimpleGET_Transaction);
7816 mock_transaction.response_headers = "Cache-Control: no-store\n";
7817 MockHttpRequest request(mock_transaction);
7819 scoped_ptr<Context> first(new Context);
7820 first->result = cache.CreateTransaction(&first->trans);
7821 ASSERT_EQ(OK, first->result);
7822 EXPECT_EQ(LOAD_STATE_IDLE, first->trans->GetLoadState());
7823 first->result =
7824 first->trans->Start(&request, first->callback.callback(), BoundNetLog());
7825 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, first->trans->GetLoadState());
7827 base::MessageLoop::current()->RunUntilIdle();
7828 EXPECT_EQ(LOAD_STATE_IDLE, first->trans->GetLoadState());
7829 ASSERT_TRUE(first->trans->GetResponseInfo());
7830 EXPECT_TRUE(first->trans->GetResponseInfo()->headers->HasHeaderValue(
7831 "Cache-Control", "no-store"));
7832 // Here we have read the response header but not read the response body yet.
7834 // Let us create the second (read) transaction.
7835 scoped_ptr<Context> second(new Context);
7836 second->result = cache.CreateTransaction(&second->trans);
7837 ASSERT_EQ(OK, second->result);
7838 EXPECT_EQ(LOAD_STATE_IDLE, second->trans->GetLoadState());
7839 second->result = second->trans->Start(&request, second->callback.callback(),
7840 BoundNetLog());
7842 // Here the second transaction proceeds without reading the first body.
7843 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, second->trans->GetLoadState());
7844 base::MessageLoop::current()->RunUntilIdle();
7845 EXPECT_EQ(LOAD_STATE_IDLE, second->trans->GetLoadState());
7846 ASSERT_TRUE(second->trans->GetResponseInfo());
7847 EXPECT_TRUE(second->trans->GetResponseInfo()->headers->HasHeaderValue(
7848 "Cache-Control", "no-store"));
7849 ReadAndVerifyTransaction(second->trans.get(), kSimpleGET_Transaction);
7851 } // namespace net