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 #ifndef NET_SOCKET_SOCKET_TEST_UTIL_H_
6 #define NET_SOCKET_SOCKET_TEST_UTIL_H_
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 "net/base/address_list.h"
22 #include "net/base/io_buffer.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/net_log.h"
25 #include "net/base/test_completion_callback.h"
26 #include "net/http/http_auth_controller.h"
27 #include "net/http/http_proxy_client_socket_pool.h"
28 #include "net/socket/client_socket_factory.h"
29 #include "net/socket/client_socket_handle.h"
30 #include "net/socket/socks_client_socket_pool.h"
31 #include "net/socket/ssl_client_socket.h"
32 #include "net/socket/ssl_client_socket_pool.h"
33 #include "net/socket/transport_client_socket_pool.h"
34 #include "net/ssl/ssl_config_service.h"
35 #include "net/udp/datagram_client_socket.h"
36 #include "testing/gtest/include/gtest/gtest.h"
41 // A private network error code used by the socket test utility classes.
42 // If the |result| member of a MockRead is
43 // ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ, that MockRead is just a
44 // marker that indicates the peer will close the connection after the next
45 // MockRead. The other members of that MockRead are ignored.
46 ERR_TEST_PEER_CLOSE_AFTER_NEXT_MOCK_READ = -10000,
50 class MockClientSocket;
51 class ServerBoundCertService;
52 class SSLClientSocket;
61 // Asynchronous connection success.
62 // Creates a MockConnect with |mode| ASYC, |result| OK, and
63 // |peer_addr| 192.0.2.33.
65 // Creates a MockConnect with the specified mode and result, with
66 // |peer_addr| 192.0.2.33.
67 MockConnect(IoMode io_mode, int r);
68 MockConnect(IoMode io_mode, int r, IPEndPoint addr);
76 // MockRead and MockWrite shares the same interface and members, but we'd like
77 // to have distinct types because we don't want to have them used
78 // interchangably. To do this, a struct template is defined, and MockRead and
79 // MockWrite are instantiated by using this template. Template parameter |type|
80 // is not used in the struct definition (it purely exists for creating a new
83 // |data| in MockRead and MockWrite has different meanings: |data| in MockRead
84 // is the data returned from the socket when MockTCPClientSocket::Read() is
85 // attempted, while |data| in MockWrite is the expected data that should be
86 // given in MockTCPClientSocket::Write().
87 enum MockReadWriteType {
92 template <MockReadWriteType type>
93 struct MockReadWrite {
94 // Flag to indicate that the message loop should be terminated.
100 MockReadWrite() : mode(SYNCHRONOUS), result(0), data(NULL), data_len(0),
101 sequence_number(0), time_stamp(base::Time::Now()) {}
103 // Read/write failure (no data).
104 MockReadWrite(IoMode io_mode, int result) : mode(io_mode), result(result),
105 data(NULL), data_len(0), sequence_number(0),
106 time_stamp(base::Time::Now()) { }
108 // Read/write failure (no data), with sequence information.
109 MockReadWrite(IoMode io_mode, int result, int seq) : mode(io_mode),
110 result(result), data(NULL), data_len(0), sequence_number(seq),
111 time_stamp(base::Time::Now()) { }
113 // Asynchronous read/write success (inferred data length).
114 explicit MockReadWrite(const char* data) : mode(ASYNC), result(0),
115 data(data), data_len(strlen(data)), sequence_number(0),
116 time_stamp(base::Time::Now()) { }
118 // Read/write success (inferred data length).
119 MockReadWrite(IoMode io_mode, const char* data) : mode(io_mode), result(0),
120 data(data), data_len(strlen(data)), sequence_number(0),
121 time_stamp(base::Time::Now()) { }
123 // Read/write success.
124 MockReadWrite(IoMode io_mode, const char* data, int data_len) : mode(io_mode),
125 result(0), data(data), data_len(data_len), sequence_number(0),
126 time_stamp(base::Time::Now()) { }
128 // Read/write success (inferred data length) with sequence information.
129 MockReadWrite(IoMode io_mode, int seq, const char* data) : mode(io_mode),
130 result(0), data(data), data_len(strlen(data)), sequence_number(seq),
131 time_stamp(base::Time::Now()) { }
133 // Read/write success with sequence information.
134 MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq) :
135 mode(io_mode), result(0), data(data), data_len(data_len),
136 sequence_number(seq), time_stamp(base::Time::Now()) { }
143 // For OrderedSocketData, which only allows reads to occur in a particular
144 // sequence. If a read occurs before the given |sequence_number| is reached,
145 // an ERR_IO_PENDING is returned.
146 int sequence_number; // The sequence number at which a read is allowed
148 base::Time time_stamp; // The time stamp at which the operation occurred.
151 typedef MockReadWrite<MOCK_READ> MockRead;
152 typedef MockReadWrite<MOCK_WRITE> MockWrite;
154 struct MockWriteResult {
155 MockWriteResult(IoMode io_mode, int result)
163 // The SocketDataProvider is an interface used by the MockClientSocket
164 // for getting data about individual reads and writes on the socket.
165 class SocketDataProvider {
167 SocketDataProvider() : socket_(NULL) {}
169 virtual ~SocketDataProvider() {}
171 // Returns the buffer and result code for the next simulated read.
172 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
173 // that it will be called via the AsyncSocket::OnReadComplete()
174 // function at a later time.
175 virtual MockRead GetNextRead() = 0;
176 virtual MockWriteResult OnWrite(const std::string& data) = 0;
177 virtual void Reset() = 0;
179 // Accessor for the socket which is using the SocketDataProvider.
180 AsyncSocket* socket() { return socket_; }
181 void set_socket(AsyncSocket* socket) { socket_ = socket; }
183 MockConnect connect_data() const { return connect_; }
184 void set_connect_data(const MockConnect& connect) { connect_ = connect; }
187 MockConnect connect_;
188 AsyncSocket* socket_;
190 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider);
193 // The AsyncSocket is an interface used by the SocketDataProvider to
194 // complete the asynchronous read operation.
197 // If an async IO is pending because the SocketDataProvider returned
198 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
199 // is called to complete the asynchronous read operation.
200 // data.async is ignored, and this read is completed synchronously as
201 // part of this call.
202 virtual void OnReadComplete(const MockRead& data) = 0;
203 virtual void OnConnectComplete(const MockConnect& data) = 0;
206 // SocketDataProvider which responds based on static tables of mock reads and
208 class StaticSocketDataProvider : public SocketDataProvider {
210 StaticSocketDataProvider();
211 StaticSocketDataProvider(MockRead* reads, size_t reads_count,
212 MockWrite* writes, size_t writes_count);
213 virtual ~StaticSocketDataProvider();
215 // These functions get access to the next available read and write data.
216 const MockRead& PeekRead() const;
217 const MockWrite& PeekWrite() const;
218 // These functions get random access to the read and write data, for timing.
219 const MockRead& PeekRead(size_t index) const;
220 const MockWrite& PeekWrite(size_t index) const;
221 size_t read_index() const { return read_index_; }
222 size_t write_index() const { return write_index_; }
223 size_t read_count() const { return read_count_; }
224 size_t write_count() const { return write_count_; }
226 bool at_read_eof() const { return read_index_ >= read_count_; }
227 bool at_write_eof() const { return write_index_ >= write_count_; }
229 virtual void CompleteRead() {}
231 // SocketDataProvider implementation.
232 virtual MockRead GetNextRead() OVERRIDE;
233 virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
234 virtual void Reset() OVERRIDE;
244 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider);
247 // SocketDataProvider which can make decisions about next mock reads based on
248 // received writes. It can also be used to enforce order of operations, for
249 // example that tested code must send the "Hello!" message before receiving
250 // response. This is useful for testing conversation-like protocols like FTP.
251 class DynamicSocketDataProvider : public SocketDataProvider {
253 DynamicSocketDataProvider();
254 virtual ~DynamicSocketDataProvider();
256 int short_read_limit() const { return short_read_limit_; }
257 void set_short_read_limit(int limit) { short_read_limit_ = limit; }
259 void allow_unconsumed_reads(bool allow) { allow_unconsumed_reads_ = allow; }
261 // SocketDataProvider implementation.
262 virtual MockRead GetNextRead() OVERRIDE;
263 virtual MockWriteResult OnWrite(const std::string& data) = 0;
264 virtual void Reset() OVERRIDE;
267 // The next time there is a read from this socket, it will return |data|.
268 // Before calling SimulateRead next time, the previous data must be consumed.
269 void SimulateRead(const char* data, size_t length);
270 void SimulateRead(const char* data) {
271 SimulateRead(data, std::strlen(data));
275 std::deque<MockRead> reads_;
277 // Max number of bytes we will read at a time. 0 means no limit.
278 int short_read_limit_;
280 // If true, we'll not require the client to consume all data before we
281 // mock the next read.
282 bool allow_unconsumed_reads_;
284 DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider);
287 // SSLSocketDataProviders only need to keep track of the return code from calls
289 struct SSLSocketDataProvider {
290 SSLSocketDataProvider(IoMode mode, int result);
291 ~SSLSocketDataProvider();
293 void SetNextProto(NextProto proto);
296 SSLClientSocket::NextProtoStatus next_proto_status;
297 std::string next_proto;
298 std::string server_protos;
299 bool was_npn_negotiated;
300 NextProto protocol_negotiated;
301 bool client_cert_sent;
302 SSLCertRequestInfo* cert_request_info;
303 scoped_refptr<X509Certificate> cert;
304 bool channel_id_sent;
305 ServerBoundCertService* server_bound_cert_service;
308 // A DataProvider where the client must write a request before the reads (e.g.
309 // the response) will complete.
310 class DelayedSocketData : public StaticSocketDataProvider {
312 // |write_delay| the number of MockWrites to complete before allowing
313 // a MockRead to complete.
314 // |reads| the list of MockRead completions.
315 // |writes| the list of MockWrite completions.
316 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
317 // MockRead(true, 0, 0);
318 DelayedSocketData(int write_delay,
319 MockRead* reads, size_t reads_count,
320 MockWrite* writes, size_t writes_count);
322 // |connect| the result for the connect phase.
323 // |reads| the list of MockRead completions.
324 // |write_delay| the number of MockWrites to complete before allowing
325 // a MockRead to complete.
326 // |writes| the list of MockWrite completions.
327 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
328 // MockRead(true, 0, 0);
329 DelayedSocketData(const MockConnect& connect, int write_delay,
330 MockRead* reads, size_t reads_count,
331 MockWrite* writes, size_t writes_count);
332 virtual ~DelayedSocketData();
334 void ForceNextRead();
336 // StaticSocketDataProvider:
337 virtual MockRead GetNextRead() OVERRIDE;
338 virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
339 virtual void Reset() OVERRIDE;
340 virtual void CompleteRead() OVERRIDE;
344 bool read_in_progress_;
345 base::WeakPtrFactory<DelayedSocketData> weak_factory_;
348 // A DataProvider where the reads are ordered.
349 // If a read is requested before its sequence number is reached, we return an
350 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
352 // The sequence number is incremented on every read and write operation.
353 // The message loop may be interrupted by setting the high bit of the sequence
354 // number in the MockRead's sequence number. When that MockRead is reached,
355 // we post a Quit message to the loop. This allows us to interrupt the reading
356 // of data before a complete message has arrived, and provides support for
357 // testing server push when the request is issued while the response is in the
358 // middle of being received.
359 class OrderedSocketData : public StaticSocketDataProvider {
361 // |reads| the list of MockRead completions.
362 // |writes| the list of MockWrite completions.
363 // Note: All MockReads and MockWrites must be async.
364 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
365 // MockRead(true, 0, 0);
366 OrderedSocketData(MockRead* reads, size_t reads_count,
367 MockWrite* writes, size_t writes_count);
368 virtual ~OrderedSocketData();
370 // |connect| the result for the connect phase.
371 // |reads| the list of MockRead completions.
372 // |writes| the list of MockWrite completions.
373 // Note: All MockReads and MockWrites must be async.
374 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
375 // MockRead(true, 0, 0);
376 OrderedSocketData(const MockConnect& connect,
377 MockRead* reads, size_t reads_count,
378 MockWrite* writes, size_t writes_count);
380 // Posts a quit message to the current message loop, if one is running.
383 // StaticSocketDataProvider:
384 virtual MockRead GetNextRead() OVERRIDE;
385 virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
386 virtual void Reset() OVERRIDE;
387 virtual void CompleteRead() OVERRIDE;
390 int sequence_number_;
391 int loop_stop_stage_;
393 base::WeakPtrFactory<OrderedSocketData> weak_factory_;
396 class DeterministicMockTCPClientSocket;
398 // This class gives the user full control over the network activity,
399 // specifically the timing of the COMPLETION of I/O operations. Regardless of
400 // the order in which I/O operations are initiated, this class ensures that they
401 // complete in the correct order.
403 // Network activity is modeled as a sequence of numbered steps which is
404 // incremented whenever an I/O operation completes. This can happen under two
405 // different circumstances:
407 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
408 // when the corresponding MockRead or MockWrite is marked !async).
409 // 2) Running the Run() method of this class. The run method will invoke
410 // the current MessageLoop, running all pending events, and will then
411 // invoke any pending IO callbacks.
413 // In addition, this class allows for I/O processing to "stop" at a specified
414 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
415 // by calling Read() or Write() while stopped is permitted if the operation is
416 // asynchronous. It is an error to perform synchronous I/O while stopped.
418 // When creating the MockReads and MockWrites, note that the sequence number
419 // refers to the number of the step in which the I/O will complete. In the
420 // case of synchronous I/O, this will be the same step as the I/O is initiated.
421 // However, in the case of asynchronous I/O, this I/O may be initiated in
422 // a much earlier step. Furthermore, when the a Read() or Write() is separated
423 // from its completion by other Read() or Writes()'s, it can not be marked
424 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
425 // synchronous Read() or Write() could not be completed synchronously because of
426 // the specific ordering constraints.
428 // Sequence numbers are preserved across both reads and writes. There should be
429 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
430 // MockRead reads[] = {
431 // MockRead(false, "first read", length, 0) // sync
432 // MockRead(true, "second read", length, 2) // async
434 // MockWrite writes[] = {
435 // MockWrite(true, "first write", length, 1), // async
436 // MockWrite(false, "second write", length, 3), // sync
439 // Example control flow:
440 // Read() is called. The current step is 0. The first available read is
441 // synchronous, so the call to Read() returns length. The current step is
442 // now 1. Next, Read() is called again. The next available read can
443 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
444 // step is still 1. Write is called(). The first available write is able to
445 // complete in this step, but is marked asynchronous. Write() returns
446 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
447 // called which will cause the write callback to be invoked, and will then
448 // stop. The current state is now 2. RunFor(1) is called again, which
449 // causes the read callback to be invoked, and will then stop. Then current
450 // step is 2. Write() is called again. Then next available write is
451 // synchronous so the call to Write() returns length.
453 // For examples of how to use this class, see:
454 // deterministic_socket_data_unittests.cc
455 class DeterministicSocketData
456 : public StaticSocketDataProvider {
458 // The Delegate is an abstract interface which handles the communication from
459 // the DeterministicSocketData to the Deterministic MockSocket. The
460 // MockSockets directly store a pointer to the DeterministicSocketData,
461 // whereas the DeterministicSocketData only stores a pointer to the
462 // abstract Delegate interface.
465 // Returns true if there is currently a write pending. That is to say, if
466 // an asynchronous write has been started but the callback has not been
468 virtual bool WritePending() const = 0;
469 // Returns true if there is currently a read pending. That is to say, if
470 // an asynchronous read has been started but the callback has not been
472 virtual bool ReadPending() const = 0;
473 // Called to complete an asynchronous write to execute the write callback.
474 virtual void CompleteWrite() = 0;
475 // Called to complete an asynchronous read to execute the read callback.
476 virtual int CompleteRead() = 0;
479 virtual ~Delegate() {}
482 // |reads| the list of MockRead completions.
483 // |writes| the list of MockWrite completions.
484 DeterministicSocketData(MockRead* reads, size_t reads_count,
485 MockWrite* writes, size_t writes_count);
486 virtual ~DeterministicSocketData();
488 // Consume all the data up to the give stop point (via SetStop()).
491 // Set the stop point to be |steps| from now, and then invoke Run().
492 void RunFor(int steps);
494 // Stop at step |seq|, which must be in the future.
495 virtual void SetStop(int seq);
497 // Stop |seq| steps after the current step.
498 virtual void StopAfter(int seq);
499 bool stopped() const { return stopped_; }
500 void SetStopped(bool val) { stopped_ = val; }
501 MockRead& current_read() { return current_read_; }
502 MockWrite& current_write() { return current_write_; }
503 int sequence_number() const { return sequence_number_; }
504 void set_delegate(base::WeakPtr<Delegate> delegate) {
505 delegate_ = delegate;
508 // StaticSocketDataProvider:
510 // When the socket calls Read(), that calls GetNextRead(), and expects either
511 // ERR_IO_PENDING or data.
512 virtual MockRead GetNextRead() OVERRIDE;
514 // When the socket calls Write(), it always completes synchronously. OnWrite()
515 // checks to make sure the written data matches the expected data. The
516 // callback will not be invoked until its sequence number is reached.
517 virtual MockWriteResult OnWrite(const std::string& data) OVERRIDE;
518 virtual void Reset() OVERRIDE;
519 virtual void CompleteRead() OVERRIDE {}
522 // Invoke the read and write callbacks, if the timing is appropriate.
523 void InvokeCallbacks();
527 void VerifyCorrectSequenceNumbers(MockRead* reads, size_t reads_count,
528 MockWrite* writes, size_t writes_count);
530 int sequence_number_;
531 MockRead current_read_;
532 MockWrite current_write_;
533 int stopping_sequence_number_;
535 base::WeakPtr<Delegate> delegate_;
540 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
541 // objects get instantiated, they take their data from the i'th element of this
544 class SocketDataProviderArray {
546 SocketDataProviderArray() : next_index_(0) {}
549 DCHECK_LT(next_index_, data_providers_.size());
550 return data_providers_[next_index_++];
553 void Add(T* data_provider) {
554 DCHECK(data_provider);
555 data_providers_.push_back(data_provider);
558 size_t next_index() { return next_index_; }
560 void ResetNextIndex() {
565 // Index of the next |data_providers_| element to use. Not an iterator
566 // because those are invalidated on vector reallocation.
569 // SocketDataProviders to be returned.
570 std::vector<T*> data_providers_;
573 class MockUDPClientSocket;
574 class MockTCPClientSocket;
575 class MockSSLClientSocket;
577 // ClientSocketFactory which contains arrays of sockets of each type.
578 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
579 // is asked to create a socket, it takes next entry from appropriate array.
580 // You can use ResetNextMockIndexes to reset that next entry index for all mock
582 class MockClientSocketFactory : public ClientSocketFactory {
584 MockClientSocketFactory();
585 virtual ~MockClientSocketFactory();
587 void AddSocketDataProvider(SocketDataProvider* socket);
588 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
589 void ResetNextMockIndexes();
591 SocketDataProviderArray<SocketDataProvider>& mock_data() {
595 // ClientSocketFactory
596 virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
597 DatagramSocket::BindType bind_type,
598 const RandIntCallback& rand_int_cb,
600 const NetLog::Source& source) OVERRIDE;
601 virtual scoped_ptr<StreamSocket> CreateTransportClientSocket(
602 const AddressList& addresses,
604 const NetLog::Source& source) OVERRIDE;
605 virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
606 scoped_ptr<ClientSocketHandle> transport_socket,
607 const HostPortPair& host_and_port,
608 const SSLConfig& ssl_config,
609 const SSLClientSocketContext& context) OVERRIDE;
610 virtual void ClearSSLSessionCache() OVERRIDE;
613 SocketDataProviderArray<SocketDataProvider> mock_data_;
614 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
617 class MockClientSocket : public SSLClientSocket {
619 // Value returned by GetTLSUniqueChannelBinding().
620 static const char kTlsUnique[];
622 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
623 // unique socket IDs.
624 explicit MockClientSocket(const BoundNetLog& net_log);
626 // Socket implementation.
627 virtual int Read(IOBuffer* buf, int buf_len,
628 const CompletionCallback& callback) = 0;
629 virtual int Write(IOBuffer* buf, int buf_len,
630 const CompletionCallback& callback) = 0;
631 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE;
632 virtual bool SetSendBufferSize(int32 size) OVERRIDE;
634 // StreamSocket implementation.
635 virtual int Connect(const CompletionCallback& callback) = 0;
636 virtual void Disconnect() OVERRIDE;
637 virtual bool IsConnected() const OVERRIDE;
638 virtual bool IsConnectedAndIdle() const OVERRIDE;
639 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
640 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
641 virtual const BoundNetLog& NetLog() const OVERRIDE;
642 virtual void SetSubresourceSpeculation() OVERRIDE {}
643 virtual void SetOmniboxSpeculation() OVERRIDE {}
645 // SSLClientSocket implementation.
646 virtual void GetSSLCertRequestInfo(
647 SSLCertRequestInfo* cert_request_info) OVERRIDE;
648 virtual int ExportKeyingMaterial(const base::StringPiece& label,
650 const base::StringPiece& context,
652 unsigned int outlen) OVERRIDE;
653 virtual int GetTLSUniqueChannelBinding(std::string* out) OVERRIDE;
654 virtual NextProtoStatus GetNextProto(std::string* proto,
655 std::string* server_protos) OVERRIDE;
656 virtual ServerBoundCertService* GetServerBoundCertService() const OVERRIDE;
659 virtual ~MockClientSocket();
660 void RunCallbackAsync(const CompletionCallback& callback, int result);
661 void RunCallback(const CompletionCallback& callback, int result);
663 base::WeakPtrFactory<MockClientSocket> weak_factory_;
665 // True if Connect completed successfully and Disconnect hasn't been called.
668 // Address of the "remote" peer we're connected to.
669 IPEndPoint peer_addr_;
671 BoundNetLog net_log_;
674 class MockTCPClientSocket : public MockClientSocket, public AsyncSocket {
676 MockTCPClientSocket(const AddressList& addresses, net::NetLog* net_log,
677 SocketDataProvider* socket);
678 virtual ~MockTCPClientSocket();
680 const AddressList& addresses() const { return addresses_; }
682 // Socket implementation.
683 virtual int Read(IOBuffer* buf, int buf_len,
684 const CompletionCallback& callback) OVERRIDE;
685 virtual int Write(IOBuffer* buf, int buf_len,
686 const CompletionCallback& callback) OVERRIDE;
688 // StreamSocket implementation.
689 virtual int Connect(const CompletionCallback& callback) OVERRIDE;
690 virtual void Disconnect() OVERRIDE;
691 virtual bool IsConnected() const OVERRIDE;
692 virtual bool IsConnectedAndIdle() const OVERRIDE;
693 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
694 virtual bool WasEverUsed() const OVERRIDE;
695 virtual bool UsingTCPFastOpen() const OVERRIDE;
696 virtual bool WasNpnNegotiated() const OVERRIDE;
697 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
700 virtual void OnReadComplete(const MockRead& data) OVERRIDE;
701 virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
706 AddressList addresses_;
708 SocketDataProvider* data_;
711 bool need_read_data_;
713 // True if the peer has closed the connection. This allows us to simulate
714 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
716 bool peer_closed_connection_;
718 // While an asynchronous IO is pending, we save our user-buffer state.
719 scoped_refptr<IOBuffer> pending_buf_;
720 int pending_buf_len_;
721 CompletionCallback pending_callback_;
722 bool was_used_to_convey_data_;
725 // DeterministicSocketHelper is a helper class that can be used
726 // to simulate net::Socket::Read() and net::Socket::Write()
727 // using deterministic |data|.
728 // Note: This is provided as a common helper class because
729 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
730 // desire not to introduce an additional common base class.
731 class DeterministicSocketHelper {
733 DeterministicSocketHelper(net::NetLog* net_log,
734 DeterministicSocketData* data);
735 virtual ~DeterministicSocketHelper();
737 bool write_pending() const { return write_pending_; }
738 bool read_pending() const { return read_pending_; }
740 void CompleteWrite();
743 int Write(IOBuffer* buf, int buf_len,
744 const CompletionCallback& callback);
745 int Read(IOBuffer* buf, int buf_len,
746 const CompletionCallback& callback);
748 const BoundNetLog& net_log() const { return net_log_; }
750 bool was_used_to_convey_data() const { return was_used_to_convey_data_; }
752 bool peer_closed_connection() const { return peer_closed_connection_; }
754 DeterministicSocketData* data() const { return data_; }
758 CompletionCallback write_callback_;
766 CompletionCallback read_callback_;
767 DeterministicSocketData* data_;
768 bool was_used_to_convey_data_;
769 bool peer_closed_connection_;
770 BoundNetLog net_log_;
773 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
774 class DeterministicMockUDPClientSocket
775 : public DatagramClientSocket,
777 public DeterministicSocketData::Delegate,
778 public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> {
780 DeterministicMockUDPClientSocket(net::NetLog* net_log,
781 DeterministicSocketData* data);
782 virtual ~DeterministicMockUDPClientSocket();
784 // DeterministicSocketData::Delegate:
785 virtual bool WritePending() const OVERRIDE;
786 virtual bool ReadPending() const OVERRIDE;
787 virtual void CompleteWrite() OVERRIDE;
788 virtual int CompleteRead() OVERRIDE;
790 // Socket implementation.
791 virtual int Read(IOBuffer* buf, int buf_len,
792 const CompletionCallback& callback) OVERRIDE;
793 virtual int Write(IOBuffer* buf, int buf_len,
794 const CompletionCallback& callback) OVERRIDE;
795 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE;
796 virtual bool SetSendBufferSize(int32 size) OVERRIDE;
798 // DatagramSocket implementation.
799 virtual void Close() OVERRIDE;
800 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
801 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
802 virtual const BoundNetLog& NetLog() const OVERRIDE;
804 // DatagramClientSocket implementation.
805 virtual int Connect(const IPEndPoint& address) OVERRIDE;
807 // AsyncSocket implementation.
808 virtual void OnReadComplete(const MockRead& data) OVERRIDE;
809 virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
813 IPEndPoint peer_address_;
814 DeterministicSocketHelper helper_;
817 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
818 class DeterministicMockTCPClientSocket
819 : public MockClientSocket,
821 public DeterministicSocketData::Delegate,
822 public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> {
824 DeterministicMockTCPClientSocket(net::NetLog* net_log,
825 DeterministicSocketData* data);
826 virtual ~DeterministicMockTCPClientSocket();
828 // DeterministicSocketData::Delegate:
829 virtual bool WritePending() const OVERRIDE;
830 virtual bool ReadPending() const OVERRIDE;
831 virtual void CompleteWrite() OVERRIDE;
832 virtual int CompleteRead() OVERRIDE;
835 virtual int Write(IOBuffer* buf, int buf_len,
836 const CompletionCallback& callback) OVERRIDE;
837 virtual int Read(IOBuffer* buf, int buf_len,
838 const CompletionCallback& callback) OVERRIDE;
841 virtual int Connect(const CompletionCallback& callback) OVERRIDE;
842 virtual void Disconnect() OVERRIDE;
843 virtual bool IsConnected() const OVERRIDE;
844 virtual bool IsConnectedAndIdle() const OVERRIDE;
845 virtual bool WasEverUsed() const OVERRIDE;
846 virtual bool UsingTCPFastOpen() const OVERRIDE;
847 virtual bool WasNpnNegotiated() const OVERRIDE;
848 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
851 virtual void OnReadComplete(const MockRead& data) OVERRIDE;
852 virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
855 DeterministicSocketHelper helper_;
858 class MockSSLClientSocket : public MockClientSocket, public AsyncSocket {
861 scoped_ptr<ClientSocketHandle> transport_socket,
862 const HostPortPair& host_and_port,
863 const SSLConfig& ssl_config,
864 SSLSocketDataProvider* socket);
865 virtual ~MockSSLClientSocket();
867 // Socket implementation.
868 virtual int Read(IOBuffer* buf, int buf_len,
869 const CompletionCallback& callback) OVERRIDE;
870 virtual int Write(IOBuffer* buf, int buf_len,
871 const CompletionCallback& callback) OVERRIDE;
873 // StreamSocket implementation.
874 virtual int Connect(const CompletionCallback& callback) OVERRIDE;
875 virtual void Disconnect() OVERRIDE;
876 virtual bool IsConnected() const OVERRIDE;
877 virtual bool WasEverUsed() const OVERRIDE;
878 virtual bool UsingTCPFastOpen() const OVERRIDE;
879 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
880 virtual bool WasNpnNegotiated() const OVERRIDE;
881 virtual bool GetSSLInfo(SSLInfo* ssl_info) OVERRIDE;
883 // SSLClientSocket implementation.
884 virtual void GetSSLCertRequestInfo(
885 SSLCertRequestInfo* cert_request_info) OVERRIDE;
886 virtual NextProtoStatus GetNextProto(std::string* proto,
887 std::string* server_protos) OVERRIDE;
888 virtual bool set_was_npn_negotiated(bool negotiated) OVERRIDE;
889 virtual void set_protocol_negotiated(
890 NextProto protocol_negotiated) OVERRIDE;
891 virtual NextProto GetNegotiatedProtocol() const OVERRIDE;
893 // This MockSocket does not implement the manual async IO feature.
894 virtual void OnReadComplete(const MockRead& data) OVERRIDE;
895 virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
897 virtual bool WasChannelIDSent() const OVERRIDE;
898 virtual void set_channel_id_sent(bool channel_id_sent) OVERRIDE;
899 virtual ServerBoundCertService* GetServerBoundCertService() const OVERRIDE;
902 static void ConnectCallback(MockSSLClientSocket *ssl_client_socket,
903 const CompletionCallback& callback,
906 scoped_ptr<ClientSocketHandle> transport_;
907 SSLSocketDataProvider* data_;
908 bool is_npn_state_set_;
910 bool is_protocol_negotiated_set_;
911 NextProto protocol_negotiated_;
914 class MockUDPClientSocket
915 : public DatagramClientSocket,
918 MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log);
919 virtual ~MockUDPClientSocket();
921 // Socket implementation.
922 virtual int Read(IOBuffer* buf, int buf_len,
923 const CompletionCallback& callback) OVERRIDE;
924 virtual int Write(IOBuffer* buf, int buf_len,
925 const CompletionCallback& callback) OVERRIDE;
926 virtual bool SetReceiveBufferSize(int32 size) OVERRIDE;
927 virtual bool SetSendBufferSize(int32 size) OVERRIDE;
929 // DatagramSocket implementation.
930 virtual void Close() OVERRIDE;
931 virtual int GetPeerAddress(IPEndPoint* address) const OVERRIDE;
932 virtual int GetLocalAddress(IPEndPoint* address) const OVERRIDE;
933 virtual const BoundNetLog& NetLog() const OVERRIDE;
935 // DatagramClientSocket implementation.
936 virtual int Connect(const IPEndPoint& address) OVERRIDE;
938 // AsyncSocket implementation.
939 virtual void OnReadComplete(const MockRead& data) OVERRIDE;
940 virtual void OnConnectComplete(const MockConnect& data) OVERRIDE;
945 void RunCallbackAsync(const CompletionCallback& callback, int result);
946 void RunCallback(const CompletionCallback& callback, int result);
949 SocketDataProvider* data_;
952 bool need_read_data_;
954 // Address of the "remote" peer we're connected to.
955 IPEndPoint peer_addr_;
957 // While an asynchronous IO is pending, we save our user-buffer state.
958 scoped_refptr<IOBuffer> pending_buf_;
959 int pending_buf_len_;
960 CompletionCallback pending_callback_;
962 BoundNetLog net_log_;
964 base::WeakPtrFactory<MockUDPClientSocket> weak_factory_;
966 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket);
969 class TestSocketRequest : public TestCompletionCallbackBase {
971 TestSocketRequest(std::vector<TestSocketRequest*>* request_order,
972 size_t* completion_count);
973 virtual ~TestSocketRequest();
975 ClientSocketHandle* handle() { return &handle_; }
977 const net::CompletionCallback& callback() const { return callback_; }
980 void OnComplete(int result);
982 ClientSocketHandle handle_;
983 std::vector<TestSocketRequest*>* request_order_;
984 size_t* completion_count_;
985 CompletionCallback callback_;
987 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest);
990 class ClientSocketPoolTest {
995 // A socket will be disconnected in addition to handle being reset.
999 static const int kIndexOutOfBounds;
1000 static const int kRequestNotFound;
1002 ClientSocketPoolTest();
1003 ~ClientSocketPoolTest();
1005 template <typename PoolType>
1006 int StartRequestUsingPool(
1007 PoolType* socket_pool,
1008 const std::string& group_name,
1009 RequestPriority priority,
1010 const scoped_refptr<typename PoolType::SocketParams>& socket_params) {
1011 DCHECK(socket_pool);
1012 TestSocketRequest* request = new TestSocketRequest(&request_order_,
1013 &completion_count_);
1014 requests_.push_back(request);
1015 int rv = request->handle()->Init(
1016 group_name, socket_params, priority, request->callback(),
1017 socket_pool, BoundNetLog());
1018 if (rv != ERR_IO_PENDING)
1019 request_order_.push_back(request);
1023 // Provided there were n requests started, takes |index| in range 1..n
1024 // and returns order in which that request completed, in range 1..n,
1025 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1026 // if that request did not complete (for example was canceled).
1027 int GetOrderOfRequest(size_t index) const;
1029 // Resets first initialized socket handle from |requests_|. If found such
1030 // a handle, returns true.
1031 bool ReleaseOneConnection(KeepAlive keep_alive);
1033 // Releases connections until there is nothing to release.
1034 void ReleaseAllConnections(KeepAlive keep_alive);
1036 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1037 // returns 0-based indices.
1038 TestSocketRequest* request(int i) { return requests_[i]; }
1040 size_t requests_size() const { return requests_.size(); }
1041 ScopedVector<TestSocketRequest>* requests() { return &requests_; }
1042 size_t completion_count() const { return completion_count_; }
1045 ScopedVector<TestSocketRequest> requests_;
1046 std::vector<TestSocketRequest*> request_order_;
1047 size_t completion_count_;
1050 class MockTransportSocketParams
1051 : public base::RefCounted<MockTransportSocketParams> {
1053 friend class base::RefCounted<MockTransportSocketParams>;
1054 ~MockTransportSocketParams() {}
1057 class MockTransportClientSocketPool : public TransportClientSocketPool {
1059 typedef MockTransportSocketParams SocketParams;
1061 class MockConnectJob {
1063 MockConnectJob(scoped_ptr<StreamSocket> socket, ClientSocketHandle* handle,
1064 const CompletionCallback& callback);
1068 bool CancelHandle(const ClientSocketHandle* handle);
1071 void OnConnect(int rv);
1073 scoped_ptr<StreamSocket> socket_;
1074 ClientSocketHandle* handle_;
1075 CompletionCallback user_callback_;
1077 DISALLOW_COPY_AND_ASSIGN(MockConnectJob);
1080 MockTransportClientSocketPool(
1082 int max_sockets_per_group,
1083 ClientSocketPoolHistograms* histograms,
1084 ClientSocketFactory* socket_factory);
1086 virtual ~MockTransportClientSocketPool();
1088 RequestPriority last_request_priority() const {
1089 return last_request_priority_;
1091 int release_count() const { return release_count_; }
1092 int cancel_count() const { return cancel_count_; }
1094 // TransportClientSocketPool implementation.
1095 virtual int RequestSocket(const std::string& group_name,
1096 const void* socket_params,
1097 RequestPriority priority,
1098 ClientSocketHandle* handle,
1099 const CompletionCallback& callback,
1100 const BoundNetLog& net_log) OVERRIDE;
1102 virtual void CancelRequest(const std::string& group_name,
1103 ClientSocketHandle* handle) OVERRIDE;
1104 virtual void ReleaseSocket(const std::string& group_name,
1105 scoped_ptr<StreamSocket> socket,
1109 ClientSocketFactory* client_socket_factory_;
1110 ScopedVector<MockConnectJob> job_list_;
1111 RequestPriority last_request_priority_;
1115 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool);
1118 class DeterministicMockClientSocketFactory : public ClientSocketFactory {
1120 DeterministicMockClientSocketFactory();
1121 virtual ~DeterministicMockClientSocketFactory();
1123 void AddSocketDataProvider(DeterministicSocketData* socket);
1124 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
1125 void ResetNextMockIndexes();
1127 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1129 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const;
1131 SocketDataProviderArray<DeterministicSocketData>& mock_data() {
1134 std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() {
1135 return tcp_client_sockets_;
1137 std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() {
1138 return udp_client_sockets_;
1141 // ClientSocketFactory
1142 virtual scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
1143 DatagramSocket::BindType bind_type,
1144 const RandIntCallback& rand_int_cb,
1146 const NetLog::Source& source) OVERRIDE;
1147 virtual scoped_ptr<StreamSocket> CreateTransportClientSocket(
1148 const AddressList& addresses,
1150 const NetLog::Source& source) OVERRIDE;
1151 virtual scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
1152 scoped_ptr<ClientSocketHandle> transport_socket,
1153 const HostPortPair& host_and_port,
1154 const SSLConfig& ssl_config,
1155 const SSLClientSocketContext& context) OVERRIDE;
1156 virtual void ClearSSLSessionCache() OVERRIDE;
1159 SocketDataProviderArray<DeterministicSocketData> mock_data_;
1160 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
1162 // Store pointers to handed out sockets in case the test wants to get them.
1163 std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_;
1164 std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_;
1165 std::vector<MockSSLClientSocket*> ssl_client_sockets_;
1168 class MockSOCKSClientSocketPool : public SOCKSClientSocketPool {
1170 MockSOCKSClientSocketPool(
1172 int max_sockets_per_group,
1173 ClientSocketPoolHistograms* histograms,
1174 TransportClientSocketPool* transport_pool);
1176 virtual ~MockSOCKSClientSocketPool();
1178 // SOCKSClientSocketPool implementation.
1179 virtual int RequestSocket(const std::string& group_name,
1180 const void* socket_params,
1181 RequestPriority priority,
1182 ClientSocketHandle* handle,
1183 const CompletionCallback& callback,
1184 const BoundNetLog& net_log) OVERRIDE;
1186 virtual void CancelRequest(const std::string& group_name,
1187 ClientSocketHandle* handle) OVERRIDE;
1188 virtual void ReleaseSocket(const std::string& group_name,
1189 scoped_ptr<StreamSocket> socket,
1193 TransportClientSocketPool* const transport_pool_;
1195 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool);
1198 // Constants for a successful SOCKS v5 handshake.
1199 extern const char kSOCKS5GreetRequest[];
1200 extern const int kSOCKS5GreetRequestLength;
1202 extern const char kSOCKS5GreetResponse[];
1203 extern const int kSOCKS5GreetResponseLength;
1205 extern const char kSOCKS5OkRequest[];
1206 extern const int kSOCKS5OkRequestLength;
1208 extern const char kSOCKS5OkResponse[];
1209 extern const int kSOCKS5OkResponseLength;
1213 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_