def test_basic_send_recv(self): """ Test basic send/recv methods between TCPFrameClient and a sample server socket. """ # Create a listening server socket: s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # Reuse address: s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind(('',LOCAL_PORT)) s.listen(5) # Connect FrameClient to server: tfc = TCPFrameClient(('127.0.0.1',LOCAL_PORT)) # Accept connection on the server side: sock,addr = s.accept() # Send a frame from the TCPFrameClient to the server socket: frame = 'hello' tfc.send_frame(frame) # Read 4 bytes first: length = sock.recv(4) length_int = struct.unpack('I',length)[0] self.assertEquals(length_int,len(frame)) # Receive the rest of the frame: r_frame = sock.recv(length_int) self.assertEquals(r_frame,frame) # Send a frame from the server socket to the TCPFrameClient: frame = 'How are you doing?' data = len_prefix_pack(frame) sock.send(data) r_frame = tfc.recv_frame() self.assertEquals(r_frame,frame) # Close server socket: sock.close() # We expect to get a None frame on the TCPFrameClient side: frame = tfc.recv_frame() self.assertEquals(frame,None) # Close listening socket: s.close() # Close TCPFrameClient: tfc.close()
def test_len_prefix_pack(self): """ Test len_prefix_{pack,unpack} functions. """ # Simple packing and unpacking: msg = 'Example msg' data = len_prefix_pack(msg) self.assertEqual(len(data),len(msg) + 4) msg1,data1 = len_prefix_unpack(data) self.assertEqual(msg1,msg) self.assertEqual(len(data1),0) # Dealing with extra data: extra_data = 'some extra' longer_data = data + extra_data msg2,data2 = len_prefix_unpack(longer_data) self.assertEqual(msg2,msg) self.assertEqual(data2,extra_data)