Flask-socketio: How to get the callback function in SocketioTestClient.emit ?

Created on 9 Oct 2020  路  2Comments  路  Source: miguelgrinberg/Flask-SocketIO

I have already written a simple flask-socketio application and want to write a testing for it.
I mostly followed the code from Project Flack.
However, I don't know how to get ack from the server in SocketioTestClient:

# app.py
from flask import Flask
from flask_socketio import SocketIO

socketio = SocketIO()

def create_app(config_name=None):
    app = Flask(__name__)
    socketio.init_app(app, cors_allowed_origins="*")
    return app

@socketio.on('some_event')
def on_some_event(data):
    print('in some_event, data:', data)
    return {'test': 123}
# tests.py
import unittest
from app import create_app, socketio

def print_response(data):
    print(f'in print response, {data}')

class FlaskTests(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.ctx = self.app.app_context()
        self.ctx.push()

    def tearDown(self):
        self.ctx.pop()

    def test_socketio(self):
        client = socketio.test_client(self.app)
        client.emit('some_event', {'from': 'testing'}, callback=True)
        # how do I pass function print_response to emit()?
        response = client.get_received()
        print(response)

I want to get the ack from the server in testing, which is {'test': 123} in this case,
so I can check if the returned value is valid.
It also seems that SocketioTestClient.emit only accept boolean in the callback argument.
Then how should I pass a callback function to SocketioTestClient.emit?
Or is there another way to check the returned value from the server?
Thanks!

question

All 2 comments

The test client is not a fully featured client, so it does not have the ability to invoke callbacks. How to work with callbacks is explained in the documentation:

        :param callback: ``True`` if the client requests a callback, ``False``
                         if not. Note that client-side callbacks are not
                         implemented, a callback request will just tell the
                         server to provide the arguments to invoke the
                         callback, but no callback is invoked. Instead, the
                         arguments that the server provided for the callback
                         are returned by this function.

In your case the test should coded as follows:

    def test_socketio(self):
        client = socketio.test_client(self.app)
        response = client.emit('some_event', {'from': 'testing'}, callback=True)
        print(response)

This totally solved my problem, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blstdmi picture blstdmi  路  3Comments

nh916 picture nh916  路  3Comments

zuifengwuchou picture zuifengwuchou  路  5Comments

lnunno picture lnunno  路  4Comments

EndenDragon picture EndenDragon  路  3Comments