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