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