mock_http_cache.h revision a36e5920737c6adbddd3e43b760e5de8431db6e0
1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This is a mock of the http cache and related testing classes. To be fair, it
6// is not really a mock http cache given that it uses the real implementation of
7// the http cache, but it has fake implementations of all required components,
8// so it is useful for unit tests at the http layer.
9
10#ifndef NET_HTTP_MOCK_HTTP_CACHE_H_
11#define NET_HTTP_MOCK_HTTP_CACHE_H_
12
13#include "base/containers/hash_tables.h"
14#include "net/disk_cache/disk_cache.h"
15#include "net/http/http_cache.h"
16#include "net/http/http_transaction_unittest.h"
17
18//-----------------------------------------------------------------------------
19// Mock disk cache (a very basic memory cache implementation).
20
21class MockDiskEntry : public disk_cache::Entry,
22                      public base::RefCounted<MockDiskEntry> {
23 public:
24  MockDiskEntry();
25  explicit MockDiskEntry(const std::string& key);
26
27  bool is_doomed() const { return doomed_; }
28
29  virtual void Doom() OVERRIDE;
30  virtual void Close() OVERRIDE;
31  virtual std::string GetKey() const OVERRIDE;
32  virtual base::Time GetLastUsed() const OVERRIDE;
33  virtual base::Time GetLastModified() const OVERRIDE;
34  virtual int32 GetDataSize(int index) const OVERRIDE;
35  virtual int ReadData(int index, int offset, net::IOBuffer* buf, int buf_len,
36                       const net::CompletionCallback& callback) OVERRIDE;
37  virtual int WriteData(int index, int offset, net::IOBuffer* buf, int buf_len,
38                        const net::CompletionCallback& callback,
39                        bool truncate) OVERRIDE;
40  virtual int ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
41                             const net::CompletionCallback& callback) OVERRIDE;
42  virtual int WriteSparseData(
43      int64 offset, net::IOBuffer* buf, int buf_len,
44      const net::CompletionCallback& callback) OVERRIDE;
45  virtual int GetAvailableRange(
46      int64 offset, int len, int64* start,
47      const net::CompletionCallback& callback) OVERRIDE;
48  virtual bool CouldBeSparse() const OVERRIDE;
49  virtual void CancelSparseIO() OVERRIDE;
50  virtual int ReadyForSparseIO(
51      const net::CompletionCallback& completion_callback) OVERRIDE;
52
53  // Fail most subsequent requests.
54  void set_fail_requests() { fail_requests_ = true; }
55
56  // If |value| is true, don't deliver any completion callbacks until called
57  // again with |value| set to false.  Caution: remember to enable callbacks
58  // again or all subsequent tests will fail.
59  static void IgnoreCallbacks(bool value);
60
61 private:
62  friend class base::RefCounted<MockDiskEntry>;
63  struct CallbackInfo;
64
65  virtual ~MockDiskEntry();
66
67  // Unlike the callbacks for MockHttpTransaction, we want this one to run even
68  // if the consumer called Close on the MockDiskEntry.  We achieve that by
69  // leveraging the fact that this class is reference counted.
70  void CallbackLater(const net::CompletionCallback& callback, int result);
71
72  void RunCallback(const net::CompletionCallback& callback, int result);
73
74  // When |store| is true, stores the callback to be delivered later; otherwise
75  // delivers any callback previously stored.
76  static void StoreAndDeliverCallbacks(bool store, MockDiskEntry* entry,
77                                       const net::CompletionCallback& callback,
78                                       int result);
79
80  static const int kNumCacheEntryDataIndices = 3;
81
82  std::string key_;
83  std::vector<char> data_[kNumCacheEntryDataIndices];
84  int test_mode_;
85  bool doomed_;
86  bool sparse_;
87  bool fail_requests_;
88  bool busy_;
89  bool delayed_;
90  static bool cancel_;
91  static bool ignore_callbacks_;
92};
93
94class MockDiskCache : public disk_cache::Backend {
95 public:
96  MockDiskCache();
97  virtual ~MockDiskCache();
98
99  virtual net::CacheType GetCacheType() const OVERRIDE;
100  virtual int32 GetEntryCount() const OVERRIDE;
101  virtual int OpenEntry(const std::string& key, disk_cache::Entry** entry,
102                        const net::CompletionCallback& callback) OVERRIDE;
103  virtual int CreateEntry(const std::string& key, disk_cache::Entry** entry,
104                          const net::CompletionCallback& callback) OVERRIDE;
105  virtual int DoomEntry(const std::string& key,
106                        const net::CompletionCallback& callback) OVERRIDE;
107  virtual int DoomAllEntries(const net::CompletionCallback& callback) OVERRIDE;
108  virtual int DoomEntriesBetween(
109      base::Time initial_time,
110      base::Time end_time,
111      const net::CompletionCallback& callback) OVERRIDE;
112  virtual int DoomEntriesSince(
113      base::Time initial_time,
114      const net::CompletionCallback& callback) OVERRIDE;
115  virtual int OpenNextEntry(void** iter, disk_cache::Entry** next_entry,
116                            const net::CompletionCallback& callback) OVERRIDE;
117  virtual void EndEnumeration(void** iter) OVERRIDE;
118  virtual void GetStats(
119      std::vector<std::pair<std::string, std::string> >* stats) OVERRIDE;
120  virtual void OnExternalCacheHit(const std::string& key) OVERRIDE;
121
122  // Returns number of times a cache entry was successfully opened.
123  int open_count() const { return open_count_; }
124
125  // Returns number of times a cache entry was successfully created.
126  int create_count() const { return create_count_; }
127
128  // Fail any subsequent CreateEntry and OpenEntry.
129  void set_fail_requests() { fail_requests_ = true; }
130
131  // Return entries that fail some of their requests.
132  void set_soft_failures(bool value) { soft_failures_ = value; }
133
134  // Makes sure that CreateEntry is not called twice for a given key.
135  void set_double_create_check(bool value) { double_create_check_ = value; }
136
137  void ReleaseAll();
138
139 private:
140  typedef base::hash_map<std::string, MockDiskEntry*> EntryMap;
141
142  void CallbackLater(const net::CompletionCallback& callback, int result);
143
144  EntryMap entries_;
145  int open_count_;
146  int create_count_;
147  bool fail_requests_;
148  bool soft_failures_;
149  bool double_create_check_;
150};
151
152class MockBackendFactory : public net::HttpCache::BackendFactory {
153 public:
154  virtual int CreateBackend(net::NetLog* net_log,
155                            scoped_ptr<disk_cache::Backend>* backend,
156                            const net::CompletionCallback& callback) OVERRIDE;
157};
158
159class MockHttpCache {
160 public:
161  MockHttpCache();
162  explicit MockHttpCache(net::HttpCache::BackendFactory* disk_cache_factory);
163
164  net::HttpCache* http_cache() { return &http_cache_; }
165
166  MockNetworkLayer* network_layer() {
167    return static_cast<MockNetworkLayer*>(http_cache_.network_layer());
168  }
169  MockDiskCache* disk_cache();
170
171  // Helper function for reading response info from the disk cache.
172  static bool ReadResponseInfo(disk_cache::Entry* disk_entry,
173                               net::HttpResponseInfo* response_info,
174                               bool* response_truncated);
175
176  // Helper function for writing response info into the disk cache.
177  static bool WriteResponseInfo(disk_cache::Entry* disk_entry,
178                                const net::HttpResponseInfo* response_info,
179                                bool skip_transient_headers,
180                                bool response_truncated);
181
182  // Helper function to synchronously open a backend entry.
183  bool OpenBackendEntry(const std::string& key, disk_cache::Entry** entry);
184
185  // Helper function to synchronously create a backend entry.
186  bool CreateBackendEntry(const std::string& key, disk_cache::Entry** entry,
187                          net::NetLog* net_log);
188
189  // Returns the test mode after considering the global override.
190  static int GetTestMode(int test_mode);
191
192  // Overrides the test mode for a given operation. Remember to reset it after
193  // the test! (by setting test_mode to zero).
194  static void SetTestMode(int test_mode);
195
196 private:
197  net::HttpCache http_cache_;
198};
199
200// This version of the disk cache doesn't invoke CreateEntry callbacks.
201class MockDiskCacheNoCB : public MockDiskCache {
202  virtual int CreateEntry(const std::string& key, disk_cache::Entry** entry,
203                          const net::CompletionCallback& callback) OVERRIDE;
204};
205
206class MockBackendNoCbFactory : public net::HttpCache::BackendFactory {
207 public:
208  virtual int CreateBackend(net::NetLog* net_log,
209                            scoped_ptr<disk_cache::Backend>* backend,
210                            const net::CompletionCallback& callback) OVERRIDE;
211};
212
213// This backend factory allows us to control the backend instantiation.
214class MockBlockingBackendFactory : public net::HttpCache::BackendFactory {
215 public:
216  MockBlockingBackendFactory();
217  virtual ~MockBlockingBackendFactory();
218
219  virtual int CreateBackend(net::NetLog* net_log,
220                            scoped_ptr<disk_cache::Backend>* backend,
221                            const net::CompletionCallback& callback) OVERRIDE;
222
223  // Completes the backend creation. Any blocked call will be notified via the
224  // provided callback.
225  void FinishCreation();
226
227  scoped_ptr<disk_cache::Backend>* backend() { return backend_; }
228  void set_fail(bool fail) { fail_ = fail; }
229
230  const net::CompletionCallback& callback() { return callback_; }
231
232 private:
233  int Result() { return fail_ ? net::ERR_FAILED : net::OK; }
234
235  scoped_ptr<disk_cache::Backend>* backend_;
236  net::CompletionCallback callback_;
237  bool block_;
238  bool fail_;
239};
240
241#endif  // NET_HTTP_MOCK_HTTP_CACHE_H_
242