1- # These tests test the behaviours expected of wsproto in when the
2- # connection is a client.
31from typing import List , Optional
42
53import h11
64import pytest
75
86from wsproto import WSConnection
9- from wsproto .connection import CLIENT
7+ from wsproto .connection import CLIENT , ConnectionState
108from wsproto .events import (
119 AcceptConnection ,
1210 Event ,
1816from wsproto .typing import Headers
1917from wsproto .utilities import (
2018 generate_accept_token ,
19+ LocalProtocolError ,
2120 normed_header_dict ,
2221 RemoteProtocolError ,
2322)
@@ -102,6 +101,42 @@ def test_connection_request_subprotocols() -> None:
102101 assert headers [b"sec-websocket-protocol" ] == b"one, two"
103102
104103
104+ def test_connection_send_state () -> None :
105+ client = WSConnection (CLIENT )
106+ assert client .state is ConnectionState .CONNECTING
107+
108+ server = h11 .Connection (h11 .SERVER )
109+ server .receive_data (
110+ client .send (
111+ Request (
112+ host = "localhost" ,
113+ target = "/" ,
114+ )
115+ )
116+ )
117+ headers = normed_header_dict (server .next_event ().headers )
118+ response = h11 .InformationalResponse (
119+ status_code = 101 ,
120+ headers = [
121+ (b"connection" , b"Upgrade" ),
122+ (b"upgrade" , b"WebSocket" ),
123+ (
124+ b"Sec-WebSocket-Accept" ,
125+ generate_accept_token (headers [b"sec-websocket-key" ]),
126+ ),
127+ ],
128+ )
129+ client .receive_data (server .send (response ))
130+ assert len (list (client .events ())) == 1
131+ assert client .state is ConnectionState .OPEN # type: ignore # https://github.com/python/mypy/issues/9005
132+
133+ with pytest .raises (LocalProtocolError ) as excinfo :
134+ client .send (Request (host = "localhost" , target = "/" ))
135+
136+ client .receive_data (b"foobar" )
137+ assert len (list (client .events ())) == 1
138+
139+
105140def _make_handshake (
106141 response_status : int ,
107142 response_headers : Headers ,
@@ -110,6 +145,8 @@ def _make_handshake(
110145 auto_accept_key : bool = True ,
111146) -> List [Event ]:
112147 client = WSConnection (CLIENT )
148+ assert client .state is ConnectionState .CONNECTING
149+
113150 server = h11 .Connection (h11 .SERVER )
114151 server .receive_data (
115152 client .send (
@@ -134,6 +171,7 @@ def _make_handshake(
134171 status_code = response_status , headers = response_headers
135172 )
136173 client .receive_data (server .send (response ))
174+ assert client .state is not ConnectionState .CONNECTING
137175
138176 return list (client .events ())
139177
0 commit comments