http_transaction_test_util.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // Copyright 2014 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. #ifndef NET_HTTP_HTTP_TRANSACTION_TEST_UTIL_H_
  5. #define NET_HTTP_HTTP_TRANSACTION_TEST_UTIL_H_
  6. #include "base/memory/raw_ptr.h"
  7. #include "net/http/http_transaction.h"
  8. #include <stdint.h>
  9. #include <set>
  10. #include <string>
  11. #include <vector>
  12. #include "base/callback.h"
  13. #include "base/compiler_specific.h"
  14. #include "base/memory/scoped_refptr.h"
  15. #include "base/memory/weak_ptr.h"
  16. #include "base/time/time.h"
  17. #include "net/base/completion_once_callback.h"
  18. #include "net/base/io_buffer.h"
  19. #include "net/base/load_flags.h"
  20. #include "net/base/net_error_details.h"
  21. #include "net/base/net_errors.h"
  22. #include "net/base/request_priority.h"
  23. #include "net/base/test_completion_callback.h"
  24. #include "net/base/transport_info.h"
  25. #include "net/cert/x509_certificate.h"
  26. #include "net/disk_cache/disk_cache.h"
  27. #include "net/http/http_cache.h"
  28. #include "net/http/http_request_info.h"
  29. #include "net/http/http_response_headers.h"
  30. #include "net/http/http_response_info.h"
  31. #include "net/log/net_log_source.h"
  32. #include "net/socket/connection_attempts.h"
  33. namespace net {
  34. class IOBuffer;
  35. class SSLPrivateKey;
  36. class NetLogWithSource;
  37. struct HttpRequestInfo;
  38. //-----------------------------------------------------------------------------
  39. // mock transaction data
  40. // these flags may be combined to form the test_mode field
  41. enum {
  42. TEST_MODE_NORMAL = 0,
  43. TEST_MODE_SYNC_NET_START = 1 << 0,
  44. TEST_MODE_SYNC_NET_READ = 1 << 1,
  45. TEST_MODE_SYNC_CACHE_START = 1 << 2,
  46. TEST_MODE_SYNC_CACHE_READ = 1 << 3,
  47. TEST_MODE_SYNC_CACHE_WRITE = 1 << 4,
  48. TEST_MODE_SYNC_ALL = (TEST_MODE_SYNC_NET_START | TEST_MODE_SYNC_NET_READ |
  49. TEST_MODE_SYNC_CACHE_START | TEST_MODE_SYNC_CACHE_READ |
  50. TEST_MODE_SYNC_CACHE_WRITE),
  51. TEST_MODE_SLOW_READ = 1 << 5
  52. };
  53. using MockTransactionReadHandler = int (*)(int64_t content_length,
  54. int64_t offset,
  55. IOBuffer* buf,
  56. int buf_len);
  57. using MockTransactionHandler = void (*)(const HttpRequestInfo* request,
  58. std::string* response_status,
  59. std::string* response_headers,
  60. std::string* response_data);
  61. // Default TransportInfo suitable for most MockTransactions.
  62. // Describes a direct connection to (127.0.0.1, 80).
  63. TransportInfo DefaultTransportInfo();
  64. struct MockTransaction {
  65. const char* url;
  66. const char* method;
  67. // If |request_time| is unspecified, the current time will be used.
  68. base::Time request_time;
  69. const char* request_headers;
  70. int load_flags;
  71. // Connection info passed to ConnectedCallback(), if any.
  72. TransportInfo transport_info = DefaultTransportInfo();
  73. const char* status;
  74. const char* response_headers;
  75. // If |response_time| is unspecified, the current time will be used.
  76. base::Time response_time;
  77. const char* data;
  78. // Any aliases for the requested URL, as read from DNS records. Includes all
  79. // known aliases, e.g. from A, AAAA, or HTTPS, not just from the address used
  80. // for the connection, in no particular order.
  81. std::set<std::string> dns_aliases;
  82. int test_mode;
  83. MockTransactionHandler handler;
  84. MockTransactionReadHandler read_handler;
  85. scoped_refptr<X509Certificate> cert;
  86. CertStatus cert_status;
  87. int ssl_connection_status;
  88. // Value returned by MockNetworkTransaction::Start (potentially
  89. // asynchronously if |!(test_mode & TEST_MODE_SYNC_NET_START)|.)
  90. Error start_return_code;
  91. // Value returned by MockNetworkTransaction::Read (potentially
  92. // asynchronously if |!(test_mode & TEST_MODE_SYNC_NET_START)|.)
  93. Error read_return_code;
  94. };
  95. extern const MockTransaction kSimpleGET_Transaction;
  96. extern const MockTransaction kSimplePOST_Transaction;
  97. extern const MockTransaction kTypicalGET_Transaction;
  98. extern const MockTransaction kETagGET_Transaction;
  99. extern const MockTransaction kRangeGET_Transaction;
  100. // returns the mock transaction for the given URL
  101. const MockTransaction* FindMockTransaction(const GURL& url);
  102. // Add/Remove a mock transaction that can be accessed via FindMockTransaction.
  103. // There can be only one MockTransaction associated with a given URL.
  104. void AddMockTransaction(const MockTransaction* trans);
  105. void RemoveMockTransaction(const MockTransaction* trans);
  106. struct ScopedMockTransaction : MockTransaction {
  107. ScopedMockTransaction() {
  108. AddMockTransaction(this);
  109. }
  110. explicit ScopedMockTransaction(const MockTransaction& t)
  111. : MockTransaction(t) {
  112. AddMockTransaction(this);
  113. }
  114. ~ScopedMockTransaction() {
  115. RemoveMockTransaction(this);
  116. }
  117. };
  118. //-----------------------------------------------------------------------------
  119. // mock http request
  120. class MockHttpRequest : public HttpRequestInfo {
  121. public:
  122. explicit MockHttpRequest(const MockTransaction& t);
  123. std::string CacheKey();
  124. };
  125. //-----------------------------------------------------------------------------
  126. // use this class to test completely consuming a transaction
  127. class TestTransactionConsumer {
  128. public:
  129. TestTransactionConsumer(RequestPriority priority,
  130. HttpTransactionFactory* factory);
  131. virtual ~TestTransactionConsumer();
  132. void Start(const HttpRequestInfo* request, const NetLogWithSource& net_log);
  133. bool is_done() const { return state_ == State::kDone; }
  134. int error() const { return error_; }
  135. const HttpResponseInfo* response_info() const {
  136. return trans_->GetResponseInfo();
  137. }
  138. const HttpTransaction* transaction() const { return trans_.get(); }
  139. const std::string& content() const { return content_; }
  140. private:
  141. enum class State { kIdle, kStarting, kReading, kDone };
  142. void DidStart(int result);
  143. void DidRead(int result);
  144. void DidFinish(int result);
  145. void Read();
  146. void OnIOComplete(int result);
  147. State state_ = State::kIdle;
  148. std::unique_ptr<HttpTransaction> trans_;
  149. std::string content_;
  150. scoped_refptr<IOBuffer> read_buf_;
  151. int error_ = OK;
  152. static int quit_counter_;
  153. };
  154. //-----------------------------------------------------------------------------
  155. // mock network layer
  156. class MockNetworkLayer;
  157. // This transaction class inspects the available set of mock transactions to
  158. // find data for the request URL. It supports IO operations that complete
  159. // synchronously or asynchronously to help exercise different code paths in the
  160. // HttpCache implementation.
  161. class MockNetworkTransaction
  162. : public HttpTransaction,
  163. public base::SupportsWeakPtr<MockNetworkTransaction> {
  164. typedef WebSocketHandshakeStreamBase::CreateHelper CreateHelper;
  165. public:
  166. MockNetworkTransaction(RequestPriority priority, MockNetworkLayer* factory);
  167. ~MockNetworkTransaction() override;
  168. int Start(const HttpRequestInfo* request,
  169. CompletionOnceCallback callback,
  170. const NetLogWithSource& net_log) override;
  171. int RestartIgnoringLastError(CompletionOnceCallback callback) override;
  172. int RestartWithCertificate(scoped_refptr<X509Certificate> client_cert,
  173. scoped_refptr<SSLPrivateKey> client_private_key,
  174. CompletionOnceCallback callback) override;
  175. int RestartWithAuth(const AuthCredentials& credentials,
  176. CompletionOnceCallback callback) override;
  177. bool IsReadyToRestartForAuth() override;
  178. int Read(IOBuffer* buf,
  179. int buf_len,
  180. CompletionOnceCallback callback) override;
  181. void PopulateNetErrorDetails(NetErrorDetails* details) const override;
  182. void StopCaching() override;
  183. int64_t GetTotalReceivedBytes() const override;
  184. int64_t GetTotalSentBytes() const override;
  185. void DoneReading() override;
  186. const HttpResponseInfo* GetResponseInfo() const override;
  187. LoadState GetLoadState() const override;
  188. void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
  189. bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
  190. bool GetRemoteEndpoint(IPEndPoint* endpoint) const override;
  191. void SetPriority(RequestPriority priority) override;
  192. void SetWebSocketHandshakeStreamCreateHelper(
  193. CreateHelper* create_helper) override;
  194. void SetBeforeNetworkStartCallback(
  195. BeforeNetworkStartCallback callback) override;
  196. void SetConnectedCallback(const ConnectedCallback& callback) override;
  197. void SetRequestHeadersCallback(RequestHeadersCallback callback) override {}
  198. void SetResponseHeadersCallback(ResponseHeadersCallback) override {}
  199. void SetEarlyResponseHeadersCallback(ResponseHeadersCallback) override {}
  200. int ResumeNetworkStart() override;
  201. ConnectionAttempts GetConnectionAttempts() const override;
  202. void CloseConnectionOnDestruction() override;
  203. CreateHelper* websocket_handshake_stream_create_helper() {
  204. return websocket_handshake_stream_create_helper_;
  205. }
  206. RequestPriority priority() const { return priority_; }
  207. const HttpRequestInfo* request() const { return request_; }
  208. // Bogus value that will be returned by GetTotalReceivedBytes() if the
  209. // MockNetworkTransaction was started.
  210. static const int64_t kTotalReceivedBytes;
  211. // Bogus value that will be returned by GetTotalSentBytes() if the
  212. // MockNetworkTransaction was started.
  213. static const int64_t kTotalSentBytes;
  214. private:
  215. int StartInternal(const HttpRequestInfo* request,
  216. CompletionOnceCallback callback,
  217. const NetLogWithSource& net_log);
  218. void CallbackLater(CompletionOnceCallback callback, int result);
  219. void RunCallback(CompletionOnceCallback callback, int result);
  220. raw_ptr<const HttpRequestInfo> request_ = nullptr;
  221. HttpResponseInfo response_;
  222. std::string data_;
  223. int64_t data_cursor_ = 0;
  224. int64_t content_length_ = 0;
  225. int test_mode_;
  226. RequestPriority priority_;
  227. MockTransactionReadHandler read_handler_ = nullptr;
  228. raw_ptr<CreateHelper> websocket_handshake_stream_create_helper_ = nullptr;
  229. BeforeNetworkStartCallback before_network_start_callback_;
  230. ConnectedCallback connected_callback_;
  231. base::WeakPtr<MockNetworkLayer> transaction_factory_;
  232. int64_t received_bytes_ = 0;
  233. int64_t sent_bytes_ = 0;
  234. // NetLog ID of the fake / non-existent underlying socket used by the
  235. // connection. Requires Start() be passed a NetLogWithSource with a real
  236. // NetLog to
  237. // be initialized.
  238. unsigned int socket_log_id_ = NetLogSource::kInvalidId;
  239. bool done_reading_called_ = false;
  240. bool reading_ = false;
  241. CompletionOnceCallback resume_start_callback_; // used for pause and restart.
  242. base::WeakPtrFactory<MockNetworkTransaction> weak_factory_{this};
  243. };
  244. class MockNetworkLayer : public HttpTransactionFactory,
  245. public base::SupportsWeakPtr<MockNetworkLayer> {
  246. public:
  247. MockNetworkLayer();
  248. ~MockNetworkLayer() override;
  249. int transaction_count() const { return transaction_count_; }
  250. bool done_reading_called() const { return done_reading_called_; }
  251. bool stop_caching_called() const { return stop_caching_called_; }
  252. void TransactionDoneReading();
  253. void TransactionStopCaching();
  254. // Resets the transaction count. Can be called after test setup in order to
  255. // make test expectations independent of how test setup is performed.
  256. void ResetTransactionCount();
  257. // Returns the last priority passed to CreateTransaction, or
  258. // DEFAULT_PRIORITY if it hasn't been called yet.
  259. RequestPriority last_create_transaction_priority() const {
  260. return last_create_transaction_priority_;
  261. }
  262. // Returns the last transaction created by
  263. // CreateTransaction. Returns a NULL WeakPtr if one has not been
  264. // created yet, or the last transaction has been destroyed, or
  265. // ClearLastTransaction() has been called and a new transaction
  266. // hasn't been created yet.
  267. base::WeakPtr<MockNetworkTransaction> last_transaction() {
  268. return last_transaction_;
  269. }
  270. // Makes last_transaction() return NULL until the next transaction
  271. // is created.
  272. void ClearLastTransaction() {
  273. last_transaction_.reset();
  274. }
  275. // HttpTransactionFactory:
  276. int CreateTransaction(RequestPriority priority,
  277. std::unique_ptr<HttpTransaction>* trans) override;
  278. HttpCache* GetCache() override;
  279. HttpNetworkSession* GetSession() override;
  280. // The caller must guarantee that |clock| will outlive this object.
  281. void SetClock(base::Clock* clock);
  282. base::Clock* clock() const { return clock_; }
  283. // The current time (will use clock_ if it is non NULL).
  284. base::Time Now();
  285. private:
  286. int transaction_count_ = 0;
  287. bool done_reading_called_ = false;
  288. bool stop_caching_called_ = false;
  289. RequestPriority last_create_transaction_priority_ = DEFAULT_PRIORITY;
  290. // By default clock_ is NULL but it can be set to a custom clock by test
  291. // frameworks using SetClock.
  292. raw_ptr<base::Clock> clock_ = nullptr;
  293. base::WeakPtr<MockNetworkTransaction> last_transaction_;
  294. };
  295. //-----------------------------------------------------------------------------
  296. // helpers
  297. // read the transaction completely
  298. int ReadTransaction(HttpTransaction* trans, std::string* result);
  299. //-----------------------------------------------------------------------------
  300. // connected callback handler
  301. // Used for injecting ConnectedCallback instances in HttpTransaction.
  302. class ConnectedHandler {
  303. public:
  304. ConnectedHandler();
  305. ~ConnectedHandler();
  306. // Instances of this class are copyable and efficiently movable.
  307. // WARNING: Do not move an instance to which a callback is bound.
  308. ConnectedHandler(const ConnectedHandler&);
  309. ConnectedHandler& operator=(const ConnectedHandler&);
  310. ConnectedHandler(ConnectedHandler&&);
  311. ConnectedHandler& operator=(ConnectedHandler&&);
  312. // Returns a callback bound to this->OnConnected().
  313. // The returned callback must not outlive this instance.
  314. HttpTransaction::ConnectedCallback Callback() {
  315. return base::BindRepeating(&ConnectedHandler::OnConnected,
  316. base::Unretained(this));
  317. }
  318. // Compatible with HttpTransaction::ConnectedCallback.
  319. // Returns the last value passed to set_result(), if any, OK otherwise.
  320. int OnConnected(const TransportInfo& info, CompletionOnceCallback callback);
  321. // Returns the list of arguments with which OnConnected() was called.
  322. // The arguments are listed in the same order as the calls were received.
  323. const std::vector<TransportInfo>& transports() const { return transports_; }
  324. // Sets the value to be returned by subsequent calls to OnConnected().
  325. void set_result(int result) { result_ = result; }
  326. // If true, runs the callback supplied to OnConnected asynchronously with
  327. // `result_`. Otherwise, the callback is skipped and `result_` is returned
  328. // directly.
  329. void set_run_callback(bool run_callback) { run_callback_ = run_callback; }
  330. private:
  331. std::vector<TransportInfo> transports_;
  332. int result_ = OK;
  333. bool run_callback_ = false;
  334. };
  335. } // namespace net
  336. #endif // NET_HTTP_HTTP_TRANSACTION_TEST_UTIL_H_