Python UnitTest - Websocket Server

2.1k views Asked by At

today I was working to create some unittests for my application: a websocket client..

In the real world, ws server is an embeeded pc in the home network.

Now, for my unittest, I'd like to create a fake ws server and use it to test the client. can you suggest me some ws-server plug&play that I can call inside my unittest setup and use it for testing?

I tried to use Autobahn ws server, but it is not plug&play.. It should work but I'm not able to handle correctly it in a separate thread.

My goal is to test the client not to develop a dummy server.

Can you help me with something easy and ready-to-use?

Thanks in advance, Salvo

1

There are 1 answers

0
nos_86 On

Here the minimal code, I wrote, in order to avoid the blocking command (serve_forever)

I used ws4py as websocket library.

from wsgiref.simple_server import make_server
from ws4py.websocket import WebSocket
from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
from ws4py.server.wsgiutils import WebSocketWSGIApplication
import threading


class TestWebSocket(WebSocket):
    def received_message(self, message):
        self.send("+OK", False)


class TestServer:
    def __init__(self, hostname='127.0.0.1', port=8080):
        self.server = make_server(hostname,\
                             port,\
                             server_class=WSGIServer,\
                             handler_class=WebSocketWSGIRequestHandler,\
                             app=WebSocketWSGIApplication(handler_cls=TestWebSocket)\
                             )
        self.server.initialize_websockets_manager()
        self.thread = threading.Thread(target=self.server.serve_forever)
        self.thread.start()
        print("Server started for {}:{}".format(hostname, str(port)))

    def shutdown(self):
        self.server.shutdown()