Compute if a layer is clipped outside CalcDrawProps
[chromium-blink-merge.git] / net / socket / socket_test_util.h
blobbd9725c3889ed971220ccbe7a087b172b9726984
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_
8 #include <cstring>
9 #include <deque>
10 #include <string>
11 #include <vector>
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"
39 namespace net {
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,
50 class AsyncSocket;
51 class ChannelIDService;
52 class MockClientSocket;
53 class SSLClientSocket;
54 class StreamSocket;
56 enum IoMode {
57 ASYNC,
58 SYNCHRONOUS
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();
72 IoMode mode;
73 int result;
74 IPEndPoint peer_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
82 // type).
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
93 template <MockReadWriteType type>
94 struct MockReadWrite {
95 // Flag to indicate that the message loop should be terminated.
96 enum {
97 STOPLOOP = 1 << 31
100 // Default
101 MockReadWrite()
102 : mode(SYNCHRONOUS),
103 result(0),
104 data(NULL),
105 data_len(0),
106 sequence_number(0) {}
108 // Read/write failure (no data).
109 MockReadWrite(IoMode io_mode, int result)
110 : mode(io_mode),
111 result(result),
112 data(NULL),
113 data_len(0),
114 sequence_number(0) {}
116 // Read/write failure (no data), with sequence information.
117 MockReadWrite(IoMode io_mode, int result, int seq)
118 : mode(io_mode),
119 result(result),
120 data(NULL),
121 data_len(0),
122 sequence_number(seq) {}
124 // Asynchronous read/write success (inferred data length).
125 explicit MockReadWrite(const char* data)
126 : mode(ASYNC),
127 result(0),
128 data(data),
129 data_len(strlen(data)),
130 sequence_number(0) {}
132 // Read/write success (inferred data length).
133 MockReadWrite(IoMode io_mode, const char* data)
134 : mode(io_mode),
135 result(0),
136 data(data),
137 data_len(strlen(data)),
138 sequence_number(0) {}
140 // Read/write success.
141 MockReadWrite(IoMode io_mode, const char* data, int data_len)
142 : mode(io_mode),
143 result(0),
144 data(data),
145 data_len(data_len),
146 sequence_number(0) {}
148 // Read/write success (inferred data length) with sequence information.
149 MockReadWrite(IoMode io_mode, int seq, const char* data)
150 : mode(io_mode),
151 result(0),
152 data(data),
153 data_len(strlen(data)),
154 sequence_number(seq) {}
156 // Read/write success with sequence information.
157 MockReadWrite(IoMode io_mode, const char* data, int data_len, int seq)
158 : mode(io_mode),
159 result(0),
160 data(data),
161 data_len(data_len),
162 sequence_number(seq) {}
164 IoMode mode;
165 int result;
166 const char* data;
167 int data_len;
169 // For data providers that only allows reads to occur in a particular
170 // sequence. If a read occurs before the given |sequence_number| is reached,
171 // an ERR_IO_PENDING is returned.
172 int sequence_number; // The sequence number at which a read is allowed
173 // to occur.
176 typedef MockReadWrite<MOCK_READ> MockRead;
177 typedef MockReadWrite<MOCK_WRITE> MockWrite;
179 struct MockWriteResult {
180 MockWriteResult(IoMode io_mode, int result) : mode(io_mode), result(result) {}
182 IoMode mode;
183 int result;
186 // The SocketDataProvider is an interface used by the MockClientSocket
187 // for getting data about individual reads and writes on the socket.
188 class SocketDataProvider {
189 public:
190 SocketDataProvider() : socket_(NULL) {}
192 virtual ~SocketDataProvider() {}
194 // Returns the buffer and result code for the next simulated read.
195 // If the |MockRead.result| is ERR_IO_PENDING, it informs the caller
196 // that it will be called via the AsyncSocket::OnReadComplete()
197 // function at a later time.
198 virtual MockRead OnRead() = 0;
199 virtual MockWriteResult OnWrite(const std::string& data) = 0;
200 virtual void Reset() = 0;
201 virtual bool AllReadDataConsumed() const = 0;
202 virtual bool AllWriteDataConsumed() const = 0;
204 // Accessor for the socket which is using the SocketDataProvider.
205 AsyncSocket* socket() { return socket_; }
206 void set_socket(AsyncSocket* socket) { socket_ = socket; }
208 MockConnect connect_data() const { return connect_; }
209 void set_connect_data(const MockConnect& connect) { connect_ = connect; }
211 private:
212 MockConnect connect_;
213 AsyncSocket* socket_;
215 DISALLOW_COPY_AND_ASSIGN(SocketDataProvider);
218 // The AsyncSocket is an interface used by the SocketDataProvider to
219 // complete the asynchronous read operation.
220 class AsyncSocket {
221 public:
222 // If an async IO is pending because the SocketDataProvider returned
223 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
224 // is called to complete the asynchronous read operation.
225 // data.async is ignored, and this read is completed synchronously as
226 // part of this call.
227 // TODO(rch): this should take a StringPiece since most of the fields
228 // are ignored.
229 virtual void OnReadComplete(const MockRead& data) = 0;
230 // If an async IO is pending because the SocketDataProvider returned
231 // ERR_IO_PENDING, then the AsyncSocket waits until this OnReadComplete
232 // is called to complete the asynchronous read operation.
233 virtual void OnWriteComplete(int rv) = 0;
234 virtual void OnConnectComplete(const MockConnect& data) = 0;
237 // StaticSocketDataHelper manages a list of reads and writes.
238 class StaticSocketDataHelper {
239 public:
240 StaticSocketDataHelper(MockRead* reads,
241 size_t reads_count,
242 MockWrite* writes,
243 size_t writes_count);
244 ~StaticSocketDataHelper();
246 // These functions get access to the next available read and write data,
247 // or null if there is no more data available.
248 const MockRead& PeekRead() const;
249 const MockWrite& PeekWrite() const;
251 // Returns the current read or write , and then advances to the next one.
252 const MockRead& AdvanceRead();
253 const MockWrite& AdvanceWrite();
255 // Resets the read and write indexes to 0.
256 void Reset();
258 // Returns true if |data| is valid data for the next write. In order
259 // to support short writes, the next write may be longer than |data|
260 // in which case this method will still return true.
261 bool VerifyWriteData(const std::string& data);
263 size_t read_index() const { return read_index_; }
264 size_t write_index() const { return write_index_; }
265 size_t read_count() const { return read_count_; }
266 size_t write_count() const { return write_count_; }
268 bool AllReadDataConsumed() const { return read_index_ >= read_count_; }
269 bool AllWriteDataConsumed() const { return write_index_ >= write_count_; }
271 private:
272 MockRead* reads_;
273 size_t read_index_;
274 size_t read_count_;
275 MockWrite* writes_;
276 size_t write_index_;
277 size_t write_count_;
279 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataHelper);
282 // SocketDataProvider which responds based on static tables of mock reads and
283 // writes.
284 class StaticSocketDataProvider : public SocketDataProvider {
285 public:
286 StaticSocketDataProvider();
287 StaticSocketDataProvider(MockRead* reads,
288 size_t reads_count,
289 MockWrite* writes,
290 size_t writes_count);
291 ~StaticSocketDataProvider() override;
293 virtual void CompleteRead() {}
295 // SocketDataProvider implementation.
296 MockRead OnRead() override;
297 MockWriteResult OnWrite(const std::string& data) override;
298 void Reset() override;
299 bool AllReadDataConsumed() const override;
300 bool AllWriteDataConsumed() const override;
302 size_t read_index() const { return helper_.read_index(); }
303 size_t write_index() const { return helper_.write_index(); }
304 size_t read_count() const { return helper_.read_count(); }
305 size_t write_count() const { return helper_.write_count(); }
307 protected:
308 StaticSocketDataHelper* helper() { return &helper_; }
310 private:
311 StaticSocketDataHelper helper_;
313 DISALLOW_COPY_AND_ASSIGN(StaticSocketDataProvider);
316 // SSLSocketDataProviders only need to keep track of the return code from calls
317 // to Connect().
318 struct SSLSocketDataProvider {
319 SSLSocketDataProvider(IoMode mode, int result);
320 ~SSLSocketDataProvider();
322 void SetNextProto(NextProto proto);
324 MockConnect connect;
325 SSLClientSocket::NextProtoStatus next_proto_status;
326 std::string next_proto;
327 NextProtoVector next_protos_expected_in_ssl_config;
328 bool client_cert_sent;
329 SSLCertRequestInfo* cert_request_info;
330 scoped_refptr<X509Certificate> cert;
331 bool channel_id_sent;
332 ChannelIDService* channel_id_service;
333 int connection_status;
336 // Uses the sequence_number field in the mock reads and writes to
337 // complete the operations in a specified order.
338 class SequencedSocketData : public SocketDataProvider {
339 public:
340 // |reads| is the list of MockRead completions.
341 // |writes| is the list of MockWrite completions.
342 SequencedSocketData(MockRead* reads,
343 size_t reads_count,
344 MockWrite* writes,
345 size_t writes_count);
347 // |connect| is the result for the connect phase.
348 // |reads| is the list of MockRead completions.
349 // |writes| is the list of MockWrite completions.
350 SequencedSocketData(const MockConnect& connect,
351 MockRead* reads,
352 size_t reads_count,
353 MockWrite* writes,
354 size_t writes_count);
356 ~SequencedSocketData() override;
358 // SocketDataProviderBase implementation.
359 MockRead OnRead() override;
360 MockWriteResult OnWrite(const std::string& data) override;
361 void Reset() override;
362 bool AllReadDataConsumed() const override;
363 bool AllWriteDataConsumed() const override;
365 bool IsReadPaused();
366 void CompleteRead();
368 private:
369 // Defines the state for the read or write path.
370 enum IoState {
371 IDLE, // No async operation is in progress.
372 PENDING, // An async operation in waiting for another opteration to
373 // complete.
374 COMPLETING, // A task has been posted to complet an async operation.
375 PAUSED, // IO is paused until CompleteRead() is called.
378 void OnReadComplete();
379 void OnWriteComplete();
381 void MaybePostReadCompleteTask();
382 void MaybePostWriteCompleteTask();
384 StaticSocketDataHelper helper_;
385 int sequence_number_;
386 IoState read_state_;
387 IoState write_state_;
389 base::WeakPtrFactory<SequencedSocketData> weak_factory_;
391 DISALLOW_COPY_AND_ASSIGN(SequencedSocketData);
394 class DeterministicMockTCPClientSocket;
396 // This class gives the user full control over the network activity,
397 // specifically the timing of the COMPLETION of I/O operations. Regardless of
398 // the order in which I/O operations are initiated, this class ensures that they
399 // complete in the correct order.
401 // Network activity is modeled as a sequence of numbered steps which is
402 // incremented whenever an I/O operation completes. This can happen under two
403 // different circumstances:
405 // 1) Performing a synchronous I/O operation. (Invoking Read() or Write()
406 // when the corresponding MockRead or MockWrite is marked !async).
407 // 2) Running the Run() method of this class. The run method will invoke
408 // the current MessageLoop, running all pending events, and will then
409 // invoke any pending IO callbacks.
411 // In addition, this class allows for I/O processing to "stop" at a specified
412 // step, by calling SetStop(int) or StopAfter(int). Initiating an I/O operation
413 // by calling Read() or Write() while stopped is permitted if the operation is
414 // asynchronous. It is an error to perform synchronous I/O while stopped.
416 // When creating the MockReads and MockWrites, note that the sequence number
417 // refers to the number of the step in which the I/O will complete. In the
418 // case of synchronous I/O, this will be the same step as the I/O is initiated.
419 // However, in the case of asynchronous I/O, this I/O may be initiated in
420 // a much earlier step. Furthermore, when the a Read() or Write() is separated
421 // from its completion by other Read() or Writes()'s, it can not be marked
422 // synchronous. If it is, ERR_UNUEXPECTED will be returned indicating that a
423 // synchronous Read() or Write() could not be completed synchronously because of
424 // the specific ordering constraints.
426 // Sequence numbers are preserved across both reads and writes. There should be
427 // no gaps in sequence numbers, and no repeated sequence numbers. i.e.
428 // MockRead reads[] = {
429 // MockRead(false, "first read", length, 0) // sync
430 // MockRead(true, "second read", length, 2) // async
431 // };
432 // MockWrite writes[] = {
433 // MockWrite(true, "first write", length, 1), // async
434 // MockWrite(false, "second write", length, 3), // sync
435 // };
437 // Example control flow:
438 // Read() is called. The current step is 0. The first available read is
439 // synchronous, so the call to Read() returns length. The current step is
440 // now 1. Next, Read() is called again. The next available read can
441 // not be completed until step 2, so Read() returns ERR_IO_PENDING. The current
442 // step is still 1. Write is called(). The first available write is able to
443 // complete in this step, but is marked asynchronous. Write() returns
444 // ERR_IO_PENDING. The current step is still 1. At this point RunFor(1) is
445 // called which will cause the write callback to be invoked, and will then
446 // stop. The current state is now 2. RunFor(1) is called again, which
447 // causes the read callback to be invoked, and will then stop. Then current
448 // step is 2. Write() is called again. Then next available write is
449 // synchronous so the call to Write() returns length.
451 // For examples of how to use this class, see:
452 // deterministic_socket_data_unittests.cc
453 class DeterministicSocketData {
454 public:
455 // The Delegate is an abstract interface which handles the communication from
456 // the DeterministicSocketData to the Deterministic MockSocket. The
457 // MockSockets directly store a pointer to the DeterministicSocketData,
458 // whereas the DeterministicSocketData only stores a pointer to the
459 // abstract Delegate interface.
460 class Delegate {
461 public:
462 // Returns true if there is currently a write pending. That is to say, if
463 // an asynchronous write has been started but the callback has not been
464 // invoked.
465 virtual bool WritePending() const = 0;
466 // Returns true if there is currently a read pending. That is to say, if
467 // an asynchronous read has been started but the callback has not been
468 // invoked.
469 virtual bool ReadPending() const = 0;
470 // Called to complete an asynchronous write to execute the write callback.
471 virtual void CompleteWrite() = 0;
472 // Called to complete an asynchronous read to execute the read callback.
473 virtual int CompleteRead() = 0;
475 protected:
476 virtual ~Delegate() {}
479 // |reads| the list of MockRead completions.
480 // |writes| the list of MockWrite completions.
481 DeterministicSocketData(MockRead* reads,
482 size_t reads_count,
483 MockWrite* writes,
484 size_t writes_count);
485 ~DeterministicSocketData();
487 // Consume all the data up to the give stop point (via SetStop()).
488 void Run();
490 // Set the stop point to be |steps| from now, and then invoke Run().
491 void RunFor(int steps);
493 // Stop at step |seq|, which must be in the future.
494 void SetStop(int seq);
496 // Stop |seq| steps after the current step.
497 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) { delegate_ = delegate; }
505 MockConnect connect_data() const { return connect_; }
506 void set_connect_data(const MockConnect& connect) { connect_ = connect; }
508 // When the socket calls Read(), that calls OnRead(), and expects either
509 // ERR_IO_PENDING or data.
510 MockRead OnRead();
512 // When the socket calls Write(), it always completes synchronously. OnWrite()
513 // checks to make sure the written data matches the expected data. The
514 // callback will not be invoked until its sequence number is reached.
515 MockWriteResult OnWrite(const std::string& data);
517 bool AllReadDataConsumed() const;
518 bool AllWriteDataConsumed() const;
520 private:
521 // Invoke the read and write callbacks, if the timing is appropriate.
522 void InvokeCallbacks();
524 void NextStep();
526 void VerifyCorrectSequenceNumbers(MockRead* reads,
527 size_t reads_count,
528 MockWrite* writes,
529 size_t writes_count);
530 StaticSocketDataHelper helper_;
531 MockConnect connect_;
532 int sequence_number_;
533 MockRead current_read_;
534 MockWrite current_write_;
535 int stopping_sequence_number_;
536 bool stopped_;
537 base::WeakPtr<Delegate> delegate_;
538 bool print_debug_;
539 bool is_running_;
542 // Holds an array of SocketDataProvider elements. As Mock{TCP,SSL}StreamSocket
543 // objects get instantiated, they take their data from the i'th element of this
544 // array.
545 template <typename T>
546 class SocketDataProviderArray {
547 public:
548 SocketDataProviderArray() : next_index_(0) {}
550 T* GetNext() {
551 DCHECK_LT(next_index_, data_providers_.size());
552 return data_providers_[next_index_++];
555 void Add(T* data_provider) {
556 DCHECK(data_provider);
557 data_providers_.push_back(data_provider);
560 size_t next_index() { return next_index_; }
562 void ResetNextIndex() { next_index_ = 0; }
564 private:
565 // Index of the next |data_providers_| element to use. Not an iterator
566 // because those are invalidated on vector reallocation.
567 size_t next_index_;
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
581 // socket types.
582 class MockClientSocketFactory : public ClientSocketFactory {
583 public:
584 MockClientSocketFactory();
585 ~MockClientSocketFactory() override;
587 void AddSocketDataProvider(SocketDataProvider* socket);
588 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
589 void ResetNextMockIndexes();
591 SocketDataProviderArray<SocketDataProvider>& mock_data() {
592 return mock_data_;
595 // ClientSocketFactory
596 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
597 DatagramSocket::BindType bind_type,
598 const RandIntCallback& rand_int_cb,
599 NetLog* net_log,
600 const NetLog::Source& source) override;
601 scoped_ptr<StreamSocket> CreateTransportClientSocket(
602 const AddressList& addresses,
603 NetLog* net_log,
604 const NetLog::Source& source) override;
605 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 void ClearSSLSessionCache() override;
612 private:
613 SocketDataProviderArray<SocketDataProvider> mock_data_;
614 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
617 class MockClientSocket : public SSLClientSocket {
618 public:
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 int Read(IOBuffer* buf,
628 int buf_len,
629 const CompletionCallback& callback) override = 0;
630 int Write(IOBuffer* buf,
631 int buf_len,
632 const CompletionCallback& callback) override = 0;
633 int SetReceiveBufferSize(int32 size) override;
634 int SetSendBufferSize(int32 size) override;
636 // StreamSocket implementation.
637 int Connect(const CompletionCallback& callback) override = 0;
638 void Disconnect() override;
639 bool IsConnected() const override;
640 bool IsConnectedAndIdle() const override;
641 int GetPeerAddress(IPEndPoint* address) const override;
642 int GetLocalAddress(IPEndPoint* address) const override;
643 const BoundNetLog& NetLog() const override;
644 void SetSubresourceSpeculation() override {}
645 void SetOmniboxSpeculation() override {}
646 void GetConnectionAttempts(ConnectionAttempts* out) const override;
647 void ClearConnectionAttempts() override {}
648 void AddConnectionAttempts(const ConnectionAttempts& attempts) override {}
650 // SSLClientSocket implementation.
651 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
652 int ExportKeyingMaterial(const base::StringPiece& label,
653 bool has_context,
654 const base::StringPiece& context,
655 unsigned char* out,
656 unsigned int outlen) override;
657 int GetTLSUniqueChannelBinding(std::string* out) override;
658 NextProtoStatus GetNextProto(std::string* proto) const override;
659 ChannelIDService* GetChannelIDService() const override;
660 SSLFailureState GetSSLFailureState() const override;
662 protected:
663 ~MockClientSocket() override;
664 void RunCallbackAsync(const CompletionCallback& callback, int result);
665 void RunCallback(const CompletionCallback& callback, int result);
667 // True if Connect completed successfully and Disconnect hasn't been called.
668 bool connected_;
670 // Address of the "remote" peer we're connected to.
671 IPEndPoint peer_addr_;
673 BoundNetLog net_log_;
675 private:
676 base::WeakPtrFactory<MockClientSocket> weak_factory_;
678 DISALLOW_COPY_AND_ASSIGN(MockClientSocket);
681 class MockTCPClientSocket : public MockClientSocket, public AsyncSocket {
682 public:
683 MockTCPClientSocket(const AddressList& addresses,
684 net::NetLog* net_log,
685 SocketDataProvider* socket);
686 ~MockTCPClientSocket() override;
688 const AddressList& addresses() const { return addresses_; }
690 // Socket implementation.
691 int Read(IOBuffer* buf,
692 int buf_len,
693 const CompletionCallback& callback) override;
694 int Write(IOBuffer* buf,
695 int buf_len,
696 const CompletionCallback& callback) override;
698 // StreamSocket implementation.
699 int Connect(const CompletionCallback& callback) override;
700 void Disconnect() override;
701 bool IsConnected() const override;
702 bool IsConnectedAndIdle() const override;
703 int GetPeerAddress(IPEndPoint* address) const override;
704 bool WasEverUsed() const override;
705 bool UsingTCPFastOpen() const override;
706 bool WasNpnNegotiated() const override;
707 bool GetSSLInfo(SSLInfo* ssl_info) override;
708 void GetConnectionAttempts(ConnectionAttempts* out) const override;
709 void ClearConnectionAttempts() override;
710 void AddConnectionAttempts(const ConnectionAttempts& attempts) override;
712 // AsyncSocket:
713 void OnReadComplete(const MockRead& data) override;
714 void OnWriteComplete(int rv) override;
715 void OnConnectComplete(const MockConnect& data) override;
717 private:
718 int CompleteRead();
720 AddressList addresses_;
722 SocketDataProvider* data_;
723 int read_offset_;
724 MockRead read_data_;
725 bool need_read_data_;
727 // True if the peer has closed the connection. This allows us to simulate
728 // the recv(..., MSG_PEEK) call in the IsConnectedAndIdle method of the real
729 // TCPClientSocket.
730 bool peer_closed_connection_;
732 // While an asynchronous read is pending, we save our user-buffer state.
733 scoped_refptr<IOBuffer> pending_read_buf_;
734 int pending_read_buf_len_;
735 CompletionCallback pending_read_callback_;
736 CompletionCallback pending_write_callback_;
737 bool was_used_to_convey_data_;
739 DISALLOW_COPY_AND_ASSIGN(MockTCPClientSocket);
742 // DeterministicSocketHelper is a helper class that can be used
743 // to simulate Socket::Read() and Socket::Write()
744 // using deterministic |data|.
745 // Note: This is provided as a common helper class because
746 // of the inheritance hierarchy of DeterministicMock[UDP,TCP]ClientSocket and a
747 // desire not to introduce an additional common base class.
748 class DeterministicSocketHelper {
749 public:
750 DeterministicSocketHelper(NetLog* net_log, DeterministicSocketData* data);
751 virtual ~DeterministicSocketHelper();
753 bool write_pending() const { return write_pending_; }
754 bool read_pending() const { return read_pending_; }
756 void CompleteWrite();
757 int CompleteRead();
759 int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
760 int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
762 const BoundNetLog& net_log() const { return net_log_; }
764 bool was_used_to_convey_data() const { return was_used_to_convey_data_; }
766 bool peer_closed_connection() const { return peer_closed_connection_; }
768 DeterministicSocketData* data() const { return data_; }
770 private:
771 bool write_pending_;
772 CompletionCallback write_callback_;
773 int write_result_;
775 MockRead read_data_;
777 IOBuffer* read_buf_;
778 int read_buf_len_;
779 bool read_pending_;
780 CompletionCallback read_callback_;
781 DeterministicSocketData* data_;
782 bool was_used_to_convey_data_;
783 bool peer_closed_connection_;
784 BoundNetLog net_log_;
787 // Mock UDP socket to be used in conjunction with DeterministicSocketData.
788 class DeterministicMockUDPClientSocket
789 : public DatagramClientSocket,
790 public DeterministicSocketData::Delegate,
791 public base::SupportsWeakPtr<DeterministicMockUDPClientSocket> {
792 public:
793 DeterministicMockUDPClientSocket(net::NetLog* net_log,
794 DeterministicSocketData* data);
795 ~DeterministicMockUDPClientSocket() override;
797 // DeterministicSocketData::Delegate:
798 bool WritePending() const override;
799 bool ReadPending() const override;
800 void CompleteWrite() override;
801 int CompleteRead() override;
803 // Socket implementation.
804 int Read(IOBuffer* buf,
805 int buf_len,
806 const CompletionCallback& callback) override;
807 int Write(IOBuffer* buf,
808 int buf_len,
809 const CompletionCallback& callback) override;
810 int SetReceiveBufferSize(int32 size) override;
811 int SetSendBufferSize(int32 size) override;
813 // DatagramSocket implementation.
814 void Close() override;
815 int GetPeerAddress(IPEndPoint* address) const override;
816 int GetLocalAddress(IPEndPoint* address) const override;
817 const BoundNetLog& NetLog() const override;
819 // DatagramClientSocket implementation.
820 int Connect(const IPEndPoint& address) override;
822 void set_source_port(uint16 port) { source_port_ = port; }
824 private:
825 bool connected_;
826 IPEndPoint peer_address_;
827 DeterministicSocketHelper helper_;
828 uint16 source_port_; // Ephemeral source port.
830 DISALLOW_COPY_AND_ASSIGN(DeterministicMockUDPClientSocket);
833 // Mock TCP socket to be used in conjunction with DeterministicSocketData.
834 class DeterministicMockTCPClientSocket
835 : public MockClientSocket,
836 public DeterministicSocketData::Delegate,
837 public base::SupportsWeakPtr<DeterministicMockTCPClientSocket> {
838 public:
839 DeterministicMockTCPClientSocket(net::NetLog* net_log,
840 DeterministicSocketData* data);
841 ~DeterministicMockTCPClientSocket() override;
843 // DeterministicSocketData::Delegate:
844 bool WritePending() const override;
845 bool ReadPending() const override;
846 void CompleteWrite() override;
847 int CompleteRead() override;
849 // Socket:
850 int Write(IOBuffer* buf,
851 int buf_len,
852 const CompletionCallback& callback) override;
853 int Read(IOBuffer* buf,
854 int buf_len,
855 const CompletionCallback& callback) override;
857 // StreamSocket:
858 int Connect(const CompletionCallback& callback) override;
859 void Disconnect() override;
860 bool IsConnected() const override;
861 bool IsConnectedAndIdle() const override;
862 bool WasEverUsed() const override;
863 bool UsingTCPFastOpen() const override;
864 bool WasNpnNegotiated() const override;
865 bool GetSSLInfo(SSLInfo* ssl_info) override;
867 private:
868 DeterministicSocketHelper helper_;
870 DISALLOW_COPY_AND_ASSIGN(DeterministicMockTCPClientSocket);
873 class MockSSLClientSocket : public MockClientSocket, public AsyncSocket {
874 public:
875 MockSSLClientSocket(scoped_ptr<ClientSocketHandle> transport_socket,
876 const HostPortPair& host_and_port,
877 const SSLConfig& ssl_config,
878 SSLSocketDataProvider* socket);
879 ~MockSSLClientSocket() override;
881 // Socket implementation.
882 int Read(IOBuffer* buf,
883 int buf_len,
884 const CompletionCallback& callback) override;
885 int Write(IOBuffer* buf,
886 int buf_len,
887 const CompletionCallback& callback) override;
889 // StreamSocket implementation.
890 int Connect(const CompletionCallback& callback) override;
891 void Disconnect() override;
892 bool IsConnected() const override;
893 bool WasEverUsed() const override;
894 bool UsingTCPFastOpen() const override;
895 int GetPeerAddress(IPEndPoint* address) const override;
896 bool GetSSLInfo(SSLInfo* ssl_info) override;
898 // SSLClientSocket implementation.
899 void GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info) override;
900 NextProtoStatus GetNextProto(std::string* proto) const override;
902 // This MockSocket does not implement the manual async IO feature.
903 void OnReadComplete(const MockRead& data) override;
904 void OnWriteComplete(int rv) override;
905 void OnConnectComplete(const MockConnect& data) override;
907 ChannelIDService* GetChannelIDService() const override;
909 private:
910 static void ConnectCallback(MockSSLClientSocket* ssl_client_socket,
911 const CompletionCallback& callback,
912 int rv);
914 scoped_ptr<ClientSocketHandle> transport_;
915 SSLSocketDataProvider* data_;
917 DISALLOW_COPY_AND_ASSIGN(MockSSLClientSocket);
920 class MockUDPClientSocket : public DatagramClientSocket, public AsyncSocket {
921 public:
922 MockUDPClientSocket(SocketDataProvider* data, net::NetLog* net_log);
923 ~MockUDPClientSocket() override;
925 // Socket implementation.
926 int Read(IOBuffer* buf,
927 int buf_len,
928 const CompletionCallback& callback) override;
929 int Write(IOBuffer* buf,
930 int buf_len,
931 const CompletionCallback& callback) override;
932 int SetReceiveBufferSize(int32 size) override;
933 int SetSendBufferSize(int32 size) override;
935 // DatagramSocket implementation.
936 void Close() override;
937 int GetPeerAddress(IPEndPoint* address) const override;
938 int GetLocalAddress(IPEndPoint* address) const override;
939 const BoundNetLog& NetLog() const override;
941 // DatagramClientSocket implementation.
942 int Connect(const IPEndPoint& address) override;
944 // AsyncSocket implementation.
945 void OnReadComplete(const MockRead& data) override;
946 void OnWriteComplete(int rv) override;
947 void OnConnectComplete(const MockConnect& data) override;
949 void set_source_port(uint16 port) { source_port_ = port;}
951 private:
952 int CompleteRead();
954 void RunCallbackAsync(const CompletionCallback& callback, int result);
955 void RunCallback(const CompletionCallback& callback, int result);
957 bool connected_;
958 SocketDataProvider* data_;
959 int read_offset_;
960 MockRead read_data_;
961 bool need_read_data_;
962 uint16 source_port_; // Ephemeral source port.
964 // Address of the "remote" peer we're connected to.
965 IPEndPoint peer_addr_;
967 // While an asynchronous IO is pending, we save our user-buffer state.
968 scoped_refptr<IOBuffer> pending_read_buf_;
969 int pending_read_buf_len_;
970 CompletionCallback pending_read_callback_;
971 CompletionCallback pending_write_callback_;
973 BoundNetLog net_log_;
975 base::WeakPtrFactory<MockUDPClientSocket> weak_factory_;
977 DISALLOW_COPY_AND_ASSIGN(MockUDPClientSocket);
980 class TestSocketRequest : public TestCompletionCallbackBase {
981 public:
982 TestSocketRequest(std::vector<TestSocketRequest*>* request_order,
983 size_t* completion_count);
984 ~TestSocketRequest() override;
986 ClientSocketHandle* handle() { return &handle_; }
988 const CompletionCallback& callback() const { return callback_; }
990 private:
991 void OnComplete(int result);
993 ClientSocketHandle handle_;
994 std::vector<TestSocketRequest*>* request_order_;
995 size_t* completion_count_;
996 CompletionCallback callback_;
998 DISALLOW_COPY_AND_ASSIGN(TestSocketRequest);
1001 class ClientSocketPoolTest {
1002 public:
1003 enum KeepAlive {
1004 KEEP_ALIVE,
1006 // A socket will be disconnected in addition to handle being reset.
1007 NO_KEEP_ALIVE,
1010 static const int kIndexOutOfBounds;
1011 static const int kRequestNotFound;
1013 ClientSocketPoolTest();
1014 ~ClientSocketPoolTest();
1016 template <typename PoolType>
1017 int StartRequestUsingPool(
1018 PoolType* socket_pool,
1019 const std::string& group_name,
1020 RequestPriority priority,
1021 const scoped_refptr<typename PoolType::SocketParams>& socket_params) {
1022 DCHECK(socket_pool);
1023 TestSocketRequest* request =
1024 new TestSocketRequest(&request_order_, &completion_count_);
1025 requests_.push_back(request);
1026 int rv = request->handle()->Init(group_name,
1027 socket_params,
1028 priority,
1029 request->callback(),
1030 socket_pool,
1031 BoundNetLog());
1032 if (rv != ERR_IO_PENDING)
1033 request_order_.push_back(request);
1034 return rv;
1037 // Provided there were n requests started, takes |index| in range 1..n
1038 // and returns order in which that request completed, in range 1..n,
1039 // or kIndexOutOfBounds if |index| is out of bounds, or kRequestNotFound
1040 // if that request did not complete (for example was canceled).
1041 int GetOrderOfRequest(size_t index) const;
1043 // Resets first initialized socket handle from |requests_|. If found such
1044 // a handle, returns true.
1045 bool ReleaseOneConnection(KeepAlive keep_alive);
1047 // Releases connections until there is nothing to release.
1048 void ReleaseAllConnections(KeepAlive keep_alive);
1050 // Note that this uses 0-based indices, while GetOrderOfRequest takes and
1051 // returns 0-based indices.
1052 TestSocketRequest* request(int i) { return requests_[i]; }
1054 size_t requests_size() const { return requests_.size(); }
1055 ScopedVector<TestSocketRequest>* requests() { return &requests_; }
1056 size_t completion_count() const { return completion_count_; }
1058 private:
1059 ScopedVector<TestSocketRequest> requests_;
1060 std::vector<TestSocketRequest*> request_order_;
1061 size_t completion_count_;
1063 DISALLOW_COPY_AND_ASSIGN(ClientSocketPoolTest);
1066 class MockTransportSocketParams
1067 : public base::RefCounted<MockTransportSocketParams> {
1068 private:
1069 friend class base::RefCounted<MockTransportSocketParams>;
1070 ~MockTransportSocketParams() {}
1072 DISALLOW_COPY_AND_ASSIGN(MockTransportSocketParams);
1075 class MockTransportClientSocketPool : public TransportClientSocketPool {
1076 public:
1077 typedef MockTransportSocketParams SocketParams;
1079 class MockConnectJob {
1080 public:
1081 MockConnectJob(scoped_ptr<StreamSocket> socket,
1082 ClientSocketHandle* handle,
1083 const CompletionCallback& callback);
1084 ~MockConnectJob();
1086 int Connect();
1087 bool CancelHandle(const ClientSocketHandle* handle);
1089 private:
1090 void OnConnect(int rv);
1092 scoped_ptr<StreamSocket> socket_;
1093 ClientSocketHandle* handle_;
1094 CompletionCallback user_callback_;
1096 DISALLOW_COPY_AND_ASSIGN(MockConnectJob);
1099 MockTransportClientSocketPool(int max_sockets,
1100 int max_sockets_per_group,
1101 ClientSocketFactory* socket_factory);
1103 ~MockTransportClientSocketPool() override;
1105 RequestPriority last_request_priority() const {
1106 return last_request_priority_;
1108 int release_count() const { return release_count_; }
1109 int cancel_count() const { return cancel_count_; }
1111 // TransportClientSocketPool implementation.
1112 int RequestSocket(const std::string& group_name,
1113 const void* socket_params,
1114 RequestPriority priority,
1115 ClientSocketHandle* handle,
1116 const CompletionCallback& callback,
1117 const BoundNetLog& net_log) override;
1119 void CancelRequest(const std::string& group_name,
1120 ClientSocketHandle* handle) override;
1121 void ReleaseSocket(const std::string& group_name,
1122 scoped_ptr<StreamSocket> socket,
1123 int id) override;
1125 private:
1126 ClientSocketFactory* client_socket_factory_;
1127 ScopedVector<MockConnectJob> job_list_;
1128 RequestPriority last_request_priority_;
1129 int release_count_;
1130 int cancel_count_;
1132 DISALLOW_COPY_AND_ASSIGN(MockTransportClientSocketPool);
1135 class DeterministicMockClientSocketFactory : public ClientSocketFactory {
1136 public:
1137 DeterministicMockClientSocketFactory();
1138 ~DeterministicMockClientSocketFactory() override;
1140 void AddSocketDataProvider(DeterministicSocketData* socket);
1141 void AddSSLSocketDataProvider(SSLSocketDataProvider* socket);
1142 void ResetNextMockIndexes();
1144 // Return |index|-th MockSSLClientSocket (starting from 0) that the factory
1145 // created.
1146 MockSSLClientSocket* GetMockSSLClientSocket(size_t index) const;
1148 SocketDataProviderArray<DeterministicSocketData>& mock_data() {
1149 return mock_data_;
1151 std::vector<DeterministicMockTCPClientSocket*>& tcp_client_sockets() {
1152 return tcp_client_sockets_;
1154 std::vector<DeterministicMockUDPClientSocket*>& udp_client_sockets() {
1155 return udp_client_sockets_;
1158 // ClientSocketFactory
1159 scoped_ptr<DatagramClientSocket> CreateDatagramClientSocket(
1160 DatagramSocket::BindType bind_type,
1161 const RandIntCallback& rand_int_cb,
1162 NetLog* net_log,
1163 const NetLog::Source& source) override;
1164 scoped_ptr<StreamSocket> CreateTransportClientSocket(
1165 const AddressList& addresses,
1166 NetLog* net_log,
1167 const NetLog::Source& source) override;
1168 scoped_ptr<SSLClientSocket> CreateSSLClientSocket(
1169 scoped_ptr<ClientSocketHandle> transport_socket,
1170 const HostPortPair& host_and_port,
1171 const SSLConfig& ssl_config,
1172 const SSLClientSocketContext& context) override;
1173 void ClearSSLSessionCache() override;
1175 private:
1176 SocketDataProviderArray<DeterministicSocketData> mock_data_;
1177 SocketDataProviderArray<SSLSocketDataProvider> mock_ssl_data_;
1179 // Store pointers to handed out sockets in case the test wants to get them.
1180 std::vector<DeterministicMockTCPClientSocket*> tcp_client_sockets_;
1181 std::vector<DeterministicMockUDPClientSocket*> udp_client_sockets_;
1182 std::vector<MockSSLClientSocket*> ssl_client_sockets_;
1184 DISALLOW_COPY_AND_ASSIGN(DeterministicMockClientSocketFactory);
1187 class MockSOCKSClientSocketPool : public SOCKSClientSocketPool {
1188 public:
1189 MockSOCKSClientSocketPool(int max_sockets,
1190 int max_sockets_per_group,
1191 TransportClientSocketPool* transport_pool);
1193 ~MockSOCKSClientSocketPool() override;
1195 // SOCKSClientSocketPool implementation.
1196 int RequestSocket(const std::string& group_name,
1197 const void* socket_params,
1198 RequestPriority priority,
1199 ClientSocketHandle* handle,
1200 const CompletionCallback& callback,
1201 const BoundNetLog& net_log) override;
1203 void CancelRequest(const std::string& group_name,
1204 ClientSocketHandle* handle) override;
1205 void ReleaseSocket(const std::string& group_name,
1206 scoped_ptr<StreamSocket> socket,
1207 int id) override;
1209 private:
1210 TransportClientSocketPool* const transport_pool_;
1212 DISALLOW_COPY_AND_ASSIGN(MockSOCKSClientSocketPool);
1215 // Convenience class to temporarily set the WebSocketEndpointLockManager unlock
1216 // delay to zero for testing purposes. Automatically restores the original value
1217 // when destroyed.
1218 class ScopedWebSocketEndpointZeroUnlockDelay {
1219 public:
1220 ScopedWebSocketEndpointZeroUnlockDelay();
1221 ~ScopedWebSocketEndpointZeroUnlockDelay();
1223 private:
1224 base::TimeDelta old_delay_;
1227 // Constants for a successful SOCKS v5 handshake.
1228 extern const char kSOCKS5GreetRequest[];
1229 extern const int kSOCKS5GreetRequestLength;
1231 extern const char kSOCKS5GreetResponse[];
1232 extern const int kSOCKS5GreetResponseLength;
1234 extern const char kSOCKS5OkRequest[];
1235 extern const int kSOCKS5OkRequestLength;
1237 extern const char kSOCKS5OkResponse[];
1238 extern const int kSOCKS5OkResponseLength;
1240 } // namespace net
1242 #endif // NET_SOCKET_SOCKET_TEST_UTIL_H_