Commits

Andrew Godwin  committed f843710

Improve test coverage for websocket up to 100%, and fix a bug that doing so caught. We love you, coverage.

  • Participants
  • Parent commits b46a7db

Comments (0)

Files changed (2)

File eventlet/websocket.py

 
 try:
     from hashlib import md5
-except ImportError:
+except ImportError: #pragma NO COVER
     from md5 import md5
 
 import eventlet
                     environ.get('HTTP_HOST'),
                     environ.get('PATH_INFO'),
                     response))
-        else:
-            raise ValueError("Unknown WebSocket protocol version.")
+        else: #pragma NO COVER
+            raise ValueError("Unknown WebSocket protocol version.") 
         
         sock.sendall(handshake_reply)
         try:
         """Waits for and deserializes messages. Returns a single
         message; the oldest not yet processed."""
         while not self._msgs:
-            # no parsed messages, must mean buf needs more data (or it's closed)
+            # Websocket might be closed already.
+            if self.websocket_closed:
+                return None
+            # no parsed messages, must mean buf needs more data
             delta = self.socket.recv(8096)
-            if delta == '' or self.websocket_closed:
+            if delta == '':
                 return None
             self._buf += delta
             msgs = self._parse_messages()
             except SocketError:
                 # Sometimes, like when the remote side cuts off the connection,
                 # we don't care about this.
-                if not ignore_send_errors:
+                if not ignore_send_errors: #pragma NO COVER
                     raise
             self.websocket_closed = True
 

File tests/websocket_test.py

         self.assertEqual(resp.read(), '')
 
     def test_incomplete_headers_76(self):
+        # First test: Missing Connection:
         headers = dict(kv.split(': ') for kv in [
                 "Upgrade: WebSocket",
                 # NOTE: intentionally no connection header
         self.assertEqual(resp.status, 400)
         self.assertEqual(resp.getheader('connection'), 'close')
         self.assertEqual(resp.read(), '')
+        
+        # Now, miss off key2
+        headers = dict(kv.split(': ') for kv in [
+                "Upgrade: WebSocket",
+                "Connection: Upgrade",
+                "Host: localhost:%s" % self.port,
+                "Origin: http://localhost:%s" % self.port,
+                "Sec-WebSocket-Protocol: ws",
+                "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5",
+                # NOTE: Intentionally no Key2 header
+                ])
+        http = httplib.HTTPConnection('localhost', self.port)
+        http.request("GET", "/echo", headers=headers)
+        resp = http.getresponse()
+
+        self.assertEqual(resp.status, 400)
+        self.assertEqual(resp.getheader('connection'), 'close')
+        self.assertEqual(resp.read(), '')
 
     def test_correct_upgrade_request_75(self):
         connect = [
         self.site = error_detector
         self.spawn_server()
         connect = [
-                "GET /range HTTP/1.1",
+                "GET /echo HTTP/1.1",
                 "Upgrade: WebSocket",
                 "Connection: Upgrade",
                 "Host: localhost:%s" % self.port,
         done_with_request.wait()
         self.assert_(not error_detected[0])
     
+    def test_client_invalid_packet_76(self):
+        error_detected = [False]
+        done_with_request = event.Event()
+        site = self.site
+        def error_detector(environ, start_response):
+            try:
+                try:
+                    return site(environ, start_response)
+                except:
+                    error_detected[0] = True
+                    raise
+            finally:
+                done_with_request.send(True)
+        self.site = error_detector
+        self.spawn_server()
+        connect = [
+                "GET /echo HTTP/1.1",
+                "Upgrade: WebSocket",
+                "Connection: Upgrade",
+                "Host: localhost:%s" % self.port,
+                "Origin: http://localhost:%s" % self.port,
+                "Sec-WebSocket-Protocol: ws",
+                "Sec-WebSocket-Key1: 4 @1  46546xW%0l 1 5",
+                "Sec-WebSocket-Key2: 12998 5 Y3 1  .P00",
+                ]
+        sock = eventlet.connect(
+            ('localhost', self.port))
+        sock.sendall('\r\n'.join(connect) + '\r\n\r\n^n:ds[4U')
+        resp = sock.recv(1024)  # get the headers
+        sock.sendall('\xef\x00') # Weird packet.
+        done_with_request.wait()
+        self.assert_(error_detected[0])
+    
     def test_server_closing_connect_76(self):
         connect = [
                 "GET / HTTP/1.1",