I'm writing a tcp server. It has an infinite loop to receive and respond requests. Something like this:
class TCPServer:
...
def start(self):
try:
while True:
connection, addr = self.socket.accept()
logging.info(f'Address {self.format_address(addr)} connected.')
data = connection.recv(self.RECEIVING_SIZE)
logging.info(data)
response = self.handle_request(data)
connection.sendall(data)
connection.close()
except KeyboardInterrupt:
self.socket.close()
The whole code is here. My question is how can I test it? I've wroten a test which never ends until I press ctrl-C.
class TestTCPServer:
@staticmethod
def _start_server(server):
thr = threading.Thread(target=server.start, args=(), kwargs={})
thr.start()
return thr
def test_connecting_to_tcp_server(self, client):
host = '127.0.0.1'
port = 12345
tcp_server = TCPServer(host=host, port=port)
running_server = self._start_server(tcp_server)
client.connect((host, port))
running_server.join()
How can I write a test to terminate after testing the connection?