def test_read(body): @mock_server def handle(socket, address): assert socket.recv(4) == b' V2' socket.sendall(struct.pack('>l', len(body))) socket.sendall(body) assert socket.recv(1) == b'' with handle as server: conn = NsqdTCPClient('127.0.0.1', server.server_port) conn.connect() assert conn._read_response() == body conn.close_stream()
def test_disconnected(): @mock_server def handle(socket, address): assert socket.recv(4) == b' V2' assert socket.recv(1) == b'' with handle as server: conn = NsqdTCPClient('127.0.0.1', server.server_port) conn.connect() conn.close_stream() assert conn.state == states.DISCONNECTED with pytest.raises(errors.NSQSocketError): conn.nop() with pytest.raises(errors.NSQSocketError): conn.read_response()
def test_connection(): @mock_server def handle(socket, address): assert socket.recv(4) == b' V2' assert socket.recv(1) == b'' with handle as server: conn = NsqdTCPClient('127.0.0.1', server.server_port) assert conn.state == states.INIT conn.connect() assert conn.state == states.CONNECTED conn.connect() assert conn.state == states.CONNECTED conn.close_stream() assert conn.state == states.DISCONNECTED
def test_socket_upgrades(tls, deflate, snappy): with NsqdIntegrationServer() as server: options = { 'address': server.address, 'port': server.tcp_port, 'deflate': deflate, 'snappy': snappy, } if tls: options.update({ 'tls_v1': True, 'tls_options': { 'keyfile': server.tls_key, 'certfile': server.tls_cert, } }) conn = NsqdTCPClient(**options) conn.connect() assert conn.state == states.CONNECTED if deflate and snappy: with pytest.raises(errors.NSQErrorCode): conn.identify() return if tls and BAD_GEVENT: with pytest.raises(AttributeError): conn.identify() return if tls and server.version < (0, 2, 28): with pytest.raises(ssl.SSLError): conn.identify() return resp = conn.identify() assert isinstance(resp, dict) assert resp['tls_v1'] is tls assert resp['deflate'] is deflate assert resp['snappy'] is snappy if tls and (deflate or snappy): assert isinstance(conn.stream.socket._socket, SSLSocket) elif tls: assert isinstance(conn.stream.socket, SSLSocket) if deflate: assert isinstance(conn.stream.socket, DefalteSocket) if snappy: assert isinstance(conn.stream.socket, SnappySocket) conn.publish('topic', b'sup') frame, data = conn.read_response() assert frame == nsq.FRAME_TYPE_RESPONSE assert data == b'OK' conn.subscribe('topic', 'channel') frame, data = conn.read_response() assert frame == nsq.FRAME_TYPE_RESPONSE assert data == b'OK' conn.ready(1) frame, data = conn.read_response() assert frame == nsq.FRAME_TYPE_MESSAGE assert data.body == b'sup' conn.close_stream()