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 "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/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/log/net_log.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"
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,
51 class ChannelIDService
;
52 class MockClientSocket
;
53 class SSLClientSocket
;
62 // Asynchronous connection success.
63 // Creates a MockConnect with |mode| ASYC, |result| OK, and
64 // |peer_addr| 192.0.2.33.
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
);
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
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
{
93 template <MockReadWriteType type
>
94 struct MockReadWrite
{
95 // Flag to indicate that the message loop should be terminated.
107 time_stamp(base::Time::Now()) {}
109 // Read/write failure (no data).
110 MockReadWrite(IoMode io_mode
, int result
)
116 time_stamp(base::Time::Now()) {}
118 // Read/write failure (no data), with sequence information.
119 MockReadWrite(IoMode io_mode
, int result
, int seq
)
124 sequence_number(seq
),
125 time_stamp(base::Time::Now()) {}
127 // Asynchronous read/write success (inferred data length).
128 explicit MockReadWrite(const char* data
)
132 data_len(strlen(data
)),
134 time_stamp(base::Time::Now()) {}
136 // Read/write success (inferred data length).
137 MockReadWrite(IoMode io_mode
, const char* data
)
141 data_len(strlen(data
)),
143 time_stamp(base::Time::Now()) {}
145 // Read/write success.
146 MockReadWrite(IoMode io_mode
, const char* data
, int data_len
)
152 time_stamp(base::Time::Now()) {}
154 // Read/write success (inferred data length) with sequence information.
155 MockReadWrite(IoMode io_mode
, int seq
, const char* data
)
159 data_len(strlen(data
)),
160 sequence_number(seq
),
161 time_stamp(base::Time::Now()) {}
163 // Read/write success with sequence information.
164 MockReadWrite(IoMode io_mode
, const char* data
, int data_len
, int seq
)
169 sequence_number(seq
),
170 time_stamp(base::Time::Now()) {}
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
182 base::Time time_stamp
; // The time stamp at which the operation occurred.
185 typedef MockReadWrite
<MOCK_READ
> MockRead
;
186 typedef MockReadWrite
<MOCK_WRITE
> MockWrite
;
188 struct MockWriteResult
{
189 MockWriteResult(IoMode io_mode
, int result
) : mode(io_mode
), result(result
) {}
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
{
199 SocketDataProvider() : socket_(NULL
) {}
201 virtual ~SocketDataProvider() {}
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;
211 // Accessor for the socket which is using the SocketDataProvider.
212 AsyncSocket
* socket() { return socket_
; }
213 void set_socket(AsyncSocket
* socket
) { socket_
= socket
; }
215 MockConnect
connect_data() const { return connect_
; }
216 void set_connect_data(const MockConnect
& connect
) { connect_
= connect
; }
219 MockConnect connect_
;
220 AsyncSocket
* socket_
;
222 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider
);
225 // The AsyncSocket is an interface used by the SocketDataProvider to
226 // complete the asynchronous read operation.
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;
238 // SocketDataProvider which responds based on static tables of mock reads and
240 class StaticSocketDataProvider
: public SocketDataProvider
{
242 StaticSocketDataProvider();
243 StaticSocketDataProvider(MockRead
* reads
,
246 size_t writes_count
);
247 ~StaticSocketDataProvider() override
;
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_
; }
260 bool at_read_eof() const { return read_index_
>= read_count_
; }
261 bool at_write_eof() const { return write_index_
>= write_count_
; }
263 virtual void CompleteRead() {}
265 // SocketDataProvider implementation.
266 MockRead
GetNextRead() override
;
267 MockWriteResult
OnWrite(const std::string
& data
) override
;
268 void Reset() override
;
278 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider
);
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
{
287 DynamicSocketDataProvider();
288 ~DynamicSocketDataProvider() override
;
290 int short_read_limit() const { return short_read_limit_
; }
291 void set_short_read_limit(int limit
) { short_read_limit_
= limit
; }
293 void allow_unconsumed_reads(bool allow
) { allow_unconsumed_reads_
= allow
; }
295 // SocketDataProvider implementation.
296 MockRead
GetNextRead() override
;
297 MockWriteResult
OnWrite(const std::string
& data
) override
= 0;
298 void Reset() override
;
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
)); }
307 std::deque
<MockRead
> reads_
;
309 // Max number of bytes we will read at a time. 0 means no limit.
310 int short_read_limit_
;
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_
;
316 DISALLOW_COPY_AND_ASSIGN(DynamicSocketDataProvider
);
319 // SSLSocketDataProviders only need to keep track of the return code from calls
321 struct SSLSocketDataProvider
{
322 SSLSocketDataProvider(IoMode mode
, int result
);
323 ~SSLSocketDataProvider();
325 void SetNextProto(NextProto proto
);
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
;
341 // A DataProvider where the client must write a request before the reads (e.g.
342 // the response) will complete.
343 class DelayedSocketData
: public StaticSocketDataProvider
{
345 // |write_delay| the number of MockWrites to complete before allowing
346 // a MockRead to complete.
347 // |reads| the list of MockRead completions.
348 // |writes| the list of MockWrite completions.
349 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
350 // MockRead(true, 0, 0);
351 DelayedSocketData(int write_delay
,
355 size_t writes_count
);
357 // |connect| the result for the connect phase.
358 // |reads| the list of MockRead completions.
359 // |write_delay| the number of MockWrites to complete before allowing
360 // a MockRead to complete.
361 // |writes| the list of MockWrite completions.
362 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
363 // MockRead(true, 0, 0);
364 DelayedSocketData(const MockConnect
& connect
,
369 size_t writes_count
);
370 ~DelayedSocketData() override
;
372 void ForceNextRead();
374 // StaticSocketDataProvider:
375 MockRead
GetNextRead() override
;
376 MockWriteResult
OnWrite(const std::string
& data
) override
;
377 void Reset() override
;
378 void CompleteRead() override
;
382 bool read_in_progress_
;
384 base::WeakPtrFactory
<DelayedSocketData
> weak_factory_
;
386 DISALLOW_COPY_AND_ASSIGN(DelayedSocketData
);
389 // A DataProvider where the reads are ordered.
390 // If a read is requested before its sequence number is reached, we return an
391 // ERR_IO_PENDING (that way we don't have to explicitly add a MockRead just to
393 // The sequence number is incremented on every read and write operation.
394 // The message loop may be interrupted by setting the high bit of the sequence
395 // number in the MockRead's sequence number. When that MockRead is reached,
396 // we post a Quit message to the loop. This allows us to interrupt the reading
397 // of data before a complete message has arrived, and provides support for
398 // testing server push when the request is issued while the response is in the
399 // middle of being received.
400 class OrderedSocketData
: public StaticSocketDataProvider
{
402 // |reads| the list of MockRead completions.
403 // |writes| the list of MockWrite completions.
404 // Note: All MockReads and MockWrites must be async.
405 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
406 // MockRead(true, 0, 0);
407 OrderedSocketData(MockRead
* reads
,
410 size_t writes_count
);
411 ~OrderedSocketData() override
;
413 // |connect| the result for the connect phase.
414 // |reads| the list of MockRead completions.
415 // |writes| the list of MockWrite completions.
416 // Note: All MockReads and MockWrites must be async.
417 // Note: For stream sockets, the MockRead list must end with a EOF, e.g., a
418 // MockRead(true, 0, 0);
419 OrderedSocketData(const MockConnect
& connect
,
423 size_t writes_count
);
425 // Posts a quit message to the current message loop, if one is running.
428 // StaticSocketDataProvider:
429 MockRead
GetNextRead() override
;
430 MockWriteResult
OnWrite(const std::string
& data
) override
;
431 void Reset() override
;
432 void CompleteRead() override
;
435 int sequence_number_
;
436 int loop_stop_stage_
;
439 base::WeakPtrFactory
<OrderedSocketData
> weak_factory_
;
441 DISALLOW_COPY_AND_ASSIGN(OrderedSocketData
);
444 class DeterministicMockTCPClientSocket
;
446 // This class gives the user full control over the network activity,
447 // specifically the timing of the COMPLETION of I/O operations. Regardless of
448 // the order in which I/O operations are initiated, this class ensures that they
449 // complete in the correct order.
451 // Network activity is modeled as a sequence of numbered steps which is
452 // incremented whenever an I/O operation completes. This can happen under two
453 // different circumstances:
455 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
456 // when the corresponding MockRead or MockWrite is marked !async).
457 // 2) Running the Run() method of this class. The run method will invoke
458 // the current MessageLoop, running all pending events, and will then
459 // invoke any pending IO callbacks.
461 // In addition, this class allows for I/O processing to "stop" at a specified
462 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
463 // by calling Read() or Write() while stopped is permitted if the operation is
464 // asynchronous. It is an error to perform synchronous I/O while stopped.
466 // When creating the MockReads and MockWrites, note that the sequence number
467 // refers to the number of the step in which the I/O will complete. In the
468 // case of synchronous I/O, this will be the same step as the I/O is initiated.
469 // However, in the case of asynchronous I/O, this I/O may be initiated in
470 // a much earlier step. Furthermore, when the a Read() or Write() is separated
471 // from its completion by other Read() or Writes()'s, it can not be marked
472 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
473 // synchronous Read() or Write() could not be completed synchronously because of
474 // the specific ordering constraints.
476 // Sequence numbers are preserved across both reads and writes. There should be
477 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
478 // MockRead reads[] = {
479 // MockRead(false, "first read", length, 0) // sync
480 // MockRead(true, "second read", length, 2) // async
482 // MockWrite writes[] = {
483 // MockWrite(true, "first write", length, 1), // async
484 // MockWrite(false, "second write", length, 3), // sync
487 // Example control flow:
488 // Read() is called. The current step is 0. The first available read is
489 // synchronous, so the call to Read() returns length. The current step is
490 // now 1. Next, Read() is called again. The next available read can
491 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
492 // step is still 1. Write is called(). The first available write is able to
493 // complete in this step, but is marked asynchronous. Write() returns
494 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
495 // called which will cause the write callback to be invoked, and will then
496 // stop. The current state is now 2. RunFor(1) is called again, which
497 // causes the read callback to be invoked, and will then stop. Then current
498 // step is 2. Write() is called again. Then next available write is
499 // synchronous so the call to Write() returns length.
501 // For examples of how to use this class, see:
502 // deterministic_socket_data_unittests.cc
503 class DeterministicSocketData
: public StaticSocketDataProvider
{
505 // The Delegate is an abstract interface which handles the communication from
506 // the DeterministicSocketData to the Deterministic MockSocket. The
507 // MockSockets directly store a pointer to the DeterministicSocketData,
508 // whereas the DeterministicSocketData only stores a pointer to the
509 // abstract Delegate interface.
512 // Returns true if there is currently a write pending. That is to say, if
513 // an asynchronous write has been started but the callback has not been
515 virtual bool WritePending() const = 0;
516 // Returns true if there is currently a read pending. That is to say, if
517 // an asynchronous read has been started but the callback has not been
519 virtual bool ReadPending() const = 0;
520 // Called to complete an asynchronous write to execute the write callback.
521 virtual void CompleteWrite() = 0;
522 // Called to complete an asynchronous read to execute the read callback.
523 virtual int CompleteRead() = 0;
526 virtual ~Delegate() {}
529 // |reads| the list of MockRead completions.
530 // |writes| the list of MockWrite completions.
531 DeterministicSocketData(MockRead
* reads
,
534 size_t writes_count
);
535 ~DeterministicSocketData() override
;
537 // Consume all the data up to the give stop point (via SetStop()).
540 // Set the stop point to be |steps| from now, and then invoke Run().
541 void RunFor(int steps
);
543 // Stop at step |seq|, which must be in the future.
544 virtual void SetStop(int seq
);
546 // Stop |seq| steps after the current step.
547 virtual void StopAfter(int seq
);
548 bool stopped() const { return stopped_
; }
549 void SetStopped(bool val
) { stopped_
= val
; }
550 MockRead
& current_read() { return current_read_
; }
551 MockWrite
& current_write() { return current_write_
; }
552 int sequence_number() const { return sequence_number_
; }
553 void set_delegate(base::WeakPtr
<Delegate
> delegate
) { delegate_
= delegate
; }
555 // StaticSocketDataProvider:
557 // When the socket calls Read(), that calls GetNextRead(), and expects either
558 // ERR_IO_PENDING or data.
559 MockRead
GetNextRead() override
;
561 // When the socket calls Write(), it always completes synchronously. OnWrite()
562 // checks to make sure the written data matches the expected data. The
563 // callback will not be invoked until its sequence number is reached.
564 MockWriteResult
OnWrite(const std::string
& data
) override
;
565 void Reset() override
;
566 void CompleteRead() override
{}
569 // Invoke the read and write callbacks, if the timing is appropriate.
570 void InvokeCallbacks();
574 void VerifyCorrectSequenceNumbers(MockRead
* reads
,
577 size_t writes_count
);
579 int sequence_number_
;
580 MockRead current_read_
;
581 MockWrite current_write_
;
582 int stopping_sequence_number_
;
584 base::WeakPtr
<Delegate
> delegate_
;
589 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
590 // objects get instantiated, they take their data from the i'th element of this
592 template <typename T
>
593 class SocketDataProviderArray
{
595 SocketDataProviderArray() : next_index_(0) {}
598 DCHECK_LT(next_index_
, data_providers_
.size());
599 return data_providers_
[next_index_
++];
602 void Add(T
* data_provider
) {
603 DCHECK(data_provider
);
604 data_providers_
.push_back(data_provider
);
607 size_t next_index() { return next_index_
; }
609 void ResetNextIndex() { next_index_
= 0; }
612 // Index of the next |data_providers_| element to use. Not an iterator
613 // because those are invalidated on vector reallocation.
616 // SocketDataProviders to be returned.
617 std::vector
<T
*> data_providers_
;
620 class MockUDPClientSocket
;
621 class MockTCPClientSocket
;
622 class MockSSLClientSocket
;
624 // ClientSocketFactory which contains arrays of sockets of each type.
625 // You should first fill the arrays using AddMock{SSL,}Socket. When the factory
626 // is asked to create a socket, it takes next entry from appropriate array.
627 // You can use ResetNextMockIndexes to reset that next entry index for all mock
629 class MockClientSocketFactory
: public ClientSocketFactory
{
631 MockClientSocketFactory();
632 ~MockClientSocketFactory() override
;
634 void AddSocketDataProvider(SocketDataProvider
* socket
);
635 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
636 void ResetNextMockIndexes();
638 SocketDataProviderArray
<SocketDataProvider
>& mock_data() {
642 // ClientSocketFactory
643 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
644 DatagramSocket::BindType bind_type
,
645 const RandIntCallback
& rand_int_cb
,
647 const NetLog::Source
& source
) override
;
648 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
649 const AddressList
& addresses
,
651 const NetLog::Source
& source
) override
;
652 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
653 scoped_ptr
<ClientSocketHandle
> transport_socket
,
654 const HostPortPair
& host_and_port
,
655 const SSLConfig
& ssl_config
,
656 const SSLClientSocketContext
& context
) override
;
657 void ClearSSLSessionCache() override
;
660 SocketDataProviderArray
<SocketDataProvider
> mock_data_
;
661 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
664 class MockClientSocket
: public SSLClientSocket
{
666 // Value returned by GetTLSUniqueChannelBinding().
667 static const char kTlsUnique
[];
669 // The BoundNetLog is needed to test LoadTimingInfo, which uses NetLog IDs as
670 // unique socket IDs.
671 explicit MockClientSocket(const BoundNetLog
& net_log
);
673 // Socket implementation.
674 int Read(IOBuffer
* buf
,
676 const CompletionCallback
& callback
) override
= 0;
677 int Write(IOBuffer
* buf
,
679 const CompletionCallback
& callback
) override
= 0;
680 int SetReceiveBufferSize(int32 size
) override
;
681 int SetSendBufferSize(int32 size
) override
;
683 // StreamSocket implementation.
684 int Connect(const CompletionCallback
& callback
) override
= 0;
685 void Disconnect() override
;
686 bool IsConnected() const override
;
687 bool IsConnectedAndIdle() const override
;
688 int GetPeerAddress(IPEndPoint
* address
) const override
;
689 int GetLocalAddress(IPEndPoint
* address
) const override
;
690 const BoundNetLog
& NetLog() const override
;
691 void SetSubresourceSpeculation() override
{}
692 void SetOmniboxSpeculation() override
{}
694 // SSLClientSocket implementation.
695 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
696 int ExportKeyingMaterial(const base::StringPiece
& label
,
698 const base::StringPiece
& context
,
700 unsigned int outlen
) override
;
701 int GetTLSUniqueChannelBinding(std::string
* out
) override
;
702 NextProtoStatus
GetNextProto(std::string
* proto
) override
;
703 ChannelIDService
* GetChannelIDService() const override
;
706 ~MockClientSocket() override
;
707 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
708 void RunCallback(const CompletionCallback
& callback
, int result
);
710 // SSLClientSocket implementation.
711 scoped_refptr
<X509Certificate
> GetUnverifiedServerCertificateChain()
714 // True if Connect completed successfully and Disconnect hasn't been called.
717 // Address of the "remote" peer we're connected to.
718 IPEndPoint peer_addr_
;
720 BoundNetLog net_log_
;
723 base::WeakPtrFactory
<MockClientSocket
> weak_factory_
;
725 DISALLOW_COPY_AND_ASSIGN(MockClientSocket
);
728 class MockTCPClientSocket
: public MockClientSocket
, public AsyncSocket
{
730 MockTCPClientSocket(const AddressList
& addresses
,
731 net::NetLog
* net_log
,
732 SocketDataProvider
* socket
);
733 ~MockTCPClientSocket() override
;
735 const AddressList
& addresses() const { return addresses_
; }
737 // Socket implementation.
738 int Read(IOBuffer
* buf
,
740 const CompletionCallback
& callback
) override
;
741 int Write(IOBuffer
* buf
,
743 const CompletionCallback
& callback
) override
;
745 // StreamSocket implementation.
746 int Connect(const CompletionCallback
& callback
) override
;
747 void Disconnect() override
;
748 bool IsConnected() const override
;
749 bool IsConnectedAndIdle() const override
;
750 int GetPeerAddress(IPEndPoint
* address
) const override
;
751 bool WasEverUsed() const override
;
752 bool UsingTCPFastOpen() const override
;
753 bool WasNpnNegotiated() const override
;
754 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
757 void OnReadComplete(const MockRead
& data
) override
;
758 void OnConnectComplete(const MockConnect
& data
) override
;
763 AddressList addresses_
;
765 SocketDataProvider
* data_
;
768 bool need_read_data_
;
770 // True if the peer has closed the connection. This allows us to simulate
771 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
773 bool peer_closed_connection_
;
775 // While an asynchronous IO is pending, we save our user-buffer state.
776 scoped_refptr
<IOBuffer
> pending_buf_
;
777 int pending_buf_len_
;
778 CompletionCallback pending_callback_
;
779 bool was_used_to_convey_data_
;
781 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket
);
784 // DeterministicSocketHelper is a helper class that can be used
785 // to simulate net::Socket::Read() and net::Socket::Write()
786 // using deterministic |data|.
787 // Note: This is provided as a common helper class because
788 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
789 // desire not to introduce an additional common base class.
790 class DeterministicSocketHelper
{
792 DeterministicSocketHelper(net::NetLog
* net_log
,
793 DeterministicSocketData
* data
);
794 virtual ~DeterministicSocketHelper();
796 bool write_pending() const { return write_pending_
; }
797 bool read_pending() const { return read_pending_
; }
799 void CompleteWrite();
802 int Write(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
803 int Read(IOBuffer
* buf
, int buf_len
, const CompletionCallback
& callback
);
805 const BoundNetLog
& net_log() const { return net_log_
; }
807 bool was_used_to_convey_data() const { return was_used_to_convey_data_
; }
809 bool peer_closed_connection() const { return peer_closed_connection_
; }
811 DeterministicSocketData
* data() const { return data_
; }
815 CompletionCallback write_callback_
;
823 CompletionCallback read_callback_
;
824 DeterministicSocketData
* data_
;
825 bool was_used_to_convey_data_
;
826 bool peer_closed_connection_
;
827 BoundNetLog net_log_
;
830 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
831 class DeterministicMockUDPClientSocket
832 : public DatagramClientSocket
,
834 public DeterministicSocketData::Delegate
,
835 public base::SupportsWeakPtr
<DeterministicMockUDPClientSocket
> {
837 DeterministicMockUDPClientSocket(net::NetLog
* net_log
,
838 DeterministicSocketData
* data
);
839 ~DeterministicMockUDPClientSocket() override
;
841 // DeterministicSocketData::Delegate:
842 bool WritePending() const override
;
843 bool ReadPending() const override
;
844 void CompleteWrite() override
;
845 int CompleteRead() override
;
847 // Socket implementation.
848 int Read(IOBuffer
* buf
,
850 const CompletionCallback
& callback
) override
;
851 int Write(IOBuffer
* buf
,
853 const CompletionCallback
& callback
) override
;
854 int SetReceiveBufferSize(int32 size
) override
;
855 int SetSendBufferSize(int32 size
) override
;
857 // DatagramSocket implementation.
858 void Close() override
;
859 int GetPeerAddress(IPEndPoint
* address
) const override
;
860 int GetLocalAddress(IPEndPoint
* address
) const override
;
861 const BoundNetLog
& NetLog() const override
;
863 // DatagramClientSocket implementation.
864 int Connect(const IPEndPoint
& address
) override
;
866 // AsyncSocket implementation.
867 void OnReadComplete(const MockRead
& data
) override
;
868 void OnConnectComplete(const MockConnect
& data
) override
;
870 void set_source_port(uint16 port
) { source_port_
= port
; }
874 IPEndPoint peer_address_
;
875 DeterministicSocketHelper helper_
;
876 uint16 source_port_
; // Ephemeral source port.
878 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket
);
881 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
882 class DeterministicMockTCPClientSocket
883 : public MockClientSocket
,
885 public DeterministicSocketData::Delegate
,
886 public base::SupportsWeakPtr
<DeterministicMockTCPClientSocket
> {
888 DeterministicMockTCPClientSocket(net::NetLog
* net_log
,
889 DeterministicSocketData
* data
);
890 ~DeterministicMockTCPClientSocket() override
;
892 // DeterministicSocketData::Delegate:
893 bool WritePending() const override
;
894 bool ReadPending() const override
;
895 void CompleteWrite() override
;
896 int CompleteRead() override
;
899 int Write(IOBuffer
* buf
,
901 const CompletionCallback
& callback
) override
;
902 int Read(IOBuffer
* buf
,
904 const CompletionCallback
& callback
) override
;
907 int Connect(const CompletionCallback
& callback
) override
;
908 void Disconnect() override
;
909 bool IsConnected() const override
;
910 bool IsConnectedAndIdle() const override
;
911 bool WasEverUsed() const override
;
912 bool UsingTCPFastOpen() const override
;
913 bool WasNpnNegotiated() const override
;
914 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
917 void OnReadComplete(const MockRead
& data
) override
;
918 void OnConnectComplete(const MockConnect
& data
) override
;
921 DeterministicSocketHelper helper_
;
923 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket
);
926 class MockSSLClientSocket
: public MockClientSocket
, public AsyncSocket
{
928 MockSSLClientSocket(scoped_ptr
<ClientSocketHandle
> transport_socket
,
929 const HostPortPair
& host_and_port
,
930 const SSLConfig
& ssl_config
,
931 SSLSocketDataProvider
* socket
);
932 ~MockSSLClientSocket() override
;
934 // Socket implementation.
935 int Read(IOBuffer
* buf
,
937 const CompletionCallback
& callback
) override
;
938 int Write(IOBuffer
* buf
,
940 const CompletionCallback
& callback
) override
;
942 // StreamSocket implementation.
943 int Connect(const CompletionCallback
& callback
) override
;
944 void Disconnect() override
;
945 bool IsConnected() const override
;
946 bool WasEverUsed() const override
;
947 bool UsingTCPFastOpen() const override
;
948 int GetPeerAddress(IPEndPoint
* address
) const override
;
949 bool WasNpnNegotiated() const override
;
950 bool GetSSLInfo(SSLInfo
* ssl_info
) override
;
952 // SSLClientSocket implementation.
953 void GetSSLCertRequestInfo(SSLCertRequestInfo
* cert_request_info
) override
;
954 NextProtoStatus
GetNextProto(std::string
* proto
) override
;
955 bool set_was_npn_negotiated(bool negotiated
) override
;
956 void set_protocol_negotiated(NextProto protocol_negotiated
) override
;
957 NextProto
GetNegotiatedProtocol() const override
;
959 // This MockSocket does not implement the manual async IO feature.
960 void OnReadComplete(const MockRead
& data
) override
;
961 void OnConnectComplete(const MockConnect
& data
) override
;
963 bool WasChannelIDSent() const override
;
964 void set_channel_id_sent(bool channel_id_sent
) override
;
965 ChannelIDService
* GetChannelIDService() const override
;
968 static void ConnectCallback(MockSSLClientSocket
* ssl_client_socket
,
969 const CompletionCallback
& callback
,
972 scoped_ptr
<ClientSocketHandle
> transport_
;
973 SSLSocketDataProvider
* data_
;
974 bool is_npn_state_set_
;
976 bool is_protocol_negotiated_set_
;
977 NextProto protocol_negotiated_
;
979 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket
);
982 class MockUDPClientSocket
: public DatagramClientSocket
, public AsyncSocket
{
984 MockUDPClientSocket(SocketDataProvider
* data
, net::NetLog
* net_log
);
985 ~MockUDPClientSocket() override
;
987 // Socket implementation.
988 int Read(IOBuffer
* buf
,
990 const CompletionCallback
& callback
) override
;
991 int Write(IOBuffer
* buf
,
993 const CompletionCallback
& callback
) override
;
994 int SetReceiveBufferSize(int32 size
) override
;
995 int SetSendBufferSize(int32 size
) override
;
997 // DatagramSocket implementation.
998 void Close() override
;
999 int GetPeerAddress(IPEndPoint
* address
) const override
;
1000 int GetLocalAddress(IPEndPoint
* address
) const override
;
1001 const BoundNetLog
& NetLog() const override
;
1003 // DatagramClientSocket implementation.
1004 int Connect(const IPEndPoint
& address
) override
;
1006 // AsyncSocket implementation.
1007 void OnReadComplete(const MockRead
& data
) override
;
1008 void OnConnectComplete(const MockConnect
& data
) override
;
1010 void set_source_port(uint16 port
) { source_port_
= port
;}
1015 void RunCallbackAsync(const CompletionCallback
& callback
, int result
);
1016 void RunCallback(const CompletionCallback
& callback
, int result
);
1019 SocketDataProvider
* data_
;
1021 MockRead read_data_
;
1022 bool need_read_data_
;
1023 uint16 source_port_
; // Ephemeral source port.
1025 // Address of the "remote" peer we're connected to.
1026 IPEndPoint peer_addr_
;
1028 // While an asynchronous IO is pending, we save our user-buffer state.
1029 scoped_refptr
<IOBuffer
> pending_buf_
;
1030 int pending_buf_len_
;
1031 CompletionCallback pending_callback_
;
1033 BoundNetLog net_log_
;
1035 base::WeakPtrFactory
<MockUDPClientSocket
> weak_factory_
;
1037 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket
);
1040 class TestSocketRequest
: public TestCompletionCallbackBase
{
1042 TestSocketRequest(std::vector
<TestSocketRequest
*>* request_order
,
1043 size_t* completion_count
);
1044 ~TestSocketRequest() override
;
1046 ClientSocketHandle
* handle() { return &handle_
; }
1048 const net::CompletionCallback
& callback() const { return callback_
; }
1051 void OnComplete(int result
);
1053 ClientSocketHandle handle_
;
1054 std::vector
<TestSocketRequest
*>* request_order_
;
1055 size_t* completion_count_
;
1056 CompletionCallback callback_
;
1058 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest
);
1061 class ClientSocketPoolTest
{
1066 // A socket will be disconnected in addition to handle being reset.
1070 static const int kIndexOutOfBounds
;
1071 static const int kRequestNotFound
;
1073 ClientSocketPoolTest();
1074 ~ClientSocketPoolTest();
1076 template <typename PoolType
>
1077 int StartRequestUsingPool(
1078 PoolType
* socket_pool
,
1079 const std::string
& group_name
,
1080 RequestPriority priority
,
1081 const scoped_refptr
<typename
PoolType::SocketParams
>& socket_params
) {
1082 DCHECK(socket_pool
);
1083 TestSocketRequest
* request
=
1084 new TestSocketRequest(&request_order_
, &completion_count_
);
1085 requests_
.push_back(request
);
1086 int rv
= request
->handle()->Init(group_name
,
1089 request
->callback(),
1092 if (rv
!= ERR_IO_PENDING
)
1093 request_order_
.push_back(request
);
1097 // Provided there were n requests started, takes |index| in range 1..n
1098 // and returns order in which that request completed, in range 1..n,
1099 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1100 // if that request did not complete (for example was canceled).
1101 int GetOrderOfRequest(size_t index
) const;
1103 // Resets first initialized socket handle from |requests_|. If found such
1104 // a handle, returns true.
1105 bool ReleaseOneConnection(KeepAlive keep_alive
);
1107 // Releases connections until there is nothing to release.
1108 void ReleaseAllConnections(KeepAlive keep_alive
);
1110 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1111 // returns 0-based indices.
1112 TestSocketRequest
* request(int i
) { return requests_
[i
]; }
1114 size_t requests_size() const { return requests_
.size(); }
1115 ScopedVector
<TestSocketRequest
>* requests() { return &requests_
; }
1116 size_t completion_count() const { return completion_count_
; }
1119 ScopedVector
<TestSocketRequest
> requests_
;
1120 std::vector
<TestSocketRequest
*> request_order_
;
1121 size_t completion_count_
;
1123 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest
);
1126 class MockTransportSocketParams
1127 : public base::RefCounted
<MockTransportSocketParams
> {
1129 friend class base::RefCounted
<MockTransportSocketParams
>;
1130 ~MockTransportSocketParams() {}
1132 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams
);
1135 class MockTransportClientSocketPool
: public TransportClientSocketPool
{
1137 typedef MockTransportSocketParams SocketParams
;
1139 class MockConnectJob
{
1141 MockConnectJob(scoped_ptr
<StreamSocket
> socket
,
1142 ClientSocketHandle
* handle
,
1143 const CompletionCallback
& callback
);
1147 bool CancelHandle(const ClientSocketHandle
* handle
);
1150 void OnConnect(int rv
);
1152 scoped_ptr
<StreamSocket
> socket_
;
1153 ClientSocketHandle
* handle_
;
1154 CompletionCallback user_callback_
;
1156 DISALLOW_COPY_AND_ASSIGN(MockConnectJob
);
1159 MockTransportClientSocketPool(int max_sockets
,
1160 int max_sockets_per_group
,
1161 ClientSocketFactory
* socket_factory
);
1163 ~MockTransportClientSocketPool() override
;
1165 RequestPriority
last_request_priority() const {
1166 return last_request_priority_
;
1168 int release_count() const { return release_count_
; }
1169 int cancel_count() const { return cancel_count_
; }
1171 // TransportClientSocketPool implementation.
1172 int RequestSocket(const std::string
& group_name
,
1173 const void* socket_params
,
1174 RequestPriority priority
,
1175 ClientSocketHandle
* handle
,
1176 const CompletionCallback
& callback
,
1177 const BoundNetLog
& net_log
) override
;
1179 void CancelRequest(const std::string
& group_name
,
1180 ClientSocketHandle
* handle
) override
;
1181 void ReleaseSocket(const std::string
& group_name
,
1182 scoped_ptr
<StreamSocket
> socket
,
1186 ClientSocketFactory
* client_socket_factory_
;
1187 ScopedVector
<MockConnectJob
> job_list_
;
1188 RequestPriority last_request_priority_
;
1192 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool
);
1195 class DeterministicMockClientSocketFactory
: public ClientSocketFactory
{
1197 DeterministicMockClientSocketFactory();
1198 ~DeterministicMockClientSocketFactory() override
;
1200 void AddSocketDataProvider(DeterministicSocketData
* socket
);
1201 void AddSSLSocketDataProvider(SSLSocketDataProvider
* socket
);
1202 void ResetNextMockIndexes();
1204 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1206 MockSSLClientSocket
* GetMockSSLClientSocket(size_t index
) const;
1208 SocketDataProviderArray
<DeterministicSocketData
>& mock_data() {
1211 std::vector
<DeterministicMockTCPClientSocket
*>& tcp_client_sockets() {
1212 return tcp_client_sockets_
;
1214 std::vector
<DeterministicMockUDPClientSocket
*>& udp_client_sockets() {
1215 return udp_client_sockets_
;
1218 // ClientSocketFactory
1219 scoped_ptr
<DatagramClientSocket
> CreateDatagramClientSocket(
1220 DatagramSocket::BindType bind_type
,
1221 const RandIntCallback
& rand_int_cb
,
1223 const NetLog::Source
& source
) override
;
1224 scoped_ptr
<StreamSocket
> CreateTransportClientSocket(
1225 const AddressList
& addresses
,
1227 const NetLog::Source
& source
) override
;
1228 scoped_ptr
<SSLClientSocket
> CreateSSLClientSocket(
1229 scoped_ptr
<ClientSocketHandle
> transport_socket
,
1230 const HostPortPair
& host_and_port
,
1231 const SSLConfig
& ssl_config
,
1232 const SSLClientSocketContext
& context
) override
;
1233 void ClearSSLSessionCache() override
;
1236 SocketDataProviderArray
<DeterministicSocketData
> mock_data_
;
1237 SocketDataProviderArray
<SSLSocketDataProvider
> mock_ssl_data_
;
1239 // Store pointers to handed out sockets in case the test wants to get them.
1240 std::vector
<DeterministicMockTCPClientSocket
*> tcp_client_sockets_
;
1241 std::vector
<DeterministicMockUDPClientSocket
*> udp_client_sockets_
;
1242 std::vector
<MockSSLClientSocket
*> ssl_client_sockets_
;
1244 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory
);
1247 class MockSOCKSClientSocketPool
: public SOCKSClientSocketPool
{
1249 MockSOCKSClientSocketPool(int max_sockets
,
1250 int max_sockets_per_group
,
1251 TransportClientSocketPool
* transport_pool
);
1253 ~MockSOCKSClientSocketPool() override
;
1255 // SOCKSClientSocketPool implementation.
1256 int RequestSocket(const std::string
& group_name
,
1257 const void* socket_params
,
1258 RequestPriority priority
,
1259 ClientSocketHandle
* handle
,
1260 const CompletionCallback
& callback
,
1261 const BoundNetLog
& net_log
) override
;
1263 void CancelRequest(const std::string
& group_name
,
1264 ClientSocketHandle
* handle
) override
;
1265 void ReleaseSocket(const std::string
& group_name
,
1266 scoped_ptr
<StreamSocket
> socket
,
1270 TransportClientSocketPool
* const transport_pool_
;
1272 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool
);
1275 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock
1276 // delay to zero for testing purposes. Automatically restores the original value
1278 class ScopedWebSocketEndpointZeroUnlockDelay
{
1280 ScopedWebSocketEndpointZeroUnlockDelay();
1281 ~ScopedWebSocketEndpointZeroUnlockDelay();
1284 base::TimeDelta old_delay_
;
1287 // Constants for a successful SOCKS v5 handshake.
1288 extern const char kSOCKS5GreetRequest
[];
1289 extern const int kSOCKS5GreetRequestLength
;
1291 extern const char kSOCKS5GreetResponse
[];
1292 extern const int kSOCKS5GreetResponseLength
;
1294 extern const char kSOCKS5OkRequest
[];
1295 extern const int kSOCKS5OkRequestLength
;
1297 extern const char kSOCKS5OkResponse
[];
1298 extern const int kSOCKS5OkResponseLength
;
1302 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_