Help: Python socket unit test framework
Harsh Gupta
harsh.mkg at gmail.com
Tue Jul 5 16:15:05 EDT 2016
Hello All,
I have been trying to write a test framework for a pretty simple command server application in python. I have not been able to figure out how to test the socket server.
I would really appreciate if you could help me out in testing this application using unittest.
Please kindly review it.
The tests cases I came up with are:
1. Start the server
2. Establish connection with client
3. Test the server by sending 3 commands
- loopback command should send all payload.
- print command should print payload
- close command should close the connection between server and client.
4. Raise error if any other command is send other than listed 3 commands
Other nominal cases
1. Check if both the server and client are closed. It might happen that only one is closed.
2. Go to sleep/Cancel the connection if no command is received after a certain period of time.
''''
import socket
import time
supported_commands = {'loopback', 'print', 'close'}
class CommandServer:
def __init__(self, ip='localhost', port=5000):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((ip, port))
print "Server running"
self.is_running = True
def start_listening(self, num_connections=2):
self.server.listen(num_connections)
self._accept()
def is_running(self):
return self.is_running
def _accept(self):
self.client, self.remote_addr = self.server.accept()
print "Received connection from %s" % (self.remote_addr,)
self.is_connected = True
def _get_data(self, bufsize=32):
try:
return self.client.recv(bufsize)
except KeyboardInterrupt:
self.close()
def wait_for_commands(self):
while self.is_connected:
cmd = self._get_data()
if cmd:
if cmd not in supported_commands:
print "Received unsupported command"
continue
if cmd in ("loopback", "print"):
payload = self._get_data(512)
if cmd == "loopback":
self.client.sendall(payload)
elif cmd == "print":
print payload
elif cmd == "close":
self.close()
def close(self):
self.client.close()
self.server.close()
self.is_connected = False
print "Connection closed"
if __name__ == '__main__':
cmd_server = CommandServer()
cmd_server.start_listening()
cmd_server.wait_for_commands()
''''
Thank You
H
More information about the Python-list
mailing list