Update V8 to version 4.7.47.
[chromium-blink-merge.git] / net / http / http_cache_unittest.cc
blob2d4625f7559d296dcb3df1f3314c5259025c92be
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 <stdint.h>
9 #include <algorithm>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/memory/scoped_vector.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/stringprintf.h"
18 #include "base/test/simple_test_clock.h"
19 #include "net/base/cache_type.h"
20 #include "net/base/elements_upload_data_stream.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/load_flags.h"
23 #include "net/base/load_timing_info.h"
24 #include "net/base/load_timing_info_test_util.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/test_data_directory.h"
27 #include "net/base/upload_bytes_element_reader.h"
28 #include "net/cert/cert_status_flags.h"
29 #include "net/cert/x509_certificate.h"
30 #include "net/disk_cache/disk_cache.h"
31 #include "net/http/http_byte_range.h"
32 #include "net/http/http_cache_transaction.h"
33 #include "net/http/http_request_headers.h"
34 #include "net/http/http_request_info.h"
35 #include "net/http/http_response_headers.h"
36 #include "net/http/http_response_info.h"
37 #include "net/http/http_transaction.h"
38 #include "net/http/http_transaction_test_util.h"
39 #include "net/http/http_util.h"
40 #include "net/http/mock_http_cache.h"
41 #include "net/log/test_net_log.h"
42 #include "net/log/test_net_log_entry.h"
43 #include "net/log/test_net_log_util.h"
44 #include "net/socket/client_socket_handle.h"
45 #include "net/ssl/ssl_cert_request_info.h"
46 #include "net/ssl/ssl_connection_status_flags.h"
47 #include "net/test/cert_test_util.h"
48 #include "net/websockets/websocket_handshake_stream_base.h"
49 #include "testing/gtest/include/gtest/gtest.h"
51 using base::Time;
53 namespace net {
55 namespace {
57 // Tests the load timing values of a request that goes through a
58 // MockNetworkTransaction.
59 void TestLoadTimingNetworkRequest(const LoadTimingInfo& load_timing_info) {
60 EXPECT_FALSE(load_timing_info.socket_reused);
61 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
63 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
64 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
66 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
67 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
68 EXPECT_LE(load_timing_info.connect_timing.connect_end,
69 load_timing_info.send_start);
71 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
73 // Set by URLRequest / URLRequestHttpJob, at a higher level.
74 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
75 EXPECT_TRUE(load_timing_info.request_start.is_null());
76 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
79 // Tests the load timing values of a request that receives a cached response.
80 void TestLoadTimingCachedResponse(const LoadTimingInfo& load_timing_info) {
81 EXPECT_FALSE(load_timing_info.socket_reused);
82 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
84 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
85 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
87 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
89 // Only the send start / end times should be sent, and they should have the
90 // same value.
91 EXPECT_FALSE(load_timing_info.send_start.is_null());
92 EXPECT_EQ(load_timing_info.send_start, load_timing_info.send_end);
94 // Set by URLRequest / URLRequestHttpJob, at a higher level.
95 EXPECT_TRUE(load_timing_info.request_start_time.is_null());
96 EXPECT_TRUE(load_timing_info.request_start.is_null());
97 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
100 class DeleteCacheCompletionCallback : public TestCompletionCallbackBase {
101 public:
102 explicit DeleteCacheCompletionCallback(MockHttpCache* cache)
103 : cache_(cache),
104 callback_(base::Bind(&DeleteCacheCompletionCallback::OnComplete,
105 base::Unretained(this))) {
108 const CompletionCallback& callback() const { return callback_; }
110 private:
111 void OnComplete(int result) {
112 delete cache_;
113 SetResult(result);
116 MockHttpCache* cache_;
117 CompletionCallback callback_;
119 DISALLOW_COPY_AND_ASSIGN(DeleteCacheCompletionCallback);
122 //-----------------------------------------------------------------------------
123 // helpers
125 void ReadAndVerifyTransaction(HttpTransaction* trans,
126 const MockTransaction& trans_info) {
127 std::string content;
128 int rv = ReadTransaction(trans, &content);
130 EXPECT_EQ(OK, rv);
131 std::string expected(trans_info.data);
132 EXPECT_EQ(expected, content);
135 void RunTransactionTestBase(HttpCache* cache,
136 const MockTransaction& trans_info,
137 const MockHttpRequest& request,
138 HttpResponseInfo* response_info,
139 const BoundNetLog& net_log,
140 LoadTimingInfo* load_timing_info,
141 int64_t* sent_bytes,
142 int64_t* received_bytes) {
143 TestCompletionCallback callback;
145 // write to the cache
147 scoped_ptr<HttpTransaction> trans;
148 int rv = cache->CreateTransaction(DEFAULT_PRIORITY, &trans);
149 EXPECT_EQ(OK, rv);
150 ASSERT_TRUE(trans.get());
152 rv = trans->Start(&request, callback.callback(), net_log);
153 if (rv == ERR_IO_PENDING)
154 rv = callback.WaitForResult();
155 ASSERT_EQ(trans_info.return_code, rv);
157 if (OK != rv)
158 return;
160 const HttpResponseInfo* response = trans->GetResponseInfo();
161 ASSERT_TRUE(response);
163 if (response_info)
164 *response_info = *response;
166 if (load_timing_info) {
167 // If a fake network connection is used, need a NetLog to get a fake socket
168 // ID.
169 EXPECT_TRUE(net_log.net_log());
170 *load_timing_info = LoadTimingInfo();
171 trans->GetLoadTimingInfo(load_timing_info);
174 ReadAndVerifyTransaction(trans.get(), trans_info);
176 if (sent_bytes)
177 *sent_bytes = trans->GetTotalSentBytes();
178 if (received_bytes)
179 *received_bytes = trans->GetTotalReceivedBytes();
182 void RunTransactionTestWithRequest(HttpCache* cache,
183 const MockTransaction& trans_info,
184 const MockHttpRequest& request,
185 HttpResponseInfo* response_info) {
186 RunTransactionTestBase(cache, trans_info, request, response_info,
187 BoundNetLog(), nullptr, nullptr, nullptr);
190 void RunTransactionTestAndGetTiming(HttpCache* cache,
191 const MockTransaction& trans_info,
192 const BoundNetLog& log,
193 LoadTimingInfo* load_timing_info) {
194 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
195 nullptr, log, load_timing_info, nullptr, nullptr);
198 void RunTransactionTest(HttpCache* cache, const MockTransaction& trans_info) {
199 RunTransactionTestAndGetTiming(cache, trans_info, BoundNetLog(), nullptr);
202 void RunTransactionTestWithLog(HttpCache* cache,
203 const MockTransaction& trans_info,
204 const BoundNetLog& log) {
205 RunTransactionTestAndGetTiming(cache, trans_info, log, nullptr);
208 void RunTransactionTestWithResponseInfo(HttpCache* cache,
209 const MockTransaction& trans_info,
210 HttpResponseInfo* response) {
211 RunTransactionTestWithRequest(cache, trans_info, MockHttpRequest(trans_info),
212 response);
215 void RunTransactionTestWithResponseInfoAndGetTiming(
216 HttpCache* cache,
217 const MockTransaction& trans_info,
218 HttpResponseInfo* response,
219 const BoundNetLog& log,
220 LoadTimingInfo* load_timing_info) {
221 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
222 response, log, load_timing_info, nullptr, nullptr);
225 void RunTransactionTestWithResponse(HttpCache* cache,
226 const MockTransaction& trans_info,
227 std::string* response_headers) {
228 HttpResponseInfo response;
229 RunTransactionTestWithResponseInfo(cache, trans_info, &response);
230 response.headers->GetNormalizedHeaders(response_headers);
233 void RunTransactionTestWithResponseAndGetTiming(
234 HttpCache* cache,
235 const MockTransaction& trans_info,
236 std::string* response_headers,
237 const BoundNetLog& log,
238 LoadTimingInfo* load_timing_info) {
239 HttpResponseInfo response;
240 RunTransactionTestBase(cache, trans_info, MockHttpRequest(trans_info),
241 &response, log, load_timing_info, nullptr, nullptr);
242 response.headers->GetNormalizedHeaders(response_headers);
245 // This class provides a handler for kFastNoStoreGET_Transaction so that the
246 // no-store header can be included on demand.
247 class FastTransactionServer {
248 public:
249 FastTransactionServer() {
250 no_store = false;
252 ~FastTransactionServer() {}
254 void set_no_store(bool value) { no_store = value; }
256 static void FastNoStoreHandler(const HttpRequestInfo* request,
257 std::string* response_status,
258 std::string* response_headers,
259 std::string* response_data) {
260 if (no_store)
261 *response_headers = "Cache-Control: no-store\n";
264 private:
265 static bool no_store;
266 DISALLOW_COPY_AND_ASSIGN(FastTransactionServer);
268 bool FastTransactionServer::no_store;
270 const MockTransaction kFastNoStoreGET_Transaction = {
271 "http://www.google.com/nostore",
272 "GET",
273 base::Time(),
275 LOAD_VALIDATE_CACHE,
276 "HTTP/1.1 200 OK",
277 "Cache-Control: max-age=10000\n",
278 base::Time(),
279 "<html><body>Google Blah Blah</body></html>",
280 TEST_MODE_SYNC_NET_START,
281 &FastTransactionServer::FastNoStoreHandler,
282 nullptr,
285 OK};
287 // This class provides a handler for kRangeGET_TransactionOK so that the range
288 // request can be served on demand.
289 class RangeTransactionServer {
290 public:
291 RangeTransactionServer() {
292 not_modified_ = false;
293 modified_ = false;
294 bad_200_ = false;
296 ~RangeTransactionServer() {
297 not_modified_ = false;
298 modified_ = false;
299 bad_200_ = false;
302 // Returns only 416 or 304 when set.
303 void set_not_modified(bool value) { not_modified_ = value; }
305 // Returns 206 when revalidating a range (instead of 304).
306 void set_modified(bool value) { modified_ = value; }
308 // Returns 200 instead of 206 (a malformed response overall).
309 void set_bad_200(bool value) { bad_200_ = value; }
311 // Other than regular range related behavior (and the flags mentioned above),
312 // the server reacts to requests headers like so:
313 // X-Require-Mock-Auth -> return 401.
314 // X-Require-Mock-Auth-Alt -> return 401.
315 // X-Return-Default-Range -> assume 40-49 was requested.
316 // The -Alt variant doesn't cause the MockNetworkTransaction to
317 // report that it IsReadyToRestartForAuth().
318 static void RangeHandler(const HttpRequestInfo* request,
319 std::string* response_status,
320 std::string* response_headers,
321 std::string* response_data);
323 private:
324 static bool not_modified_;
325 static bool modified_;
326 static bool bad_200_;
327 DISALLOW_COPY_AND_ASSIGN(RangeTransactionServer);
329 bool RangeTransactionServer::not_modified_ = false;
330 bool RangeTransactionServer::modified_ = false;
331 bool RangeTransactionServer::bad_200_ = false;
333 // A dummy extra header that must be preserved on a given request.
335 // EXTRA_HEADER_LINE doesn't include a line terminator because it
336 // will be passed to AddHeaderFromString() which doesn't accept them.
337 #define EXTRA_HEADER_LINE "Extra: header"
339 // EXTRA_HEADER contains a line terminator, as expected by
340 // AddHeadersFromString() (_not_ AddHeaderFromString()).
341 #define EXTRA_HEADER EXTRA_HEADER_LINE "\r\n"
343 static const char kExtraHeaderKey[] = "Extra";
345 // Static.
346 void RangeTransactionServer::RangeHandler(const HttpRequestInfo* request,
347 std::string* response_status,
348 std::string* response_headers,
349 std::string* response_data) {
350 if (request->extra_headers.IsEmpty()) {
351 response_status->assign("HTTP/1.1 416 Requested Range Not Satisfiable");
352 response_data->clear();
353 return;
356 // We want to make sure we don't delete extra headers.
357 EXPECT_TRUE(request->extra_headers.HasHeader(kExtraHeaderKey));
359 bool require_auth =
360 request->extra_headers.HasHeader("X-Require-Mock-Auth") ||
361 request->extra_headers.HasHeader("X-Require-Mock-Auth-Alt");
363 if (require_auth && !request->extra_headers.HasHeader("Authorization")) {
364 response_status->assign("HTTP/1.1 401 Unauthorized");
365 response_data->assign("WWW-Authenticate: Foo\n");
366 return;
369 if (not_modified_) {
370 response_status->assign("HTTP/1.1 304 Not Modified");
371 response_data->clear();
372 return;
375 std::vector<HttpByteRange> ranges;
376 std::string range_header;
377 if (!request->extra_headers.GetHeader(HttpRequestHeaders::kRange,
378 &range_header) ||
379 !HttpUtil::ParseRangeHeader(range_header, &ranges) || bad_200_ ||
380 ranges.size() != 1) {
381 // This is not a byte range request. We return 200.
382 response_status->assign("HTTP/1.1 200 OK");
383 response_headers->assign("Date: Wed, 28 Nov 2007 09:40:09 GMT");
384 response_data->assign("Not a range");
385 return;
388 // We can handle this range request.
389 HttpByteRange byte_range = ranges[0];
391 if (request->extra_headers.HasHeader("X-Return-Default-Range")) {
392 byte_range.set_first_byte_position(40);
393 byte_range.set_last_byte_position(49);
396 if (byte_range.first_byte_position() > 79) {
397 response_status->assign("HTTP/1.1 416 Requested Range Not Satisfiable");
398 response_data->clear();
399 return;
402 EXPECT_TRUE(byte_range.ComputeBounds(80));
403 int start = static_cast<int>(byte_range.first_byte_position());
404 int end = static_cast<int>(byte_range.last_byte_position());
406 EXPECT_LT(end, 80);
408 std::string content_range = base::StringPrintf(
409 "Content-Range: bytes %d-%d/80\n", start, end);
410 response_headers->append(content_range);
412 if (!request->extra_headers.HasHeader("If-None-Match") || modified_) {
413 std::string data;
414 if (end == start) {
415 EXPECT_EQ(0, end % 10);
416 data = "r";
417 } else {
418 EXPECT_EQ(9, (end - start) % 10);
419 for (int block_start = start; block_start < end; block_start += 10) {
420 base::StringAppendF(&data, "rg: %02d-%02d ",
421 block_start, block_start + 9);
424 *response_data = data;
426 if (end - start != 9) {
427 // We also have to fix content-length.
428 int len = end - start + 1;
429 std::string content_length = base::StringPrintf("Content-Length: %d\n",
430 len);
431 response_headers->replace(response_headers->find("Content-Length:"),
432 content_length.size(), content_length);
434 } else {
435 response_status->assign("HTTP/1.1 304 Not Modified");
436 response_data->clear();
440 const MockTransaction kRangeGET_TransactionOK = {
441 "http://www.google.com/range",
442 "GET",
443 base::Time(),
444 "Range: bytes = 40-49\r\n" EXTRA_HEADER,
445 LOAD_NORMAL,
446 "HTTP/1.1 206 Partial Content",
447 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
448 "ETag: \"foo\"\n"
449 "Accept-Ranges: bytes\n"
450 "Content-Length: 10\n",
451 base::Time(),
452 "rg: 40-49 ",
453 TEST_MODE_NORMAL,
454 &RangeTransactionServer::RangeHandler,
455 nullptr,
458 OK};
460 const char kFullRangeData[] =
461 "rg: 00-09 rg: 10-19 rg: 20-29 rg: 30-39 "
462 "rg: 40-49 rg: 50-59 rg: 60-69 rg: 70-79 ";
464 // Verifies the response headers (|response|) match a partial content
465 // response for the range starting at |start| and ending at |end|.
466 void Verify206Response(std::string response, int start, int end) {
467 std::string raw_headers(
468 HttpUtil::AssembleRawHeaders(response.data(), response.size()));
469 scoped_refptr<HttpResponseHeaders> headers(
470 new HttpResponseHeaders(raw_headers));
472 ASSERT_EQ(206, headers->response_code());
474 int64 range_start, range_end, object_size;
475 ASSERT_TRUE(
476 headers->GetContentRange(&range_start, &range_end, &object_size));
477 int64 content_length = headers->GetContentLength();
479 int length = end - start + 1;
480 ASSERT_EQ(length, content_length);
481 ASSERT_EQ(start, range_start);
482 ASSERT_EQ(end, range_end);
485 // Creates a truncated entry that can be resumed using byte ranges.
486 void CreateTruncatedEntry(std::string raw_headers, MockHttpCache* cache) {
487 // Create a disk cache entry that stores an incomplete resource.
488 disk_cache::Entry* entry;
489 ASSERT_TRUE(cache->CreateBackendEntry(kRangeGET_TransactionOK.url, &entry,
490 NULL));
492 raw_headers =
493 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
495 HttpResponseInfo response;
496 response.response_time = base::Time::Now();
497 response.request_time = base::Time::Now();
498 response.headers = new HttpResponseHeaders(raw_headers);
499 // Set the last argument for this to be an incomplete request.
500 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, true));
502 scoped_refptr<IOBuffer> buf(new IOBuffer(100));
503 int len = static_cast<int>(base::strlcpy(buf->data(),
504 "rg: 00-09 rg: 10-19 ", 100));
505 TestCompletionCallback cb;
506 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
507 EXPECT_EQ(len, cb.GetResult(rv));
508 entry->Close();
511 // Helper to represent a network HTTP response.
512 struct Response {
513 // Set this response into |trans|.
514 void AssignTo(MockTransaction* trans) const {
515 trans->status = status;
516 trans->response_headers = headers;
517 trans->data = body;
520 std::string status_and_headers() const {
521 return std::string(status) + "\n" + std::string(headers);
524 const char* status;
525 const char* headers;
526 const char* body;
529 struct Context {
530 Context() : result(ERR_IO_PENDING) {}
532 int result;
533 TestCompletionCallback callback;
534 scoped_ptr<HttpTransaction> trans;
537 class FakeWebSocketHandshakeStreamCreateHelper
538 : public WebSocketHandshakeStreamBase::CreateHelper {
539 public:
540 ~FakeWebSocketHandshakeStreamCreateHelper() override {}
541 WebSocketHandshakeStreamBase* CreateBasicStream(
542 scoped_ptr<ClientSocketHandle> connect,
543 bool using_proxy) override {
544 return NULL;
546 WebSocketHandshakeStreamBase* CreateSpdyStream(
547 const base::WeakPtr<SpdySession>& session,
548 bool use_relative_url) override {
549 return NULL;
553 // Returns true if |entry| is not one of the log types paid attention to in this
554 // test. Note that TYPE_HTTP_CACHE_WRITE_INFO and TYPE_HTTP_CACHE_*_DATA are
555 // ignored.
556 bool ShouldIgnoreLogEntry(const TestNetLogEntry& entry) {
557 switch (entry.type) {
558 case NetLog::TYPE_HTTP_CACHE_GET_BACKEND:
559 case NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY:
560 case NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY:
561 case NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY:
562 case NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY:
563 case NetLog::TYPE_HTTP_CACHE_READ_INFO:
564 return false;
565 default:
566 return true;
570 // Modifies |entries| to only include log entries created by the cache layer and
571 // asserted on in these tests.
572 void FilterLogEntries(TestNetLogEntry::List* entries) {
573 entries->erase(std::remove_if(entries->begin(), entries->end(),
574 &ShouldIgnoreLogEntry),
575 entries->end());
578 bool LogContainsEventType(const BoundTestNetLog& log,
579 NetLog::EventType expected) {
580 TestNetLogEntry::List entries;
581 log.GetEntries(&entries);
582 for (size_t i = 0; i < entries.size(); i++) {
583 if (entries[i].type == expected)
584 return true;
586 return false;
589 } // namespace
592 //-----------------------------------------------------------------------------
593 // Tests.
595 TEST(HttpCache, CreateThenDestroy) {
596 MockHttpCache cache;
598 scoped_ptr<HttpTransaction> trans;
599 EXPECT_EQ(OK, cache.CreateTransaction(&trans));
600 ASSERT_TRUE(trans.get());
603 TEST(HttpCache, GetBackend) {
604 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(0));
606 disk_cache::Backend* backend;
607 TestCompletionCallback cb;
608 // This will lazily initialize the backend.
609 int rv = cache.http_cache()->GetBackend(&backend, cb.callback());
610 EXPECT_EQ(OK, cb.GetResult(rv));
613 TEST(HttpCache, SimpleGET) {
614 MockHttpCache cache;
615 BoundTestNetLog log;
616 LoadTimingInfo load_timing_info;
618 // Write to the cache.
619 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
620 log.bound(), &load_timing_info);
622 EXPECT_EQ(1, cache.network_layer()->transaction_count());
623 EXPECT_EQ(0, cache.disk_cache()->open_count());
624 EXPECT_EQ(1, cache.disk_cache()->create_count());
625 TestLoadTimingNetworkRequest(load_timing_info);
628 TEST(HttpCache, SimpleGETNoDiskCache) {
629 MockHttpCache cache;
631 cache.disk_cache()->set_fail_requests();
633 BoundTestNetLog log;
634 LoadTimingInfo load_timing_info;
636 // Read from the network, and don't use the cache.
637 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
638 log.bound(), &load_timing_info);
640 // Check that the NetLog was filled as expected.
641 // (We attempted to both Open and Create entries, but both failed).
642 TestNetLogEntry::List entries;
643 log.GetEntries(&entries);
644 FilterLogEntries(&entries);
646 EXPECT_EQ(6u, entries.size());
647 EXPECT_TRUE(
648 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
649 EXPECT_TRUE(
650 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
651 EXPECT_TRUE(
652 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
653 EXPECT_TRUE(
654 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
655 EXPECT_TRUE(
656 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
657 EXPECT_TRUE(
658 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
660 EXPECT_EQ(1, cache.network_layer()->transaction_count());
661 EXPECT_EQ(0, cache.disk_cache()->open_count());
662 EXPECT_EQ(0, cache.disk_cache()->create_count());
663 TestLoadTimingNetworkRequest(load_timing_info);
666 TEST(HttpCache, SimpleGETNoDiskCache2) {
667 // This will initialize a cache object with NULL backend.
668 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
669 factory->set_fail(true);
670 factory->FinishCreation(); // We'll complete synchronously.
671 MockHttpCache cache(factory);
673 // Read from the network, and don't use the cache.
674 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
676 EXPECT_EQ(1, cache.network_layer()->transaction_count());
677 EXPECT_FALSE(cache.http_cache()->GetCurrentBackend());
680 // Tests that IOBuffers are not referenced after IO completes.
681 TEST(HttpCache, ReleaseBuffer) {
682 MockHttpCache cache;
684 // Write to the cache.
685 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
687 MockHttpRequest request(kSimpleGET_Transaction);
688 scoped_ptr<HttpTransaction> trans;
689 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
691 const int kBufferSize = 10;
692 scoped_refptr<IOBuffer> buffer(new IOBuffer(kBufferSize));
693 ReleaseBufferCompletionCallback cb(buffer.get());
695 int rv = trans->Start(&request, cb.callback(), BoundNetLog());
696 EXPECT_EQ(OK, cb.GetResult(rv));
698 rv = trans->Read(buffer.get(), kBufferSize, cb.callback());
699 EXPECT_EQ(kBufferSize, cb.GetResult(rv));
702 TEST(HttpCache, SimpleGETWithDiskFailures) {
703 MockHttpCache cache;
705 cache.disk_cache()->set_soft_failures(true);
707 // Read from the network, and fail to write to the cache.
708 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
710 EXPECT_EQ(1, cache.network_layer()->transaction_count());
711 EXPECT_EQ(0, cache.disk_cache()->open_count());
712 EXPECT_EQ(1, cache.disk_cache()->create_count());
714 // This one should see an empty cache again.
715 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
717 EXPECT_EQ(2, cache.network_layer()->transaction_count());
718 EXPECT_EQ(0, cache.disk_cache()->open_count());
719 EXPECT_EQ(2, cache.disk_cache()->create_count());
722 // Tests that disk failures after the transaction has started don't cause the
723 // request to fail.
724 TEST(HttpCache, SimpleGETWithDiskFailures2) {
725 MockHttpCache cache;
727 MockHttpRequest request(kSimpleGET_Transaction);
729 scoped_ptr<Context> c(new Context());
730 int rv = cache.CreateTransaction(&c->trans);
731 ASSERT_EQ(OK, rv);
733 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
734 EXPECT_EQ(ERR_IO_PENDING, rv);
735 rv = c->callback.WaitForResult();
737 // Start failing request now.
738 cache.disk_cache()->set_soft_failures(true);
740 // We have to open the entry again to propagate the failure flag.
741 disk_cache::Entry* en;
742 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &en));
743 en->Close();
745 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
746 c.reset();
748 EXPECT_EQ(1, cache.network_layer()->transaction_count());
749 EXPECT_EQ(1, cache.disk_cache()->open_count());
750 EXPECT_EQ(1, cache.disk_cache()->create_count());
752 // This one should see an empty cache again.
753 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
755 EXPECT_EQ(2, cache.network_layer()->transaction_count());
756 EXPECT_EQ(1, cache.disk_cache()->open_count());
757 EXPECT_EQ(2, cache.disk_cache()->create_count());
760 // Tests that we handle failures to read from the cache.
761 TEST(HttpCache, SimpleGETWithDiskFailures3) {
762 MockHttpCache cache;
764 // Read from the network, and write to the cache.
765 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
767 EXPECT_EQ(1, cache.network_layer()->transaction_count());
768 EXPECT_EQ(0, cache.disk_cache()->open_count());
769 EXPECT_EQ(1, cache.disk_cache()->create_count());
771 cache.disk_cache()->set_soft_failures(true);
773 // Now fail to read from the cache.
774 scoped_ptr<Context> c(new Context());
775 int rv = cache.CreateTransaction(&c->trans);
776 ASSERT_EQ(OK, rv);
778 MockHttpRequest request(kSimpleGET_Transaction);
779 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
780 EXPECT_EQ(OK, c->callback.GetResult(rv));
782 // Now verify that the entry was removed from the cache.
783 cache.disk_cache()->set_soft_failures(false);
785 EXPECT_EQ(2, cache.network_layer()->transaction_count());
786 EXPECT_EQ(1, cache.disk_cache()->open_count());
787 EXPECT_EQ(2, cache.disk_cache()->create_count());
789 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
791 EXPECT_EQ(3, cache.network_layer()->transaction_count());
792 EXPECT_EQ(1, cache.disk_cache()->open_count());
793 EXPECT_EQ(3, cache.disk_cache()->create_count());
796 TEST(HttpCache, SimpleGET_LoadOnlyFromCache_Hit) {
797 MockHttpCache cache;
799 BoundTestNetLog log;
800 LoadTimingInfo load_timing_info;
802 // Write to the cache.
803 RunTransactionTestAndGetTiming(cache.http_cache(), kSimpleGET_Transaction,
804 log.bound(), &load_timing_info);
806 // Check that the NetLog was filled as expected.
807 TestNetLogEntry::List entries;
808 log.GetEntries(&entries);
809 FilterLogEntries(&entries);
811 EXPECT_EQ(8u, entries.size());
812 EXPECT_TRUE(
813 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
814 EXPECT_TRUE(
815 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
816 EXPECT_TRUE(
817 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
818 EXPECT_TRUE(
819 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
820 EXPECT_TRUE(
821 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
822 EXPECT_TRUE(
823 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
824 EXPECT_TRUE(
825 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
826 EXPECT_TRUE(
827 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
829 TestLoadTimingNetworkRequest(load_timing_info);
831 // Force this transaction to read from the cache.
832 MockTransaction transaction(kSimpleGET_Transaction);
833 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
835 log.Clear();
837 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
838 &load_timing_info);
840 // Check that the NetLog was filled as expected.
841 log.GetEntries(&entries);
842 FilterLogEntries(&entries);
844 EXPECT_EQ(8u, entries.size());
845 EXPECT_TRUE(
846 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
847 EXPECT_TRUE(
848 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
849 EXPECT_TRUE(
850 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
851 EXPECT_TRUE(
852 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY));
853 EXPECT_TRUE(
854 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
855 EXPECT_TRUE(
856 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
857 EXPECT_TRUE(
858 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_READ_INFO));
859 EXPECT_TRUE(
860 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_READ_INFO));
862 EXPECT_EQ(1, cache.network_layer()->transaction_count());
863 EXPECT_EQ(1, cache.disk_cache()->open_count());
864 EXPECT_EQ(1, cache.disk_cache()->create_count());
865 TestLoadTimingCachedResponse(load_timing_info);
868 TEST(HttpCache, SimpleGET_LoadOnlyFromCache_Miss) {
869 MockHttpCache cache;
871 // force this transaction to read from the cache
872 MockTransaction transaction(kSimpleGET_Transaction);
873 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
875 MockHttpRequest request(transaction);
876 TestCompletionCallback callback;
878 scoped_ptr<HttpTransaction> trans;
879 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
881 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
882 if (rv == ERR_IO_PENDING)
883 rv = callback.WaitForResult();
884 ASSERT_EQ(ERR_CACHE_MISS, rv);
886 trans.reset();
888 EXPECT_EQ(0, cache.network_layer()->transaction_count());
889 EXPECT_EQ(0, cache.disk_cache()->open_count());
890 EXPECT_EQ(0, cache.disk_cache()->create_count());
893 TEST(HttpCache, SimpleGET_LoadPreferringCache_Hit) {
894 MockHttpCache cache;
896 // write to the cache
897 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
899 // force this transaction to read from the cache if valid
900 MockTransaction transaction(kSimpleGET_Transaction);
901 transaction.load_flags |= LOAD_PREFERRING_CACHE;
903 RunTransactionTest(cache.http_cache(), transaction);
905 EXPECT_EQ(1, cache.network_layer()->transaction_count());
906 EXPECT_EQ(1, cache.disk_cache()->open_count());
907 EXPECT_EQ(1, cache.disk_cache()->create_count());
910 TEST(HttpCache, SimpleGET_LoadPreferringCache_Miss) {
911 MockHttpCache cache;
913 // force this transaction to read from the cache if valid
914 MockTransaction transaction(kSimpleGET_Transaction);
915 transaction.load_flags |= LOAD_PREFERRING_CACHE;
917 RunTransactionTest(cache.http_cache(), transaction);
919 EXPECT_EQ(1, cache.network_layer()->transaction_count());
920 EXPECT_EQ(0, cache.disk_cache()->open_count());
921 EXPECT_EQ(1, cache.disk_cache()->create_count());
924 // Tests LOAD_PREFERRING_CACHE in the presence of vary headers.
925 TEST(HttpCache, SimpleGET_LoadPreferringCache_VaryMatch) {
926 MockHttpCache cache;
928 // Write to the cache.
929 MockTransaction transaction(kSimpleGET_Transaction);
930 transaction.request_headers = "Foo: bar\r\n";
931 transaction.response_headers = "Cache-Control: max-age=10000\n"
932 "Vary: Foo\n";
933 AddMockTransaction(&transaction);
934 RunTransactionTest(cache.http_cache(), transaction);
936 // Read from the cache.
937 transaction.load_flags |= LOAD_PREFERRING_CACHE;
938 RunTransactionTest(cache.http_cache(), transaction);
940 EXPECT_EQ(1, cache.network_layer()->transaction_count());
941 EXPECT_EQ(1, cache.disk_cache()->open_count());
942 EXPECT_EQ(1, cache.disk_cache()->create_count());
943 RemoveMockTransaction(&transaction);
946 // Tests LOAD_PREFERRING_CACHE in the presence of vary headers.
947 TEST(HttpCache, SimpleGET_LoadPreferringCache_VaryMismatch) {
948 MockHttpCache cache;
950 // Write to the cache.
951 MockTransaction transaction(kSimpleGET_Transaction);
952 transaction.request_headers = "Foo: bar\r\n";
953 transaction.response_headers = "Cache-Control: max-age=10000\n"
954 "Vary: Foo\n";
955 AddMockTransaction(&transaction);
956 RunTransactionTest(cache.http_cache(), transaction);
958 // Attempt to read from the cache... this is a vary mismatch that must reach
959 // the network again.
960 transaction.load_flags |= LOAD_PREFERRING_CACHE;
961 transaction.request_headers = "Foo: none\r\n";
962 BoundTestNetLog log;
963 LoadTimingInfo load_timing_info;
964 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
965 &load_timing_info);
967 EXPECT_EQ(2, cache.network_layer()->transaction_count());
968 EXPECT_EQ(1, cache.disk_cache()->open_count());
969 EXPECT_EQ(1, cache.disk_cache()->create_count());
970 TestLoadTimingNetworkRequest(load_timing_info);
971 RemoveMockTransaction(&transaction);
974 // Tests that was_cached was set properly on a failure, even if the cached
975 // response wasn't returned.
976 TEST(HttpCache, SimpleGET_CacheSignal_Failure) {
977 MockHttpCache cache;
979 // Prime cache.
980 MockTransaction transaction(kSimpleGET_Transaction);
981 transaction.response_headers = "Cache-Control: no-cache\n";
983 AddMockTransaction(&transaction);
984 RunTransactionTest(cache.http_cache(), transaction);
985 EXPECT_EQ(1, cache.network_layer()->transaction_count());
986 EXPECT_EQ(1, cache.disk_cache()->create_count());
987 RemoveMockTransaction(&transaction);
989 // Network failure with error; should fail but have was_cached set.
990 transaction.return_code = ERR_FAILED;
991 AddMockTransaction(&transaction);
993 MockHttpRequest request(transaction);
994 TestCompletionCallback callback;
995 scoped_ptr<HttpTransaction> trans;
996 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
997 EXPECT_EQ(OK, rv);
998 ASSERT_TRUE(trans.get());
999 rv = trans->Start(&request, callback.callback(), BoundNetLog());
1000 EXPECT_EQ(ERR_FAILED, callback.GetResult(rv));
1002 const HttpResponseInfo* response_info = trans->GetResponseInfo();
1003 ASSERT_TRUE(response_info);
1004 EXPECT_TRUE(response_info->was_cached);
1005 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1007 RemoveMockTransaction(&transaction);
1010 // Confirm if we have an empty cache, a read is marked as network verified.
1011 TEST(HttpCache, SimpleGET_NetworkAccessed_Network) {
1012 MockHttpCache cache;
1014 // write to the cache
1015 HttpResponseInfo response_info;
1016 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
1017 &response_info);
1019 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1020 EXPECT_EQ(0, cache.disk_cache()->open_count());
1021 EXPECT_EQ(1, cache.disk_cache()->create_count());
1022 EXPECT_TRUE(response_info.network_accessed);
1025 // Confirm if we have a fresh entry in cache, it isn't marked as
1026 // network verified.
1027 TEST(HttpCache, SimpleGET_NetworkAccessed_Cache) {
1028 MockHttpCache cache;
1030 // Prime cache.
1031 MockTransaction transaction(kSimpleGET_Transaction);
1033 RunTransactionTest(cache.http_cache(), transaction);
1034 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1035 EXPECT_EQ(1, cache.disk_cache()->create_count());
1037 // Re-run transaction; make sure we don't mark the network as accessed.
1038 HttpResponseInfo response_info;
1039 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
1040 &response_info);
1042 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1043 EXPECT_FALSE(response_info.server_data_unavailable);
1044 EXPECT_FALSE(response_info.network_accessed);
1047 TEST(HttpCache, SimpleGET_LoadBypassCache) {
1048 MockHttpCache cache;
1050 // Write to the cache.
1051 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1053 // Force this transaction to write to the cache again.
1054 MockTransaction transaction(kSimpleGET_Transaction);
1055 transaction.load_flags |= LOAD_BYPASS_CACHE;
1057 BoundTestNetLog log;
1058 LoadTimingInfo load_timing_info;
1060 // Write to the cache.
1061 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
1062 &load_timing_info);
1064 // Check that the NetLog was filled as expected.
1065 TestNetLogEntry::List entries;
1066 log.GetEntries(&entries);
1067 FilterLogEntries(&entries);
1069 EXPECT_EQ(8u, entries.size());
1070 EXPECT_TRUE(
1071 LogContainsBeginEvent(entries, 0, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
1072 EXPECT_TRUE(
1073 LogContainsEndEvent(entries, 1, NetLog::TYPE_HTTP_CACHE_GET_BACKEND));
1074 EXPECT_TRUE(
1075 LogContainsBeginEvent(entries, 2, NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY));
1076 EXPECT_TRUE(
1077 LogContainsEndEvent(entries, 3, NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY));
1078 EXPECT_TRUE(
1079 LogContainsBeginEvent(entries, 4, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
1080 EXPECT_TRUE(
1081 LogContainsEndEvent(entries, 5, NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY));
1082 EXPECT_TRUE(
1083 LogContainsBeginEvent(entries, 6, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
1084 EXPECT_TRUE(
1085 LogContainsEndEvent(entries, 7, NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY));
1087 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1088 EXPECT_EQ(0, cache.disk_cache()->open_count());
1089 EXPECT_EQ(2, cache.disk_cache()->create_count());
1090 TestLoadTimingNetworkRequest(load_timing_info);
1093 TEST(HttpCache, SimpleGET_LoadBypassCache_Implicit) {
1094 MockHttpCache cache;
1096 // write to the cache
1097 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1099 // force this transaction to write to the cache again
1100 MockTransaction transaction(kSimpleGET_Transaction);
1101 transaction.request_headers = "pragma: no-cache\r\n";
1103 RunTransactionTest(cache.http_cache(), transaction);
1105 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1106 EXPECT_EQ(0, cache.disk_cache()->open_count());
1107 EXPECT_EQ(2, cache.disk_cache()->create_count());
1110 TEST(HttpCache, SimpleGET_LoadBypassCache_Implicit2) {
1111 MockHttpCache cache;
1113 // write to the cache
1114 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1116 // force this transaction to write to the cache again
1117 MockTransaction transaction(kSimpleGET_Transaction);
1118 transaction.request_headers = "cache-control: no-cache\r\n";
1120 RunTransactionTest(cache.http_cache(), transaction);
1122 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1123 EXPECT_EQ(0, cache.disk_cache()->open_count());
1124 EXPECT_EQ(2, cache.disk_cache()->create_count());
1127 TEST(HttpCache, SimpleGET_LoadValidateCache) {
1128 MockHttpCache cache;
1130 // Write to the cache.
1131 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1133 // Read from the cache.
1134 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1136 // Force this transaction to validate the cache.
1137 MockTransaction transaction(kSimpleGET_Transaction);
1138 transaction.load_flags |= LOAD_VALIDATE_CACHE;
1140 HttpResponseInfo response_info;
1141 BoundTestNetLog log;
1142 LoadTimingInfo load_timing_info;
1143 RunTransactionTestWithResponseInfoAndGetTiming(
1144 cache.http_cache(), transaction, &response_info, log.bound(),
1145 &load_timing_info);
1147 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1148 EXPECT_EQ(1, cache.disk_cache()->open_count());
1149 EXPECT_EQ(1, cache.disk_cache()->create_count());
1150 EXPECT_TRUE(response_info.network_accessed);
1151 TestLoadTimingNetworkRequest(load_timing_info);
1154 TEST(HttpCache, SimpleGET_LoadValidateCache_Implicit) {
1155 MockHttpCache cache;
1157 // write to the cache
1158 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1160 // read from the cache
1161 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1163 // force this transaction to validate the cache
1164 MockTransaction transaction(kSimpleGET_Transaction);
1165 transaction.request_headers = "cache-control: max-age=0\r\n";
1167 RunTransactionTest(cache.http_cache(), transaction);
1169 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1170 EXPECT_EQ(1, cache.disk_cache()->open_count());
1171 EXPECT_EQ(1, cache.disk_cache()->create_count());
1174 static void PreserveRequestHeaders_Handler(const HttpRequestInfo* request,
1175 std::string* response_status,
1176 std::string* response_headers,
1177 std::string* response_data) {
1178 EXPECT_TRUE(request->extra_headers.HasHeader(kExtraHeaderKey));
1181 // Tests that we don't remove extra headers for simple requests.
1182 TEST(HttpCache, SimpleGET_PreserveRequestHeaders) {
1183 MockHttpCache cache;
1185 MockTransaction transaction(kSimpleGET_Transaction);
1186 transaction.handler = PreserveRequestHeaders_Handler;
1187 transaction.request_headers = EXTRA_HEADER;
1188 transaction.response_headers = "Cache-Control: max-age=0\n";
1189 AddMockTransaction(&transaction);
1191 // Write, then revalidate the entry.
1192 RunTransactionTest(cache.http_cache(), transaction);
1193 RunTransactionTest(cache.http_cache(), transaction);
1195 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1196 EXPECT_EQ(1, cache.disk_cache()->open_count());
1197 EXPECT_EQ(1, cache.disk_cache()->create_count());
1198 RemoveMockTransaction(&transaction);
1201 // Tests that we don't remove extra headers for conditionalized requests.
1202 TEST(HttpCache, ConditionalizedGET_PreserveRequestHeaders) {
1203 MockHttpCache cache;
1205 // Write to the cache.
1206 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
1208 MockTransaction transaction(kETagGET_Transaction);
1209 transaction.handler = PreserveRequestHeaders_Handler;
1210 transaction.request_headers = "If-None-Match: \"foopy\"\r\n"
1211 EXTRA_HEADER;
1212 AddMockTransaction(&transaction);
1214 RunTransactionTest(cache.http_cache(), transaction);
1216 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1217 EXPECT_EQ(1, cache.disk_cache()->open_count());
1218 EXPECT_EQ(1, cache.disk_cache()->create_count());
1219 RemoveMockTransaction(&transaction);
1222 TEST(HttpCache, SimpleGET_ManyReaders) {
1223 MockHttpCache cache;
1225 MockHttpRequest request(kSimpleGET_Transaction);
1227 std::vector<Context*> context_list;
1228 const int kNumTransactions = 5;
1230 for (int i = 0; i < kNumTransactions; ++i) {
1231 context_list.push_back(new Context());
1232 Context* c = context_list[i];
1234 c->result = cache.CreateTransaction(&c->trans);
1235 ASSERT_EQ(OK, c->result);
1236 EXPECT_EQ(LOAD_STATE_IDLE, c->trans->GetLoadState());
1238 c->result =
1239 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1242 // All requests are waiting for the active entry.
1243 for (int i = 0; i < kNumTransactions; ++i) {
1244 Context* c = context_list[i];
1245 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, c->trans->GetLoadState());
1248 // Allow all requests to move from the Create queue to the active entry.
1249 base::MessageLoop::current()->RunUntilIdle();
1251 // The first request should be a writer at this point, and the subsequent
1252 // requests should be pending.
1254 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1255 EXPECT_EQ(0, cache.disk_cache()->open_count());
1256 EXPECT_EQ(1, cache.disk_cache()->create_count());
1258 // All requests depend on the writer, and the writer is between Start and
1259 // Read, i.e. idle.
1260 for (int i = 0; i < kNumTransactions; ++i) {
1261 Context* c = context_list[i];
1262 EXPECT_EQ(LOAD_STATE_IDLE, c->trans->GetLoadState());
1265 for (int i = 0; i < kNumTransactions; ++i) {
1266 Context* c = context_list[i];
1267 if (c->result == ERR_IO_PENDING)
1268 c->result = c->callback.WaitForResult();
1269 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1272 // We should not have had to re-open the disk entry
1274 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1275 EXPECT_EQ(0, cache.disk_cache()->open_count());
1276 EXPECT_EQ(1, cache.disk_cache()->create_count());
1278 for (int i = 0; i < kNumTransactions; ++i) {
1279 Context* c = context_list[i];
1280 delete c;
1284 // This is a test for http://code.google.com/p/chromium/issues/detail?id=4769.
1285 // If cancelling a request is racing with another request for the same resource
1286 // finishing, we have to make sure that we remove both transactions from the
1287 // entry.
1288 TEST(HttpCache, SimpleGET_RacingReaders) {
1289 MockHttpCache cache;
1291 MockHttpRequest request(kSimpleGET_Transaction);
1292 MockHttpRequest reader_request(kSimpleGET_Transaction);
1293 reader_request.load_flags = LOAD_ONLY_FROM_CACHE;
1295 std::vector<Context*> context_list;
1296 const int kNumTransactions = 5;
1298 for (int i = 0; i < kNumTransactions; ++i) {
1299 context_list.push_back(new Context());
1300 Context* c = context_list[i];
1302 c->result = cache.CreateTransaction(&c->trans);
1303 ASSERT_EQ(OK, c->result);
1305 MockHttpRequest* this_request = &request;
1306 if (i == 1 || i == 2)
1307 this_request = &reader_request;
1309 c->result =
1310 c->trans->Start(this_request, c->callback.callback(), BoundNetLog());
1313 // Allow all requests to move from the Create queue to the active entry.
1314 base::MessageLoop::current()->RunUntilIdle();
1316 // The first request should be a writer at this point, and the subsequent
1317 // requests should be pending.
1319 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1320 EXPECT_EQ(0, cache.disk_cache()->open_count());
1321 EXPECT_EQ(1, cache.disk_cache()->create_count());
1323 Context* c = context_list[0];
1324 ASSERT_EQ(ERR_IO_PENDING, c->result);
1325 c->result = c->callback.WaitForResult();
1326 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1328 // Now we have 2 active readers and two queued transactions.
1330 EXPECT_EQ(LOAD_STATE_IDLE, context_list[2]->trans->GetLoadState());
1331 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE,
1332 context_list[3]->trans->GetLoadState());
1334 c = context_list[1];
1335 ASSERT_EQ(ERR_IO_PENDING, c->result);
1336 c->result = c->callback.WaitForResult();
1337 if (c->result == OK)
1338 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1340 // At this point we have one reader, two pending transactions and a task on
1341 // the queue to move to the next transaction. Now we cancel the request that
1342 // is the current reader, and expect the queued task to be able to start the
1343 // next request.
1345 c = context_list[2];
1346 c->trans.reset();
1348 for (int i = 3; i < kNumTransactions; ++i) {
1349 Context* c = context_list[i];
1350 if (c->result == ERR_IO_PENDING)
1351 c->result = c->callback.WaitForResult();
1352 if (c->result == OK)
1353 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1356 // We should not have had to re-open the disk entry.
1358 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1359 EXPECT_EQ(0, cache.disk_cache()->open_count());
1360 EXPECT_EQ(1, cache.disk_cache()->create_count());
1362 for (int i = 0; i < kNumTransactions; ++i) {
1363 Context* c = context_list[i];
1364 delete c;
1368 // Tests that we can doom an entry with pending transactions and delete one of
1369 // the pending transactions before the first one completes.
1370 // See http://code.google.com/p/chromium/issues/detail?id=25588
1371 TEST(HttpCache, SimpleGET_DoomWithPending) {
1372 // We need simultaneous doomed / not_doomed entries so let's use a real cache.
1373 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(1024 * 1024));
1375 MockHttpRequest request(kSimpleGET_Transaction);
1376 MockHttpRequest writer_request(kSimpleGET_Transaction);
1377 writer_request.load_flags = LOAD_BYPASS_CACHE;
1379 ScopedVector<Context> context_list;
1380 const int kNumTransactions = 4;
1382 for (int i = 0; i < kNumTransactions; ++i) {
1383 context_list.push_back(new Context());
1384 Context* c = context_list[i];
1386 c->result = cache.CreateTransaction(&c->trans);
1387 ASSERT_EQ(OK, c->result);
1389 MockHttpRequest* this_request = &request;
1390 if (i == 3)
1391 this_request = &writer_request;
1393 c->result =
1394 c->trans->Start(this_request, c->callback.callback(), BoundNetLog());
1397 // The first request should be a writer at this point, and the two subsequent
1398 // requests should be pending. The last request doomed the first entry.
1400 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1402 // Cancel the first queued transaction.
1403 delete context_list[1];
1404 context_list.get()[1] = NULL;
1406 for (int i = 0; i < kNumTransactions; ++i) {
1407 if (i == 1)
1408 continue;
1409 Context* c = context_list[i];
1410 ASSERT_EQ(ERR_IO_PENDING, c->result);
1411 c->result = c->callback.WaitForResult();
1412 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1416 // This is a test for http://code.google.com/p/chromium/issues/detail?id=4731.
1417 // We may attempt to delete an entry synchronously with the act of adding a new
1418 // transaction to said entry.
1419 TEST(HttpCache, FastNoStoreGET_DoneWithPending) {
1420 MockHttpCache cache;
1422 // The headers will be served right from the call to Start() the request.
1423 MockHttpRequest request(kFastNoStoreGET_Transaction);
1424 FastTransactionServer request_handler;
1425 AddMockTransaction(&kFastNoStoreGET_Transaction);
1427 std::vector<Context*> context_list;
1428 const int kNumTransactions = 3;
1430 for (int i = 0; i < kNumTransactions; ++i) {
1431 context_list.push_back(new Context());
1432 Context* c = context_list[i];
1434 c->result = cache.CreateTransaction(&c->trans);
1435 ASSERT_EQ(OK, c->result);
1437 c->result =
1438 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1441 // Allow all requests to move from the Create queue to the active entry.
1442 base::MessageLoop::current()->RunUntilIdle();
1444 // The first request should be a writer at this point, and the subsequent
1445 // requests should be pending.
1447 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1448 EXPECT_EQ(0, cache.disk_cache()->open_count());
1449 EXPECT_EQ(1, cache.disk_cache()->create_count());
1451 // Now, make sure that the second request asks for the entry not to be stored.
1452 request_handler.set_no_store(true);
1454 for (int i = 0; i < kNumTransactions; ++i) {
1455 Context* c = context_list[i];
1456 if (c->result == ERR_IO_PENDING)
1457 c->result = c->callback.WaitForResult();
1458 ReadAndVerifyTransaction(c->trans.get(), kFastNoStoreGET_Transaction);
1459 delete c;
1462 EXPECT_EQ(3, cache.network_layer()->transaction_count());
1463 EXPECT_EQ(0, cache.disk_cache()->open_count());
1464 EXPECT_EQ(2, cache.disk_cache()->create_count());
1466 RemoveMockTransaction(&kFastNoStoreGET_Transaction);
1469 TEST(HttpCache, SimpleGET_ManyWriters_CancelFirst) {
1470 MockHttpCache cache;
1472 MockHttpRequest request(kSimpleGET_Transaction);
1474 std::vector<Context*> context_list;
1475 const int kNumTransactions = 2;
1477 for (int i = 0; i < kNumTransactions; ++i) {
1478 context_list.push_back(new Context());
1479 Context* c = context_list[i];
1481 c->result = cache.CreateTransaction(&c->trans);
1482 ASSERT_EQ(OK, c->result);
1484 c->result =
1485 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1488 // Allow all requests to move from the Create queue to the active entry.
1489 base::MessageLoop::current()->RunUntilIdle();
1491 // The first request should be a writer at this point, and the subsequent
1492 // requests should be pending.
1494 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1495 EXPECT_EQ(0, cache.disk_cache()->open_count());
1496 EXPECT_EQ(1, cache.disk_cache()->create_count());
1498 for (int i = 0; i < kNumTransactions; ++i) {
1499 Context* c = context_list[i];
1500 if (c->result == ERR_IO_PENDING)
1501 c->result = c->callback.WaitForResult();
1502 // Destroy only the first transaction.
1503 if (i == 0) {
1504 delete c;
1505 context_list[i] = NULL;
1509 // Complete the rest of the transactions.
1510 for (int i = 1; i < kNumTransactions; ++i) {
1511 Context* c = context_list[i];
1512 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1515 // We should have had to re-open the disk entry.
1517 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1518 EXPECT_EQ(0, cache.disk_cache()->open_count());
1519 EXPECT_EQ(2, cache.disk_cache()->create_count());
1521 for (int i = 1; i < kNumTransactions; ++i) {
1522 Context* c = context_list[i];
1523 delete c;
1527 // Tests that we can cancel requests that are queued waiting to open the disk
1528 // cache entry.
1529 TEST(HttpCache, SimpleGET_ManyWriters_CancelCreate) {
1530 MockHttpCache cache;
1532 MockHttpRequest request(kSimpleGET_Transaction);
1534 std::vector<Context*> context_list;
1535 const int kNumTransactions = 5;
1537 for (int i = 0; i < kNumTransactions; i++) {
1538 context_list.push_back(new Context());
1539 Context* c = context_list[i];
1541 c->result = cache.CreateTransaction(&c->trans);
1542 ASSERT_EQ(OK, c->result);
1544 c->result =
1545 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1548 // The first request should be creating the disk cache entry and the others
1549 // should be pending.
1551 EXPECT_EQ(0, cache.network_layer()->transaction_count());
1552 EXPECT_EQ(0, cache.disk_cache()->open_count());
1553 EXPECT_EQ(1, cache.disk_cache()->create_count());
1555 // Cancel a request from the pending queue.
1556 delete context_list[3];
1557 context_list[3] = NULL;
1559 // Cancel the request that is creating the entry. This will force the pending
1560 // operations to restart.
1561 delete context_list[0];
1562 context_list[0] = NULL;
1564 // Complete the rest of the transactions.
1565 for (int i = 1; i < kNumTransactions; i++) {
1566 Context* c = context_list[i];
1567 if (c) {
1568 c->result = c->callback.GetResult(c->result);
1569 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1573 // We should have had to re-create the disk entry.
1575 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1576 EXPECT_EQ(0, cache.disk_cache()->open_count());
1577 EXPECT_EQ(2, cache.disk_cache()->create_count());
1579 for (int i = 1; i < kNumTransactions; ++i) {
1580 delete context_list[i];
1584 // Tests that we can cancel a single request to open a disk cache entry.
1585 TEST(HttpCache, SimpleGET_CancelCreate) {
1586 MockHttpCache cache;
1588 MockHttpRequest request(kSimpleGET_Transaction);
1590 Context* c = new Context();
1592 c->result = cache.CreateTransaction(&c->trans);
1593 ASSERT_EQ(OK, c->result);
1595 c->result = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1596 EXPECT_EQ(ERR_IO_PENDING, c->result);
1598 // Release the reference that the mock disk cache keeps for this entry, so
1599 // that we test that the http cache handles the cancellation correctly.
1600 cache.disk_cache()->ReleaseAll();
1601 delete c;
1603 base::MessageLoop::current()->RunUntilIdle();
1604 EXPECT_EQ(1, cache.disk_cache()->create_count());
1607 // Tests that we delete/create entries even if multiple requests are queued.
1608 TEST(HttpCache, SimpleGET_ManyWriters_BypassCache) {
1609 MockHttpCache cache;
1611 MockHttpRequest request(kSimpleGET_Transaction);
1612 request.load_flags = LOAD_BYPASS_CACHE;
1614 std::vector<Context*> context_list;
1615 const int kNumTransactions = 5;
1617 for (int i = 0; i < kNumTransactions; i++) {
1618 context_list.push_back(new Context());
1619 Context* c = context_list[i];
1621 c->result = cache.CreateTransaction(&c->trans);
1622 ASSERT_EQ(OK, c->result);
1624 c->result =
1625 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1628 // The first request should be deleting the disk cache entry and the others
1629 // should be pending.
1631 EXPECT_EQ(0, cache.network_layer()->transaction_count());
1632 EXPECT_EQ(0, cache.disk_cache()->open_count());
1633 EXPECT_EQ(0, cache.disk_cache()->create_count());
1635 // Complete the transactions.
1636 for (int i = 0; i < kNumTransactions; i++) {
1637 Context* c = context_list[i];
1638 c->result = c->callback.GetResult(c->result);
1639 ReadAndVerifyTransaction(c->trans.get(), kSimpleGET_Transaction);
1642 // We should have had to re-create the disk entry multiple times.
1644 EXPECT_EQ(5, cache.network_layer()->transaction_count());
1645 EXPECT_EQ(0, cache.disk_cache()->open_count());
1646 EXPECT_EQ(5, cache.disk_cache()->create_count());
1648 for (int i = 0; i < kNumTransactions; ++i) {
1649 delete context_list[i];
1653 // Tests that a (simulated) timeout allows transactions waiting on the cache
1654 // lock to continue.
1655 TEST(HttpCache, SimpleGET_WriterTimeout) {
1656 MockHttpCache cache;
1657 cache.BypassCacheLock();
1659 MockHttpRequest request(kSimpleGET_Transaction);
1660 Context c1, c2;
1661 ASSERT_EQ(OK, cache.CreateTransaction(&c1.trans));
1662 ASSERT_EQ(ERR_IO_PENDING,
1663 c1.trans->Start(&request, c1.callback.callback(), BoundNetLog()));
1664 ASSERT_EQ(OK, cache.CreateTransaction(&c2.trans));
1665 ASSERT_EQ(ERR_IO_PENDING,
1666 c2.trans->Start(&request, c2.callback.callback(), BoundNetLog()));
1668 // The second request is queued after the first one.
1670 c2.callback.WaitForResult();
1671 ReadAndVerifyTransaction(c2.trans.get(), kSimpleGET_Transaction);
1673 // Complete the first transaction.
1674 c1.callback.WaitForResult();
1675 ReadAndVerifyTransaction(c1.trans.get(), kSimpleGET_Transaction);
1678 TEST(HttpCache, SimpleGET_AbandonedCacheRead) {
1679 MockHttpCache cache;
1681 // write to the cache
1682 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
1684 MockHttpRequest request(kSimpleGET_Transaction);
1685 TestCompletionCallback callback;
1687 scoped_ptr<HttpTransaction> trans;
1688 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
1689 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
1690 if (rv == ERR_IO_PENDING)
1691 rv = callback.WaitForResult();
1692 ASSERT_EQ(OK, rv);
1694 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
1695 rv = trans->Read(buf.get(), 256, callback.callback());
1696 EXPECT_EQ(ERR_IO_PENDING, rv);
1698 // Test that destroying the transaction while it is reading from the cache
1699 // works properly.
1700 trans.reset();
1702 // Make sure we pump any pending events, which should include a call to
1703 // HttpCache::Transaction::OnCacheReadCompleted.
1704 base::MessageLoop::current()->RunUntilIdle();
1707 // Tests that we can delete the HttpCache and deal with queued transactions
1708 // ("waiting for the backend" as opposed to Active or Doomed entries).
1709 TEST(HttpCache, SimpleGET_ManyWriters_DeleteCache) {
1710 scoped_ptr<MockHttpCache> cache(new MockHttpCache(
1711 new MockBackendNoCbFactory()));
1713 MockHttpRequest request(kSimpleGET_Transaction);
1715 std::vector<Context*> context_list;
1716 const int kNumTransactions = 5;
1718 for (int i = 0; i < kNumTransactions; i++) {
1719 context_list.push_back(new Context());
1720 Context* c = context_list[i];
1722 c->result = cache->CreateTransaction(&c->trans);
1723 ASSERT_EQ(OK, c->result);
1725 c->result =
1726 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1729 // The first request should be creating the disk cache entry and the others
1730 // should be pending.
1732 EXPECT_EQ(0, cache->network_layer()->transaction_count());
1733 EXPECT_EQ(0, cache->disk_cache()->open_count());
1734 EXPECT_EQ(0, cache->disk_cache()->create_count());
1736 cache.reset();
1738 // There is not much to do with the transactions at this point... they are
1739 // waiting for a callback that will not fire.
1740 for (int i = 0; i < kNumTransactions; ++i) {
1741 delete context_list[i];
1745 // Tests that we queue requests when initializing the backend.
1746 TEST(HttpCache, SimpleGET_WaitForBackend) {
1747 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1748 MockHttpCache cache(factory);
1750 MockHttpRequest request0(kSimpleGET_Transaction);
1751 MockHttpRequest request1(kTypicalGET_Transaction);
1752 MockHttpRequest request2(kETagGET_Transaction);
1754 std::vector<Context*> context_list;
1755 const int kNumTransactions = 3;
1757 for (int i = 0; i < kNumTransactions; i++) {
1758 context_list.push_back(new Context());
1759 Context* c = context_list[i];
1761 c->result = cache.CreateTransaction(&c->trans);
1762 ASSERT_EQ(OK, c->result);
1765 context_list[0]->result = context_list[0]->trans->Start(
1766 &request0, context_list[0]->callback.callback(), BoundNetLog());
1767 context_list[1]->result = context_list[1]->trans->Start(
1768 &request1, context_list[1]->callback.callback(), BoundNetLog());
1769 context_list[2]->result = context_list[2]->trans->Start(
1770 &request2, context_list[2]->callback.callback(), BoundNetLog());
1772 // Just to make sure that everything is still pending.
1773 base::MessageLoop::current()->RunUntilIdle();
1775 // The first request should be creating the disk cache.
1776 EXPECT_FALSE(context_list[0]->callback.have_result());
1778 factory->FinishCreation();
1780 base::MessageLoop::current()->RunUntilIdle();
1781 EXPECT_EQ(3, cache.network_layer()->transaction_count());
1782 EXPECT_EQ(3, cache.disk_cache()->create_count());
1784 for (int i = 0; i < kNumTransactions; ++i) {
1785 EXPECT_TRUE(context_list[i]->callback.have_result());
1786 delete context_list[i];
1790 // Tests that we can cancel requests that are queued waiting for the backend
1791 // to be initialized.
1792 TEST(HttpCache, SimpleGET_WaitForBackend_CancelCreate) {
1793 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1794 MockHttpCache cache(factory);
1796 MockHttpRequest request0(kSimpleGET_Transaction);
1797 MockHttpRequest request1(kTypicalGET_Transaction);
1798 MockHttpRequest request2(kETagGET_Transaction);
1800 std::vector<Context*> context_list;
1801 const int kNumTransactions = 3;
1803 for (int i = 0; i < kNumTransactions; i++) {
1804 context_list.push_back(new Context());
1805 Context* c = context_list[i];
1807 c->result = cache.CreateTransaction(&c->trans);
1808 ASSERT_EQ(OK, c->result);
1811 context_list[0]->result = context_list[0]->trans->Start(
1812 &request0, context_list[0]->callback.callback(), BoundNetLog());
1813 context_list[1]->result = context_list[1]->trans->Start(
1814 &request1, context_list[1]->callback.callback(), BoundNetLog());
1815 context_list[2]->result = context_list[2]->trans->Start(
1816 &request2, context_list[2]->callback.callback(), BoundNetLog());
1818 // Just to make sure that everything is still pending.
1819 base::MessageLoop::current()->RunUntilIdle();
1821 // The first request should be creating the disk cache.
1822 EXPECT_FALSE(context_list[0]->callback.have_result());
1824 // Cancel a request from the pending queue.
1825 delete context_list[1];
1826 context_list[1] = NULL;
1828 // Cancel the request that is creating the entry.
1829 delete context_list[0];
1830 context_list[0] = NULL;
1832 // Complete the last transaction.
1833 factory->FinishCreation();
1835 context_list[2]->result =
1836 context_list[2]->callback.GetResult(context_list[2]->result);
1837 ReadAndVerifyTransaction(context_list[2]->trans.get(), kETagGET_Transaction);
1839 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1840 EXPECT_EQ(1, cache.disk_cache()->create_count());
1842 delete context_list[2];
1845 // Tests that we can delete the cache while creating the backend.
1846 TEST(HttpCache, DeleteCacheWaitingForBackend) {
1847 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1848 scoped_ptr<MockHttpCache> cache(new MockHttpCache(factory));
1850 MockHttpRequest request(kSimpleGET_Transaction);
1852 scoped_ptr<Context> c(new Context());
1853 c->result = cache->CreateTransaction(&c->trans);
1854 ASSERT_EQ(OK, c->result);
1856 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1858 // Just to make sure that everything is still pending.
1859 base::MessageLoop::current()->RunUntilIdle();
1861 // The request should be creating the disk cache.
1862 EXPECT_FALSE(c->callback.have_result());
1864 // We cannot call FinishCreation because the factory itself will go away with
1865 // the cache, so grab the callback and attempt to use it.
1866 CompletionCallback callback = factory->callback();
1867 scoped_ptr<disk_cache::Backend>* backend = factory->backend();
1869 cache.reset();
1870 base::MessageLoop::current()->RunUntilIdle();
1872 backend->reset();
1873 callback.Run(ERR_ABORTED);
1876 // Tests that we can delete the cache while creating the backend, from within
1877 // one of the callbacks.
1878 TEST(HttpCache, DeleteCacheWaitingForBackend2) {
1879 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
1880 MockHttpCache* cache = new MockHttpCache(factory);
1882 DeleteCacheCompletionCallback cb(cache);
1883 disk_cache::Backend* backend;
1884 int rv = cache->http_cache()->GetBackend(&backend, cb.callback());
1885 EXPECT_EQ(ERR_IO_PENDING, rv);
1887 // Now let's queue a regular transaction
1888 MockHttpRequest request(kSimpleGET_Transaction);
1890 scoped_ptr<Context> c(new Context());
1891 c->result = cache->CreateTransaction(&c->trans);
1892 ASSERT_EQ(OK, c->result);
1894 c->trans->Start(&request, c->callback.callback(), BoundNetLog());
1896 // And another direct backend request.
1897 TestCompletionCallback cb2;
1898 rv = cache->http_cache()->GetBackend(&backend, cb2.callback());
1899 EXPECT_EQ(ERR_IO_PENDING, rv);
1901 // Just to make sure that everything is still pending.
1902 base::MessageLoop::current()->RunUntilIdle();
1904 // The request should be queued.
1905 EXPECT_FALSE(c->callback.have_result());
1907 // Generate the callback.
1908 factory->FinishCreation();
1909 rv = cb.WaitForResult();
1911 // The cache should be gone by now.
1912 base::MessageLoop::current()->RunUntilIdle();
1913 EXPECT_EQ(OK, c->callback.GetResult(c->result));
1914 EXPECT_FALSE(cb2.have_result());
1917 TEST(HttpCache, TypicalGET_ConditionalRequest) {
1918 MockHttpCache cache;
1920 // write to the cache
1921 RunTransactionTest(cache.http_cache(), kTypicalGET_Transaction);
1923 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1924 EXPECT_EQ(0, cache.disk_cache()->open_count());
1925 EXPECT_EQ(1, cache.disk_cache()->create_count());
1927 // Get the same URL again, but this time we expect it to result
1928 // in a conditional request.
1929 BoundTestNetLog log;
1930 LoadTimingInfo load_timing_info;
1931 RunTransactionTestAndGetTiming(cache.http_cache(), kTypicalGET_Transaction,
1932 log.bound(), &load_timing_info);
1934 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1935 EXPECT_EQ(1, cache.disk_cache()->open_count());
1936 EXPECT_EQ(1, cache.disk_cache()->create_count());
1937 TestLoadTimingNetworkRequest(load_timing_info);
1940 static void ETagGet_ConditionalRequest_Handler(const HttpRequestInfo* request,
1941 std::string* response_status,
1942 std::string* response_headers,
1943 std::string* response_data) {
1944 EXPECT_TRUE(
1945 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
1946 response_status->assign("HTTP/1.1 304 Not Modified");
1947 response_headers->assign(kETagGET_Transaction.response_headers);
1948 response_data->clear();
1951 TEST(HttpCache, ETagGET_ConditionalRequest_304) {
1952 MockHttpCache cache;
1954 ScopedMockTransaction transaction(kETagGET_Transaction);
1956 // write to the cache
1957 RunTransactionTest(cache.http_cache(), transaction);
1959 EXPECT_EQ(1, cache.network_layer()->transaction_count());
1960 EXPECT_EQ(0, cache.disk_cache()->open_count());
1961 EXPECT_EQ(1, cache.disk_cache()->create_count());
1963 // Get the same URL again, but this time we expect it to result
1964 // in a conditional request.
1965 transaction.load_flags = LOAD_VALIDATE_CACHE;
1966 transaction.handler = ETagGet_ConditionalRequest_Handler;
1967 BoundTestNetLog log;
1968 LoadTimingInfo load_timing_info;
1969 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
1970 &load_timing_info);
1972 EXPECT_EQ(2, cache.network_layer()->transaction_count());
1973 EXPECT_EQ(1, cache.disk_cache()->open_count());
1974 EXPECT_EQ(1, cache.disk_cache()->create_count());
1975 TestLoadTimingNetworkRequest(load_timing_info);
1978 class RevalidationServer {
1979 public:
1980 RevalidationServer() {
1981 s_etag_used_ = false;
1982 s_last_modified_used_ = false;
1985 bool EtagUsed() { return s_etag_used_; }
1986 bool LastModifiedUsed() { return s_last_modified_used_; }
1988 static void Handler(const HttpRequestInfo* request,
1989 std::string* response_status,
1990 std::string* response_headers,
1991 std::string* response_data);
1993 private:
1994 static bool s_etag_used_;
1995 static bool s_last_modified_used_;
1997 bool RevalidationServer::s_etag_used_ = false;
1998 bool RevalidationServer::s_last_modified_used_ = false;
2000 void RevalidationServer::Handler(const HttpRequestInfo* request,
2001 std::string* response_status,
2002 std::string* response_headers,
2003 std::string* response_data) {
2004 if (request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch))
2005 s_etag_used_ = true;
2007 if (request->extra_headers.HasHeader(HttpRequestHeaders::kIfModifiedSince)) {
2008 s_last_modified_used_ = true;
2011 if (s_etag_used_ || s_last_modified_used_) {
2012 response_status->assign("HTTP/1.1 304 Not Modified");
2013 response_headers->assign(kTypicalGET_Transaction.response_headers);
2014 response_data->clear();
2015 } else {
2016 response_status->assign(kTypicalGET_Transaction.status);
2017 response_headers->assign(kTypicalGET_Transaction.response_headers);
2018 response_data->assign(kTypicalGET_Transaction.data);
2022 // Tests revalidation after a vary match.
2023 TEST(HttpCache, GET_ValidateCache_VaryMatch) {
2024 MockHttpCache cache;
2026 // Write to the cache.
2027 MockTransaction transaction(kTypicalGET_Transaction);
2028 transaction.request_headers = "Foo: bar\r\n";
2029 transaction.response_headers =
2030 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2031 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2032 "Etag: \"foopy\"\n"
2033 "Cache-Control: max-age=0\n"
2034 "Vary: Foo\n";
2035 AddMockTransaction(&transaction);
2036 RunTransactionTest(cache.http_cache(), transaction);
2038 // Read from the cache.
2039 RevalidationServer server;
2040 transaction.handler = server.Handler;
2041 BoundTestNetLog log;
2042 LoadTimingInfo load_timing_info;
2043 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2044 &load_timing_info);
2046 EXPECT_TRUE(server.EtagUsed());
2047 EXPECT_TRUE(server.LastModifiedUsed());
2048 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2049 EXPECT_EQ(1, cache.disk_cache()->open_count());
2050 EXPECT_EQ(1, cache.disk_cache()->create_count());
2051 TestLoadTimingNetworkRequest(load_timing_info);
2052 RemoveMockTransaction(&transaction);
2055 // Tests revalidation after a vary mismatch if etag is present.
2056 TEST(HttpCache, GET_ValidateCache_VaryMismatch) {
2057 MockHttpCache cache;
2059 // Write to the cache.
2060 MockTransaction transaction(kTypicalGET_Transaction);
2061 transaction.request_headers = "Foo: bar\r\n";
2062 transaction.response_headers =
2063 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2064 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2065 "Etag: \"foopy\"\n"
2066 "Cache-Control: max-age=0\n"
2067 "Vary: Foo\n";
2068 AddMockTransaction(&transaction);
2069 RunTransactionTest(cache.http_cache(), transaction);
2071 // Read from the cache and revalidate the entry.
2072 RevalidationServer server;
2073 transaction.handler = server.Handler;
2074 transaction.request_headers = "Foo: none\r\n";
2075 BoundTestNetLog log;
2076 LoadTimingInfo load_timing_info;
2077 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2078 &load_timing_info);
2080 EXPECT_TRUE(server.EtagUsed());
2081 EXPECT_FALSE(server.LastModifiedUsed());
2082 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2083 EXPECT_EQ(1, cache.disk_cache()->open_count());
2084 EXPECT_EQ(1, cache.disk_cache()->create_count());
2085 TestLoadTimingNetworkRequest(load_timing_info);
2086 RemoveMockTransaction(&transaction);
2089 // Tests lack of revalidation after a vary mismatch and no etag.
2090 TEST(HttpCache, GET_DontValidateCache_VaryMismatch) {
2091 MockHttpCache cache;
2093 // Write to the cache.
2094 MockTransaction transaction(kTypicalGET_Transaction);
2095 transaction.request_headers = "Foo: bar\r\n";
2096 transaction.response_headers =
2097 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
2098 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
2099 "Cache-Control: max-age=0\n"
2100 "Vary: Foo\n";
2101 AddMockTransaction(&transaction);
2102 RunTransactionTest(cache.http_cache(), transaction);
2104 // Read from the cache and don't revalidate the entry.
2105 RevalidationServer server;
2106 transaction.handler = server.Handler;
2107 transaction.request_headers = "Foo: none\r\n";
2108 BoundTestNetLog log;
2109 LoadTimingInfo load_timing_info;
2110 RunTransactionTestAndGetTiming(cache.http_cache(), transaction, log.bound(),
2111 &load_timing_info);
2113 EXPECT_FALSE(server.EtagUsed());
2114 EXPECT_FALSE(server.LastModifiedUsed());
2115 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2116 EXPECT_EQ(1, cache.disk_cache()->open_count());
2117 EXPECT_EQ(1, cache.disk_cache()->create_count());
2118 TestLoadTimingNetworkRequest(load_timing_info);
2119 RemoveMockTransaction(&transaction);
2122 // Tests that a new vary header provided when revalidating an entry is saved.
2123 TEST(HttpCache, GET_ValidateCache_VaryMatch_UpdateVary) {
2124 MockHttpCache cache;
2126 // Write to the cache.
2127 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2128 transaction.request_headers = "Foo: bar\r\n Name: bar\r\n";
2129 transaction.response_headers =
2130 "Etag: \"foopy\"\n"
2131 "Cache-Control: max-age=0\n"
2132 "Vary: Foo\n";
2133 RunTransactionTest(cache.http_cache(), transaction);
2135 // Validate the entry and change the vary field in the response.
2136 transaction.request_headers = "Foo: bar\r\n Name: none\r\n";
2137 transaction.status = "HTTP/1.1 304 Not Modified";
2138 transaction.response_headers =
2139 "Etag: \"foopy\"\n"
2140 "Cache-Control: max-age=3600\n"
2141 "Vary: Name\n";
2142 RunTransactionTest(cache.http_cache(), transaction);
2144 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2145 EXPECT_EQ(1, cache.disk_cache()->open_count());
2146 EXPECT_EQ(1, cache.disk_cache()->create_count());
2148 // Make sure that the ActiveEntry is gone.
2149 base::RunLoop().RunUntilIdle();
2151 // Generate a vary mismatch.
2152 transaction.request_headers = "Foo: bar\r\n Name: bar\r\n";
2153 RunTransactionTest(cache.http_cache(), transaction);
2155 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2156 EXPECT_EQ(2, cache.disk_cache()->open_count());
2157 EXPECT_EQ(1, cache.disk_cache()->create_count());
2160 // Tests that new request headers causing a vary mismatch are paired with the
2161 // new response when the server says the old response can be used.
2162 TEST(HttpCache, GET_ValidateCache_VaryMismatch_UpdateRequestHeader) {
2163 MockHttpCache cache;
2165 // Write to the cache.
2166 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2167 transaction.request_headers = "Foo: bar\r\n";
2168 transaction.response_headers =
2169 "Etag: \"foopy\"\n"
2170 "Cache-Control: max-age=3600\n"
2171 "Vary: Foo\n";
2172 RunTransactionTest(cache.http_cache(), transaction);
2174 // Vary-mismatch validation receives 304.
2175 transaction.request_headers = "Foo: none\r\n";
2176 transaction.status = "HTTP/1.1 304 Not Modified";
2177 RunTransactionTest(cache.http_cache(), transaction);
2179 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2180 EXPECT_EQ(1, cache.disk_cache()->open_count());
2181 EXPECT_EQ(1, cache.disk_cache()->create_count());
2183 // Make sure that the ActiveEntry is gone.
2184 base::RunLoop().RunUntilIdle();
2186 // Generate a vary mismatch.
2187 transaction.request_headers = "Foo: bar\r\n";
2188 RunTransactionTest(cache.http_cache(), transaction);
2190 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2191 EXPECT_EQ(2, cache.disk_cache()->open_count());
2192 EXPECT_EQ(1, cache.disk_cache()->create_count());
2195 // Tests that a 304 without vary headers doesn't delete the previously stored
2196 // vary data after a vary match revalidation.
2197 TEST(HttpCache, GET_ValidateCache_VaryMatch_DontDeleteVary) {
2198 MockHttpCache cache;
2200 // Write to the cache.
2201 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2202 transaction.request_headers = "Foo: bar\r\n";
2203 transaction.response_headers =
2204 "Etag: \"foopy\"\n"
2205 "Cache-Control: max-age=0\n"
2206 "Vary: Foo\n";
2207 RunTransactionTest(cache.http_cache(), transaction);
2209 // Validate the entry and remove the vary field in the response.
2210 transaction.status = "HTTP/1.1 304 Not Modified";
2211 transaction.response_headers =
2212 "Etag: \"foopy\"\n"
2213 "Cache-Control: max-age=3600\n";
2214 RunTransactionTest(cache.http_cache(), transaction);
2216 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2217 EXPECT_EQ(1, cache.disk_cache()->open_count());
2218 EXPECT_EQ(1, cache.disk_cache()->create_count());
2220 // Make sure that the ActiveEntry is gone.
2221 base::RunLoop().RunUntilIdle();
2223 // Generate a vary mismatch.
2224 transaction.request_headers = "Foo: none\r\n";
2225 RunTransactionTest(cache.http_cache(), transaction);
2227 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2228 EXPECT_EQ(2, cache.disk_cache()->open_count());
2229 EXPECT_EQ(1, cache.disk_cache()->create_count());
2232 // Tests that a 304 without vary headers doesn't delete the previously stored
2233 // vary data after a vary mismatch.
2234 TEST(HttpCache, GET_ValidateCache_VaryMismatch_DontDeleteVary) {
2235 MockHttpCache cache;
2237 // Write to the cache.
2238 ScopedMockTransaction transaction(kTypicalGET_Transaction);
2239 transaction.request_headers = "Foo: bar\r\n";
2240 transaction.response_headers =
2241 "Etag: \"foopy\"\n"
2242 "Cache-Control: max-age=3600\n"
2243 "Vary: Foo\n";
2244 RunTransactionTest(cache.http_cache(), transaction);
2246 // Vary-mismatch validation receives 304 and no vary header.
2247 transaction.request_headers = "Foo: none\r\n";
2248 transaction.status = "HTTP/1.1 304 Not Modified";
2249 transaction.response_headers =
2250 "Etag: \"foopy\"\n"
2251 "Cache-Control: max-age=3600\n";
2252 RunTransactionTest(cache.http_cache(), transaction);
2254 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2255 EXPECT_EQ(1, cache.disk_cache()->open_count());
2256 EXPECT_EQ(1, cache.disk_cache()->create_count());
2258 // Make sure that the ActiveEntry is gone.
2259 base::RunLoop().RunUntilIdle();
2261 // Generate a vary mismatch.
2262 transaction.request_headers = "Foo: bar\r\n";
2263 RunTransactionTest(cache.http_cache(), transaction);
2265 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2266 EXPECT_EQ(2, cache.disk_cache()->open_count());
2267 EXPECT_EQ(1, cache.disk_cache()->create_count());
2270 static void ETagGet_UnconditionalRequest_Handler(const HttpRequestInfo* request,
2271 std::string* response_status,
2272 std::string* response_headers,
2273 std::string* response_data) {
2274 EXPECT_FALSE(
2275 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
2278 TEST(HttpCache, ETagGET_Http10) {
2279 MockHttpCache cache;
2281 ScopedMockTransaction transaction(kETagGET_Transaction);
2282 transaction.status = "HTTP/1.0 200 OK";
2284 // Write to the cache.
2285 RunTransactionTest(cache.http_cache(), transaction);
2287 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2288 EXPECT_EQ(0, cache.disk_cache()->open_count());
2289 EXPECT_EQ(1, cache.disk_cache()->create_count());
2291 // Get the same URL again, without generating a conditional request.
2292 transaction.load_flags = LOAD_VALIDATE_CACHE;
2293 transaction.handler = ETagGet_UnconditionalRequest_Handler;
2294 RunTransactionTest(cache.http_cache(), transaction);
2296 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2297 EXPECT_EQ(1, cache.disk_cache()->open_count());
2298 EXPECT_EQ(1, cache.disk_cache()->create_count());
2301 TEST(HttpCache, ETagGET_Http10_Range) {
2302 MockHttpCache cache;
2304 ScopedMockTransaction transaction(kETagGET_Transaction);
2305 transaction.status = "HTTP/1.0 200 OK";
2307 // Write to the cache.
2308 RunTransactionTest(cache.http_cache(), transaction);
2310 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2311 EXPECT_EQ(0, cache.disk_cache()->open_count());
2312 EXPECT_EQ(1, cache.disk_cache()->create_count());
2314 // Get the same URL again, but use a byte range request.
2315 transaction.load_flags = LOAD_VALIDATE_CACHE;
2316 transaction.handler = ETagGet_UnconditionalRequest_Handler;
2317 transaction.request_headers = "Range: bytes = 5-\r\n";
2318 RunTransactionTest(cache.http_cache(), transaction);
2320 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2321 EXPECT_EQ(1, cache.disk_cache()->open_count());
2322 EXPECT_EQ(2, cache.disk_cache()->create_count());
2325 static void ETagGet_ConditionalRequest_NoStore_Handler(
2326 const HttpRequestInfo* request,
2327 std::string* response_status,
2328 std::string* response_headers,
2329 std::string* response_data) {
2330 EXPECT_TRUE(
2331 request->extra_headers.HasHeader(HttpRequestHeaders::kIfNoneMatch));
2332 response_status->assign("HTTP/1.1 304 Not Modified");
2333 response_headers->assign("Cache-Control: no-store\n");
2334 response_data->clear();
2337 TEST(HttpCache, ETagGET_ConditionalRequest_304_NoStore) {
2338 MockHttpCache cache;
2340 ScopedMockTransaction transaction(kETagGET_Transaction);
2342 // Write to the cache.
2343 RunTransactionTest(cache.http_cache(), transaction);
2345 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2346 EXPECT_EQ(0, cache.disk_cache()->open_count());
2347 EXPECT_EQ(1, cache.disk_cache()->create_count());
2349 // Get the same URL again, but this time we expect it to result
2350 // in a conditional request.
2351 transaction.load_flags = LOAD_VALIDATE_CACHE;
2352 transaction.handler = ETagGet_ConditionalRequest_NoStore_Handler;
2353 RunTransactionTest(cache.http_cache(), transaction);
2355 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2356 EXPECT_EQ(1, cache.disk_cache()->open_count());
2357 EXPECT_EQ(1, cache.disk_cache()->create_count());
2359 ScopedMockTransaction transaction2(kETagGET_Transaction);
2361 // Write to the cache again. This should create a new entry.
2362 RunTransactionTest(cache.http_cache(), transaction2);
2364 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2365 EXPECT_EQ(1, cache.disk_cache()->open_count());
2366 EXPECT_EQ(2, cache.disk_cache()->create_count());
2369 // Helper that does 4 requests using HttpCache:
2371 // (1) loads |kUrl| -- expects |net_response_1| to be returned.
2372 // (2) loads |kUrl| from cache only -- expects |net_response_1| to be returned.
2373 // (3) loads |kUrl| using |extra_request_headers| -- expects |net_response_2| to
2374 // be returned.
2375 // (4) loads |kUrl| from cache only -- expects |cached_response_2| to be
2376 // returned.
2377 static void ConditionalizedRequestUpdatesCacheHelper(
2378 const Response& net_response_1,
2379 const Response& net_response_2,
2380 const Response& cached_response_2,
2381 const char* extra_request_headers) {
2382 MockHttpCache cache;
2384 // The URL we will be requesting.
2385 const char kUrl[] = "http://foobar.com/main.css";
2387 // Junk network response.
2388 static const Response kUnexpectedResponse = {
2389 "HTTP/1.1 500 Unexpected",
2390 "Server: unexpected_header",
2391 "unexpected body"
2394 // We will control the network layer's responses for |kUrl| using
2395 // |mock_network_response|.
2396 MockTransaction mock_network_response = { 0 };
2397 mock_network_response.url = kUrl;
2398 AddMockTransaction(&mock_network_response);
2400 // Request |kUrl| for the first time. It should hit the network and
2401 // receive |kNetResponse1|, which it saves into the HTTP cache.
2403 MockTransaction request = { 0 };
2404 request.url = kUrl;
2405 request.method = "GET";
2406 request.request_headers = "";
2408 net_response_1.AssignTo(&mock_network_response); // Network mock.
2409 net_response_1.AssignTo(&request); // Expected result.
2411 std::string response_headers;
2412 RunTransactionTestWithResponse(
2413 cache.http_cache(), request, &response_headers);
2415 EXPECT_EQ(net_response_1.status_and_headers(), response_headers);
2416 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2417 EXPECT_EQ(0, cache.disk_cache()->open_count());
2418 EXPECT_EQ(1, cache.disk_cache()->create_count());
2420 // Request |kUrl| a second time. Now |kNetResponse1| it is in the HTTP
2421 // cache, so we don't hit the network.
2423 request.load_flags = LOAD_ONLY_FROM_CACHE;
2425 kUnexpectedResponse.AssignTo(&mock_network_response); // Network mock.
2426 net_response_1.AssignTo(&request); // Expected result.
2428 RunTransactionTestWithResponse(
2429 cache.http_cache(), request, &response_headers);
2431 EXPECT_EQ(net_response_1.status_and_headers(), response_headers);
2432 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2433 EXPECT_EQ(1, cache.disk_cache()->open_count());
2434 EXPECT_EQ(1, cache.disk_cache()->create_count());
2436 // Request |kUrl| yet again, but this time give the request an
2437 // "If-Modified-Since" header. This will cause the request to re-hit the
2438 // network. However now the network response is going to be
2439 // different -- this simulates a change made to the CSS file.
2441 request.request_headers = extra_request_headers;
2442 request.load_flags = LOAD_NORMAL;
2444 net_response_2.AssignTo(&mock_network_response); // Network mock.
2445 net_response_2.AssignTo(&request); // Expected result.
2447 RunTransactionTestWithResponse(
2448 cache.http_cache(), request, &response_headers);
2450 EXPECT_EQ(net_response_2.status_and_headers(), response_headers);
2451 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2452 EXPECT_EQ(1, cache.disk_cache()->open_count());
2453 EXPECT_EQ(1, cache.disk_cache()->create_count());
2455 // Finally, request |kUrl| again. This request should be serviced from
2456 // the cache. Moreover, the value in the cache should be |kNetResponse2|
2457 // and NOT |kNetResponse1|. The previous step should have replaced the
2458 // value in the cache with the modified response.
2460 request.request_headers = "";
2461 request.load_flags = LOAD_ONLY_FROM_CACHE;
2463 kUnexpectedResponse.AssignTo(&mock_network_response); // Network mock.
2464 cached_response_2.AssignTo(&request); // Expected result.
2466 RunTransactionTestWithResponse(
2467 cache.http_cache(), request, &response_headers);
2469 EXPECT_EQ(cached_response_2.status_and_headers(), response_headers);
2470 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2471 EXPECT_EQ(2, cache.disk_cache()->open_count());
2472 EXPECT_EQ(1, cache.disk_cache()->create_count());
2474 RemoveMockTransaction(&mock_network_response);
2477 // Check that when an "if-modified-since" header is attached
2478 // to the request, the result still updates the cached entry.
2479 TEST(HttpCache, ConditionalizedRequestUpdatesCache1) {
2480 // First network response for |kUrl|.
2481 static const Response kNetResponse1 = {
2482 "HTTP/1.1 200 OK",
2483 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2484 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2485 "body1"
2488 // Second network response for |kUrl|.
2489 static const Response kNetResponse2 = {
2490 "HTTP/1.1 200 OK",
2491 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2492 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2493 "body2"
2496 const char extra_headers[] =
2497 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2499 ConditionalizedRequestUpdatesCacheHelper(
2500 kNetResponse1, kNetResponse2, kNetResponse2, extra_headers);
2503 // Check that when an "if-none-match" header is attached
2504 // to the request, the result updates the cached entry.
2505 TEST(HttpCache, ConditionalizedRequestUpdatesCache2) {
2506 // First network response for |kUrl|.
2507 static const Response kNetResponse1 = {
2508 "HTTP/1.1 200 OK",
2509 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2510 "Etag: \"ETAG1\"\n"
2511 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n", // Should never expire.
2512 "body1"
2515 // Second network response for |kUrl|.
2516 static const Response kNetResponse2 = {
2517 "HTTP/1.1 200 OK",
2518 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2519 "Etag: \"ETAG2\"\n"
2520 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n", // Should never expire.
2521 "body2"
2524 const char extra_headers[] = "If-None-Match: \"ETAG1\"\r\n";
2526 ConditionalizedRequestUpdatesCacheHelper(
2527 kNetResponse1, kNetResponse2, kNetResponse2, extra_headers);
2530 // Check that when an "if-modified-since" header is attached
2531 // to a request, the 304 (not modified result) result updates the cached
2532 // headers, and the 304 response is returned rather than the cached response.
2533 TEST(HttpCache, ConditionalizedRequestUpdatesCache3) {
2534 // First network response for |kUrl|.
2535 static const Response kNetResponse1 = {
2536 "HTTP/1.1 200 OK",
2537 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2538 "Server: server1\n"
2539 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2540 "body1"
2543 // Second network response for |kUrl|.
2544 static const Response kNetResponse2 = {
2545 "HTTP/1.1 304 Not Modified",
2546 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2547 "Server: server2\n"
2548 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2552 static const Response kCachedResponse2 = {
2553 "HTTP/1.1 200 OK",
2554 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2555 "Server: server2\n"
2556 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2557 "body1"
2560 const char extra_headers[] =
2561 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2563 ConditionalizedRequestUpdatesCacheHelper(
2564 kNetResponse1, kNetResponse2, kCachedResponse2, extra_headers);
2567 // Test that when doing an externally conditionalized if-modified-since
2568 // and there is no corresponding cache entry, a new cache entry is NOT
2569 // created (304 response).
2570 TEST(HttpCache, ConditionalizedRequestUpdatesCache4) {
2571 MockHttpCache cache;
2573 const char kUrl[] = "http://foobar.com/main.css";
2575 static const Response kNetResponse = {
2576 "HTTP/1.1 304 Not Modified",
2577 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2578 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2582 const char kExtraRequestHeaders[] =
2583 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2585 // We will control the network layer's responses for |kUrl| using
2586 // |mock_network_response|.
2587 MockTransaction mock_network_response = { 0 };
2588 mock_network_response.url = kUrl;
2589 AddMockTransaction(&mock_network_response);
2591 MockTransaction request = { 0 };
2592 request.url = kUrl;
2593 request.method = "GET";
2594 request.request_headers = kExtraRequestHeaders;
2596 kNetResponse.AssignTo(&mock_network_response); // Network mock.
2597 kNetResponse.AssignTo(&request); // Expected result.
2599 std::string response_headers;
2600 RunTransactionTestWithResponse(
2601 cache.http_cache(), request, &response_headers);
2603 EXPECT_EQ(kNetResponse.status_and_headers(), response_headers);
2604 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2605 EXPECT_EQ(0, cache.disk_cache()->open_count());
2606 EXPECT_EQ(0, cache.disk_cache()->create_count());
2608 RemoveMockTransaction(&mock_network_response);
2611 // Test that when doing an externally conditionalized if-modified-since
2612 // and there is no corresponding cache entry, a new cache entry is NOT
2613 // created (200 response).
2614 TEST(HttpCache, ConditionalizedRequestUpdatesCache5) {
2615 MockHttpCache cache;
2617 const char kUrl[] = "http://foobar.com/main.css";
2619 static const Response kNetResponse = {
2620 "HTTP/1.1 200 OK",
2621 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2622 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2623 "foobar!!!"
2626 const char kExtraRequestHeaders[] =
2627 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n";
2629 // We will control the network layer's responses for |kUrl| using
2630 // |mock_network_response|.
2631 MockTransaction mock_network_response = { 0 };
2632 mock_network_response.url = kUrl;
2633 AddMockTransaction(&mock_network_response);
2635 MockTransaction request = { 0 };
2636 request.url = kUrl;
2637 request.method = "GET";
2638 request.request_headers = kExtraRequestHeaders;
2640 kNetResponse.AssignTo(&mock_network_response); // Network mock.
2641 kNetResponse.AssignTo(&request); // Expected result.
2643 std::string response_headers;
2644 RunTransactionTestWithResponse(
2645 cache.http_cache(), request, &response_headers);
2647 EXPECT_EQ(kNetResponse.status_and_headers(), response_headers);
2648 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2649 EXPECT_EQ(0, cache.disk_cache()->open_count());
2650 EXPECT_EQ(0, cache.disk_cache()->create_count());
2652 RemoveMockTransaction(&mock_network_response);
2655 // Test that when doing an externally conditionalized if-modified-since
2656 // if the date does not match the cache entry's last-modified date,
2657 // then we do NOT use the response (304) to update the cache.
2658 // (the if-modified-since date is 2 days AFTER the cache's modification date).
2659 TEST(HttpCache, ConditionalizedRequestUpdatesCache6) {
2660 static const Response kNetResponse1 = {
2661 "HTTP/1.1 200 OK",
2662 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2663 "Server: server1\n"
2664 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2665 "body1"
2668 // Second network response for |kUrl|.
2669 static const Response kNetResponse2 = {
2670 "HTTP/1.1 304 Not Modified",
2671 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2672 "Server: server2\n"
2673 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2677 // This is two days in the future from the original response's last-modified
2678 // date!
2679 const char kExtraRequestHeaders[] =
2680 "If-Modified-Since: Fri, 08 Feb 2008 22:38:21 GMT\r\n";
2682 ConditionalizedRequestUpdatesCacheHelper(
2683 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2686 // Test that when doing an externally conditionalized if-none-match
2687 // if the etag does not match the cache entry's etag, then we do not use the
2688 // response (304) to update the cache.
2689 TEST(HttpCache, ConditionalizedRequestUpdatesCache7) {
2690 static const Response kNetResponse1 = {
2691 "HTTP/1.1 200 OK",
2692 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2693 "Etag: \"Foo1\"\n"
2694 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2695 "body1"
2698 // Second network response for |kUrl|.
2699 static const Response kNetResponse2 = {
2700 "HTTP/1.1 304 Not Modified",
2701 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2702 "Etag: \"Foo2\"\n"
2703 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2707 // Different etag from original response.
2708 const char kExtraRequestHeaders[] = "If-None-Match: \"Foo2\"\r\n";
2710 ConditionalizedRequestUpdatesCacheHelper(
2711 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2714 // Test that doing an externally conditionalized request with both if-none-match
2715 // and if-modified-since updates the cache.
2716 TEST(HttpCache, ConditionalizedRequestUpdatesCache8) {
2717 static const Response kNetResponse1 = {
2718 "HTTP/1.1 200 OK",
2719 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2720 "Etag: \"Foo1\"\n"
2721 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2722 "body1"
2725 // Second network response for |kUrl|.
2726 static const Response kNetResponse2 = {
2727 "HTTP/1.1 200 OK",
2728 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2729 "Etag: \"Foo2\"\n"
2730 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2731 "body2"
2734 const char kExtraRequestHeaders[] =
2735 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n"
2736 "If-None-Match: \"Foo1\"\r\n";
2738 ConditionalizedRequestUpdatesCacheHelper(
2739 kNetResponse1, kNetResponse2, kNetResponse2, kExtraRequestHeaders);
2742 // Test that doing an externally conditionalized request with both if-none-match
2743 // and if-modified-since does not update the cache with only one match.
2744 TEST(HttpCache, ConditionalizedRequestUpdatesCache9) {
2745 static const Response kNetResponse1 = {
2746 "HTTP/1.1 200 OK",
2747 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2748 "Etag: \"Foo1\"\n"
2749 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2750 "body1"
2753 // Second network response for |kUrl|.
2754 static const Response kNetResponse2 = {
2755 "HTTP/1.1 200 OK",
2756 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2757 "Etag: \"Foo2\"\n"
2758 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2759 "body2"
2762 // The etag doesn't match what we have stored.
2763 const char kExtraRequestHeaders[] =
2764 "If-Modified-Since: Wed, 06 Feb 2008 22:38:21 GMT\r\n"
2765 "If-None-Match: \"Foo2\"\r\n";
2767 ConditionalizedRequestUpdatesCacheHelper(
2768 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2771 // Test that doing an externally conditionalized request with both if-none-match
2772 // and if-modified-since does not update the cache with only one match.
2773 TEST(HttpCache, ConditionalizedRequestUpdatesCache10) {
2774 static const Response kNetResponse1 = {
2775 "HTTP/1.1 200 OK",
2776 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
2777 "Etag: \"Foo1\"\n"
2778 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
2779 "body1"
2782 // Second network response for |kUrl|.
2783 static const Response kNetResponse2 = {
2784 "HTTP/1.1 200 OK",
2785 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
2786 "Etag: \"Foo2\"\n"
2787 "Last-Modified: Fri, 03 Jul 2009 02:14:27 GMT\n",
2788 "body2"
2791 // The modification date doesn't match what we have stored.
2792 const char kExtraRequestHeaders[] =
2793 "If-Modified-Since: Fri, 08 Feb 2008 22:38:21 GMT\r\n"
2794 "If-None-Match: \"Foo1\"\r\n";
2796 ConditionalizedRequestUpdatesCacheHelper(
2797 kNetResponse1, kNetResponse2, kNetResponse1, kExtraRequestHeaders);
2800 TEST(HttpCache, UrlContainingHash) {
2801 MockHttpCache cache;
2803 // Do a typical GET request -- should write an entry into our cache.
2804 MockTransaction trans(kTypicalGET_Transaction);
2805 RunTransactionTest(cache.http_cache(), trans);
2807 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2808 EXPECT_EQ(0, cache.disk_cache()->open_count());
2809 EXPECT_EQ(1, cache.disk_cache()->create_count());
2811 // Request the same URL, but this time with a reference section (hash).
2812 // Since the cache key strips the hash sections, this should be a cache hit.
2813 std::string url_with_hash = std::string(trans.url) + "#multiple#hashes";
2814 trans.url = url_with_hash.c_str();
2815 trans.load_flags = LOAD_ONLY_FROM_CACHE;
2817 RunTransactionTest(cache.http_cache(), trans);
2819 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2820 EXPECT_EQ(1, cache.disk_cache()->open_count());
2821 EXPECT_EQ(1, cache.disk_cache()->create_count());
2824 // Tests that we skip the cache for POST requests that do not have an upload
2825 // identifier.
2826 TEST(HttpCache, SimplePOST_SkipsCache) {
2827 MockHttpCache cache;
2829 RunTransactionTest(cache.http_cache(), kSimplePOST_Transaction);
2831 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2832 EXPECT_EQ(0, cache.disk_cache()->open_count());
2833 EXPECT_EQ(0, cache.disk_cache()->create_count());
2836 // Tests POST handling with a disabled cache (no DCHECK).
2837 TEST(HttpCache, SimplePOST_DisabledCache) {
2838 MockHttpCache cache;
2839 cache.http_cache()->set_mode(HttpCache::Mode::DISABLE);
2841 RunTransactionTest(cache.http_cache(), kSimplePOST_Transaction);
2843 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2844 EXPECT_EQ(0, cache.disk_cache()->open_count());
2845 EXPECT_EQ(0, cache.disk_cache()->create_count());
2848 TEST(HttpCache, SimplePOST_LoadOnlyFromCache_Miss) {
2849 MockHttpCache cache;
2851 MockTransaction transaction(kSimplePOST_Transaction);
2852 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
2854 MockHttpRequest request(transaction);
2855 TestCompletionCallback callback;
2857 scoped_ptr<HttpTransaction> trans;
2858 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
2859 ASSERT_TRUE(trans.get());
2861 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
2862 ASSERT_EQ(ERR_CACHE_MISS, callback.GetResult(rv));
2864 trans.reset();
2866 EXPECT_EQ(0, cache.network_layer()->transaction_count());
2867 EXPECT_EQ(0, cache.disk_cache()->open_count());
2868 EXPECT_EQ(0, cache.disk_cache()->create_count());
2871 TEST(HttpCache, SimplePOST_LoadOnlyFromCache_Hit) {
2872 MockHttpCache cache;
2874 // Test that we hit the cache for POST requests.
2876 MockTransaction transaction(kSimplePOST_Transaction);
2878 const int64 kUploadId = 1; // Just a dummy value.
2880 ScopedVector<UploadElementReader> element_readers;
2881 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2882 ElementsUploadDataStream upload_data_stream(element_readers.Pass(),
2883 kUploadId);
2884 MockHttpRequest request(transaction);
2885 request.upload_data_stream = &upload_data_stream;
2887 // Populate the cache.
2888 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2890 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2891 EXPECT_EQ(0, cache.disk_cache()->open_count());
2892 EXPECT_EQ(1, cache.disk_cache()->create_count());
2894 // Load from cache.
2895 request.load_flags |= LOAD_ONLY_FROM_CACHE;
2896 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2898 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2899 EXPECT_EQ(1, cache.disk_cache()->open_count());
2900 EXPECT_EQ(1, cache.disk_cache()->create_count());
2903 // Test that we don't hit the cache for POST requests if there is a byte range.
2904 TEST(HttpCache, SimplePOST_WithRanges) {
2905 MockHttpCache cache;
2907 MockTransaction transaction(kSimplePOST_Transaction);
2908 transaction.request_headers = "Range: bytes = 0-4\r\n";
2910 const int64 kUploadId = 1; // Just a dummy value.
2912 ScopedVector<UploadElementReader> element_readers;
2913 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2914 ElementsUploadDataStream upload_data_stream(element_readers.Pass(),
2915 kUploadId);
2917 MockHttpRequest request(transaction);
2918 request.upload_data_stream = &upload_data_stream;
2920 // Attempt to populate the cache.
2921 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
2923 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2924 EXPECT_EQ(0, cache.disk_cache()->open_count());
2925 EXPECT_EQ(0, cache.disk_cache()->create_count());
2928 // Tests that a POST is cached separately from a previously cached GET.
2929 TEST(HttpCache, SimplePOST_SeparateCache) {
2930 MockHttpCache cache;
2932 ScopedVector<UploadElementReader> element_readers;
2933 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2934 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
2936 MockTransaction transaction(kSimplePOST_Transaction);
2937 MockHttpRequest req1(transaction);
2938 req1.upload_data_stream = &upload_data_stream;
2940 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2942 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2943 EXPECT_EQ(0, cache.disk_cache()->open_count());
2944 EXPECT_EQ(1, cache.disk_cache()->create_count());
2946 transaction.method = "GET";
2947 MockHttpRequest req2(transaction);
2949 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
2951 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2952 EXPECT_EQ(0, cache.disk_cache()->open_count());
2953 EXPECT_EQ(2, cache.disk_cache()->create_count());
2956 // Tests that a successful POST invalidates a previously cached GET.
2957 TEST(HttpCache, SimplePOST_Invalidate_205) {
2958 MockHttpCache cache;
2960 MockTransaction transaction(kSimpleGET_Transaction);
2961 AddMockTransaction(&transaction);
2962 MockHttpRequest req1(transaction);
2964 // Attempt to populate the cache.
2965 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2967 EXPECT_EQ(1, cache.network_layer()->transaction_count());
2968 EXPECT_EQ(0, cache.disk_cache()->open_count());
2969 EXPECT_EQ(1, cache.disk_cache()->create_count());
2971 ScopedVector<UploadElementReader> element_readers;
2972 element_readers.push_back(new UploadBytesElementReader("hello", 5));
2973 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
2975 transaction.method = "POST";
2976 transaction.status = "HTTP/1.1 205 No Content";
2977 MockHttpRequest req2(transaction);
2978 req2.upload_data_stream = &upload_data_stream;
2980 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
2982 EXPECT_EQ(2, cache.network_layer()->transaction_count());
2983 EXPECT_EQ(0, cache.disk_cache()->open_count());
2984 EXPECT_EQ(2, cache.disk_cache()->create_count());
2986 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
2988 EXPECT_EQ(3, cache.network_layer()->transaction_count());
2989 EXPECT_EQ(0, cache.disk_cache()->open_count());
2990 EXPECT_EQ(3, cache.disk_cache()->create_count());
2991 RemoveMockTransaction(&transaction);
2994 // Tests that a successful POST invalidates a previously cached GET, even when
2995 // there is no upload identifier.
2996 TEST(HttpCache, SimplePOST_NoUploadId_Invalidate_205) {
2997 MockHttpCache cache;
2999 MockTransaction transaction(kSimpleGET_Transaction);
3000 AddMockTransaction(&transaction);
3001 MockHttpRequest req1(transaction);
3003 // Attempt to populate the cache.
3004 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3006 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3007 EXPECT_EQ(0, cache.disk_cache()->open_count());
3008 EXPECT_EQ(1, cache.disk_cache()->create_count());
3010 ScopedVector<UploadElementReader> element_readers;
3011 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3012 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3014 transaction.method = "POST";
3015 transaction.status = "HTTP/1.1 205 No Content";
3016 MockHttpRequest req2(transaction);
3017 req2.upload_data_stream = &upload_data_stream;
3019 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3021 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3022 EXPECT_EQ(0, cache.disk_cache()->open_count());
3023 EXPECT_EQ(1, cache.disk_cache()->create_count());
3025 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3027 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3028 EXPECT_EQ(0, cache.disk_cache()->open_count());
3029 EXPECT_EQ(2, cache.disk_cache()->create_count());
3030 RemoveMockTransaction(&transaction);
3033 // Tests that processing a POST before creating the backend doesn't crash.
3034 TEST(HttpCache, SimplePOST_NoUploadId_NoBackend) {
3035 // This will initialize a cache object with NULL backend.
3036 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
3037 factory->set_fail(true);
3038 factory->FinishCreation();
3039 MockHttpCache cache(factory);
3041 ScopedVector<UploadElementReader> element_readers;
3042 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3043 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3045 MockTransaction transaction(kSimplePOST_Transaction);
3046 AddMockTransaction(&transaction);
3047 MockHttpRequest req(transaction);
3048 req.upload_data_stream = &upload_data_stream;
3050 RunTransactionTestWithRequest(cache.http_cache(), transaction, req, NULL);
3052 RemoveMockTransaction(&transaction);
3055 // Tests that we don't invalidate entries as a result of a failed POST.
3056 TEST(HttpCache, SimplePOST_DontInvalidate_100) {
3057 MockHttpCache cache;
3059 MockTransaction transaction(kSimpleGET_Transaction);
3060 AddMockTransaction(&transaction);
3061 MockHttpRequest req1(transaction);
3063 // Attempt to populate the cache.
3064 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3066 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3067 EXPECT_EQ(0, cache.disk_cache()->open_count());
3068 EXPECT_EQ(1, cache.disk_cache()->create_count());
3070 ScopedVector<UploadElementReader> element_readers;
3071 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3072 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 1);
3074 transaction.method = "POST";
3075 transaction.status = "HTTP/1.1 100 Continue";
3076 MockHttpRequest req2(transaction);
3077 req2.upload_data_stream = &upload_data_stream;
3079 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3081 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3082 EXPECT_EQ(0, cache.disk_cache()->open_count());
3083 EXPECT_EQ(2, cache.disk_cache()->create_count());
3085 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3087 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3088 EXPECT_EQ(1, cache.disk_cache()->open_count());
3089 EXPECT_EQ(2, cache.disk_cache()->create_count());
3090 RemoveMockTransaction(&transaction);
3093 // Tests that a HEAD request is not cached by itself.
3094 TEST(HttpCache, SimpleHEAD_LoadOnlyFromCache_Miss) {
3095 MockHttpCache cache;
3096 MockTransaction transaction(kSimplePOST_Transaction);
3097 AddMockTransaction(&transaction);
3098 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3099 transaction.method = "HEAD";
3101 MockHttpRequest request(transaction);
3102 TestCompletionCallback callback;
3104 scoped_ptr<HttpTransaction> trans;
3105 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
3106 ASSERT_TRUE(trans.get());
3108 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
3109 ASSERT_EQ(ERR_CACHE_MISS, callback.GetResult(rv));
3111 trans.reset();
3113 EXPECT_EQ(0, cache.network_layer()->transaction_count());
3114 EXPECT_EQ(0, cache.disk_cache()->open_count());
3115 EXPECT_EQ(0, cache.disk_cache()->create_count());
3116 RemoveMockTransaction(&transaction);
3119 // Tests that a HEAD request is served from a cached GET.
3120 TEST(HttpCache, SimpleHEAD_LoadOnlyFromCache_Hit) {
3121 MockHttpCache cache;
3122 MockTransaction transaction(kSimpleGET_Transaction);
3123 AddMockTransaction(&transaction);
3125 // Populate the cache.
3126 RunTransactionTest(cache.http_cache(), transaction);
3128 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3129 EXPECT_EQ(0, cache.disk_cache()->open_count());
3130 EXPECT_EQ(1, cache.disk_cache()->create_count());
3132 // Load from cache.
3133 transaction.method = "HEAD";
3134 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3135 transaction.data = "";
3136 RunTransactionTest(cache.http_cache(), transaction);
3138 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3139 EXPECT_EQ(1, cache.disk_cache()->open_count());
3140 EXPECT_EQ(1, cache.disk_cache()->create_count());
3141 RemoveMockTransaction(&transaction);
3144 // Tests that a read-only request served from the cache preserves CL.
3145 TEST(HttpCache, SimpleHEAD_ContentLengthOnHit_Read) {
3146 MockHttpCache cache;
3147 MockTransaction transaction(kSimpleGET_Transaction);
3148 AddMockTransaction(&transaction);
3149 transaction.response_headers = "Content-Length: 42\n";
3151 // Populate the cache.
3152 RunTransactionTest(cache.http_cache(), transaction);
3154 // Load from cache.
3155 transaction.method = "HEAD";
3156 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3157 transaction.data = "";
3158 std::string headers;
3160 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3162 EXPECT_EQ("HTTP/1.1 200 OK\nContent-Length: 42\n", headers);
3163 RemoveMockTransaction(&transaction);
3166 // Tests that a read-write request served from the cache preserves CL.
3167 TEST(HttpCache, ETagHEAD_ContentLengthOnHit_ReadWrite) {
3168 MockHttpCache cache;
3169 MockTransaction transaction(kETagGET_Transaction);
3170 AddMockTransaction(&transaction);
3171 std::string server_headers(kETagGET_Transaction.response_headers);
3172 server_headers.append("Content-Length: 42\n");
3173 transaction.response_headers = server_headers.data();
3175 // Populate the cache.
3176 RunTransactionTest(cache.http_cache(), transaction);
3178 // Load from cache.
3179 transaction.method = "HEAD";
3180 transaction.data = "";
3181 std::string headers;
3183 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3185 EXPECT_NE(std::string::npos, headers.find("Content-Length: 42\n"));
3186 RemoveMockTransaction(&transaction);
3189 // Tests that a HEAD request that includes byte ranges bypasses the cache.
3190 TEST(HttpCache, SimpleHEAD_WithRanges) {
3191 MockHttpCache cache;
3192 MockTransaction transaction(kSimpleGET_Transaction);
3193 AddMockTransaction(&transaction);
3195 // Populate the cache.
3196 RunTransactionTest(cache.http_cache(), transaction);
3198 // Load from cache.
3199 transaction.method = "HEAD";
3200 transaction.request_headers = "Range: bytes = 0-4\r\n";
3201 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3202 transaction.return_code = ERR_CACHE_MISS;
3203 RunTransactionTest(cache.http_cache(), transaction);
3205 EXPECT_EQ(0, cache.disk_cache()->open_count());
3206 EXPECT_EQ(1, cache.disk_cache()->create_count());
3207 RemoveMockTransaction(&transaction);
3210 // Tests that a HEAD request can be served from a partialy cached resource.
3211 TEST(HttpCache, SimpleHEAD_WithCachedRanges) {
3212 MockHttpCache cache;
3213 AddMockTransaction(&kRangeGET_TransactionOK);
3215 // Write to the cache (40-49).
3216 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
3217 RemoveMockTransaction(&kRangeGET_TransactionOK);
3219 MockTransaction transaction(kSimpleGET_Transaction);
3221 transaction.url = kRangeGET_TransactionOK.url;
3222 transaction.method = "HEAD";
3223 transaction.data = "";
3224 AddMockTransaction(&transaction);
3225 std::string headers;
3227 // Load from cache.
3228 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3230 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3231 EXPECT_NE(std::string::npos, headers.find("Content-Length: 80\n"));
3232 EXPECT_EQ(std::string::npos, headers.find("Content-Range"));
3233 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3234 EXPECT_EQ(1, cache.disk_cache()->open_count());
3235 EXPECT_EQ(1, cache.disk_cache()->create_count());
3236 RemoveMockTransaction(&transaction);
3239 // Tests that a HEAD request can be served from a truncated resource.
3240 TEST(HttpCache, SimpleHEAD_WithTruncatedEntry) {
3241 MockHttpCache cache;
3242 AddMockTransaction(&kRangeGET_TransactionOK);
3244 std::string raw_headers("HTTP/1.1 200 OK\n"
3245 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
3246 "ETag: \"foo\"\n"
3247 "Accept-Ranges: bytes\n"
3248 "Content-Length: 80\n");
3249 CreateTruncatedEntry(raw_headers, &cache);
3250 RemoveMockTransaction(&kRangeGET_TransactionOK);
3252 MockTransaction transaction(kSimpleGET_Transaction);
3254 transaction.url = kRangeGET_TransactionOK.url;
3255 transaction.method = "HEAD";
3256 transaction.data = "";
3257 AddMockTransaction(&transaction);
3258 std::string headers;
3260 // Load from cache.
3261 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3263 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3264 EXPECT_NE(std::string::npos, headers.find("Content-Length: 80\n"));
3265 EXPECT_EQ(std::string::npos, headers.find("Content-Range"));
3266 EXPECT_EQ(0, cache.network_layer()->transaction_count());
3267 EXPECT_EQ(1, cache.disk_cache()->open_count());
3268 EXPECT_EQ(1, cache.disk_cache()->create_count());
3269 RemoveMockTransaction(&transaction);
3272 // Tests that a HEAD request updates the cached response.
3273 TEST(HttpCache, TypicalHEAD_UpdatesResponse) {
3274 MockHttpCache cache;
3275 MockTransaction transaction(kTypicalGET_Transaction);
3276 AddMockTransaction(&transaction);
3278 // Populate the cache.
3279 RunTransactionTest(cache.http_cache(), transaction);
3281 // Update the cache.
3282 transaction.method = "HEAD";
3283 transaction.response_headers = "Foo: bar\n";
3284 transaction.data = "";
3285 transaction.status = "HTTP/1.1 304 Not Modified\n";
3286 std::string headers;
3287 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3288 RemoveMockTransaction(&transaction);
3290 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 200 OK\n"));
3291 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3293 MockTransaction transaction2(kTypicalGET_Transaction);
3294 AddMockTransaction(&transaction2);
3296 // Make sure we are done with the previous transaction.
3297 base::MessageLoop::current()->RunUntilIdle();
3299 // Load from the cache.
3300 transaction2.load_flags |= LOAD_ONLY_FROM_CACHE;
3301 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
3303 EXPECT_NE(std::string::npos, headers.find("Foo: bar\n"));
3304 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3305 EXPECT_EQ(2, cache.disk_cache()->open_count());
3306 EXPECT_EQ(1, cache.disk_cache()->create_count());
3307 RemoveMockTransaction(&transaction2);
3310 // Tests that an externally conditionalized HEAD request updates the cache.
3311 TEST(HttpCache, TypicalHEAD_ConditionalizedRequestUpdatesResponse) {
3312 MockHttpCache cache;
3313 MockTransaction transaction(kTypicalGET_Transaction);
3314 AddMockTransaction(&transaction);
3316 // Populate the cache.
3317 RunTransactionTest(cache.http_cache(), transaction);
3319 // Update the cache.
3320 transaction.method = "HEAD";
3321 transaction.request_headers =
3322 "If-Modified-Since: Wed, 28 Nov 2007 00:40:09 GMT\r\n";
3323 transaction.response_headers = "Foo: bar\n";
3324 transaction.data = "";
3325 transaction.status = "HTTP/1.1 304 Not Modified\n";
3326 std::string headers;
3327 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3328 RemoveMockTransaction(&transaction);
3330 EXPECT_NE(std::string::npos, headers.find("HTTP/1.1 304 Not Modified\n"));
3331 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3333 MockTransaction transaction2(kTypicalGET_Transaction);
3334 AddMockTransaction(&transaction2);
3336 // Make sure we are done with the previous transaction.
3337 base::MessageLoop::current()->RunUntilIdle();
3339 // Load from the cache.
3340 transaction2.load_flags |= LOAD_ONLY_FROM_CACHE;
3341 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
3343 EXPECT_NE(std::string::npos, headers.find("Foo: bar\n"));
3344 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3345 EXPECT_EQ(2, cache.disk_cache()->open_count());
3346 EXPECT_EQ(1, cache.disk_cache()->create_count());
3347 RemoveMockTransaction(&transaction2);
3350 // Tests that a HEAD request invalidates an old cached entry.
3351 TEST(HttpCache, SimpleHEAD_InvalidatesEntry) {
3352 MockHttpCache cache;
3353 MockTransaction transaction(kTypicalGET_Transaction);
3354 AddMockTransaction(&transaction);
3356 // Populate the cache.
3357 RunTransactionTest(cache.http_cache(), transaction);
3359 // Update the cache.
3360 transaction.method = "HEAD";
3361 transaction.data = "";
3362 RunTransactionTest(cache.http_cache(), transaction);
3363 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3365 // Load from the cache.
3366 transaction.method = "GET";
3367 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
3368 transaction.return_code = ERR_CACHE_MISS;
3369 RunTransactionTest(cache.http_cache(), transaction);
3371 RemoveMockTransaction(&transaction);
3374 // Tests that we do not cache the response of a PUT.
3375 TEST(HttpCache, SimplePUT_Miss) {
3376 MockHttpCache cache;
3378 MockTransaction transaction(kSimplePOST_Transaction);
3379 transaction.method = "PUT";
3381 ScopedVector<UploadElementReader> element_readers;
3382 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3383 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3385 MockHttpRequest request(transaction);
3386 request.upload_data_stream = &upload_data_stream;
3388 // Attempt to populate the cache.
3389 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
3391 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3392 EXPECT_EQ(0, cache.disk_cache()->open_count());
3393 EXPECT_EQ(0, cache.disk_cache()->create_count());
3396 // Tests that we invalidate entries as a result of a PUT.
3397 TEST(HttpCache, SimplePUT_Invalidate) {
3398 MockHttpCache cache;
3400 MockTransaction transaction(kSimpleGET_Transaction);
3401 MockHttpRequest req1(transaction);
3403 // Attempt to populate the cache.
3404 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3406 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3407 EXPECT_EQ(0, cache.disk_cache()->open_count());
3408 EXPECT_EQ(1, cache.disk_cache()->create_count());
3410 ScopedVector<UploadElementReader> element_readers;
3411 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3412 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3414 transaction.method = "PUT";
3415 MockHttpRequest req2(transaction);
3416 req2.upload_data_stream = &upload_data_stream;
3418 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3420 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3421 EXPECT_EQ(1, cache.disk_cache()->open_count());
3422 EXPECT_EQ(1, cache.disk_cache()->create_count());
3424 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3426 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3427 EXPECT_EQ(1, cache.disk_cache()->open_count());
3428 EXPECT_EQ(2, cache.disk_cache()->create_count());
3431 // Tests that we invalidate entries as a result of a PUT.
3432 TEST(HttpCache, SimplePUT_Invalidate_305) {
3433 MockHttpCache cache;
3435 MockTransaction transaction(kSimpleGET_Transaction);
3436 AddMockTransaction(&transaction);
3437 MockHttpRequest req1(transaction);
3439 // Attempt to populate the cache.
3440 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3442 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3443 EXPECT_EQ(0, cache.disk_cache()->open_count());
3444 EXPECT_EQ(1, cache.disk_cache()->create_count());
3446 ScopedVector<UploadElementReader> element_readers;
3447 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3448 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3450 transaction.method = "PUT";
3451 transaction.status = "HTTP/1.1 305 Use Proxy";
3452 MockHttpRequest req2(transaction);
3453 req2.upload_data_stream = &upload_data_stream;
3455 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3457 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3458 EXPECT_EQ(1, cache.disk_cache()->open_count());
3459 EXPECT_EQ(1, cache.disk_cache()->create_count());
3461 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3463 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3464 EXPECT_EQ(1, cache.disk_cache()->open_count());
3465 EXPECT_EQ(2, cache.disk_cache()->create_count());
3466 RemoveMockTransaction(&transaction);
3469 // Tests that we don't invalidate entries as a result of a failed PUT.
3470 TEST(HttpCache, SimplePUT_DontInvalidate_404) {
3471 MockHttpCache cache;
3473 MockTransaction transaction(kSimpleGET_Transaction);
3474 AddMockTransaction(&transaction);
3475 MockHttpRequest req1(transaction);
3477 // Attempt to populate the cache.
3478 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3480 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3481 EXPECT_EQ(0, cache.disk_cache()->open_count());
3482 EXPECT_EQ(1, cache.disk_cache()->create_count());
3484 ScopedVector<UploadElementReader> element_readers;
3485 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3486 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3488 transaction.method = "PUT";
3489 transaction.status = "HTTP/1.1 404 Not Found";
3490 MockHttpRequest req2(transaction);
3491 req2.upload_data_stream = &upload_data_stream;
3493 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3495 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3496 EXPECT_EQ(1, cache.disk_cache()->open_count());
3497 EXPECT_EQ(1, cache.disk_cache()->create_count());
3499 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3501 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3502 EXPECT_EQ(2, cache.disk_cache()->open_count());
3503 EXPECT_EQ(1, cache.disk_cache()->create_count());
3504 RemoveMockTransaction(&transaction);
3507 // Tests that we do not cache the response of a DELETE.
3508 TEST(HttpCache, SimpleDELETE_Miss) {
3509 MockHttpCache cache;
3511 MockTransaction transaction(kSimplePOST_Transaction);
3512 transaction.method = "DELETE";
3514 ScopedVector<UploadElementReader> element_readers;
3515 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3516 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3518 MockHttpRequest request(transaction);
3519 request.upload_data_stream = &upload_data_stream;
3521 // Attempt to populate the cache.
3522 RunTransactionTestWithRequest(cache.http_cache(), transaction, request, NULL);
3524 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3525 EXPECT_EQ(0, cache.disk_cache()->open_count());
3526 EXPECT_EQ(0, cache.disk_cache()->create_count());
3529 // Tests that we invalidate entries as a result of a DELETE.
3530 TEST(HttpCache, SimpleDELETE_Invalidate) {
3531 MockHttpCache cache;
3533 MockTransaction transaction(kSimpleGET_Transaction);
3534 MockHttpRequest req1(transaction);
3536 // Attempt to populate the cache.
3537 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3539 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3540 EXPECT_EQ(0, cache.disk_cache()->open_count());
3541 EXPECT_EQ(1, cache.disk_cache()->create_count());
3543 ScopedVector<UploadElementReader> element_readers;
3544 element_readers.push_back(new UploadBytesElementReader("hello", 5));
3545 ElementsUploadDataStream upload_data_stream(element_readers.Pass(), 0);
3547 transaction.method = "DELETE";
3548 MockHttpRequest req2(transaction);
3549 req2.upload_data_stream = &upload_data_stream;
3551 RunTransactionTestWithRequest(cache.http_cache(), transaction, req2, NULL);
3553 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3554 EXPECT_EQ(1, cache.disk_cache()->open_count());
3555 EXPECT_EQ(1, cache.disk_cache()->create_count());
3557 RunTransactionTestWithRequest(cache.http_cache(), transaction, req1, NULL);
3559 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3560 EXPECT_EQ(1, cache.disk_cache()->open_count());
3561 EXPECT_EQ(2, cache.disk_cache()->create_count());
3564 // Tests that we invalidate entries as a result of a DELETE.
3565 TEST(HttpCache, SimpleDELETE_Invalidate_301) {
3566 MockHttpCache cache;
3568 MockTransaction transaction(kSimpleGET_Transaction);
3569 AddMockTransaction(&transaction);
3571 // Attempt to populate the cache.
3572 RunTransactionTest(cache.http_cache(), transaction);
3574 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3575 EXPECT_EQ(0, cache.disk_cache()->open_count());
3576 EXPECT_EQ(1, cache.disk_cache()->create_count());
3578 transaction.method = "DELETE";
3579 transaction.status = "HTTP/1.1 301 Moved Permanently ";
3581 RunTransactionTest(cache.http_cache(), transaction);
3583 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3584 EXPECT_EQ(1, cache.disk_cache()->open_count());
3585 EXPECT_EQ(1, cache.disk_cache()->create_count());
3587 transaction.method = "GET";
3588 RunTransactionTest(cache.http_cache(), transaction);
3590 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3591 EXPECT_EQ(1, cache.disk_cache()->open_count());
3592 EXPECT_EQ(2, cache.disk_cache()->create_count());
3593 RemoveMockTransaction(&transaction);
3596 // Tests that we don't invalidate entries as a result of a failed DELETE.
3597 TEST(HttpCache, SimpleDELETE_DontInvalidate_416) {
3598 MockHttpCache cache;
3600 MockTransaction transaction(kSimpleGET_Transaction);
3601 AddMockTransaction(&transaction);
3603 // Attempt to populate the cache.
3604 RunTransactionTest(cache.http_cache(), transaction);
3606 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3607 EXPECT_EQ(0, cache.disk_cache()->open_count());
3608 EXPECT_EQ(1, cache.disk_cache()->create_count());
3610 transaction.method = "DELETE";
3611 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
3613 RunTransactionTest(cache.http_cache(), transaction);
3615 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3616 EXPECT_EQ(1, cache.disk_cache()->open_count());
3617 EXPECT_EQ(1, cache.disk_cache()->create_count());
3619 transaction.method = "GET";
3620 transaction.status = "HTTP/1.1 200 OK";
3621 RunTransactionTest(cache.http_cache(), transaction);
3623 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3624 EXPECT_EQ(2, cache.disk_cache()->open_count());
3625 EXPECT_EQ(1, cache.disk_cache()->create_count());
3626 RemoveMockTransaction(&transaction);
3629 // Tests that we don't invalidate entries after a failed network transaction.
3630 TEST(HttpCache, SimpleGET_DontInvalidateOnFailure) {
3631 MockHttpCache cache;
3633 // Populate the cache.
3634 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
3635 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3637 // Fail the network request.
3638 MockTransaction transaction(kSimpleGET_Transaction);
3639 transaction.return_code = ERR_FAILED;
3640 transaction.load_flags |= LOAD_VALIDATE_CACHE;
3642 AddMockTransaction(&transaction);
3643 RunTransactionTest(cache.http_cache(), transaction);
3644 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3645 RemoveMockTransaction(&transaction);
3647 transaction.load_flags = LOAD_ONLY_FROM_CACHE;
3648 transaction.return_code = OK;
3649 AddMockTransaction(&transaction);
3650 RunTransactionTest(cache.http_cache(), transaction);
3652 // Make sure the transaction didn't reach the network.
3653 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3654 RemoveMockTransaction(&transaction);
3657 TEST(HttpCache, RangeGET_SkipsCache) {
3658 MockHttpCache cache;
3660 // Test that we skip the cache for range GET requests. Eventually, we will
3661 // want to cache these, but we'll still have cases where skipping the cache
3662 // makes sense, so we want to make sure that it works properly.
3664 RunTransactionTest(cache.http_cache(), kRangeGET_Transaction);
3666 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3667 EXPECT_EQ(0, cache.disk_cache()->open_count());
3668 EXPECT_EQ(0, cache.disk_cache()->create_count());
3670 MockTransaction transaction(kSimpleGET_Transaction);
3671 transaction.request_headers = "If-None-Match: foo\r\n";
3672 RunTransactionTest(cache.http_cache(), transaction);
3674 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3675 EXPECT_EQ(0, cache.disk_cache()->open_count());
3676 EXPECT_EQ(0, cache.disk_cache()->create_count());
3678 transaction.request_headers =
3679 "If-Modified-Since: Wed, 28 Nov 2007 00:45:20 GMT\r\n";
3680 RunTransactionTest(cache.http_cache(), transaction);
3682 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3683 EXPECT_EQ(0, cache.disk_cache()->open_count());
3684 EXPECT_EQ(0, cache.disk_cache()->create_count());
3687 // Test that we skip the cache for range requests that include a validation
3688 // header.
3689 TEST(HttpCache, RangeGET_SkipsCache2) {
3690 MockHttpCache cache;
3692 MockTransaction transaction(kRangeGET_Transaction);
3693 transaction.request_headers = "If-None-Match: foo\r\n"
3694 EXTRA_HEADER
3695 "Range: bytes = 40-49\r\n";
3696 RunTransactionTest(cache.http_cache(), transaction);
3698 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3699 EXPECT_EQ(0, cache.disk_cache()->open_count());
3700 EXPECT_EQ(0, cache.disk_cache()->create_count());
3702 transaction.request_headers =
3703 "If-Modified-Since: Wed, 28 Nov 2007 00:45:20 GMT\r\n"
3704 EXTRA_HEADER
3705 "Range: bytes = 40-49\r\n";
3706 RunTransactionTest(cache.http_cache(), transaction);
3708 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3709 EXPECT_EQ(0, cache.disk_cache()->open_count());
3710 EXPECT_EQ(0, cache.disk_cache()->create_count());
3712 transaction.request_headers = "If-Range: bla\r\n"
3713 EXTRA_HEADER
3714 "Range: bytes = 40-49\r\n";
3715 RunTransactionTest(cache.http_cache(), transaction);
3717 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3718 EXPECT_EQ(0, cache.disk_cache()->open_count());
3719 EXPECT_EQ(0, cache.disk_cache()->create_count());
3722 TEST(HttpCache, SimpleGET_DoesntLogHeaders) {
3723 MockHttpCache cache;
3725 BoundTestNetLog log;
3726 RunTransactionTestWithLog(cache.http_cache(), kSimpleGET_Transaction,
3727 log.bound());
3729 EXPECT_FALSE(LogContainsEventType(
3730 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3733 TEST(HttpCache, RangeGET_LogsHeaders) {
3734 MockHttpCache cache;
3736 BoundTestNetLog log;
3737 RunTransactionTestWithLog(cache.http_cache(), kRangeGET_Transaction,
3738 log.bound());
3740 EXPECT_TRUE(LogContainsEventType(
3741 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3744 TEST(HttpCache, ExternalValidation_LogsHeaders) {
3745 MockHttpCache cache;
3747 BoundTestNetLog log;
3748 MockTransaction transaction(kSimpleGET_Transaction);
3749 transaction.request_headers = "If-None-Match: foo\r\n" EXTRA_HEADER;
3750 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
3752 EXPECT_TRUE(LogContainsEventType(
3753 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3756 TEST(HttpCache, SpecialHeaders_LogsHeaders) {
3757 MockHttpCache cache;
3759 BoundTestNetLog log;
3760 MockTransaction transaction(kSimpleGET_Transaction);
3761 transaction.request_headers = "cache-control: no-cache\r\n" EXTRA_HEADER;
3762 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
3764 EXPECT_TRUE(LogContainsEventType(
3765 log, NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS));
3768 // Tests that receiving 206 for a regular request is handled correctly.
3769 TEST(HttpCache, GET_Crazy206) {
3770 MockHttpCache cache;
3772 // Write to the cache.
3773 MockTransaction transaction(kRangeGET_TransactionOK);
3774 AddMockTransaction(&transaction);
3775 transaction.request_headers = EXTRA_HEADER;
3776 transaction.handler = NULL;
3777 RunTransactionTest(cache.http_cache(), transaction);
3779 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3780 EXPECT_EQ(0, cache.disk_cache()->open_count());
3781 EXPECT_EQ(1, cache.disk_cache()->create_count());
3783 // This should read again from the net.
3784 RunTransactionTest(cache.http_cache(), transaction);
3786 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3787 EXPECT_EQ(0, cache.disk_cache()->open_count());
3788 EXPECT_EQ(2, cache.disk_cache()->create_count());
3789 RemoveMockTransaction(&transaction);
3792 // Tests that receiving 416 for a regular request is handled correctly.
3793 TEST(HttpCache, GET_Crazy416) {
3794 MockHttpCache cache;
3796 // Write to the cache.
3797 MockTransaction transaction(kSimpleGET_Transaction);
3798 AddMockTransaction(&transaction);
3799 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
3800 RunTransactionTest(cache.http_cache(), transaction);
3802 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3803 EXPECT_EQ(0, cache.disk_cache()->open_count());
3804 EXPECT_EQ(1, cache.disk_cache()->create_count());
3806 RemoveMockTransaction(&transaction);
3809 // Tests that we don't store partial responses that can't be validated.
3810 TEST(HttpCache, RangeGET_NoStrongValidators) {
3811 MockHttpCache cache;
3812 std::string headers;
3814 // Attempt to write to the cache (40-49).
3815 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3816 transaction.response_headers = "Content-Length: 10\n"
3817 "Cache-Control: max-age=3600\n"
3818 "ETag: w/\"foo\"\n";
3819 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3821 Verify206Response(headers, 40, 49);
3822 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3823 EXPECT_EQ(0, cache.disk_cache()->open_count());
3824 EXPECT_EQ(1, cache.disk_cache()->create_count());
3826 // Now verify that there's no cached data.
3827 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3828 &headers);
3830 Verify206Response(headers, 40, 49);
3831 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3832 EXPECT_EQ(0, cache.disk_cache()->open_count());
3833 EXPECT_EQ(2, cache.disk_cache()->create_count());
3836 // Tests failures to conditionalize byte range requests.
3837 TEST(HttpCache, RangeGET_NoConditionalization) {
3838 MockHttpCache cache;
3839 cache.FailConditionalizations();
3840 std::string headers;
3842 // Write to the cache (40-49).
3843 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3844 transaction.response_headers = "Content-Length: 10\n"
3845 "ETag: \"foo\"\n";
3846 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3848 Verify206Response(headers, 40, 49);
3849 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3850 EXPECT_EQ(0, cache.disk_cache()->open_count());
3851 EXPECT_EQ(1, cache.disk_cache()->create_count());
3853 // Now verify that the cached data is not used.
3854 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3855 &headers);
3857 Verify206Response(headers, 40, 49);
3858 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3859 EXPECT_EQ(1, cache.disk_cache()->open_count());
3860 EXPECT_EQ(2, cache.disk_cache()->create_count());
3863 // Tests that restarting a partial request when the cached data cannot be
3864 // revalidated logs an event.
3865 TEST(HttpCache, RangeGET_NoValidation_LogsRestart) {
3866 MockHttpCache cache;
3867 cache.FailConditionalizations();
3869 // Write to the cache (40-49).
3870 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3871 transaction.response_headers = "Content-Length: 10\n"
3872 "ETag: \"foo\"\n";
3873 RunTransactionTest(cache.http_cache(), transaction);
3875 // Now verify that the cached data is not used.
3876 BoundTestNetLog log;
3877 RunTransactionTestWithLog(cache.http_cache(), kRangeGET_TransactionOK,
3878 log.bound());
3880 EXPECT_TRUE(LogContainsEventType(
3881 log, NetLog::TYPE_HTTP_CACHE_RESTART_PARTIAL_REQUEST));
3884 // Tests that a failure to conditionalize a regular request (no range) with a
3885 // sparse entry results in a full response.
3886 TEST(HttpCache, GET_NoConditionalization) {
3887 MockHttpCache cache;
3888 cache.FailConditionalizations();
3889 std::string headers;
3891 // Write to the cache (40-49).
3892 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3893 transaction.response_headers = "Content-Length: 10\n"
3894 "ETag: \"foo\"\n";
3895 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3897 Verify206Response(headers, 40, 49);
3898 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3899 EXPECT_EQ(0, cache.disk_cache()->open_count());
3900 EXPECT_EQ(1, cache.disk_cache()->create_count());
3902 // Now verify that the cached data is not used.
3903 // Don't ask for a range. The cache will attempt to use the cached data but
3904 // should discard it as it cannot be validated. A regular request should go
3905 // to the server and a new entry should be created.
3906 transaction.request_headers = EXTRA_HEADER;
3907 transaction.data = "Not a range";
3908 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3910 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
3911 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3912 EXPECT_EQ(1, cache.disk_cache()->open_count());
3913 EXPECT_EQ(2, cache.disk_cache()->create_count());
3915 // The last response was saved.
3916 RunTransactionTest(cache.http_cache(), transaction);
3917 EXPECT_EQ(3, cache.network_layer()->transaction_count());
3918 EXPECT_EQ(2, cache.disk_cache()->open_count());
3919 EXPECT_EQ(2, cache.disk_cache()->create_count());
3922 // Verifies that conditionalization failures when asking for a range that would
3923 // require the cache to modify the range to ask, result in a network request
3924 // that matches the user's one.
3925 TEST(HttpCache, RangeGET_NoConditionalization2) {
3926 MockHttpCache cache;
3927 cache.FailConditionalizations();
3928 std::string headers;
3930 // Write to the cache (40-49).
3931 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
3932 transaction.response_headers = "Content-Length: 10\n"
3933 "ETag: \"foo\"\n";
3934 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3936 Verify206Response(headers, 40, 49);
3937 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3938 EXPECT_EQ(0, cache.disk_cache()->open_count());
3939 EXPECT_EQ(1, cache.disk_cache()->create_count());
3941 // Now verify that the cached data is not used.
3942 // Ask for a range that extends before and after the cached data so that the
3943 // cache would normally mix data from three sources. After deleting the entry,
3944 // the response will come from a single network request.
3945 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
3946 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
3947 transaction.response_headers = kRangeGET_TransactionOK.response_headers;
3948 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3950 Verify206Response(headers, 20, 59);
3951 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3952 EXPECT_EQ(1, cache.disk_cache()->open_count());
3953 EXPECT_EQ(2, cache.disk_cache()->create_count());
3955 // The last response was saved.
3956 RunTransactionTest(cache.http_cache(), transaction);
3957 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3958 EXPECT_EQ(2, cache.disk_cache()->open_count());
3959 EXPECT_EQ(2, cache.disk_cache()->create_count());
3962 // Tests that we cache partial responses that lack content-length.
3963 TEST(HttpCache, RangeGET_NoContentLength) {
3964 MockHttpCache cache;
3965 std::string headers;
3967 // Attempt to write to the cache (40-49).
3968 MockTransaction transaction(kRangeGET_TransactionOK);
3969 AddMockTransaction(&transaction);
3970 transaction.response_headers = "ETag: \"foo\"\n"
3971 "Accept-Ranges: bytes\n"
3972 "Content-Range: bytes 40-49/80\n";
3973 transaction.handler = NULL;
3974 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
3976 EXPECT_EQ(1, cache.network_layer()->transaction_count());
3977 EXPECT_EQ(0, cache.disk_cache()->open_count());
3978 EXPECT_EQ(1, cache.disk_cache()->create_count());
3980 // Now verify that there's no cached data.
3981 transaction.handler = &RangeTransactionServer::RangeHandler;
3982 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
3983 &headers);
3985 Verify206Response(headers, 40, 49);
3986 EXPECT_EQ(2, cache.network_layer()->transaction_count());
3987 EXPECT_EQ(1, cache.disk_cache()->open_count());
3988 EXPECT_EQ(1, cache.disk_cache()->create_count());
3990 RemoveMockTransaction(&transaction);
3993 // Tests that we can cache range requests and fetch random blocks from the
3994 // cache and the network.
3995 TEST(HttpCache, RangeGET_OK) {
3996 MockHttpCache cache;
3997 AddMockTransaction(&kRangeGET_TransactionOK);
3998 std::string headers;
4000 // Write to the cache (40-49).
4001 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4002 &headers);
4004 Verify206Response(headers, 40, 49);
4005 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4006 EXPECT_EQ(0, cache.disk_cache()->open_count());
4007 EXPECT_EQ(1, cache.disk_cache()->create_count());
4009 // Read from the cache (40-49).
4010 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4011 &headers);
4013 Verify206Response(headers, 40, 49);
4014 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4015 EXPECT_EQ(1, cache.disk_cache()->open_count());
4016 EXPECT_EQ(1, cache.disk_cache()->create_count());
4018 // Make sure we are done with the previous transaction.
4019 base::MessageLoop::current()->RunUntilIdle();
4021 // Write to the cache (30-39).
4022 MockTransaction transaction(kRangeGET_TransactionOK);
4023 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
4024 transaction.data = "rg: 30-39 ";
4025 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4027 Verify206Response(headers, 30, 39);
4028 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4029 EXPECT_EQ(2, cache.disk_cache()->open_count());
4030 EXPECT_EQ(1, cache.disk_cache()->create_count());
4032 // Make sure we are done with the previous transaction.
4033 base::MessageLoop::current()->RunUntilIdle();
4035 // Write and read from the cache (20-59).
4036 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
4037 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
4038 BoundTestNetLog log;
4039 LoadTimingInfo load_timing_info;
4040 RunTransactionTestWithResponseAndGetTiming(
4041 cache.http_cache(), transaction, &headers, log.bound(),
4042 &load_timing_info);
4044 Verify206Response(headers, 20, 59);
4045 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4046 EXPECT_EQ(3, cache.disk_cache()->open_count());
4047 EXPECT_EQ(1, cache.disk_cache()->create_count());
4048 TestLoadTimingNetworkRequest(load_timing_info);
4050 RemoveMockTransaction(&kRangeGET_TransactionOK);
4053 // Tests that we can cache range requests and fetch random blocks from the
4054 // cache and the network, with synchronous responses.
4055 TEST(HttpCache, RangeGET_SyncOK) {
4056 MockHttpCache cache;
4058 MockTransaction transaction(kRangeGET_TransactionOK);
4059 transaction.test_mode = TEST_MODE_SYNC_ALL;
4060 AddMockTransaction(&transaction);
4062 // Write to the cache (40-49).
4063 std::string headers;
4064 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4066 Verify206Response(headers, 40, 49);
4067 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4068 EXPECT_EQ(0, cache.disk_cache()->open_count());
4069 EXPECT_EQ(1, cache.disk_cache()->create_count());
4071 // Read from the cache (40-49).
4072 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4074 Verify206Response(headers, 40, 49);
4075 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4076 EXPECT_EQ(0, 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 to the cache (30-39).
4083 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
4084 transaction.data = "rg: 30-39 ";
4085 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4087 Verify206Response(headers, 30, 39);
4088 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4089 EXPECT_EQ(1, cache.disk_cache()->open_count());
4090 EXPECT_EQ(1, cache.disk_cache()->create_count());
4092 // Make sure we are done with the previous transaction.
4093 base::MessageLoop::current()->RunUntilIdle();
4095 // Write and read from the cache (20-59).
4096 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
4097 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
4098 BoundTestNetLog log;
4099 LoadTimingInfo load_timing_info;
4100 RunTransactionTestWithResponseAndGetTiming(
4101 cache.http_cache(), transaction, &headers, log.bound(),
4102 &load_timing_info);
4104 Verify206Response(headers, 20, 59);
4105 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4106 EXPECT_EQ(2, cache.disk_cache()->open_count());
4107 EXPECT_EQ(1, cache.disk_cache()->create_count());
4108 TestLoadTimingNetworkRequest(load_timing_info);
4110 RemoveMockTransaction(&transaction);
4113 // Tests that if the previous transaction is cancelled while busy (doing sparse
4114 // IO), a new transaction (that reuses that same ActiveEntry) waits until the
4115 // entry is ready again.
4116 TEST(HttpCache, Sparse_WaitForEntry) {
4117 MockHttpCache cache;
4119 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4121 // Create a sparse entry.
4122 RunTransactionTest(cache.http_cache(), transaction);
4124 // Simulate a previous transaction being cancelled.
4125 disk_cache::Entry* entry;
4126 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
4127 entry->CancelSparseIO();
4129 // Test with a range request.
4130 RunTransactionTest(cache.http_cache(), transaction);
4132 // Now test with a regular request.
4133 entry->CancelSparseIO();
4134 transaction.request_headers = EXTRA_HEADER;
4135 transaction.data = kFullRangeData;
4136 RunTransactionTest(cache.http_cache(), transaction);
4138 entry->Close();
4141 // Tests that we don't revalidate an entry unless we are required to do so.
4142 TEST(HttpCache, RangeGET_Revalidate1) {
4143 MockHttpCache cache;
4144 std::string headers;
4146 // Write to the cache (40-49).
4147 MockTransaction transaction(kRangeGET_TransactionOK);
4148 transaction.response_headers =
4149 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
4150 "Expires: Wed, 7 Sep 2033 21:46:42 GMT\n" // Should never expire.
4151 "ETag: \"foo\"\n"
4152 "Accept-Ranges: bytes\n"
4153 "Content-Length: 10\n";
4154 AddMockTransaction(&transaction);
4155 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4157 Verify206Response(headers, 40, 49);
4158 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4159 EXPECT_EQ(0, cache.disk_cache()->open_count());
4160 EXPECT_EQ(1, cache.disk_cache()->create_count());
4162 // Read from the cache (40-49).
4163 BoundTestNetLog log;
4164 LoadTimingInfo load_timing_info;
4165 RunTransactionTestWithResponseAndGetTiming(
4166 cache.http_cache(), transaction, &headers, log.bound(),
4167 &load_timing_info);
4169 Verify206Response(headers, 40, 49);
4170 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4171 EXPECT_EQ(1, cache.disk_cache()->open_count());
4172 EXPECT_EQ(1, cache.disk_cache()->create_count());
4173 TestLoadTimingCachedResponse(load_timing_info);
4175 // Read again forcing the revalidation.
4176 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4177 RunTransactionTestWithResponseAndGetTiming(
4178 cache.http_cache(), transaction, &headers, log.bound(),
4179 &load_timing_info);
4181 Verify206Response(headers, 40, 49);
4182 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4183 EXPECT_EQ(1, cache.disk_cache()->open_count());
4184 EXPECT_EQ(1, cache.disk_cache()->create_count());
4185 TestLoadTimingNetworkRequest(load_timing_info);
4187 RemoveMockTransaction(&transaction);
4190 // Checks that we revalidate an entry when the headers say so.
4191 TEST(HttpCache, RangeGET_Revalidate2) {
4192 MockHttpCache cache;
4193 std::string headers;
4195 // Write to the cache (40-49).
4196 MockTransaction transaction(kRangeGET_TransactionOK);
4197 transaction.response_headers =
4198 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
4199 "Expires: Sat, 18 Apr 2009 01:10:43 GMT\n" // Expired.
4200 "ETag: \"foo\"\n"
4201 "Accept-Ranges: bytes\n"
4202 "Content-Length: 10\n";
4203 AddMockTransaction(&transaction);
4204 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4206 Verify206Response(headers, 40, 49);
4207 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4208 EXPECT_EQ(0, cache.disk_cache()->open_count());
4209 EXPECT_EQ(1, cache.disk_cache()->create_count());
4211 // Read from the cache (40-49).
4212 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4213 Verify206Response(headers, 40, 49);
4215 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4216 EXPECT_EQ(1, cache.disk_cache()->open_count());
4217 EXPECT_EQ(1, cache.disk_cache()->create_count());
4219 RemoveMockTransaction(&transaction);
4222 // Tests that we deal with 304s for range requests.
4223 TEST(HttpCache, RangeGET_304) {
4224 MockHttpCache cache;
4225 AddMockTransaction(&kRangeGET_TransactionOK);
4226 std::string headers;
4228 // Write to the cache (40-49).
4229 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4230 &headers);
4232 Verify206Response(headers, 40, 49);
4233 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4234 EXPECT_EQ(0, cache.disk_cache()->open_count());
4235 EXPECT_EQ(1, cache.disk_cache()->create_count());
4237 // Read from the cache (40-49).
4238 RangeTransactionServer handler;
4239 handler.set_not_modified(true);
4240 MockTransaction transaction(kRangeGET_TransactionOK);
4241 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4242 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4244 Verify206Response(headers, 40, 49);
4245 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4246 EXPECT_EQ(1, cache.disk_cache()->open_count());
4247 EXPECT_EQ(1, cache.disk_cache()->create_count());
4249 RemoveMockTransaction(&kRangeGET_TransactionOK);
4252 // Tests that we deal with 206s when revalidating range requests.
4253 TEST(HttpCache, RangeGET_ModifiedResult) {
4254 MockHttpCache cache;
4255 AddMockTransaction(&kRangeGET_TransactionOK);
4256 std::string headers;
4258 // Write to the cache (40-49).
4259 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4260 &headers);
4262 Verify206Response(headers, 40, 49);
4263 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4264 EXPECT_EQ(0, cache.disk_cache()->open_count());
4265 EXPECT_EQ(1, cache.disk_cache()->create_count());
4267 // Attempt to read from the cache (40-49).
4268 RangeTransactionServer handler;
4269 handler.set_modified(true);
4270 MockTransaction transaction(kRangeGET_TransactionOK);
4271 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4272 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4274 Verify206Response(headers, 40, 49);
4275 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4276 EXPECT_EQ(1, cache.disk_cache()->open_count());
4277 EXPECT_EQ(1, cache.disk_cache()->create_count());
4279 // And the entry should be gone.
4280 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4281 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4282 EXPECT_EQ(1, cache.disk_cache()->open_count());
4283 EXPECT_EQ(2, cache.disk_cache()->create_count());
4285 RemoveMockTransaction(&kRangeGET_TransactionOK);
4288 // Tests that when a server returns 206 with a sub-range of the requested range,
4289 // and there is nothing stored in the cache, the returned response is passed to
4290 // the caller as is. In this context, a subrange means a response that starts
4291 // with the same byte that was requested, but that is not the whole range that
4292 // was requested.
4293 TEST(HttpCache, RangeGET_206ReturnsSubrangeRange_NoCachedContent) {
4294 MockHttpCache cache;
4295 std::string headers;
4297 // Request a large range (40-59). The server sends 40-49.
4298 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4299 transaction.request_headers = "Range: bytes = 40-59\r\n" EXTRA_HEADER;
4300 transaction.response_headers =
4301 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4302 "ETag: \"foo\"\n"
4303 "Accept-Ranges: bytes\n"
4304 "Content-Length: 10\n"
4305 "Content-Range: bytes 40-49/80\n";
4306 transaction.handler = nullptr;
4307 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4309 Verify206Response(headers, 40, 49);
4310 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4311 EXPECT_EQ(0, cache.disk_cache()->open_count());
4312 EXPECT_EQ(1, cache.disk_cache()->create_count());
4315 // Tests that when a server returns 206 with a sub-range of the requested range,
4316 // and there was an entry stored in the cache, the cache gets out of the way.
4317 TEST(HttpCache, RangeGET_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 // Request a large range (40-79). The cache will ask the server for 40-59.
4329 // The server returns 40-49. The cache should consider the server confused and
4330 // abort caching, restarting the request without caching.
4331 transaction.request_headers = "Range: bytes = 40-79\r\n" EXTRA_HEADER;
4332 transaction.response_headers =
4333 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4334 "ETag: \"foo\"\n"
4335 "Accept-Ranges: bytes\n"
4336 "Content-Length: 10\n"
4337 "Content-Range: bytes 40-49/80\n";
4338 transaction.handler = nullptr;
4339 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4341 // Two new network requests were issued, one from the cache and another after
4342 // deleting the entry.
4343 Verify206Response(headers, 40, 49);
4344 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4345 EXPECT_EQ(1, cache.disk_cache()->open_count());
4346 EXPECT_EQ(1, cache.disk_cache()->create_count());
4348 // The entry was deleted.
4349 RunTransactionTest(cache.http_cache(), transaction);
4350 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4351 EXPECT_EQ(1, cache.disk_cache()->open_count());
4352 EXPECT_EQ(2, cache.disk_cache()->create_count());
4355 // Tests that when a server returns 206 with a sub-range of the requested range,
4356 // and there was an entry stored in the cache, the cache gets out of the way,
4357 // when the caller is not using ranges.
4358 TEST(HttpCache, GET_206ReturnsSubrangeRange_CachedContent) {
4359 MockHttpCache cache;
4360 std::string headers;
4362 // Write to the cache (70-79).
4363 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4364 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4365 transaction.data = "rg: 70-79 ";
4366 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4367 Verify206Response(headers, 70, 79);
4369 // Don't ask for a range. The cache will ask the server for 0-69.
4370 // The server returns 40-49. The cache should consider the server confused and
4371 // abort caching, restarting the request.
4372 // The second network request should not be a byte range request so the server
4373 // should return 200 + "Not a range"
4374 transaction.request_headers = "X-Return-Default-Range:\r\n" EXTRA_HEADER;
4375 transaction.data = "Not a range";
4376 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4378 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4379 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4380 EXPECT_EQ(1, cache.disk_cache()->open_count());
4381 EXPECT_EQ(1, cache.disk_cache()->create_count());
4383 // The entry was deleted.
4384 RunTransactionTest(cache.http_cache(), transaction);
4385 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4386 EXPECT_EQ(1, cache.disk_cache()->open_count());
4387 EXPECT_EQ(2, cache.disk_cache()->create_count());
4390 // Tests that when a server returns 206 with a random range and there is
4391 // nothing stored in the cache, the returned response is passed to the caller
4392 // as is. In this context, a WrongRange means that the returned range may or may
4393 // not have any relationship with the requested range (may or may not be
4394 // contained). The important part is that the first byte doesn't match the first
4395 // requested byte.
4396 TEST(HttpCache, RangeGET_206ReturnsWrongRange_NoCachedContent) {
4397 MockHttpCache cache;
4398 std::string headers;
4400 // Request a large range (30-59). The server sends (40-49).
4401 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4402 transaction.request_headers = "Range: bytes = 30-59\r\n" EXTRA_HEADER;
4403 transaction.response_headers =
4404 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4405 "ETag: \"foo\"\n"
4406 "Accept-Ranges: bytes\n"
4407 "Content-Length: 10\n"
4408 "Content-Range: bytes 40-49/80\n";
4409 transaction.handler = nullptr;
4410 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4412 Verify206Response(headers, 40, 49);
4413 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4414 EXPECT_EQ(0, cache.disk_cache()->open_count());
4415 EXPECT_EQ(1, cache.disk_cache()->create_count());
4417 // The entry was deleted.
4418 RunTransactionTest(cache.http_cache(), transaction);
4419 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4420 EXPECT_EQ(0, cache.disk_cache()->open_count());
4421 EXPECT_EQ(2, cache.disk_cache()->create_count());
4424 // Tests that when a server returns 206 with a random range and there is
4425 // an entry stored in the cache, the cache gets out of the way.
4426 TEST(HttpCache, RangeGET_206ReturnsWrongRange_CachedContent) {
4427 MockHttpCache cache;
4428 std::string headers;
4430 // Write to the cache (70-79).
4431 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4432 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4433 transaction.data = "rg: 70-79 ";
4434 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4435 Verify206Response(headers, 70, 79);
4437 // Request a large range (30-79). The cache will ask the server for 30-69.
4438 // The server returns 40-49. The cache should consider the server confused and
4439 // abort caching, returning the weird range to the caller.
4440 transaction.request_headers = "Range: bytes = 30-79\r\n" EXTRA_HEADER;
4441 transaction.response_headers =
4442 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
4443 "ETag: \"foo\"\n"
4444 "Accept-Ranges: bytes\n"
4445 "Content-Length: 10\n"
4446 "Content-Range: bytes 40-49/80\n";
4447 transaction.handler = nullptr;
4448 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4450 Verify206Response(headers, 40, 49);
4451 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4452 EXPECT_EQ(1, cache.disk_cache()->open_count());
4453 EXPECT_EQ(1, cache.disk_cache()->create_count());
4455 // The entry was deleted.
4456 RunTransactionTest(cache.http_cache(), transaction);
4457 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4458 EXPECT_EQ(1, cache.disk_cache()->open_count());
4459 EXPECT_EQ(2, cache.disk_cache()->create_count());
4462 // Tests that when a caller asks for a range beyond EOF, with an empty cache,
4463 // the response matches the one provided by the server.
4464 TEST(HttpCache, RangeGET_206ReturnsSmallerFile_NoCachedContent) {
4465 MockHttpCache cache;
4466 std::string headers;
4468 // Request a large range (70-99). The server sends 70-79.
4469 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4470 transaction.request_headers = "Range: bytes = 70-99\r\n" EXTRA_HEADER;
4471 transaction.data = "rg: 70-79 ";
4472 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4474 Verify206Response(headers, 70, 79);
4475 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4476 EXPECT_EQ(0, cache.disk_cache()->open_count());
4477 EXPECT_EQ(1, cache.disk_cache()->create_count());
4479 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4480 EXPECT_EQ(1, cache.disk_cache()->open_count());
4483 // Tests that when a caller asks for a range beyond EOF, with a cached entry,
4484 // the cache automatically fixes the request.
4485 TEST(HttpCache, RangeGET_206ReturnsSmallerFile_CachedContent) {
4486 MockHttpCache cache;
4487 std::string headers;
4489 // Write to the cache (40-49).
4490 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4491 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4493 // Request a large range (70-99). The server sends 70-79.
4494 transaction.request_headers = "Range: bytes = 70-99\r\n" EXTRA_HEADER;
4495 transaction.data = "rg: 70-79 ";
4496 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4498 Verify206Response(headers, 70, 79);
4499 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4500 EXPECT_EQ(1, cache.disk_cache()->open_count());
4501 EXPECT_EQ(1, cache.disk_cache()->create_count());
4503 // The entry was not deleted (the range was automatically fixed).
4504 RunTransactionTest(cache.http_cache(), transaction);
4505 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4506 EXPECT_EQ(2, cache.disk_cache()->open_count());
4507 EXPECT_EQ(1, cache.disk_cache()->create_count());
4510 // Tests that when a caller asks for a not-satisfiable range, the server's
4511 // response is forwarded to the caller.
4512 TEST(HttpCache, RangeGET_416_NoCachedContent) {
4513 MockHttpCache cache;
4514 std::string headers;
4516 // Request a range beyond EOF (80-99).
4517 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4518 transaction.request_headers = "Range: bytes = 80-99\r\n" EXTRA_HEADER;
4519 transaction.data = "";
4520 transaction.status = "HTTP/1.1 416 Requested Range Not Satisfiable";
4521 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4523 EXPECT_EQ(0U, headers.find(transaction.status));
4524 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4525 EXPECT_EQ(0, cache.disk_cache()->open_count());
4526 EXPECT_EQ(1, cache.disk_cache()->create_count());
4528 // The entry was deleted.
4529 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
4530 EXPECT_EQ(2, cache.disk_cache()->create_count());
4533 // Tests that we cache 301s for range requests.
4534 TEST(HttpCache, RangeGET_301) {
4535 MockHttpCache cache;
4536 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
4537 transaction.status = "HTTP/1.1 301 Moved Permanently";
4538 transaction.response_headers = "Location: http://www.bar.com/\n";
4539 transaction.data = "";
4540 transaction.handler = NULL;
4542 // Write to the cache.
4543 RunTransactionTest(cache.http_cache(), transaction);
4544 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4545 EXPECT_EQ(0, cache.disk_cache()->open_count());
4546 EXPECT_EQ(1, cache.disk_cache()->create_count());
4548 // Read from the cache.
4549 RunTransactionTest(cache.http_cache(), transaction);
4550 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4551 EXPECT_EQ(1, cache.disk_cache()->open_count());
4552 EXPECT_EQ(1, cache.disk_cache()->create_count());
4555 // Tests that we can cache range requests when the start or end is unknown.
4556 // We start with one suffix request, followed by a request from a given point.
4557 TEST(HttpCache, UnknownRangeGET_1) {
4558 MockHttpCache cache;
4559 AddMockTransaction(&kRangeGET_TransactionOK);
4560 std::string headers;
4562 // Write to the cache (70-79).
4563 MockTransaction transaction(kRangeGET_TransactionOK);
4564 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
4565 transaction.data = "rg: 70-79 ";
4566 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4568 Verify206Response(headers, 70, 79);
4569 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4570 EXPECT_EQ(0, cache.disk_cache()->open_count());
4571 EXPECT_EQ(1, cache.disk_cache()->create_count());
4573 // Make sure we are done with the previous transaction.
4574 base::MessageLoop::current()->RunUntilIdle();
4576 // Write and read from the cache (60-79).
4577 transaction.request_headers = "Range: bytes = 60-\r\n" EXTRA_HEADER;
4578 transaction.data = "rg: 60-69 rg: 70-79 ";
4579 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4581 Verify206Response(headers, 60, 79);
4582 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4583 EXPECT_EQ(1, cache.disk_cache()->open_count());
4584 EXPECT_EQ(1, cache.disk_cache()->create_count());
4586 RemoveMockTransaction(&kRangeGET_TransactionOK);
4589 // Tests that we can cache range requests when the start or end is unknown.
4590 // We start with one request from a given point, followed by a suffix request.
4591 // We'll also verify that synchronous cache responses work as intended.
4592 TEST(HttpCache, UnknownRangeGET_2) {
4593 MockHttpCache cache;
4594 std::string headers;
4596 MockTransaction transaction(kRangeGET_TransactionOK);
4597 transaction.test_mode = TEST_MODE_SYNC_CACHE_START |
4598 TEST_MODE_SYNC_CACHE_READ |
4599 TEST_MODE_SYNC_CACHE_WRITE;
4600 AddMockTransaction(&transaction);
4602 // Write to the cache (70-79).
4603 transaction.request_headers = "Range: bytes = 70-\r\n" EXTRA_HEADER;
4604 transaction.data = "rg: 70-79 ";
4605 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4607 Verify206Response(headers, 70, 79);
4608 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4609 EXPECT_EQ(0, cache.disk_cache()->open_count());
4610 EXPECT_EQ(1, cache.disk_cache()->create_count());
4612 // Make sure we are done with the previous transaction.
4613 base::MessageLoop::current()->RunUntilIdle();
4615 // Write and read from the cache (60-79).
4616 transaction.request_headers = "Range: bytes = -20\r\n" EXTRA_HEADER;
4617 transaction.data = "rg: 60-69 rg: 70-79 ";
4618 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4620 Verify206Response(headers, 60, 79);
4621 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4622 EXPECT_EQ(1, cache.disk_cache()->open_count());
4623 EXPECT_EQ(1, cache.disk_cache()->create_count());
4625 RemoveMockTransaction(&transaction);
4628 // Tests that receiving Not Modified when asking for an open range doesn't mess
4629 // up things.
4630 TEST(HttpCache, UnknownRangeGET_304) {
4631 MockHttpCache cache;
4632 std::string headers;
4634 MockTransaction transaction(kRangeGET_TransactionOK);
4635 AddMockTransaction(&transaction);
4637 RangeTransactionServer handler;
4638 handler.set_not_modified(true);
4640 // Ask for the end of the file, without knowing the length.
4641 transaction.request_headers = "Range: bytes = 70-\r\n" EXTRA_HEADER;
4642 transaction.data = "";
4643 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4645 // We just bypass the cache.
4646 EXPECT_EQ(0U, headers.find("HTTP/1.1 304 Not Modified\n"));
4647 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4648 EXPECT_EQ(0, cache.disk_cache()->open_count());
4649 EXPECT_EQ(1, cache.disk_cache()->create_count());
4651 RunTransactionTest(cache.http_cache(), transaction);
4652 EXPECT_EQ(2, cache.disk_cache()->create_count());
4654 RemoveMockTransaction(&transaction);
4657 // Tests that we can handle non-range requests when we have cached a range.
4658 TEST(HttpCache, GET_Previous206) {
4659 MockHttpCache cache;
4660 AddMockTransaction(&kRangeGET_TransactionOK);
4661 std::string headers;
4662 BoundTestNetLog log;
4663 LoadTimingInfo load_timing_info;
4665 // Write to the cache (40-49).
4666 RunTransactionTestWithResponseAndGetTiming(
4667 cache.http_cache(), kRangeGET_TransactionOK, &headers, log.bound(),
4668 &load_timing_info);
4670 Verify206Response(headers, 40, 49);
4671 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4672 EXPECT_EQ(0, cache.disk_cache()->open_count());
4673 EXPECT_EQ(1, cache.disk_cache()->create_count());
4674 TestLoadTimingNetworkRequest(load_timing_info);
4676 // Write and read from the cache (0-79), when not asked for a range.
4677 MockTransaction transaction(kRangeGET_TransactionOK);
4678 transaction.request_headers = EXTRA_HEADER;
4679 transaction.data = kFullRangeData;
4680 RunTransactionTestWithResponseAndGetTiming(
4681 cache.http_cache(), transaction, &headers, log.bound(),
4682 &load_timing_info);
4684 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4685 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4686 EXPECT_EQ(1, cache.disk_cache()->open_count());
4687 EXPECT_EQ(1, cache.disk_cache()->create_count());
4688 TestLoadTimingNetworkRequest(load_timing_info);
4690 RemoveMockTransaction(&kRangeGET_TransactionOK);
4693 // Tests that we can handle non-range requests when we have cached the first
4694 // part of the object and the server replies with 304 (Not Modified).
4695 TEST(HttpCache, GET_Previous206_NotModified) {
4696 MockHttpCache cache;
4698 MockTransaction transaction(kRangeGET_TransactionOK);
4699 AddMockTransaction(&transaction);
4700 std::string headers;
4701 BoundTestNetLog log;
4702 LoadTimingInfo load_timing_info;
4704 // Write to the cache (0-9).
4705 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
4706 transaction.data = "rg: 00-09 ";
4707 RunTransactionTestWithResponseAndGetTiming(
4708 cache.http_cache(), transaction, &headers, log.bound(),
4709 &load_timing_info);
4710 Verify206Response(headers, 0, 9);
4711 TestLoadTimingNetworkRequest(load_timing_info);
4713 // Write to the cache (70-79).
4714 transaction.request_headers = "Range: bytes = 70-79\r\n" EXTRA_HEADER;
4715 transaction.data = "rg: 70-79 ";
4716 RunTransactionTestWithResponseAndGetTiming(
4717 cache.http_cache(), transaction, &headers, log.bound(),
4718 &load_timing_info);
4719 Verify206Response(headers, 70, 79);
4721 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4722 EXPECT_EQ(1, cache.disk_cache()->open_count());
4723 EXPECT_EQ(1, cache.disk_cache()->create_count());
4724 TestLoadTimingNetworkRequest(load_timing_info);
4726 // Read from the cache (0-9), write and read from cache (10 - 79).
4727 transaction.load_flags |= LOAD_VALIDATE_CACHE;
4728 transaction.request_headers = "Foo: bar\r\n" EXTRA_HEADER;
4729 transaction.data = kFullRangeData;
4730 RunTransactionTestWithResponseAndGetTiming(
4731 cache.http_cache(), transaction, &headers, log.bound(),
4732 &load_timing_info);
4734 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4735 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4736 EXPECT_EQ(2, cache.disk_cache()->open_count());
4737 EXPECT_EQ(1, cache.disk_cache()->create_count());
4738 TestLoadTimingNetworkRequest(load_timing_info);
4740 RemoveMockTransaction(&transaction);
4743 // Tests that we can handle a regular request to a sparse entry, that results in
4744 // new content provided by the server (206).
4745 TEST(HttpCache, GET_Previous206_NewContent) {
4746 MockHttpCache cache;
4747 AddMockTransaction(&kRangeGET_TransactionOK);
4748 std::string headers;
4750 // Write to the cache (0-9).
4751 MockTransaction transaction(kRangeGET_TransactionOK);
4752 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
4753 transaction.data = "rg: 00-09 ";
4754 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
4756 Verify206Response(headers, 0, 9);
4757 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4758 EXPECT_EQ(0, cache.disk_cache()->open_count());
4759 EXPECT_EQ(1, cache.disk_cache()->create_count());
4761 // Now we'll issue a request without any range that should result first in a
4762 // 206 (when revalidating), and then in a weird standard answer: the test
4763 // server will not modify the response so we'll get the default range... a
4764 // real server will answer with 200.
4765 MockTransaction transaction2(kRangeGET_TransactionOK);
4766 transaction2.request_headers = EXTRA_HEADER;
4767 transaction2.load_flags |= LOAD_VALIDATE_CACHE;
4768 transaction2.data = "Not a range";
4769 RangeTransactionServer handler;
4770 handler.set_modified(true);
4771 BoundTestNetLog log;
4772 LoadTimingInfo load_timing_info;
4773 RunTransactionTestWithResponseAndGetTiming(
4774 cache.http_cache(), transaction2, &headers, log.bound(),
4775 &load_timing_info);
4777 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 OK\n"));
4778 EXPECT_EQ(3, cache.network_layer()->transaction_count());
4779 EXPECT_EQ(1, cache.disk_cache()->open_count());
4780 EXPECT_EQ(1, cache.disk_cache()->create_count());
4781 TestLoadTimingNetworkRequest(load_timing_info);
4783 // Verify that the previous request deleted the entry.
4784 RunTransactionTest(cache.http_cache(), transaction);
4785 EXPECT_EQ(2, cache.disk_cache()->create_count());
4787 RemoveMockTransaction(&transaction);
4790 // Tests that we can handle cached 206 responses that are not sparse.
4791 TEST(HttpCache, GET_Previous206_NotSparse) {
4792 MockHttpCache cache;
4794 // Create a disk cache entry that stores 206 headers while not being sparse.
4795 disk_cache::Entry* entry;
4796 ASSERT_TRUE(cache.CreateBackendEntry(kSimpleGET_Transaction.url, &entry,
4797 NULL));
4799 std::string raw_headers(kRangeGET_TransactionOK.status);
4800 raw_headers.append("\n");
4801 raw_headers.append(kRangeGET_TransactionOK.response_headers);
4802 raw_headers =
4803 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4805 HttpResponseInfo response;
4806 response.headers = new HttpResponseHeaders(raw_headers);
4807 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4809 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4810 int len = static_cast<int>(base::strlcpy(buf->data(),
4811 kRangeGET_TransactionOK.data, 500));
4812 TestCompletionCallback cb;
4813 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4814 EXPECT_EQ(len, cb.GetResult(rv));
4815 entry->Close();
4817 // Now see that we don't use the stored entry.
4818 std::string headers;
4819 BoundTestNetLog log;
4820 LoadTimingInfo load_timing_info;
4821 RunTransactionTestWithResponseAndGetTiming(
4822 cache.http_cache(), kSimpleGET_Transaction, &headers, log.bound(),
4823 &load_timing_info);
4825 // We are expecting a 200.
4826 std::string expected_headers(kSimpleGET_Transaction.status);
4827 expected_headers.append("\n");
4828 expected_headers.append(kSimpleGET_Transaction.response_headers);
4829 EXPECT_EQ(expected_headers, headers);
4830 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4831 EXPECT_EQ(1, cache.disk_cache()->open_count());
4832 EXPECT_EQ(2, cache.disk_cache()->create_count());
4833 TestLoadTimingNetworkRequest(load_timing_info);
4836 // Tests that we can handle cached 206 responses that are not sparse. This time
4837 // we issue a range request and expect to receive a range.
4838 TEST(HttpCache, RangeGET_Previous206_NotSparse_2) {
4839 MockHttpCache cache;
4840 AddMockTransaction(&kRangeGET_TransactionOK);
4842 // Create a disk cache entry that stores 206 headers while not being sparse.
4843 disk_cache::Entry* entry;
4844 ASSERT_TRUE(cache.CreateBackendEntry(kRangeGET_TransactionOK.url, &entry,
4845 NULL));
4847 std::string raw_headers(kRangeGET_TransactionOK.status);
4848 raw_headers.append("\n");
4849 raw_headers.append(kRangeGET_TransactionOK.response_headers);
4850 raw_headers =
4851 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4853 HttpResponseInfo response;
4854 response.headers = new HttpResponseHeaders(raw_headers);
4855 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4857 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4858 int len = static_cast<int>(base::strlcpy(buf->data(),
4859 kRangeGET_TransactionOK.data, 500));
4860 TestCompletionCallback cb;
4861 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4862 EXPECT_EQ(len, cb.GetResult(rv));
4863 entry->Close();
4865 // Now see that we don't use the stored entry.
4866 std::string headers;
4867 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
4868 &headers);
4870 // We are expecting a 206.
4871 Verify206Response(headers, 40, 49);
4872 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4873 EXPECT_EQ(1, cache.disk_cache()->open_count());
4874 EXPECT_EQ(2, cache.disk_cache()->create_count());
4876 RemoveMockTransaction(&kRangeGET_TransactionOK);
4879 // Tests that we can handle cached 206 responses that can't be validated.
4880 TEST(HttpCache, GET_Previous206_NotValidation) {
4881 MockHttpCache cache;
4883 // Create a disk cache entry that stores 206 headers.
4884 disk_cache::Entry* entry;
4885 ASSERT_TRUE(cache.CreateBackendEntry(kSimpleGET_Transaction.url, &entry,
4886 NULL));
4888 // Make sure that the headers cannot be validated with the server.
4889 std::string raw_headers(kRangeGET_TransactionOK.status);
4890 raw_headers.append("\n");
4891 raw_headers.append("Content-Length: 80\n");
4892 raw_headers =
4893 HttpUtil::AssembleRawHeaders(raw_headers.data(), raw_headers.size());
4895 HttpResponseInfo response;
4896 response.headers = new HttpResponseHeaders(raw_headers);
4897 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
4899 scoped_refptr<IOBuffer> buf(new IOBuffer(500));
4900 int len = static_cast<int>(base::strlcpy(buf->data(),
4901 kRangeGET_TransactionOK.data, 500));
4902 TestCompletionCallback cb;
4903 int rv = entry->WriteData(1, 0, buf.get(), len, cb.callback(), true);
4904 EXPECT_EQ(len, cb.GetResult(rv));
4905 entry->Close();
4907 // Now see that we don't use the stored entry.
4908 std::string headers;
4909 RunTransactionTestWithResponse(cache.http_cache(), kSimpleGET_Transaction,
4910 &headers);
4912 // We are expecting a 200.
4913 std::string expected_headers(kSimpleGET_Transaction.status);
4914 expected_headers.append("\n");
4915 expected_headers.append(kSimpleGET_Transaction.response_headers);
4916 EXPECT_EQ(expected_headers, headers);
4917 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4918 EXPECT_EQ(1, cache.disk_cache()->open_count());
4919 EXPECT_EQ(2, cache.disk_cache()->create_count());
4922 // Tests that we can handle range requests with cached 200 responses.
4923 TEST(HttpCache, RangeGET_Previous200) {
4924 MockHttpCache cache;
4926 // Store the whole thing with status 200.
4927 MockTransaction transaction(kTypicalGET_Transaction);
4928 transaction.url = kRangeGET_TransactionOK.url;
4929 transaction.data = kFullRangeData;
4930 AddMockTransaction(&transaction);
4931 RunTransactionTest(cache.http_cache(), transaction);
4932 EXPECT_EQ(1, cache.network_layer()->transaction_count());
4933 EXPECT_EQ(0, cache.disk_cache()->open_count());
4934 EXPECT_EQ(1, cache.disk_cache()->create_count());
4936 RemoveMockTransaction(&transaction);
4937 AddMockTransaction(&kRangeGET_TransactionOK);
4939 // Now see that we use the stored entry.
4940 std::string headers;
4941 MockTransaction transaction2(kRangeGET_TransactionOK);
4942 RangeTransactionServer handler;
4943 handler.set_not_modified(true);
4944 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
4946 // We are expecting a 206.
4947 Verify206Response(headers, 40, 49);
4948 EXPECT_EQ(2, cache.network_layer()->transaction_count());
4949 EXPECT_EQ(1, cache.disk_cache()->open_count());
4950 EXPECT_EQ(1, cache.disk_cache()->create_count());
4952 // The last transaction has finished so make sure the entry is deactivated.
4953 base::MessageLoop::current()->RunUntilIdle();
4955 // Make a request for an invalid range.
4956 MockTransaction transaction3(kRangeGET_TransactionOK);
4957 transaction3.request_headers = "Range: bytes = 80-90\r\n" EXTRA_HEADER;
4958 transaction3.data = transaction.data;
4959 transaction3.load_flags = LOAD_PREFERRING_CACHE;
4960 RunTransactionTestWithResponse(cache.http_cache(), transaction3, &headers);
4961 EXPECT_EQ(2, cache.disk_cache()->open_count());
4962 EXPECT_EQ(0U, headers.find("HTTP/1.1 200 "));
4963 EXPECT_EQ(std::string::npos, headers.find("Content-Range:"));
4964 EXPECT_EQ(std::string::npos, headers.find("Content-Length: 80"));
4966 // Make sure the entry is deactivated.
4967 base::MessageLoop::current()->RunUntilIdle();
4969 // Even though the request was invalid, we should have the entry.
4970 RunTransactionTest(cache.http_cache(), transaction2);
4971 EXPECT_EQ(3, cache.disk_cache()->open_count());
4973 // Make sure the entry is deactivated.
4974 base::MessageLoop::current()->RunUntilIdle();
4976 // Now we should receive a range from the server and drop the stored entry.
4977 handler.set_not_modified(false);
4978 transaction2.request_headers = kRangeGET_TransactionOK.request_headers;
4979 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
4980 Verify206Response(headers, 40, 49);
4981 EXPECT_EQ(4, cache.network_layer()->transaction_count());
4982 EXPECT_EQ(4, cache.disk_cache()->open_count());
4983 EXPECT_EQ(1, cache.disk_cache()->create_count());
4985 RunTransactionTest(cache.http_cache(), transaction2);
4986 EXPECT_EQ(2, cache.disk_cache()->create_count());
4988 RemoveMockTransaction(&kRangeGET_TransactionOK);
4991 // Tests that we can handle a 200 response when dealing with sparse entries.
4992 TEST(HttpCache, RangeRequestResultsIn200) {
4993 MockHttpCache cache;
4994 AddMockTransaction(&kRangeGET_TransactionOK);
4995 std::string headers;
4997 // Write to the cache (70-79).
4998 MockTransaction transaction(kRangeGET_TransactionOK);
4999 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
5000 transaction.data = "rg: 70-79 ";
5001 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5003 Verify206Response(headers, 70, 79);
5004 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5005 EXPECT_EQ(0, cache.disk_cache()->open_count());
5006 EXPECT_EQ(1, cache.disk_cache()->create_count());
5008 // Now we'll issue a request that results in a plain 200 response, but to
5009 // the to the same URL that we used to store sparse data, and making sure
5010 // that we ask for a range.
5011 RemoveMockTransaction(&kRangeGET_TransactionOK);
5012 MockTransaction transaction2(kSimpleGET_Transaction);
5013 transaction2.url = kRangeGET_TransactionOK.url;
5014 transaction2.request_headers = kRangeGET_TransactionOK.request_headers;
5015 AddMockTransaction(&transaction2);
5017 RunTransactionTestWithResponse(cache.http_cache(), transaction2, &headers);
5019 std::string expected_headers(kSimpleGET_Transaction.status);
5020 expected_headers.append("\n");
5021 expected_headers.append(kSimpleGET_Transaction.response_headers);
5022 EXPECT_EQ(expected_headers, headers);
5023 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5024 EXPECT_EQ(1, cache.disk_cache()->open_count());
5025 EXPECT_EQ(1, cache.disk_cache()->create_count());
5027 RemoveMockTransaction(&transaction2);
5030 // Tests that a range request that falls outside of the size that we know about
5031 // only deletes the entry if the resource has indeed changed.
5032 TEST(HttpCache, RangeGET_MoreThanCurrentSize) {
5033 MockHttpCache cache;
5034 AddMockTransaction(&kRangeGET_TransactionOK);
5035 std::string headers;
5037 // Write to the cache (40-49).
5038 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
5039 &headers);
5041 Verify206Response(headers, 40, 49);
5042 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5043 EXPECT_EQ(0, cache.disk_cache()->open_count());
5044 EXPECT_EQ(1, cache.disk_cache()->create_count());
5046 // A weird request should not delete this entry. Ask for bytes 120-.
5047 MockTransaction transaction(kRangeGET_TransactionOK);
5048 transaction.request_headers = "Range: bytes = 120-\r\n" EXTRA_HEADER;
5049 transaction.data = "";
5050 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5052 EXPECT_EQ(0U, headers.find("HTTP/1.1 416 "));
5053 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5054 EXPECT_EQ(1, cache.disk_cache()->open_count());
5055 EXPECT_EQ(1, cache.disk_cache()->create_count());
5057 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5058 EXPECT_EQ(2, cache.disk_cache()->open_count());
5059 EXPECT_EQ(1, cache.disk_cache()->create_count());
5061 RemoveMockTransaction(&kRangeGET_TransactionOK);
5064 // Tests that we don't delete a sparse entry when we cancel a request.
5065 TEST(HttpCache, RangeGET_Cancel) {
5066 MockHttpCache cache;
5067 AddMockTransaction(&kRangeGET_TransactionOK);
5069 MockHttpRequest request(kRangeGET_TransactionOK);
5071 Context* c = new Context();
5072 int rv = cache.CreateTransaction(&c->trans);
5073 ASSERT_EQ(OK, rv);
5075 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5076 if (rv == ERR_IO_PENDING)
5077 rv = c->callback.WaitForResult();
5079 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5080 EXPECT_EQ(0, cache.disk_cache()->open_count());
5081 EXPECT_EQ(1, cache.disk_cache()->create_count());
5083 // Make sure that the entry has some data stored.
5084 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5085 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5086 if (rv == ERR_IO_PENDING)
5087 rv = c->callback.WaitForResult();
5088 EXPECT_EQ(buf->size(), rv);
5090 // Destroy the transaction.
5091 delete c;
5093 // Verify that the entry has not been deleted.
5094 disk_cache::Entry* entry;
5095 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5096 entry->Close();
5097 RemoveMockTransaction(&kRangeGET_TransactionOK);
5100 // Tests that we don't delete a sparse entry when we start a new request after
5101 // cancelling the previous one.
5102 TEST(HttpCache, RangeGET_Cancel2) {
5103 MockHttpCache cache;
5104 AddMockTransaction(&kRangeGET_TransactionOK);
5106 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5107 MockHttpRequest request(kRangeGET_TransactionOK);
5108 request.load_flags |= LOAD_VALIDATE_CACHE;
5110 Context* c = new Context();
5111 int rv = cache.CreateTransaction(&c->trans);
5112 ASSERT_EQ(OK, rv);
5114 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5115 if (rv == ERR_IO_PENDING)
5116 rv = c->callback.WaitForResult();
5118 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5119 EXPECT_EQ(1, cache.disk_cache()->open_count());
5120 EXPECT_EQ(1, cache.disk_cache()->create_count());
5122 // Make sure that we revalidate the entry and read from the cache (a single
5123 // read will return while waiting for the network).
5124 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5125 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5126 EXPECT_EQ(5, c->callback.GetResult(rv));
5127 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5128 EXPECT_EQ(ERR_IO_PENDING, rv);
5130 // Destroy the transaction before completing the read.
5131 delete c;
5133 // We have the read and the delete (OnProcessPendingQueue) waiting on the
5134 // message loop. This means that a new transaction will just reuse the same
5135 // active entry (no open or create).
5137 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5139 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5140 EXPECT_EQ(1, cache.disk_cache()->open_count());
5141 EXPECT_EQ(1, cache.disk_cache()->create_count());
5142 RemoveMockTransaction(&kRangeGET_TransactionOK);
5145 // A slight variation of the previous test, this time we cancel two requests in
5146 // a row, making sure that the second is waiting for the entry to be ready.
5147 TEST(HttpCache, RangeGET_Cancel3) {
5148 MockHttpCache cache;
5149 AddMockTransaction(&kRangeGET_TransactionOK);
5151 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5152 MockHttpRequest request(kRangeGET_TransactionOK);
5153 request.load_flags |= LOAD_VALIDATE_CACHE;
5155 Context* c = new Context();
5156 int rv = cache.CreateTransaction(&c->trans);
5157 ASSERT_EQ(OK, rv);
5159 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5160 EXPECT_EQ(ERR_IO_PENDING, rv);
5161 rv = c->callback.WaitForResult();
5163 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5164 EXPECT_EQ(1, cache.disk_cache()->open_count());
5165 EXPECT_EQ(1, cache.disk_cache()->create_count());
5167 // Make sure that we revalidate the entry and read from the cache (a single
5168 // read will return while waiting for the network).
5169 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5170 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5171 EXPECT_EQ(5, c->callback.GetResult(rv));
5172 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5173 EXPECT_EQ(ERR_IO_PENDING, rv);
5175 // Destroy the transaction before completing the read.
5176 delete c;
5178 // We have the read and the delete (OnProcessPendingQueue) waiting on the
5179 // message loop. This means that a new transaction will just reuse the same
5180 // active entry (no open or create).
5182 c = new Context();
5183 rv = cache.CreateTransaction(&c->trans);
5184 ASSERT_EQ(OK, rv);
5186 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5187 EXPECT_EQ(ERR_IO_PENDING, rv);
5189 MockDiskEntry::IgnoreCallbacks(true);
5190 base::MessageLoop::current()->RunUntilIdle();
5191 MockDiskEntry::IgnoreCallbacks(false);
5193 // The new transaction is waiting for the query range callback.
5194 delete c;
5196 // And we should not crash when the callback is delivered.
5197 base::MessageLoop::current()->RunUntilIdle();
5199 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5200 EXPECT_EQ(1, cache.disk_cache()->open_count());
5201 EXPECT_EQ(1, cache.disk_cache()->create_count());
5202 RemoveMockTransaction(&kRangeGET_TransactionOK);
5205 // Tests that an invalid range response results in no cached entry.
5206 TEST(HttpCache, RangeGET_InvalidResponse1) {
5207 MockHttpCache cache;
5208 std::string headers;
5210 MockTransaction transaction(kRangeGET_TransactionOK);
5211 transaction.handler = NULL;
5212 transaction.response_headers = "Content-Range: bytes 40-49/45\n"
5213 "Content-Length: 10\n";
5214 AddMockTransaction(&transaction);
5215 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5217 std::string expected(transaction.status);
5218 expected.append("\n");
5219 expected.append(transaction.response_headers);
5220 EXPECT_EQ(expected, headers);
5222 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5223 EXPECT_EQ(0, cache.disk_cache()->open_count());
5224 EXPECT_EQ(1, cache.disk_cache()->create_count());
5226 // Verify that we don't have a cached entry.
5227 disk_cache::Entry* entry;
5228 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5230 RemoveMockTransaction(&kRangeGET_TransactionOK);
5233 // Tests that we reject a range that doesn't match the content-length.
5234 TEST(HttpCache, RangeGET_InvalidResponse2) {
5235 MockHttpCache cache;
5236 std::string headers;
5238 MockTransaction transaction(kRangeGET_TransactionOK);
5239 transaction.handler = NULL;
5240 transaction.response_headers = "Content-Range: bytes 40-49/80\n"
5241 "Content-Length: 20\n";
5242 AddMockTransaction(&transaction);
5243 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5245 std::string expected(transaction.status);
5246 expected.append("\n");
5247 expected.append(transaction.response_headers);
5248 EXPECT_EQ(expected, headers);
5250 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5251 EXPECT_EQ(0, cache.disk_cache()->open_count());
5252 EXPECT_EQ(1, cache.disk_cache()->create_count());
5254 // Verify that we don't have a cached entry.
5255 disk_cache::Entry* entry;
5256 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5258 RemoveMockTransaction(&kRangeGET_TransactionOK);
5261 // Tests that if a server tells us conflicting information about a resource we
5262 // drop the entry.
5263 TEST(HttpCache, RangeGET_InvalidResponse3) {
5264 MockHttpCache cache;
5265 std::string headers;
5267 MockTransaction transaction(kRangeGET_TransactionOK);
5268 transaction.handler = NULL;
5269 transaction.request_headers = "Range: bytes = 50-59\r\n" EXTRA_HEADER;
5270 std::string response_headers(transaction.response_headers);
5271 response_headers.append("Content-Range: bytes 50-59/160\n");
5272 transaction.response_headers = response_headers.c_str();
5273 AddMockTransaction(&transaction);
5274 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5276 Verify206Response(headers, 50, 59);
5277 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5278 EXPECT_EQ(0, cache.disk_cache()->open_count());
5279 EXPECT_EQ(1, cache.disk_cache()->create_count());
5281 RemoveMockTransaction(&transaction);
5282 AddMockTransaction(&kRangeGET_TransactionOK);
5284 // This transaction will report a resource size of 80 bytes, and we think it's
5285 // 160 so we should ignore the response.
5286 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
5287 &headers);
5289 Verify206Response(headers, 40, 49);
5290 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5291 EXPECT_EQ(1, cache.disk_cache()->open_count());
5292 EXPECT_EQ(1, cache.disk_cache()->create_count());
5294 // Verify that the entry is gone.
5295 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5296 EXPECT_EQ(1, cache.disk_cache()->open_count());
5297 EXPECT_EQ(2, cache.disk_cache()->create_count());
5298 RemoveMockTransaction(&kRangeGET_TransactionOK);
5301 // Tests that we handle large range values properly.
5302 TEST(HttpCache, RangeGET_LargeValues) {
5303 // We need a real sparse cache for this test.
5304 MockHttpCache cache(HttpCache::DefaultBackend::InMemory(1024 * 1024));
5305 std::string headers;
5307 MockTransaction transaction(kRangeGET_TransactionOK);
5308 transaction.handler = NULL;
5309 transaction.request_headers = "Range: bytes = 4294967288-4294967297\r\n"
5310 EXTRA_HEADER;
5311 transaction.response_headers =
5312 "ETag: \"foo\"\n"
5313 "Content-Range: bytes 4294967288-4294967297/4294967299\n"
5314 "Content-Length: 10\n";
5315 AddMockTransaction(&transaction);
5316 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5318 std::string expected(transaction.status);
5319 expected.append("\n");
5320 expected.append(transaction.response_headers);
5321 EXPECT_EQ(expected, headers);
5323 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5325 // Verify that we have a cached entry.
5326 disk_cache::Entry* en;
5327 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &en));
5328 en->Close();
5330 RemoveMockTransaction(&kRangeGET_TransactionOK);
5333 // Tests that we don't crash with a range request if the disk cache was not
5334 // initialized properly.
5335 TEST(HttpCache, RangeGET_NoDiskCache) {
5336 MockBlockingBackendFactory* factory = new MockBlockingBackendFactory();
5337 factory->set_fail(true);
5338 factory->FinishCreation(); // We'll complete synchronously.
5339 MockHttpCache cache(factory);
5341 AddMockTransaction(&kRangeGET_TransactionOK);
5343 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5344 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5346 RemoveMockTransaction(&kRangeGET_TransactionOK);
5349 // Tests that we handle byte range requests that skip the cache.
5350 TEST(HttpCache, RangeHEAD) {
5351 MockHttpCache cache;
5352 AddMockTransaction(&kRangeGET_TransactionOK);
5354 MockTransaction transaction(kRangeGET_TransactionOK);
5355 transaction.request_headers = "Range: bytes = -10\r\n" EXTRA_HEADER;
5356 transaction.method = "HEAD";
5357 transaction.data = "rg: 70-79 ";
5359 std::string headers;
5360 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5362 Verify206Response(headers, 70, 79);
5363 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5364 EXPECT_EQ(0, cache.disk_cache()->open_count());
5365 EXPECT_EQ(0, cache.disk_cache()->create_count());
5367 RemoveMockTransaction(&kRangeGET_TransactionOK);
5370 // Tests that we don't crash when after reading from the cache we issue a
5371 // request for the next range and the server gives us a 200 synchronously.
5372 TEST(HttpCache, RangeGET_FastFlakyServer) {
5373 MockHttpCache cache;
5375 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
5376 transaction.request_headers = "Range: bytes = 40-\r\n" EXTRA_HEADER;
5377 transaction.test_mode = TEST_MODE_SYNC_NET_START;
5378 transaction.load_flags |= LOAD_VALIDATE_CACHE;
5380 // Write to the cache.
5381 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5383 // And now read from the cache and the network.
5384 RangeTransactionServer handler;
5385 handler.set_bad_200(true);
5386 transaction.data = "Not a range";
5387 BoundTestNetLog log;
5388 RunTransactionTestWithLog(cache.http_cache(), transaction, log.bound());
5390 EXPECT_EQ(3, cache.network_layer()->transaction_count());
5391 EXPECT_EQ(1, cache.disk_cache()->open_count());
5392 EXPECT_EQ(1, cache.disk_cache()->create_count());
5393 EXPECT_TRUE(LogContainsEventType(
5394 log, NetLog::TYPE_HTTP_CACHE_RE_SEND_PARTIAL_REQUEST));
5397 // Tests that when the server gives us less data than expected, we don't keep
5398 // asking for more data.
5399 TEST(HttpCache, RangeGET_FastFlakyServer2) {
5400 MockHttpCache cache;
5402 // First, check with an empty cache (WRITE mode).
5403 MockTransaction transaction(kRangeGET_TransactionOK);
5404 transaction.request_headers = "Range: bytes = 40-49\r\n" EXTRA_HEADER;
5405 transaction.data = "rg: 40-"; // Less than expected.
5406 transaction.handler = NULL;
5407 std::string headers(transaction.response_headers);
5408 headers.append("Content-Range: bytes 40-49/80\n");
5409 transaction.response_headers = headers.c_str();
5411 AddMockTransaction(&transaction);
5413 // Write to the cache.
5414 RunTransactionTest(cache.http_cache(), transaction);
5416 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5417 EXPECT_EQ(0, cache.disk_cache()->open_count());
5418 EXPECT_EQ(1, cache.disk_cache()->create_count());
5420 // Now verify that even in READ_WRITE mode, we forward the bad response to
5421 // the caller.
5422 transaction.request_headers = "Range: bytes = 60-69\r\n" EXTRA_HEADER;
5423 transaction.data = "rg: 60-"; // Less than expected.
5424 headers = kRangeGET_TransactionOK.response_headers;
5425 headers.append("Content-Range: bytes 60-69/80\n");
5426 transaction.response_headers = headers.c_str();
5428 RunTransactionTest(cache.http_cache(), transaction);
5430 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5431 EXPECT_EQ(1, cache.disk_cache()->open_count());
5432 EXPECT_EQ(1, cache.disk_cache()->create_count());
5434 RemoveMockTransaction(&transaction);
5437 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
5438 // This test hits a NOTREACHED so it is a release mode only test.
5439 TEST(HttpCache, RangeGET_OK_LoadOnlyFromCache) {
5440 MockHttpCache cache;
5441 AddMockTransaction(&kRangeGET_TransactionOK);
5443 // Write to the cache (40-49).
5444 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
5445 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5446 EXPECT_EQ(0, cache.disk_cache()->open_count());
5447 EXPECT_EQ(1, cache.disk_cache()->create_count());
5449 // Force this transaction to read from the cache.
5450 MockTransaction transaction(kRangeGET_TransactionOK);
5451 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
5453 MockHttpRequest request(transaction);
5454 TestCompletionCallback callback;
5456 scoped_ptr<HttpTransaction> trans;
5457 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
5458 EXPECT_EQ(OK, rv);
5459 ASSERT_TRUE(trans.get());
5461 rv = trans->Start(&request, callback.callback(), BoundNetLog());
5462 if (rv == ERR_IO_PENDING)
5463 rv = callback.WaitForResult();
5464 ASSERT_EQ(ERR_CACHE_MISS, rv);
5466 trans.reset();
5468 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5469 EXPECT_EQ(1, cache.disk_cache()->open_count());
5470 EXPECT_EQ(1, cache.disk_cache()->create_count());
5472 RemoveMockTransaction(&kRangeGET_TransactionOK);
5474 #endif
5476 // Tests the handling of the "truncation" flag.
5477 TEST(HttpCache, WriteResponseInfo_Truncated) {
5478 MockHttpCache cache;
5479 disk_cache::Entry* entry;
5480 ASSERT_TRUE(cache.CreateBackendEntry("http://www.google.com", &entry,
5481 NULL));
5483 std::string headers("HTTP/1.1 200 OK");
5484 headers = HttpUtil::AssembleRawHeaders(headers.data(), headers.size());
5485 HttpResponseInfo response;
5486 response.headers = new HttpResponseHeaders(headers);
5488 // Set the last argument for this to be an incomplete request.
5489 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, true));
5490 bool truncated = false;
5491 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5492 EXPECT_TRUE(truncated);
5494 // And now test the opposite case.
5495 EXPECT_TRUE(MockHttpCache::WriteResponseInfo(entry, &response, true, false));
5496 truncated = true;
5497 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5498 EXPECT_FALSE(truncated);
5499 entry->Close();
5502 // Tests basic pickling/unpickling of HttpResponseInfo.
5503 TEST(HttpCache, PersistHttpResponseInfo) {
5504 // Set some fields (add more if needed.)
5505 HttpResponseInfo response1;
5506 response1.was_cached = false;
5507 response1.socket_address = HostPortPair("1.2.3.4", 80);
5508 response1.headers = new HttpResponseHeaders("HTTP/1.1 200 OK");
5510 // Pickle.
5511 base::Pickle pickle;
5512 response1.Persist(&pickle, false, false);
5514 // Unpickle.
5515 HttpResponseInfo response2;
5516 bool response_truncated;
5517 EXPECT_TRUE(response2.InitFromPickle(pickle, &response_truncated));
5518 EXPECT_FALSE(response_truncated);
5520 // Verify fields.
5521 EXPECT_TRUE(response2.was_cached); // InitFromPickle sets this flag.
5522 EXPECT_EQ("1.2.3.4", response2.socket_address.host());
5523 EXPECT_EQ(80, response2.socket_address.port());
5524 EXPECT_EQ("HTTP/1.1 200 OK", response2.headers->GetStatusLine());
5527 // Tests that we delete an entry when the request is cancelled before starting
5528 // to read from the network.
5529 TEST(HttpCache, DoomOnDestruction) {
5530 MockHttpCache cache;
5532 MockHttpRequest request(kSimpleGET_Transaction);
5534 Context* c = new Context();
5535 int rv = cache.CreateTransaction(&c->trans);
5536 ASSERT_EQ(OK, rv);
5538 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5539 if (rv == ERR_IO_PENDING)
5540 c->result = c->callback.WaitForResult();
5542 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5543 EXPECT_EQ(0, cache.disk_cache()->open_count());
5544 EXPECT_EQ(1, cache.disk_cache()->create_count());
5546 // Destroy the transaction. We only have the headers so we should delete this
5547 // entry.
5548 delete c;
5550 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5552 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5553 EXPECT_EQ(0, cache.disk_cache()->open_count());
5554 EXPECT_EQ(2, cache.disk_cache()->create_count());
5557 // Tests that we delete an entry when the request is cancelled if the response
5558 // does not have content-length and strong validators.
5559 TEST(HttpCache, DoomOnDestruction2) {
5560 MockHttpCache cache;
5562 MockHttpRequest request(kSimpleGET_Transaction);
5564 Context* c = new Context();
5565 int rv = cache.CreateTransaction(&c->trans);
5566 ASSERT_EQ(OK, rv);
5568 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5569 if (rv == ERR_IO_PENDING)
5570 rv = c->callback.WaitForResult();
5572 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5573 EXPECT_EQ(0, cache.disk_cache()->open_count());
5574 EXPECT_EQ(1, cache.disk_cache()->create_count());
5576 // Make sure that the entry has some data stored.
5577 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5578 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5579 if (rv == ERR_IO_PENDING)
5580 rv = c->callback.WaitForResult();
5581 EXPECT_EQ(buf->size(), rv);
5583 // Destroy the transaction.
5584 delete c;
5586 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5588 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5589 EXPECT_EQ(0, cache.disk_cache()->open_count());
5590 EXPECT_EQ(2, cache.disk_cache()->create_count());
5593 // Tests that we delete an entry when the request is cancelled if the response
5594 // has an "Accept-Ranges: none" header.
5595 TEST(HttpCache, DoomOnDestruction3) {
5596 MockHttpCache cache;
5598 MockTransaction transaction(kSimpleGET_Transaction);
5599 transaction.response_headers =
5600 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5601 "Content-Length: 22\n"
5602 "Accept-Ranges: none\n"
5603 "Etag: \"foopy\"\n";
5604 AddMockTransaction(&transaction);
5605 MockHttpRequest request(transaction);
5607 Context* c = new Context();
5608 int rv = cache.CreateTransaction(&c->trans);
5609 ASSERT_EQ(OK, rv);
5611 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5612 if (rv == ERR_IO_PENDING)
5613 rv = c->callback.WaitForResult();
5615 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5616 EXPECT_EQ(0, cache.disk_cache()->open_count());
5617 EXPECT_EQ(1, cache.disk_cache()->create_count());
5619 // Make sure that the entry has some data stored.
5620 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5621 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5622 if (rv == ERR_IO_PENDING)
5623 rv = c->callback.WaitForResult();
5624 EXPECT_EQ(buf->size(), rv);
5626 // Destroy the transaction.
5627 delete c;
5629 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
5631 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5632 EXPECT_EQ(0, cache.disk_cache()->open_count());
5633 EXPECT_EQ(2, cache.disk_cache()->create_count());
5635 RemoveMockTransaction(&transaction);
5638 // Tests that we mark an entry as incomplete when the request is cancelled.
5639 TEST(HttpCache, SetTruncatedFlag) {
5640 MockHttpCache cache;
5642 MockTransaction transaction(kSimpleGET_Transaction);
5643 transaction.response_headers =
5644 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5645 "Content-Length: 22\n"
5646 "Etag: \"foopy\"\n";
5647 AddMockTransaction(&transaction);
5648 MockHttpRequest request(transaction);
5650 scoped_ptr<Context> c(new Context());
5652 int rv = cache.CreateTransaction(&c->trans);
5653 ASSERT_EQ(OK, rv);
5655 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5656 if (rv == ERR_IO_PENDING)
5657 rv = c->callback.WaitForResult();
5659 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5660 EXPECT_EQ(0, cache.disk_cache()->open_count());
5661 EXPECT_EQ(1, cache.disk_cache()->create_count());
5663 // Make sure that the entry has some data stored.
5664 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(10));
5665 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5666 if (rv == ERR_IO_PENDING)
5667 rv = c->callback.WaitForResult();
5668 EXPECT_EQ(buf->size(), rv);
5670 // We want to cancel the request when the transaction is busy.
5671 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5672 EXPECT_EQ(ERR_IO_PENDING, rv);
5673 EXPECT_FALSE(c->callback.have_result());
5675 MockHttpCache::SetTestMode(TEST_MODE_SYNC_ALL);
5677 // Destroy the transaction.
5678 c->trans.reset();
5679 MockHttpCache::SetTestMode(0);
5682 // Make sure that we don't invoke the callback. We may have an issue if the
5683 // UrlRequestJob is killed directly (without cancelling the UrlRequest) so we
5684 // could end up with the transaction being deleted twice if we send any
5685 // notification from the transaction destructor (see http://crbug.com/31723).
5686 EXPECT_FALSE(c->callback.have_result());
5688 // Verify that the entry is marked as incomplete.
5689 disk_cache::Entry* entry;
5690 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
5691 HttpResponseInfo response;
5692 bool truncated = false;
5693 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5694 EXPECT_TRUE(truncated);
5695 entry->Close();
5697 RemoveMockTransaction(&transaction);
5700 // Tests that we don't mark an entry as truncated when we read everything.
5701 TEST(HttpCache, DontSetTruncatedFlag) {
5702 MockHttpCache cache;
5704 MockTransaction transaction(kSimpleGET_Transaction);
5705 transaction.response_headers =
5706 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
5707 "Content-Length: 22\n"
5708 "Etag: \"foopy\"\n";
5709 AddMockTransaction(&transaction);
5710 MockHttpRequest request(transaction);
5712 scoped_ptr<Context> c(new Context());
5713 int rv = cache.CreateTransaction(&c->trans);
5714 ASSERT_EQ(OK, rv);
5716 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5717 EXPECT_EQ(OK, c->callback.GetResult(rv));
5719 // Read everything.
5720 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(22));
5721 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5722 EXPECT_EQ(buf->size(), c->callback.GetResult(rv));
5724 // Destroy the transaction.
5725 c->trans.reset();
5727 // Verify that the entry is not marked as truncated.
5728 disk_cache::Entry* entry;
5729 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
5730 HttpResponseInfo response;
5731 bool truncated = true;
5732 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5733 EXPECT_FALSE(truncated);
5734 entry->Close();
5736 RemoveMockTransaction(&transaction);
5739 // Tests that we can continue with a request that was interrupted.
5740 TEST(HttpCache, GET_IncompleteResource) {
5741 MockHttpCache cache;
5742 AddMockTransaction(&kRangeGET_TransactionOK);
5744 std::string raw_headers("HTTP/1.1 200 OK\n"
5745 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5746 "ETag: \"foo\"\n"
5747 "Accept-Ranges: bytes\n"
5748 "Content-Length: 80\n");
5749 CreateTruncatedEntry(raw_headers, &cache);
5751 // Now make a regular request.
5752 std::string headers;
5753 MockTransaction transaction(kRangeGET_TransactionOK);
5754 transaction.request_headers = EXTRA_HEADER;
5755 transaction.data = kFullRangeData;
5756 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5758 // We update the headers with the ones received while revalidating.
5759 std::string expected_headers(
5760 "HTTP/1.1 200 OK\n"
5761 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5762 "Accept-Ranges: bytes\n"
5763 "ETag: \"foo\"\n"
5764 "Content-Length: 80\n");
5766 EXPECT_EQ(expected_headers, headers);
5767 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5768 EXPECT_EQ(1, cache.disk_cache()->open_count());
5769 EXPECT_EQ(1, cache.disk_cache()->create_count());
5771 // Verify that the disk entry was updated.
5772 disk_cache::Entry* entry;
5773 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5774 EXPECT_EQ(80, entry->GetDataSize(1));
5775 bool truncated = true;
5776 HttpResponseInfo response;
5777 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
5778 EXPECT_FALSE(truncated);
5779 entry->Close();
5781 RemoveMockTransaction(&kRangeGET_TransactionOK);
5784 // Tests the handling of no-store when revalidating a truncated entry.
5785 TEST(HttpCache, GET_IncompleteResource_NoStore) {
5786 MockHttpCache cache;
5787 AddMockTransaction(&kRangeGET_TransactionOK);
5789 std::string raw_headers("HTTP/1.1 200 OK\n"
5790 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5791 "ETag: \"foo\"\n"
5792 "Accept-Ranges: bytes\n"
5793 "Content-Length: 80\n");
5794 CreateTruncatedEntry(raw_headers, &cache);
5795 RemoveMockTransaction(&kRangeGET_TransactionOK);
5797 // Now make a regular request.
5798 MockTransaction transaction(kRangeGET_TransactionOK);
5799 transaction.request_headers = EXTRA_HEADER;
5800 std::string response_headers(transaction.response_headers);
5801 response_headers += ("Cache-Control: no-store\n");
5802 transaction.response_headers = response_headers.c_str();
5803 transaction.data = kFullRangeData;
5804 AddMockTransaction(&transaction);
5806 std::string headers;
5807 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5809 // We update the headers with the ones received while revalidating.
5810 std::string expected_headers(
5811 "HTTP/1.1 200 OK\n"
5812 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5813 "Accept-Ranges: bytes\n"
5814 "Cache-Control: no-store\n"
5815 "ETag: \"foo\"\n"
5816 "Content-Length: 80\n");
5818 EXPECT_EQ(expected_headers, headers);
5819 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5820 EXPECT_EQ(1, cache.disk_cache()->open_count());
5821 EXPECT_EQ(1, cache.disk_cache()->create_count());
5823 // Verify that the disk entry was deleted.
5824 disk_cache::Entry* entry;
5825 EXPECT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5826 RemoveMockTransaction(&transaction);
5829 // Tests cancelling a request after the server sent no-store.
5830 TEST(HttpCache, GET_IncompleteResource_Cancel) {
5831 MockHttpCache cache;
5832 AddMockTransaction(&kRangeGET_TransactionOK);
5834 std::string raw_headers("HTTP/1.1 200 OK\n"
5835 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5836 "ETag: \"foo\"\n"
5837 "Accept-Ranges: bytes\n"
5838 "Content-Length: 80\n");
5839 CreateTruncatedEntry(raw_headers, &cache);
5840 RemoveMockTransaction(&kRangeGET_TransactionOK);
5842 // Now make a regular request.
5843 MockTransaction transaction(kRangeGET_TransactionOK);
5844 transaction.request_headers = EXTRA_HEADER;
5845 std::string response_headers(transaction.response_headers);
5846 response_headers += ("Cache-Control: no-store\n");
5847 transaction.response_headers = response_headers.c_str();
5848 transaction.data = kFullRangeData;
5849 AddMockTransaction(&transaction);
5851 MockHttpRequest request(transaction);
5852 Context* c = new Context();
5854 int rv = cache.CreateTransaction(&c->trans);
5855 ASSERT_EQ(OK, rv);
5857 // Queue another request to this transaction. We have to start this request
5858 // before the first one gets the response from the server and dooms the entry,
5859 // otherwise it will just create a new entry without being queued to the first
5860 // request.
5861 Context* pending = new Context();
5862 ASSERT_EQ(OK, cache.CreateTransaction(&pending->trans));
5864 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5865 EXPECT_EQ(ERR_IO_PENDING,
5866 pending->trans->Start(&request, pending->callback.callback(),
5867 BoundNetLog()));
5868 EXPECT_EQ(OK, c->callback.GetResult(rv));
5870 // Make sure that the entry has some data stored.
5871 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(5));
5872 rv = c->trans->Read(buf.get(), buf->size(), c->callback.callback());
5873 EXPECT_EQ(5, c->callback.GetResult(rv));
5875 // Cancel the requests.
5876 delete c;
5877 delete pending;
5879 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5880 EXPECT_EQ(1, cache.disk_cache()->open_count());
5881 EXPECT_EQ(2, cache.disk_cache()->create_count());
5883 base::MessageLoop::current()->RunUntilIdle();
5884 RemoveMockTransaction(&transaction);
5887 // Tests that we delete truncated entries if the server changes its mind midway.
5888 TEST(HttpCache, GET_IncompleteResource2) {
5889 MockHttpCache cache;
5890 AddMockTransaction(&kRangeGET_TransactionOK);
5892 // Content-length will be intentionally bad.
5893 std::string raw_headers("HTTP/1.1 200 OK\n"
5894 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5895 "ETag: \"foo\"\n"
5896 "Accept-Ranges: bytes\n"
5897 "Content-Length: 50\n");
5898 CreateTruncatedEntry(raw_headers, &cache);
5900 // Now make a regular request. We expect the code to fail the validation and
5901 // retry the request without using byte ranges.
5902 std::string headers;
5903 MockTransaction transaction(kRangeGET_TransactionOK);
5904 transaction.request_headers = EXTRA_HEADER;
5905 transaction.data = "Not a range";
5906 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
5908 // The server will return 200 instead of a byte range.
5909 std::string expected_headers(
5910 "HTTP/1.1 200 OK\n"
5911 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n");
5913 EXPECT_EQ(expected_headers, headers);
5914 EXPECT_EQ(2, cache.network_layer()->transaction_count());
5915 EXPECT_EQ(1, cache.disk_cache()->open_count());
5916 EXPECT_EQ(1, cache.disk_cache()->create_count());
5918 // Verify that the disk entry was deleted.
5919 disk_cache::Entry* entry;
5920 ASSERT_FALSE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
5921 RemoveMockTransaction(&kRangeGET_TransactionOK);
5924 // Tests that we always validate a truncated request.
5925 TEST(HttpCache, GET_IncompleteResource3) {
5926 MockHttpCache cache;
5927 AddMockTransaction(&kRangeGET_TransactionOK);
5929 // This should not require validation for 10 hours.
5930 std::string raw_headers("HTTP/1.1 200 OK\n"
5931 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
5932 "ETag: \"foo\"\n"
5933 "Cache-Control: max-age= 36000\n"
5934 "Accept-Ranges: bytes\n"
5935 "Content-Length: 80\n");
5936 CreateTruncatedEntry(raw_headers, &cache);
5938 // Now make a regular request.
5939 std::string headers;
5940 MockTransaction transaction(kRangeGET_TransactionOK);
5941 transaction.request_headers = EXTRA_HEADER;
5942 transaction.data = kFullRangeData;
5944 scoped_ptr<Context> c(new Context);
5945 int rv = cache.CreateTransaction(&c->trans);
5946 ASSERT_EQ(OK, rv);
5948 MockHttpRequest request(transaction);
5949 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5950 EXPECT_EQ(OK, c->callback.GetResult(rv));
5952 // We should have checked with the server before finishing Start().
5953 EXPECT_EQ(1, cache.network_layer()->transaction_count());
5954 EXPECT_EQ(1, cache.disk_cache()->open_count());
5955 EXPECT_EQ(1, cache.disk_cache()->create_count());
5957 RemoveMockTransaction(&kRangeGET_TransactionOK);
5960 // Tests that we handle 401s for truncated resources.
5961 TEST(HttpCache, GET_IncompleteResourceWithAuth) {
5962 MockHttpCache cache;
5963 AddMockTransaction(&kRangeGET_TransactionOK);
5965 std::string raw_headers("HTTP/1.1 200 OK\n"
5966 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
5967 "ETag: \"foo\"\n"
5968 "Accept-Ranges: bytes\n"
5969 "Content-Length: 80\n");
5970 CreateTruncatedEntry(raw_headers, &cache);
5972 // Now make a regular request.
5973 MockTransaction transaction(kRangeGET_TransactionOK);
5974 transaction.request_headers = "X-Require-Mock-Auth: dummy\r\n"
5975 EXTRA_HEADER;
5976 transaction.data = kFullRangeData;
5977 RangeTransactionServer handler;
5979 scoped_ptr<Context> c(new Context);
5980 int rv = cache.CreateTransaction(&c->trans);
5981 ASSERT_EQ(OK, rv);
5983 MockHttpRequest request(transaction);
5984 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
5985 EXPECT_EQ(OK, c->callback.GetResult(rv));
5987 const HttpResponseInfo* response = c->trans->GetResponseInfo();
5988 ASSERT_TRUE(response);
5989 ASSERT_EQ(401, response->headers->response_code());
5990 rv = c->trans->RestartWithAuth(AuthCredentials(), c->callback.callback());
5991 EXPECT_EQ(OK, c->callback.GetResult(rv));
5992 response = c->trans->GetResponseInfo();
5993 ASSERT_TRUE(response);
5994 ASSERT_EQ(200, response->headers->response_code());
5996 ReadAndVerifyTransaction(c->trans.get(), transaction);
5997 c.reset(); // The destructor could delete the entry.
5998 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6000 // Verify that the entry was not deleted.
6001 disk_cache::Entry* entry;
6002 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6003 entry->Close();
6005 RemoveMockTransaction(&kRangeGET_TransactionOK);
6008 // Test that the transaction won't retry failed partial requests
6009 // after it starts reading data. http://crbug.com/474835
6010 TEST(HttpCache, TransactionRetryLimit) {
6011 MockHttpCache cache;
6013 // Cache 0-9, so that we have data to read before failing.
6014 ScopedMockTransaction transaction(kRangeGET_TransactionOK);
6015 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
6016 transaction.data = "rg: 00-09 ";
6018 // Write to the cache.
6019 RunTransactionTest(cache.http_cache(), transaction);
6020 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6022 // And now read from the cache and the network. 10-19 will get a
6023 // 401, but will have already returned 0-9.
6024 // We do not set X-Require-Mock-Auth because that causes the mock
6025 // network transaction to become IsReadyToRestartForAuth().
6026 transaction.request_headers =
6027 "Range: bytes = 0-79\r\n"
6028 "X-Require-Mock-Auth-Alt: dummy\r\n" EXTRA_HEADER;
6030 scoped_ptr<Context> c(new Context);
6031 int rv = cache.CreateTransaction(&c->trans);
6032 ASSERT_EQ(OK, rv);
6034 MockHttpRequest request(transaction);
6036 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
6037 if (rv == ERR_IO_PENDING)
6038 rv = c->callback.WaitForResult();
6039 std::string content;
6040 rv = ReadTransaction(c->trans.get(), &content);
6041 EXPECT_EQ(ERR_CACHE_AUTH_FAILURE_AFTER_READ, rv);
6044 // Tests that we cache a 200 response to the validation request.
6045 TEST(HttpCache, GET_IncompleteResource4) {
6046 MockHttpCache cache;
6047 AddMockTransaction(&kRangeGET_TransactionOK);
6049 std::string raw_headers("HTTP/1.1 200 OK\n"
6050 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
6051 "ETag: \"foo\"\n"
6052 "Accept-Ranges: bytes\n"
6053 "Content-Length: 80\n");
6054 CreateTruncatedEntry(raw_headers, &cache);
6056 // Now make a regular request.
6057 std::string headers;
6058 MockTransaction transaction(kRangeGET_TransactionOK);
6059 transaction.request_headers = EXTRA_HEADER;
6060 transaction.data = "Not a range";
6061 RangeTransactionServer handler;
6062 handler.set_bad_200(true);
6063 RunTransactionTestWithResponse(cache.http_cache(), transaction, &headers);
6065 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6066 EXPECT_EQ(1, cache.disk_cache()->open_count());
6067 EXPECT_EQ(1, cache.disk_cache()->create_count());
6069 // Verify that the disk entry was updated.
6070 disk_cache::Entry* entry;
6071 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6072 EXPECT_EQ(11, entry->GetDataSize(1));
6073 bool truncated = true;
6074 HttpResponseInfo response;
6075 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6076 EXPECT_FALSE(truncated);
6077 entry->Close();
6079 RemoveMockTransaction(&kRangeGET_TransactionOK);
6082 // Tests that when we cancel a request that was interrupted, we mark it again
6083 // as truncated.
6084 TEST(HttpCache, GET_CancelIncompleteResource) {
6085 MockHttpCache cache;
6086 AddMockTransaction(&kRangeGET_TransactionOK);
6088 std::string raw_headers("HTTP/1.1 200 OK\n"
6089 "Last-Modified: Sat, 18 Apr 2009 01:10:43 GMT\n"
6090 "ETag: \"foo\"\n"
6091 "Accept-Ranges: bytes\n"
6092 "Content-Length: 80\n");
6093 CreateTruncatedEntry(raw_headers, &cache);
6095 // Now make a regular request.
6096 MockTransaction transaction(kRangeGET_TransactionOK);
6097 transaction.request_headers = EXTRA_HEADER;
6099 MockHttpRequest request(transaction);
6100 Context* c = new Context();
6101 int rv = cache.CreateTransaction(&c->trans);
6102 ASSERT_EQ(OK, rv);
6104 rv = c->trans->Start(&request, c->callback.callback(), BoundNetLog());
6105 EXPECT_EQ(OK, c->callback.GetResult(rv));
6107 // Read 20 bytes from the cache, and 10 from the net.
6108 scoped_refptr<IOBuffer> buf(new IOBuffer(100));
6109 rv = c->trans->Read(buf.get(), 20, c->callback.callback());
6110 EXPECT_EQ(20, c->callback.GetResult(rv));
6111 rv = c->trans->Read(buf.get(), 10, c->callback.callback());
6112 EXPECT_EQ(10, c->callback.GetResult(rv));
6114 // At this point, we are already reading so canceling the request should leave
6115 // a truncated one.
6116 delete c;
6118 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6119 EXPECT_EQ(1, cache.disk_cache()->open_count());
6120 EXPECT_EQ(1, cache.disk_cache()->create_count());
6122 // Verify that the disk entry was updated: now we have 30 bytes.
6123 disk_cache::Entry* entry;
6124 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6125 EXPECT_EQ(30, entry->GetDataSize(1));
6126 bool truncated = false;
6127 HttpResponseInfo response;
6128 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6129 EXPECT_TRUE(truncated);
6130 entry->Close();
6131 RemoveMockTransaction(&kRangeGET_TransactionOK);
6134 // Tests that we can handle range requests when we have a truncated entry.
6135 TEST(HttpCache, RangeGET_IncompleteResource) {
6136 MockHttpCache cache;
6137 AddMockTransaction(&kRangeGET_TransactionOK);
6139 // Content-length will be intentionally bogus.
6140 std::string raw_headers("HTTP/1.1 200 OK\n"
6141 "Last-Modified: something\n"
6142 "ETag: \"foo\"\n"
6143 "Accept-Ranges: bytes\n"
6144 "Content-Length: 10\n");
6145 CreateTruncatedEntry(raw_headers, &cache);
6147 // Now make a range request.
6148 std::string headers;
6149 RunTransactionTestWithResponse(cache.http_cache(), kRangeGET_TransactionOK,
6150 &headers);
6152 Verify206Response(headers, 40, 49);
6153 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6154 EXPECT_EQ(1, cache.disk_cache()->open_count());
6155 EXPECT_EQ(2, cache.disk_cache()->create_count());
6157 RemoveMockTransaction(&kRangeGET_TransactionOK);
6160 TEST(HttpCache, SyncRead) {
6161 MockHttpCache cache;
6163 // This test ensures that a read that completes synchronously does not cause
6164 // any problems.
6166 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6167 transaction.test_mode |= (TEST_MODE_SYNC_CACHE_START |
6168 TEST_MODE_SYNC_CACHE_READ |
6169 TEST_MODE_SYNC_CACHE_WRITE);
6171 MockHttpRequest r1(transaction),
6172 r2(transaction),
6173 r3(transaction);
6175 TestTransactionConsumer c1(DEFAULT_PRIORITY, cache.http_cache()),
6176 c2(DEFAULT_PRIORITY, cache.http_cache()),
6177 c3(DEFAULT_PRIORITY, cache.http_cache());
6179 c1.Start(&r1, BoundNetLog());
6181 r2.load_flags |= LOAD_ONLY_FROM_CACHE;
6182 c2.Start(&r2, BoundNetLog());
6184 r3.load_flags |= LOAD_ONLY_FROM_CACHE;
6185 c3.Start(&r3, BoundNetLog());
6187 base::MessageLoop::current()->Run();
6189 EXPECT_TRUE(c1.is_done());
6190 EXPECT_TRUE(c2.is_done());
6191 EXPECT_TRUE(c3.is_done());
6193 EXPECT_EQ(OK, c1.error());
6194 EXPECT_EQ(OK, c2.error());
6195 EXPECT_EQ(OK, c3.error());
6198 TEST(HttpCache, ValidationResultsIn200) {
6199 MockHttpCache cache;
6201 // This test ensures that a conditional request, which results in a 200
6202 // instead of a 304, properly truncates the existing response data.
6204 // write to the cache
6205 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
6207 // force this transaction to validate the cache
6208 MockTransaction transaction(kETagGET_Transaction);
6209 transaction.load_flags |= LOAD_VALIDATE_CACHE;
6210 RunTransactionTest(cache.http_cache(), transaction);
6212 // read from the cache
6213 RunTransactionTest(cache.http_cache(), kETagGET_Transaction);
6216 TEST(HttpCache, CachedRedirect) {
6217 MockHttpCache cache;
6219 ScopedMockTransaction kTestTransaction(kSimpleGET_Transaction);
6220 kTestTransaction.status = "HTTP/1.1 301 Moved Permanently";
6221 kTestTransaction.response_headers = "Location: http://www.bar.com/\n";
6223 MockHttpRequest request(kTestTransaction);
6224 TestCompletionCallback callback;
6226 // Write to the cache.
6228 scoped_ptr<HttpTransaction> trans;
6229 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6231 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6232 if (rv == ERR_IO_PENDING)
6233 rv = callback.WaitForResult();
6234 ASSERT_EQ(OK, rv);
6236 const HttpResponseInfo* info = trans->GetResponseInfo();
6237 ASSERT_TRUE(info);
6239 EXPECT_EQ(info->headers->response_code(), 301);
6241 std::string location;
6242 info->headers->EnumerateHeader(NULL, "Location", &location);
6243 EXPECT_EQ(location, "http://www.bar.com/");
6245 // Mark the transaction as completed so it is cached.
6246 trans->DoneReading();
6248 // Destroy transaction when going out of scope. We have not actually
6249 // read the response body -- want to test that it is still getting cached.
6251 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6252 EXPECT_EQ(0, cache.disk_cache()->open_count());
6253 EXPECT_EQ(1, cache.disk_cache()->create_count());
6255 // Active entries in the cache are not retired synchronously. Make
6256 // sure the next run hits the MockHttpCache and open_count is
6257 // correct.
6258 base::MessageLoop::current()->RunUntilIdle();
6260 // Read from the cache.
6262 scoped_ptr<HttpTransaction> trans;
6263 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6265 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6266 if (rv == ERR_IO_PENDING)
6267 rv = callback.WaitForResult();
6268 ASSERT_EQ(OK, rv);
6270 const HttpResponseInfo* info = trans->GetResponseInfo();
6271 ASSERT_TRUE(info);
6273 EXPECT_EQ(info->headers->response_code(), 301);
6275 std::string location;
6276 info->headers->EnumerateHeader(NULL, "Location", &location);
6277 EXPECT_EQ(location, "http://www.bar.com/");
6279 // Mark the transaction as completed so it is cached.
6280 trans->DoneReading();
6282 // Destroy transaction when going out of scope. We have not actually
6283 // read the response body -- want to test that it is still getting cached.
6285 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6286 EXPECT_EQ(1, cache.disk_cache()->open_count());
6287 EXPECT_EQ(1, cache.disk_cache()->create_count());
6290 // Verify that no-cache resources are stored in cache, but are not fetched from
6291 // cache during normal loads.
6292 TEST(HttpCache, CacheControlNoCacheNormalLoad) {
6293 MockHttpCache cache;
6295 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6296 transaction.response_headers = "cache-control: no-cache\n";
6298 // Initial load.
6299 RunTransactionTest(cache.http_cache(), transaction);
6301 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6302 EXPECT_EQ(0, cache.disk_cache()->open_count());
6303 EXPECT_EQ(1, cache.disk_cache()->create_count());
6305 // Try loading again; it should result in a network fetch.
6306 RunTransactionTest(cache.http_cache(), transaction);
6308 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6309 EXPECT_EQ(1, cache.disk_cache()->open_count());
6310 EXPECT_EQ(1, cache.disk_cache()->create_count());
6312 disk_cache::Entry* entry;
6313 EXPECT_TRUE(cache.OpenBackendEntry(transaction.url, &entry));
6314 entry->Close();
6317 // Verify that no-cache resources are stored in cache and fetched from cache
6318 // when the LOAD_PREFERRING_CACHE flag is set.
6319 TEST(HttpCache, CacheControlNoCacheHistoryLoad) {
6320 MockHttpCache cache;
6322 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6323 transaction.response_headers = "cache-control: no-cache\n";
6325 // Initial load.
6326 RunTransactionTest(cache.http_cache(), transaction);
6328 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6329 EXPECT_EQ(0, cache.disk_cache()->open_count());
6330 EXPECT_EQ(1, cache.disk_cache()->create_count());
6332 // Try loading again with LOAD_PREFERRING_CACHE.
6333 transaction.load_flags = LOAD_PREFERRING_CACHE;
6334 RunTransactionTest(cache.http_cache(), transaction);
6336 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6337 EXPECT_EQ(1, cache.disk_cache()->open_count());
6338 EXPECT_EQ(1, cache.disk_cache()->create_count());
6340 disk_cache::Entry* entry;
6341 EXPECT_TRUE(cache.OpenBackendEntry(transaction.url, &entry));
6342 entry->Close();
6345 TEST(HttpCache, CacheControlNoStore) {
6346 MockHttpCache cache;
6348 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6349 transaction.response_headers = "cache-control: no-store\n";
6351 // initial load
6352 RunTransactionTest(cache.http_cache(), transaction);
6354 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6355 EXPECT_EQ(0, cache.disk_cache()->open_count());
6356 EXPECT_EQ(1, cache.disk_cache()->create_count());
6358 // try loading again; it should result in a network fetch
6359 RunTransactionTest(cache.http_cache(), transaction);
6361 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6362 EXPECT_EQ(0, cache.disk_cache()->open_count());
6363 EXPECT_EQ(2, cache.disk_cache()->create_count());
6365 disk_cache::Entry* entry;
6366 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6369 TEST(HttpCache, CacheControlNoStore2) {
6370 // this test is similar to the above test, except that the initial response
6371 // is cachable, but when it is validated, no-store is received causing the
6372 // cached document to be deleted.
6373 MockHttpCache cache;
6375 ScopedMockTransaction transaction(kETagGET_Transaction);
6377 // initial load
6378 RunTransactionTest(cache.http_cache(), transaction);
6380 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6381 EXPECT_EQ(0, cache.disk_cache()->open_count());
6382 EXPECT_EQ(1, cache.disk_cache()->create_count());
6384 // try loading again; it should result in a network fetch
6385 transaction.load_flags = LOAD_VALIDATE_CACHE;
6386 transaction.response_headers = "cache-control: no-store\n";
6387 RunTransactionTest(cache.http_cache(), transaction);
6389 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6390 EXPECT_EQ(1, cache.disk_cache()->open_count());
6391 EXPECT_EQ(1, cache.disk_cache()->create_count());
6393 disk_cache::Entry* entry;
6394 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6397 TEST(HttpCache, CacheControlNoStore3) {
6398 // this test is similar to the above test, except that the response is a 304
6399 // instead of a 200. this should never happen in practice, but it seems like
6400 // a good thing to verify that we still destroy the cache entry.
6401 MockHttpCache cache;
6403 ScopedMockTransaction transaction(kETagGET_Transaction);
6405 // initial load
6406 RunTransactionTest(cache.http_cache(), transaction);
6408 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6409 EXPECT_EQ(0, cache.disk_cache()->open_count());
6410 EXPECT_EQ(1, cache.disk_cache()->create_count());
6412 // try loading again; it should result in a network fetch
6413 transaction.load_flags = LOAD_VALIDATE_CACHE;
6414 transaction.response_headers = "cache-control: no-store\n";
6415 transaction.status = "HTTP/1.1 304 Not Modified";
6416 RunTransactionTest(cache.http_cache(), transaction);
6418 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6419 EXPECT_EQ(1, cache.disk_cache()->open_count());
6420 EXPECT_EQ(1, cache.disk_cache()->create_count());
6422 disk_cache::Entry* entry;
6423 EXPECT_FALSE(cache.OpenBackendEntry(transaction.url, &entry));
6426 // Ensure that we don't cache requests served over bad HTTPS.
6427 TEST(HttpCache, SimpleGET_SSLError) {
6428 MockHttpCache cache;
6430 MockTransaction transaction = kSimpleGET_Transaction;
6431 transaction.cert_status = CERT_STATUS_REVOKED;
6432 ScopedMockTransaction scoped_transaction(transaction);
6434 // write to the cache
6435 RunTransactionTest(cache.http_cache(), transaction);
6437 // Test that it was not cached.
6438 transaction.load_flags |= LOAD_ONLY_FROM_CACHE;
6440 MockHttpRequest request(transaction);
6441 TestCompletionCallback callback;
6443 scoped_ptr<HttpTransaction> trans;
6444 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6446 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6447 if (rv == ERR_IO_PENDING)
6448 rv = callback.WaitForResult();
6449 ASSERT_EQ(ERR_CACHE_MISS, rv);
6452 // Ensure that we don't crash by if left-behind transactions.
6453 TEST(HttpCache, OutlivedTransactions) {
6454 MockHttpCache* cache = new MockHttpCache;
6456 scoped_ptr<HttpTransaction> trans;
6457 EXPECT_EQ(OK, cache->CreateTransaction(&trans));
6459 delete cache;
6460 trans.reset();
6463 // Test that the disabled mode works.
6464 TEST(HttpCache, CacheDisabledMode) {
6465 MockHttpCache cache;
6467 // write to the cache
6468 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6470 // go into disabled mode
6471 cache.http_cache()->set_mode(HttpCache::DISABLE);
6473 // force this transaction to write to the cache again
6474 MockTransaction transaction(kSimpleGET_Transaction);
6476 RunTransactionTest(cache.http_cache(), transaction);
6478 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6479 EXPECT_EQ(0, cache.disk_cache()->open_count());
6480 EXPECT_EQ(1, cache.disk_cache()->create_count());
6483 // Other tests check that the response headers of the cached response
6484 // get updated on 304. Here we specifically check that the
6485 // HttpResponseHeaders::request_time and HttpResponseHeaders::response_time
6486 // fields also gets updated.
6487 // http://crbug.com/20594.
6488 TEST(HttpCache, UpdatesRequestResponseTimeOn304) {
6489 MockHttpCache cache;
6491 const char kUrl[] = "http://foobar";
6492 const char kData[] = "body";
6494 MockTransaction mock_network_response = { 0 };
6495 mock_network_response.url = kUrl;
6497 AddMockTransaction(&mock_network_response);
6499 // Request |kUrl|, causing |kNetResponse1| to be written to the cache.
6501 MockTransaction request = { 0 };
6502 request.url = kUrl;
6503 request.method = "GET";
6504 request.request_headers = "\r\n";
6505 request.data = kData;
6507 static const Response kNetResponse1 = {
6508 "HTTP/1.1 200 OK",
6509 "Date: Fri, 12 Jun 2009 21:46:42 GMT\n"
6510 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
6511 kData
6514 kNetResponse1.AssignTo(&mock_network_response);
6516 RunTransactionTest(cache.http_cache(), request);
6518 // Request |kUrl| again, this time validating the cache and getting
6519 // a 304 back.
6521 request.load_flags = LOAD_VALIDATE_CACHE;
6523 static const Response kNetResponse2 = {
6524 "HTTP/1.1 304 Not Modified",
6525 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n",
6529 kNetResponse2.AssignTo(&mock_network_response);
6531 base::Time request_time = base::Time() + base::TimeDelta::FromHours(1234);
6532 base::Time response_time = base::Time() + base::TimeDelta::FromHours(1235);
6534 mock_network_response.request_time = request_time;
6535 mock_network_response.response_time = response_time;
6537 HttpResponseInfo response;
6538 RunTransactionTestWithResponseInfo(cache.http_cache(), request, &response);
6540 // The request and response times should have been updated.
6541 EXPECT_EQ(request_time.ToInternalValue(),
6542 response.request_time.ToInternalValue());
6543 EXPECT_EQ(response_time.ToInternalValue(),
6544 response.response_time.ToInternalValue());
6546 std::string headers;
6547 response.headers->GetNormalizedHeaders(&headers);
6549 EXPECT_EQ("HTTP/1.1 200 OK\n"
6550 "Date: Wed, 22 Jul 2009 03:15:26 GMT\n"
6551 "Last-Modified: Wed, 06 Feb 2008 22:38:21 GMT\n",
6552 headers);
6554 RemoveMockTransaction(&mock_network_response);
6557 // Tests that we can write metadata to an entry.
6558 TEST(HttpCache, WriteMetadata_OK) {
6559 MockHttpCache cache;
6561 // Write to the cache
6562 HttpResponseInfo response;
6563 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6564 &response);
6565 EXPECT_TRUE(response.metadata.get() == NULL);
6567 // Trivial call.
6568 cache.http_cache()->WriteMetadata(GURL("foo"), DEFAULT_PRIORITY, Time::Now(),
6569 NULL, 0);
6571 // Write meta data to the same entry.
6572 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6573 memset(buf->data(), 0, buf->size());
6574 base::strlcpy(buf->data(), "Hi there", buf->size());
6575 cache.http_cache()->WriteMetadata(GURL(kSimpleGET_Transaction.url),
6576 DEFAULT_PRIORITY, response.response_time,
6577 buf.get(), buf->size());
6579 // Release the buffer before the operation takes place.
6580 buf = NULL;
6582 // Makes sure we finish pending operations.
6583 base::MessageLoop::current()->RunUntilIdle();
6585 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6586 &response);
6587 ASSERT_TRUE(response.metadata.get() != NULL);
6588 EXPECT_EQ(50, response.metadata->size());
6589 EXPECT_EQ(0, strcmp(response.metadata->data(), "Hi there"));
6591 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6592 EXPECT_EQ(2, cache.disk_cache()->open_count());
6593 EXPECT_EQ(1, cache.disk_cache()->create_count());
6596 // Tests that we only write metadata to an entry if the time stamp matches.
6597 TEST(HttpCache, WriteMetadata_Fail) {
6598 MockHttpCache cache;
6600 // Write to the cache
6601 HttpResponseInfo response;
6602 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6603 &response);
6604 EXPECT_TRUE(response.metadata.get() == NULL);
6606 // Attempt to write meta data to the same entry.
6607 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6608 memset(buf->data(), 0, buf->size());
6609 base::strlcpy(buf->data(), "Hi there", buf->size());
6610 base::Time expected_time = response.response_time -
6611 base::TimeDelta::FromMilliseconds(20);
6612 cache.http_cache()->WriteMetadata(GURL(kSimpleGET_Transaction.url),
6613 DEFAULT_PRIORITY, expected_time, buf.get(),
6614 buf->size());
6616 // Makes sure we finish pending operations.
6617 base::MessageLoop::current()->RunUntilIdle();
6619 RunTransactionTestWithResponseInfo(cache.http_cache(), kSimpleGET_Transaction,
6620 &response);
6621 EXPECT_TRUE(response.metadata.get() == NULL);
6623 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6624 EXPECT_EQ(2, cache.disk_cache()->open_count());
6625 EXPECT_EQ(1, cache.disk_cache()->create_count());
6628 // Tests that we can read metadata after validating the entry and with READ mode
6629 // transactions.
6630 TEST(HttpCache, ReadMetadata) {
6631 MockHttpCache cache;
6633 // Write to the cache
6634 HttpResponseInfo response;
6635 RunTransactionTestWithResponseInfo(cache.http_cache(),
6636 kTypicalGET_Transaction, &response);
6637 EXPECT_TRUE(response.metadata.get() == NULL);
6639 // Write meta data to the same entry.
6640 scoped_refptr<IOBufferWithSize> buf(new IOBufferWithSize(50));
6641 memset(buf->data(), 0, buf->size());
6642 base::strlcpy(buf->data(), "Hi there", buf->size());
6643 cache.http_cache()->WriteMetadata(GURL(kTypicalGET_Transaction.url),
6644 DEFAULT_PRIORITY, response.response_time,
6645 buf.get(), buf->size());
6647 // Makes sure we finish pending operations.
6648 base::MessageLoop::current()->RunUntilIdle();
6650 // Start with a READ mode transaction.
6651 MockTransaction trans1(kTypicalGET_Transaction);
6652 trans1.load_flags = LOAD_ONLY_FROM_CACHE;
6654 RunTransactionTestWithResponseInfo(cache.http_cache(), trans1, &response);
6655 ASSERT_TRUE(response.metadata.get() != NULL);
6656 EXPECT_EQ(50, response.metadata->size());
6657 EXPECT_EQ(0, strcmp(response.metadata->data(), "Hi there"));
6659 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6660 EXPECT_EQ(2, cache.disk_cache()->open_count());
6661 EXPECT_EQ(1, cache.disk_cache()->create_count());
6662 base::MessageLoop::current()->RunUntilIdle();
6664 // Now make sure that the entry is re-validated with the server.
6665 trans1.load_flags = LOAD_VALIDATE_CACHE;
6666 trans1.status = "HTTP/1.1 304 Not Modified";
6667 AddMockTransaction(&trans1);
6669 response.metadata = NULL;
6670 RunTransactionTestWithResponseInfo(cache.http_cache(), trans1, &response);
6671 EXPECT_TRUE(response.metadata.get() != NULL);
6673 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6674 EXPECT_EQ(3, cache.disk_cache()->open_count());
6675 EXPECT_EQ(1, cache.disk_cache()->create_count());
6676 base::MessageLoop::current()->RunUntilIdle();
6677 RemoveMockTransaction(&trans1);
6679 // Now return 200 when validating the entry so the metadata will be lost.
6680 MockTransaction trans2(kTypicalGET_Transaction);
6681 trans2.load_flags = LOAD_VALIDATE_CACHE;
6682 RunTransactionTestWithResponseInfo(cache.http_cache(), trans2, &response);
6683 EXPECT_TRUE(response.metadata.get() == NULL);
6685 EXPECT_EQ(3, cache.network_layer()->transaction_count());
6686 EXPECT_EQ(4, cache.disk_cache()->open_count());
6687 EXPECT_EQ(1, cache.disk_cache()->create_count());
6690 // Tests that we don't mark entries as truncated when a filter detects the end
6691 // of the stream.
6692 TEST(HttpCache, FilterCompletion) {
6693 MockHttpCache cache;
6694 TestCompletionCallback callback;
6697 scoped_ptr<HttpTransaction> trans;
6698 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6700 MockHttpRequest request(kSimpleGET_Transaction);
6701 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6702 EXPECT_EQ(OK, callback.GetResult(rv));
6704 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6705 rv = trans->Read(buf.get(), 256, callback.callback());
6706 EXPECT_GT(callback.GetResult(rv), 0);
6708 // Now make sure that the entry is preserved.
6709 trans->DoneReading();
6712 // Make sure that the ActiveEntry is gone.
6713 base::MessageLoop::current()->RunUntilIdle();
6715 // Read from the cache.
6716 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6718 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6719 EXPECT_EQ(1, cache.disk_cache()->open_count());
6720 EXPECT_EQ(1, cache.disk_cache()->create_count());
6723 // Tests that we don't mark entries as truncated and release the cache
6724 // entry when DoneReading() is called before any Read() calls, such as
6725 // for a redirect.
6726 TEST(HttpCache, DoneReading) {
6727 MockHttpCache cache;
6728 TestCompletionCallback callback;
6730 ScopedMockTransaction transaction(kSimpleGET_Transaction);
6731 transaction.data = "";
6733 scoped_ptr<HttpTransaction> trans;
6734 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6736 MockHttpRequest request(transaction);
6737 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6738 EXPECT_EQ(OK, callback.GetResult(rv));
6740 trans->DoneReading();
6741 // Leave the transaction around.
6743 // Make sure that the ActiveEntry is gone.
6744 base::MessageLoop::current()->RunUntilIdle();
6746 // Read from the cache. This should not deadlock.
6747 RunTransactionTest(cache.http_cache(), transaction);
6749 EXPECT_EQ(1, cache.network_layer()->transaction_count());
6750 EXPECT_EQ(1, cache.disk_cache()->open_count());
6751 EXPECT_EQ(1, cache.disk_cache()->create_count());
6754 // Tests that we stop caching when told.
6755 TEST(HttpCache, StopCachingDeletesEntry) {
6756 MockHttpCache cache;
6757 TestCompletionCallback callback;
6758 MockHttpRequest request(kSimpleGET_Transaction);
6761 scoped_ptr<HttpTransaction> trans;
6762 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6764 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6765 EXPECT_EQ(OK, callback.GetResult(rv));
6767 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6768 rv = trans->Read(buf.get(), 10, callback.callback());
6769 EXPECT_EQ(10, callback.GetResult(rv));
6771 trans->StopCaching();
6773 // We should be able to keep reading.
6774 rv = trans->Read(buf.get(), 256, callback.callback());
6775 EXPECT_GT(callback.GetResult(rv), 0);
6776 rv = trans->Read(buf.get(), 256, callback.callback());
6777 EXPECT_EQ(0, callback.GetResult(rv));
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, even if DoneReading is called
6792 // after StopCaching.
6793 TEST(HttpCache, StopCachingThenDoneReadingDeletesEntry) {
6794 MockHttpCache cache;
6795 TestCompletionCallback callback;
6796 MockHttpRequest request(kSimpleGET_Transaction);
6799 scoped_ptr<HttpTransaction> trans;
6800 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6802 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6803 EXPECT_EQ(OK, callback.GetResult(rv));
6805 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6806 rv = trans->Read(buf.get(), 10, callback.callback());
6807 EXPECT_EQ(10, callback.GetResult(rv));
6809 trans->StopCaching();
6811 // We should be able to keep reading.
6812 rv = trans->Read(buf.get(), 256, callback.callback());
6813 EXPECT_GT(callback.GetResult(rv), 0);
6814 rv = trans->Read(buf.get(), 256, callback.callback());
6815 EXPECT_EQ(0, callback.GetResult(rv));
6817 // We should be able to call DoneReading.
6818 trans->DoneReading();
6821 // Make sure that the ActiveEntry is gone.
6822 base::MessageLoop::current()->RunUntilIdle();
6824 // Verify that the entry is gone.
6825 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6827 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6828 EXPECT_EQ(0, cache.disk_cache()->open_count());
6829 EXPECT_EQ(2, cache.disk_cache()->create_count());
6832 // Tests that we stop caching when told, when using auth.
6833 TEST(HttpCache, StopCachingWithAuthDeletesEntry) {
6834 MockHttpCache cache;
6835 TestCompletionCallback callback;
6836 MockTransaction mock_transaction(kSimpleGET_Transaction);
6837 mock_transaction.status = "HTTP/1.1 401 Unauthorized";
6838 AddMockTransaction(&mock_transaction);
6839 MockHttpRequest request(mock_transaction);
6842 scoped_ptr<HttpTransaction> trans;
6843 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6845 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6846 EXPECT_EQ(OK, callback.GetResult(rv));
6848 trans->StopCaching();
6850 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6851 rv = trans->Read(buf.get(), 10, callback.callback());
6852 EXPECT_EQ(callback.GetResult(rv), 10);
6854 RemoveMockTransaction(&mock_transaction);
6856 // Make sure that the ActiveEntry is gone.
6857 base::MessageLoop::current()->RunUntilIdle();
6859 // Verify that the entry is gone.
6860 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6862 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6863 EXPECT_EQ(0, cache.disk_cache()->open_count());
6864 EXPECT_EQ(2, cache.disk_cache()->create_count());
6867 // Tests that when we are told to stop caching we don't throw away valid data.
6868 TEST(HttpCache, StopCachingSavesEntry) {
6869 MockHttpCache cache;
6870 TestCompletionCallback callback;
6871 MockHttpRequest request(kSimpleGET_Transaction);
6874 scoped_ptr<HttpTransaction> trans;
6875 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6877 // Force a response that can be resumed.
6878 MockTransaction mock_transaction(kSimpleGET_Transaction);
6879 AddMockTransaction(&mock_transaction);
6880 mock_transaction.response_headers = "Cache-Control: max-age=10000\n"
6881 "Content-Length: 42\n"
6882 "Etag: \"foo\"\n";
6884 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6885 EXPECT_EQ(OK, callback.GetResult(rv));
6887 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6888 rv = trans->Read(buf.get(), 10, callback.callback());
6889 EXPECT_EQ(callback.GetResult(rv), 10);
6891 trans->StopCaching();
6893 // We should be able to keep reading.
6894 rv = trans->Read(buf.get(), 256, callback.callback());
6895 EXPECT_GT(callback.GetResult(rv), 0);
6896 rv = trans->Read(buf.get(), 256, callback.callback());
6897 EXPECT_EQ(callback.GetResult(rv), 0);
6899 RemoveMockTransaction(&mock_transaction);
6902 // Verify that the entry is marked as incomplete.
6903 disk_cache::Entry* entry;
6904 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
6905 HttpResponseInfo response;
6906 bool truncated = false;
6907 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6908 EXPECT_TRUE(truncated);
6909 entry->Close();
6912 // Tests that we handle truncated enries when StopCaching is called.
6913 TEST(HttpCache, StopCachingTruncatedEntry) {
6914 MockHttpCache cache;
6915 TestCompletionCallback callback;
6916 MockHttpRequest request(kRangeGET_TransactionOK);
6917 request.extra_headers.Clear();
6918 request.extra_headers.AddHeaderFromString(EXTRA_HEADER_LINE);
6919 AddMockTransaction(&kRangeGET_TransactionOK);
6921 std::string raw_headers("HTTP/1.1 200 OK\n"
6922 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
6923 "ETag: \"foo\"\n"
6924 "Accept-Ranges: bytes\n"
6925 "Content-Length: 80\n");
6926 CreateTruncatedEntry(raw_headers, &cache);
6929 // Now make a regular request.
6930 scoped_ptr<HttpTransaction> trans;
6931 ASSERT_EQ(OK, cache.CreateTransaction(&trans));
6933 int rv = trans->Start(&request, callback.callback(), BoundNetLog());
6934 EXPECT_EQ(OK, callback.GetResult(rv));
6936 scoped_refptr<IOBuffer> buf(new IOBuffer(256));
6937 rv = trans->Read(buf.get(), 10, callback.callback());
6938 EXPECT_EQ(callback.GetResult(rv), 10);
6940 // This is actually going to do nothing.
6941 trans->StopCaching();
6943 // We should be able to keep reading.
6944 rv = trans->Read(buf.get(), 256, callback.callback());
6945 EXPECT_GT(callback.GetResult(rv), 0);
6946 rv = trans->Read(buf.get(), 256, callback.callback());
6947 EXPECT_GT(callback.GetResult(rv), 0);
6948 rv = trans->Read(buf.get(), 256, callback.callback());
6949 EXPECT_EQ(callback.GetResult(rv), 0);
6952 // Verify that the disk entry was updated.
6953 disk_cache::Entry* entry;
6954 ASSERT_TRUE(cache.OpenBackendEntry(kRangeGET_TransactionOK.url, &entry));
6955 EXPECT_EQ(80, entry->GetDataSize(1));
6956 bool truncated = true;
6957 HttpResponseInfo response;
6958 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
6959 EXPECT_FALSE(truncated);
6960 entry->Close();
6962 RemoveMockTransaction(&kRangeGET_TransactionOK);
6965 // Tests that we detect truncated resources from the net when there is
6966 // a Content-Length header.
6967 TEST(HttpCache, TruncatedByContentLength) {
6968 MockHttpCache cache;
6969 TestCompletionCallback callback;
6971 MockTransaction transaction(kSimpleGET_Transaction);
6972 AddMockTransaction(&transaction);
6973 transaction.response_headers = "Cache-Control: max-age=10000\n"
6974 "Content-Length: 100\n";
6975 RunTransactionTest(cache.http_cache(), transaction);
6976 RemoveMockTransaction(&transaction);
6978 // Read from the cache.
6979 RunTransactionTest(cache.http_cache(), kSimpleGET_Transaction);
6981 EXPECT_EQ(2, cache.network_layer()->transaction_count());
6982 EXPECT_EQ(0, cache.disk_cache()->open_count());
6983 EXPECT_EQ(2, cache.disk_cache()->create_count());
6986 // Tests that we actually flag entries as truncated when we detect an error
6987 // from the net.
6988 TEST(HttpCache, TruncatedByContentLength2) {
6989 MockHttpCache cache;
6990 TestCompletionCallback callback;
6992 MockTransaction transaction(kSimpleGET_Transaction);
6993 AddMockTransaction(&transaction);
6994 transaction.response_headers = "Cache-Control: max-age=10000\n"
6995 "Content-Length: 100\n"
6996 "Etag: \"foo\"\n";
6997 RunTransactionTest(cache.http_cache(), transaction);
6998 RemoveMockTransaction(&transaction);
7000 // Verify that the entry is marked as incomplete.
7001 disk_cache::Entry* entry;
7002 ASSERT_TRUE(cache.OpenBackendEntry(kSimpleGET_Transaction.url, &entry));
7003 HttpResponseInfo response;
7004 bool truncated = false;
7005 EXPECT_TRUE(MockHttpCache::ReadResponseInfo(entry, &response, &truncated));
7006 EXPECT_TRUE(truncated);
7007 entry->Close();
7010 // Make sure that calling SetPriority on a cache transaction passes on
7011 // its priority updates to its underlying network transaction.
7012 TEST(HttpCache, SetPriority) {
7013 MockHttpCache cache;
7015 scoped_ptr<HttpTransaction> trans;
7016 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(IDLE, &trans));
7018 // Shouldn't crash, but doesn't do anything either.
7019 trans->SetPriority(LOW);
7021 EXPECT_FALSE(cache.network_layer()->last_transaction());
7022 EXPECT_EQ(DEFAULT_PRIORITY,
7023 cache.network_layer()->last_create_transaction_priority());
7025 HttpRequestInfo info;
7026 info.url = GURL(kSimpleGET_Transaction.url);
7027 TestCompletionCallback callback;
7028 EXPECT_EQ(ERR_IO_PENDING,
7029 trans->Start(&info, callback.callback(), BoundNetLog()));
7031 EXPECT_TRUE(cache.network_layer()->last_transaction());
7032 if (cache.network_layer()->last_transaction()) {
7033 EXPECT_EQ(LOW, cache.network_layer()->last_create_transaction_priority());
7034 EXPECT_EQ(LOW, cache.network_layer()->last_transaction()->priority());
7037 trans->SetPriority(HIGHEST);
7039 if (cache.network_layer()->last_transaction()) {
7040 EXPECT_EQ(LOW, cache.network_layer()->last_create_transaction_priority());
7041 EXPECT_EQ(HIGHEST, cache.network_layer()->last_transaction()->priority());
7044 EXPECT_EQ(OK, callback.WaitForResult());
7047 // Make sure that calling SetWebSocketHandshakeStreamCreateHelper on a cache
7048 // transaction passes on its argument to the underlying network transaction.
7049 TEST(HttpCache, SetWebSocketHandshakeStreamCreateHelper) {
7050 MockHttpCache cache;
7052 FakeWebSocketHandshakeStreamCreateHelper create_helper;
7053 scoped_ptr<HttpTransaction> trans;
7054 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(IDLE, &trans));
7056 EXPECT_FALSE(cache.network_layer()->last_transaction());
7058 HttpRequestInfo info;
7059 info.url = GURL(kSimpleGET_Transaction.url);
7060 TestCompletionCallback callback;
7061 EXPECT_EQ(ERR_IO_PENDING,
7062 trans->Start(&info, callback.callback(), BoundNetLog()));
7064 ASSERT_TRUE(cache.network_layer()->last_transaction());
7065 EXPECT_FALSE(cache.network_layer()->last_transaction()->
7066 websocket_handshake_stream_create_helper());
7067 trans->SetWebSocketHandshakeStreamCreateHelper(&create_helper);
7068 EXPECT_EQ(&create_helper,
7069 cache.network_layer()->last_transaction()->
7070 websocket_handshake_stream_create_helper());
7071 EXPECT_EQ(OK, callback.WaitForResult());
7074 // Make sure that a cache transaction passes on its priority to
7075 // newly-created network transactions.
7076 TEST(HttpCache, SetPriorityNewTransaction) {
7077 MockHttpCache cache;
7078 AddMockTransaction(&kRangeGET_TransactionOK);
7080 std::string raw_headers("HTTP/1.1 200 OK\n"
7081 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7082 "ETag: \"foo\"\n"
7083 "Accept-Ranges: bytes\n"
7084 "Content-Length: 80\n");
7085 CreateTruncatedEntry(raw_headers, &cache);
7087 // Now make a regular request.
7088 std::string headers;
7089 MockTransaction transaction(kRangeGET_TransactionOK);
7090 transaction.request_headers = EXTRA_HEADER;
7091 transaction.data = kFullRangeData;
7093 scoped_ptr<HttpTransaction> trans;
7094 ASSERT_EQ(OK, cache.http_cache()->CreateTransaction(MEDIUM, &trans));
7095 EXPECT_EQ(DEFAULT_PRIORITY,
7096 cache.network_layer()->last_create_transaction_priority());
7098 MockHttpRequest info(transaction);
7099 TestCompletionCallback callback;
7100 EXPECT_EQ(ERR_IO_PENDING,
7101 trans->Start(&info, callback.callback(), BoundNetLog()));
7102 EXPECT_EQ(OK, callback.WaitForResult());
7104 EXPECT_EQ(MEDIUM, cache.network_layer()->last_create_transaction_priority());
7106 trans->SetPriority(HIGHEST);
7107 // Should trigger a new network transaction and pick up the new
7108 // priority.
7109 ReadAndVerifyTransaction(trans.get(), transaction);
7111 EXPECT_EQ(HIGHEST, cache.network_layer()->last_create_transaction_priority());
7113 RemoveMockTransaction(&kRangeGET_TransactionOK);
7116 namespace {
7118 void RunTransactionAndGetNetworkBytes(MockHttpCache& cache,
7119 const MockTransaction& trans_info,
7120 int64_t* sent_bytes,
7121 int64_t* received_bytes) {
7122 RunTransactionTestBase(cache.http_cache(), trans_info,
7123 MockHttpRequest(trans_info), nullptr, BoundNetLog(),
7124 nullptr, sent_bytes, received_bytes);
7127 } // namespace
7129 TEST(HttpCache, NetworkBytesCacheMissAndThenHit) {
7130 MockHttpCache cache;
7132 MockTransaction transaction(kSimpleGET_Transaction);
7133 int64_t sent, received;
7134 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7135 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7136 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7138 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7139 EXPECT_EQ(0, sent);
7140 EXPECT_EQ(0, received);
7143 TEST(HttpCache, NetworkBytesConditionalRequest304) {
7144 MockHttpCache cache;
7146 ScopedMockTransaction transaction(kETagGET_Transaction);
7147 int64_t sent, received;
7148 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7149 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7150 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7152 transaction.load_flags = LOAD_VALIDATE_CACHE;
7153 transaction.handler = ETagGet_ConditionalRequest_Handler;
7154 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7155 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7156 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7159 TEST(HttpCache, NetworkBytesConditionalRequest200) {
7160 MockHttpCache cache;
7162 MockTransaction transaction(kTypicalGET_Transaction);
7163 transaction.request_headers = "Foo: bar\r\n";
7164 transaction.response_headers =
7165 "Date: Wed, 28 Nov 2007 09:40:09 GMT\n"
7166 "Last-Modified: Wed, 28 Nov 2007 00:40:09 GMT\n"
7167 "Etag: \"foopy\"\n"
7168 "Cache-Control: max-age=0\n"
7169 "Vary: Foo\n";
7170 AddMockTransaction(&transaction);
7171 int64_t sent, received;
7172 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7173 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7174 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7176 RevalidationServer server;
7177 transaction.handler = server.Handler;
7178 transaction.request_headers = "Foo: none\r\n";
7179 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7180 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7181 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7183 RemoveMockTransaction(&transaction);
7186 TEST(HttpCache, NetworkBytesRange) {
7187 MockHttpCache cache;
7188 AddMockTransaction(&kRangeGET_TransactionOK);
7189 MockTransaction transaction(kRangeGET_TransactionOK);
7191 // Read bytes 40-49 from the network.
7192 int64_t sent, received;
7193 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7194 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7195 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7197 // Read bytes 40-49 from the cache.
7198 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7199 EXPECT_EQ(0, sent);
7200 EXPECT_EQ(0, received);
7201 base::MessageLoop::current()->RunUntilIdle();
7203 // Read bytes 30-39 from the network.
7204 transaction.request_headers = "Range: bytes = 30-39\r\n" EXTRA_HEADER;
7205 transaction.data = "rg: 30-39 ";
7206 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7207 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes, sent);
7208 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes, received);
7209 base::MessageLoop::current()->RunUntilIdle();
7211 // Read bytes 20-29 and 50-59 from the network, bytes 30-49 from the cache.
7212 transaction.request_headers = "Range: bytes = 20-59\r\n" EXTRA_HEADER;
7213 transaction.data = "rg: 20-29 rg: 30-39 rg: 40-49 rg: 50-59 ";
7214 RunTransactionAndGetNetworkBytes(cache, transaction, &sent, &received);
7215 EXPECT_EQ(MockNetworkTransaction::kTotalSentBytes * 2, sent);
7216 EXPECT_EQ(MockNetworkTransaction::kTotalReceivedBytes * 2, received);
7218 RemoveMockTransaction(&kRangeGET_TransactionOK);
7221 class HttpCachePrefetchValidationTest : public ::testing::Test {
7222 protected:
7223 static const int kMaxAgeSecs = 100;
7224 static const int kRequireValidationSecs = kMaxAgeSecs + 1;
7226 HttpCachePrefetchValidationTest() : transaction_(kSimpleGET_Transaction) {
7227 DCHECK_LT(kMaxAgeSecs, prefetch_reuse_mins() * kNumSecondsPerMinute);
7229 clock_ = new base::SimpleTestClock();
7230 cache_.http_cache()->SetClockForTesting(make_scoped_ptr(clock_));
7231 cache_.network_layer()->SetClock(clock_);
7233 transaction_.response_headers = "Cache-Control: max-age=100\n";
7236 bool TransactionRequiredNetwork(int load_flags) {
7237 int pre_transaction_count = transaction_count();
7238 transaction_.load_flags = load_flags;
7239 RunTransactionTest(cache_.http_cache(), transaction_);
7240 return pre_transaction_count != transaction_count();
7243 void AdvanceTime(int seconds) {
7244 clock_->Advance(base::TimeDelta::FromSeconds(seconds));
7247 int prefetch_reuse_mins() { return HttpCache::kPrefetchReuseMins; }
7249 // How many times this test has sent requests to the (fake) origin
7250 // server. Every test case needs to make at least one request to initialise
7251 // the cache.
7252 int transaction_count() {
7253 return cache_.network_layer()->transaction_count();
7256 MockHttpCache cache_;
7257 ScopedMockTransaction transaction_;
7258 std::string response_headers_;
7259 base::SimpleTestClock* clock_;
7262 TEST_F(HttpCachePrefetchValidationTest, SkipValidationShortlyAfterPrefetch) {
7263 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7264 AdvanceTime(kRequireValidationSecs);
7265 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7268 TEST_F(HttpCachePrefetchValidationTest, ValidateLongAfterPrefetch) {
7269 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7270 AdvanceTime(prefetch_reuse_mins() * kNumSecondsPerMinute);
7271 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7274 TEST_F(HttpCachePrefetchValidationTest, SkipValidationOnceOnly) {
7275 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7276 AdvanceTime(kRequireValidationSecs);
7277 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7278 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7281 TEST_F(HttpCachePrefetchValidationTest, SkipValidationOnceReadOnly) {
7282 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7283 AdvanceTime(kRequireValidationSecs);
7284 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_ONLY_FROM_CACHE));
7285 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7288 TEST_F(HttpCachePrefetchValidationTest, BypassCacheOverwritesPrefetch) {
7289 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7290 AdvanceTime(kRequireValidationSecs);
7291 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_BYPASS_CACHE));
7292 AdvanceTime(kRequireValidationSecs);
7293 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7296 TEST_F(HttpCachePrefetchValidationTest,
7297 SkipValidationOnExistingEntryThatNeedsValidation) {
7298 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7299 AdvanceTime(kRequireValidationSecs);
7300 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7301 AdvanceTime(kRequireValidationSecs);
7302 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7303 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7306 TEST_F(HttpCachePrefetchValidationTest,
7307 SkipValidationOnExistingEntryThatDoesNotNeedValidation) {
7308 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7309 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_PREFETCH));
7310 AdvanceTime(kRequireValidationSecs);
7311 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7312 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_NORMAL));
7315 TEST_F(HttpCachePrefetchValidationTest, PrefetchMultipleTimes) {
7316 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7317 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_PREFETCH));
7318 AdvanceTime(kRequireValidationSecs);
7319 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7322 TEST_F(HttpCachePrefetchValidationTest, ValidateOnDelayedSecondPrefetch) {
7323 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7324 AdvanceTime(kRequireValidationSecs);
7325 EXPECT_TRUE(TransactionRequiredNetwork(LOAD_PREFETCH));
7326 AdvanceTime(kRequireValidationSecs);
7327 EXPECT_FALSE(TransactionRequiredNetwork(LOAD_NORMAL));
7330 static void CheckResourceFreshnessHeader(const HttpRequestInfo* request,
7331 std::string* response_status,
7332 std::string* response_headers,
7333 std::string* response_data) {
7334 std::string value;
7335 EXPECT_TRUE(request->extra_headers.GetHeader("Resource-Freshness", &value));
7336 EXPECT_EQ("max-age=3600,stale-while-revalidate=7200,age=10801", value);
7339 // Verify that the Resource-Freshness header is sent on a revalidation if the
7340 // stale-while-revalidate directive was on the response.
7341 TEST(HttpCache, ResourceFreshnessHeaderSent) {
7342 MockHttpCache cache;
7344 ScopedMockTransaction stale_while_revalidate_transaction(
7345 kSimpleGET_Transaction);
7346 stale_while_revalidate_transaction.response_headers =
7347 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7348 "Age: 10801\n"
7349 "Cache-Control: max-age=3600,stale-while-revalidate=7200\n";
7351 // Write to the cache.
7352 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7354 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7356 // Send the request again and check that Resource-Freshness header is added.
7357 stale_while_revalidate_transaction.handler = CheckResourceFreshnessHeader;
7359 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7361 EXPECT_EQ(2, cache.network_layer()->transaction_count());
7364 static void CheckResourceFreshnessAbsent(const HttpRequestInfo* request,
7365 std::string* response_status,
7366 std::string* response_headers,
7367 std::string* response_data) {
7368 EXPECT_FALSE(request->extra_headers.HasHeader("Resource-Freshness"));
7371 // Verify that the Resource-Freshness header is not sent when
7372 // stale-while-revalidate is 0.
7373 TEST(HttpCache, ResourceFreshnessHeaderNotSent) {
7374 MockHttpCache cache;
7376 ScopedMockTransaction stale_while_revalidate_transaction(
7377 kSimpleGET_Transaction);
7378 stale_while_revalidate_transaction.response_headers =
7379 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7380 "Age: 10801\n"
7381 "Cache-Control: max-age=3600,stale-while-revalidate=0\n";
7383 // Write to the cache.
7384 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7386 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7388 // Send the request again and check that Resource-Freshness header is absent.
7389 stale_while_revalidate_transaction.handler = CheckResourceFreshnessAbsent;
7391 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7393 EXPECT_EQ(2, cache.network_layer()->transaction_count());
7396 TEST(HttpCache, StaleContentNotUsedWhenLoadFlagNotSet) {
7397 MockHttpCache cache;
7399 ScopedMockTransaction stale_while_revalidate_transaction(
7400 kSimpleGET_Transaction);
7402 stale_while_revalidate_transaction.response_headers =
7403 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7404 "Age: 10801\n"
7405 "Cache-Control: max-age=0,stale-while-revalidate=86400\n";
7407 // Write to the cache.
7408 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7410 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7412 // Send the request again and check that it is sent to the network again.
7413 HttpResponseInfo response_info;
7414 RunTransactionTestWithResponseInfo(
7415 cache.http_cache(), stale_while_revalidate_transaction, &response_info);
7417 EXPECT_EQ(2, cache.network_layer()->transaction_count());
7418 EXPECT_FALSE(response_info.async_revalidation_required);
7421 TEST(HttpCache, StaleContentUsedWhenLoadFlagSetAndUsable) {
7422 MockHttpCache cache;
7424 ScopedMockTransaction stale_while_revalidate_transaction(
7425 kSimpleGET_Transaction);
7426 stale_while_revalidate_transaction.load_flags |=
7427 LOAD_SUPPORT_ASYNC_REVALIDATION;
7428 stale_while_revalidate_transaction.response_headers =
7429 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7430 "Age: 10801\n"
7431 "Cache-Control: max-age=0,stale-while-revalidate=86400\n";
7433 // Write to the cache.
7434 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7436 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7438 // Send the request again and check that it is not sent to the network again.
7439 HttpResponseInfo response_info;
7440 RunTransactionTestWithResponseInfo(
7441 cache.http_cache(), stale_while_revalidate_transaction, &response_info);
7443 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7444 EXPECT_TRUE(response_info.async_revalidation_required);
7447 TEST(HttpCache, StaleContentNotUsedWhenUnusable) {
7448 MockHttpCache cache;
7450 ScopedMockTransaction stale_while_revalidate_transaction(
7451 kSimpleGET_Transaction);
7452 stale_while_revalidate_transaction.load_flags |=
7453 LOAD_SUPPORT_ASYNC_REVALIDATION;
7454 stale_while_revalidate_transaction.response_headers =
7455 "Last-Modified: Sat, 18 Apr 2007 01:10:43 GMT\n"
7456 "Age: 10801\n"
7457 "Cache-Control: max-age=0,stale-while-revalidate=1800\n";
7459 // Write to the cache.
7460 RunTransactionTest(cache.http_cache(), stale_while_revalidate_transaction);
7462 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7464 // Send the request again and check that it is sent to the network again.
7465 HttpResponseInfo response_info;
7466 RunTransactionTestWithResponseInfo(
7467 cache.http_cache(), stale_while_revalidate_transaction, &response_info);
7469 EXPECT_EQ(2, cache.network_layer()->transaction_count());
7470 EXPECT_FALSE(response_info.async_revalidation_required);
7473 // Tests that we allow multiple simultaneous, non-overlapping transactions to
7474 // take place on a sparse entry.
7475 TEST(HttpCache, RangeGET_MultipleRequests) {
7476 MockHttpCache cache;
7478 // Create a transaction for bytes 0-9.
7479 MockHttpRequest request(kRangeGET_TransactionOK);
7480 MockTransaction transaction(kRangeGET_TransactionOK);
7481 transaction.request_headers = "Range: bytes = 0-9\r\n" EXTRA_HEADER;
7482 transaction.data = "rg: 00-09 ";
7483 AddMockTransaction(&transaction);
7485 TestCompletionCallback callback;
7486 scoped_ptr<HttpTransaction> trans;
7487 int rv = cache.http_cache()->CreateTransaction(DEFAULT_PRIORITY, &trans);
7488 EXPECT_EQ(OK, rv);
7489 ASSERT_TRUE(trans.get());
7491 // Start our transaction.
7492 trans->Start(&request, callback.callback(), BoundNetLog());
7494 // A second transaction on a different part of the file (the default
7495 // kRangeGET_TransactionOK requests 40-49) should not be blocked by
7496 // the already pending transaction.
7497 RunTransactionTest(cache.http_cache(), kRangeGET_TransactionOK);
7499 // Let the first transaction complete.
7500 callback.WaitForResult();
7502 RemoveMockTransaction(&transaction);
7505 // Makes sure that a request stops using the cache when the response headers
7506 // with "Cache-Control: no-store" arrives. That means that another request for
7507 // the same URL can be processed before the response body of the original
7508 // request arrives.
7509 TEST(HttpCache, NoStoreResponseShouldNotBlockFollowingRequests) {
7510 MockHttpCache cache;
7511 ScopedMockTransaction mock_transaction(kSimpleGET_Transaction);
7512 mock_transaction.response_headers = "Cache-Control: no-store\n";
7513 MockHttpRequest request(mock_transaction);
7515 scoped_ptr<Context> first(new Context);
7516 first->result = cache.CreateTransaction(&first->trans);
7517 ASSERT_EQ(OK, first->result);
7518 EXPECT_EQ(LOAD_STATE_IDLE, first->trans->GetLoadState());
7519 first->result =
7520 first->trans->Start(&request, first->callback.callback(), BoundNetLog());
7521 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, first->trans->GetLoadState());
7523 base::MessageLoop::current()->RunUntilIdle();
7524 EXPECT_EQ(LOAD_STATE_IDLE, first->trans->GetLoadState());
7525 ASSERT_TRUE(first->trans->GetResponseInfo());
7526 EXPECT_TRUE(first->trans->GetResponseInfo()->headers->HasHeaderValue(
7527 "Cache-Control", "no-store"));
7528 // Here we have read the response header but not read the response body yet.
7530 // Let us create the second (read) transaction.
7531 scoped_ptr<Context> second(new Context);
7532 second->result = cache.CreateTransaction(&second->trans);
7533 ASSERT_EQ(OK, second->result);
7534 EXPECT_EQ(LOAD_STATE_IDLE, second->trans->GetLoadState());
7535 second->result = second->trans->Start(&request, second->callback.callback(),
7536 BoundNetLog());
7538 // Here the second transaction proceeds without reading the first body.
7539 EXPECT_EQ(LOAD_STATE_WAITING_FOR_CACHE, second->trans->GetLoadState());
7540 base::MessageLoop::current()->RunUntilIdle();
7541 EXPECT_EQ(LOAD_STATE_IDLE, second->trans->GetLoadState());
7542 ASSERT_TRUE(second->trans->GetResponseInfo());
7543 EXPECT_TRUE(second->trans->GetResponseInfo()->headers->HasHeaderValue(
7544 "Cache-Control", "no-store"));
7545 ReadAndVerifyTransaction(second->trans.get(), kSimpleGET_Transaction);
7548 // Tests that serving a response entirely from cache replays the previous
7549 // SSLInfo.
7550 TEST(HttpCache, CachePreservesSSLInfo) {
7551 static const uint16_t kTLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xc02f;
7552 int status = 0;
7553 SSLConnectionStatusSetCipherSuite(kTLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
7554 &status);
7555 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2, &status);
7557 scoped_refptr<X509Certificate> cert =
7558 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
7560 MockHttpCache cache;
7562 ScopedMockTransaction transaction(kSimpleGET_Transaction);
7563 transaction.cert = cert;
7564 transaction.ssl_connection_status = status;
7566 // Fetch the resource.
7567 HttpResponseInfo response_info;
7568 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
7569 &response_info);
7571 // The request should have hit the network and a cache entry created.
7572 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7573 EXPECT_EQ(0, cache.disk_cache()->open_count());
7574 EXPECT_EQ(1, cache.disk_cache()->create_count());
7576 // The expected SSL state was reported.
7577 EXPECT_EQ(transaction.ssl_connection_status,
7578 response_info.ssl_info.connection_status);
7579 EXPECT_TRUE(cert->Equals(response_info.ssl_info.cert.get()));
7581 // Fetch the resource again.
7582 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
7583 &response_info);
7585 // The request should have been reused without hitting the network.
7586 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7587 EXPECT_EQ(1, cache.disk_cache()->open_count());
7588 EXPECT_EQ(1, cache.disk_cache()->create_count());
7590 // The SSL state was preserved.
7591 EXPECT_EQ(status, response_info.ssl_info.connection_status);
7592 EXPECT_TRUE(cert->Equals(response_info.ssl_info.cert.get()));
7595 // Tests that SSLInfo gets updated when revalidating a cached response.
7596 TEST(HttpCache, RevalidationUpdatesSSLInfo) {
7597 static const uint16_t kTLS_RSA_WITH_RC4_128_MD5 = 0x0004;
7598 static const uint16_t kTLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xc02f;
7600 int status1 = 0;
7601 SSLConnectionStatusSetCipherSuite(kTLS_RSA_WITH_RC4_128_MD5, &status1);
7602 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1, &status1);
7603 int status2 = 0;
7604 SSLConnectionStatusSetCipherSuite(kTLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
7605 &status2);
7606 SSLConnectionStatusSetVersion(SSL_CONNECTION_VERSION_TLS1_2, &status2);
7608 scoped_refptr<X509Certificate> cert1 =
7609 ImportCertFromFile(GetTestCertsDirectory(), "expired_cert.pem");
7610 scoped_refptr<X509Certificate> cert2 =
7611 ImportCertFromFile(GetTestCertsDirectory(), "ok_cert.pem");
7613 MockHttpCache cache;
7615 ScopedMockTransaction transaction(kTypicalGET_Transaction);
7616 transaction.cert = cert1;
7617 transaction.ssl_connection_status = status1;
7619 // Fetch the resource.
7620 HttpResponseInfo response_info;
7621 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
7622 &response_info);
7624 // The request should have hit the network and a cache entry created.
7625 EXPECT_EQ(1, cache.network_layer()->transaction_count());
7626 EXPECT_EQ(0, cache.disk_cache()->open_count());
7627 EXPECT_EQ(1, cache.disk_cache()->create_count());
7628 EXPECT_FALSE(response_info.was_cached);
7630 // The expected SSL state was reported.
7631 EXPECT_EQ(status1, response_info.ssl_info.connection_status);
7632 EXPECT_TRUE(cert1->Equals(response_info.ssl_info.cert.get()));
7634 // The server deploys a more modern configuration but reports 304 on the
7635 // revalidation attempt.
7636 transaction.status = "HTTP/1.1 304 Not Modified";
7637 transaction.cert = cert2;
7638 transaction.ssl_connection_status = status2;
7640 // Fetch the resource again, forcing a revalidation.
7641 transaction.request_headers = "Cache-Control: max-age=0\r\n";
7642 RunTransactionTestWithResponseInfo(cache.http_cache(), transaction,
7643 &response_info);
7645 // The request should have been successfully revalidated.
7646 EXPECT_EQ(2, cache.network_layer()->transaction_count());
7647 EXPECT_EQ(1, cache.disk_cache()->open_count());
7648 EXPECT_EQ(1, cache.disk_cache()->create_count());
7649 EXPECT_TRUE(response_info.was_cached);
7651 // The new SSL state is reported.
7652 EXPECT_EQ(status2, response_info.ssl_info.connection_status);
7653 EXPECT_TRUE(cert2->Equals(response_info.ssl_info.cert.get()));
7656 } // namespace net