miguelgrinberg / Flask-SocketIO

Socket.IO integration for Flask applications.
MIT License
5.31k stars 888 forks source link

Flask socketio test_client method to test received ConnectionRefusedError messages #1963

Closed Seluj78 closed 1 year ago

Seluj78 commented 1 year ago

Hi !

I'm writing unit tests to test my socketio auth and I'd like to test if the correct message is returned by ConnectionRefusedError based on my auth send.

Sadly, this isn't doable right now. The only method available for the test_client is get_received which checks if the client is connected before getting the messages, but the client isn't connected when a ConnectionRefusedError is raised during the on("connect") method.

I would like to be able to do

    def test_no_token(self):
        socketio_client = socketio.test_client(application)

        self.assertEqual("JWT access token required in query parameters.", socketio_client.get_received()[0]["args"])

Or something along those lines.

But currently, all I can do is:

    def test_no_token(self):
        socketio_client = socketio.test_client(application)
        with self.assertRaises(RuntimeError):
            socketio_client.get_received()

    def test_invalid_token(self):
        socketio_client = socketio.test_client(application)(
            query_params="?token=yJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
            ".eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY3OTk"
        )
        with self.assertRaises(RuntimeError):
            socketio_client.get_received()

Thank you very much !

Seluj78 commented 1 year ago

Do you need any more details on this @miguelgrinberg ? :)

miguelgrinberg commented 1 year ago

No, I don't need anything else. The test client wasn't designed to work like a real client and for that reason some things cannot be done. I will see if a connection failure can be simulated, but if you really want to do serious testing I recommend that you run a real client against a real server.

Seluj78 commented 1 year ago

The idea was to run unit tests directly from unittest without having a huge setup elsewhere. Having a real client against a real server is a completely different type of testing and not one we're ready to work on on this projet :)

miguelgrinberg commented 1 year ago

@Seluj78 Right, but I'm sure you understand that the simplicity that you have is paid by the complexity in creating a solution that implements the client-server communication in the test client. Nothing is free, this is complex and that complexity has to be somewhere.

Seluj78 commented 1 year ago

Fair enough ! I will make it work without it for now, and figure out a solution if needed later ! Thank you !