Web MIDI: enable receiving functionality in Linux and Chrome OS
[chromium-blink-merge.git] / net / websockets / websocket_channel_test.cc
blobed309c71126a2c9ef9fadfe716f0911a258333c3
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"
7 #include <string.h>
9 #include <iostream>
10 #include <string>
11 #include <vector>
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/strings/string_piece.h"
22 #include "net/base/net_errors.h"
23 #include "net/base/test_completion_callback.h"
24 #include "net/http/http_response_headers.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_handshake_request_info.h"
29 #include "net/websockets/websocket_handshake_response_info.h"
30 #include "net/websockets/websocket_mux.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "url/gurl.h"
35 // Hacky macros to construct the body of a Close message from a code and a
36 // string, while ensuring the result is a compile-time constant string.
37 // Use like CLOSE_DATA(NORMAL_CLOSURE, "Explanation String")
38 #define CLOSE_DATA(code, string) WEBSOCKET_CLOSE_CODE_AS_STRING_##code string
39 #define WEBSOCKET_CLOSE_CODE_AS_STRING_NORMAL_CLOSURE "\x03\xe8"
40 #define WEBSOCKET_CLOSE_CODE_AS_STRING_GOING_AWAY "\x03\xe9"
41 #define WEBSOCKET_CLOSE_CODE_AS_STRING_PROTOCOL_ERROR "\x03\xea"
42 #define WEBSOCKET_CLOSE_CODE_AS_STRING_ABNORMAL_CLOSURE "\x03\xee"
43 #define WEBSOCKET_CLOSE_CODE_AS_STRING_SERVER_ERROR "\x03\xf3"
45 namespace net {
47 // Printing helpers to allow GoogleMock to print frames. These are explicitly
48 // designed to look like the static initialisation format we use in these
49 // tests. They have to live in the net namespace in order to be found by
50 // GoogleMock; a nested anonymous namespace will not work.
52 std::ostream& operator<<(std::ostream& os, const WebSocketFrameHeader& header) {
53 return os << (header.final ? "FINAL_FRAME" : "NOT_FINAL_FRAME") << ", "
54 << header.opcode << ", "
55 << (header.masked ? "MASKED" : "NOT_MASKED");
58 std::ostream& operator<<(std::ostream& os, const WebSocketFrame& frame) {
59 os << "{" << frame.header << ", ";
60 if (frame.data) {
61 return os << "\"" << base::StringPiece(frame.data->data(),
62 frame.header.payload_length)
63 << "\"}";
65 return os << "NULL}";
68 std::ostream& operator<<(std::ostream& os,
69 const ScopedVector<WebSocketFrame>& vector) {
70 os << "{";
71 bool first = true;
72 for (ScopedVector<WebSocketFrame>::const_iterator it = vector.begin();
73 it != vector.end();
74 ++it) {
75 if (!first) {
76 os << ",\n";
77 } else {
78 first = false;
80 os << **it;
82 return os << "}";
85 std::ostream& operator<<(std::ostream& os,
86 const ScopedVector<WebSocketFrame>* vector) {
87 return os << '&' << *vector;
90 namespace {
92 using ::base::TimeDelta;
94 using ::testing::AnyNumber;
95 using ::testing::DefaultValue;
96 using ::testing::InSequence;
97 using ::testing::MockFunction;
98 using ::testing::Return;
99 using ::testing::SaveArg;
100 using ::testing::StrictMock;
101 using ::testing::_;
103 // A selection of characters that have traditionally been mangled in some
104 // environment or other, for testing 8-bit cleanliness.
105 const char kBinaryBlob[] = {'\n', '\r', // BACKWARDS CRNL
106 '\0', // nul
107 '\x7F', // DEL
108 '\x80', '\xFF', // NOT VALID UTF-8
109 '\x1A', // Control-Z, EOF on DOS
110 '\x03', // Control-C
111 '\x04', // EOT, special for Unix terms
112 '\x1B', // ESC, often special
113 '\b', // backspace
114 '\'', // single-quote, special in PHP
116 const size_t kBinaryBlobSize = arraysize(kBinaryBlob);
118 // The amount of quota a new connection gets by default.
119 // TODO(ricea): If kDefaultSendQuotaHighWaterMark changes, then this value will
120 // need to be updated.
121 const size_t kDefaultInitialQuota = 1 << 17;
122 // The amount of bytes we need to send after the initial connection to trigger a
123 // quota refresh. TODO(ricea): Change this if kDefaultSendQuotaHighWaterMark or
124 // kDefaultSendQuotaLowWaterMark change.
125 const size_t kDefaultQuotaRefreshTrigger = (1 << 16) + 1;
127 // TestTimeouts::tiny_timeout() is 100ms! I could run halfway around the world
128 // in that time! I would like my tests to run a bit quicker.
129 const int kVeryTinyTimeoutMillis = 1;
131 typedef WebSocketEventInterface::ChannelState ChannelState;
132 const ChannelState CHANNEL_ALIVE = WebSocketEventInterface::CHANNEL_ALIVE;
133 const ChannelState CHANNEL_DELETED = WebSocketEventInterface::CHANNEL_DELETED;
135 // This typedef mainly exists to avoid having to repeat the "NOLINT" incantation
136 // all over the place.
137 typedef MockFunction<void(int)> Checkpoint; // NOLINT
139 // This mock is for testing expectations about how the EventInterface is used.
140 class MockWebSocketEventInterface : public WebSocketEventInterface {
141 public:
142 MockWebSocketEventInterface() {}
144 MOCK_METHOD3(OnAddChannelResponse,
145 ChannelState(bool,
146 const std::string&,
147 const std::string&)); // NOLINT
148 MOCK_METHOD3(OnDataFrame,
149 ChannelState(bool,
150 WebSocketMessageType,
151 const std::vector<char>&)); // NOLINT
152 MOCK_METHOD1(OnFlowControl, ChannelState(int64)); // NOLINT
153 MOCK_METHOD0(OnClosingHandshake, ChannelState(void)); // NOLINT
154 MOCK_METHOD1(OnFailChannel, ChannelState(const std::string&)); // NOLINT
155 MOCK_METHOD2(OnDropChannel,
156 ChannelState(uint16, const std::string&)); // NOLINT
158 // We can't use GMock with scoped_ptr.
159 ChannelState OnStartOpeningHandshake(
160 scoped_ptr<WebSocketHandshakeRequestInfo>) OVERRIDE {
161 OnStartOpeningHandshakeCalled();
162 return CHANNEL_ALIVE;
164 ChannelState OnFinishOpeningHandshake(
165 scoped_ptr<WebSocketHandshakeResponseInfo>) OVERRIDE {
166 OnFinishOpeningHandshakeCalled();
167 return CHANNEL_ALIVE;
170 MOCK_METHOD0(OnStartOpeningHandshakeCalled, void()); // NOLINT
171 MOCK_METHOD0(OnFinishOpeningHandshakeCalled, void()); // NOLINT
174 // This fake EventInterface is for tests which need a WebSocketEventInterface
175 // implementation but are not verifying how it is used.
176 class FakeWebSocketEventInterface : public WebSocketEventInterface {
177 virtual ChannelState OnAddChannelResponse(
178 bool fail,
179 const std::string& selected_protocol,
180 const std::string& extensions) OVERRIDE {
181 return fail ? CHANNEL_DELETED : CHANNEL_ALIVE;
183 virtual ChannelState OnDataFrame(bool fin,
184 WebSocketMessageType type,
185 const std::vector<char>& data) OVERRIDE {
186 return CHANNEL_ALIVE;
188 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
189 return CHANNEL_ALIVE;
191 virtual ChannelState OnClosingHandshake() OVERRIDE { return CHANNEL_ALIVE; }
192 virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
193 return CHANNEL_DELETED;
195 virtual ChannelState OnDropChannel(uint16 code,
196 const std::string& reason) OVERRIDE {
197 return CHANNEL_DELETED;
199 virtual ChannelState OnStartOpeningHandshake(
200 scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
201 return CHANNEL_ALIVE;
203 virtual ChannelState OnFinishOpeningHandshake(
204 scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
205 return CHANNEL_ALIVE;
209 // This fake WebSocketStream is for tests that require a WebSocketStream but are
210 // not testing the way it is used. It has minimal functionality to return
211 // the |protocol| and |extensions| that it was constructed with.
212 class FakeWebSocketStream : public WebSocketStream {
213 public:
214 // Constructs with empty protocol and extensions.
215 FakeWebSocketStream() {}
217 // Constructs with specified protocol and extensions.
218 FakeWebSocketStream(const std::string& protocol,
219 const std::string& extensions)
220 : protocol_(protocol), extensions_(extensions) {}
222 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
223 const CompletionCallback& callback) OVERRIDE {
224 return ERR_IO_PENDING;
227 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
228 const CompletionCallback& callback) OVERRIDE {
229 return ERR_IO_PENDING;
232 virtual void Close() OVERRIDE {}
234 // Returns the string passed to the constructor.
235 virtual std::string GetSubProtocol() const OVERRIDE { return protocol_; }
237 // Returns the string passed to the constructor.
238 virtual std::string GetExtensions() const OVERRIDE { return extensions_; }
240 private:
241 // The string to return from GetSubProtocol().
242 std::string protocol_;
244 // The string to return from GetExtensions().
245 std::string extensions_;
248 // To make the static initialisers easier to read, we use enums rather than
249 // bools.
250 enum IsFinal { NOT_FINAL_FRAME, FINAL_FRAME };
252 enum IsMasked { NOT_MASKED, MASKED };
254 // This is used to initialise a WebSocketFrame but is statically initialisable.
255 struct InitFrame {
256 IsFinal final;
257 // Reserved fields omitted for now. Add them if you need them.
258 WebSocketFrameHeader::OpCode opcode;
259 IsMasked masked;
261 // Will be used to create the IOBuffer member. Can be NULL for NULL data. Is a
262 // nul-terminated string for ease-of-use. |header.payload_length| is
263 // initialised from |strlen(data)|. This means it is not 8-bit clean, but this
264 // is not an issue for test data.
265 const char* const data;
268 // For GoogleMock
269 std::ostream& operator<<(std::ostream& os, const InitFrame& frame) {
270 os << "{" << (frame.final == FINAL_FRAME ? "FINAL_FRAME" : "NOT_FINAL_FRAME")
271 << ", " << frame.opcode << ", "
272 << (frame.masked == MASKED ? "MASKED" : "NOT_MASKED") << ", ";
273 if (frame.data) {
274 return os << "\"" << frame.data << "\"}";
276 return os << "NULL}";
279 template <size_t N>
280 std::ostream& operator<<(std::ostream& os, const InitFrame (&frames)[N]) {
281 os << "{";
282 bool first = true;
283 for (size_t i = 0; i < N; ++i) {
284 if (!first) {
285 os << ",\n";
286 } else {
287 first = false;
289 os << frames[i];
291 return os << "}";
294 // Convert a const array of InitFrame structs to the format used at
295 // runtime. Templated on the size of the array to save typing.
296 template <size_t N>
297 ScopedVector<WebSocketFrame> CreateFrameVector(
298 const InitFrame (&source_frames)[N]) {
299 ScopedVector<WebSocketFrame> result_frames;
300 result_frames.reserve(N);
301 for (size_t i = 0; i < N; ++i) {
302 const InitFrame& source_frame = source_frames[i];
303 scoped_ptr<WebSocketFrame> result_frame(
304 new WebSocketFrame(source_frame.opcode));
305 size_t frame_length = source_frame.data ? strlen(source_frame.data) : 0;
306 WebSocketFrameHeader& result_header = result_frame->header;
307 result_header.final = (source_frame.final == FINAL_FRAME);
308 result_header.masked = (source_frame.masked == MASKED);
309 result_header.payload_length = frame_length;
310 if (source_frame.data) {
311 result_frame->data = new IOBuffer(frame_length);
312 memcpy(result_frame->data->data(), source_frame.data, frame_length);
314 result_frames.push_back(result_frame.release());
316 return result_frames.Pass();
319 // A GoogleMock action which can be used to respond to call to ReadFrames with
320 // some frames. Use like ReadFrames(_, _).WillOnce(ReturnFrames(&frames));
321 // |frames| is an array of InitFrame. |frames| needs to be passed by pointer
322 // because otherwise it will be treated as a pointer and the array size
323 // information will be lost.
324 ACTION_P(ReturnFrames, source_frames) {
325 *arg0 = CreateFrameVector(*source_frames);
326 return OK;
329 // The implementation of a GoogleMock matcher which can be used to compare a
330 // ScopedVector<WebSocketFrame>* against an expectation defined as an array of
331 // InitFrame objects. Although it is possible to compose built-in GoogleMock
332 // matchers to check the contents of a WebSocketFrame, the results are so
333 // unreadable that it is better to use this matcher.
334 template <size_t N>
335 class EqualsFramesMatcher
336 : public ::testing::MatcherInterface<ScopedVector<WebSocketFrame>*> {
337 public:
338 EqualsFramesMatcher(const InitFrame (*expect_frames)[N])
339 : expect_frames_(expect_frames) {}
341 virtual bool MatchAndExplain(ScopedVector<WebSocketFrame>* actual_frames,
342 ::testing::MatchResultListener* listener) const {
343 if (actual_frames->size() != N) {
344 *listener << "the vector size is " << actual_frames->size();
345 return false;
347 for (size_t i = 0; i < N; ++i) {
348 const WebSocketFrame& actual_frame = *(*actual_frames)[i];
349 const InitFrame& expected_frame = (*expect_frames_)[i];
350 if (actual_frame.header.final != (expected_frame.final == FINAL_FRAME)) {
351 *listener << "the frame is marked as "
352 << (actual_frame.header.final ? "" : "not ") << "final";
353 return false;
355 if (actual_frame.header.opcode != expected_frame.opcode) {
356 *listener << "the opcode is " << actual_frame.header.opcode;
357 return false;
359 if (actual_frame.header.masked != (expected_frame.masked == MASKED)) {
360 *listener << "the frame is "
361 << (actual_frame.header.masked ? "masked" : "not masked");
362 return false;
364 const size_t expected_length =
365 expected_frame.data ? strlen(expected_frame.data) : 0;
366 if (actual_frame.header.payload_length != expected_length) {
367 *listener << "the payload length is "
368 << actual_frame.header.payload_length;
369 return false;
371 if (expected_length != 0 &&
372 memcmp(actual_frame.data->data(),
373 expected_frame.data,
374 actual_frame.header.payload_length) != 0) {
375 *listener << "the data content differs";
376 return false;
379 return true;
382 virtual void DescribeTo(std::ostream* os) const {
383 *os << "matches " << *expect_frames_;
386 virtual void DescribeNegationTo(std::ostream* os) const {
387 *os << "does not match " << *expect_frames_;
390 private:
391 const InitFrame (*expect_frames_)[N];
394 // The definition of EqualsFrames GoogleMock matcher. Unlike the ReturnFrames
395 // action, this can take the array by reference.
396 template <size_t N>
397 ::testing::Matcher<ScopedVector<WebSocketFrame>*> EqualsFrames(
398 const InitFrame (&frames)[N]) {
399 return ::testing::MakeMatcher(new EqualsFramesMatcher<N>(&frames));
402 // TestClosure works like TestCompletionCallback, but doesn't take an argument.
403 class TestClosure {
404 public:
405 base::Closure closure() { return base::Bind(callback_.callback(), OK); }
407 void WaitForResult() { callback_.WaitForResult(); }
409 private:
410 // Delegate to TestCompletionCallback for the implementation.
411 TestCompletionCallback callback_;
414 // A GoogleMock action to run a Closure.
415 ACTION_P(InvokeClosure, closure) { closure.Run(); }
417 // A GoogleMock action to run a Closure and return CHANNEL_DELETED.
418 ACTION_P(InvokeClosureReturnDeleted, closure) {
419 closure.Run();
420 return WebSocketEventInterface::CHANNEL_DELETED;
423 // A FakeWebSocketStream whose ReadFrames() function returns data.
424 class ReadableFakeWebSocketStream : public FakeWebSocketStream {
425 public:
426 enum IsSync { SYNC, ASYNC };
428 // After constructing the object, call PrepareReadFrames() once for each
429 // time you wish it to return from the test.
430 ReadableFakeWebSocketStream() : index_(0), read_frames_pending_(false) {}
432 // Check that all the prepared responses have been consumed.
433 virtual ~ReadableFakeWebSocketStream() {
434 CHECK(index_ >= responses_.size());
435 CHECK(!read_frames_pending_);
438 // Prepares a fake response. Fake responses will be returned from ReadFrames()
439 // in the same order they were prepared with PrepareReadFrames() and
440 // PrepareReadFramesError(). If |async| is ASYNC, then ReadFrames() will
441 // return ERR_IO_PENDING and the callback will be scheduled to run on the
442 // message loop. This requires the test case to run the message loop. If
443 // |async| is SYNC, the response will be returned synchronously. |error| is
444 // returned directly from ReadFrames() in the synchronous case, or passed to
445 // the callback in the asynchronous case. |frames| will be converted to a
446 // ScopedVector<WebSocketFrame> and copied to the pointer that was passed to
447 // ReadFrames().
448 template <size_t N>
449 void PrepareReadFrames(IsSync async,
450 int error,
451 const InitFrame (&frames)[N]) {
452 responses_.push_back(new Response(async, error, CreateFrameVector(frames)));
455 // An alternate version of PrepareReadFrames for when we need to construct
456 // the frames manually.
457 void PrepareRawReadFrames(IsSync async,
458 int error,
459 ScopedVector<WebSocketFrame> frames) {
460 responses_.push_back(new Response(async, error, frames.Pass()));
463 // Prepares a fake error response (ie. there is no data).
464 void PrepareReadFramesError(IsSync async, int error) {
465 responses_.push_back(
466 new Response(async, error, ScopedVector<WebSocketFrame>()));
469 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
470 const CompletionCallback& callback) OVERRIDE {
471 CHECK(!read_frames_pending_);
472 if (index_ >= responses_.size())
473 return ERR_IO_PENDING;
474 if (responses_[index_]->async == ASYNC) {
475 read_frames_pending_ = true;
476 base::MessageLoop::current()->PostTask(
477 FROM_HERE,
478 base::Bind(&ReadableFakeWebSocketStream::DoCallback,
479 base::Unretained(this),
480 frames,
481 callback));
482 return ERR_IO_PENDING;
483 } else {
484 frames->swap(responses_[index_]->frames);
485 return responses_[index_++]->error;
489 private:
490 void DoCallback(ScopedVector<WebSocketFrame>* frames,
491 const CompletionCallback& callback) {
492 read_frames_pending_ = false;
493 frames->swap(responses_[index_]->frames);
494 callback.Run(responses_[index_++]->error);
495 return;
498 struct Response {
499 Response(IsSync async, int error, ScopedVector<WebSocketFrame> frames)
500 : async(async), error(error), frames(frames.Pass()) {}
502 IsSync async;
503 int error;
504 ScopedVector<WebSocketFrame> frames;
506 private:
507 // Bad things will happen if we attempt to copy or assign |frames|.
508 DISALLOW_COPY_AND_ASSIGN(Response);
510 ScopedVector<Response> responses_;
512 // The index into the responses_ array of the next response to be returned.
513 size_t index_;
515 // True when an async response from ReadFrames() is pending. This only applies
516 // to "real" async responses. Once all the prepared responses have been
517 // returned, ReadFrames() returns ERR_IO_PENDING but read_frames_pending_ is
518 // not set to true.
519 bool read_frames_pending_;
522 // A FakeWebSocketStream where writes always complete successfully and
523 // synchronously.
524 class WriteableFakeWebSocketStream : public FakeWebSocketStream {
525 public:
526 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
527 const CompletionCallback& callback) OVERRIDE {
528 return OK;
532 // A FakeWebSocketStream where writes always fail.
533 class UnWriteableFakeWebSocketStream : public FakeWebSocketStream {
534 public:
535 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
536 const CompletionCallback& callback) OVERRIDE {
537 return ERR_CONNECTION_RESET;
541 // A FakeWebSocketStream which echoes any frames written back. Clears the
542 // "masked" header bit, but makes no other checks for validity. Tests using this
543 // must run the MessageLoop to receive the callback(s). If a message with opcode
544 // Close is echoed, then an ERR_CONNECTION_CLOSED is returned in the next
545 // callback. The test must do something to cause WriteFrames() to be called,
546 // otherwise the ReadFrames() callback will never be called.
547 class EchoeyFakeWebSocketStream : public FakeWebSocketStream {
548 public:
549 EchoeyFakeWebSocketStream() : read_frames_(NULL), done_(false) {}
551 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
552 const CompletionCallback& callback) OVERRIDE {
553 // Users of WebSocketStream will not expect the ReadFrames() callback to be
554 // called from within WriteFrames(), so post it to the message loop instead.
555 stored_frames_.insert(stored_frames_.end(), frames->begin(), frames->end());
556 frames->weak_clear();
557 PostCallback();
558 return OK;
561 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
562 const CompletionCallback& callback) OVERRIDE {
563 read_callback_ = callback;
564 read_frames_ = frames;
565 if (done_)
566 PostCallback();
567 return ERR_IO_PENDING;
570 private:
571 void PostCallback() {
572 base::MessageLoop::current()->PostTask(
573 FROM_HERE,
574 base::Bind(&EchoeyFakeWebSocketStream::DoCallback,
575 base::Unretained(this)));
578 void DoCallback() {
579 if (done_) {
580 read_callback_.Run(ERR_CONNECTION_CLOSED);
581 } else if (!stored_frames_.empty()) {
582 done_ = MoveFrames(read_frames_);
583 read_frames_ = NULL;
584 read_callback_.Run(OK);
588 // Copy the frames stored in stored_frames_ to |out|, while clearing the
589 // "masked" header bit. Returns true if a Close Frame was seen, false
590 // otherwise.
591 bool MoveFrames(ScopedVector<WebSocketFrame>* out) {
592 bool seen_close = false;
593 *out = stored_frames_.Pass();
594 for (ScopedVector<WebSocketFrame>::iterator it = out->begin();
595 it != out->end();
596 ++it) {
597 WebSocketFrameHeader& header = (*it)->header;
598 header.masked = false;
599 if (header.opcode == WebSocketFrameHeader::kOpCodeClose)
600 seen_close = true;
602 return seen_close;
605 ScopedVector<WebSocketFrame> stored_frames_;
606 CompletionCallback read_callback_;
607 // Owned by the caller of ReadFrames().
608 ScopedVector<WebSocketFrame>* read_frames_;
609 // True if we should close the connection.
610 bool done_;
613 // A FakeWebSocketStream where writes trigger a connection reset.
614 // This differs from UnWriteableFakeWebSocketStream in that it is asynchronous
615 // and triggers ReadFrames to return a reset as well. Tests using this need to
616 // run the message loop. There are two tricky parts here:
617 // 1. Calling the write callback may call Close(), after which the read callback
618 // should not be called.
619 // 2. Calling either callback may delete the stream altogether.
620 class ResetOnWriteFakeWebSocketStream : public FakeWebSocketStream {
621 public:
622 ResetOnWriteFakeWebSocketStream() : closed_(false), weak_ptr_factory_(this) {}
624 virtual int WriteFrames(ScopedVector<WebSocketFrame>* frames,
625 const CompletionCallback& callback) OVERRIDE {
626 base::MessageLoop::current()->PostTask(
627 FROM_HERE,
628 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
629 weak_ptr_factory_.GetWeakPtr(),
630 callback,
631 ERR_CONNECTION_RESET));
632 base::MessageLoop::current()->PostTask(
633 FROM_HERE,
634 base::Bind(&ResetOnWriteFakeWebSocketStream::CallCallbackUnlessClosed,
635 weak_ptr_factory_.GetWeakPtr(),
636 read_callback_,
637 ERR_CONNECTION_RESET));
638 return ERR_IO_PENDING;
641 virtual int ReadFrames(ScopedVector<WebSocketFrame>* frames,
642 const CompletionCallback& callback) OVERRIDE {
643 read_callback_ = callback;
644 return ERR_IO_PENDING;
647 virtual void Close() OVERRIDE { closed_ = true; }
649 private:
650 void CallCallbackUnlessClosed(const CompletionCallback& callback, int value) {
651 if (!closed_)
652 callback.Run(value);
655 CompletionCallback read_callback_;
656 bool closed_;
657 // An IO error can result in the socket being deleted, so we use weak pointers
658 // to ensure correct behaviour in that case.
659 base::WeakPtrFactory<ResetOnWriteFakeWebSocketStream> weak_ptr_factory_;
662 // This mock is for verifying that WebSocket protocol semantics are obeyed (to
663 // the extent that they are implemented in WebSocketCommon).
664 class MockWebSocketStream : public WebSocketStream {
665 public:
666 MOCK_METHOD2(ReadFrames,
667 int(ScopedVector<WebSocketFrame>* frames,
668 const CompletionCallback& callback));
669 MOCK_METHOD2(WriteFrames,
670 int(ScopedVector<WebSocketFrame>* frames,
671 const CompletionCallback& callback));
672 MOCK_METHOD0(Close, void());
673 MOCK_CONST_METHOD0(GetSubProtocol, std::string());
674 MOCK_CONST_METHOD0(GetExtensions, std::string());
675 MOCK_METHOD0(AsWebSocketStream, WebSocketStream*());
678 struct ArgumentCopyingWebSocketStreamCreator {
679 scoped_ptr<WebSocketStreamRequest> Create(
680 const GURL& socket_url,
681 const std::vector<std::string>& requested_subprotocols,
682 const GURL& origin,
683 URLRequestContext* url_request_context,
684 const BoundNetLog& net_log,
685 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate) {
686 this->socket_url = socket_url;
687 this->requested_subprotocols = requested_subprotocols;
688 this->origin = origin;
689 this->url_request_context = url_request_context;
690 this->net_log = net_log;
691 this->connect_delegate = connect_delegate.Pass();
692 return make_scoped_ptr(new WebSocketStreamRequest);
695 GURL socket_url;
696 GURL origin;
697 std::vector<std::string> requested_subprotocols;
698 URLRequestContext* url_request_context;
699 BoundNetLog net_log;
700 scoped_ptr<WebSocketStream::ConnectDelegate> connect_delegate;
703 // Converts a std::string to a std::vector<char>. For test purposes, it is
704 // convenient to be able to specify data as a string, but the
705 // WebSocketEventInterface requires the vector<char> type.
706 std::vector<char> AsVector(const std::string& s) {
707 return std::vector<char>(s.begin(), s.end());
710 // Base class for all test fixtures.
711 class WebSocketChannelTest : public ::testing::Test {
712 protected:
713 WebSocketChannelTest() : stream_(new FakeWebSocketStream) {}
715 // Creates a new WebSocketChannel and connects it, using the settings stored
716 // in |connect_data_|.
717 void CreateChannelAndConnect() {
718 channel_.reset(new WebSocketChannel(CreateEventInterface(),
719 &connect_data_.url_request_context));
720 channel_->SendAddChannelRequestForTesting(
721 connect_data_.socket_url,
722 connect_data_.requested_subprotocols,
723 connect_data_.origin,
724 base::Bind(&ArgumentCopyingWebSocketStreamCreator::Create,
725 base::Unretained(&connect_data_.creator)));
728 // Same as CreateChannelAndConnect(), but calls the on_success callback as
729 // well. This method is virtual so that subclasses can also set the stream.
730 virtual void CreateChannelAndConnectSuccessfully() {
731 CreateChannelAndConnect();
732 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
735 // Returns a WebSocketEventInterface to be passed to the WebSocketChannel.
736 // This implementation returns a newly-created fake. Subclasses may return a
737 // mock instead.
738 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() {
739 return scoped_ptr<WebSocketEventInterface>(new FakeWebSocketEventInterface);
742 // This method serves no other purpose than to provide a nice syntax for
743 // assigning to stream_. class T must be a subclass of WebSocketStream or you
744 // will have unpleasant compile errors.
745 template <class T>
746 void set_stream(scoped_ptr<T> stream) {
747 // Since the definition of "PassAs" depends on the type T, the C++ standard
748 // requires the "template" keyword to indicate that "PassAs" should be
749 // parsed as a template method.
750 stream_ = stream.template PassAs<WebSocketStream>();
753 // A struct containing the data that will be used to connect the channel.
754 // Grouped for readability.
755 struct ConnectData {
756 ConnectData() : socket_url("ws://ws/"), origin("http://ws/") {}
758 // URLRequestContext object.
759 URLRequestContext url_request_context;
761 // URL to (pretend to) connect to.
762 GURL socket_url;
763 // Requested protocols for the request.
764 std::vector<std::string> requested_subprotocols;
765 // Origin of the request
766 GURL origin;
768 // A fake WebSocketStreamCreator that just records its arguments.
769 ArgumentCopyingWebSocketStreamCreator creator;
771 ConnectData connect_data_;
773 // The channel we are testing. Not initialised until SetChannel() is called.
774 scoped_ptr<WebSocketChannel> channel_;
776 // A mock or fake stream for tests that need one.
777 scoped_ptr<WebSocketStream> stream_;
780 // enum of WebSocketEventInterface calls. These are intended to be or'd together
781 // in order to instruct WebSocketChannelDeletingTest when it should fail.
782 enum EventInterfaceCall {
783 EVENT_ON_ADD_CHANNEL_RESPONSE = 0x1,
784 EVENT_ON_DATA_FRAME = 0x2,
785 EVENT_ON_FLOW_CONTROL = 0x4,
786 EVENT_ON_CLOSING_HANDSHAKE = 0x8,
787 EVENT_ON_FAIL_CHANNEL = 0x10,
788 EVENT_ON_DROP_CHANNEL = 0x20,
789 EVENT_ON_START_OPENING_HANDSHAKE = 0x40,
790 EVENT_ON_FINISH_OPENING_HANDSHAKE = 0x80,
793 class WebSocketChannelDeletingTest : public WebSocketChannelTest {
794 public:
795 ChannelState DeleteIfDeleting(EventInterfaceCall call) {
796 if (deleting_ & call) {
797 channel_.reset();
798 return CHANNEL_DELETED;
799 } else {
800 return CHANNEL_ALIVE;
804 protected:
805 WebSocketChannelDeletingTest()
806 : deleting_(EVENT_ON_ADD_CHANNEL_RESPONSE | EVENT_ON_DATA_FRAME |
807 EVENT_ON_FLOW_CONTROL |
808 EVENT_ON_CLOSING_HANDSHAKE |
809 EVENT_ON_FAIL_CHANNEL |
810 EVENT_ON_DROP_CHANNEL |
811 EVENT_ON_START_OPENING_HANDSHAKE |
812 EVENT_ON_FINISH_OPENING_HANDSHAKE) {}
813 // Create a ChannelDeletingFakeWebSocketEventInterface. Defined out-of-line to
814 // avoid circular dependency.
815 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE;
817 // Tests can set deleting_ to a bitmap of EventInterfaceCall members that they
818 // want to cause Channel deletion. The default is for all calls to cause
819 // deletion.
820 int deleting_;
823 // A FakeWebSocketEventInterface that deletes the WebSocketChannel on failure to
824 // connect.
825 class ChannelDeletingFakeWebSocketEventInterface
826 : public FakeWebSocketEventInterface {
827 public:
828 ChannelDeletingFakeWebSocketEventInterface(
829 WebSocketChannelDeletingTest* fixture)
830 : fixture_(fixture) {}
832 virtual ChannelState OnAddChannelResponse(
833 bool fail,
834 const std::string& selected_protocol,
835 const std::string& extensions) OVERRIDE {
836 return fixture_->DeleteIfDeleting(EVENT_ON_ADD_CHANNEL_RESPONSE);
839 virtual ChannelState OnDataFrame(bool fin,
840 WebSocketMessageType type,
841 const std::vector<char>& data) OVERRIDE {
842 return fixture_->DeleteIfDeleting(EVENT_ON_DATA_FRAME);
845 virtual ChannelState OnFlowControl(int64 quota) OVERRIDE {
846 return fixture_->DeleteIfDeleting(EVENT_ON_FLOW_CONTROL);
849 virtual ChannelState OnClosingHandshake() OVERRIDE {
850 return fixture_->DeleteIfDeleting(EVENT_ON_CLOSING_HANDSHAKE);
853 virtual ChannelState OnFailChannel(const std::string& message) OVERRIDE {
854 return fixture_->DeleteIfDeleting(EVENT_ON_FAIL_CHANNEL);
857 virtual ChannelState OnDropChannel(uint16 code,
858 const std::string& reason) OVERRIDE {
859 return fixture_->DeleteIfDeleting(EVENT_ON_DROP_CHANNEL);
862 virtual ChannelState OnStartOpeningHandshake(
863 scoped_ptr<WebSocketHandshakeRequestInfo> request) OVERRIDE {
864 return fixture_->DeleteIfDeleting(EVENT_ON_START_OPENING_HANDSHAKE);
866 virtual ChannelState OnFinishOpeningHandshake(
867 scoped_ptr<WebSocketHandshakeResponseInfo> response) OVERRIDE {
868 return fixture_->DeleteIfDeleting(EVENT_ON_FINISH_OPENING_HANDSHAKE);
871 private:
872 // A pointer to the test fixture. Owned by the test harness; this object will
873 // be deleted before it is.
874 WebSocketChannelDeletingTest* fixture_;
877 scoped_ptr<WebSocketEventInterface>
878 WebSocketChannelDeletingTest::CreateEventInterface() {
879 return scoped_ptr<WebSocketEventInterface>(
880 new ChannelDeletingFakeWebSocketEventInterface(this));
883 // Base class for tests which verify that EventInterface methods are called
884 // appropriately.
885 class WebSocketChannelEventInterfaceTest : public WebSocketChannelTest {
886 protected:
887 WebSocketChannelEventInterfaceTest()
888 : event_interface_(new StrictMock<MockWebSocketEventInterface>) {
889 DefaultValue<ChannelState>::Set(CHANNEL_ALIVE);
890 ON_CALL(*event_interface_, OnAddChannelResponse(true, _, _))
891 .WillByDefault(Return(CHANNEL_DELETED));
892 ON_CALL(*event_interface_, OnDropChannel(_, _))
893 .WillByDefault(Return(CHANNEL_DELETED));
894 ON_CALL(*event_interface_, OnFailChannel(_))
895 .WillByDefault(Return(CHANNEL_DELETED));
898 virtual ~WebSocketChannelEventInterfaceTest() {
899 DefaultValue<ChannelState>::Clear();
902 // Tests using this fixture must set expectations on the event_interface_ mock
903 // object before calling CreateChannelAndConnect() or
904 // CreateChannelAndConnectSuccessfully(). This will only work once per test
905 // case, but once should be enough.
906 virtual scoped_ptr<WebSocketEventInterface> CreateEventInterface() OVERRIDE {
907 return scoped_ptr<WebSocketEventInterface>(event_interface_.release());
910 scoped_ptr<MockWebSocketEventInterface> event_interface_;
913 // Base class for tests which verify that WebSocketStream methods are called
914 // appropriately by using a MockWebSocketStream.
915 class WebSocketChannelStreamTest : public WebSocketChannelTest {
916 protected:
917 WebSocketChannelStreamTest()
918 : mock_stream_(new StrictMock<MockWebSocketStream>) {}
920 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
921 set_stream(mock_stream_.Pass());
922 WebSocketChannelTest::CreateChannelAndConnectSuccessfully();
925 scoped_ptr<MockWebSocketStream> mock_stream_;
928 // Simple test that everything that should be passed to the creator function is
929 // passed to the creator function.
930 TEST_F(WebSocketChannelTest, EverythingIsPassedToTheCreatorFunction) {
931 connect_data_.socket_url = GURL("ws://example.com/test");
932 connect_data_.origin = GURL("http://example.com/test");
933 connect_data_.requested_subprotocols.push_back("Sinbad");
935 CreateChannelAndConnect();
937 const ArgumentCopyingWebSocketStreamCreator& actual = connect_data_.creator;
939 EXPECT_EQ(&connect_data_.url_request_context, actual.url_request_context);
941 EXPECT_EQ(connect_data_.socket_url, actual.socket_url);
942 EXPECT_EQ(connect_data_.requested_subprotocols,
943 actual.requested_subprotocols);
944 EXPECT_EQ(connect_data_.origin, actual.origin);
947 // Verify that calling SendFlowControl before the connection is established does
948 // not cause a crash.
949 TEST_F(WebSocketChannelTest, SendFlowControlDuringHandshakeOkay) {
950 CreateChannelAndConnect();
951 ASSERT_TRUE(channel_);
952 channel_->SendFlowControl(65536);
955 // Any WebSocketEventInterface methods can delete the WebSocketChannel and
956 // return CHANNEL_DELETED. The WebSocketChannelDeletingTests are intended to
957 // verify that there are no use-after-free bugs when this happens. Problems will
958 // probably only be found when running under Address Sanitizer or a similar
959 // tool.
960 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseFail) {
961 CreateChannelAndConnect();
962 EXPECT_TRUE(channel_);
963 connect_data_.creator.connect_delegate->OnFailure("bye");
964 EXPECT_EQ(NULL, channel_.get());
967 // Deletion is possible (due to IPC failure) even if the connect succeeds.
968 TEST_F(WebSocketChannelDeletingTest, OnAddChannelResponseSuccess) {
969 CreateChannelAndConnectSuccessfully();
970 EXPECT_EQ(NULL, channel_.get());
973 TEST_F(WebSocketChannelDeletingTest, OnDataFrameSync) {
974 scoped_ptr<ReadableFakeWebSocketStream> stream(
975 new ReadableFakeWebSocketStream);
976 static const InitFrame frames[] = {
977 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
978 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
979 set_stream(stream.Pass());
980 deleting_ = EVENT_ON_DATA_FRAME;
982 CreateChannelAndConnectSuccessfully();
983 EXPECT_EQ(NULL, channel_.get());
986 TEST_F(WebSocketChannelDeletingTest, OnDataFrameAsync) {
987 scoped_ptr<ReadableFakeWebSocketStream> stream(
988 new ReadableFakeWebSocketStream);
989 static const InitFrame frames[] = {
990 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
991 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
992 set_stream(stream.Pass());
993 deleting_ = EVENT_ON_DATA_FRAME;
995 CreateChannelAndConnectSuccessfully();
996 EXPECT_TRUE(channel_);
997 base::MessageLoop::current()->RunUntilIdle();
998 EXPECT_EQ(NULL, channel_.get());
1001 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterConnect) {
1002 deleting_ = EVENT_ON_FLOW_CONTROL;
1004 CreateChannelAndConnectSuccessfully();
1005 EXPECT_EQ(NULL, channel_.get());
1008 TEST_F(WebSocketChannelDeletingTest, OnFlowControlAfterSend) {
1009 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1010 // Avoid deleting the channel yet.
1011 deleting_ = EVENT_ON_FAIL_CHANNEL | EVENT_ON_DROP_CHANNEL;
1012 CreateChannelAndConnectSuccessfully();
1013 ASSERT_TRUE(channel_);
1014 deleting_ = EVENT_ON_FLOW_CONTROL;
1015 channel_->SendFrame(true,
1016 WebSocketFrameHeader::kOpCodeText,
1017 std::vector<char>(kDefaultInitialQuota, 'B'));
1018 EXPECT_EQ(NULL, channel_.get());
1021 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeSync) {
1022 scoped_ptr<ReadableFakeWebSocketStream> stream(
1023 new ReadableFakeWebSocketStream);
1024 static const InitFrame frames[] = {
1025 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1026 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1027 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1028 set_stream(stream.Pass());
1029 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1030 CreateChannelAndConnectSuccessfully();
1031 EXPECT_EQ(NULL, channel_.get());
1034 TEST_F(WebSocketChannelDeletingTest, OnClosingHandshakeAsync) {
1035 scoped_ptr<ReadableFakeWebSocketStream> stream(
1036 new ReadableFakeWebSocketStream);
1037 static const InitFrame frames[] = {
1038 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1039 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
1040 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1041 set_stream(stream.Pass());
1042 deleting_ = EVENT_ON_CLOSING_HANDSHAKE;
1043 CreateChannelAndConnectSuccessfully();
1044 ASSERT_TRUE(channel_);
1045 base::MessageLoop::current()->RunUntilIdle();
1046 EXPECT_EQ(NULL, channel_.get());
1049 TEST_F(WebSocketChannelDeletingTest, OnDropChannelWriteError) {
1050 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1051 deleting_ = EVENT_ON_DROP_CHANNEL;
1052 CreateChannelAndConnectSuccessfully();
1053 ASSERT_TRUE(channel_);
1054 channel_->SendFrame(
1055 true, WebSocketFrameHeader::kOpCodeText, AsVector("this will fail"));
1056 EXPECT_EQ(NULL, channel_.get());
1059 TEST_F(WebSocketChannelDeletingTest, OnDropChannelReadError) {
1060 scoped_ptr<ReadableFakeWebSocketStream> stream(
1061 new ReadableFakeWebSocketStream);
1062 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1063 ERR_FAILED);
1064 set_stream(stream.Pass());
1065 deleting_ = EVENT_ON_DROP_CHANNEL;
1066 CreateChannelAndConnectSuccessfully();
1067 ASSERT_TRUE(channel_);
1068 base::MessageLoop::current()->RunUntilIdle();
1069 EXPECT_EQ(NULL, channel_.get());
1072 TEST_F(WebSocketChannelDeletingTest, OnNotifyStartOpeningHandshakeError) {
1073 scoped_ptr<ReadableFakeWebSocketStream> stream(
1074 new ReadableFakeWebSocketStream);
1075 static const InitFrame frames[] = {
1076 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1077 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1078 set_stream(stream.Pass());
1079 deleting_ = EVENT_ON_START_OPENING_HANDSHAKE;
1081 CreateChannelAndConnectSuccessfully();
1082 ASSERT_TRUE(channel_);
1083 channel_->OnStartOpeningHandshake(scoped_ptr<WebSocketHandshakeRequestInfo>(
1084 new WebSocketHandshakeRequestInfo(GURL("http://www.example.com/"),
1085 base::Time())));
1086 base::MessageLoop::current()->RunUntilIdle();
1087 EXPECT_EQ(NULL, channel_.get());
1090 TEST_F(WebSocketChannelDeletingTest, OnNotifyFinishOpeningHandshakeError) {
1091 scoped_ptr<ReadableFakeWebSocketStream> stream(
1092 new ReadableFakeWebSocketStream);
1093 static const InitFrame frames[] = {
1094 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1095 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1096 set_stream(stream.Pass());
1097 deleting_ = EVENT_ON_FINISH_OPENING_HANDSHAKE;
1099 CreateChannelAndConnectSuccessfully();
1100 ASSERT_TRUE(channel_);
1101 scoped_refptr<HttpResponseHeaders> response_headers(
1102 new HttpResponseHeaders(""));
1103 channel_->OnFinishOpeningHandshake(scoped_ptr<WebSocketHandshakeResponseInfo>(
1104 new WebSocketHandshakeResponseInfo(GURL("http://www.example.com/"),
1105 200,
1106 "OK",
1107 response_headers,
1108 base::Time())));
1109 base::MessageLoop::current()->RunUntilIdle();
1110 EXPECT_EQ(NULL, channel_.get());
1113 TEST_F(WebSocketChannelDeletingTest, FailChannelInSendFrame) {
1114 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1115 deleting_ = EVENT_ON_FAIL_CHANNEL;
1116 CreateChannelAndConnectSuccessfully();
1117 ASSERT_TRUE(channel_);
1118 channel_->SendFrame(true,
1119 WebSocketFrameHeader::kOpCodeText,
1120 std::vector<char>(kDefaultInitialQuota * 2, 'T'));
1121 EXPECT_EQ(NULL, channel_.get());
1124 TEST_F(WebSocketChannelDeletingTest, FailChannelInOnReadDone) {
1125 scoped_ptr<ReadableFakeWebSocketStream> stream(
1126 new ReadableFakeWebSocketStream);
1127 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1128 ERR_WS_PROTOCOL_ERROR);
1129 set_stream(stream.Pass());
1130 deleting_ = EVENT_ON_FAIL_CHANNEL;
1131 CreateChannelAndConnectSuccessfully();
1132 ASSERT_TRUE(channel_);
1133 base::MessageLoop::current()->RunUntilIdle();
1134 EXPECT_EQ(NULL, channel_.get());
1137 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToMaskedFrame) {
1138 scoped_ptr<ReadableFakeWebSocketStream> stream(
1139 new ReadableFakeWebSocketStream);
1140 static const InitFrame frames[] = {
1141 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1142 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1143 set_stream(stream.Pass());
1144 deleting_ = EVENT_ON_FAIL_CHANNEL;
1146 CreateChannelAndConnectSuccessfully();
1147 EXPECT_EQ(NULL, channel_.get());
1150 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrame) {
1151 scoped_ptr<ReadableFakeWebSocketStream> stream(
1152 new ReadableFakeWebSocketStream);
1153 static const InitFrame frames[] = {
1154 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1155 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1156 set_stream(stream.Pass());
1157 deleting_ = EVENT_ON_FAIL_CHANNEL;
1159 CreateChannelAndConnectSuccessfully();
1160 EXPECT_EQ(NULL, channel_.get());
1163 // Version of above test with NULL data.
1164 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToBadControlFrameNull) {
1165 scoped_ptr<ReadableFakeWebSocketStream> stream(
1166 new ReadableFakeWebSocketStream);
1167 static const InitFrame frames[] = {
1168 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1169 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1170 set_stream(stream.Pass());
1171 deleting_ = EVENT_ON_FAIL_CHANNEL;
1173 CreateChannelAndConnectSuccessfully();
1174 EXPECT_EQ(NULL, channel_.get());
1177 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterClose) {
1178 scoped_ptr<ReadableFakeWebSocketStream> stream(
1179 new ReadableFakeWebSocketStream);
1180 static const InitFrame frames[] = {
1181 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1182 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1183 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1184 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1185 set_stream(stream.Pass());
1186 deleting_ = EVENT_ON_FAIL_CHANNEL;
1188 CreateChannelAndConnectSuccessfully();
1189 EXPECT_EQ(NULL, channel_.get());
1192 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToPongAfterCloseNull) {
1193 scoped_ptr<ReadableFakeWebSocketStream> stream(
1194 new ReadableFakeWebSocketStream);
1195 static const InitFrame frames[] = {
1196 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1197 CLOSE_DATA(NORMAL_CLOSURE, "Success")},
1198 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1199 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1200 set_stream(stream.Pass());
1201 deleting_ = EVENT_ON_FAIL_CHANNEL;
1203 CreateChannelAndConnectSuccessfully();
1204 EXPECT_EQ(NULL, channel_.get());
1207 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCode) {
1208 scoped_ptr<ReadableFakeWebSocketStream> stream(
1209 new ReadableFakeWebSocketStream);
1210 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, ""}};
1211 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1212 set_stream(stream.Pass());
1213 deleting_ = EVENT_ON_FAIL_CHANNEL;
1215 CreateChannelAndConnectSuccessfully();
1216 EXPECT_EQ(NULL, channel_.get());
1219 TEST_F(WebSocketChannelDeletingTest, FailChannelDueToUnknownOpCodeNull) {
1220 scoped_ptr<ReadableFakeWebSocketStream> stream(
1221 new ReadableFakeWebSocketStream);
1222 static const InitFrame frames[] = {{FINAL_FRAME, 0x7, NOT_MASKED, NULL}};
1223 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1224 set_stream(stream.Pass());
1225 deleting_ = EVENT_ON_FAIL_CHANNEL;
1227 CreateChannelAndConnectSuccessfully();
1228 EXPECT_EQ(NULL, channel_.get());
1231 TEST_F(WebSocketChannelDeletingTest, FailChannelDueInvalidCloseReason) {
1232 scoped_ptr<ReadableFakeWebSocketStream> stream(
1233 new ReadableFakeWebSocketStream);
1234 static const InitFrame frames[] = {
1235 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1236 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
1237 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1238 set_stream(stream.Pass());
1239 deleting_ = EVENT_ON_FAIL_CHANNEL;
1241 CreateChannelAndConnectSuccessfully();
1242 EXPECT_EQ(NULL, channel_.get());
1245 TEST_F(WebSocketChannelEventInterfaceTest, ConnectSuccessReported) {
1246 // false means success.
1247 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "", ""));
1248 // OnFlowControl is always called immediately after connect to provide initial
1249 // quota to the renderer.
1250 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1252 CreateChannelAndConnect();
1254 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
1257 TEST_F(WebSocketChannelEventInterfaceTest, ConnectFailureReported) {
1258 EXPECT_CALL(*event_interface_, OnFailChannel("hello"));
1260 CreateChannelAndConnect();
1262 connect_data_.creator.connect_delegate->OnFailure("hello");
1265 TEST_F(WebSocketChannelEventInterfaceTest, NonWebSocketSchemeRejected) {
1266 EXPECT_CALL(*event_interface_, OnAddChannelResponse(true, "", ""));
1267 connect_data_.socket_url = GURL("http://www.google.com/");
1268 CreateChannelAndConnect();
1271 TEST_F(WebSocketChannelEventInterfaceTest, ProtocolPassed) {
1272 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, "Bob", ""));
1273 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1275 CreateChannelAndConnect();
1277 connect_data_.creator.connect_delegate->OnSuccess(
1278 scoped_ptr<WebSocketStream>(new FakeWebSocketStream("Bob", "")));
1281 TEST_F(WebSocketChannelEventInterfaceTest, ExtensionsPassed) {
1282 EXPECT_CALL(*event_interface_,
1283 OnAddChannelResponse(false, "", "extension1, extension2"));
1284 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1286 CreateChannelAndConnect();
1288 connect_data_.creator.connect_delegate->OnSuccess(scoped_ptr<WebSocketStream>(
1289 new FakeWebSocketStream("", "extension1, extension2")));
1292 // The first frames from the server can arrive together with the handshake, in
1293 // which case they will be available as soon as ReadFrames() is called the first
1294 // time.
1295 TEST_F(WebSocketChannelEventInterfaceTest, DataLeftFromHandshake) {
1296 scoped_ptr<ReadableFakeWebSocketStream> stream(
1297 new ReadableFakeWebSocketStream);
1298 static const InitFrame frames[] = {
1299 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1300 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1301 set_stream(stream.Pass());
1303 InSequence s;
1304 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1305 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1306 EXPECT_CALL(
1307 *event_interface_,
1308 OnDataFrame(
1309 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1312 CreateChannelAndConnectSuccessfully();
1315 // A remote server could accept the handshake, but then immediately send a
1316 // Close frame.
1317 TEST_F(WebSocketChannelEventInterfaceTest, CloseAfterHandshake) {
1318 scoped_ptr<ReadableFakeWebSocketStream> stream(
1319 new ReadableFakeWebSocketStream);
1320 static const InitFrame frames[] = {
1321 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
1322 NOT_MASKED, CLOSE_DATA(SERVER_ERROR, "Internal Server Error")}};
1323 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1324 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1325 ERR_CONNECTION_CLOSED);
1326 set_stream(stream.Pass());
1328 InSequence s;
1329 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1330 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1331 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1332 EXPECT_CALL(*event_interface_,
1333 OnDropChannel(kWebSocketErrorInternalServerError,
1334 "Internal Server Error"));
1337 CreateChannelAndConnectSuccessfully();
1340 // A remote server could close the connection immediately after sending the
1341 // handshake response (most likely a bug in the server).
1342 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionCloseAfterHandshake) {
1343 scoped_ptr<ReadableFakeWebSocketStream> stream(
1344 new ReadableFakeWebSocketStream);
1345 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1346 ERR_CONNECTION_CLOSED);
1347 set_stream(stream.Pass());
1349 InSequence s;
1350 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1351 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1352 EXPECT_CALL(*event_interface_,
1353 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1356 CreateChannelAndConnectSuccessfully();
1359 TEST_F(WebSocketChannelEventInterfaceTest, NormalAsyncRead) {
1360 scoped_ptr<ReadableFakeWebSocketStream> stream(
1361 new ReadableFakeWebSocketStream);
1362 static const InitFrame frames[] = {
1363 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1364 // We use this checkpoint object to verify that the callback isn't called
1365 // until we expect it to be.
1366 Checkpoint checkpoint;
1367 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1368 set_stream(stream.Pass());
1370 InSequence s;
1371 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1372 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1373 EXPECT_CALL(checkpoint, Call(1));
1374 EXPECT_CALL(
1375 *event_interface_,
1376 OnDataFrame(
1377 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1378 EXPECT_CALL(checkpoint, Call(2));
1381 CreateChannelAndConnectSuccessfully();
1382 checkpoint.Call(1);
1383 base::MessageLoop::current()->RunUntilIdle();
1384 checkpoint.Call(2);
1387 // Extra data can arrive while a read is being processed, resulting in the next
1388 // read completing synchronously.
1389 TEST_F(WebSocketChannelEventInterfaceTest, AsyncThenSyncRead) {
1390 scoped_ptr<ReadableFakeWebSocketStream> stream(
1391 new ReadableFakeWebSocketStream);
1392 static const InitFrame frames1[] = {
1393 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "HELLO"}};
1394 static const InitFrame frames2[] = {
1395 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "WORLD"}};
1396 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1397 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames2);
1398 set_stream(stream.Pass());
1400 InSequence s;
1401 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1402 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1403 EXPECT_CALL(
1404 *event_interface_,
1405 OnDataFrame(
1406 true, WebSocketFrameHeader::kOpCodeText, AsVector("HELLO")));
1407 EXPECT_CALL(
1408 *event_interface_,
1409 OnDataFrame(
1410 true, WebSocketFrameHeader::kOpCodeText, AsVector("WORLD")));
1413 CreateChannelAndConnectSuccessfully();
1414 base::MessageLoop::current()->RunUntilIdle();
1417 // Data frames are delivered the same regardless of how many reads they arrive
1418 // as.
1419 TEST_F(WebSocketChannelEventInterfaceTest, FragmentedMessage) {
1420 scoped_ptr<ReadableFakeWebSocketStream> stream(
1421 new ReadableFakeWebSocketStream);
1422 // Here we have one message which arrived in five frames split across three
1423 // reads. It may have been reframed on arrival, but this class doesn't care
1424 // about that.
1425 static const InitFrame frames1[] = {
1426 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "THREE"},
1427 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1428 NOT_MASKED, " "}};
1429 static const InitFrame frames2[] = {
1430 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1431 NOT_MASKED, "SMALL"}};
1432 static const InitFrame frames3[] = {
1433 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1434 NOT_MASKED, " "},
1435 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1436 NOT_MASKED, "FRAMES"}};
1437 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1438 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1439 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1440 set_stream(stream.Pass());
1442 InSequence s;
1443 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1444 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1445 EXPECT_CALL(
1446 *event_interface_,
1447 OnDataFrame(
1448 false, WebSocketFrameHeader::kOpCodeText, AsVector("THREE")));
1449 EXPECT_CALL(
1450 *event_interface_,
1451 OnDataFrame(
1452 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1453 EXPECT_CALL(*event_interface_,
1454 OnDataFrame(false,
1455 WebSocketFrameHeader::kOpCodeContinuation,
1456 AsVector("SMALL")));
1457 EXPECT_CALL(
1458 *event_interface_,
1459 OnDataFrame(
1460 false, WebSocketFrameHeader::kOpCodeContinuation, AsVector(" ")));
1461 EXPECT_CALL(*event_interface_,
1462 OnDataFrame(true,
1463 WebSocketFrameHeader::kOpCodeContinuation,
1464 AsVector("FRAMES")));
1467 CreateChannelAndConnectSuccessfully();
1468 base::MessageLoop::current()->RunUntilIdle();
1471 // A message can consist of one frame with NULL payload.
1472 TEST_F(WebSocketChannelEventInterfaceTest, NullMessage) {
1473 scoped_ptr<ReadableFakeWebSocketStream> stream(
1474 new ReadableFakeWebSocketStream);
1475 static const InitFrame frames[] = {
1476 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, NULL}};
1477 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1478 set_stream(stream.Pass());
1479 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1480 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1481 EXPECT_CALL(
1482 *event_interface_,
1483 OnDataFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("")));
1484 CreateChannelAndConnectSuccessfully();
1487 // A control frame is not permitted to be split into multiple frames. RFC6455
1488 // 5.5 "All control frames ... MUST NOT be fragmented."
1489 TEST_F(WebSocketChannelEventInterfaceTest, MultiFrameControlMessageIsRejected) {
1490 scoped_ptr<ReadableFakeWebSocketStream> stream(
1491 new ReadableFakeWebSocketStream);
1492 static const InitFrame frames[] = {
1493 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, "Pi"},
1494 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1495 NOT_MASKED, "ng"}};
1496 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1497 set_stream(stream.Pass());
1499 InSequence s;
1500 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1501 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1502 EXPECT_CALL(*event_interface_,
1503 OnFailChannel("Received fragmented control frame: opcode = 9"));
1506 CreateChannelAndConnectSuccessfully();
1507 base::MessageLoop::current()->RunUntilIdle();
1510 // Connection closed by the remote host without a closing handshake.
1511 TEST_F(WebSocketChannelEventInterfaceTest, AsyncAbnormalClosure) {
1512 scoped_ptr<ReadableFakeWebSocketStream> stream(
1513 new ReadableFakeWebSocketStream);
1514 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1515 ERR_CONNECTION_CLOSED);
1516 set_stream(stream.Pass());
1518 InSequence s;
1519 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1520 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1521 EXPECT_CALL(*event_interface_,
1522 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1525 CreateChannelAndConnectSuccessfully();
1526 base::MessageLoop::current()->RunUntilIdle();
1529 // A connection reset should produce the same event as an unexpected closure.
1530 TEST_F(WebSocketChannelEventInterfaceTest, ConnectionReset) {
1531 scoped_ptr<ReadableFakeWebSocketStream> stream(
1532 new ReadableFakeWebSocketStream);
1533 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1534 ERR_CONNECTION_RESET);
1535 set_stream(stream.Pass());
1537 InSequence s;
1538 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1539 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1540 EXPECT_CALL(*event_interface_,
1541 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1544 CreateChannelAndConnectSuccessfully();
1545 base::MessageLoop::current()->RunUntilIdle();
1548 // RFC6455 5.1 "A client MUST close a connection if it detects a masked frame."
1549 TEST_F(WebSocketChannelEventInterfaceTest, MaskedFramesAreRejected) {
1550 scoped_ptr<ReadableFakeWebSocketStream> stream(
1551 new ReadableFakeWebSocketStream);
1552 static const InitFrame frames[] = {
1553 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"}};
1555 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1556 set_stream(stream.Pass());
1558 InSequence s;
1559 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1560 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1561 EXPECT_CALL(
1562 *event_interface_,
1563 OnFailChannel(
1564 "A server must not mask any frames that it sends to the client."));
1567 CreateChannelAndConnectSuccessfully();
1568 base::MessageLoop::current()->RunUntilIdle();
1571 // RFC6455 5.2 "If an unknown opcode is received, the receiving endpoint MUST
1572 // _Fail the WebSocket Connection_."
1573 TEST_F(WebSocketChannelEventInterfaceTest, UnknownOpCodeIsRejected) {
1574 scoped_ptr<ReadableFakeWebSocketStream> stream(
1575 new ReadableFakeWebSocketStream);
1576 static const InitFrame frames[] = {{FINAL_FRAME, 4, NOT_MASKED, "HELLO"}};
1578 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1579 set_stream(stream.Pass());
1581 InSequence s;
1582 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1583 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1584 EXPECT_CALL(*event_interface_,
1585 OnFailChannel("Unrecognized frame opcode: 4"));
1588 CreateChannelAndConnectSuccessfully();
1589 base::MessageLoop::current()->RunUntilIdle();
1592 // RFC6455 5.4 "Control frames ... MAY be injected in the middle of a
1593 // fragmented message."
1594 TEST_F(WebSocketChannelEventInterfaceTest, ControlFrameInDataMessage) {
1595 scoped_ptr<ReadableFakeWebSocketStream> stream(
1596 new ReadableFakeWebSocketStream);
1597 // We have one message of type Text split into two frames. In the middle is a
1598 // control message of type Pong.
1599 static const InitFrame frames1[] = {
1600 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
1601 NOT_MASKED, "SPLIT "}};
1602 static const InitFrame frames2[] = {
1603 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, ""}};
1604 static const InitFrame frames3[] = {
1605 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
1606 NOT_MASKED, "MESSAGE"}};
1607 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames1);
1608 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames2);
1609 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames3);
1610 set_stream(stream.Pass());
1612 InSequence s;
1613 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1614 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1615 EXPECT_CALL(
1616 *event_interface_,
1617 OnDataFrame(
1618 false, WebSocketFrameHeader::kOpCodeText, AsVector("SPLIT ")));
1619 EXPECT_CALL(*event_interface_,
1620 OnDataFrame(true,
1621 WebSocketFrameHeader::kOpCodeContinuation,
1622 AsVector("MESSAGE")));
1625 CreateChannelAndConnectSuccessfully();
1626 base::MessageLoop::current()->RunUntilIdle();
1629 // It seems redundant to repeat the entirety of the above test, so just test a
1630 // Pong with NULL data.
1631 TEST_F(WebSocketChannelEventInterfaceTest, PongWithNullData) {
1632 scoped_ptr<ReadableFakeWebSocketStream> stream(
1633 new ReadableFakeWebSocketStream);
1634 static const InitFrame frames[] = {
1635 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, NOT_MASKED, NULL}};
1636 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1637 set_stream(stream.Pass());
1638 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1639 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1641 CreateChannelAndConnectSuccessfully();
1642 base::MessageLoop::current()->RunUntilIdle();
1645 // If a frame has an invalid header, then the connection is closed and
1646 // subsequent frames must not trigger events.
1647 TEST_F(WebSocketChannelEventInterfaceTest, FrameAfterInvalidFrame) {
1648 scoped_ptr<ReadableFakeWebSocketStream> stream(
1649 new ReadableFakeWebSocketStream);
1650 static const InitFrame frames[] = {
1651 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "HELLO"},
1652 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, " WORLD"}};
1654 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
1655 set_stream(stream.Pass());
1657 InSequence s;
1658 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1659 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1660 EXPECT_CALL(
1661 *event_interface_,
1662 OnFailChannel(
1663 "A server must not mask any frames that it sends to the client."));
1666 CreateChannelAndConnectSuccessfully();
1667 base::MessageLoop::current()->RunUntilIdle();
1670 // If the renderer sends lots of small writes, we don't want to update the quota
1671 // for each one.
1672 TEST_F(WebSocketChannelEventInterfaceTest, SmallWriteDoesntUpdateQuota) {
1673 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1675 InSequence s;
1676 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1677 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1680 CreateChannelAndConnectSuccessfully();
1681 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("B"));
1684 // If we send enough to go below send_quota_low_water_mask_ we should get our
1685 // quota refreshed.
1686 TEST_F(WebSocketChannelEventInterfaceTest, LargeWriteUpdatesQuota) {
1687 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1688 // We use this checkpoint object to verify that the quota update comes after
1689 // the write.
1690 Checkpoint checkpoint;
1692 InSequence s;
1693 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1694 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1695 EXPECT_CALL(checkpoint, Call(1));
1696 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1697 EXPECT_CALL(checkpoint, Call(2));
1700 CreateChannelAndConnectSuccessfully();
1701 checkpoint.Call(1);
1702 channel_->SendFrame(true,
1703 WebSocketFrameHeader::kOpCodeText,
1704 std::vector<char>(kDefaultInitialQuota, 'B'));
1705 checkpoint.Call(2);
1708 // Verify that our quota actually is refreshed when we are told it is.
1709 TEST_F(WebSocketChannelEventInterfaceTest, QuotaReallyIsRefreshed) {
1710 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1711 Checkpoint checkpoint;
1713 InSequence s;
1714 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1715 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1716 EXPECT_CALL(checkpoint, Call(1));
1717 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1718 EXPECT_CALL(checkpoint, Call(2));
1719 // If quota was not really refreshed, we would get an OnDropChannel()
1720 // message.
1721 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1722 EXPECT_CALL(checkpoint, Call(3));
1725 CreateChannelAndConnectSuccessfully();
1726 checkpoint.Call(1);
1727 channel_->SendFrame(true,
1728 WebSocketFrameHeader::kOpCodeText,
1729 std::vector<char>(kDefaultQuotaRefreshTrigger, 'D'));
1730 checkpoint.Call(2);
1731 // We should have received more quota at this point.
1732 channel_->SendFrame(true,
1733 WebSocketFrameHeader::kOpCodeText,
1734 std::vector<char>(kDefaultQuotaRefreshTrigger, 'E'));
1735 checkpoint.Call(3);
1738 // If we send more than the available quota then the connection will be closed
1739 // with an error.
1740 TEST_F(WebSocketChannelEventInterfaceTest, WriteOverQuotaIsRejected) {
1741 set_stream(make_scoped_ptr(new WriteableFakeWebSocketStream));
1743 InSequence s;
1744 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1745 EXPECT_CALL(*event_interface_, OnFlowControl(kDefaultInitialQuota));
1746 EXPECT_CALL(*event_interface_, OnFailChannel("Send quota exceeded"));
1749 CreateChannelAndConnectSuccessfully();
1750 channel_->SendFrame(true,
1751 WebSocketFrameHeader::kOpCodeText,
1752 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
1755 // If a write fails, the channel is dropped.
1756 TEST_F(WebSocketChannelEventInterfaceTest, FailedWrite) {
1757 set_stream(make_scoped_ptr(new UnWriteableFakeWebSocketStream));
1758 Checkpoint checkpoint;
1760 InSequence s;
1761 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1762 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1763 EXPECT_CALL(checkpoint, Call(1));
1764 EXPECT_CALL(*event_interface_,
1765 OnDropChannel(kWebSocketErrorAbnormalClosure, _));
1766 EXPECT_CALL(checkpoint, Call(2));
1769 CreateChannelAndConnectSuccessfully();
1770 checkpoint.Call(1);
1772 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("H"));
1773 checkpoint.Call(2);
1776 // OnDropChannel() is called exactly once when StartClosingHandshake() is used.
1777 TEST_F(WebSocketChannelEventInterfaceTest, SendCloseDropsChannel) {
1778 set_stream(make_scoped_ptr(new EchoeyFakeWebSocketStream));
1780 InSequence s;
1781 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1782 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1783 EXPECT_CALL(*event_interface_,
1784 OnDropChannel(kWebSocketNormalClosure, "Fred"));
1787 CreateChannelAndConnectSuccessfully();
1789 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Fred");
1790 base::MessageLoop::current()->RunUntilIdle();
1793 // StartClosingHandshake() also works before connection completes, and calls
1794 // OnDropChannel.
1795 TEST_F(WebSocketChannelEventInterfaceTest, CloseDuringConnection) {
1796 EXPECT_CALL(*event_interface_,
1797 OnDropChannel(kWebSocketErrorAbnormalClosure, ""));
1799 CreateChannelAndConnect();
1800 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Joe");
1803 // OnDropChannel() is only called once when a write() on the socket triggers a
1804 // connection reset.
1805 TEST_F(WebSocketChannelEventInterfaceTest, OnDropChannelCalledOnce) {
1806 set_stream(make_scoped_ptr(new ResetOnWriteFakeWebSocketStream));
1807 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1808 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1810 EXPECT_CALL(*event_interface_,
1811 OnDropChannel(kWebSocketErrorAbnormalClosure, ""))
1812 .Times(1);
1814 CreateChannelAndConnectSuccessfully();
1816 channel_->SendFrame(true, WebSocketFrameHeader::kOpCodeText, AsVector("yt?"));
1817 base::MessageLoop::current()->RunUntilIdle();
1820 // When the remote server sends a Close frame with an empty payload,
1821 // WebSocketChannel should report code 1005, kWebSocketErrorNoStatusReceived.
1822 TEST_F(WebSocketChannelEventInterfaceTest, CloseWithNoPayloadGivesStatus1005) {
1823 scoped_ptr<ReadableFakeWebSocketStream> stream(
1824 new ReadableFakeWebSocketStream);
1825 static const InitFrame frames[] = {
1826 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
1827 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1828 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1829 ERR_CONNECTION_CLOSED);
1830 set_stream(stream.Pass());
1831 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1832 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1833 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1834 EXPECT_CALL(*event_interface_,
1835 OnDropChannel(kWebSocketErrorNoStatusReceived, _));
1837 CreateChannelAndConnectSuccessfully();
1840 // A version of the above test with NULL payload.
1841 TEST_F(WebSocketChannelEventInterfaceTest,
1842 CloseWithNullPayloadGivesStatus1005) {
1843 scoped_ptr<ReadableFakeWebSocketStream> stream(
1844 new ReadableFakeWebSocketStream);
1845 static const InitFrame frames[] = {
1846 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
1847 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1848 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1849 ERR_CONNECTION_CLOSED);
1850 set_stream(stream.Pass());
1851 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1852 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1853 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1854 EXPECT_CALL(*event_interface_,
1855 OnDropChannel(kWebSocketErrorNoStatusReceived, _));
1857 CreateChannelAndConnectSuccessfully();
1860 // If ReadFrames() returns ERR_WS_PROTOCOL_ERROR, then the connection must be
1861 // failed.
1862 TEST_F(WebSocketChannelEventInterfaceTest, SyncProtocolErrorGivesStatus1002) {
1863 scoped_ptr<ReadableFakeWebSocketStream> stream(
1864 new ReadableFakeWebSocketStream);
1865 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
1866 ERR_WS_PROTOCOL_ERROR);
1867 set_stream(stream.Pass());
1868 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1869 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1871 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1873 CreateChannelAndConnectSuccessfully();
1876 // Async version of above test.
1877 TEST_F(WebSocketChannelEventInterfaceTest, AsyncProtocolErrorGivesStatus1002) {
1878 scoped_ptr<ReadableFakeWebSocketStream> stream(
1879 new ReadableFakeWebSocketStream);
1880 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::ASYNC,
1881 ERR_WS_PROTOCOL_ERROR);
1882 set_stream(stream.Pass());
1883 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1884 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1886 EXPECT_CALL(*event_interface_, OnFailChannel("Invalid frame header"));
1888 CreateChannelAndConnectSuccessfully();
1889 base::MessageLoop::current()->RunUntilIdle();
1892 TEST_F(WebSocketChannelEventInterfaceTest, StartHandshakeRequest) {
1894 InSequence s;
1895 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1896 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1897 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1900 CreateChannelAndConnectSuccessfully();
1902 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1903 new WebSocketHandshakeRequestInfo(GURL("ws://www.example.com/"),
1904 base::Time()));
1905 connect_data_.creator.connect_delegate->OnStartOpeningHandshake(
1906 request_info.Pass());
1908 base::MessageLoop::current()->RunUntilIdle();
1911 TEST_F(WebSocketChannelEventInterfaceTest, FinishHandshakeRequest) {
1913 InSequence s;
1914 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1915 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1916 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1919 CreateChannelAndConnectSuccessfully();
1921 scoped_refptr<HttpResponseHeaders> response_headers(
1922 new HttpResponseHeaders(""));
1923 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1924 new WebSocketHandshakeResponseInfo(GURL("ws://www.example.com/"),
1925 200,
1926 "OK",
1927 response_headers,
1928 base::Time()));
1929 connect_data_.creator.connect_delegate->OnFinishOpeningHandshake(
1930 response_info.Pass());
1931 base::MessageLoop::current()->RunUntilIdle();
1934 TEST_F(WebSocketChannelEventInterfaceTest, FailJustAfterHandshake) {
1936 InSequence s;
1937 EXPECT_CALL(*event_interface_, OnStartOpeningHandshakeCalled());
1938 EXPECT_CALL(*event_interface_, OnFinishOpeningHandshakeCalled());
1939 EXPECT_CALL(*event_interface_, OnFailChannel("bye"));
1942 CreateChannelAndConnect();
1944 WebSocketStream::ConnectDelegate* connect_delegate =
1945 connect_data_.creator.connect_delegate.get();
1946 GURL url("ws://www.example.com/");
1947 scoped_ptr<WebSocketHandshakeRequestInfo> request_info(
1948 new WebSocketHandshakeRequestInfo(url, base::Time()));
1949 scoped_refptr<HttpResponseHeaders> response_headers(
1950 new HttpResponseHeaders(""));
1951 scoped_ptr<WebSocketHandshakeResponseInfo> response_info(
1952 new WebSocketHandshakeResponseInfo(url,
1953 200,
1954 "OK",
1955 response_headers,
1956 base::Time()));
1957 connect_delegate->OnStartOpeningHandshake(request_info.Pass());
1958 connect_delegate->OnFinishOpeningHandshake(response_info.Pass());
1960 connect_delegate->OnFailure("bye");
1961 base::MessageLoop::current()->RunUntilIdle();
1964 // Any frame after close is invalid. This test uses a Text frame. See also
1965 // test "PingAfterCloseIfRejected".
1966 TEST_F(WebSocketChannelEventInterfaceTest, DataAfterCloseIsRejected) {
1967 scoped_ptr<ReadableFakeWebSocketStream> stream(
1968 new ReadableFakeWebSocketStream);
1969 static const InitFrame frames[] = {
1970 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED,
1971 CLOSE_DATA(NORMAL_CLOSURE, "OK")},
1972 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, NOT_MASKED, "Payload"}};
1973 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1974 set_stream(stream.Pass());
1975 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1976 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1979 InSequence s;
1980 EXPECT_CALL(*event_interface_, OnClosingHandshake());
1981 EXPECT_CALL(*event_interface_,
1982 OnFailChannel("Data frame received after close"));
1985 CreateChannelAndConnectSuccessfully();
1988 // A Close frame with a one-byte payload elicits a specific console error
1989 // message.
1990 TEST_F(WebSocketChannelEventInterfaceTest, OneByteClosePayloadMessage) {
1991 scoped_ptr<ReadableFakeWebSocketStream> stream(
1992 new ReadableFakeWebSocketStream);
1993 static const InitFrame frames[] = {
1994 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, "\x03"}};
1995 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
1996 set_stream(stream.Pass());
1997 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
1998 EXPECT_CALL(*event_interface_, OnFlowControl(_));
1999 EXPECT_CALL(
2000 *event_interface_,
2001 OnFailChannel(
2002 "Received a broken close frame containing an invalid size body."));
2004 CreateChannelAndConnectSuccessfully();
2007 // A Close frame with a reserved status code also elicits a specific console
2008 // error message.
2009 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadReservedStatusMessage) {
2010 scoped_ptr<ReadableFakeWebSocketStream> stream(
2011 new ReadableFakeWebSocketStream);
2012 static const InitFrame frames[] = {
2013 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2014 NOT_MASKED, CLOSE_DATA(ABNORMAL_CLOSURE, "Not valid on wire")}};
2015 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2016 set_stream(stream.Pass());
2017 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2018 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2019 EXPECT_CALL(
2020 *event_interface_,
2021 OnFailChannel(
2022 "Received a broken close frame containing a reserved status code."));
2024 CreateChannelAndConnectSuccessfully();
2027 // A Close frame with invalid UTF-8 also elicits a specific console error
2028 // message.
2029 TEST_F(WebSocketChannelEventInterfaceTest, ClosePayloadInvalidReason) {
2030 scoped_ptr<ReadableFakeWebSocketStream> stream(
2031 new ReadableFakeWebSocketStream);
2032 static const InitFrame frames[] = {
2033 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2034 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2035 stream->PrepareReadFrames(ReadableFakeWebSocketStream::SYNC, OK, frames);
2036 set_stream(stream.Pass());
2037 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2038 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2039 EXPECT_CALL(
2040 *event_interface_,
2041 OnFailChannel(
2042 "Received a broken close frame containing invalid UTF-8."));
2044 CreateChannelAndConnectSuccessfully();
2047 // The closing handshake times out and sends an OnDropChannel event if no
2048 // response to the client Close message is received.
2049 TEST_F(WebSocketChannelEventInterfaceTest,
2050 ClientInitiatedClosingHandshakeTimesOut) {
2051 scoped_ptr<ReadableFakeWebSocketStream> stream(
2052 new ReadableFakeWebSocketStream);
2053 stream->PrepareReadFramesError(ReadableFakeWebSocketStream::SYNC,
2054 ERR_IO_PENDING);
2055 set_stream(stream.Pass());
2056 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2057 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2058 // This checkpoint object verifies that the OnDropChannel message comes after
2059 // the timeout.
2060 Checkpoint checkpoint;
2061 TestClosure completion;
2063 InSequence s;
2064 EXPECT_CALL(checkpoint, Call(1));
2065 EXPECT_CALL(*event_interface_,
2066 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
2067 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2069 CreateChannelAndConnectSuccessfully();
2070 // OneShotTimer is not very friendly to testing; there is no apparent way to
2071 // set an expectation on it. Instead the tests need to infer that the timeout
2072 // was fired by the behaviour of the WebSocketChannel object.
2073 channel_->SetClosingHandshakeTimeoutForTesting(
2074 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2075 channel_->StartClosingHandshake(kWebSocketNormalClosure, "");
2076 checkpoint.Call(1);
2077 completion.WaitForResult();
2080 // The closing handshake times out and sends an OnDropChannel event if a Close
2081 // message is received but the connection isn't closed by the remote host.
2082 TEST_F(WebSocketChannelEventInterfaceTest,
2083 ServerInitiatedClosingHandshakeTimesOut) {
2084 scoped_ptr<ReadableFakeWebSocketStream> stream(
2085 new ReadableFakeWebSocketStream);
2086 static const InitFrame frames[] = {
2087 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2088 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2089 stream->PrepareReadFrames(ReadableFakeWebSocketStream::ASYNC, OK, frames);
2090 set_stream(stream.Pass());
2091 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2092 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2093 Checkpoint checkpoint;
2094 TestClosure completion;
2096 InSequence s;
2097 EXPECT_CALL(checkpoint, Call(1));
2098 EXPECT_CALL(*event_interface_, OnClosingHandshake());
2099 EXPECT_CALL(*event_interface_,
2100 OnDropChannel(kWebSocketErrorAbnormalClosure, _))
2101 .WillOnce(InvokeClosureReturnDeleted(completion.closure()));
2103 CreateChannelAndConnectSuccessfully();
2104 channel_->SetClosingHandshakeTimeoutForTesting(
2105 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2106 checkpoint.Call(1);
2107 completion.WaitForResult();
2110 // RFC6455 5.1 "a client MUST mask all frames that it sends to the server".
2111 // WebSocketChannel actually only sets the mask bit in the header, it doesn't
2112 // perform masking itself (not all transports actually use masking).
2113 TEST_F(WebSocketChannelStreamTest, SentFramesAreMasked) {
2114 static const InitFrame expected[] = {
2115 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText,
2116 MASKED, "NEEDS MASKING"}};
2117 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2118 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2119 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2120 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2121 .WillOnce(Return(OK));
2123 CreateChannelAndConnectSuccessfully();
2124 channel_->SendFrame(
2125 true, WebSocketFrameHeader::kOpCodeText, AsVector("NEEDS MASKING"));
2128 // RFC6455 5.5.1 "The application MUST NOT send any more data frames after
2129 // sending a Close frame."
2130 TEST_F(WebSocketChannelStreamTest, NothingIsSentAfterClose) {
2131 static const InitFrame expected[] = {
2132 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2133 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Success")}};
2134 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2135 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2136 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2137 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2138 .WillOnce(Return(OK));
2140 CreateChannelAndConnectSuccessfully();
2141 channel_->StartClosingHandshake(1000, "Success");
2142 channel_->SendFrame(
2143 true, WebSocketFrameHeader::kOpCodeText, AsVector("SHOULD BE IGNORED"));
2146 // RFC6455 5.5.1 "If an endpoint receives a Close frame and did not previously
2147 // send a Close frame, the endpoint MUST send a Close frame in response."
2148 TEST_F(WebSocketChannelStreamTest, CloseIsEchoedBack) {
2149 static const InitFrame frames[] = {
2150 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2151 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2152 static const InitFrame expected[] = {
2153 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2154 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2155 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2156 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2157 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2158 .WillOnce(ReturnFrames(&frames))
2159 .WillRepeatedly(Return(ERR_IO_PENDING));
2160 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2161 .WillOnce(Return(OK));
2163 CreateChannelAndConnectSuccessfully();
2166 // The converse of the above case; after sending a Close frame, we should not
2167 // send another one.
2168 TEST_F(WebSocketChannelStreamTest, CloseOnlySentOnce) {
2169 static const InitFrame expected[] = {
2170 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2171 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2172 static const InitFrame frames_init[] = {
2173 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2174 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "Close")}};
2176 // We store the parameters that were passed to ReadFrames() so that we can
2177 // call them explicitly later.
2178 CompletionCallback read_callback;
2179 ScopedVector<WebSocketFrame>* frames = NULL;
2181 // These are not interesting.
2182 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2183 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2185 // Use a checkpoint to make the ordering of events clearer.
2186 Checkpoint checkpoint;
2188 InSequence s;
2189 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2190 .WillOnce(DoAll(SaveArg<0>(&frames),
2191 SaveArg<1>(&read_callback),
2192 Return(ERR_IO_PENDING)));
2193 EXPECT_CALL(checkpoint, Call(1));
2194 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2195 .WillOnce(Return(OK));
2196 EXPECT_CALL(checkpoint, Call(2));
2197 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2198 .WillOnce(Return(ERR_IO_PENDING));
2199 EXPECT_CALL(checkpoint, Call(3));
2200 // WriteFrames() must not be called again. GoogleMock will ensure that the
2201 // test fails if it is.
2204 CreateChannelAndConnectSuccessfully();
2205 checkpoint.Call(1);
2206 channel_->StartClosingHandshake(kWebSocketNormalClosure, "Close");
2207 checkpoint.Call(2);
2209 *frames = CreateFrameVector(frames_init);
2210 read_callback.Run(OK);
2211 checkpoint.Call(3);
2214 // Invalid close status codes should not be sent on the network.
2215 TEST_F(WebSocketChannelStreamTest, InvalidCloseStatusCodeNotSent) {
2216 static const InitFrame expected[] = {
2217 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2218 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2220 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2221 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2222 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2223 .WillOnce(Return(ERR_IO_PENDING));
2225 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2227 CreateChannelAndConnectSuccessfully();
2228 channel_->StartClosingHandshake(999, "");
2231 // A Close frame with a reason longer than 123 bytes cannot be sent on the
2232 // network.
2233 TEST_F(WebSocketChannelStreamTest, LongCloseReasonNotSent) {
2234 static const InitFrame expected[] = {
2235 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2236 MASKED, CLOSE_DATA(SERVER_ERROR, "")}};
2238 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2239 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2240 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2241 .WillOnce(Return(ERR_IO_PENDING));
2243 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _));
2245 CreateChannelAndConnectSuccessfully();
2246 channel_->StartClosingHandshake(1000, std::string(124, 'A'));
2249 // We generate code 1005, kWebSocketErrorNoStatusReceived, when there is no
2250 // status in the Close message from the other side. Code 1005 is not allowed to
2251 // appear on the wire, so we should not echo it back. See test
2252 // CloseWithNoPayloadGivesStatus1005, above, for confirmation that code 1005 is
2253 // correctly generated internally.
2254 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoed) {
2255 static const InitFrame frames[] = {
2256 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, ""}};
2257 static const InitFrame expected[] = {
2258 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2259 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2260 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2261 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2262 .WillOnce(ReturnFrames(&frames))
2263 .WillRepeatedly(Return(ERR_IO_PENDING));
2264 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2265 .WillOnce(Return(OK));
2267 CreateChannelAndConnectSuccessfully();
2270 TEST_F(WebSocketChannelStreamTest, Code1005IsNotEchoedNull) {
2271 static const InitFrame frames[] = {
2272 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, NOT_MASKED, NULL}};
2273 static const InitFrame expected[] = {
2274 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose, MASKED, ""}};
2275 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2276 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2277 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2278 .WillOnce(ReturnFrames(&frames))
2279 .WillRepeatedly(Return(ERR_IO_PENDING));
2280 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2281 .WillOnce(Return(OK));
2283 CreateChannelAndConnectSuccessfully();
2286 // Receiving an invalid UTF-8 payload in a Close frame causes us to fail the
2287 // connection.
2288 TEST_F(WebSocketChannelStreamTest, CloseFrameInvalidUtf8) {
2289 static const InitFrame frames[] = {
2290 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2291 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "\xFF")}};
2292 static const InitFrame expected[] = {
2293 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2294 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "Invalid UTF-8 in Close frame")}};
2296 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2297 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2298 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2299 .WillOnce(ReturnFrames(&frames))
2300 .WillRepeatedly(Return(ERR_IO_PENDING));
2301 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2302 .WillOnce(Return(OK));
2303 EXPECT_CALL(*mock_stream_, Close());
2305 CreateChannelAndConnectSuccessfully();
2308 // RFC6455 5.5.2 "Upon receipt of a Ping frame, an endpoint MUST send a Pong
2309 // frame in response"
2310 // 5.5.3 "A Pong frame sent in response to a Ping frame must have identical
2311 // "Application data" as found in the message body of the Ping frame being
2312 // replied to."
2313 TEST_F(WebSocketChannelStreamTest, PingRepliedWithPong) {
2314 static const InitFrame frames[] = {
2315 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2316 NOT_MASKED, "Application data"}};
2317 static const InitFrame expected[] = {
2318 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2319 MASKED, "Application data"}};
2320 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2321 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2322 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2323 .WillOnce(ReturnFrames(&frames))
2324 .WillRepeatedly(Return(ERR_IO_PENDING));
2325 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2326 .WillOnce(Return(OK));
2328 CreateChannelAndConnectSuccessfully();
2331 // A ping with a NULL payload should be responded to with a Pong with a NULL
2332 // payload.
2333 TEST_F(WebSocketChannelStreamTest, NullPingRepliedWithNullPong) {
2334 static const InitFrame frames[] = {
2335 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing, NOT_MASKED, NULL}};
2336 static const InitFrame expected[] = {
2337 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong, MASKED, NULL}};
2338 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2339 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2340 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2341 .WillOnce(ReturnFrames(&frames))
2342 .WillRepeatedly(Return(ERR_IO_PENDING));
2343 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2344 .WillOnce(Return(OK));
2346 CreateChannelAndConnectSuccessfully();
2349 TEST_F(WebSocketChannelStreamTest, PongInTheMiddleOfDataMessage) {
2350 static const InitFrame frames[] = {
2351 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2352 NOT_MASKED, "Application data"}};
2353 static const InitFrame expected1[] = {
2354 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2355 static const InitFrame expected2[] = {
2356 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePong,
2357 MASKED, "Application data"}};
2358 static const InitFrame expected3[] = {
2359 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeContinuation,
2360 MASKED, "World"}};
2361 ScopedVector<WebSocketFrame>* read_frames;
2362 CompletionCallback read_callback;
2363 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2364 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2365 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2366 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2367 SaveArg<1>(&read_callback),
2368 Return(ERR_IO_PENDING)))
2369 .WillRepeatedly(Return(ERR_IO_PENDING));
2371 InSequence s;
2373 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2374 .WillOnce(Return(OK));
2375 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2376 .WillOnce(Return(OK));
2377 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected3), _))
2378 .WillOnce(Return(OK));
2381 CreateChannelAndConnectSuccessfully();
2382 channel_->SendFrame(
2383 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2384 *read_frames = CreateFrameVector(frames);
2385 read_callback.Run(OK);
2386 channel_->SendFrame(
2387 true, WebSocketFrameHeader::kOpCodeContinuation, AsVector("World"));
2390 // WriteFrames() may not be called until the previous write has completed.
2391 // WebSocketChannel must buffer writes that happen in the meantime.
2392 TEST_F(WebSocketChannelStreamTest, WriteFramesOneAtATime) {
2393 static const InitFrame expected1[] = {
2394 {NOT_FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "Hello "}};
2395 static const InitFrame expected2[] = {
2396 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "World"}};
2397 CompletionCallback write_callback;
2398 Checkpoint checkpoint;
2400 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2401 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2402 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2404 InSequence s;
2405 EXPECT_CALL(checkpoint, Call(1));
2406 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2407 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2408 EXPECT_CALL(checkpoint, Call(2));
2409 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2410 .WillOnce(Return(ERR_IO_PENDING));
2411 EXPECT_CALL(checkpoint, Call(3));
2414 CreateChannelAndConnectSuccessfully();
2415 checkpoint.Call(1);
2416 channel_->SendFrame(
2417 false, WebSocketFrameHeader::kOpCodeText, AsVector("Hello "));
2418 channel_->SendFrame(
2419 true, WebSocketFrameHeader::kOpCodeText, AsVector("World"));
2420 checkpoint.Call(2);
2421 write_callback.Run(OK);
2422 checkpoint.Call(3);
2425 // WebSocketChannel must buffer frames while it is waiting for a write to
2426 // complete, and then send them in a single batch. The batching behaviour is
2427 // important to get good throughput in the "many small messages" case.
2428 TEST_F(WebSocketChannelStreamTest, WaitingMessagesAreBatched) {
2429 static const char input_letters[] = "Hello";
2430 static const InitFrame expected1[] = {
2431 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "H"}};
2432 static const InitFrame expected2[] = {
2433 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "e"},
2434 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2435 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "l"},
2436 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeText, MASKED, "o"}};
2437 CompletionCallback write_callback;
2439 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2440 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2441 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2443 InSequence s;
2444 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected1), _))
2445 .WillOnce(DoAll(SaveArg<1>(&write_callback), Return(ERR_IO_PENDING)));
2446 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected2), _))
2447 .WillOnce(Return(ERR_IO_PENDING));
2450 CreateChannelAndConnectSuccessfully();
2451 for (size_t i = 0; i < strlen(input_letters); ++i) {
2452 channel_->SendFrame(true,
2453 WebSocketFrameHeader::kOpCodeText,
2454 std::vector<char>(1, input_letters[i]));
2456 write_callback.Run(OK);
2459 // When the renderer sends more on a channel than it has quota for, then we send
2460 // a kWebSocketMuxErrorSendQuotaViolation status code (from the draft websocket
2461 // mux specification) back to the renderer. This should not be sent to the
2462 // remote server, which may not even implement the mux specification, and could
2463 // even be using a different extension which uses that code to mean something
2464 // else.
2465 TEST_F(WebSocketChannelStreamTest, MuxErrorIsNotSentToStream) {
2466 static const InitFrame expected[] = {
2467 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2468 MASKED, CLOSE_DATA(GOING_AWAY, "")}};
2469 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2470 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2471 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2472 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2473 .WillOnce(Return(OK));
2474 EXPECT_CALL(*mock_stream_, Close());
2476 CreateChannelAndConnectSuccessfully();
2477 channel_->SendFrame(true,
2478 WebSocketFrameHeader::kOpCodeText,
2479 std::vector<char>(kDefaultInitialQuota + 1, 'C'));
2482 // For convenience, most of these tests use Text frames. However, the WebSocket
2483 // protocol also has Binary frames and those need to be 8-bit clean. For the
2484 // sake of completeness, this test verifies that they are.
2485 TEST_F(WebSocketChannelStreamTest, WrittenBinaryFramesAre8BitClean) {
2486 ScopedVector<WebSocketFrame>* frames = NULL;
2488 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2489 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2490 EXPECT_CALL(*mock_stream_, ReadFrames(_, _)).WillOnce(Return(ERR_IO_PENDING));
2491 EXPECT_CALL(*mock_stream_, WriteFrames(_, _))
2492 .WillOnce(DoAll(SaveArg<0>(&frames), Return(ERR_IO_PENDING)));
2494 CreateChannelAndConnectSuccessfully();
2495 channel_->SendFrame(
2496 true,
2497 WebSocketFrameHeader::kOpCodeBinary,
2498 std::vector<char>(kBinaryBlob, kBinaryBlob + kBinaryBlobSize));
2499 ASSERT_TRUE(frames != NULL);
2500 ASSERT_EQ(1U, frames->size());
2501 const WebSocketFrame* out_frame = (*frames)[0];
2502 EXPECT_EQ(kBinaryBlobSize, out_frame->header.payload_length);
2503 ASSERT_TRUE(out_frame->data);
2504 EXPECT_EQ(0, memcmp(kBinaryBlob, out_frame->data->data(), kBinaryBlobSize));
2507 // Test the read path for 8-bit cleanliness as well.
2508 TEST_F(WebSocketChannelEventInterfaceTest, ReadBinaryFramesAre8BitClean) {
2509 scoped_ptr<WebSocketFrame> frame(
2510 new WebSocketFrame(WebSocketFrameHeader::kOpCodeBinary));
2511 WebSocketFrameHeader& frame_header = frame->header;
2512 frame_header.final = true;
2513 frame_header.payload_length = kBinaryBlobSize;
2514 frame->data = new IOBuffer(kBinaryBlobSize);
2515 memcpy(frame->data->data(), kBinaryBlob, kBinaryBlobSize);
2516 ScopedVector<WebSocketFrame> frames;
2517 frames.push_back(frame.release());
2518 scoped_ptr<ReadableFakeWebSocketStream> stream(
2519 new ReadableFakeWebSocketStream);
2520 stream->PrepareRawReadFrames(
2521 ReadableFakeWebSocketStream::SYNC, OK, frames.Pass());
2522 set_stream(stream.Pass());
2523 EXPECT_CALL(*event_interface_, OnAddChannelResponse(false, _, _));
2524 EXPECT_CALL(*event_interface_, OnFlowControl(_));
2525 EXPECT_CALL(*event_interface_,
2526 OnDataFrame(true,
2527 WebSocketFrameHeader::kOpCodeBinary,
2528 std::vector<char>(kBinaryBlob,
2529 kBinaryBlob + kBinaryBlobSize)));
2531 CreateChannelAndConnectSuccessfully();
2534 // If we receive another frame after Close, it is not valid. It is not
2535 // completely clear what behaviour is required from the standard in this case,
2536 // but the current implementation fails the connection. Since a Close has
2537 // already been sent, this just means closing the connection.
2538 TEST_F(WebSocketChannelStreamTest, PingAfterCloseIsRejected) {
2539 static const InitFrame frames[] = {
2540 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2541 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")},
2542 {FINAL_FRAME, WebSocketFrameHeader::kOpCodePing,
2543 NOT_MASKED, "Ping body"}};
2544 static const InitFrame expected[] = {
2545 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2546 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2547 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2548 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2549 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2550 .WillOnce(ReturnFrames(&frames))
2551 .WillRepeatedly(Return(ERR_IO_PENDING));
2553 // We only need to verify the relative order of WriteFrames() and
2554 // Close(). The current implementation calls WriteFrames() for the Close
2555 // frame before calling ReadFrames() again, but that is an implementation
2556 // detail and better not to consider required behaviour.
2557 InSequence s;
2558 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2559 .WillOnce(Return(OK));
2560 EXPECT_CALL(*mock_stream_, Close()).Times(1);
2563 CreateChannelAndConnectSuccessfully();
2566 // A protocol error from the remote server should result in a close frame with
2567 // status 1002, followed by the connection closing.
2568 TEST_F(WebSocketChannelStreamTest, ProtocolError) {
2569 static const InitFrame expected[] = {
2570 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2571 MASKED, CLOSE_DATA(PROTOCOL_ERROR, "WebSocket Protocol Error")}};
2572 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2573 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2574 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2575 .WillOnce(Return(ERR_WS_PROTOCOL_ERROR));
2576 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2577 .WillOnce(Return(OK));
2578 EXPECT_CALL(*mock_stream_, Close());
2580 CreateChannelAndConnectSuccessfully();
2583 // Set the closing handshake timeout to a very tiny value before connecting.
2584 class WebSocketChannelStreamTimeoutTest : public WebSocketChannelStreamTest {
2585 protected:
2586 WebSocketChannelStreamTimeoutTest() {}
2588 virtual void CreateChannelAndConnectSuccessfully() OVERRIDE {
2589 set_stream(mock_stream_.Pass());
2590 CreateChannelAndConnect();
2591 channel_->SetClosingHandshakeTimeoutForTesting(
2592 TimeDelta::FromMilliseconds(kVeryTinyTimeoutMillis));
2593 connect_data_.creator.connect_delegate->OnSuccess(stream_.Pass());
2597 // In this case the server initiates the closing handshake with a Close
2598 // message. WebSocketChannel responds with a matching Close message, and waits
2599 // for the server to close the TCP/IP connection. The server never closes the
2600 // connection, so the closing handshake times out and WebSocketChannel closes
2601 // the connection itself.
2602 TEST_F(WebSocketChannelStreamTimeoutTest, ServerInitiatedCloseTimesOut) {
2603 static const InitFrame frames[] = {
2604 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2605 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2606 static const InitFrame expected[] = {
2607 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2608 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2609 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2610 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2611 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2612 .WillOnce(ReturnFrames(&frames))
2613 .WillRepeatedly(Return(ERR_IO_PENDING));
2614 Checkpoint checkpoint;
2615 TestClosure completion;
2617 InSequence s;
2618 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2619 .WillOnce(Return(OK));
2620 EXPECT_CALL(checkpoint, Call(1));
2621 EXPECT_CALL(*mock_stream_, Close())
2622 .WillOnce(InvokeClosure(completion.closure()));
2625 CreateChannelAndConnectSuccessfully();
2626 checkpoint.Call(1);
2627 completion.WaitForResult();
2630 // In this case the client initiates the closing handshake by sending a Close
2631 // message. WebSocketChannel waits for a Close message in response from the
2632 // server. The server never responds to the Close message, so the closing
2633 // handshake times out and WebSocketChannel closes the connection.
2634 TEST_F(WebSocketChannelStreamTimeoutTest, ClientInitiatedCloseTimesOut) {
2635 static const InitFrame expected[] = {
2636 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2637 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2638 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2639 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2640 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2641 .WillRepeatedly(Return(ERR_IO_PENDING));
2642 TestClosure completion;
2644 InSequence s;
2645 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2646 .WillOnce(Return(OK));
2647 EXPECT_CALL(*mock_stream_, Close())
2648 .WillOnce(InvokeClosure(completion.closure()));
2651 CreateChannelAndConnectSuccessfully();
2652 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2653 completion.WaitForResult();
2656 // In this case the client initiates the closing handshake and the server
2657 // responds with a matching Close message. WebSocketChannel waits for the server
2658 // to close the TCP/IP connection, but it never does. The closing handshake
2659 // times out and WebSocketChannel closes the connection.
2660 TEST_F(WebSocketChannelStreamTimeoutTest, ConnectionCloseTimesOut) {
2661 static const InitFrame expected[] = {
2662 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2663 MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2664 static const InitFrame frames[] = {
2665 {FINAL_FRAME, WebSocketFrameHeader::kOpCodeClose,
2666 NOT_MASKED, CLOSE_DATA(NORMAL_CLOSURE, "OK")}};
2667 EXPECT_CALL(*mock_stream_, GetSubProtocol()).Times(AnyNumber());
2668 EXPECT_CALL(*mock_stream_, GetExtensions()).Times(AnyNumber());
2669 TestClosure completion;
2670 ScopedVector<WebSocketFrame>* read_frames = NULL;
2671 CompletionCallback read_callback;
2673 InSequence s;
2674 // Copy the arguments to ReadFrames so that the test can call the callback
2675 // after it has send the close message.
2676 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2677 .WillOnce(DoAll(SaveArg<0>(&read_frames),
2678 SaveArg<1>(&read_callback),
2679 Return(ERR_IO_PENDING)));
2680 // The first real event that happens is the client sending the Close
2681 // message.
2682 EXPECT_CALL(*mock_stream_, WriteFrames(EqualsFrames(expected), _))
2683 .WillOnce(Return(OK));
2684 // The |read_frames| callback is called (from this test case) at this
2685 // point. ReadFrames is called again by WebSocketChannel, waiting for
2686 // ERR_CONNECTION_CLOSED.
2687 EXPECT_CALL(*mock_stream_, ReadFrames(_, _))
2688 .WillOnce(Return(ERR_IO_PENDING));
2689 // The timeout happens and so WebSocketChannel closes the stream.
2690 EXPECT_CALL(*mock_stream_, Close())
2691 .WillOnce(InvokeClosure(completion.closure()));
2694 CreateChannelAndConnectSuccessfully();
2695 channel_->StartClosingHandshake(kWebSocketNormalClosure, "OK");
2696 ASSERT_TRUE(read_frames);
2697 // Provide the "Close" message from the server.
2698 *read_frames = CreateFrameVector(frames);
2699 read_callback.Run(OK);
2700 completion.WaitForResult();
2703 } // namespace
2704 } // namespace net