1 // Copyright 2013 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 #include "net/websockets/websocket_channel.h"
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/callback.h"
16 #include "base/location.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/message_loop/message_loop.h"
21 #include "base/safe_numerics.h"
22 #include "base/strings/string_piece.h"
23 #include "net/base/net_errors.h"
24 #include "net/base/test_completion_callback.h"
25 #include "net/url_request/url_request_context.h"
26 #include "net/websockets/websocket_errors.h"
27 #include "net/websockets/websocket_event_interface.h"
28 #include "net/websockets/websocket_mux.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
33 // Hacky macros to construct the body of a Close message from a code and a
34 // string, while ensuring the result is a compile-time constant string.
35 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
36 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
37 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
38 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
39 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
40 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
44 // Printing helpers to allow GoogleMock to print frames. These are explicitly
45 // designed to look like the static initialisation format we use in these
46 // tests. They have to live in the net namespace in order to be found by
47 // GoogleMock; a nested anonymous namespace will not work.
49 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
50 return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
51 << header.opcode << ", "
52 << (header.masked ? "MASKED" : "NOT_MASKED");
55 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
56 os << "{" << frame.header << ", ";
58 return os << "\"" << base::StringPiece(frame.data->data(),
59 frame.header.payload_length)
65 std::ostream& operator<<(std::ostream& os,
66 const ScopedVector<WebSocketFrame>& vector) {
69 for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
82 std::ostream& operator<<(std::ostream& os,
83 const ScopedVector<WebSocketFrame>* vector) {
84 return os << '&' << *vector;
89 using ::base::TimeDelta;
91 using ::testing::AnyNumber;
92 using ::testing::DefaultValue;
93 using ::testing::InSequence;
94 using ::testing::MockFunction;
95 using ::testing::Return;
96 using ::testing::SaveArg;
97 using ::testing::StrictMock;
100 // A selection of characters that have traditionally been mangled in some
101 // environment or other, for testing 8-bit cleanliness.
102 const char kBinaryBlob[] = {'\n', '\r', // BACKWARDS CRNL
105 '\x80', '\xFF', // NOT VALID UTF-8
106 '\x1A', // Control-Z, EOF on DOS
108 '\x04', // EOT, special for Unix terms
109 '\x1B', // ESC, often special
111 '\'', // single-quote, special in PHP
113 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
115 // The amount of quota a new connection gets by default.
116 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
117 // need to be updated.
118 const size_t kDefaultInitialQuota = 1 << 17;
119 // The amount of bytes we need to send after the initial connection to trigger a
120 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
121 // kDefaultSendQuotaLowWaterMark change.
122 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
124 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
125 // in that time! I would like my tests to run a bit quicker.
126 const int kVeryTinyTimeoutMillis = 1;
128 typedef WebSocketEventInterface::ChannelState ChannelState;
129 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
130 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
132 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
133 // all over the place.
134 typedef MockFunction<void(int)> Checkpoint; // NOLINT
136 // This mock is for testing expectations about how the EventInterface is used.
137 class MockWebSocketEventInterface : public WebSocketEventInterface {
139 MOCK_METHOD2(OnAddChannelResponse,
140 ChannelState(bool, const std::string&)); // NOLINT
141 MOCK_METHOD3(OnDataFrame,
143 WebSocketMessageType,
144 const std::vector<char>&)); // NOLINT
145 MOCK_METHOD1(OnFlowControl, ChannelState(int64)); // NOLINT
146 MOCK_METHOD0(OnClosingHandshake, ChannelState(void)); // NOLINT
147 MOCK_METHOD2(OnDropChannel,
148 ChannelState(uint16, const std::string&)); // NOLINT
151 // This fake EventInterface is for tests which need a WebSocketEventInterface
152 // implementation but are not verifying how it is used.
153 class FakeWebSocketEventInterface : public WebSocketEventInterface {
154 virtual ChannelState OnAddChannelResponse(
156 const std::string& selected_protocol) OVERRIDE {
157 return fail ? CHANNEL_DELETED : CHANNEL_ALIVE;
159 virtual ChannelState OnDataFrame(bool fin,
160 WebSocketMessageType type,
161 const std::vector<char>& data) OVERRIDE {
162 return CHANNEL_ALIVE;
164 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
165 return CHANNEL_ALIVE;
167 virtual ChannelState OnClosingHandshake() OVERRIDE { return CHANNEL_ALIVE; }
168 virtual ChannelState OnDropChannel(uint16 code,
169 const std::string& reason) OVERRIDE {
170 return CHANNEL_DELETED;
174 // This fake WebSocketStream is for tests that require a WebSocketStream but are
175 // not testing the way it is used. It has minimal functionality to return
176 // the |protocol| and |extensions| that it was constructed with.
177 class FakeWebSocketStream : public WebSocketStream {
179 // Constructs with empty protocol and extensions.
180 FakeWebSocketStream() {}
182 // Constructs with specified protocol and extensions.
183 FakeWebSocketStream(const std::string& protocol,
184 const std::string& extensions)
185 : protocol_(protocol), extensions_(extensions) {}
187 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
188 const CompletionCallback& callback) OVERRIDE {
189 return ERR_IO_PENDING;
192 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
193 const CompletionCallback& callback) OVERRIDE {
194 return ERR_IO_PENDING;
197 virtual void Close() OVERRIDE {}
199 // Returns the string passed to the constructor.
200 virtual std::string GetSubProtocol() const OVERRIDE { return protocol_; }
202 // Returns the string passed to the constructor.
203 virtual std::string GetExtensions() const OVERRIDE { return extensions_; }
206 // The string to return from GetSubProtocol().
207 std::string protocol_;
209 // The string to return from GetExtensions().
210 std::string extensions_;
213 // To make the static initialisers easier to read, we use enums rather than
225 // This is used to initialise a WebSocketFrame but is statically initialisable.
228 // Reserved fields omitted for now. Add them if you need them.
229 WebSocketFrameHeader::OpCode opcode;
232 // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
233 // nul-terminated string for ease-of-use. |header.payload_length| is
234 // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
235 // is not an issue for test data.
236 const char* const data;
240 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
241 os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
242 << ", " << frame.opcode << ", "
243 << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
245 return os << "\"" << frame.data << "\"}";
247 return os << "NULL}";
251 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
254 for (size_t i = 0; i < N; ++i) {
265 // Convert a const array of InitFrame structs to the format used at
266 // runtime. Templated on the size of the array to save typing.
268 ScopedVector<WebSocketFrame> CreateFrameVector(
269 const InitFrame (&source_frames)[N]) {
270 ScopedVector<WebSocketFrame> result_frames;
271 result_frames.reserve(N);
272 for (size_t i = 0; i < N; ++i) {
273 const InitFrame& source_frame = source_frames[i];
274 scoped_ptr<WebSocketFrame> result_frame(
275 new WebSocketFrame(source_frame.opcode));
276 size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
277 WebSocketFrameHeader& result_header = result_frame->header;
278 result_header.final = (source_frame.final == FINAL_FRAME);
279 result_header.masked = (source_frame.masked == MASKED);
280 result_header.payload_length = frame_length;
281 if (source_frame.data) {
282 result_frame->data = new IOBuffer(frame_length);
283 memcpy(result_frame->data->data(), source_frame.data, frame_length);
285 result_frames.push_back(result_frame.release());
287 return result_frames.Pass();
290 // A GoogleMock action which can be used to respond to call to ReadFrames with
291 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
292 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
293 // because otherwise it will be treated as a pointer and the array size
294 // information will be lost.
295 ACTION_P(ReturnFrames, source_frames) {
296 *arg0 = CreateFrameVector(*source_frames);
300 // The implementation of a GoogleMock matcher which can be used to compare a
301 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
302 // InitFrame objects. Although it is possible to compose built-in GoogleMock
303 // matchers to check the contents of a WebSocketFrame, the results are so
304 // unreadable that it is better to use this matcher.
306 class EqualsFramesMatcher
307 : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
309 EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
310 : expect_frames_(expect_frames) {}
312 virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
313 ::testing::MatchResultListener* listener) const {
314 if (actual_frames->size() != N) {
315 *listener << "the vector size is " << actual_frames->size();
318 for (size_t i = 0; i < N; ++i) {
319 const WebSocketFrame& actual_frame = *(*actual_frames)[i];
320 const InitFrame& expected_frame = (*expect_frames_)[i];
321 if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
322 *listener << "the frame is marked as "
323 << (actual_frame.header.final ? "" : "not ") << "final";
326 if (actual_frame.header.opcode != expected_frame.opcode) {
327 *listener << "the opcode is " << actual_frame.header.opcode;
330 if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
331 *listener << "the frame is "
332 << (actual_frame.header.masked ? "masked" : "not masked");
335 const size_t expected_length =
336 expected_frame.data ? strlen(expected_frame.data) : 0;
337 if (actual_frame.header.payload_length != expected_length) {
338 *listener << "the payload length is "
339 << actual_frame.header.payload_length;
342 if (expected_length != 0 &&
343 memcmp(actual_frame.data->data(),
345 actual_frame.header.payload_length) != 0) {
346 *listener << "the data content differs";
353 virtual void DescribeTo(std::ostream* os) const {
354 *os << "matches " << *expect_frames_;
357 virtual void DescribeNegationTo(std::ostream* os) const {
358 *os << "does not match " << *expect_frames_;
362 const InitFrame (*expect_frames_)[N];
365 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
366 // action, this can take the array by reference.
368 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
369 const InitFrame (&frames)[N]) {
370 return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
373 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
376 base::Closure closure() { return base::Bind(callback_.callback(), OK); }
378 void WaitForResult() { callback_.WaitForResult(); }
381 // Delegate to TestCompletionCallback for the implementation.
382 TestCompletionCallback callback_;
385 // A GoogleMock action to run a Closure.
386 ACTION_P(InvokeClosure, closure) { closure.Run(); }
388 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
389 ACTION_P(InvokeClosureReturnDeleted, closure) {
391 return WebSocketEventInterface::CHANNEL_DELETED;
394 // A FakeWebSocketStream whose ReadFrames() function returns data.
395 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
402 // After constructing the object, call PrepareReadFrames() once for each
403 // time you wish it to return from the test.
404 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
406 // Check that all the prepared responses have been consumed.
407 virtual ~ReadableFakeWebSocketStream() {
408 CHECK(index_ >= responses_.size());
409 CHECK(!read_frames_pending_);
412 // Prepares a fake response. Fake responses will be returned from ReadFrames()
413 // in the same order they were prepared with PrepareReadFrames() and
414 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
415 // return ERR_IO_PENDING and the callback will be scheduled to run on the
416 // message loop. This requires the test case to run the message loop. If
417 // |async| is SYNC, the response will be returned synchronously. |error| is
418 // returned directly from ReadFrames() in the synchronous case, or passed to
419 // the callback in the asynchronous case. |frames| will be converted to a
420 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
423 void PrepareReadFrames(IsSync async,
425 const InitFrame (&frames)[N]) {
426 responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
429 // An alternate version of PrepareReadFrames for when we need to construct
430 // the frames manually.
431 void PrepareRawReadFrames(IsSync async,
433 ScopedVector<WebSocketFrame> frames) {
434 responses_.push_back(new Response(async, error, frames.Pass()));
437 // Prepares a fake error response (ie. there is no data).
438 void PrepareReadFramesError(IsSync async, int error) {
439 responses_.push_back(
440 new Response(async, error, ScopedVector<WebSocketFrame>()));
443 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
444 const CompletionCallback& callback) OVERRIDE {
445 CHECK(!read_frames_pending_);
446 if (index_ >= responses_.size())
447 return ERR_IO_PENDING;
448 if (responses_[index_]->async == ASYNC) {
449 read_frames_pending_ = true;
450 base::MessageLoop::current()->PostTask(
452 base::Bind(&ReadableFakeWebSocketStream::DoCallback,
453 base::Unretained(this),
456 return ERR_IO_PENDING;
458 frames->swap(responses_[index_]->frames);
459 return responses_[index_++]->error;
464 void DoCallback(ScopedVector<WebSocketFrame>* frames,
465 const CompletionCallback& callback) {
466 read_frames_pending_ = false;
467 frames->swap(responses_[index_]->frames);
468 callback.Run(responses_[index_++]->error);
473 Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
474 : async(async), error(error), frames(frames.Pass()) {}
478 ScopedVector<WebSocketFrame> frames;
481 // Bad things will happen if we attempt to copy or assign |frames|.
482 DISALLOW_COPY_AND_ASSIGN(Response);
484 ScopedVector<Response> responses_;
486 // The index into the responses_ array of the next response to be returned.
489 // True when an async response from ReadFrames() is pending. This only applies
490 // to "real" async responses. Once all the prepared responses have been
491 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
493 bool read_frames_pending_;
496 // A FakeWebSocketStream where writes always complete successfully and
498 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
500 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
501 const CompletionCallback& callback) OVERRIDE {
506 // A FakeWebSocketStream where writes always fail.
507 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
509 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
510 const CompletionCallback& callback) OVERRIDE {
511 return ERR_CONNECTION_RESET;
515 // A FakeWebSocketStream which echoes any frames written back. Clears the
516 // "masked" header bit, but makes no other checks for validity. Tests using this
517 // must run the MessageLoop to receive the callback(s). If a message with opcode
518 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
519 // callback. The test must do something to cause WriteFrames() to be called,
520 // otherwise the ReadFrames() callback will never be called.
521 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
523 EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
525 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
526 const CompletionCallback& callback) OVERRIDE {
527 // Users of WebSocketStream will not expect the ReadFrames() callback to be
528 // called from within WriteFrames(), so post it to the message loop instead.
529 stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
530 frames->weak_clear();
535 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
536 const CompletionCallback& callback) OVERRIDE {
537 read_callback_ = callback;
538 read_frames_ = frames;
541 return ERR_IO_PENDING;
545 void PostCallback() {
546 base::MessageLoop::current()->PostTask(
548 base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
549 base::Unretained(this)));
554 read_callback_.Run(ERR_CONNECTION_CLOSED);
555 } else if (!stored_frames_.empty()) {
556 done_ = MoveFrames(read_frames_);
558 read_callback_.Run(OK);
562 // Copy the frames stored in stored_frames_ to |out|, while clearing the
563 // "masked" header bit. Returns true if a Close Frame was seen, false
565 bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
566 bool seen_close = false;
567 *out = stored_frames_.Pass();
568 for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
571 WebSocketFrameHeader& header = (*it)->header;
572 header.masked = false;
573 if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
579 ScopedVector<WebSocketFrame> stored_frames_;
580 CompletionCallback read_callback_;
581 // Owned by the caller of ReadFrames().
582 ScopedVector<WebSocketFrame>* read_frames_;
583 // True if we should close the connection.
587 // A FakeWebSocketStream where writes trigger a connection reset.
588 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
589 // and triggers ReadFrames to return a reset as well. Tests using this need to
590 // run the message loop. There are two tricky parts here:
591 // 1. Calling the write callback may call Close(), after which the read callback
592 // should not be called.
593 // 2. Calling either callback may delete the stream altogether.
594 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
596 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
598 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
599 const CompletionCallback& callback) OVERRIDE {
600 base::MessageLoop::current()->PostTask(
602 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
603 weak_ptr_factory_.GetWeakPtr(),
605 ERR_CONNECTION_RESET));
606 base::MessageLoop::current()->PostTask(
608 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
609 weak_ptr_factory_.GetWeakPtr(),
611 ERR_CONNECTION_RESET));
612 return ERR_IO_PENDING;
615 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
616 const CompletionCallback& callback) OVERRIDE {
617 read_callback_ = callback;
618 return ERR_IO_PENDING;
621 virtual void Close() OVERRIDE { closed_ = true; }
624 void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
629 CompletionCallback read_callback_;
631 // An IO error can result in the socket being deleted, so we use weak pointers
632 // to ensure correct behaviour in that case.
633 base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
636 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
637 // the extent that they are implemented in WebSocketCommon).
638 class MockWebSocketStream : public WebSocketStream {
640 MOCK_METHOD2(ReadFrames,
641 int(ScopedVector<WebSocketFrame>* frames,
642 const CompletionCallback& callback));
643 MOCK_METHOD2(WriteFrames,
644 int(ScopedVector<WebSocketFrame>* frames,
645 const CompletionCallback& callback));
646 MOCK_METHOD0(Close, void());
647 MOCK_CONST_METHOD0(GetSubProtocol, std::string());
648 MOCK_CONST_METHOD0(GetExtensions, std::string());
649 MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
652 struct ArgumentCopyingWebSocketStreamFactory {
653 scoped_ptr<WebSocketStreamRequest> Factory(
654 const GURL& socket_url,
655 const std::vector<std::string>& requested_subprotocols,
657 URLRequestContext* url_request_context,
658 const BoundNetLog& net_log,
659 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
660 this->socket_url = socket_url;
661 this->requested_subprotocols = requested_subprotocols;
662 this->origin = origin;
663 this->url_request_context = url_request_context;
664 this->net_log = net_log;
665 this->connect_delegate = connect_delegate.Pass();
666 return make_scoped_ptr(new WebSocketStreamRequest);
671 std::vector<std::string> requested_subprotocols;
672 URLRequestContext* url_request_context;
674 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
677 // Converts a std::string to a std::vector<char>. For test purposes, it is
678 // convenient to be able to specify data as a string, but the
679 // WebSocketEventInterface requires the vector<char> type.
680 std::vector<char> AsVector(const std::string& s) {
681 return std::vector<char>(s.begin(), s.end());
684 // Base class for all test fixtures.
685 class WebSocketChannelTest : public ::testing::Test {
687 WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
689 // Creates a new WebSocketChannel and connects it, using the settings stored
690 // in |connect_data_|.
691 void CreateChannelAndConnect() {
692 channel_.reset(new WebSocketChannel(CreateEventInterface(),
693 &connect_data_.url_request_context));
694 channel_->SendAddChannelRequestForTesting(
695 connect_data_.socket_url,
696 connect_data_.requested_subprotocols,
697 connect_data_.origin,
698 base::Bind(&ArgumentCopyingWebSocketStreamFactory::Factory,
699 base::Unretained(&connect_data_.factory)));
702 // Same as CreateChannelAndConnect(), but calls the on_success callback as
703 // well. This method is virtual so that subclasses can also set the stream.
704 virtual void CreateChannelAndConnectSuccessfully() {
705 CreateChannelAndConnect();
706 connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
709 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
710 // This implementation returns a newly-created fake. Subclasses may return a
712 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
713 return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
716 // This method serves no other purpose than to provide a nice syntax for
717 // assigning to stream_. class T must be a subclass of WebSocketStream or you
718 // will have unpleasant compile errors.
720 void set_stream(scoped_ptr<T> stream) {
721 // Since the definition of "PassAs" depends on the type T, the C++ standard
722 // requires the "template" keyword to indicate that "PassAs" should be
723 // parsed as a template method.
724 stream_ = stream.template PassAs<WebSocketStream>();
727 // A struct containing the data that will be used to connect the channel.
728 // Grouped for readability.
730 // URLRequestContext object.
731 URLRequestContext url_request_context;
733 // URL to (pretend to) connect to.
735 // Requested protocols for the request.
736 std::vector<std::string> requested_subprotocols;
737 // Origin of the request
740 // A fake WebSocketStreamFactory that just records its arguments.
741 ArgumentCopyingWebSocketStreamFactory factory;
743 ConnectData connect_data_;
745 // The channel we are testing. Not initialised until SetChannel() is called.
746 scoped_ptr<WebSocketChannel> channel_;
748 // A mock or fake stream for tests that need one.
749 scoped_ptr<WebSocketStream> stream_;
752 // enum of WebSocketEventInterface calls. These are intended to be or'd together
753 // in order to instruct WebSocketChannelDeletingTest when it should fail.
754 enum EventInterfaceCall {
755 EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
756 EVENT_ON_DATA_FRAME = 0x2,
757 EVENT_ON_FLOW_CONTROL = 0x4,
758 EVENT_ON_CLOSING_HANDSHAKE = 0x8,
759 EVENT_ON_DROP_CHANNEL = 0x10,
762 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
764 ChannelState DeleteIfDeleting(EventInterfaceCall call) {
765 if (deleting_ & call) {
767 return CHANNEL_DELETED;
769 return CHANNEL_ALIVE;
774 WebSocketChannelDeletingTest()
775 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
776 EVENT_ON_FLOW_CONTROL |
777 EVENT_ON_CLOSING_HANDSHAKE |
778 EVENT_ON_DROP_CHANNEL) {}
779 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
780 // avoid circular dependency.
781 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE;
783 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
784 // want to cause Channel deletion. The default is for all calls to cause
789 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
791 class ChannelDeletingFakeWebSocketEventInterface
792 : public FakeWebSocketEventInterface {
794 ChannelDeletingFakeWebSocketEventInterface(
795 WebSocketChannelDeletingTest* fixture)
796 : fixture_(fixture) {}
798 virtual ChannelState OnAddChannelResponse(
800 const std::string& selected_protocol) OVERRIDE {
801 return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
804 virtual ChannelState OnDataFrame(bool fin,
805 WebSocketMessageType type,
806 const std::vector<char>& data) OVERRIDE {
807 return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
810 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
811 return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
814 virtual ChannelState OnClosingHandshake() OVERRIDE {
815 return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
818 virtual ChannelState OnDropChannel(uint16 code,
819 const std::string& reason) OVERRIDE {
820 return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
824 // A pointer to the test fixture. Owned by the test harness; this object will
825 // be deleted before it is.
826 WebSocketChannelDeletingTest* fixture_;
829 scoped_ptr<WebSocketEventInterface>
830 WebSocketChannelDeletingTest::CreateEventInterface() {
831 return scoped_ptr<WebSocketEventInterface>(
832 new ChannelDeletingFakeWebSocketEventInterface(this));
835 // Base class for tests which verify that EventInterface methods are called
837 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
839 WebSocketChannelEventInterfaceTest()
840 : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
841 DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
842 ON_CALL(*event_interface_, OnAddChannelResponse(true, _))
843 .WillByDefault(Return(CHANNEL_DELETED));
844 ON_CALL(*event_interface_, OnDropChannel(_, _))
845 .WillByDefault(Return(CHANNEL_DELETED));
848 virtual ~WebSocketChannelEventInterfaceTest() {
849 DefaultValue<ChannelState>::Clear();
852 // Tests using this fixture must set expectations on the event_interface_ mock
853 // object before calling CreateChannelAndConnect() or
854 // CreateChannelAndConnectSuccessfully(). This will only work once per test
855 // case, but once should be enough.
856 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE {
857 return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
860 scoped_ptr<MockWebSocketEventInterface> event_interface_;
863 // Base class for tests which verify that WebSocketStream methods are called
864 // appropriately by using a MockWebSocketStream.
865 class WebSocketChannelStreamTest : public WebSocketChannelTest {
867 WebSocketChannelStreamTest()
868 : mock_stream_(new StrictMock<MockWebSocketStream>) {}
870 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
871 set_stream(mock_stream_.Pass());
872 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
875 scoped_ptr<MockWebSocketStream> mock_stream_;
878 // Simple test that everything that should be passed to the factory function is
879 // passed to the factory function.
880 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheFactoryFunction) {
881 connect_data_.socket_url = GURL("ws://example.com/test");
882 connect_data_.origin = GURL("http://example.com/test");
883 connect_data_.requested_subprotocols.push_back("Sinbad");
885 CreateChannelAndConnect();
887 const ArgumentCopyingWebSocketStreamFactory& actual = connect_data_.factory;
889 EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
891 EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
892 EXPECT_EQ(connect_data_.requested_subprotocols,
893 actual.requested_subprotocols);
894 EXPECT_EQ(connect_data_.origin, actual.origin);
897 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
898 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
899 // verify that there are no use-after-free bugs when this happens. Problems will
900 // probably only be found when running under Address Sanitizer or a similar
902 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
903 CreateChannelAndConnect();
904 EXPECT_TRUE(channel_);
905 connect_data_.factory.connect_delegate->OnFailure(
906 kWebSocketErrorNoStatusReceived);
907 EXPECT_EQ(NULL, channel_.get());
910 // Deletion is possible (due to IPC failure) even if the connect succeeds.
911 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
912 CreateChannelAndConnectSuccessfully();
913 EXPECT_EQ(NULL, channel_.get());
916 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
917 scoped_ptr<ReadableFakeWebSocketStream> stream(
918 new ReadableFakeWebSocketStream);
919 static const InitFrame frames[] = {
920 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
921 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
922 set_stream(stream.Pass());
923 deleting_ = EVENT_ON_DATA_FRAME;
925 CreateChannelAndConnectSuccessfully();
926 EXPECT_EQ(NULL, channel_.get());
929 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
930 scoped_ptr<ReadableFakeWebSocketStream> stream(
931 new ReadableFakeWebSocketStream);
932 static const InitFrame frames[] = {
933 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
934 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
935 set_stream(stream.Pass());
936 deleting_ = EVENT_ON_DATA_FRAME;
938 CreateChannelAndConnectSuccessfully();
939 EXPECT_TRUE(channel_);
940 base::MessageLoop::current()->RunUntilIdle();
941 EXPECT_EQ(NULL, channel_.get());
944 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
945 deleting_ = EVENT_ON_FLOW_CONTROL;
947 CreateChannelAndConnectSuccessfully();
948 EXPECT_EQ(NULL, channel_.get());
951 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
952 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
953 // Avoid deleting the channel yet.
954 deleting_ = EVENT_ON_DROP_CHANNEL;
955 CreateChannelAndConnectSuccessfully();
956 ASSERT_TRUE(channel_);
957 deleting_ = EVENT_ON_FLOW_CONTROL;
958 channel_->SendFrame(true,
959 WebSocketFrameHeader::kOpCodeText,
960 std::vector<char>(kDefaultInitialQuota, 'B'));
961 EXPECT_EQ(NULL, channel_.get());
964 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
965 scoped_ptr<ReadableFakeWebSocketStream> stream(
966 new ReadableFakeWebSocketStream);
967 static const InitFrame frames[] = {
968 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
969 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
970 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
971 set_stream(stream.Pass());
972 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
973 CreateChannelAndConnectSuccessfully();
974 EXPECT_EQ(NULL, channel_.get());
977 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
978 scoped_ptr<ReadableFakeWebSocketStream> stream(
979 new ReadableFakeWebSocketStream);
980 static const InitFrame frames[] = {
981 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
982 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
983 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
984 set_stream(stream.Pass());
985 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
986 CreateChannelAndConnectSuccessfully();
987 ASSERT_TRUE(channel_);
988 base::MessageLoop::current()->RunUntilIdle();
989 EXPECT_EQ(NULL, channel_.get());
992 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
993 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
994 deleting_ = EVENT_ON_DROP_CHANNEL;
995 CreateChannelAndConnectSuccessfully();
996 ASSERT_TRUE(channel_);
998 true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
999 EXPECT_EQ(NULL, channel_.get());
1002 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1003 scoped_ptr<ReadableFakeWebSocketStream> stream(
1004 new ReadableFakeWebSocketStream);
1005 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1007 set_stream(stream.Pass());
1008 deleting_ = EVENT_ON_DROP_CHANNEL;
1009 CreateChannelAndConnectSuccessfully();
1010 ASSERT_TRUE(channel_);
1011 base::MessageLoop::current()->RunUntilIdle();
1012 EXPECT_EQ(NULL, channel_.get());
1015 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1016 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1017 deleting_ = EVENT_ON_DROP_CHANNEL;
1018 CreateChannelAndConnectSuccessfully();
1019 ASSERT_TRUE(channel_);
1020 channel_->SendFrame(true,
1021 WebSocketFrameHeader::kOpCodeText,
1022 std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1023 EXPECT_EQ(NULL, channel_.get());
1026 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1027 scoped_ptr<ReadableFakeWebSocketStream> stream(
1028 new ReadableFakeWebSocketStream);
1029 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1030 ERR_WS_PROTOCOL_ERROR);
1031 set_stream(stream.Pass());
1032 deleting_ = EVENT_ON_DROP_CHANNEL;
1033 CreateChannelAndConnectSuccessfully();
1034 ASSERT_TRUE(channel_);
1035 base::MessageLoop::current()->RunUntilIdle();
1036 EXPECT_EQ(NULL, channel_.get());
1039 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1040 scoped_ptr<ReadableFakeWebSocketStream> stream(
1041 new ReadableFakeWebSocketStream);
1042 static const InitFrame frames[] = {
1043 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1044 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1045 set_stream(stream.Pass());
1046 deleting_ = EVENT_ON_DROP_CHANNEL;
1048 CreateChannelAndConnectSuccessfully();
1049 EXPECT_EQ(NULL, channel_.get());
1052 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1053 scoped_ptr<ReadableFakeWebSocketStream> stream(
1054 new ReadableFakeWebSocketStream);
1055 static const InitFrame frames[] = {
1056 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1057 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1058 set_stream(stream.Pass());
1059 deleting_ = EVENT_ON_DROP_CHANNEL;
1061 CreateChannelAndConnectSuccessfully();
1062 EXPECT_EQ(NULL, channel_.get());
1065 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1066 scoped_ptr<ReadableFakeWebSocketStream> stream(
1067 new ReadableFakeWebSocketStream);
1068 static const InitFrame frames[] = {
1069 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1070 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1071 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1072 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1073 set_stream(stream.Pass());
1074 deleting_ = EVENT_ON_DROP_CHANNEL;
1076 CreateChannelAndConnectSuccessfully();
1077 EXPECT_EQ(NULL, channel_.get());
1080 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1081 scoped_ptr<ReadableFakeWebSocketStream> stream(
1082 new ReadableFakeWebSocketStream);
1083 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1084 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1085 set_stream(stream.Pass());
1086 deleting_ = EVENT_ON_DROP_CHANNEL;
1088 CreateChannelAndConnectSuccessfully();
1089 EXPECT_EQ(NULL, channel_.get());
1092 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1093 // false means success.
1094 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, ""));
1095 // OnFlowControl is always called immediately after connect to provide initial
1096 // quota to the renderer.
1097 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1099 CreateChannelAndConnect();
1101 connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
1104 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1105 // true means failure.
1106 EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, ""));
1108 CreateChannelAndConnect();
1110 connect_data_.factory.connect_delegate->OnFailure(
1111 kWebSocketErrorNoStatusReceived);
1114 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1115 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob"));
1116 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1118 CreateChannelAndConnect();
1120 connect_data_.factory.connect_delegate->OnSuccess(
1121 scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1124 // The first frames from the server can arrive together with the handshake, in
1125 // which case they will be available as soon as ReadFrames() is called the first
1127 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1128 scoped_ptr<ReadableFakeWebSocketStream> stream(
1129 new ReadableFakeWebSocketStream);
1130 static const InitFrame frames[] = {
1131 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1132 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1133 set_stream(stream.Pass());
1136 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1137 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1141 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1144 CreateChannelAndConnectSuccessfully();
1147 // A remote server could accept the handshake, but then immediately send a
1149 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1150 scoped_ptr<ReadableFakeWebSocketStream> stream(
1151 new ReadableFakeWebSocketStream);
1152 static const InitFrame frames[] = {
1153 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1154 NOT_MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1155 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1156 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1157 ERR_CONNECTION_CLOSED);
1158 set_stream(stream.Pass());
1161 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1162 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1163 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1164 EXPECT_CALL(*event_interface_,
1165 OnDropChannel(kWebSocketErrorInternalServerError,
1166 "Internal Server Error"));
1169 CreateChannelAndConnectSuccessfully();
1172 // A remote server could close the connection immediately after sending the
1173 // handshake response (most likely a bug in the server).
1174 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1175 scoped_ptr<ReadableFakeWebSocketStream> stream(
1176 new ReadableFakeWebSocketStream);
1177 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1178 ERR_CONNECTION_CLOSED);
1179 set_stream(stream.Pass());
1182 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1183 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1184 EXPECT_CALL(*event_interface_,
1185 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1188 CreateChannelAndConnectSuccessfully();
1191 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1192 scoped_ptr<ReadableFakeWebSocketStream> stream(
1193 new ReadableFakeWebSocketStream);
1194 static const InitFrame frames[] = {
1195 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1196 // We use this checkpoint object to verify that the callback isn't called
1197 // until we expect it to be.
1198 Checkpoint checkpoint;
1199 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1200 set_stream(stream.Pass());
1203 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1204 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1205 EXPECT_CALL(checkpoint, Call(1));
1209 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1210 EXPECT_CALL(checkpoint, Call(2));
1213 CreateChannelAndConnectSuccessfully();
1215 base::MessageLoop::current()->RunUntilIdle();
1219 // Extra data can arrive while a read is being processed, resulting in the next
1220 // read completing synchronously.
1221 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1222 scoped_ptr<ReadableFakeWebSocketStream> stream(
1223 new ReadableFakeWebSocketStream);
1224 static const InitFrame frames1[] = {
1225 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1226 static const InitFrame frames2[] = {
1227 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1228 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1229 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1230 set_stream(stream.Pass());
1233 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1234 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1238 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1242 true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1245 CreateChannelAndConnectSuccessfully();
1246 base::MessageLoop::current()->RunUntilIdle();
1249 // Data frames are delivered the same regardless of how many reads they arrive
1251 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1252 scoped_ptr<ReadableFakeWebSocketStream> stream(
1253 new ReadableFakeWebSocketStream);
1254 // Here we have one message which arrived in five frames split across three
1255 // reads. It may have been reframed on arrival, but this class doesn't care
1257 static const InitFrame frames1[] = {
1258 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1259 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1261 static const InitFrame frames2[] = {
1262 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1263 NOT_MASKED, "SMALL"}};
1264 static const InitFrame frames3[] = {
1265 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1267 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1268 NOT_MASKED, "FRAMES"}};
1269 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1270 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1271 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1272 set_stream(stream.Pass());
1275 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1276 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1280 false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1284 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1285 EXPECT_CALL(*event_interface_,
1287 WebSocketFrameHeader::kOpCodeContinuation,
1288 AsVector("SMALL")));
1292 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1293 EXPECT_CALL(*event_interface_,
1295 WebSocketFrameHeader::kOpCodeContinuation,
1296 AsVector("FRAMES")));
1299 CreateChannelAndConnectSuccessfully();
1300 base::MessageLoop::current()->RunUntilIdle();
1303 // A control frame is not permitted to be split into multiple frames. RFC6455
1304 // 5.5 "All control frames ... MUST NOT be fragmented."
1305 TEST_F(WebSocketChannelEventInterfaceTest, MultiFrameControlMessageIsRejected) {
1306 scoped_ptr<ReadableFakeWebSocketStream> stream(
1307 new ReadableFakeWebSocketStream);
1308 static const InitFrame frames[] = {
1309 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, "Pi"},
1310 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1312 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1313 set_stream(stream.Pass());
1316 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1317 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1318 EXPECT_CALL(*event_interface_,
1319 OnDropChannel(kWebSocketErrorProtocolError, _));
1322 CreateChannelAndConnectSuccessfully();
1323 base::MessageLoop::current()->RunUntilIdle();
1326 // Connection closed by the remote host without a closing handshake.
1327 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1328 scoped_ptr<ReadableFakeWebSocketStream> stream(
1329 new ReadableFakeWebSocketStream);
1330 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1331 ERR_CONNECTION_CLOSED);
1332 set_stream(stream.Pass());
1335 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1336 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1337 EXPECT_CALL(*event_interface_,
1338 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1341 CreateChannelAndConnectSuccessfully();
1342 base::MessageLoop::current()->RunUntilIdle();
1345 // A connection reset should produce the same event as an unexpected closure.
1346 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1347 scoped_ptr<ReadableFakeWebSocketStream> stream(
1348 new ReadableFakeWebSocketStream);
1349 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1350 ERR_CONNECTION_RESET);
1351 set_stream(stream.Pass());
1354 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1355 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1356 EXPECT_CALL(*event_interface_,
1357 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1360 CreateChannelAndConnectSuccessfully();
1361 base::MessageLoop::current()->RunUntilIdle();
1364 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1365 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1366 scoped_ptr<ReadableFakeWebSocketStream> stream(
1367 new ReadableFakeWebSocketStream);
1368 static const InitFrame frames[] = {
1369 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1371 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1372 set_stream(stream.Pass());
1375 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1376 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1377 EXPECT_CALL(*event_interface_,
1378 OnDropChannel(kWebSocketErrorProtocolError, _));
1381 CreateChannelAndConnectSuccessfully();
1382 base::MessageLoop::current()->RunUntilIdle();
1385 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1386 // _Fail the WebSocket Connection_."
1387 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1388 scoped_ptr<ReadableFakeWebSocketStream> stream(
1389 new ReadableFakeWebSocketStream);
1390 static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1392 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1393 set_stream(stream.Pass());
1396 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1397 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1398 EXPECT_CALL(*event_interface_,
1399 OnDropChannel(kWebSocketErrorProtocolError, _));
1402 CreateChannelAndConnectSuccessfully();
1403 base::MessageLoop::current()->RunUntilIdle();
1406 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1407 // fragmented message."
1408 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1409 scoped_ptr<ReadableFakeWebSocketStream> stream(
1410 new ReadableFakeWebSocketStream);
1411 // We have one message of type Text split into two frames. In the middle is a
1412 // control message of type Pong.
1413 static const InitFrame frames1[] = {
1414 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1415 NOT_MASKED, "SPLIT "}};
1416 static const InitFrame frames2[] = {
1417 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1418 static const InitFrame frames3[] = {
1419 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1420 NOT_MASKED, "MESSAGE"}};
1421 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1422 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1423 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1424 set_stream(stream.Pass());
1427 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1428 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1432 false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1433 EXPECT_CALL(*event_interface_,
1435 WebSocketFrameHeader::kOpCodeContinuation,
1436 AsVector("MESSAGE")));
1439 CreateChannelAndConnectSuccessfully();
1440 base::MessageLoop::current()->RunUntilIdle();
1443 // If a frame has an invalid header, then the connection is closed and
1444 // subsequent frames must not trigger events.
1445 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1446 scoped_ptr<ReadableFakeWebSocketStream> stream(
1447 new ReadableFakeWebSocketStream);
1448 static const InitFrame frames[] = {
1449 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1450 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1452 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1453 set_stream(stream.Pass());
1456 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1457 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1458 EXPECT_CALL(*event_interface_,
1459 OnDropChannel(kWebSocketErrorProtocolError, _));
1462 CreateChannelAndConnectSuccessfully();
1463 base::MessageLoop::current()->RunUntilIdle();
1466 // If the renderer sends lots of small writes, we don't want to update the quota
1468 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1469 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1472 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1473 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1476 CreateChannelAndConnectSuccessfully();
1477 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1480 // If we send enough to go below send_quota_low_water_mask_ we should get our
1482 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1483 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1484 // We use this checkpoint object to verify that the quota update comes after
1486 Checkpoint checkpoint;
1489 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1490 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1491 EXPECT_CALL(checkpoint, Call(1));
1492 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1493 EXPECT_CALL(checkpoint, Call(2));
1496 CreateChannelAndConnectSuccessfully();
1498 channel_->SendFrame(true,
1499 WebSocketFrameHeader::kOpCodeText,
1500 std::vector<char>(kDefaultInitialQuota, 'B'));
1504 // Verify that our quota actually is refreshed when we are told it is.
1505 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1506 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1507 Checkpoint checkpoint;
1510 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1511 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1512 EXPECT_CALL(checkpoint, Call(1));
1513 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1514 EXPECT_CALL(checkpoint, Call(2));
1515 // If quota was not really refreshed, we would get an OnDropChannel()
1517 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1518 EXPECT_CALL(checkpoint, Call(3));
1521 CreateChannelAndConnectSuccessfully();
1523 channel_->SendFrame(true,
1524 WebSocketFrameHeader::kOpCodeText,
1525 std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1527 // We should have received more quota at this point.
1528 channel_->SendFrame(true,
1529 WebSocketFrameHeader::kOpCodeText,
1530 std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1534 // If we send more than the available quota then the connection will be closed
1536 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1537 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1540 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1541 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1542 EXPECT_CALL(*event_interface_,
1543 OnDropChannel(kWebSocketMuxErrorSendQuotaViolation, _));
1546 CreateChannelAndConnectSuccessfully();
1547 channel_->SendFrame(true,
1548 WebSocketFrameHeader::kOpCodeText,
1549 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1552 // If a write fails, the channel is dropped.
1553 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1554 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1555 Checkpoint checkpoint;
1558 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1559 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1560 EXPECT_CALL(checkpoint, Call(1));
1561 EXPECT_CALL(*event_interface_,
1562 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1563 EXPECT_CALL(checkpoint, Call(2));
1566 CreateChannelAndConnectSuccessfully();
1569 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1573 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1574 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1575 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1578 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1579 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1580 EXPECT_CALL(*event_interface_,
1581 OnDropChannel(kWebSocketNormalClosure, "Fred"));
1584 CreateChannelAndConnectSuccessfully();
1586 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1587 base::MessageLoop::current()->RunUntilIdle();
1590 // OnDropChannel() is only called once when a write() on the socket triggers a
1591 // connection reset.
1592 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1593 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1594 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1595 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1597 EXPECT_CALL(*event_interface_,
1598 OnDropChannel(kWebSocketErrorAbnormalClosure, "Abnormal Closure"))
1601 CreateChannelAndConnectSuccessfully();
1603 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1604 base::MessageLoop::current()->RunUntilIdle();
1607 // When the remote server sends a Close frame with an empty payload,
1608 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1609 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1610 scoped_ptr<ReadableFakeWebSocketStream> stream(
1611 new ReadableFakeWebSocketStream);
1612 static const InitFrame frames[] = {
1613 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1614 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1615 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1616 ERR_CONNECTION_CLOSED);
1617 set_stream(stream.Pass());
1618 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1619 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1620 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1621 EXPECT_CALL(*event_interface_,
1622 OnDropChannel(kWebSocketErrorNoStatusReceived, _));
1624 CreateChannelAndConnectSuccessfully();
1627 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then
1628 // kWebSocketErrorProtocolError must be sent to the renderer.
1629 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1630 scoped_ptr<ReadableFakeWebSocketStream> stream(
1631 new ReadableFakeWebSocketStream);
1632 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1633 ERR_WS_PROTOCOL_ERROR);
1634 set_stream(stream.Pass());
1635 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1636 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1638 EXPECT_CALL(*event_interface_,
1639 OnDropChannel(kWebSocketErrorProtocolError, _));
1641 CreateChannelAndConnectSuccessfully();
1644 // Async version of above test.
1645 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1646 scoped_ptr<ReadableFakeWebSocketStream> stream(
1647 new ReadableFakeWebSocketStream);
1648 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1649 ERR_WS_PROTOCOL_ERROR);
1650 set_stream(stream.Pass());
1651 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1652 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1654 EXPECT_CALL(*event_interface_,
1655 OnDropChannel(kWebSocketErrorProtocolError, _));
1657 CreateChannelAndConnectSuccessfully();
1658 base::MessageLoop::current()->RunUntilIdle();
1661 // The closing handshake times out and sends an OnDropChannel event if no
1662 // response to the client Close message is received.
1663 TEST_F(WebSocketChannelEventInterfaceTest,
1664 ClientInitiatedClosingHandshakeTimesOut) {
1665 scoped_ptr<ReadableFakeWebSocketStream> stream(
1666 new ReadableFakeWebSocketStream);
1667 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1669 set_stream(stream.Pass());
1670 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1671 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1672 // This checkpoint object verifies that the OnDropChannel message comes after
1674 Checkpoint checkpoint;
1675 TestClosure completion;
1678 EXPECT_CALL(checkpoint, Call(1));
1679 EXPECT_CALL(*event_interface_,
1680 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
1681 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
1683 CreateChannelAndConnectSuccessfully();
1684 // OneShotTimer is not very friendly to testing; there is no apparent way to
1685 // set an expectation on it. Instead the tests need to infer that the timeout
1686 // was fired by the behaviour of the WebSocketChannel object.
1687 channel_->SetClosingHandshakeTimeoutForTesting(
1688 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
1689 channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
1691 completion.WaitForResult();
1694 // The closing handshake times out and sends an OnDropChannel event if a Close
1695 // message is received but the connection isn't closed by the remote host.
1696 TEST_F(WebSocketChannelEventInterfaceTest,
1697 ServerInitiatedClosingHandshakeTimesOut) {
1698 scoped_ptr<ReadableFakeWebSocketStream> stream(
1699 new ReadableFakeWebSocketStream);
1700 static const InitFrame frames[] = {
1701 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1702 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
1703 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1704 set_stream(stream.Pass());
1705 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
1706 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1707 Checkpoint checkpoint;
1708 TestClosure completion;
1711 EXPECT_CALL(checkpoint, Call(1));
1712 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1713 EXPECT_CALL(*event_interface_,
1714 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
1715 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
1717 CreateChannelAndConnectSuccessfully();
1718 channel_->SetClosingHandshakeTimeoutForTesting(
1719 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
1721 completion.WaitForResult();
1724 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
1725 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
1726 // perform masking itself (not all transports actually use masking).
1727 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
1728 static const InitFrame expected[] = {
1729 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1730 MASKED, "NEEDS MASKING"}};
1731 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1732 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1733 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1734 .WillOnce(Return(OK));
1736 CreateChannelAndConnectSuccessfully();
1737 channel_->SendFrame(
1738 true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
1741 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
1742 // sending a Close frame."
1743 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
1744 static const InitFrame expected[] = {
1745 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1746 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1747 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1748 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1749 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1750 .WillOnce(Return(OK));
1752 CreateChannelAndConnectSuccessfully();
1753 channel_->StartClosingHandshake(1000, "Success");
1754 channel_->SendFrame(
1755 true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD BE IGNORED"));
1758 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
1759 // send a Close frame, the endpoint MUST send a Close frame in response."
1760 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
1761 static const InitFrame frames[] = {
1762 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1763 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1764 static const InitFrame expected[] = {
1765 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1766 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1767 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1768 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1769 .WillOnce(ReturnFrames(&frames))
1770 .WillRepeatedly(Return(ERR_IO_PENDING));
1771 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1772 .WillOnce(Return(OK));
1774 CreateChannelAndConnectSuccessfully();
1777 // The converse of the above case; after sending a Close frame, we should not
1778 // send another one.
1779 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
1780 static const InitFrame expected[] = {
1781 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1782 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1783 static const InitFrame frames_init[] = {
1784 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1785 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
1787 // We store the parameters that were passed to ReadFrames() so that we can
1788 // call them explicitly later.
1789 CompletionCallback read_callback;
1790 ScopedVector<WebSocketFrame>* frames = NULL;
1792 // Use a checkpoint to make the ordering of events clearer.
1793 Checkpoint checkpoint;
1796 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1797 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1798 .WillOnce(DoAll(SaveArg<0>(&frames),
1799 SaveArg<1>(&read_callback),
1800 Return(ERR_IO_PENDING)));
1801 EXPECT_CALL(checkpoint, Call(1));
1802 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1803 .WillOnce(Return(OK));
1804 EXPECT_CALL(checkpoint, Call(2));
1805 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1806 .WillOnce(Return(ERR_IO_PENDING));
1807 EXPECT_CALL(checkpoint, Call(3));
1808 // WriteFrames() must not be called again. GoogleMock will ensure that the
1809 // test fails if it is.
1812 CreateChannelAndConnectSuccessfully();
1814 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
1817 *frames = CreateFrameVector(frames_init);
1818 read_callback.Run(OK);
1822 // Invalid close status codes should not be sent on the network.
1823 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
1824 static const InitFrame expected[] = {
1825 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1826 MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Error")}};
1828 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1829 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1830 .WillOnce(Return(ERR_IO_PENDING));
1832 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
1834 CreateChannelAndConnectSuccessfully();
1835 channel_->StartClosingHandshake(999, "");
1838 // A Close frame with a reason longer than 123 bytes cannot be sent on the
1840 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
1841 static const InitFrame expected[] = {
1842 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1843 MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Error")}};
1845 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1846 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1847 .WillOnce(Return(ERR_IO_PENDING));
1849 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
1851 CreateChannelAndConnectSuccessfully();
1852 channel_->StartClosingHandshake(1000, std::string(124, 'A'));
1855 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
1856 // status in the Close message from the other side. Code 1005 is not allowed to
1857 // appear on the wire, so we should not echo it back. See test
1858 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
1859 // correctly generated internally.
1860 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
1861 static const InitFrame frames[] = {
1862 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1863 static const InitFrame expected[] = {
1864 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
1865 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1866 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1867 .WillOnce(ReturnFrames(&frames))
1868 .WillRepeatedly(Return(ERR_IO_PENDING));
1869 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1870 .WillOnce(Return(OK));
1872 CreateChannelAndConnectSuccessfully();
1875 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
1876 // frame in response"
1877 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
1878 // "Application data" as found in the message body of the Ping frame being
1880 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
1881 static const InitFrame frames[] = {
1882 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
1883 NOT_MASKED, "Application data"}};
1884 static const InitFrame expected[] = {
1885 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
1886 MASKED, "Application data"}};
1887 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1888 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1889 .WillOnce(ReturnFrames(&frames))
1890 .WillRepeatedly(Return(ERR_IO_PENDING));
1891 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
1892 .WillOnce(Return(OK));
1894 CreateChannelAndConnectSuccessfully();
1897 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
1898 static const InitFrame frames[] = {
1899 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
1900 NOT_MASKED, "Application data"}};
1901 static const InitFrame expected1[] = {
1902 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
1903 static const InitFrame expected2[] = {
1904 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
1905 MASKED, "Application data"}};
1906 static const InitFrame expected3[] = {
1907 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1909 ScopedVector<WebSocketFrame>* read_frames;
1910 CompletionCallback read_callback;
1911 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1912 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
1913 .WillOnce(DoAll(SaveArg<0>(&read_frames),
1914 SaveArg<1>(&read_callback),
1915 Return(ERR_IO_PENDING)))
1916 .WillRepeatedly(Return(ERR_IO_PENDING));
1920 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1921 .WillOnce(Return(OK));
1922 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1923 .WillOnce(Return(OK));
1924 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
1925 .WillOnce(Return(OK));
1928 CreateChannelAndConnectSuccessfully();
1929 channel_->SendFrame(
1930 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
1931 *read_frames = CreateFrameVector(frames);
1932 read_callback.Run(OK);
1933 channel_->SendFrame(
1934 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
1937 // WriteFrames() may not be called until the previous write has completed.
1938 // WebSocketChannel must buffer writes that happen in the meantime.
1939 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
1940 static const InitFrame expected1[] = {
1941 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
1942 static const InitFrame expected2[] = {
1943 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
1944 CompletionCallback write_callback;
1945 Checkpoint checkpoint;
1947 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1948 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1951 EXPECT_CALL(checkpoint, Call(1));
1952 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1953 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
1954 EXPECT_CALL(checkpoint, Call(2));
1955 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1956 .WillOnce(Return(ERR_IO_PENDING));
1957 EXPECT_CALL(checkpoint, Call(3));
1960 CreateChannelAndConnectSuccessfully();
1962 channel_->SendFrame(
1963 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
1964 channel_->SendFrame(
1965 true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
1967 write_callback.Run(OK);
1971 // WebSocketChannel must buffer frames while it is waiting for a write to
1972 // complete, and then send them in a single batch. The batching behaviour is
1973 // important to get good throughput in the "many small messages" case.
1974 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
1975 static const char input_letters[] = "Hello";
1976 static const InitFrame expected1[] = {
1977 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
1978 static const InitFrame expected2[] = {
1979 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
1980 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
1981 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
1982 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
1983 CompletionCallback write_callback;
1985 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
1986 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
1989 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
1990 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
1991 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
1992 .WillOnce(Return(ERR_IO_PENDING));
1995 CreateChannelAndConnectSuccessfully();
1996 for (size_t i = 0; i < strlen(input_letters); ++i) {
1997 channel_->SendFrame(true,
1998 WebSocketFrameHeader::kOpCodeText,
1999 std::vector<char>(1, input_letters[i]));
2001 write_callback.Run(OK);
2004 // When the renderer sends more on a channel than it has quota for, then we send
2005 // a kWebSocketMuxErrorSendQuotaViolation status code (from the draft websocket
2006 // mux specification) back to the renderer. This should not be sent to the
2007 // remote server, which may not even implement the mux specification, and could
2008 // even be using a different extension which uses that code to mean something
2010 TEST_F(WebSocketChannelStreamTest, MuxErrorIsNotSentToStream) {
2011 static const InitFrame expected[] = {
2012 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2013 MASKED, CLOSE_DATA(GOING_AWAY, "Internal Error")}};
2014 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2015 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2016 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2017 .WillOnce(Return(OK));
2018 EXPECT_CALL(*mock_stream_, Close());
2020 CreateChannelAndConnectSuccessfully();
2021 channel_->SendFrame(true,
2022 WebSocketFrameHeader::kOpCodeText,
2023 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2026 // For convenience, most of these tests use Text frames. However, the WebSocket
2027 // protocol also has Binary frames and those need to be 8-bit clean. For the
2028 // sake of completeness, this test verifies that they are.
2029 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2030 ScopedVector<WebSocketFrame>* frames = NULL;
2032 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2033 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2034 EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2035 .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2037 CreateChannelAndConnectSuccessfully();
2038 channel_->SendFrame(
2040 WebSocketFrameHeader::kOpCodeBinary,
2041 std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2042 ASSERT_TRUE(frames != NULL);
2043 ASSERT_EQ(1U, frames->size());
2044 const WebSocketFrame* out_frame = (*frames)[0];
2045 EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2046 ASSERT_TRUE(out_frame->data);
2047 EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2050 // Test the read path for 8-bit cleanliness as well.
2051 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2052 scoped_ptr<WebSocketFrame> frame(
2053 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2054 WebSocketFrameHeader& frame_header = frame->header;
2055 frame_header.final = true;
2056 frame_header.payload_length = kBinaryBlobSize;
2057 frame->data = new IOBuffer(kBinaryBlobSize);
2058 memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2059 ScopedVector<WebSocketFrame> frames;
2060 frames.push_back(frame.release());
2061 scoped_ptr<ReadableFakeWebSocketStream> stream(
2062 new ReadableFakeWebSocketStream);
2063 stream->PrepareRawReadFrames(
2064 ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2065 set_stream(stream.Pass());
2066 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _));
2067 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2068 EXPECT_CALL(*event_interface_,
2070 WebSocketFrameHeader::kOpCodeBinary,
2071 std::vector<char>(kBinaryBlob,
2072 kBinaryBlob + kBinaryBlobSize)));
2074 CreateChannelAndConnectSuccessfully();
2077 // If we receive another frame after Close, it is not valid. It is not
2078 // completely clear what behaviour is required from the standard in this case,
2079 // but the current implementation fails the connection. Since a Close has
2080 // already been sent, this just means closing the connection.
2081 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
2082 static const InitFrame frames[] = {
2083 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2084 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2085 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2086 NOT_MASKED, "Ping body"}};
2087 static const InitFrame expected[] = {
2088 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2089 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2090 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2091 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2092 .WillOnce(ReturnFrames(&frames))
2093 .WillRepeatedly(Return(ERR_IO_PENDING));
2095 // We only need to verify the relative order of WriteFrames() and
2096 // Close(). The current implementation calls WriteFrames() for the Close
2097 // frame before calling ReadFrames() again, but that is an implementation
2098 // detail and better not to consider required behaviour.
2100 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2101 .WillOnce(Return(OK));
2102 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2105 CreateChannelAndConnectSuccessfully();
2108 // A protocol error from the remote server should result in a close frame with
2109 // status 1002, followed by the connection closing.
2110 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
2111 static const InitFrame expected[] = {
2112 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2113 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
2114 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2115 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2116 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
2117 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2118 .WillOnce(Return(OK));
2119 EXPECT_CALL(*mock_stream_, Close());
2121 CreateChannelAndConnectSuccessfully();
2124 // Set the closing handshake timeout to a very tiny value before connecting.
2125 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
2127 WebSocketChannelStreamTimeoutTest() {}
2129 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
2130 set_stream(mock_stream_.Pass());
2131 CreateChannelAndConnect();
2132 channel_->SetClosingHandshakeTimeoutForTesting(
2133 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2134 connect_data_.factory.connect_delegate->OnSuccess(stream_.Pass());
2138 // In this case the server initiates the closing handshake with a Close
2139 // message. WebSocketChannel responds with a matching Close message, and waits
2140 // for the server to close the TCP/IP connection. The server never closes the
2141 // connection, so the closing handshake times out and WebSocketChannel closes
2142 // the connection itself.
2143 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
2144 static const InitFrame frames[] = {
2145 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2146 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2147 static const InitFrame expected[] = {
2148 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2149 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2150 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2151 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2152 .WillOnce(ReturnFrames(&frames))
2153 .WillRepeatedly(Return(ERR_IO_PENDING));
2154 Checkpoint checkpoint;
2155 TestClosure completion;
2158 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2159 .WillOnce(Return(OK));
2160 EXPECT_CALL(checkpoint, Call(1));
2161 EXPECT_CALL(*mock_stream_, Close())
2162 .WillOnce(InvokeClosure(completion.closure()));
2165 CreateChannelAndConnectSuccessfully();
2167 completion.WaitForResult();
2170 // In this case the client initiates the closing handshake by sending a Close
2171 // message. WebSocketChannel waits for a Close message in response from the
2172 // server. The server never responds to the Close message, so the closing
2173 // handshake times out and WebSocketChannel closes the connection.
2174 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
2175 static const InitFrame expected[] = {
2176 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2177 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2178 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2179 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2180 .WillRepeatedly(Return(ERR_IO_PENDING));
2181 TestClosure completion;
2184 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2185 .WillOnce(Return(OK));
2186 EXPECT_CALL(*mock_stream_, Close())
2187 .WillOnce(InvokeClosure(completion.closure()));
2190 CreateChannelAndConnectSuccessfully();
2191 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2192 completion.WaitForResult();
2195 // In this case the client initiates the closing handshake and the server
2196 // responds with a matching Close message. WebSocketChannel waits for the server
2197 // to close the TCP/IP connection, but it never does. The closing handshake
2198 // times out and WebSocketChannel closes the connection.
2199 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
2200 static const InitFrame expected[] = {
2201 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2202 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2203 static const InitFrame frames[] = {
2204 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2205 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2206 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2207 TestClosure completion;
2208 ScopedVector<WebSocketFrame>* read_frames = NULL;
2209 CompletionCallback read_callback;
2212 // Copy the arguments to ReadFrames so that the test can call the callback
2213 // after it has send the close message.
2214 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2215 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2216 SaveArg<1>(&read_callback),
2217 Return(ERR_IO_PENDING)));
2218 // The first real event that happens is the client sending the Close
2220 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2221 .WillOnce(Return(OK));
2222 // The |read_frames| callback is called (from this test case) at this
2223 // point. ReadFrames is called again by WebSocketChannel, waiting for
2224 // ERR_CONNECTION_CLOSED.
2225 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2226 .WillOnce(Return(ERR_IO_PENDING));
2227 // The timeout happens and so WebSocketChannel closes the stream.
2228 EXPECT_CALL(*mock_stream_, Close())
2229 .WillOnce(InvokeClosure(completion.closure()));
2232 CreateChannelAndConnectSuccessfully();
2233 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2234 ASSERT_TRUE(read_frames);
2235 // Provide the "Close" message from the server.
2236 *read_frames = CreateFrameVector(frames);
2237 read_callback.Run(OK);
2238 completion.WaitForResult();