OLD | NEW |
| (Empty) |
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. | |
4 | |
5 #ifndef NET_SOCKET_SOCKET_TEST_UTIL_H_ | |
6 #define NET_SOCKET_SOCKET_TEST_UTIL_H_ | |
7 | |
8 #include <cstring> | |
9 #include <deque> | |
10 #include <string> | |
11 #include <vector> | |
12 | |
13 #include "base/basictypes.h" | |
14 #include "base/callback.h" | |
15 #include "base/logging.h" | |
16 #include "base/memory/ref_counted.h" | |
17 #include "base/memory/scoped_ptr.h" | |
18 #include "base/memory/scoped_vector.h" | |
19 #include "base/memory/weak_ptr.h" | |
20 #include "base/strings/string16.h" | |
21 #include "base/time/time.h" | |
22 #include "net/base/address_list.h" | |
23 #include "net/base/io_buffer.h" | |
24 #include "net/base/net_errors.h" | |
25 #include "net/base/net_log.h" | |
26 #include "net/base/test_completion_callback.h" | |
27 #include "net/http/http_auth_controller.h" | |
28 #include "net/http/http_proxy_client_socket_pool.h" | |
29 #include "net/socket/client_socket_factory.h" | |
30 #include "net/socket/client_socket_handle.h" | |
31 #include "net/socket/socks_client_socket_pool.h" | |
32 #include "net/socket/ssl_client_socket.h" | |
33 #include "net/socket/ssl_client_socket_pool.h" | |
34 #include "net/socket/transport_client_socket_pool.h" | |
35 #include "net/ssl/ssl_config_service.h" | |
36 #include "net/udp/datagram_client_socket.h" | |
37 #include "testing/gtest/include/gtest/gtest.h" | |
38 | |
39 namespace net { | |
40 | |
41 enum { | |
42 // A private network error code used by the socket test utility classes. | |
43 // If the |result| member of a MockRead is | |
44 // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a | |
45 // marker that indicates the peer will close the connection after the next | |
46 // MockRead. The other members of that MockRead are ignored. | |
47 ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000, | |
48 }; | |
49 | |
50 class AsyncSocket; | |
51 class ChannelIDService; | |
52 class MockClientSocket; | |
53 class SSLClientSocket; | |
54 class StreamSocket; | |
55 | |
56 enum IoMode { | |
57 ASYNC, | |
58 SYNCHRONOUS | |
59 }; | |
60 | |
61 struct MockConnect { | |
62 // Asynchronous connection success. | |
63 // Creates a MockConnect with |mode| ASYC, |result| OK, and | |
64 // |peer_addr| 192.0.2.33. | |
65 MockConnect(); | |
66 // Creates a MockConnect with the specified mode and result, with | |
67 // |peer_addr| 192.0.2.33. | |
68 MockConnect(IoMode io_mode, int r); | |
69 MockConnect(IoMode io_mode, int r, IPEndPoint addr); | |
70 ~MockConnect(); | |
71 | |
72 IoMode mode; | |
73 int result; | |
74 IPEndPoint peer_addr; | |
75 }; | |
76 | |
77 // MockRead and MockWrite shares the same interface and members, but we'd like | |
78 // to have distinct types because we don't want to have them used | |
79 // interchangably. To do this, a struct template is defined, and MockRead and | |
80 // MockWrite are instantiated by using this template. Template parameter |type| | |
81 // is not used in the struct definition (it purely exists for creating a new | |
82 // type). | |
83 // | |
84 // |data| in MockRead and MockWrite has different meanings: |data| in MockRead | |
85 // is the data returned from the socket when MockTCPClientSocket::Read() is | |
86 // attempted, while |data| in MockWrite is the expected data that should be | |
87 // given in MockTCPClientSocket::Write(). | |
88 enum MockReadWriteType { | |
89 MOCK_READ, | |
90 MOCK_WRITE | |
91 }; | |
92 | |
93 template <MockReadWriteType type> | |
94 struct MockReadWrite { | |
95 // Flag to indicate that the message loop should be terminated. | |
96 enum { | |
97 STOPLOOP = 1 << 31 | |
98 }; | |
99 | |
100 // Default | |
101 MockReadWrite() | |
102 : mode(SYNCHRONOUS), | |
103 result(0), | |
104 data(NULL), | |
105 data_len(0), | |
106 sequence_number(0), | |
107 time_stamp(base::Time::Now()) {} | |
108 | |
109 // Read/write failure (no data). | |
110 MockReadWrite(IoMode io_mode, int result) | |
111 : mode(io_mode), | |
112 result(result), | |
113 data(NULL), | |
114 data_len(0), | |
115 sequence_number(0), | |
116 time_stamp(base::Time::Now()) {} | |
117 | |
118 // Read/write failure (no data), with sequence information. | |
119 MockReadWrite(IoMode io_mode, int result, int seq) | |
120 : mode(io_mode), | |
121 result(result), | |
122 data(NULL), | |
123 data_len(0), | |
124 sequence_number(seq), | |
125 time_stamp(base::Time::Now()) {} | |
126 | |
127 // Asynchronous read/write success (inferred data length). | |
128 explicit MockReadWrite(const char* data) | |
129 : mode(ASYNC), | |
130 result(0), | |
131 data(data), | |
132 data_len(strlen(data)), | |
133 sequence_number(0), | |
134 time_stamp(base::Time::Now()) {} | |
135 | |
136 // Read/write success (inferred data length). | |
137 MockReadWrite(IoMode io_mode, const char* data) | |
138 : mode(io_mode), | |
139 result(0), | |
140 data(data), | |
141 data_len(strlen(data)), | |
142 sequence_number(0), | |
143 time_stamp(base::Time::Now()) {} | |
144 | |
145 // Read/write success. | |
146 MockReadWrite(IoMode io_mode, const char* data, int data_len) | |
147 : mode(io_mode), | |
148 result(0), | |
149 data(data), | |
150 data_len(data_len), | |
151 sequence_number(0), | |
152 time_stamp(base::Time::Now()) {} | |
153 | |
154 // Read/write success (inferred data length) with sequence information. | |
155 MockReadWrite(IoMode io_mode, int seq, const char* data) | |
156 : mode(io_mode), | |
157 result(0), | |
158 data(data), | |
159 data_len(strlen(data)), | |
160 sequence_number(seq), | |
161 time_stamp(base::Time::Now()) {} | |
162 | |
163 // Read/write success with sequence information. | |
164 MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq) | |
165 : mode(io_mode), | |
166 result(0), | |
167 data(data), | |
168 data_len(data_len), | |
169 sequence_number(seq), | |
170 time_stamp(base::Time::Now()) {} | |
171 | |
172 IoMode mode; | |
173 int result; | |
174 const char* data; | |
175 int data_len; | |
176 | |
177 // For OrderedSocketData, which only allows reads to occur in a particular | |
178 // sequence. If a read occurs before the given |sequence_number| is reached, | |
179 // an ERR_IO_PENDING is returned. | |
180 int sequence_number; // The sequence number at which a read is allowed | |
181 // to occur. | |
182 base::Time time_stamp; // The time stamp at which the operation occurred. | |
183 }; | |
184 | |
185 typedef MockReadWrite<MOCK_READ> MockRead; | |
186 typedef MockReadWrite<MOCK_WRITE> MockWrite; | |
187 | |
188 struct MockWriteResult { | |
189 MockWriteResult(IoMode io_mode, int result) : mode(io_mode), result(result) {} | |
190 | |
191 IoMode mode; | |
192 int result; | |
193 }; | |
194 | |
195 // The SocketDataProvider is an interface used by the MockClientSocket | |
196 // for getting data about individual reads and writes on the socket. | |
197 class SocketDataProvider { | |
198 public: | |
199 SocketDataProvider() : socket_(NULL) {} | |
200 | |
201 virtual ~SocketDataProvider() {} | |
202 | |
203 // Returns the buffer and result code for the next simulated read. | |
204 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller | |
205 // that it will be called via the AsyncSocket::OnReadComplete() | |
206 // function at a later time. | |
207 virtual MockRead GetNextRead() = 0; | |
208 virtual MockWriteResult OnWrite(const std::string& data) = 0; | |
209 virtual void Reset() = 0; | |
210 | |
211 // Accessor for the socket which is using the SocketDataProvider. | |
212 AsyncSocket* socket() { return socket_; } | |
213 void set_socket(AsyncSocket* socket) { socket_ = socket; } | |
214 | |
215 MockConnect connect_data() const { return connect_; } | |
216 void set_connect_data(const MockConnect& connect) { connect_ = connect; } | |
217 | |
218 private: | |
219 MockConnect connect_; | |
220 AsyncSocket* socket_; | |
221 | |
222 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider); | |
223 }; | |
224 | |
225 // The AsyncSocket is an interface used by the SocketDataProvider to | |
226 // complete the asynchronous read operation. | |
227 class AsyncSocket { | |
228 public: | |
229 // If an async IO is pending because the SocketDataProvider returned | |
230 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete | |
231 // is called to complete the asynchronous read operation. | |
232 // data.async is ignored, and this read is completed synchronously as | |
233 // part of this call. | |
234 virtual void OnReadComplete(const MockRead& data) = 0; | |
235 virtual void OnConnectComplete(const MockConnect& data) = 0; | |
236 }; | |
237 | |
238 // SocketDataProvider which responds based on static tables of mock reads and | |
239 // writes. | |
240 class StaticSocketDataProvider : public SocketDataProvider { | |
241 public: | |
242 StaticSocketDataProvider(); | |
243 StaticSocketDataProvider(MockRead* reads, | |
244 size_t reads_count, | |
245 MockWrite* writes, | |
246 size_t writes_count); | |
247 ~StaticSocketDataProvider() override; | |
248 | |
249 // These functions get access to the next available read and write data. | |
250 const MockRead& PeekRead() const; | |
251 const MockWrite& PeekWrite() const; | |
252 // These functions get random access to the read and write data, for timing. | |
253 const MockRead& PeekRead(size_t index) const; | |
254 const MockWrite& PeekWrite(size_t index) const; | |
255 size_t read_index() const { return read_index_; } | |
256 size_t write_index() const { return write_index_; } | |
257 size_t read_count() const { return read_count_; } | |
258 size_t write_count() const { return write_count_; } | |
259 | |
260 bool at_read_eof() const { return read_index_ >= read_count_; } | |
261 bool at_write_eof() const { return write_index_ >= write_count_; } | |
262 | |
263 virtual void CompleteRead() {} | |
264 | |
265 // SocketDataProvider implementation. | |
266 MockRead GetNextRead() override; | |
267 MockWriteResult OnWrite(const std::string& data) override; | |
268 void Reset() override; | |
269 | |
270 private: | |
271 MockRead* reads_; | |
272 size_t read_index_; | |
273 size_t read_count_; | |
274 MockWrite* writes_; | |
275 size_t write_index_; | |
276 size_t write_count_; | |
277 | |
278 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider); | |
279 }; | |
280 | |
281 // SocketDataProvider which can make decisions about next mock reads based on | |
282 // received writes. It can also be used to enforce order of operations, for | |
283 // example that tested code must send the "Hello!" message before receiving | |
284 // response. This is useful for testing conversation-like protocols like FTP. | |
285 class DynamicSocketDataProvider : public SocketDataProvider { | |
286 public: | |
287 DynamicSocketDataProvider(); | |
288 ~DynamicSocketDataProvider() override; | |
289 | |
290 int short_read_limit() const { return short_read_limit_; } | |
291 void set_short_read_limit(int limit) { short_read_limit_ = limit; } | |
292 | |
293 void allow_unconsumed_reads(bool allow) { allow_unconsumed_reads_ = allow; } | |
294 | |
295 // SocketDataProvider implementation. | |
296 MockRead GetNextRead() override; | |
297 MockWriteResult OnWrite(const std::string& data) override = 0; | |
298 void Reset() override; | |
299 | |
300 protected: | |
301 // The next time there is a read from this socket, it will return |data|. | |
302 // Before calling SimulateRead next time, the previous data must be consumed. | |
303 void SimulateRead(const char* data, size_t length); | |
304 void SimulateRead(const char* data) { SimulateRead(data, std::strlen(data)); } | |
305 | |
306 private: | |
307 std::deque<MockRead> reads_; | |
308 | |
309 // Max number of bytes we will read at a time. 0 means no limit. | |
310 int short_read_limit_; | |
311 | |
312 // If true, we'll not require the client to consume all data before we | |
313 // mock the next read. | |
314 bool allow_unconsumed_reads_; | |
315 | |
316 DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider); | |
317 }; | |
318 | |
319 // SSLSocketDataProviders only need to keep track of the return code from calls | |
320 // to Connect(). | |
321 struct SSLSocketDataProvider { | |
322 SSLSocketDataProvider(IoMode mode, int result); | |
323 ~SSLSocketDataProvider(); | |
324 | |
325 void SetNextProto(NextProto proto); | |
326 | |
327 MockConnect connect; | |
328 SSLClientSocket::NextProtoStatus next_proto_status; | |
329 std::string next_proto; | |
330 bool was_npn_negotiated; | |
331 NextProto protocol_negotiated; | |
332 NextProtoVector next_protos_expected_in_ssl_config; | |
333 bool client_cert_sent; | |
334 SSLCertRequestInfo* cert_request_info; | |
335 scoped_refptr<X509Certificate> cert; | |
336 bool channel_id_sent; | |
337 ChannelIDService* channel_id_service; | |
338 int connection_status; | |
339 // Indicates that the socket should pause in the Connect method. | |
340 bool should_pause_on_connect; | |
341 // Whether or not the Socket should behave like there is a pre-existing | |
342 // session to resume. Whether or not such a session is reported as | |
343 // resumed is controlled by |connection_status|. | |
344 bool is_in_session_cache; | |
345 }; | |
346 | |
347 // A DataProvider where the client must write a request before the reads (e.g. | |
348 // the response) will complete. | |
349 class DelayedSocketData : public StaticSocketDataProvider { | |
350 public: | |
351 // |write_delay| the number of MockWrites to complete before allowing | |
352 // a MockRead to complete. | |
353 // |reads| the list of MockRead completions. | |
354 // |writes| the list of MockWrite completions. | |
355 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a | |
356 // MockRead(true, 0, 0); | |
357 DelayedSocketData(int write_delay, | |
358 MockRead* reads, | |
359 size_t reads_count, | |
360 MockWrite* writes, | |
361 size_t writes_count); | |
362 | |
363 // |connect| the result for the connect phase. | |
364 // |reads| the list of MockRead completions. | |
365 // |write_delay| the number of MockWrites to complete before allowing | |
366 // a MockRead to complete. | |
367 // |writes| the list of MockWrite completions. | |
368 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a | |
369 // MockRead(true, 0, 0); | |
370 DelayedSocketData(const MockConnect& connect, | |
371 int write_delay, | |
372 MockRead* reads, | |
373 size_t reads_count, | |
374 MockWrite* writes, | |
375 size_t writes_count); | |
376 ~DelayedSocketData() override; | |
377 | |
378 void ForceNextRead(); | |
379 | |
380 // StaticSocketDataProvider: | |
381 MockRead GetNextRead() override; | |
382 MockWriteResult OnWrite(const std::string& data) override; | |
383 void Reset() override; | |
384 void CompleteRead() override; | |
385 | |
386 private: | |
387 int write_delay_; | |
388 bool read_in_progress_; | |
389 | |
390 base::WeakPtrFactory<DelayedSocketData> weak_factory_; | |
391 | |
392 DISALLOW_COPY_AND_ASSIGN(DelayedSocketData); | |
393 }; | |
394 | |
395 // A DataProvider where the reads are ordered. | |
396 // If a read is requested before its sequence number is reached, we return an | |
397 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to | |
398 // wait). | |
399 // The sequence number is incremented on every read and write operation. | |
400 // The message loop may be interrupted by setting the high bit of the sequence | |
401 // number in the MockRead's sequence number. When that MockRead is reached, | |
402 // we post a Quit message to the loop. This allows us to interrupt the reading | |
403 // of data before a complete message has arrived, and provides support for | |
404 // testing server push when the request is issued while the response is in the | |
405 // middle of being received. | |
406 class OrderedSocketData : public StaticSocketDataProvider { | |
407 public: | |
408 // |reads| the list of MockRead completions. | |
409 // |writes| the list of MockWrite completions. | |
410 // Note: All MockReads and MockWrites must be async. | |
411 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a | |
412 // MockRead(true, 0, 0); | |
413 OrderedSocketData(MockRead* reads, | |
414 size_t reads_count, | |
415 MockWrite* writes, | |
416 size_t writes_count); | |
417 ~OrderedSocketData() override; | |
418 | |
419 // |connect| the result for the connect phase. | |
420 // |reads| the list of MockRead completions. | |
421 // |writes| the list of MockWrite completions. | |
422 // Note: All MockReads and MockWrites must be async. | |
423 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a | |
424 // MockRead(true, 0, 0); | |
425 OrderedSocketData(const MockConnect& connect, | |
426 MockRead* reads, | |
427 size_t reads_count, | |
428 MockWrite* writes, | |
429 size_t writes_count); | |
430 | |
431 // Posts a quit message to the current message loop, if one is running. | |
432 void EndLoop(); | |
433 | |
434 // StaticSocketDataProvider: | |
435 MockRead GetNextRead() override; | |
436 MockWriteResult OnWrite(const std::string& data) override; | |
437 void Reset() override; | |
438 void CompleteRead() override; | |
439 | |
440 private: | |
441 int sequence_number_; | |
442 int loop_stop_stage_; | |
443 bool blocked_; | |
444 | |
445 base::WeakPtrFactory<OrderedSocketData> weak_factory_; | |
446 | |
447 DISALLOW_COPY_AND_ASSIGN(OrderedSocketData); | |
448 }; | |
449 | |
450 class DeterministicMockTCPClientSocket; | |
451 | |
452 // This class gives the user full control over the network activity, | |
453 // specifically the timing of the COMPLETION of I/O operations. Regardless of | |
454 // the order in which I/O operations are initiated, this class ensures that they | |
455 // complete in the correct order. | |
456 // | |
457 // Network activity is modeled as a sequence of numbered steps which is | |
458 // incremented whenever an I/O operation completes. This can happen under two | |
459 // different circumstances: | |
460 // | |
461 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write() | |
462 // when the corresponding MockRead or MockWrite is marked !async). | |
463 // 2) Running the Run() method of this class. The run method will invoke | |
464 // the current MessageLoop, running all pending events, and will then | |
465 // invoke any pending IO callbacks. | |
466 // | |
467 // In addition, this class allows for I/O processing to "stop" at a specified | |
468 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation | |
469 // by calling Read() or Write() while stopped is permitted if the operation is | |
470 // asynchronous. It is an error to perform synchronous I/O while stopped. | |
471 // | |
472 // When creating the MockReads and MockWrites, note that the sequence number | |
473 // refers to the number of the step in which the I/O will complete. In the | |
474 // case of synchronous I/O, this will be the same step as the I/O is initiated. | |
475 // However, in the case of asynchronous I/O, this I/O may be initiated in | |
476 // a much earlier step. Furthermore, when the a Read() or Write() is separated | |
477 // from its completion by other Read() or Writes()'s, it can not be marked | |
478 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a | |
479 // synchronous Read() or Write() could not be completed synchronously because of | |
480 // the specific ordering constraints. | |
481 // | |
482 // Sequence numbers are preserved across both reads and writes. There should be | |
483 // no gaps in sequence numbers, and no repeated sequence numbers. i.e. | |
484 // MockRead reads[] = { | |
485 // MockRead(false, "first read", length, 0) // sync | |
486 // MockRead(true, "second read", length, 2) // async | |
487 // }; | |
488 // MockWrite writes[] = { | |
489 // MockWrite(true, "first write", length, 1), // async | |
490 // MockWrite(false, "second write", length, 3), // sync | |
491 // }; | |
492 // | |
493 // Example control flow: | |
494 // Read() is called. The current step is 0. The first available read is | |
495 // synchronous, so the call to Read() returns length. The current step is | |
496 // now 1. Next, Read() is called again. The next available read can | |
497 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current | |
498 // step is still 1. Write is called(). The first available write is able to | |
499 // complete in this step, but is marked asynchronous. Write() returns | |
500 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is | |
501 // called which will cause the write callback to be invoked, and will then | |
502 // stop. The current state is now 2. RunFor(1) is called again, which | |
503 // causes the read callback to be invoked, and will then stop. Then current | |
504 // step is 2. Write() is called again. Then next available write is | |
505 // synchronous so the call to Write() returns length. | |
506 // | |
507 // For examples of how to use this class, see: | |
508 // deterministic_socket_data_unittests.cc | |
509 class DeterministicSocketData : public StaticSocketDataProvider { | |
510 public: | |
511 // The Delegate is an abstract interface which handles the communication from | |
512 // the DeterministicSocketData to the Deterministic MockSocket. The | |
513 // MockSockets directly store a pointer to the DeterministicSocketData, | |
514 // whereas the DeterministicSocketData only stores a pointer to the | |
515 // abstract Delegate interface. | |
516 class Delegate { | |
517 public: | |
518 // Returns true if there is currently a write pending. That is to say, if | |
519 // an asynchronous write has been started but the callback has not been | |
520 // invoked. | |
521 virtual bool WritePending() const = 0; | |
522 // Returns true if there is currently a read pending. That is to say, if | |
523 // an asynchronous read has been started but the callback has not been | |
524 // invoked. | |
525 virtual bool ReadPending() const = 0; | |
526 // Called to complete an asynchronous write to execute the write callback. | |
527 virtual void CompleteWrite() = 0; | |
528 // Called to complete an asynchronous read to execute the read callback. | |
529 virtual int CompleteRead() = 0; | |
530 | |
531 protected: | |
532 virtual ~Delegate() {} | |
533 }; | |
534 | |
535 // |reads| the list of MockRead completions. | |
536 // |writes| the list of MockWrite completions. | |
537 DeterministicSocketData(MockRead* reads, | |
538 size_t reads_count, | |
539 MockWrite* writes, | |
540 size_t writes_count); | |
541 ~DeterministicSocketData() override; | |
542 | |
543 // Consume all the data up to the give stop point (via SetStop()). | |
544 void Run(); | |
545 | |
546 // Set the stop point to be |steps| from now, and then invoke Run(). | |
547 void RunFor(int steps); | |
548 | |
549 // Stop at step |seq|, which must be in the future. | |
550 virtual void SetStop(int seq); | |
551 | |
552 // Stop |seq| steps after the current step. | |
553 virtual void StopAfter(int seq); | |
554 bool stopped() const { return stopped_; } | |
555 void SetStopped(bool val) { stopped_ = val; } | |
556 MockRead& current_read() { return current_read_; } | |
557 MockWrite& current_write() { return current_write_; } | |
558 int sequence_number() const { return sequence_number_; } | |
559 void set_delegate(base::WeakPtr<Delegate> delegate) { delegate_ = delegate; } | |
560 | |
561 // StaticSocketDataProvider: | |
562 | |
563 // When the socket calls Read(), that calls GetNextRead(), and expects either | |
564 // ERR_IO_PENDING or data. | |
565 MockRead GetNextRead() override; | |
566 | |
567 // When the socket calls Write(), it always completes synchronously. OnWrite() | |
568 // checks to make sure the written data matches the expected data. The | |
569 // callback will not be invoked until its sequence number is reached. | |
570 MockWriteResult OnWrite(const std::string& data) override; | |
571 void Reset() override; | |
572 void CompleteRead() override {} | |
573 | |
574 private: | |
575 // Invoke the read and write callbacks, if the timing is appropriate. | |
576 void InvokeCallbacks(); | |
577 | |
578 void NextStep(); | |
579 | |
580 void VerifyCorrectSequenceNumbers(MockRead* reads, | |
581 size_t reads_count, | |
582 MockWrite* writes, | |
583 size_t writes_count); | |
584 | |
585 int sequence_number_; | |
586 MockRead current_read_; | |
587 MockWrite current_write_; | |
588 int stopping_sequence_number_; | |
589 bool stopped_; | |
590 base::WeakPtr<Delegate> delegate_; | |
591 bool print_debug_; | |
592 bool is_running_; | |
593 }; | |
594 | |
595 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket | |
596 // objects get instantiated, they take their data from the i'th element of this | |
597 // array. | |
598 template <typename T> | |
599 class SocketDataProviderArray { | |
600 public: | |
601 SocketDataProviderArray() : next_index_(0) {} | |
602 | |
603 T* GetNext() { | |
604 DCHECK_LT(next_index_, data_providers_.size()); | |
605 return data_providers_[next_index_++]; | |
606 } | |
607 | |
608 void Add(T* data_provider) { | |
609 DCHECK(data_provider); | |
610 data_providers_.push_back(data_provider); | |
611 } | |
612 | |
613 size_t next_index() { return next_index_; } | |
614 | |
615 void ResetNextIndex() { next_index_ = 0; } | |
616 | |
617 private: | |
618 // Index of the next |data_providers_| element to use. Not an iterator | |
619 // because those are invalidated on vector reallocation. | |
620 size_t next_index_; | |
621 | |
622 // SocketDataProviders to be returned. | |
623 std::vector<T*> data_providers_; | |
624 }; | |
625 | |
626 class MockUDPClientSocket; | |
627 class MockTCPClientSocket; | |
628 class MockSSLClientSocket; | |
629 | |
630 // ClientSocketFactory which contains arrays of sockets of each type. | |
631 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory | |
632 // is asked to create a socket, it takes next entry from appropriate array. | |
633 // You can use ResetNextMockIndexes to reset that next entry index for all mock | |
634 // socket types. | |
635 class MockClientSocketFactory : public ClientSocketFactory { | |
636 public: | |
637 MockClientSocketFactory(); | |
638 ~MockClientSocketFactory() override; | |
639 | |
640 void AddSocketDataProvider(SocketDataProvider* socket); | |
641 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket); | |
642 void ResetNextMockIndexes(); | |
643 | |
644 SocketDataProviderArray<SocketDataProvider>& mock_data() { | |
645 return mock_data_; | |
646 } | |
647 | |
648 // Note: this method is unsafe; the elements of the returned vector | |
649 // are not necessarily valid. | |
650 const std::vector<MockSSLClientSocket*>& ssl_client_sockets() const { | |
651 return ssl_client_sockets_; | |
652 } | |
653 | |
654 // ClientSocketFactory | |
655 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( | |
656 DatagramSocket::BindType bind_type, | |
657 const RandIntCallback& rand_int_cb, | |
658 NetLog* net_log, | |
659 const NetLog::Source& source) override; | |
660 scoped_ptr<StreamSocket> CreateTransportClientSocket( | |
661 const AddressList& addresses, | |
662 NetLog* net_log, | |
663 const NetLog::Source& source) override; | |
664 scoped_ptr<SSLClientSocket> CreateSSLClientSocket( | |
665 scoped_ptr<ClientSocketHandle> transport_socket, | |
666 const HostPortPair& host_and_port, | |
667 const SSLConfig& ssl_config, | |
668 const SSLClientSocketContext& context) override; | |
669 void ClearSSLSessionCache() override; | |
670 | |
671 private: | |
672 SocketDataProviderArray<SocketDataProvider> mock_data_; | |
673 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_; | |
674 std::vector<MockSSLClientSocket*> ssl_client_sockets_; | |
675 }; | |
676 | |
677 class MockClientSocket : public SSLClientSocket { | |
678 public: | |
679 // Value returned by GetTLSUniqueChannelBinding(). | |
680 static const char kTlsUnique[]; | |
681 | |
682 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as | |
683 // unique socket IDs. | |
684 explicit MockClientSocket(const BoundNetLog& net_log); | |
685 | |
686 // Socket implementation. | |
687 int Read(IOBuffer* buf, | |
688 int buf_len, | |
689 const CompletionCallback& callback) override = 0; | |
690 int Write(IOBuffer* buf, | |
691 int buf_len, | |
692 const CompletionCallback& callback) override = 0; | |
693 int SetReceiveBufferSize(int32 size) override; | |
694 int SetSendBufferSize(int32 size) override; | |
695 | |
696 // StreamSocket implementation. | |
697 int Connect(const CompletionCallback& callback) override = 0; | |
698 void Disconnect() override; | |
699 bool IsConnected() const override; | |
700 bool IsConnectedAndIdle() const override; | |
701 int GetPeerAddress(IPEndPoint* address) const override; | |
702 int GetLocalAddress(IPEndPoint* address) const override; | |
703 const BoundNetLog& NetLog() const override; | |
704 void SetSubresourceSpeculation() override {} | |
705 void SetOmniboxSpeculation() override {} | |
706 | |
707 // SSLClientSocket implementation. | |
708 std::string GetSessionCacheKey() const override; | |
709 bool InSessionCache() const override; | |
710 void SetHandshakeCompletionCallback(const base::Closure& cb) override; | |
711 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; | |
712 int ExportKeyingMaterial(const base::StringPiece& label, | |
713 bool has_context, | |
714 const base::StringPiece& context, | |
715 unsigned char* out, | |
716 unsigned int outlen) override; | |
717 int GetTLSUniqueChannelBinding(std::string* out) override; | |
718 NextProtoStatus GetNextProto(std::string* proto) override; | |
719 ChannelIDService* GetChannelIDService() const override; | |
720 | |
721 protected: | |
722 ~MockClientSocket() override; | |
723 void RunCallbackAsync(const CompletionCallback& callback, int result); | |
724 void RunCallback(const CompletionCallback& callback, int result); | |
725 | |
726 // SSLClientSocket implementation. | |
727 scoped_refptr<X509Certificate> GetUnverifiedServerCertificateChain() | |
728 const override; | |
729 | |
730 // True if Connect completed successfully and Disconnect hasn't been called. | |
731 bool connected_; | |
732 | |
733 // Address of the "remote" peer we're connected to. | |
734 IPEndPoint peer_addr_; | |
735 | |
736 BoundNetLog net_log_; | |
737 | |
738 private: | |
739 base::WeakPtrFactory<MockClientSocket> weak_factory_; | |
740 | |
741 DISALLOW_COPY_AND_ASSIGN(MockClientSocket); | |
742 }; | |
743 | |
744 class MockTCPClientSocket : public MockClientSocket, public AsyncSocket { | |
745 public: | |
746 MockTCPClientSocket(const AddressList& addresses, | |
747 net::NetLog* net_log, | |
748 SocketDataProvider* socket); | |
749 ~MockTCPClientSocket() override; | |
750 | |
751 const AddressList& addresses() const { return addresses_; } | |
752 | |
753 // Socket implementation. | |
754 int Read(IOBuffer* buf, | |
755 int buf_len, | |
756 const CompletionCallback& callback) override; | |
757 int Write(IOBuffer* buf, | |
758 int buf_len, | |
759 const CompletionCallback& callback) override; | |
760 | |
761 // StreamSocket implementation. | |
762 int Connect(const CompletionCallback& callback) override; | |
763 void Disconnect() override; | |
764 bool IsConnected() const override; | |
765 bool IsConnectedAndIdle() const override; | |
766 int GetPeerAddress(IPEndPoint* address) const override; | |
767 bool WasEverUsed() const override; | |
768 bool UsingTCPFastOpen() const override; | |
769 bool WasNpnNegotiated() const override; | |
770 bool GetSSLInfo(SSLInfo* ssl_info) override; | |
771 | |
772 // AsyncSocket: | |
773 void OnReadComplete(const MockRead& data) override; | |
774 void OnConnectComplete(const MockConnect& data) override; | |
775 | |
776 private: | |
777 int CompleteRead(); | |
778 | |
779 AddressList addresses_; | |
780 | |
781 SocketDataProvider* data_; | |
782 int read_offset_; | |
783 MockRead read_data_; | |
784 bool need_read_data_; | |
785 | |
786 // True if the peer has closed the connection. This allows us to simulate | |
787 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real | |
788 // TCPClientSocket. | |
789 bool peer_closed_connection_; | |
790 | |
791 // While an asynchronous IO is pending, we save our user-buffer state. | |
792 scoped_refptr<IOBuffer> pending_buf_; | |
793 int pending_buf_len_; | |
794 CompletionCallback pending_callback_; | |
795 bool was_used_to_convey_data_; | |
796 | |
797 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket); | |
798 }; | |
799 | |
800 // DeterministicSocketHelper is a helper class that can be used | |
801 // to simulate net::Socket::Read() and net::Socket::Write() | |
802 // using deterministic |data|. | |
803 // Note: This is provided as a common helper class because | |
804 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a | |
805 // desire not to introduce an additional common base class. | |
806 class DeterministicSocketHelper { | |
807 public: | |
808 DeterministicSocketHelper(net::NetLog* net_log, | |
809 DeterministicSocketData* data); | |
810 virtual ~DeterministicSocketHelper(); | |
811 | |
812 bool write_pending() const { return write_pending_; } | |
813 bool read_pending() const { return read_pending_; } | |
814 | |
815 void CompleteWrite(); | |
816 int CompleteRead(); | |
817 | |
818 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback); | |
819 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback); | |
820 | |
821 const BoundNetLog& net_log() const { return net_log_; } | |
822 | |
823 bool was_used_to_convey_data() const { return was_used_to_convey_data_; } | |
824 | |
825 bool peer_closed_connection() const { return peer_closed_connection_; } | |
826 | |
827 DeterministicSocketData* data() const { return data_; } | |
828 | |
829 private: | |
830 bool write_pending_; | |
831 CompletionCallback write_callback_; | |
832 int write_result_; | |
833 | |
834 MockRead read_data_; | |
835 | |
836 IOBuffer* read_buf_; | |
837 int read_buf_len_; | |
838 bool read_pending_; | |
839 CompletionCallback read_callback_; | |
840 DeterministicSocketData* data_; | |
841 bool was_used_to_convey_data_; | |
842 bool peer_closed_connection_; | |
843 BoundNetLog net_log_; | |
844 }; | |
845 | |
846 // Mock UDP socket to be used in conjunction with DeterministicSocketData. | |
847 class DeterministicMockUDPClientSocket | |
848 : public DatagramClientSocket, | |
849 public AsyncSocket, | |
850 public DeterministicSocketData::Delegate, | |
851 public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> { | |
852 public: | |
853 DeterministicMockUDPClientSocket(net::NetLog* net_log, | |
854 DeterministicSocketData* data); | |
855 ~DeterministicMockUDPClientSocket() override; | |
856 | |
857 // DeterministicSocketData::Delegate: | |
858 bool WritePending() const override; | |
859 bool ReadPending() const override; | |
860 void CompleteWrite() override; | |
861 int CompleteRead() override; | |
862 | |
863 // Socket implementation. | |
864 int Read(IOBuffer* buf, | |
865 int buf_len, | |
866 const CompletionCallback& callback) override; | |
867 int Write(IOBuffer* buf, | |
868 int buf_len, | |
869 const CompletionCallback& callback) override; | |
870 int SetReceiveBufferSize(int32 size) override; | |
871 int SetSendBufferSize(int32 size) override; | |
872 | |
873 // DatagramSocket implementation. | |
874 void Close() override; | |
875 int GetPeerAddress(IPEndPoint* address) const override; | |
876 int GetLocalAddress(IPEndPoint* address) const override; | |
877 const BoundNetLog& NetLog() const override; | |
878 | |
879 // DatagramClientSocket implementation. | |
880 int Connect(const IPEndPoint& address) override; | |
881 | |
882 // AsyncSocket implementation. | |
883 void OnReadComplete(const MockRead& data) override; | |
884 void OnConnectComplete(const MockConnect& data) override; | |
885 | |
886 void set_source_port(uint16 port) { source_port_ = port; } | |
887 | |
888 private: | |
889 bool connected_; | |
890 IPEndPoint peer_address_; | |
891 DeterministicSocketHelper helper_; | |
892 uint16 source_port_; // Ephemeral source port. | |
893 | |
894 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket); | |
895 }; | |
896 | |
897 // Mock TCP socket to be used in conjunction with DeterministicSocketData. | |
898 class DeterministicMockTCPClientSocket | |
899 : public MockClientSocket, | |
900 public AsyncSocket, | |
901 public DeterministicSocketData::Delegate, | |
902 public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> { | |
903 public: | |
904 DeterministicMockTCPClientSocket(net::NetLog* net_log, | |
905 DeterministicSocketData* data); | |
906 ~DeterministicMockTCPClientSocket() override; | |
907 | |
908 // DeterministicSocketData::Delegate: | |
909 bool WritePending() const override; | |
910 bool ReadPending() const override; | |
911 void CompleteWrite() override; | |
912 int CompleteRead() override; | |
913 | |
914 // Socket: | |
915 int Write(IOBuffer* buf, | |
916 int buf_len, | |
917 const CompletionCallback& callback) override; | |
918 int Read(IOBuffer* buf, | |
919 int buf_len, | |
920 const CompletionCallback& callback) override; | |
921 | |
922 // StreamSocket: | |
923 int Connect(const CompletionCallback& callback) override; | |
924 void Disconnect() override; | |
925 bool IsConnected() const override; | |
926 bool IsConnectedAndIdle() const override; | |
927 bool WasEverUsed() const override; | |
928 bool UsingTCPFastOpen() const override; | |
929 bool WasNpnNegotiated() const override; | |
930 bool GetSSLInfo(SSLInfo* ssl_info) override; | |
931 | |
932 // AsyncSocket: | |
933 void OnReadComplete(const MockRead& data) override; | |
934 void OnConnectComplete(const MockConnect& data) override; | |
935 | |
936 private: | |
937 DeterministicSocketHelper helper_; | |
938 | |
939 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket); | |
940 }; | |
941 | |
942 class MockSSLClientSocket : public MockClientSocket, public AsyncSocket { | |
943 public: | |
944 MockSSLClientSocket(scoped_ptr<ClientSocketHandle> transport_socket, | |
945 const HostPortPair& host_and_port, | |
946 const SSLConfig& ssl_config, | |
947 SSLSocketDataProvider* socket); | |
948 ~MockSSLClientSocket() override; | |
949 | |
950 // Socket implementation. | |
951 int Read(IOBuffer* buf, | |
952 int buf_len, | |
953 const CompletionCallback& callback) override; | |
954 int Write(IOBuffer* buf, | |
955 int buf_len, | |
956 const CompletionCallback& callback) override; | |
957 | |
958 // StreamSocket implementation. | |
959 int Connect(const CompletionCallback& callback) override; | |
960 void Disconnect() override; | |
961 bool IsConnected() const override; | |
962 bool WasEverUsed() const override; | |
963 bool UsingTCPFastOpen() const override; | |
964 int GetPeerAddress(IPEndPoint* address) const override; | |
965 bool WasNpnNegotiated() const override; | |
966 bool GetSSLInfo(SSLInfo* ssl_info) override; | |
967 | |
968 // SSLClientSocket implementation. | |
969 std::string GetSessionCacheKey() const override; | |
970 bool InSessionCache() const override; | |
971 void SetHandshakeCompletionCallback(const base::Closure& cb) override; | |
972 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override; | |
973 NextProtoStatus GetNextProto(std::string* proto) override; | |
974 bool set_was_npn_negotiated(bool negotiated) override; | |
975 void set_protocol_negotiated(NextProto protocol_negotiated) override; | |
976 NextProto GetNegotiatedProtocol() const override; | |
977 | |
978 // This MockSocket does not implement the manual async IO feature. | |
979 void OnReadComplete(const MockRead& data) override; | |
980 void OnConnectComplete(const MockConnect& data) override; | |
981 | |
982 bool WasChannelIDSent() const override; | |
983 void set_channel_id_sent(bool channel_id_sent) override; | |
984 ChannelIDService* GetChannelIDService() const override; | |
985 | |
986 bool reached_connect() const { return reached_connect_; } | |
987 | |
988 // Resumes the connection of a socket that was paused for testing. | |
989 // |connect_callback_| should be set before invoking this method. | |
990 void RestartPausedConnect(); | |
991 | |
992 private: | |
993 enum ConnectState { | |
994 STATE_NONE, | |
995 STATE_SSL_CONNECT, | |
996 STATE_SSL_CONNECT_COMPLETE, | |
997 }; | |
998 | |
999 void OnIOComplete(int result); | |
1000 | |
1001 // Runs the state transistion loop. | |
1002 int DoConnectLoop(int result); | |
1003 | |
1004 int DoSSLConnect(); | |
1005 int DoSSLConnectComplete(int result); | |
1006 | |
1007 scoped_ptr<ClientSocketHandle> transport_; | |
1008 HostPortPair host_port_pair_; | |
1009 SSLSocketDataProvider* data_; | |
1010 bool is_npn_state_set_; | |
1011 bool new_npn_value_; | |
1012 bool is_protocol_negotiated_set_; | |
1013 NextProto protocol_negotiated_; | |
1014 | |
1015 CompletionCallback connect_callback_; | |
1016 // Indicates what state of Connect the socket should enter. | |
1017 ConnectState next_connect_state_; | |
1018 // True if the Connect method has been called on the socket. | |
1019 bool reached_connect_; | |
1020 | |
1021 base::Closure handshake_completion_callback_; | |
1022 | |
1023 base::WeakPtrFactory<MockSSLClientSocket> weak_factory_; | |
1024 | |
1025 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket); | |
1026 }; | |
1027 | |
1028 class MockUDPClientSocket : public DatagramClientSocket, public AsyncSocket { | |
1029 public: | |
1030 MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log); | |
1031 ~MockUDPClientSocket() override; | |
1032 | |
1033 // Socket implementation. | |
1034 int Read(IOBuffer* buf, | |
1035 int buf_len, | |
1036 const CompletionCallback& callback) override; | |
1037 int Write(IOBuffer* buf, | |
1038 int buf_len, | |
1039 const CompletionCallback& callback) override; | |
1040 int SetReceiveBufferSize(int32 size) override; | |
1041 int SetSendBufferSize(int32 size) override; | |
1042 | |
1043 // DatagramSocket implementation. | |
1044 void Close() override; | |
1045 int GetPeerAddress(IPEndPoint* address) const override; | |
1046 int GetLocalAddress(IPEndPoint* address) const override; | |
1047 const BoundNetLog& NetLog() const override; | |
1048 | |
1049 // DatagramClientSocket implementation. | |
1050 int Connect(const IPEndPoint& address) override; | |
1051 | |
1052 // AsyncSocket implementation. | |
1053 void OnReadComplete(const MockRead& data) override; | |
1054 void OnConnectComplete(const MockConnect& data) override; | |
1055 | |
1056 void set_source_port(uint16 port) { source_port_ = port;} | |
1057 | |
1058 private: | |
1059 int CompleteRead(); | |
1060 | |
1061 void RunCallbackAsync(const CompletionCallback& callback, int result); | |
1062 void RunCallback(const CompletionCallback& callback, int result); | |
1063 | |
1064 bool connected_; | |
1065 SocketDataProvider* data_; | |
1066 int read_offset_; | |
1067 MockRead read_data_; | |
1068 bool need_read_data_; | |
1069 uint16 source_port_; // Ephemeral source port. | |
1070 | |
1071 // Address of the "remote" peer we're connected to. | |
1072 IPEndPoint peer_addr_; | |
1073 | |
1074 // While an asynchronous IO is pending, we save our user-buffer state. | |
1075 scoped_refptr<IOBuffer> pending_buf_; | |
1076 int pending_buf_len_; | |
1077 CompletionCallback pending_callback_; | |
1078 | |
1079 BoundNetLog net_log_; | |
1080 | |
1081 base::WeakPtrFactory<MockUDPClientSocket> weak_factory_; | |
1082 | |
1083 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket); | |
1084 }; | |
1085 | |
1086 class TestSocketRequest : public TestCompletionCallbackBase { | |
1087 public: | |
1088 TestSocketRequest(std::vector<TestSocketRequest*>* request_order, | |
1089 size_t* completion_count); | |
1090 ~TestSocketRequest() override; | |
1091 | |
1092 ClientSocketHandle* handle() { return &handle_; } | |
1093 | |
1094 const net::CompletionCallback& callback() const { return callback_; } | |
1095 | |
1096 private: | |
1097 void OnComplete(int result); | |
1098 | |
1099 ClientSocketHandle handle_; | |
1100 std::vector<TestSocketRequest*>* request_order_; | |
1101 size_t* completion_count_; | |
1102 CompletionCallback callback_; | |
1103 | |
1104 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest); | |
1105 }; | |
1106 | |
1107 class ClientSocketPoolTest { | |
1108 public: | |
1109 enum KeepAlive { | |
1110 KEEP_ALIVE, | |
1111 | |
1112 // A socket will be disconnected in addition to handle being reset. | |
1113 NO_KEEP_ALIVE, | |
1114 }; | |
1115 | |
1116 static const int kIndexOutOfBounds; | |
1117 static const int kRequestNotFound; | |
1118 | |
1119 ClientSocketPoolTest(); | |
1120 ~ClientSocketPoolTest(); | |
1121 | |
1122 template <typename PoolType> | |
1123 int StartRequestUsingPool( | |
1124 PoolType* socket_pool, | |
1125 const std::string& group_name, | |
1126 RequestPriority priority, | |
1127 const scoped_refptr<typename PoolType::SocketParams>& socket_params) { | |
1128 DCHECK(socket_pool); | |
1129 TestSocketRequest* request = | |
1130 new TestSocketRequest(&request_order_, &completion_count_); | |
1131 requests_.push_back(request); | |
1132 int rv = request->handle()->Init(group_name, | |
1133 socket_params, | |
1134 priority, | |
1135 request->callback(), | |
1136 socket_pool, | |
1137 BoundNetLog()); | |
1138 if (rv != ERR_IO_PENDING) | |
1139 request_order_.push_back(request); | |
1140 return rv; | |
1141 } | |
1142 | |
1143 // Provided there were n requests started, takes |index| in range 1..n | |
1144 // and returns order in which that request completed, in range 1..n, | |
1145 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound | |
1146 // if that request did not complete (for example was canceled). | |
1147 int GetOrderOfRequest(size_t index) const; | |
1148 | |
1149 // Resets first initialized socket handle from |requests_|. If found such | |
1150 // a handle, returns true. | |
1151 bool ReleaseOneConnection(KeepAlive keep_alive); | |
1152 | |
1153 // Releases connections until there is nothing to release. | |
1154 void ReleaseAllConnections(KeepAlive keep_alive); | |
1155 | |
1156 // Note that this uses 0-based indices, while GetOrderOfRequest takes and | |
1157 // returns 0-based indices. | |
1158 TestSocketRequest* request(int i) { return requests_[i]; } | |
1159 | |
1160 size_t requests_size() const { return requests_.size(); } | |
1161 ScopedVector<TestSocketRequest>* requests() { return &requests_; } | |
1162 size_t completion_count() const { return completion_count_; } | |
1163 | |
1164 private: | |
1165 ScopedVector<TestSocketRequest> requests_; | |
1166 std::vector<TestSocketRequest*> request_order_; | |
1167 size_t completion_count_; | |
1168 | |
1169 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest); | |
1170 }; | |
1171 | |
1172 class MockTransportSocketParams | |
1173 : public base::RefCounted<MockTransportSocketParams> { | |
1174 private: | |
1175 friend class base::RefCounted<MockTransportSocketParams>; | |
1176 ~MockTransportSocketParams() {} | |
1177 | |
1178 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams); | |
1179 }; | |
1180 | |
1181 class MockTransportClientSocketPool : public TransportClientSocketPool { | |
1182 public: | |
1183 typedef MockTransportSocketParams SocketParams; | |
1184 | |
1185 class MockConnectJob { | |
1186 public: | |
1187 MockConnectJob(scoped_ptr<StreamSocket> socket, | |
1188 ClientSocketHandle* handle, | |
1189 const CompletionCallback& callback); | |
1190 ~MockConnectJob(); | |
1191 | |
1192 int Connect(); | |
1193 bool CancelHandle(const ClientSocketHandle* handle); | |
1194 | |
1195 private: | |
1196 void OnConnect(int rv); | |
1197 | |
1198 scoped_ptr<StreamSocket> socket_; | |
1199 ClientSocketHandle* handle_; | |
1200 CompletionCallback user_callback_; | |
1201 | |
1202 DISALLOW_COPY_AND_ASSIGN(MockConnectJob); | |
1203 }; | |
1204 | |
1205 MockTransportClientSocketPool(int max_sockets, | |
1206 int max_sockets_per_group, | |
1207 ClientSocketPoolHistograms* histograms, | |
1208 ClientSocketFactory* socket_factory); | |
1209 | |
1210 ~MockTransportClientSocketPool() override; | |
1211 | |
1212 RequestPriority last_request_priority() const { | |
1213 return last_request_priority_; | |
1214 } | |
1215 int release_count() const { return release_count_; } | |
1216 int cancel_count() const { return cancel_count_; } | |
1217 | |
1218 // TransportClientSocketPool implementation. | |
1219 int RequestSocket(const std::string& group_name, | |
1220 const void* socket_params, | |
1221 RequestPriority priority, | |
1222 ClientSocketHandle* handle, | |
1223 const CompletionCallback& callback, | |
1224 const BoundNetLog& net_log) override; | |
1225 | |
1226 void CancelRequest(const std::string& group_name, | |
1227 ClientSocketHandle* handle) override; | |
1228 void ReleaseSocket(const std::string& group_name, | |
1229 scoped_ptr<StreamSocket> socket, | |
1230 int id) override; | |
1231 | |
1232 private: | |
1233 ClientSocketFactory* client_socket_factory_; | |
1234 ScopedVector<MockConnectJob> job_list_; | |
1235 RequestPriority last_request_priority_; | |
1236 int release_count_; | |
1237 int cancel_count_; | |
1238 | |
1239 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool); | |
1240 }; | |
1241 | |
1242 class DeterministicMockClientSocketFactory : public ClientSocketFactory { | |
1243 public: | |
1244 DeterministicMockClientSocketFactory(); | |
1245 ~DeterministicMockClientSocketFactory() override; | |
1246 | |
1247 void AddSocketDataProvider(DeterministicSocketData* socket); | |
1248 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket); | |
1249 void ResetNextMockIndexes(); | |
1250 | |
1251 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory | |
1252 // created. | |
1253 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const; | |
1254 | |
1255 SocketDataProviderArray<DeterministicSocketData>& mock_data() { | |
1256 return mock_data_; | |
1257 } | |
1258 std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() { | |
1259 return tcp_client_sockets_; | |
1260 } | |
1261 std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() { | |
1262 return udp_client_sockets_; | |
1263 } | |
1264 | |
1265 // ClientSocketFactory | |
1266 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket( | |
1267 DatagramSocket::BindType bind_type, | |
1268 const RandIntCallback& rand_int_cb, | |
1269 NetLog* net_log, | |
1270 const NetLog::Source& source) override; | |
1271 scoped_ptr<StreamSocket> CreateTransportClientSocket( | |
1272 const AddressList& addresses, | |
1273 NetLog* net_log, | |
1274 const NetLog::Source& source) override; | |
1275 scoped_ptr<SSLClientSocket> CreateSSLClientSocket( | |
1276 scoped_ptr<ClientSocketHandle> transport_socket, | |
1277 const HostPortPair& host_and_port, | |
1278 const SSLConfig& ssl_config, | |
1279 const SSLClientSocketContext& context) override; | |
1280 void ClearSSLSessionCache() override; | |
1281 | |
1282 private: | |
1283 SocketDataProviderArray<DeterministicSocketData> mock_data_; | |
1284 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_; | |
1285 | |
1286 // Store pointers to handed out sockets in case the test wants to get them. | |
1287 std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_; | |
1288 std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_; | |
1289 std::vector<MockSSLClientSocket*> ssl_client_sockets_; | |
1290 | |
1291 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory); | |
1292 }; | |
1293 | |
1294 class MockSOCKSClientSocketPool : public SOCKSClientSocketPool { | |
1295 public: | |
1296 MockSOCKSClientSocketPool(int max_sockets, | |
1297 int max_sockets_per_group, | |
1298 ClientSocketPoolHistograms* histograms, | |
1299 TransportClientSocketPool* transport_pool); | |
1300 | |
1301 ~MockSOCKSClientSocketPool() override; | |
1302 | |
1303 // SOCKSClientSocketPool implementation. | |
1304 int RequestSocket(const std::string& group_name, | |
1305 const void* socket_params, | |
1306 RequestPriority priority, | |
1307 ClientSocketHandle* handle, | |
1308 const CompletionCallback& callback, | |
1309 const BoundNetLog& net_log) override; | |
1310 | |
1311 void CancelRequest(const std::string& group_name, | |
1312 ClientSocketHandle* handle) override; | |
1313 void ReleaseSocket(const std::string& group_name, | |
1314 scoped_ptr<StreamSocket> socket, | |
1315 int id) override; | |
1316 | |
1317 private: | |
1318 TransportClientSocketPool* const transport_pool_; | |
1319 | |
1320 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool); | |
1321 }; | |
1322 | |
1323 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock | |
1324 // delay to zero for testing purposes. Automatically restores the original value | |
1325 // when destroyed. | |
1326 class ScopedWebSocketEndpointZeroUnlockDelay { | |
1327 public: | |
1328 ScopedWebSocketEndpointZeroUnlockDelay(); | |
1329 ~ScopedWebSocketEndpointZeroUnlockDelay(); | |
1330 | |
1331 private: | |
1332 base::TimeDelta old_delay_; | |
1333 }; | |
1334 | |
1335 // Constants for a successful SOCKS v5 handshake. | |
1336 extern const char kSOCKS5GreetRequest[]; | |
1337 extern const int kSOCKS5GreetRequestLength; | |
1338 | |
1339 extern const char kSOCKS5GreetResponse[]; | |
1340 extern const int kSOCKS5GreetResponseLength; | |
1341 | |
1342 extern const char kSOCKS5OkRequest[]; | |
1343 extern const int kSOCKS5OkRequestLength; | |
1344 | |
1345 extern const char kSOCKS5OkResponse[]; | |
1346 extern const int kSOCKS5OkResponseLength; | |
1347 | |
1348 } // namespace net | |
1349 | |
1350 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_ | |
OLD | NEW |