Browse Source

simplify asserts in unit tests

pull/518/head
Miguel Grinberg 5 years ago
parent
commit
a4f9992d34
No known key found for this signature in database GPG Key ID: 36848B262DF5F06C
  1. 639
      tests/asyncio/test_asyncio_client.py
  2. 186
      tests/asyncio/test_asyncio_manager.py
  3. 133
      tests/asyncio/test_asyncio_namespace.py
  4. 404
      tests/asyncio/test_asyncio_pubsub_manager.py
  5. 71
      tests/asyncio/test_asyncio_redis_manager.py
  6. 477
      tests/asyncio/test_asyncio_server.py
  7. 197
      tests/common/test_base_manager.py
  8. 667
      tests/common/test_client.py
  9. 11
      tests/common/test_middleware.py
  10. 107
      tests/common/test_namespace.py
  11. 287
      tests/common/test_packet.py
  12. 356
      tests/common/test_pubsub_manager.py
  13. 422
      tests/common/test_server.py
  14. 2
      tox.ini

639
tests/asyncio/test_asyncio_client.py

@ -4,6 +4,7 @@ import sys
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -14,6 +15,7 @@ from socketio import asyncio_namespace
from engineio import exceptions as engineio_exceptions from engineio import exceptions as engineio_exceptions
from socketio import exceptions from socketio import exceptions
from socketio import packet from socketio import packet
import pytest
def AsyncMock(*args, **kwargs): def AsyncMock(*args, **kwargs):
@ -49,67 +51,100 @@ def _run(coro):
class TestAsyncClient(unittest.TestCase): class TestAsyncClient(unittest.TestCase):
def test_is_asyncio_based(self): def test_is_asyncio_based(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
self.assertEqual(c.is_asyncio_based(), True) assert c.is_asyncio_based()
def test_connect(self): def test_connect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.connect = AsyncMock() c.eio.connect = AsyncMock()
_run(c.connect('url', headers='headers', transports='transports', _run(
namespaces=['/foo', '/', '/bar'], c.connect(
socketio_path='path')) 'url',
self.assertEqual(c.connection_url, 'url') headers='headers',
self.assertEqual(c.connection_headers, 'headers') transports='transports',
self.assertEqual(c.connection_transports, 'transports') namespaces=['/foo', '/', '/bar'],
self.assertEqual(c.connection_namespaces, ['/foo', '/', '/bar']) socketio_path='path',
self.assertEqual(c.socketio_path, 'path') )
self.assertEqual(c.namespaces, ['/foo', '/bar']) )
assert c.connection_url == 'url'
assert c.connection_headers == 'headers'
assert c.connection_transports == 'transports'
assert c.connection_namespaces == ['/foo', '/', '/bar']
assert c.socketio_path == 'path'
assert c.namespaces == ['/foo', '/bar']
c.eio.connect.mock.assert_called_once_with( c.eio.connect.mock.assert_called_once_with(
'url', headers='headers', transports='transports', 'url',
engineio_path='path') headers='headers',
transports='transports',
engineio_path='path',
)
def test_connect_one_namespace(self): def test_connect_one_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.connect = AsyncMock() c.eio.connect = AsyncMock()
_run(c.connect('url', headers='headers', transports='transports', _run(
namespaces='/foo', c.connect(
socketio_path='path')) 'url',
self.assertEqual(c.connection_url, 'url') headers='headers',
self.assertEqual(c.connection_headers, 'headers') transports='transports',
self.assertEqual(c.connection_transports, 'transports') namespaces='/foo',
self.assertEqual(c.connection_namespaces, ['/foo']) socketio_path='path',
self.assertEqual(c.socketio_path, 'path') )
self.assertEqual(c.namespaces, ['/foo']) )
assert c.connection_url == 'url'
assert c.connection_headers == 'headers'
assert c.connection_transports == 'transports'
assert c.connection_namespaces == ['/foo']
assert c.socketio_path == 'path'
assert c.namespaces == ['/foo']
c.eio.connect.mock.assert_called_once_with( c.eio.connect.mock.assert_called_once_with(
'url', headers='headers', transports='transports', 'url',
engineio_path='path') headers='headers',
transports='transports',
engineio_path='path',
)
def test_connect_default_namespaces(self): def test_connect_default_namespaces(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.connect = AsyncMock() c.eio.connect = AsyncMock()
c.on('foo', mock.MagicMock(), namespace='/foo') c.on('foo', mock.MagicMock(), namespace='/foo')
c.on('bar', mock.MagicMock(), namespace='/') c.on('bar', mock.MagicMock(), namespace='/')
_run(c.connect('url', headers='headers', transports='transports', _run(
socketio_path='path')) c.connect(
self.assertEqual(c.connection_url, 'url') 'url',
self.assertEqual(c.connection_headers, 'headers') headers='headers',
self.assertEqual(c.connection_transports, 'transports') transports='transports',
self.assertEqual(c.connection_namespaces, None) socketio_path='path',
self.assertEqual(c.socketio_path, 'path') )
self.assertEqual(c.namespaces, ['/foo']) )
assert c.connection_url == 'url'
assert c.connection_headers == 'headers'
assert c.connection_transports == 'transports'
assert c.connection_namespaces is None
assert c.socketio_path == 'path'
assert c.namespaces == ['/foo']
c.eio.connect.mock.assert_called_once_with( c.eio.connect.mock.assert_called_once_with(
'url', headers='headers', transports='transports', 'url',
engineio_path='path') headers='headers',
transports='transports',
engineio_path='path',
)
def test_connect_error(self): def test_connect_error(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.connect = AsyncMock( c.eio.connect = AsyncMock(
side_effect=engineio_exceptions.ConnectionError('foo')) side_effect=engineio_exceptions.ConnectionError('foo')
)
c.on('foo', mock.MagicMock(), namespace='/foo') c.on('foo', mock.MagicMock(), namespace='/foo')
c.on('bar', mock.MagicMock(), namespace='/') c.on('bar', mock.MagicMock(), namespace='/')
self.assertRaises( with pytest.raises(exceptions.ConnectionError):
exceptions.ConnectionError, _run, c.connect( _run(
'url', headers='headers', transports='transports', c.connect(
socketio_path='path')) 'url',
headers='headers',
transports='transports',
socketio_path='path',
)
)
def test_wait_no_reconnect(self): def test_wait_no_reconnect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -146,79 +181,106 @@ class TestAsyncClient(unittest.TestCase):
c._reconnect_task = fake_wait() c._reconnect_task = fake_wait()
_run(c.wait()) _run(c.wait())
self.assertEqual(c.eio.wait.mock.call_count, 2) assert c.eio.wait.mock.call_count == 2
self.assertEqual(c.sleep.mock.call_count, 2) assert c.sleep.mock.call_count == 2
def test_emit_no_arguments(self): def test_emit_no_arguments(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo')) _run(c.emit('foo'))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo'], id=None, binary=False) packet.EVENT, namespace='/', data=['foo'], id=None, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_one_argument(self): def test_emit_one_argument(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', 'bar')) _run(c.emit('foo', 'bar'))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo', 'bar'], id=None, packet.EVENT,
binary=False) namespace='/',
self.assertEqual(c._send_packet.mock.call_count, 1) data=['foo', 'bar'],
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), id=None,
expected_packet.encode()) binary=False,
)
assert c._send_packet.mock.call_count == 1
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_one_argument_list(self): def test_emit_one_argument_list(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', ['bar', 'baz'])) _run(c.emit('foo', ['bar', 'baz']))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo', ['bar', 'baz']], id=None, packet.EVENT,
binary=False) namespace='/',
self.assertEqual(c._send_packet.mock.call_count, 1) data=['foo', ['bar', 'baz']],
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), id=None,
expected_packet.encode()) binary=False,
)
assert c._send_packet.mock.call_count == 1
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_two_arguments(self): def test_emit_two_arguments(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', ('bar', 'baz'))) _run(c.emit('foo', ('bar', 'baz')))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo', 'bar', 'baz'], id=None, packet.EVENT,
binary=False) namespace='/',
self.assertEqual(c._send_packet.mock.call_count, 1) data=['foo', 'bar', 'baz'],
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), id=None,
expected_packet.encode()) binary=False,
)
assert c._send_packet.mock.call_count == 1
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_namespace(self): def test_emit_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.namespaces = ['/foo'] c.namespaces = ['/foo']
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', namespace='/foo')) _run(c.emit('foo', namespace='/foo'))
expected_packet = packet.Packet(packet.EVENT, namespace='/foo', expected_packet = packet.Packet(
data=['foo'], id=None, binary=False) packet.EVENT, namespace='/foo', data=['foo'], id=None, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_unknown_namespace(self): def test_emit_unknown_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.namespaces = ['/foo'] c.namespaces = ['/foo']
self.assertRaises(exceptions.BadNamespaceError, _run, with pytest.raises(exceptions.BadNamespaceError):
c.emit('foo', namespace='/bar')) _run(c.emit('foo', namespace='/bar'))
def test_emit_with_callback(self): def test_emit_with_callback(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
c._generate_ack_id = mock.MagicMock(return_value=123) c._generate_ack_id = mock.MagicMock(return_value=123)
_run(c.emit('foo', callback='cb')) _run(c.emit('foo', callback='cb'))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo'], id=123, binary=False) packet.EVENT, namespace='/', data=['foo'], id=123, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
c._generate_ack_id.assert_called_once_with('/', 'cb') c._generate_ack_id.assert_called_once_with('/', 'cb')
def test_emit_namespace_with_callback(self): def test_emit_namespace_with_callback(self):
@ -227,49 +289,65 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
c._generate_ack_id = mock.MagicMock(return_value=123) c._generate_ack_id = mock.MagicMock(return_value=123)
_run(c.emit('foo', namespace='/foo', callback='cb')) _run(c.emit('foo', namespace='/foo', callback='cb'))
expected_packet = packet.Packet(packet.EVENT, namespace='/foo', expected_packet = packet.Packet(
data=['foo'], id=123, binary=False) packet.EVENT, namespace='/foo', data=['foo'], id=123, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
c._generate_ack_id.assert_called_once_with('/foo', 'cb') c._generate_ack_id.assert_called_once_with('/foo', 'cb')
def test_emit_binary(self): def test_emit_binary(self):
c = asyncio_client.AsyncClient(binary=True) c = asyncio_client.AsyncClient(binary=True)
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', b'bar')) _run(c.emit('foo', b'bar'))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo', b'bar'], id=None, packet.EVENT,
binary=True) namespace='/',
self.assertEqual(c._send_packet.mock.call_count, 1) data=['foo', b'bar'],
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), id=None,
expected_packet.encode()) binary=True,
)
assert c._send_packet.mock.call_count == 1
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_emit_not_binary(self): def test_emit_not_binary(self):
c = asyncio_client.AsyncClient(binary=False) c = asyncio_client.AsyncClient(binary=False)
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c.emit('foo', 'bar')) _run(c.emit('foo', 'bar'))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo', 'bar'], id=None, packet.EVENT,
binary=False) namespace='/',
self.assertEqual(c._send_packet.mock.call_count, 1) data=['foo', 'bar'],
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), id=None,
expected_packet.encode()) binary=False,
)
assert c._send_packet.mock.call_count == 1
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_send(self): def test_send(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.emit = AsyncMock() c.emit = AsyncMock()
_run(c.send('data', 'namespace', 'callback')) _run(c.send('data', 'namespace', 'callback'))
c.emit.mock.assert_called_once_with( c.emit.mock.assert_called_once_with(
'message', data='data', namespace='namespace', 'message', data='data', namespace='namespace', callback='callback'
callback='callback') )
def test_send_with_defaults(self): def test_send_with_defaults(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.emit = AsyncMock() c.emit = AsyncMock()
_run(c.send('data')) _run(c.send('data'))
c.emit.mock.assert_called_once_with( c.emit.mock.assert_called_once_with(
'message', data='data', namespace=None, callback=None) 'message', data='data', namespace=None, callback=None
)
def test_call(self): def test_call(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -281,12 +359,15 @@ class TestAsyncClient(unittest.TestCase):
c._generate_ack_id = mock.MagicMock(return_value=123) c._generate_ack_id = mock.MagicMock(return_value=123)
c.eio = mock.MagicMock() c.eio = mock.MagicMock()
c.eio.create_event.return_value.wait = fake_event_wait c.eio.create_event.return_value.wait = fake_event_wait
self.assertEqual(_run(c.call('foo')), ('foo', 321)) assert _run(c.call('foo')) == ('foo', 321)
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo'], id=123, binary=False) packet.EVENT, namespace='/', data=['foo'], id=123, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_call_with_timeout(self): def test_call_with_timeout(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -298,13 +379,16 @@ class TestAsyncClient(unittest.TestCase):
c._generate_ack_id = mock.MagicMock(return_value=123) c._generate_ack_id = mock.MagicMock(return_value=123)
c.eio = mock.MagicMock() c.eio = mock.MagicMock()
c.eio.create_event.return_value.wait = fake_event_wait c.eio.create_event.return_value.wait = fake_event_wait
self.assertRaises(exceptions.TimeoutError, _run, with pytest.raises(exceptions.TimeoutError):
c.call('foo', timeout=0.01)) _run(c.call('foo', timeout=0.01))
expected_packet = packet.Packet(packet.EVENT, namespace='/', expected_packet = packet.Packet(
data=['foo'], id=123, binary=False) packet.EVENT, namespace='/', data=['foo'], id=123, binary=False
self.assertEqual(c._send_packet.mock.call_count, 1) )
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert c._send_packet.mock.call_count == 1
expected_packet.encode()) assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_disconnect(self): def test_disconnect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -314,11 +398,13 @@ class TestAsyncClient(unittest.TestCase):
c.eio.disconnect = AsyncMock() c.eio.disconnect = AsyncMock()
c.eio.state = 'connected' c.eio.state = 'connected'
_run(c.disconnect()) _run(c.disconnect())
self.assertEqual(c._trigger_event.mock.call_count, 0) assert c._trigger_event.mock.call_count == 0
self.assertEqual(c._send_packet.mock.call_count, 1) assert c._send_packet.mock.call_count == 1
expected_packet = packet.Packet(packet.DISCONNECT, namespace='/') expected_packet = packet.Packet(packet.DISCONNECT, namespace='/')
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
c.eio.disconnect.mock.assert_called_once_with(abort=True) c.eio.disconnect.mock.assert_called_once_with(abort=True)
def test_disconnect_namespaces(self): def test_disconnect_namespaces(self):
@ -330,25 +416,31 @@ class TestAsyncClient(unittest.TestCase):
c.eio.disconnect = AsyncMock() c.eio.disconnect = AsyncMock()
c.eio.state = 'connected' c.eio.state = 'connected'
_run(c.disconnect()) _run(c.disconnect())
self.assertEqual(c._trigger_event.mock.call_count, 0) assert c._trigger_event.mock.call_count == 0
self.assertEqual(c._send_packet.mock.call_count, 3) assert c._send_packet.mock.call_count == 3
expected_packet = packet.Packet(packet.DISCONNECT, namespace='/foo') expected_packet = packet.Packet(packet.DISCONNECT, namespace='/foo')
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
expected_packet = packet.Packet(packet.DISCONNECT, namespace='/bar') expected_packet = packet.Packet(packet.DISCONNECT, namespace='/bar')
self.assertEqual(c._send_packet.mock.call_args_list[1][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[1][0][0].encode()
== expected_packet.encode()
)
expected_packet = packet.Packet(packet.DISCONNECT, namespace='/') expected_packet = packet.Packet(packet.DISCONNECT, namespace='/')
self.assertEqual(c._send_packet.mock.call_args_list[2][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[2][0][0].encode()
== expected_packet.encode()
)
def test_start_background_task(self): def test_start_background_task(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.start_background_task = mock.MagicMock(return_value='foo') c.eio.start_background_task = mock.MagicMock(return_value='foo')
self.assertEqual(c.start_background_task('foo', 'bar', baz='baz'), assert c.start_background_task('foo', 'bar', baz='baz') == 'foo'
'foo') c.eio.start_background_task.assert_called_once_with(
c.eio.start_background_task.assert_called_once_with('foo', 'bar', 'foo', 'bar', baz='baz'
baz='baz') )
def test_sleep(self): def test_sleep(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -366,13 +458,13 @@ class TestAsyncClient(unittest.TestCase):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.send = AsyncMock() c.eio.send = AsyncMock()
_run(c._send_packet(packet.Packet(packet.EVENT, b'foo', binary=True))) _run(c._send_packet(packet.Packet(packet.EVENT, b'foo', binary=True)))
self.assertTrue(c.eio.send.mock.call_args_list == [ assert c.eio.send.mock.call_args_list == [
mock.call('51-{"_placeholder":true,"num":0}', binary=False), mock.call('51-{"_placeholder":true,"num":0}', binary=False),
mock.call(b'foo', binary=True) mock.call(b'foo', binary=True),
] or c.eio.send.mock.call_args_list == [ ] or c.eio.send.mock.call_args_list == [
mock.call('51-{"num":0,"_placeholder":true}', binary=False), mock.call('51-{"num":0,"_placeholder":true}', binary=False),
mock.call(b'foo', binary=True) mock.call(b'foo', binary=True),
]) ]
def test_send_packet_default_binary_py3(self): def test_send_packet_default_binary_py3(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -395,13 +487,17 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_connect('/')) _run(c._handle_connect('/'))
c._trigger_event.mock.assert_called_once_with('connect', namespace='/') c._trigger_event.mock.assert_called_once_with('connect', namespace='/')
self.assertEqual(c._send_packet.mock.call_count, 2) assert c._send_packet.mock.call_count == 2
expected_packet = packet.Packet(packet.CONNECT, namespace='/foo') expected_packet = packet.Packet(packet.CONNECT, namespace='/foo')
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
expected_packet = packet.Packet(packet.CONNECT, namespace='/bar') expected_packet = packet.Packet(packet.CONNECT, namespace='/bar')
self.assertEqual(c._send_packet.mock.call_args_list[1][0][0].encode(), assert (
expected_packet.encode()) c._send_packet.mock.call_args_list[1][0][0].encode()
== expected_packet.encode()
)
def test_handle_connect_namespace(self): def test_handle_connect_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -410,12 +506,12 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_connect('/foo')) _run(c._handle_connect('/foo'))
_run(c._handle_connect('/bar')) _run(c._handle_connect('/bar'))
self.assertEqual(c._trigger_event.mock.call_args_list, [ assert c._trigger_event.mock.call_args_list == [
mock.call('connect', namespace='/foo'), mock.call('connect', namespace='/foo'),
mock.call('connect', namespace='/bar') mock.call('connect', namespace='/bar'),
]) ]
c._send_packet.mock.assert_not_called() c._send_packet.mock.assert_not_called()
self.assertEqual(c.namespaces, ['/foo', '/bar']) assert c.namespaces == ['/foo', '/bar']
def test_handle_disconnect(self): def test_handle_disconnect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -423,10 +519,11 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_disconnect('/')) _run(c._handle_disconnect('/'))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'disconnect', namespace='/') 'disconnect', namespace='/'
self.assertFalse(c.connected) )
assert not c.connected
_run(c._handle_disconnect('/')) _run(c._handle_disconnect('/'))
self.assertEqual(c._trigger_event.mock.call_count, 1) assert c._trigger_event.mock.call_count == 1
def test_handle_disconnect_namespace(self): def test_handle_disconnect_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -435,9 +532,10 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_disconnect('/foo')) _run(c._handle_disconnect('/foo'))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'disconnect', namespace='/foo') 'disconnect', namespace='/foo'
self.assertEqual(c.namespaces, ['/bar']) )
self.assertTrue(c.connected) assert c.namespaces == ['/bar']
assert c.connected
def test_handle_disconnect_unknown_namespace(self): def test_handle_disconnect_unknown_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -446,9 +544,10 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_disconnect('/baz')) _run(c._handle_disconnect('/baz'))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'disconnect', namespace='/baz') 'disconnect', namespace='/baz'
self.assertEqual(c.namespaces, ['/foo', '/bar']) )
self.assertTrue(c.connected) assert c.namespaces == ['/foo', '/bar']
assert c.connected
def test_handle_disconnect_all_namespaces(self): def test_handle_disconnect_all_namespaces(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -456,21 +555,19 @@ class TestAsyncClient(unittest.TestCase):
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_disconnect('/')) _run(c._handle_disconnect('/'))
c._trigger_event.mock.assert_any_call( c._trigger_event.mock.assert_any_call('disconnect', namespace='/')
'disconnect', namespace='/') c._trigger_event.mock.assert_any_call('disconnect', namespace='/foo')
c._trigger_event.mock.assert_any_call( c._trigger_event.mock.assert_any_call('disconnect', namespace='/bar')
'disconnect', namespace='/foo') assert c.namespaces == []
c._trigger_event.mock.assert_any_call( assert not c.connected
'disconnect', namespace='/bar')
self.assertEqual(c.namespaces, [])
self.assertFalse(c.connected)
def test_handle_event(self): def test_handle_event(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_event('/', None, ['foo', ('bar', 'baz')])) _run(c._handle_event('/', None, ['foo', ('bar', 'baz')]))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'foo', '/', ('bar', 'baz')) 'foo', '/', ('bar', 'baz')
)
def test_handle_event_with_id_no_arguments(self): def test_handle_event_with_id_no_arguments(self):
c = asyncio_client.AsyncClient(binary=True) c = asyncio_client.AsyncClient(binary=True)
@ -478,12 +575,16 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_event('/', 123, ['foo', ('bar', 'baz')])) _run(c._handle_event('/', 123, ['foo', ('bar', 'baz')]))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'foo', '/', ('bar', 'baz')) 'foo', '/', ('bar', 'baz')
self.assertEqual(c._send_packet.mock.call_count, 1) )
expected_packet = packet.Packet(packet.ACK, namespace='/', id=123, assert c._send_packet.mock.call_count == 1
data=[], binary=None) expected_packet = packet.Packet(
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), packet.ACK, namespace='/', id=123, data=[], binary=None
expected_packet.encode()) )
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_handle_event_with_id_one_argument(self): def test_handle_event_with_id_one_argument(self):
c = asyncio_client.AsyncClient(binary=True) c = asyncio_client.AsyncClient(binary=True)
@ -491,12 +592,16 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_event('/', 123, ['foo', ('bar', 'baz')])) _run(c._handle_event('/', 123, ['foo', ('bar', 'baz')]))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'foo', '/', ('bar', 'baz')) 'foo', '/', ('bar', 'baz')
self.assertEqual(c._send_packet.mock.call_count, 1) )
expected_packet = packet.Packet(packet.ACK, namespace='/', id=123, assert c._send_packet.mock.call_count == 1
data=['ret'], binary=None) expected_packet = packet.Packet(
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), packet.ACK, namespace='/', id=123, data=['ret'], binary=None
expected_packet.encode()) )
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_handle_event_with_id_one_list_argument(self): def test_handle_event_with_id_one_list_argument(self):
c = asyncio_client.AsyncClient(binary=True) c = asyncio_client.AsyncClient(binary=True)
@ -504,12 +609,16 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_event('/', 123, ['foo', ('bar', 'baz')])) _run(c._handle_event('/', 123, ['foo', ('bar', 'baz')]))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'foo', '/', ('bar', 'baz')) 'foo', '/', ('bar', 'baz')
self.assertEqual(c._send_packet.mock.call_count, 1) )
expected_packet = packet.Packet(packet.ACK, namespace='/', id=123, assert c._send_packet.mock.call_count == 1
data=[['a', 'b']], binary=None) expected_packet = packet.Packet(
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), packet.ACK, namespace='/', id=123, data=[['a', 'b']], binary=None
expected_packet.encode()) )
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_handle_event_with_id_two_arguments(self): def test_handle_event_with_id_two_arguments(self):
c = asyncio_client.AsyncClient(binary=True) c = asyncio_client.AsyncClient(binary=True)
@ -517,12 +626,16 @@ class TestAsyncClient(unittest.TestCase):
c._send_packet = AsyncMock() c._send_packet = AsyncMock()
_run(c._handle_event('/', 123, ['foo', ('bar', 'baz')])) _run(c._handle_event('/', 123, ['foo', ('bar', 'baz')]))
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'foo', '/', ('bar', 'baz')) 'foo', '/', ('bar', 'baz')
self.assertEqual(c._send_packet.mock.call_count, 1) )
expected_packet = packet.Packet(packet.ACK, namespace='/', id=123, assert c._send_packet.mock.call_count == 1
data=['a', 'b'], binary=None) expected_packet = packet.Packet(
self.assertEqual(c._send_packet.mock.call_args_list[0][0][0].encode(), packet.ACK, namespace='/', id=123, data=['a', 'b'], binary=None
expected_packet.encode()) )
assert (
c._send_packet.mock.call_args_list[0][0][0].encode()
== expected_packet.encode()
)
def test_handle_ack(self): def test_handle_ack(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -530,7 +643,7 @@ class TestAsyncClient(unittest.TestCase):
c.callbacks['/foo'] = {123: mock_cb} c.callbacks['/foo'] = {123: mock_cb}
_run(c._handle_ack('/foo', 123, ['bar', 'baz'])) _run(c._handle_ack('/foo', 123, ['bar', 'baz']))
mock_cb.assert_called_once_with('bar', 'baz') mock_cb.assert_called_once_with('bar', 'baz')
self.assertNotIn(123, c.callbacks['/foo']) assert 123 not in c.callbacks['/foo']
def test_handle_ack_async(self): def test_handle_ack_async(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -538,7 +651,7 @@ class TestAsyncClient(unittest.TestCase):
c.callbacks['/foo'] = {123: mock_cb} c.callbacks['/foo'] = {123: mock_cb}
_run(c._handle_ack('/foo', 123, ['bar', 'baz'])) _run(c._handle_ack('/foo', 123, ['bar', 'baz']))
mock_cb.mock.assert_called_once_with('bar', 'baz') mock_cb.mock.assert_called_once_with('bar', 'baz')
self.assertNotIn(123, c.callbacks['/foo']) assert 123 not in c.callbacks['/foo']
def test_handle_ack_not_found(self): def test_handle_ack_not_found(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -546,7 +659,7 @@ class TestAsyncClient(unittest.TestCase):
c.callbacks['/foo'] = {123: mock_cb} c.callbacks['/foo'] = {123: mock_cb}
_run(c._handle_ack('/foo', 124, ['bar', 'baz'])) _run(c._handle_ack('/foo', 124, ['bar', 'baz']))
mock_cb.assert_not_called() mock_cb.assert_not_called()
self.assertIn(123, c.callbacks['/foo']) assert 123 in c.callbacks['/foo']
def test_handle_error(self): def test_handle_error(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -554,10 +667,11 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
_run(c._handle_error('/', 'error')) _run(c._handle_error('/', 'error'))
self.assertEqual(c.namespaces, []) assert c.namespaces == []
self.assertFalse(c.connected) assert not c.connected
c._trigger_event.mock.assert_called_once_with('connect_error', '/', c._trigger_event.mock.assert_called_once_with(
'error') 'connect_error', '/', 'error'
)
def test_handle_error_with_no_arguments(self): def test_handle_error_with_no_arguments(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -565,8 +679,8 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
_run(c._handle_error('/', None)) _run(c._handle_error('/', None))
self.assertEqual(c.namespaces, []) assert c.namespaces == []
self.assertFalse(c.connected) assert not c.connected
c._trigger_event.mock.assert_called_once_with('connect_error', '/') c._trigger_event.mock.assert_called_once_with('connect_error', '/')
def test_handle_error_namespace(self): def test_handle_error_namespace(self):
@ -575,10 +689,11 @@ class TestAsyncClient(unittest.TestCase):
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_error('/bar', ['error', 'message'])) _run(c._handle_error('/bar', ['error', 'message']))
self.assertEqual(c.namespaces, ['/foo']) assert c.namespaces == ['/foo']
self.assertTrue(c.connected) assert c.connected
c._trigger_event.mock.assert_called_once_with('connect_error', '/bar', c._trigger_event.mock.assert_called_once_with(
'error', 'message') 'connect_error', '/bar', 'error', 'message'
)
def test_handle_error_namespace_with_no_arguments(self): def test_handle_error_namespace_with_no_arguments(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -586,8 +701,8 @@ class TestAsyncClient(unittest.TestCase):
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
c._trigger_event = AsyncMock() c._trigger_event = AsyncMock()
_run(c._handle_error('/bar', None)) _run(c._handle_error('/bar', None))
self.assertEqual(c.namespaces, ['/foo']) assert c.namespaces == ['/foo']
self.assertTrue(c.connected) assert c.connected
c._trigger_event.mock.assert_called_once_with('connect_error', '/bar') c._trigger_event.mock.assert_called_once_with('connect_error', '/bar')
def test_handle_error_unknown_namespace(self): def test_handle_error_unknown_namespace(self):
@ -595,8 +710,8 @@ class TestAsyncClient(unittest.TestCase):
c.connected = True c.connected = True
c.namespaces = ['/foo', '/bar'] c.namespaces = ['/foo', '/bar']
_run(c._handle_error('/baz', 'error')) _run(c._handle_error('/baz', 'error'))
self.assertEqual(c.namespaces, ['/foo', '/bar']) assert c.namespaces == ['/foo', '/bar']
self.assertTrue(c.connected) assert c.connected
def test_trigger_event(self): def test_trigger_event(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -623,7 +738,7 @@ class TestAsyncClient(unittest.TestCase):
c.register_namespace(MyNamespace('/')) c.register_namespace(MyNamespace('/'))
_run(c._trigger_event('foo', '/', 1, '2')) _run(c._trigger_event('foo', '/', 1, '2'))
self.assertEqual(result, [1, '2']) assert result == [1, '2']
def test_trigger_event_unknown_namespace(self): def test_trigger_event_unknown_namespace(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -636,74 +751,96 @@ class TestAsyncClient(unittest.TestCase):
c.register_namespace(MyNamespace('/')) c.register_namespace(MyNamespace('/'))
_run(c._trigger_event('foo', '/bar', 1, '2')) _run(c._trigger_event('foo', '/bar', 1, '2'))
self.assertEqual(result, []) assert result == []
@mock.patch('asyncio.wait_for', new_callable=AsyncMock, @mock.patch(
side_effect=asyncio.TimeoutError) 'asyncio.wait_for',
new_callable=AsyncMock,
side_effect=asyncio.TimeoutError,
)
@mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5]) @mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5])
def test_handle_reconnect(self, random, wait_for): def test_handle_reconnect(self, random, wait_for):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._reconnect_task = 'foo' c._reconnect_task = 'foo'
c.connect = AsyncMock( c.connect = AsyncMock(
side_effect=[ValueError, exceptions.ConnectionError, None]) side_effect=[ValueError, exceptions.ConnectionError, None]
)
_run(c._handle_reconnect()) _run(c._handle_reconnect())
self.assertEqual(wait_for.mock.call_count, 3) assert wait_for.mock.call_count == 3
self.assertEqual( assert [x[0][1] for x in asyncio.wait_for.mock.call_args_list] == [
[x[0][1] for x in asyncio.wait_for.mock.call_args_list], 1.5,
[1.5, 1.5, 4.0]) 1.5,
self.assertEqual(c._reconnect_task, None) 4.0,
]
@mock.patch('asyncio.wait_for', new_callable=AsyncMock, assert c._reconnect_task is None
side_effect=asyncio.TimeoutError)
@mock.patch(
'asyncio.wait_for',
new_callable=AsyncMock,
side_effect=asyncio.TimeoutError,
)
@mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5]) @mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5])
def test_handle_reconnect_max_delay(self, random, wait_for): def test_handle_reconnect_max_delay(self, random, wait_for):
c = asyncio_client.AsyncClient(reconnection_delay_max=3) c = asyncio_client.AsyncClient(reconnection_delay_max=3)
c._reconnect_task = 'foo' c._reconnect_task = 'foo'
c.connect = AsyncMock( c.connect = AsyncMock(
side_effect=[ValueError, exceptions.ConnectionError, None]) side_effect=[ValueError, exceptions.ConnectionError, None]
)
_run(c._handle_reconnect()) _run(c._handle_reconnect())
self.assertEqual(wait_for.mock.call_count, 3) assert wait_for.mock.call_count == 3
self.assertEqual( assert [x[0][1] for x in asyncio.wait_for.mock.call_args_list] == [
[x[0][1] for x in asyncio.wait_for.mock.call_args_list], 1.5,
[1.5, 1.5, 3.0]) 1.5,
self.assertEqual(c._reconnect_task, None) 3.0,
]
@mock.patch('asyncio.wait_for', new_callable=AsyncMock, assert c._reconnect_task is None
side_effect=asyncio.TimeoutError)
@mock.patch(
'asyncio.wait_for',
new_callable=AsyncMock,
side_effect=asyncio.TimeoutError,
)
@mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5]) @mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5])
def test_handle_reconnect_max_attempts(self, random, wait_for): def test_handle_reconnect_max_attempts(self, random, wait_for):
c = asyncio_client.AsyncClient(reconnection_attempts=2) c = asyncio_client.AsyncClient(reconnection_attempts=2)
c._reconnect_task = 'foo' c._reconnect_task = 'foo'
c.connect = AsyncMock( c.connect = AsyncMock(
side_effect=[ValueError, exceptions.ConnectionError, None]) side_effect=[ValueError, exceptions.ConnectionError, None]
)
_run(c._handle_reconnect()) _run(c._handle_reconnect())
self.assertEqual(wait_for.mock.call_count, 2) assert wait_for.mock.call_count == 2
self.assertEqual( assert [x[0][1] for x in asyncio.wait_for.mock.call_args_list] == [
[x[0][1] for x in asyncio.wait_for.mock.call_args_list], 1.5,
[1.5, 1.5]) 1.5,
self.assertEqual(c._reconnect_task, 'foo') ]
assert c._reconnect_task == 'foo'
@mock.patch('asyncio.wait_for', new_callable=AsyncMock,
side_effect=[asyncio.TimeoutError, None]) @mock.patch(
'asyncio.wait_for',
new_callable=AsyncMock,
side_effect=[asyncio.TimeoutError, None],
)
@mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5]) @mock.patch('socketio.client.random.random', side_effect=[1, 0, 0.5])
def test_handle_reconnect_aborted(self, random, wait_for): def test_handle_reconnect_aborted(self, random, wait_for):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c._reconnect_task = 'foo' c._reconnect_task = 'foo'
c.connect = AsyncMock( c.connect = AsyncMock(
side_effect=[ValueError, exceptions.ConnectionError, None]) side_effect=[ValueError, exceptions.ConnectionError, None]
)
_run(c._handle_reconnect()) _run(c._handle_reconnect())
self.assertEqual(wait_for.mock.call_count, 2) assert wait_for.mock.call_count == 2
self.assertEqual( assert [x[0][1] for x in asyncio.wait_for.mock.call_args_list] == [
[x[0][1] for x in asyncio.wait_for.mock.call_args_list], 1.5,
[1.5, 1.5]) 1.5,
self.assertEqual(c._reconnect_task, 'foo') ]
assert c._reconnect_task == 'foo'
def test_eio_connect(self): def test_eio_connect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
c.eio.sid = 'foo' c.eio.sid = 'foo'
self.assertIsNone(c.sid) assert c.sid is None
c._handle_eio_connect() c._handle_eio_connect()
self.assertEqual(c.sid, 'foo') assert c.sid == 'foo'
def test_handle_eio_message(self): def test_handle_eio_message(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -736,18 +873,23 @@ class TestAsyncClient(unittest.TestCase):
_run(c._handle_eio_message('4/foo,["foo","bar"]')) _run(c._handle_eio_message('4/foo,["foo","bar"]'))
c._handle_error.mock.assert_called_with('/foo', ['foo', 'bar']) c._handle_error.mock.assert_called_with('/foo', ['foo', 'bar'])
_run(c._handle_eio_message('51-{"_placeholder":true,"num":0}')) _run(c._handle_eio_message('51-{"_placeholder":true,"num":0}'))
self.assertEqual(c._binary_packet.packet_type, packet.BINARY_EVENT) assert c._binary_packet.packet_type == packet.BINARY_EVENT
_run(c._handle_eio_message(b'foo')) _run(c._handle_eio_message(b'foo'))
c._handle_event.mock.assert_called_with(None, None, b'foo') c._handle_event.mock.assert_called_with(None, None, b'foo')
_run(c._handle_eio_message( _run(
'62-/foo,{"1":{"_placeholder":true,"num":1},' c._handle_eio_message(
'"2":{"_placeholder":true,"num":0}}')) '62-/foo,{"1":{"_placeholder":true,"num":1},'
self.assertEqual(c._binary_packet.packet_type, packet.BINARY_ACK) '"2":{"_placeholder":true,"num":0}}'
)
)
assert c._binary_packet.packet_type == packet.BINARY_ACK
_run(c._handle_eio_message(b'bar')) _run(c._handle_eio_message(b'bar'))
_run(c._handle_eio_message(b'foo')) _run(c._handle_eio_message(b'foo'))
c._handle_ack.mock.assert_called_with('/foo', None, {'1': b'foo', c._handle_ack.mock.assert_called_with(
'2': b'bar'}) '/foo', None, {'1': b'foo', '2': b'bar'}
self.assertRaises(ValueError, _run, c._handle_eio_message('9')) )
with pytest.raises(ValueError):
_run(c._handle_eio_message('9'))
def test_eio_disconnect(self): def test_eio_disconnect(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -757,9 +899,10 @@ class TestAsyncClient(unittest.TestCase):
c.eio.state = 'connected' c.eio.state = 'connected'
_run(c._handle_eio_disconnect()) _run(c._handle_eio_disconnect())
c._trigger_event.mock.assert_called_once_with( c._trigger_event.mock.assert_called_once_with(
'disconnect', namespace='/') 'disconnect', namespace='/'
self.assertIsNone(c.sid) )
self.assertFalse(c.connected) assert c.sid is None
assert not c.connected
def test_eio_disconnect_namespaces(self): def test_eio_disconnect_namespaces(self):
c = asyncio_client.AsyncClient() c = asyncio_client.AsyncClient()
@ -772,8 +915,8 @@ class TestAsyncClient(unittest.TestCase):
c._trigger_event.mock.assert_any_call('disconnect', namespace='/foo') c._trigger_event.mock.assert_any_call('disconnect', namespace='/foo')
c._trigger_event.mock.assert_any_call('disconnect', namespace='/bar') c._trigger_event.mock.assert_any_call('disconnect', namespace='/bar')
c._trigger_event.mock.assert_any_call('disconnect', namespace='/') c._trigger_event.mock.assert_any_call('disconnect', namespace='/')
self.assertIsNone(c.sid) assert c.sid is None
self.assertFalse(c.connected) assert not c.connected
def test_eio_disconnect_reconnect(self): def test_eio_disconnect_reconnect(self):
c = asyncio_client.AsyncClient(reconnection=True) c = asyncio_client.AsyncClient(reconnection=True)

186
tests/asyncio/test_asyncio_manager.py

@ -3,6 +3,7 @@ import sys
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -38,26 +39,28 @@ class TestAsyncManager(unittest.TestCase):
def test_connect(self): def test_connect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.assertIn(None, self.bm.rooms['/foo']) assert None in self.bm.rooms['/foo']
self.assertIn('123', self.bm.rooms['/foo']) assert '123' in self.bm.rooms['/foo']
self.assertIn('123', self.bm.rooms['/foo'][None]) assert '123' in self.bm.rooms['/foo'][None]
self.assertIn('123', self.bm.rooms['/foo']['123']) assert '123' in self.bm.rooms['/foo']['123']
self.assertEqual(self.bm.rooms['/foo'], {None: {'123': True}, assert self.bm.rooms['/foo'] == {
'123': {'123': True}}) None: {'123': True},
'123': {'123': True},
}
def test_pre_disconnect(self): def test_pre_disconnect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.bm.pre_disconnect('123', '/foo') self.bm.pre_disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123']}) assert self.bm.pending_disconnect == {'/foo': ['123']}
self.assertFalse(self.bm.is_connected('123', '/foo')) assert not self.bm.is_connected('123', '/foo')
self.bm.pre_disconnect('456', '/foo') self.bm.pre_disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123', '456']}) assert self.bm.pending_disconnect == {'/foo': ['123', '456']}
self.assertFalse(self.bm.is_connected('456', '/foo')) assert not self.bm.is_connected('456', '/foo')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['456']}) assert self.bm.pending_disconnect == {'/foo': ['456']}
self.bm.disconnect('456', '/foo') self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {}) assert self.bm.pending_disconnect == {}
def test_disconnect(self): def test_disconnect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -65,26 +68,32 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('456', '/foo', 'baz') self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, assert self.bm.rooms['/foo'] == {
'456': {'456': True}, None: {'456': True},
'baz': {'456': True}}) '456': {'456': True},
'baz': {'456': True},
}
def test_disconnect_default_namespace(self): def test_disconnect_default_namespace(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/') self.bm.connect('456', '/')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.assertTrue(self.bm.is_connected('123', '/')) assert self.bm.is_connected('123', '/')
self.assertTrue(self.bm.is_connected('123', '/foo')) assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.assertFalse(self.bm.is_connected('123', '/')) assert not self.bm.is_connected('123', '/')
self.assertTrue(self.bm.is_connected('123', '/foo')) assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertFalse(self.bm.is_connected('123', '/foo')) assert not self.bm.is_connected('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True}, assert self.bm.rooms['/'] == {
'456': {'456': True}}) None: {'456': True},
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, '456': {'456': True},
'456': {'456': True}}) }
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_twice(self): def test_disconnect_twice(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -95,10 +104,14 @@ class TestAsyncManager(unittest.TestCase):
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True}, assert self.bm.rooms['/'] == {
'456': {'456': True}}) None: {'456': True},
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, '456': {'456': True},
'456': {'456': True}}) }
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_all(self): def test_disconnect_all(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -107,7 +120,7 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'baz') self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.bm.disconnect('456', '/foo') self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.rooms, {}) assert self.bm.rooms == {}
def test_disconnect_with_callbacks(self): def test_disconnect_with_callbacks(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -115,9 +128,9 @@ class TestAsyncManager(unittest.TestCase):
self.bm._generate_ack_id('123', '/', 'f') self.bm._generate_ack_id('123', '/', 'f')
self.bm._generate_ack_id('123', '/foo', 'g') self.bm._generate_ack_id('123', '/foo', 'g')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertNotIn('/foo', self.bm.callbacks['123']) assert '/foo' not in self.bm.callbacks['123']
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.assertNotIn('123', self.bm.callbacks) assert '123' not in self.bm.callbacks
def test_trigger_sync_callback(self): def test_trigger_sync_callback(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -127,7 +140,7 @@ class TestAsyncManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb) id2 = self.bm._generate_ack_id('123', '/foo', cb)
_run(self.bm.trigger_callback('123', '/', id1, ['foo'])) _run(self.bm.trigger_callback('123', '/', id1, ['foo']))
_run(self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz'])) _run(self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz']))
self.assertEqual(cb.call_count, 2) assert cb.call_count == 2
cb.assert_any_call('foo') cb.assert_any_call('foo')
cb.assert_any_call('bar', 'baz') cb.assert_any_call('bar', 'baz')
@ -139,7 +152,7 @@ class TestAsyncManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb) id2 = self.bm._generate_ack_id('123', '/foo', cb)
_run(self.bm.trigger_callback('123', '/', id1, ['foo'])) _run(self.bm.trigger_callback('123', '/', id1, ['foo']))
_run(self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz'])) _run(self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz']))
self.assertEqual(cb.mock.call_count, 2) assert cb.mock.call_count == 2
cb.mock.assert_any_call('foo') cb.mock.assert_any_call('foo')
cb.mock.assert_any_call('bar', 'baz') cb.mock.assert_any_call('bar', 'baz')
@ -152,26 +165,26 @@ class TestAsyncManager(unittest.TestCase):
_run(self.bm.trigger_callback('124', '/', id, ['foo'])) _run(self.bm.trigger_callback('124', '/', id, ['foo']))
_run(self.bm.trigger_callback('123', '/foo', id, ['foo'])) _run(self.bm.trigger_callback('123', '/foo', id, ['foo']))
_run(self.bm.trigger_callback('123', '/', id + 1, ['foo'])) _run(self.bm.trigger_callback('123', '/', id + 1, ['foo']))
self.assertEqual(cb.mock.call_count, 0) assert cb.mock.call_count == 0
def test_get_namespaces(self): def test_get_namespaces(self):
self.assertEqual(list(self.bm.get_namespaces()), []) assert list(self.bm.get_namespaces()) == []
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
namespaces = list(self.bm.get_namespaces()) namespaces = list(self.bm.get_namespaces())
self.assertEqual(len(namespaces), 2) assert len(namespaces) == 2
self.assertIn('/', namespaces) assert '/' in namespaces
self.assertIn('/foo', namespaces) assert '/foo' in namespaces
def test_get_participants(self): def test_get_participants(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('456', '/') self.bm.connect('456', '/')
self.bm.connect('789', '/') self.bm.connect('789', '/')
self.bm.disconnect('789', '/') self.bm.disconnect('789', '/')
self.assertNotIn('789', self.bm.rooms['/'][None]) assert '789' not in self.bm.rooms['/'][None]
participants = list(self.bm.get_participants('/', None)) participants = list(self.bm.get_participants('/', None))
self.assertEqual(len(participants), 2) assert len(participants) == 2
self.assertNotIn('789', participants) assert '789' not in participants
def test_leave_invalid_room(self): def test_leave_invalid_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -180,7 +193,7 @@ class TestAsyncManager(unittest.TestCase):
def test_no_room(self): def test_no_room(self):
rooms = self.bm.get_rooms('123', '/foo') rooms = self.bm.get_rooms('123', '/foo')
self.assertEqual([], rooms) assert [] == rooms
def test_close_room(self): def test_close_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -189,7 +202,7 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
_run(self.bm.close_room('bar', '/foo')) _run(self.bm.close_room('bar', '/foo'))
self.assertNotIn('bar', self.bm.rooms['/foo']) assert 'bar' not in self.bm.rooms['/foo']
def test_close_invalid_room(self): def test_close_invalid_room(self):
self.bm.close_room('bar', '/foo') self.bm.close_room('bar', '/foo')
@ -198,17 +211,21 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
r = self.bm.get_rooms('123', '/foo') r = self.bm.get_rooms('123', '/foo')
self.assertEqual(len(r), 2) assert len(r) == 2
self.assertIn('123', r) assert '123' in r
self.assertIn('bar', r) assert 'bar' in r
def test_emit_to_sid(self): def test_emit_to_sid(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', _run(
room='123')) self.bm.emit(
'my event', {'foo': 'bar'}, namespace='/foo', room='123'
)
)
self.bm.server._emit_internal.mock.assert_called_once_with( self.bm.server._emit_internal.mock.assert_called_once_with(
'123', 'my event', {'foo': 'bar'}, '/foo', None) '123', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_room(self): def test_emit_to_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -216,13 +233,18 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', _run(
room='bar')) self.bm.emit(
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 2) 'my event', {'foo': 'bar'}, namespace='/foo', room='bar'
)
)
assert self.bm.server._emit_internal.mock.call_count == 2
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None) '123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None) '456', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all(self): def test_emit_to_all(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -232,13 +254,16 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo')) _run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo'))
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 3) assert self.bm.server._emit_internal.mock.call_count == 3
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None) '123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None) '456', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'789', 'my event', {'foo': 'bar'}, '/foo', None) '789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_one(self): def test_emit_to_all_skip_one(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -247,13 +272,18 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', _run(
skip_sid='456')) self.bm.emit(
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 2) 'my event', {'foo': 'bar'}, namespace='/foo', skip_sid='456'
)
)
assert self.bm.server._emit_internal.mock.call_count == 2
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None) '123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'789', 'my event', {'foo': 'bar'}, '/foo', None) '789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_two(self): def test_emit_to_all_skip_two(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -262,25 +292,37 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', _run(
skip_sid=['123', '789'])) self.bm.emit(
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 1) 'my event',
{'foo': 'bar'},
namespace='/foo',
skip_sid=['123', '789'],
)
)
assert self.bm.server._emit_internal.mock.call_count == 1
self.bm.server._emit_internal.mock.assert_any_call( self.bm.server._emit_internal.mock.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None) '456', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_with_callback(self): def test_emit_with_callback(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm._generate_ack_id = mock.MagicMock() self.bm._generate_ack_id = mock.MagicMock()
self.bm._generate_ack_id.return_value = 11 self.bm._generate_ack_id.return_value = 11
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', _run(
callback='cb')) self.bm.emit(
'my event', {'foo': 'bar'}, namespace='/foo', callback='cb'
)
)
self.bm._generate_ack_id.assert_called_once_with('123', '/foo', 'cb') self.bm._generate_ack_id.assert_called_once_with('123', '/foo', 'cb')
self.bm.server._emit_internal.mock.assert_called_once_with( self.bm.server._emit_internal.mock.assert_called_once_with(
'123', 'my event', {'foo': 'bar'}, '/foo', 11) '123', 'my event', {'foo': 'bar'}, '/foo', 11
)
def test_emit_to_invalid_room(self): def test_emit_to_invalid_room(self):
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/', _run(
room='123')) self.bm.emit('my event', {'foo': 'bar'}, namespace='/', room='123')
)
def test_emit_to_invalid_namespace(self): def test_emit_to_invalid_namespace(self):
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo')) _run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo'))

133
tests/asyncio/test_asyncio_namespace.py

@ -3,6 +3,7 @@ import sys
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -39,7 +40,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
_run(ns.trigger_event('connect', 'sid', {'foo': 'bar'})) _run(ns.trigger_event('connect', 'sid', {'foo': 'bar'}))
self.assertEqual(result['result'], ('sid', {'foo': 'bar'})) assert result['result'] == ('sid', {'foo': 'bar'})
def test_disconnect_event(self): def test_disconnect_event(self):
result = {} result = {}
@ -51,7 +52,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
_run(ns.trigger_event('disconnect', 'sid')) _run(ns.trigger_event('disconnect', 'sid'))
self.assertEqual(result['result'], 'sid') assert result['result'] == 'sid'
def test_sync_event(self): def test_sync_event(self):
result = {} result = {}
@ -63,7 +64,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
_run(ns.trigger_event('custom_message', 'sid', {'data': 'data'})) _run(ns.trigger_event('custom_message', 'sid', {'data': 'data'}))
self.assertEqual(result['result'], ('sid', {'data': 'data'})) assert result['result'] == ('sid', {'data': 'data'})
def test_async_event(self): def test_async_event(self):
result = {} result = {}
@ -75,7 +76,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
_run(ns.trigger_event('custom_message', 'sid', {'data': 'data'})) _run(ns.trigger_event('custom_message', 'sid', {'data': 'data'}))
self.assertEqual(result['result'], ('sid', {'data': 'data'})) assert result['result'] == ('sid', {'data': 'data'})
def test_event_not_found(self): def test_event_not_found(self):
result = {} result = {}
@ -86,25 +87,47 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
_run(ns.trigger_event('another_custom_message', 'sid', _run(
{'data': 'data'})) ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
self.assertEqual(result, {}) )
assert result == {}
def test_emit(self): def test_emit(self):
ns = asyncio_namespace.AsyncNamespace('/foo') ns = asyncio_namespace.AsyncNamespace('/foo')
mock_server = mock.MagicMock() mock_server = mock.MagicMock()
mock_server.emit = AsyncMock() mock_server.emit = AsyncMock()
ns._set_server(mock_server) ns._set_server(mock_server)
_run(ns.emit('ev', data='data', room='room', skip_sid='skip', _run(
callback='cb')) ns.emit(
'ev', data='data', room='room', skip_sid='skip', callback='cb'
)
)
ns.server.emit.mock.assert_called_with( ns.server.emit.mock.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/foo', 'ev',
callback='cb') data='data',
_run(ns.emit('ev', data='data', room='room', skip_sid='skip', room='room',
namespace='/bar', callback='cb')) skip_sid='skip',
namespace='/foo',
callback='cb',
)
_run(
ns.emit(
'ev',
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
)
ns.server.emit.mock.assert_called_with( ns.server.emit.mock.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/bar', 'ev',
callback='cb') data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_send(self): def test_send(self):
ns = asyncio_namespace.AsyncNamespace('/foo') ns = asyncio_namespace.AsyncNamespace('/foo')
@ -113,33 +136,52 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_server(mock_server) ns._set_server(mock_server)
_run(ns.send(data='data', room='room', skip_sid='skip', callback='cb')) _run(ns.send(data='data', room='room', skip_sid='skip', callback='cb'))
ns.server.send.mock.assert_called_with( ns.server.send.mock.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/foo', 'data',
callback='cb') room='room',
_run(ns.send(data='data', room='room', skip_sid='skip', skip_sid='skip',
namespace='/bar', callback='cb')) namespace='/foo',
callback='cb',
)
_run(
ns.send(
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
)
ns.server.send.mock.assert_called_with( ns.server.send.mock.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/bar', 'data',
callback='cb') room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_enter_room(self): def test_enter_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo') ns = asyncio_namespace.AsyncNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.enter_room('sid', 'room') ns.enter_room('sid', 'room')
ns.server.enter_room.assert_called_with('sid', 'room', ns.server.enter_room.assert_called_with(
namespace='/foo') 'sid', 'room', namespace='/foo'
)
ns.enter_room('sid', 'room', namespace='/bar') ns.enter_room('sid', 'room', namespace='/bar')
ns.server.enter_room.assert_called_with('sid', 'room', ns.server.enter_room.assert_called_with(
namespace='/bar') 'sid', 'room', namespace='/bar'
)
def test_leave_room(self): def test_leave_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo') ns = asyncio_namespace.AsyncNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.leave_room('sid', 'room') ns.leave_room('sid', 'room')
ns.server.leave_room.assert_called_with('sid', 'room', ns.server.leave_room.assert_called_with(
namespace='/foo') 'sid', 'room', namespace='/foo'
)
ns.leave_room('sid', 'room', namespace='/bar') ns.leave_room('sid', 'room', namespace='/bar')
ns.server.leave_room.assert_called_with('sid', 'room', ns.server.leave_room.assert_called_with(
namespace='/bar') 'sid', 'room', namespace='/bar'
)
def test_close_room(self): def test_close_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo') ns = asyncio_namespace.AsyncNamespace('/foo')
@ -170,11 +212,13 @@ class TestAsyncNamespace(unittest.TestCase):
_run(ns.get_session('sid', namespace='/bar')) _run(ns.get_session('sid', namespace='/bar'))
ns.server.get_session.mock.assert_called_with('sid', namespace='/bar') ns.server.get_session.mock.assert_called_with('sid', namespace='/bar')
_run(ns.save_session('sid', {'a': 'b'})) _run(ns.save_session('sid', {'a': 'b'}))
ns.server.save_session.mock.assert_called_with('sid', {'a': 'b'}, ns.server.save_session.mock.assert_called_with(
namespace='/foo') 'sid', {'a': 'b'}, namespace='/foo'
)
_run(ns.save_session('sid', {'a': 'b'}, namespace='/bar')) _run(ns.save_session('sid', {'a': 'b'}, namespace='/bar'))
ns.server.save_session.mock.assert_called_with('sid', {'a': 'b'}, ns.server.save_session.mock.assert_called_with(
namespace='/bar') 'sid', {'a': 'b'}, namespace='/bar'
)
ns.session('sid') ns.session('sid')
ns.server.session.assert_called_with('sid', namespace='/foo') ns.server.session.assert_called_with('sid', namespace='/foo')
ns.session('sid', namespace='/bar') ns.session('sid', namespace='/bar')
@ -200,7 +244,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock()) ns._set_client(mock.MagicMock())
_run(ns.trigger_event('custom_message', 'sid', {'data': 'data'})) _run(ns.trigger_event('custom_message', 'sid', {'data': 'data'}))
self.assertEqual(result['result'], ('sid', {'data': 'data'})) assert result['result'] == ('sid', {'data': 'data'})
def test_async_event_client(self): def test_async_event_client(self):
result = {} result = {}
@ -212,7 +256,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock()) ns._set_client(mock.MagicMock())
_run(ns.trigger_event('custom_message', 'sid', {'data': 'data'})) _run(ns.trigger_event('custom_message', 'sid', {'data': 'data'}))
self.assertEqual(result['result'], ('sid', {'data': 'data'})) assert result['result'] == ('sid', {'data': 'data'})
def test_event_not_found_client(self): def test_event_not_found_client(self):
result = {} result = {}
@ -223,9 +267,10 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock()) ns._set_client(mock.MagicMock())
_run(ns.trigger_event('another_custom_message', 'sid', _run(
{'data': 'data'})) ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
self.assertEqual(result, {}) )
assert result == {}
def test_emit_client(self): def test_emit_client(self):
ns = asyncio_namespace.AsyncClientNamespace('/foo') ns = asyncio_namespace.AsyncClientNamespace('/foo')
@ -234,10 +279,12 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_client(mock_client) ns._set_client(mock_client)
_run(ns.emit('ev', data='data', callback='cb')) _run(ns.emit('ev', data='data', callback='cb'))
ns.client.emit.mock.assert_called_with( ns.client.emit.mock.assert_called_with(
'ev', data='data', namespace='/foo', callback='cb') 'ev', data='data', namespace='/foo', callback='cb'
)
_run(ns.emit('ev', data='data', namespace='/bar', callback='cb')) _run(ns.emit('ev', data='data', namespace='/bar', callback='cb'))
ns.client.emit.mock.assert_called_with( ns.client.emit.mock.assert_called_with(
'ev', data='data', namespace='/bar', callback='cb') 'ev', data='data', namespace='/bar', callback='cb'
)
def test_send_client(self): def test_send_client(self):
ns = asyncio_namespace.AsyncClientNamespace('/foo') ns = asyncio_namespace.AsyncClientNamespace('/foo')
@ -246,10 +293,12 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_client(mock_client) ns._set_client(mock_client)
_run(ns.send(data='data', callback='cb')) _run(ns.send(data='data', callback='cb'))
ns.client.send.mock.assert_called_with( ns.client.send.mock.assert_called_with(
'data', namespace='/foo', callback='cb') 'data', namespace='/foo', callback='cb'
)
_run(ns.send(data='data', namespace='/bar', callback='cb')) _run(ns.send(data='data', namespace='/bar', callback='cb'))
ns.client.send.mock.assert_called_with( ns.client.send.mock.assert_called_with(
'data', namespace='/bar', callback='cb') 'data', namespace='/bar', callback='cb'
)
def test_disconnect_client(self): def test_disconnect_client(self):
ns = asyncio_namespace.AsyncClientNamespace('/foo') ns = asyncio_namespace.AsyncClientNamespace('/foo')

404
tests/asyncio/test_asyncio_pubsub_manager.py

@ -4,6 +4,7 @@ import sys
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -11,6 +12,7 @@ else:
from socketio import asyncio_manager from socketio import asyncio_manager
from socketio import asyncio_pubsub_manager from socketio import asyncio_pubsub_manager
import pytest
def AsyncMock(*args, **kwargs): def AsyncMock(*args, **kwargs):
@ -42,210 +44,369 @@ class TestAsyncPubSubManager(unittest.TestCase):
self.pm.initialize() self.pm.initialize()
def test_default_init(self): def test_default_init(self):
self.assertEqual(self.pm.channel, 'socketio') assert self.pm.channel == 'socketio'
self.pm.server.start_background_task.assert_called_once_with( self.pm.server.start_background_task.assert_called_once_with(
self.pm._thread) self.pm._thread
)
def test_custom_init(self): def test_custom_init(self):
pubsub = asyncio_pubsub_manager.AsyncPubSubManager(channel='foo') pubsub = asyncio_pubsub_manager.AsyncPubSubManager(channel='foo')
self.assertEqual(pubsub.channel, 'foo') assert pubsub.channel == 'foo'
self.assertEqual(len(pubsub.host_id), 32) assert len(pubsub.host_id) == 32
def test_write_only_init(self): def test_write_only_init(self):
mock_server = mock.MagicMock() mock_server = mock.MagicMock()
pm = asyncio_pubsub_manager.AsyncPubSubManager(write_only=True) pm = asyncio_pubsub_manager.AsyncPubSubManager(write_only=True)
pm.set_server(mock_server) pm.set_server(mock_server)
pm.initialize() pm.initialize()
self.assertEqual(pm.channel, 'socketio') assert pm.channel == 'socketio'
self.assertEqual(len(pm.host_id), 32) assert len(pm.host_id) == 32
self.assertEqual(pm.server.start_background_task.call_count, 0) assert pm.server.start_background_task.call_count == 0
def test_emit(self): def test_emit(self):
_run(self.pm.emit('foo', 'bar')) _run(self.pm.emit('foo', 'bar'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': None, 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_namespace(self): def test_emit_with_namespace(self):
_run(self.pm.emit('foo', 'bar', namespace='/baz')) _run(self.pm.emit('foo', 'bar', namespace='/baz'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/baz', 'room': None, 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_room(self): def test_emit_with_room(self):
_run(self.pm.emit('foo', 'bar', room='baz')) _run(self.pm.emit('foo', 'bar', room='baz'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': 'baz', 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_skip_sid(self): def test_emit_with_skip_sid(self):
_run(self.pm.emit('foo', 'bar', skip_sid='baz')) _run(self.pm.emit('foo', 'bar', skip_sid='baz'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': None, 'skip_sid': 'baz', 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': 'baz',
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_callback(self): def test_emit_with_callback(self):
with mock.patch.object(self.pm, '_generate_ack_id', with mock.patch.object(
return_value='123'): self.pm, '_generate_ack_id', return_value='123'
):
_run(self.pm.emit('foo', 'bar', room='baz', callback='cb')) _run(self.pm.emit('foo', 'bar', room='baz', callback='cb'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': 'baz', 'skip_sid': None, 'method': 'emit',
'callback': ('baz', '/', '123'), 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': ('baz', '/', '123'),
'host_id': '123456',
}
)
def test_emit_with_callback_without_server(self): def test_emit_with_callback_without_server(self):
standalone_pm = asyncio_pubsub_manager.AsyncPubSubManager() standalone_pm = asyncio_pubsub_manager.AsyncPubSubManager()
self.assertRaises(RuntimeError, _run, with pytest.raises(RuntimeError):
standalone_pm.emit('foo', 'bar', callback='cb')) _run(standalone_pm.emit('foo', 'bar', callback='cb'))
def test_emit_with_callback_missing_room(self): def test_emit_with_callback_missing_room(self):
with mock.patch.object(self.pm, '_generate_ack_id', with mock.patch.object(
return_value='123'): self.pm, '_generate_ack_id', return_value='123'
self.assertRaises(ValueError, _run, ):
self.pm.emit('foo', 'bar', callback='cb')) with pytest.raises(ValueError):
_run(self.pm.emit('foo', 'bar', callback='cb'))
def test_emit_with_ignore_queue(self): def test_emit_with_ignore_queue(self):
self.pm.connect('123', '/') self.pm.connect('123', '/')
_run(self.pm.emit('foo', 'bar', room='123', namespace='/', _run(
ignore_queue=True)) self.pm.emit(
'foo', 'bar', room='123', namespace='/', ignore_queue=True
)
)
self.pm._publish.mock.assert_not_called() self.pm._publish.mock.assert_not_called()
self.pm.server._emit_internal.mock.assert_called_once_with( self.pm.server._emit_internal.mock.assert_called_once_with(
'123', 'foo', 'bar', '/', None) '123', 'foo', 'bar', '/', None
)
def test_can_disconnect(self): def test_can_disconnect(self):
self.pm.connect('123', '/') self.pm.connect('123', '/')
self.assertTrue(_run(self.pm.can_disconnect('123', '/')) is True) assert _run(self.pm.can_disconnect('123', '/')) is True
_run(self.pm.can_disconnect('123', '/foo')) _run(self.pm.can_disconnect('123', '/foo'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}) {'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
def test_close_room(self): def test_close_room(self):
_run(self.pm.close_room('foo')) _run(self.pm.close_room('foo'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'close_room', 'room': 'foo', 'namespace': '/'}) {'method': 'close_room', 'room': 'foo', 'namespace': '/'}
)
def test_close_room_with_namespace(self): def test_close_room_with_namespace(self):
_run(self.pm.close_room('foo', '/bar')) _run(self.pm.close_room('foo', '/bar'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}) {'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}
)
def test_handle_emit(self): def test_handle_emit(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit', with mock.patch.object(
new=AsyncMock()) as super_emit: asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar'})) _run(self.pm._handle_emit({'event': 'foo', 'data': 'bar'}))
super_emit.mock.assert_called_once_with( super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room=None, self.pm,
skip_sid=None, callback=None) 'foo',
'bar',
namespace=None,
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_namespace(self): def test_handle_emit_with_namespace(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit', with mock.patch.object(
new=AsyncMock()) as super_emit: asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar', ) as super_emit:
'namespace': '/baz'})) _run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'namespace': '/baz'}
)
)
super_emit.mock.assert_called_once_with( super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace='/baz', room=None, self.pm,
skip_sid=None, callback=None) 'foo',
'bar',
namespace='/baz',
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_room(self): def test_handle_emit_with_room(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit', with mock.patch.object(
new=AsyncMock()) as super_emit: asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar', ) as super_emit:
'room': 'baz'})) _run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'room': 'baz'}
)
)
super_emit.mock.assert_called_once_with( super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room='baz', self.pm,
skip_sid=None, callback=None) 'foo',
'bar',
namespace=None,
room='baz',
skip_sid=None,
callback=None,
)
def test_handle_emit_with_skip_sid(self): def test_handle_emit_with_skip_sid(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit', with mock.patch.object(
new=AsyncMock()) as super_emit: asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar', ) as super_emit:
'skip_sid': '123'})) _run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'skip_sid': '123'}
)
)
super_emit.mock.assert_called_once_with( super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room=None, self.pm,
skip_sid='123', callback=None) 'foo',
'bar',
namespace=None,
room=None,
skip_sid='123',
callback=None,
)
def test_handle_emit_with_callback(self): def test_handle_emit_with_callback(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(asyncio_manager.AsyncManager, 'emit', with mock.patch.object(
new=AsyncMock()) as super_emit: asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar', ) as super_emit:
'namespace': '/baz', _run(
'callback': ('sid', '/baz', 123), self.pm._handle_emit(
'host_id': '123456'})) {
self.assertEqual(super_emit.mock.call_count, 1) 'event': 'foo',
self.assertEqual(super_emit.mock.call_args[0], 'data': 'bar',
(self.pm, 'foo', 'bar')) 'namespace': '/baz',
self.assertEqual(super_emit.mock.call_args[1]['namespace'], '/baz') 'callback': ('sid', '/baz', 123),
self.assertIsNone(super_emit.mock.call_args[1]['room']) 'host_id': '123456',
self.assertIsNone(super_emit.mock.call_args[1]['skip_sid']) }
self.assertIsInstance(super_emit.mock.call_args[1]['callback'], )
functools.partial) )
assert super_emit.mock.call_count == 1
assert super_emit.mock.call_args[0] == (self.pm, 'foo', 'bar')
assert super_emit.mock.call_args[1]['namespace'] == '/baz'
assert super_emit.mock.call_args[1]['room'] is None
assert super_emit.mock.call_args[1]['skip_sid'] is None
assert isinstance(
super_emit.mock.call_args[1]['callback'], functools.partial
)
_run(super_emit.mock.call_args[1]['callback']('one', 2, 'three')) _run(super_emit.mock.call_args[1]['callback']('one', 2, 'three'))
self.pm._publish.mock.assert_called_once_with( self.pm._publish.mock.assert_called_once_with(
{'method': 'callback', 'host_id': host_id, 'sid': 'sid', {
'namespace': '/baz', 'id': 123, 'args': ('one', 2, 'three')}) 'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/baz',
'id': 123,
'args': ('one', 2, 'three'),
}
)
def test_handle_callback(self): def test_handle_callback(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback', with mock.patch.object(
new=AsyncMock()) as trigger: self.pm, 'trigger_callback', new=AsyncMock()
_run(self.pm._handle_callback({'method': 'callback', ) as trigger:
'host_id': host_id, 'sid': 'sid', _run(
'namespace': '/', 'id': 123, self.pm._handle_callback(
'args': ('one', 2)})) {
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
)
trigger.mock.assert_called_once_with('sid', '/', 123, ('one', 2)) trigger.mock.assert_called_once_with('sid', '/', 123, ('one', 2))
def test_handle_callback_bad_host_id(self): def test_handle_callback_bad_host_id(self):
with mock.patch.object(self.pm, 'trigger_callback', with mock.patch.object(
new=AsyncMock()) as trigger: self.pm, 'trigger_callback', new=AsyncMock()
_run(self.pm._handle_callback({'method': 'callback', ) as trigger:
'host_id': 'bad', 'sid': 'sid', _run(
'namespace': '/', 'id': 123, self.pm._handle_callback(
'args': ('one', 2)})) {
self.assertEqual(trigger.mock.call_count, 0) 'method': 'callback',
'host_id': 'bad',
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
)
assert trigger.mock.call_count == 0
def test_handle_callback_missing_args(self): def test_handle_callback_missing_args(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback', with mock.patch.object(
new=AsyncMock()) as trigger: self.pm, 'trigger_callback', new=AsyncMock()
_run(self.pm._handle_callback({'method': 'callback', ) as trigger:
'host_id': host_id, 'sid': 'sid', _run(
'namespace': '/', 'id': 123})) self.pm._handle_callback(
_run(self.pm._handle_callback({'method': 'callback', {
'host_id': host_id, 'sid': 'sid', 'method': 'callback',
'namespace': '/'})) 'host_id': host_id,
_run(self.pm._handle_callback({'method': 'callback', 'sid': 'sid',
'host_id': host_id, 'sid': 'sid'})) 'namespace': '/',
_run(self.pm._handle_callback({'method': 'callback', 'id': 123,
'host_id': host_id})) }
self.assertEqual(trigger.mock.call_count, 0) )
)
_run(
self.pm._handle_callback(
{
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
}
)
)
_run(
self.pm._handle_callback(
{'method': 'callback', 'host_id': host_id, 'sid': 'sid'}
)
)
_run(
self.pm._handle_callback(
{'method': 'callback', 'host_id': host_id}
)
)
assert trigger.mock.call_count == 0
def test_handle_disconnect(self): def test_handle_disconnect(self):
_run(self.pm._handle_disconnect({'method': 'disconnect', 'sid': '123', _run(
'namespace': '/foo'})) self.pm._handle_disconnect(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
)
self.pm.server.disconnect.mock.assert_called_once_with( self.pm.server.disconnect.mock.assert_called_once_with(
sid='123', namespace='/foo', ignore_queue=True) sid='123', namespace='/foo', ignore_queue=True
)
def test_handle_close_room(self): def test_handle_close_room(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'close_room', with mock.patch.object(
new=AsyncMock()) as super_close_room: asyncio_manager.AsyncManager, 'close_room', new=AsyncMock()
_run(self.pm._handle_close_room({'method': 'close_room', ) as super_close_room:
'room': 'foo'})) _run(
self.pm._handle_close_room(
{'method': 'close_room', 'room': 'foo'}
)
)
super_close_room.mock.assert_called_once_with( super_close_room.mock.assert_called_once_with(
self.pm, room='foo', namespace=None) self.pm, room='foo', namespace=None
)
def test_handle_close_room_with_namespace(self): def test_handle_close_room_with_namespace(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'close_room', with mock.patch.object(
new=AsyncMock()) as super_close_room: asyncio_manager.AsyncManager, 'close_room', new=AsyncMock()
_run(self.pm._handle_close_room({'method': 'close_room', ) as super_close_room:
'room': 'foo', _run(
'namespace': '/bar'})) self.pm._handle_close_room(
{
'method': 'close_room',
'room': 'foo',
'namespace': '/bar',
}
)
)
super_close_room.mock.assert_called_once_with( super_close_room.mock.assert_called_once_with(
self.pm, room='foo', namespace='/bar') self.pm, room='foo', namespace='/bar'
)
def test_background_thread(self): def test_background_thread(self):
self.pm._handle_emit = AsyncMock() self.pm._handle_emit = AsyncMock()
@ -255,6 +416,7 @@ class TestAsyncPubSubManager(unittest.TestCase):
def messages(): def messages():
import pickle import pickle
yield {'method': 'emit', 'value': 'foo'} yield {'method': 'emit', 'value': 'foo'}
yield {'missing': 'method'} yield {'missing': 'method'}
yield '{"method": "callback", "value": "bar"}' yield '{"method": "callback", "value": "bar"}'
@ -271,10 +433,14 @@ class TestAsyncPubSubManager(unittest.TestCase):
pass pass
self.pm._handle_emit.mock.assert_called_once_with( self.pm._handle_emit.mock.assert_called_once_with(
{'method': 'emit', 'value': 'foo'}) {'method': 'emit', 'value': 'foo'}
)
self.pm._handle_callback.mock.assert_called_once_with( self.pm._handle_callback.mock.assert_called_once_with(
{'method': 'callback', 'value': 'bar'}) {'method': 'callback', 'value': 'bar'}
)
self.pm._handle_disconnect.mock.assert_called_once_with( self.pm._handle_disconnect.mock.assert_called_once_with(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}) {'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
self.pm._handle_close_room.mock.assert_called_once_with( self.pm._handle_close_room.mock.assert_called_once_with(
{'method': 'close_room', 'value': 'baz'}) {'method': 'close_room', 'value': 'baz'}
)

71
tests/asyncio/test_asyncio_redis_manager.py

@ -2,58 +2,71 @@ import sys
import unittest import unittest
from socketio import asyncio_redis_manager from socketio import asyncio_redis_manager
import pytest
@unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+') @unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+')
class TestAsyncRedisManager(unittest.TestCase): class TestAsyncRedisManager(unittest.TestCase):
def test_default_url(self): def test_default_url(self):
self.assertEqual(asyncio_redis_manager._parse_redis_url('redis://'), assert asyncio_redis_manager._parse_redis_url('redis://') == (
('localhost', 6379, None, 0, False)) 'localhost',
6379,
None,
0,
False,
)
def test_only_host_url(self): def test_only_host_url(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url(
asyncio_redis_manager._parse_redis_url('redis://redis.host'), 'redis://redis.host'
('redis.host', 6379, None, 0, False)) ) == ('redis.host', 6379, None, 0, False)
def test_no_db_url(self): def test_no_db_url(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url(
asyncio_redis_manager._parse_redis_url('redis://redis.host:123/1'), 'redis://redis.host:123/1'
('redis.host', 123, None, 1, False)) ) == ('redis.host', 123, None, 1, False)
def test_no_port_url(self): def test_no_port_url(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url(
asyncio_redis_manager._parse_redis_url('redis://redis.host/1'), 'redis://redis.host/1'
('redis.host', 6379, None, 1, False)) ) == ('redis.host', 6379, None, 1, False)
def test_password(self): def test_password(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url(
asyncio_redis_manager._parse_redis_url('redis://:[email protected]/1'), 'redis://:[email protected]/1'
('redis.host', 6379, 'pw', 1, False)) ) == ('redis.host', 6379, 'pw', 1, False)
def test_no_host_url(self): def test_no_host_url(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url('redis://:123/1') == (
asyncio_redis_manager._parse_redis_url('redis://:123/1'), 'localhost',
('localhost', 123, None, 1, False)) 123,
None,
1,
False,
)
def test_no_host_password_url(self): def test_no_host_password_url(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url(
asyncio_redis_manager._parse_redis_url('redis://:pw@:123/1'), 'redis://:pw@:123/1'
('localhost', 123, 'pw', 1, False)) ) == ('localhost', 123, 'pw', 1, False)
def test_bad_port_url(self): def test_bad_port_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url, with pytest.raises(ValueError):
'redis://localhost:abc/1') asyncio_redis_manager._parse_redis_url('redis://localhost:abc/1')
def test_bad_db_url(self): def test_bad_db_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url, with pytest.raises(ValueError):
'redis://localhost:abc/z') asyncio_redis_manager._parse_redis_url('redis://localhost:abc/z')
def test_bad_scheme_url(self): def test_bad_scheme_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url, with pytest.raises(ValueError):
'http://redis.host:123/1') asyncio_redis_manager._parse_redis_url('http://redis.host:123/1')
def test_ssl_scheme(self): def test_ssl_scheme(self):
self.assertEqual( assert asyncio_redis_manager._parse_redis_url('rediss://') == (
asyncio_redis_manager._parse_redis_url('rediss://'), 'localhost',
('localhost', 6379, None, 0, True) 6379,
None,
0,
True,
) )

477
tests/asyncio/test_asyncio_server.py

@ -5,6 +5,7 @@ import sys
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -15,6 +16,7 @@ from socketio import asyncio_namespace
from socketio import exceptions from socketio import exceptions
from socketio import namespace from socketio import namespace
from socketio import packet from socketio import packet
import pytest
def AsyncMock(*args, **kwargs): def AsyncMock(*args, **kwargs):
@ -51,15 +53,16 @@ class TestAsyncServer(unittest.TestCase):
def test_create(self, eio): def test_create(self, eio):
eio.return_value.handle_request = AsyncMock() eio.return_value.handle_request = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=True, foo='bar') client_manager=mgr, async_handlers=True, foo='bar'
)
_run(s.handle_request({})) _run(s.handle_request({}))
_run(s.handle_request({})) _run(s.handle_request({}))
eio.assert_called_once_with(**{'foo': 'bar', 'async_handlers': False}) eio.assert_called_once_with(**{'foo': 'bar', 'async_handlers': False})
self.assertEqual(s.manager, mgr) assert s.manager == mgr
self.assertEqual(s.eio.on.call_count, 3) assert s.eio.on.call_count == 3
self.assertEqual(s.binary, False) assert not s.binary
self.assertEqual(s.async_handlers, True) assert s.async_handlers
def test_attach(self, eio): def test_attach(self, eio):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
@ -75,54 +78,129 @@ class TestAsyncServer(unittest.TestCase):
def bar(): def bar():
pass pass
s.on('disconnect', bar) s.on('disconnect', bar)
s.on('disconnect', bar, namespace='/foo') s.on('disconnect', bar, namespace='/foo')
self.assertEqual(s.handlers['/']['connect'], foo) assert s.handlers['/']['connect'] == foo
self.assertEqual(s.handlers['/']['disconnect'], bar) assert s.handlers['/']['disconnect'] == bar
self.assertEqual(s.handlers['/foo']['disconnect'], bar) assert s.handlers['/foo']['disconnect'] == bar
def test_emit(self, eio): def test_emit(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
_run(s.emit('my event', {'foo': 'bar'}, to='room', _run(
skip_sid='123', namespace='/foo', callback='cb')) s.emit(
'my event',
{'foo': 'bar'},
to='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
)
s.manager.emit.mock.assert_called_once_with( s.manager.emit.mock.assert_called_once_with(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
_run(s.emit('my event', {'foo': 'bar'}, room='room', '/foo',
skip_sid='123', namespace='/foo', callback='cb')) room='room',
skip_sid='123',
callback='cb',
)
_run(
s.emit(
'my event',
{'foo': 'bar'},
room='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
)
s.manager.emit.mock.assert_called_with( s.manager.emit.mock.assert_called_with(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_emit_default_namespace(self, eio): def test_emit_default_namespace(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
_run(s.emit('my event', {'foo': 'bar'}, to='room', _run(
skip_sid='123', callback='cb')) s.emit(
'my event',
{'foo': 'bar'},
to='room',
skip_sid='123',
callback='cb',
)
)
s.manager.emit.mock.assert_called_once_with( s.manager.emit.mock.assert_called_once_with(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
_run(s.emit('my event', {'foo': 'bar'}, room='room', '/',
skip_sid='123', callback='cb')) room='room',
skip_sid='123',
callback='cb',
)
_run(
s.emit(
'my event',
{'foo': 'bar'},
room='room',
skip_sid='123',
callback='cb',
)
)
s.manager.emit.mock.assert_called_with( s.manager.emit.mock.assert_called_with(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
'/',
room='room',
skip_sid='123',
callback='cb',
)
def test_send(self, eio): def test_send(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
_run(s.send('foo', to='room', skip_sid='123', namespace='/foo', _run(
callback='cb')) s.send(
'foo',
to='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
)
s.manager.emit.mock.assert_called_once_with( s.manager.emit.mock.assert_called_once_with(
'message', 'foo', '/foo', room='room', skip_sid='123', 'message',
callback='cb') 'foo',
_run(s.send('foo', room='room', skip_sid='123', namespace='/foo', '/foo',
callback='cb')) room='room',
skip_sid='123',
callback='cb',
)
_run(
s.send(
'foo',
room='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
)
s.manager.emit.mock.assert_called_with( s.manager.emit.mock.assert_called_with(
'message', 'foo', '/foo', room='room', skip_sid='123', 'message',
callback='cb') 'foo',
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_call(self, eio): def test_call(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
@ -133,7 +211,7 @@ class TestAsyncServer(unittest.TestCase):
return True return True
s.eio.create_event.return_value.wait = fake_event_wait s.eio.create_event.return_value.wait = fake_event_wait
self.assertEqual(_run(s.call('foo', sid='123')), ('foo', 321)) assert _run(s.call('foo', sid='123')) == ('foo', 321)
def test_call_with_timeout(self, eio): def test_call_with_timeout(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
@ -143,19 +221,21 @@ class TestAsyncServer(unittest.TestCase):
await asyncio.sleep(1) await asyncio.sleep(1)
s.eio.create_event.return_value.wait = fake_event_wait s.eio.create_event.return_value.wait = fake_event_wait
self.assertRaises(exceptions.TimeoutError, _run, with pytest.raises(exceptions.TimeoutError):
s.call('foo', sid='123', timeout=0.01)) _run(s.call('foo', sid='123', timeout=0.01))
def test_call_with_broadcast(self, eio): def test_call_with_broadcast(self, eio):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
self.assertRaises(ValueError, _run, s.call('foo')) with pytest.raises(ValueError):
_run(s.call('foo'))
def test_call_without_async_handlers(self, eio): def test_call_without_async_handlers(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=False) client_manager=mgr, async_handlers=False
self.assertRaises(RuntimeError, _run, )
s.call('foo', sid='123', timeout=12)) with pytest.raises(RuntimeError):
_run(s.call('foo', sid='123', timeout=12))
def test_enter_room(self, eio): def test_enter_room(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
@ -216,59 +296,74 @@ class TestAsyncServer(unittest.TestCase):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', 'my event', 'my data', namespace='/foo')) _run(s._emit_internal('123', 'my event', 'my data', namespace='/foo'))
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2/foo,["my event","my data"]', binary=False) '123', '2/foo,["my event","my data"]', binary=False
)
def test_emit_internal_with_tuple(self, eio): def test_emit_internal_with_tuple(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', 'my event', ('foo', 'bar'), _run(
namespace='/foo')) s._emit_internal(
'123', 'my event', ('foo', 'bar'), namespace='/foo'
)
)
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2/foo,["my event","foo","bar"]', binary=False) '123', '2/foo,["my event","foo","bar"]', binary=False
)
def test_emit_internal_with_list(self, eio): def test_emit_internal_with_list(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', 'my event', ['foo', 'bar'], _run(
namespace='/foo')) s._emit_internal(
'123', 'my event', ['foo', 'bar'], namespace='/foo'
)
)
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2/foo,["my event",["foo","bar"]]', binary=False) '123', '2/foo,["my event",["foo","bar"]]', binary=False
)
def test_emit_internal_with_none(self, eio): def test_emit_internal_with_none(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', 'my event', None, namespace='/foo')) _run(s._emit_internal('123', 'my event', None, namespace='/foo'))
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2/foo,["my event"]', binary=False) '123', '2/foo,["my event"]', binary=False
)
def test_emit_internal_with_callback(self, eio): def test_emit_internal_with_callback(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
id = s.manager._generate_ack_id('123', '/foo', 'cb') id = s.manager._generate_ack_id('123', '/foo', 'cb')
_run(s._emit_internal('123', 'my event', 'my data', namespace='/foo', _run(
id=id)) s._emit_internal(
'123', 'my event', 'my data', namespace='/foo', id=id
)
)
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2/foo,1["my event","my data"]', binary=False) '123', '2/foo,1["my event","my data"]', binary=False
)
def test_emit_internal_default_namespace(self, eio): def test_emit_internal_default_namespace(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', 'my event', 'my data')) _run(s._emit_internal('123', 'my event', 'my data'))
s.eio.send.mock.assert_called_once_with( s.eio.send.mock.assert_called_once_with(
'123', '2["my event","my data"]', binary=False) '123', '2["my event","my data"]', binary=False
)
def test_emit_internal_binary(self, eio): def test_emit_internal_binary(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
_run(s._emit_internal('123', u'my event', b'my binary data')) _run(s._emit_internal('123', u'my event', b'my binary data'))
self.assertEqual(s.eio.send.mock.call_count, 2) assert s.eio.send.mock.call_count == 2
def test_transport(self, eio): def test_transport(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
s.eio.transport = mock.MagicMock(return_value='polling') s.eio.transport = mock.MagicMock(return_value='polling')
_run(s._handle_eio_connect('foo', 'environ')) _run(s._handle_eio_connect('foo', 'environ'))
self.assertEqual(s.transport('foo'), 'polling') assert s.transport('foo') == 'polling'
s.eio.transport.assert_called_once_with('foo') s.eio.transport.assert_called_once_with('foo')
def test_handle_connect(self, eio): def test_handle_connect(self, eio):
@ -281,9 +376,9 @@ class TestAsyncServer(unittest.TestCase):
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
s.manager.connect.assert_called_once_with('123', '/') s.manager.connect.assert_called_once_with('123', '/')
s.eio.send.mock.assert_called_once_with('123', '0', binary=False) s.eio.send.mock.assert_called_once_with('123', '0', binary=False)
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
_run(s._handle_eio_connect('456', 'environ')) _run(s._handle_eio_connect('456', 'environ'))
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
def test_handle_connect_async(self, eio): def test_handle_connect_async(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -295,9 +390,9 @@ class TestAsyncServer(unittest.TestCase):
handler.mock.assert_called_once_with('123', 'environ') handler.mock.assert_called_once_with('123', 'environ')
s.manager.connect.assert_called_once_with('123', '/') s.manager.connect.assert_called_once_with('123', '/')
s.eio.send.mock.assert_called_once_with('123', '0', binary=False) s.eio.send.mock.assert_called_once_with('123', '0', binary=False)
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
_run(s._handle_eio_connect('456', 'environ')) _run(s._handle_eio_connect('456', 'environ'))
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
def test_handle_connect_namespace(self, eio): def test_handle_connect_namespace(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -318,11 +413,11 @@ class TestAsyncServer(unittest.TestCase):
handler = mock.MagicMock(return_value=False) handler = mock.MagicMock(return_value=False)
s.on('connect', handler) s.on('connect', handler)
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
self.assertFalse(ret) assert not ret
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_namespace_rejected(self, eio): def test_handle_connect_namespace_rejected(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -332,41 +427,39 @@ class TestAsyncServer(unittest.TestCase):
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.mock.assert_any_call('123', '4/foo', binary=False) s.eio.send.mock.assert_any_call('123', '4/foo', binary=False)
def test_handle_connect_rejected_always_connect(self, eio): def test_handle_connect_rejected_always_connect(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(client_manager=mgr, always_connect=True)
always_connect=True)
handler = mock.MagicMock(return_value=False) handler = mock.MagicMock(return_value=False)
s.on('connect', handler) s.on('connect', handler)
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
self.assertFalse(ret) assert not ret
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
s.eio.send.mock.assert_any_call('123', '0', binary=False) s.eio.send.mock.assert_any_call('123', '0', binary=False)
s.eio.send.mock.assert_any_call('123', '1', binary=False) s.eio.send.mock.assert_any_call('123', '1', binary=False)
def test_handle_connect_namespace_rejected_always_connect(self, eio): def test_handle_connect_namespace_rejected_always_connect(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(client_manager=mgr, always_connect=True)
always_connect=True)
handler = mock.MagicMock(return_value=False) handler = mock.MagicMock(return_value=False)
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
self.assertFalse(ret) assert not ret
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.mock.assert_any_call('123', '0/foo', binary=False) s.eio.send.mock.assert_any_call('123', '0/foo', binary=False)
s.eio.send.mock.assert_any_call('123', '1/foo', binary=False) s.eio.send.mock.assert_any_call('123', '1/foo', binary=False)
@ -375,56 +468,61 @@ class TestAsyncServer(unittest.TestCase):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError('fail_reason')) side_effect=exceptions.ConnectionRefusedError('fail_reason')
)
s.on('connect', handler) s.on('connect', handler)
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
self.assertEqual(ret, 'fail_reason') assert ret == 'fail_reason'
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_rejected_with_empty_exception(self, eio): def test_handle_connect_rejected_with_empty_exception(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError()) side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler) s.on('connect', handler)
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
self.assertFalse(ret) assert not ret
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_namespace_rejected_with_exception(self, eio): def test_handle_connect_namespace_rejected_with_exception(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError('fail_reason', 1)) side_effect=exceptions.ConnectionRefusedError('fail_reason', 1)
)
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.mock.assert_any_call('123', '4/foo,["fail_reason",1]', s.eio.send.mock.assert_any_call(
binary=False) '123', '4/foo,["fail_reason",1]', binary=False
)
def test_handle_connect_namespace_rejected_with_empty_exception(self, eio): def test_handle_connect_namespace_rejected_with_empty_exception(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr) s = asyncio_server.AsyncServer(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError()) side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = _run(s._handle_eio_connect('123', 'environ')) ret = _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.mock.assert_any_call('123', '4/foo', binary=False) s.eio.send.mock.assert_any_call('123', '4/foo', binary=False)
def test_handle_disconnect(self, eio): def test_handle_disconnect(self, eio):
@ -437,7 +535,7 @@ class TestAsyncServer(unittest.TestCase):
_run(s._handle_eio_disconnect('123')) _run(s._handle_eio_disconnect('123'))
handler.assert_called_once_with('123') handler.assert_called_once_with('123')
s.manager.disconnect.assert_called_once_with('123', '/') s.manager.disconnect.assert_called_once_with('123', '/')
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_disconnect_namespace(self, eio): def test_handle_disconnect_namespace(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -453,7 +551,7 @@ class TestAsyncServer(unittest.TestCase):
_run(s._handle_eio_disconnect('123')) _run(s._handle_eio_disconnect('123'))
handler.assert_called_once_with('123') handler.assert_called_once_with('123')
handler_namespace.assert_called_once_with('123') handler_namespace.assert_called_once_with('123')
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_disconnect_only_namespace(self, eio): def test_handle_disconnect_only_namespace(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -467,9 +565,9 @@ class TestAsyncServer(unittest.TestCase):
_run(s._handle_eio_connect('123', 'environ')) _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
_run(s._handle_eio_message('123', '1/foo')) _run(s._handle_eio_message('123', '1/foo'))
self.assertEqual(handler.call_count, 0) assert handler.call_count == 0
handler_namespace.assert_called_once_with('123') handler_namespace.assert_called_once_with('123')
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
def test_handle_disconnect_unknown_client(self, eio): def test_handle_disconnect_unknown_client(self, eio):
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
@ -509,9 +607,14 @@ class TestAsyncServer(unittest.TestCase):
s.manager.connect('123', '/') s.manager.connect('123', '/')
handler = mock.MagicMock() handler = mock.MagicMock()
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '52-["my message","a",' _run(
'{"_placeholder":true,"num":1},' s._handle_eio_message(
'{"_placeholder":true,"num":0}]')) '123',
'52-["my message","a",'
'{"_placeholder":true,"num":1},'
'{"_placeholder":true,"num":0}]',
)
)
_run(s._handle_eio_message('123', b'foo')) _run(s._handle_eio_message('123', b'foo'))
_run(s._handle_eio_message('123', b'bar')) _run(s._handle_eio_message('123', b'bar'))
handler.assert_called_once_with('123', 'a', b'bar', b'foo') handler.assert_called_once_with('123', 'a', b'bar', b'foo')
@ -519,14 +622,20 @@ class TestAsyncServer(unittest.TestCase):
def test_handle_event_binary_ack(self, eio): def test_handle_event_binary_ack(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=False) client_manager=mgr, async_handlers=False
)
s.manager.initialize(s) s.manager.initialize(s)
_run(s._handle_eio_message('123', '61-321["my message","a",' _run(
'{"_placeholder":true,"num":0}]')) s._handle_eio_message(
'123',
'61-321["my message","a",' '{"_placeholder":true,"num":0}]',
)
)
_run(s._handle_eio_message('123', b'foo')) _run(s._handle_eio_message('123', b'foo'))
mgr.trigger_callback.mock.assert_called_once_with( mgr.trigger_callback.mock.assert_called_once_with(
'123', '/', 321, ['my message', 'a', b'foo']) '123', '/', 321, ['my message', 'a', b'foo']
)
def test_handle_event_with_ack(self, eio): def test_handle_event_with_ack(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -536,8 +645,9 @@ class TestAsyncServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '21000["my message","foo"]')) _run(s._handle_eio_message('123', '21000["my message","foo"]'))
handler.assert_called_once_with('123', 'foo') handler.assert_called_once_with('123', 'foo')
s.eio.send.mock.assert_called_once_with('123', '31000["foo"]', s.eio.send.mock.assert_called_once_with(
binary=False) '123', '31000["foo"]', binary=False
)
def test_handle_event_with_ack_none(self, eio): def test_handle_event_with_ack_none(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -547,38 +657,42 @@ class TestAsyncServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '21000["my message","foo"]')) _run(s._handle_eio_message('123', '21000["my message","foo"]'))
handler.assert_called_once_with('123', 'foo') handler.assert_called_once_with('123', 'foo')
s.eio.send.mock.assert_called_once_with('123', '31000[]', s.eio.send.mock.assert_called_once_with('123', '31000[]', binary=False)
binary=False)
def test_handle_event_with_ack_tuple(self, eio): def test_handle_event_with_ack_tuple(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=False) client_manager=mgr, async_handlers=False
)
handler = mock.MagicMock(return_value=(1, '2', True)) handler = mock.MagicMock(return_value=(1, '2', True))
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '21000["my message","a","b","c"]')) _run(s._handle_eio_message('123', '21000["my message","a","b","c"]'))
handler.assert_called_once_with('123', 'a', 'b', 'c') handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.mock.assert_called_once_with('123', '31000[1,"2",true]', s.eio.send.mock.assert_called_once_with(
binary=False) '123', '31000[1,"2",true]', binary=False
)
def test_handle_event_with_ack_list(self, eio): def test_handle_event_with_ack_list(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=False) client_manager=mgr, async_handlers=False
)
handler = mock.MagicMock(return_value=[1, '2', True]) handler = mock.MagicMock(return_value=[1, '2', True])
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '21000["my message","a","b","c"]')) _run(s._handle_eio_message('123', '21000["my message","a","b","c"]'))
handler.assert_called_once_with('123', 'a', 'b', 'c') handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.mock.assert_called_once_with('123', '31000[[1,"2",true]]', s.eio.send.mock.assert_called_once_with(
binary=False) '123', '31000[[1,"2",true]]', binary=False
)
def test_handle_event_with_ack_binary(self, eio): def test_handle_event_with_ack_binary(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
mgr = self._get_mock_manager() mgr = self._get_mock_manager()
s = asyncio_server.AsyncServer(client_manager=mgr, s = asyncio_server.AsyncServer(
async_handlers=False) client_manager=mgr, async_handlers=False
)
handler = mock.MagicMock(return_value=b'foo') handler = mock.MagicMock(return_value=b'foo')
s.on('my message', handler) s.on('my message', handler)
_run(s._handle_eio_message('123', '21000["my message","foo"]')) _run(s._handle_eio_message('123', '21000["my message","foo"]'))
@ -586,11 +700,13 @@ class TestAsyncServer(unittest.TestCase):
def test_handle_error_packet(self, eio): def test_handle_error_packet(self, eio):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
self.assertRaises(ValueError, _run, s._handle_eio_message('123', '4')) with pytest.raises(ValueError):
_run(s._handle_eio_message('123', '4'))
def test_handle_invalid_packet(self, eio): def test_handle_invalid_packet(self, eio):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
self.assertRaises(ValueError, _run, s._handle_eio_message('123', '9')) with pytest.raises(ValueError):
_run(s._handle_eio_message('123', '9'))
def test_send_with_ack(self, eio): def test_send_with_ack(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -611,8 +727,11 @@ class TestAsyncServer(unittest.TestCase):
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
cb = mock.MagicMock() cb = mock.MagicMock()
id = s.manager._generate_ack_id('123', '/foo', cb) id = s.manager._generate_ack_id('123', '/foo', cb)
_run(s._emit_internal('123', 'my event', ['foo'], namespace='/foo', _run(
id=id)) s._emit_internal(
'123', 'my event', ['foo'], namespace='/foo', id=id
)
)
_run(s._handle_eio_message('123', '3/foo,1["foo",2]')) _run(s._handle_eio_message('123', '3/foo,1["foo",2]'))
cb.assert_called_once_with('foo', 2) cb.assert_called_once_with('foo', 2)
@ -635,20 +754,20 @@ class TestAsyncServer(unittest.TestCase):
await s._handle_eio_connect('123', 'environ') await s._handle_eio_connect('123', 'environ')
await s.save_session('123', {'foo': 'bar'}) await s.save_session('123', {'foo': 'bar'})
async with s.session('123') as session: async with s.session('123') as session:
self.assertEqual(session, {'foo': 'bar'}) assert session == {'foo': 'bar'}
session['foo'] = 'baz' session['foo'] = 'baz'
session['bar'] = 'foo' session['bar'] = 'foo'
self.assertEqual(await s.get_session('123'), assert await s.get_session('123') == {'foo': 'baz', 'bar': 'foo'}
{'foo': 'baz', 'bar': 'foo'}) assert fake_session == {'/': {'foo': 'baz', 'bar': 'foo'}}
self.assertEqual(fake_session,
{'/': {'foo': 'baz', 'bar': 'foo'}})
async with s.session('123', namespace='/ns') as session: async with s.session('123', namespace='/ns') as session:
self.assertEqual(session, {}) assert session == {}
session['a'] = 'b' session['a'] = 'b'
self.assertEqual(await s.get_session('123', namespace='/ns'), assert await s.get_session('123', namespace='/ns') == {'a': 'b'}
{'a': 'b'}) assert fake_session == {
self.assertEqual(fake_session, {'/': {'foo': 'baz', 'bar': 'foo'}, '/': {'foo': 'baz', 'bar': 'foo'},
'/ns': {'a': 'b'}}) '/ns': {'a': 'b'},
}
_run(_test()) _run(_test())
def test_disconnect(self, eio): def test_disconnect(self, eio):
@ -687,8 +806,8 @@ class TestAsyncServer(unittest.TestCase):
_run(s.disconnect('123')) _run(s.disconnect('123'))
calls = s.eio.send.mock.call_count calls = s.eio.send.mock.call_count
_run(s.disconnect('123')) _run(s.disconnect('123'))
self.assertEqual(calls, s.eio.send.mock.call_count) assert calls == s.eio.send.mock.call_count
self.assertEqual(s.eio.disconnect.mock.call_count, 1) assert s.eio.disconnect.mock.call_count == 1
def test_disconnect_twice_namespace(self, eio): def test_disconnect_twice_namespace(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -698,7 +817,7 @@ class TestAsyncServer(unittest.TestCase):
_run(s.disconnect('123', namespace='/foo')) _run(s.disconnect('123', namespace='/foo'))
calls = s.eio.send.mock.call_count calls = s.eio.send.mock.call_count
_run(s.disconnect('123', namespace='/foo')) _run(s.disconnect('123', namespace='/foo'))
self.assertEqual(calls, s.eio.send.mock.call_count) assert calls == s.eio.send.mock.call_count
def test_namespace_handler(self, eio): def test_namespace_handler(self, eio):
eio.return_value.send = AsyncMock() eio.return_value.send = AsyncMock()
@ -724,15 +843,15 @@ class TestAsyncServer(unittest.TestCase):
s.register_namespace(MyNamespace('/foo')) s.register_namespace(MyNamespace('/foo'))
_run(s._handle_eio_connect('123', 'environ')) _run(s._handle_eio_connect('123', 'environ'))
_run(s._handle_eio_message('123', '0/foo')) _run(s._handle_eio_message('123', '0/foo'))
self.assertEqual(result['result'], ('123', 'environ')) assert result['result'] == ('123', 'environ')
_run(s._handle_eio_message('123', '2/foo,["foo","a"]')) _run(s._handle_eio_message('123', '2/foo,["foo","a"]'))
self.assertEqual(result['result'], ('123', 'a')) assert result['result'] == ('123', 'a')
_run(s._handle_eio_message('123', '2/foo,["bar"]')) _run(s._handle_eio_message('123', '2/foo,["bar"]'))
self.assertEqual(result['result'], 'bar') assert result['result'] == 'bar'
_run(s._handle_eio_message('123', '2/foo,["baz","a","b"]')) _run(s._handle_eio_message('123', '2/foo,["baz","a","b"]'))
self.assertEqual(result['result'], ('a', 'b')) assert result['result'] == ('a', 'b')
_run(s.disconnect('123', '/foo')) _run(s.disconnect('123', '/foo'))
self.assertEqual(result['result'], ('disconnect', '123')) assert result['result'] == ('disconnect', '123')
def test_bad_namespace_handler(self, eio): def test_bad_namespace_handler(self, eio):
class Dummy(object): class Dummy(object):
@ -742,30 +861,35 @@ class TestAsyncServer(unittest.TestCase):
pass pass
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
self.assertRaises(ValueError, s.register_namespace, 123) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, Dummy) s.register_namespace(123)
self.assertRaises(ValueError, s.register_namespace, Dummy()) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, s.register_namespace(Dummy)
namespace.Namespace) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, SyncNS()) s.register_namespace(Dummy())
with pytest.raises(ValueError):
s.register_namespace(namespace.Namespace)
with pytest.raises(ValueError):
s.register_namespace(SyncNS())
def test_logger(self, eio): def test_logger(self, eio):
s = asyncio_server.AsyncServer(logger=False) s = asyncio_server.AsyncServer(logger=False)
self.assertEqual(s.logger.getEffectiveLevel(), logging.ERROR) assert s.logger.getEffectiveLevel() == logging.ERROR
s.logger.setLevel(logging.NOTSET) s.logger.setLevel(logging.NOTSET)
s = asyncio_server.AsyncServer(logger=True) s = asyncio_server.AsyncServer(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.INFO) assert s.logger.getEffectiveLevel() == logging.INFO
s.logger.setLevel(logging.WARNING) s.logger.setLevel(logging.WARNING)
s = asyncio_server.AsyncServer(logger=True) s = asyncio_server.AsyncServer(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.WARNING) assert s.logger.getEffectiveLevel() == logging.WARNING
s.logger.setLevel(logging.NOTSET) s.logger.setLevel(logging.NOTSET)
s = asyncio_server.AsyncServer(logger='foo') s = asyncio_server.AsyncServer(logger='foo')
self.assertEqual(s.logger, 'foo') assert s.logger == 'foo'
def test_engineio_logger(self, eio): def test_engineio_logger(self, eio):
asyncio_server.AsyncServer(engineio_logger='foo') asyncio_server.AsyncServer(engineio_logger='foo')
eio.assert_called_once_with(**{'logger': 'foo', eio.assert_called_once_with(
'async_handlers': False}) **{'logger': 'foo', 'async_handlers': False}
)
def test_custom_json(self, eio): def test_custom_json(self, eio):
# Warning: this test cannot run in parallel with other tests, as it # Warning: this test cannot run in parallel with other tests, as it
@ -781,14 +905,17 @@ class TestAsyncServer(unittest.TestCase):
return '+++ decoded +++' return '+++ decoded +++'
asyncio_server.AsyncServer(json=CustomJSON) asyncio_server.AsyncServer(json=CustomJSON)
eio.assert_called_once_with(**{'json': CustomJSON, eio.assert_called_once_with(
'async_handlers': False}) **{'json': CustomJSON, 'async_handlers': False}
)
pkt = packet.Packet(packet_type=packet.EVENT,
data={six.text_type('foo'): six.text_type('bar')}) pkt = packet.Packet(
self.assertEqual(pkt.encode(), '2*** encoded ***') packet_type=packet.EVENT,
data={six.text_type('foo'): six.text_type('bar')},
)
assert pkt.encode() == '2*** encoded ***'
pkt2 = packet.Packet(encoded_packet=pkt.encode()) pkt2 = packet.Packet(encoded_packet=pkt.encode())
self.assertEqual(pkt2.data, '+++ decoded +++') assert pkt2.data == '+++ decoded +++'
# restore the default JSON module # restore the default JSON module
packet.Packet.json = json packet.Packet.json = json
@ -798,14 +925,20 @@ class TestAsyncServer(unittest.TestCase):
s.manager.connect('123', '/') s.manager.connect('123', '/')
_run(s._handle_eio_message('123', '2["my message","a","b","c"]')) _run(s._handle_eio_message('123', '2["my message","a","b","c"]'))
s.eio.start_background_task.assert_called_once_with( s.eio.start_background_task.assert_called_once_with(
s._handle_event_internal, s, '123', ['my message', 'a', 'b', 'c'], s._handle_event_internal,
'/', None) s,
'123',
['my message', 'a', 'b', 'c'],
'/',
None,
)
def test_start_background_task(self, eio): def test_start_background_task(self, eio):
s = asyncio_server.AsyncServer() s = asyncio_server.AsyncServer()
s.start_background_task('foo', 'bar', baz='baz') s.start_background_task('foo', 'bar', baz='baz')
s.eio.start_background_task.assert_called_once_with('foo', 'bar', s.eio.start_background_task.assert_called_once_with(
baz='baz') 'foo', 'bar', baz='baz'
)
def test_sleep(self, eio): def test_sleep(self, eio):
eio.return_value.sleep = AsyncMock() eio.return_value.sleep = AsyncMock()

197
tests/common/test_base_manager.py

@ -1,6 +1,7 @@
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -18,26 +19,28 @@ class TestBaseManager(unittest.TestCase):
def test_connect(self): def test_connect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.assertIn(None, self.bm.rooms['/foo']) assert None in self.bm.rooms['/foo']
self.assertIn('123', self.bm.rooms['/foo']) assert '123' in self.bm.rooms['/foo']
self.assertIn('123', self.bm.rooms['/foo'][None]) assert '123' in self.bm.rooms['/foo'][None]
self.assertIn('123', self.bm.rooms['/foo']['123']) assert '123' in self.bm.rooms['/foo']['123']
self.assertEqual(self.bm.rooms['/foo'], {None: {'123': True}, assert self.bm.rooms['/foo'] == {
'123': {'123': True}}) None: {'123': True},
'123': {'123': True},
}
def test_pre_disconnect(self): def test_pre_disconnect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.bm.pre_disconnect('123', '/foo') self.bm.pre_disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123']}) assert self.bm.pending_disconnect == {'/foo': ['123']}
self.assertFalse(self.bm.is_connected('123', '/foo')) assert not self.bm.is_connected('123', '/foo')
self.bm.pre_disconnect('456', '/foo') self.bm.pre_disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123', '456']}) assert self.bm.pending_disconnect == {'/foo': ['123', '456']}
self.assertFalse(self.bm.is_connected('456', '/foo')) assert not self.bm.is_connected('456', '/foo')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['456']}) assert self.bm.pending_disconnect == {'/foo': ['456']}
self.bm.disconnect('456', '/foo') self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {}) assert self.bm.pending_disconnect == {}
def test_disconnect(self): def test_disconnect(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -45,26 +48,32 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('456', '/foo', 'baz') self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, assert self.bm.rooms['/foo'] == {
'456': {'456': True}, None: {'456': True},
'baz': {'456': True}}) '456': {'456': True},
'baz': {'456': True},
}
def test_disconnect_default_namespace(self): def test_disconnect_default_namespace(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/') self.bm.connect('456', '/')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.assertTrue(self.bm.is_connected('123', '/')) assert self.bm.is_connected('123', '/')
self.assertTrue(self.bm.is_connected('123', '/foo')) assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.assertFalse(self.bm.is_connected('123', '/')) assert not self.bm.is_connected('123', '/')
self.assertTrue(self.bm.is_connected('123', '/foo')) assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertFalse(self.bm.is_connected('123', '/foo')) assert not self.bm.is_connected('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True}, assert self.bm.rooms['/'] == {
'456': {'456': True}}) None: {'456': True},
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, '456': {'456': True},
'456': {'456': True}}) }
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_twice(self): def test_disconnect_twice(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -75,10 +84,14 @@ class TestBaseManager(unittest.TestCase):
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True}, assert self.bm.rooms['/'] == {
'456': {'456': True}}) None: {'456': True},
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True}, '456': {'456': True},
'456': {'456': True}}) }
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_all(self): def test_disconnect_all(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -87,7 +100,7 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'baz') self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.bm.disconnect('456', '/foo') self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.rooms, {}) assert self.bm.rooms == {}
def test_disconnect_with_callbacks(self): def test_disconnect_with_callbacks(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -95,9 +108,9 @@ class TestBaseManager(unittest.TestCase):
self.bm._generate_ack_id('123', '/', 'f') self.bm._generate_ack_id('123', '/', 'f')
self.bm._generate_ack_id('123', '/foo', 'g') self.bm._generate_ack_id('123', '/foo', 'g')
self.bm.disconnect('123', '/foo') self.bm.disconnect('123', '/foo')
self.assertNotIn('/foo', self.bm.callbacks['123']) assert '/foo' not in self.bm.callbacks['123']
self.bm.disconnect('123', '/') self.bm.disconnect('123', '/')
self.assertNotIn('123', self.bm.callbacks) assert '123' not in self.bm.callbacks
def test_disconnect_bad_namespace(self): def test_disconnect_bad_namespace(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
@ -112,7 +125,7 @@ class TestBaseManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb) id2 = self.bm._generate_ack_id('123', '/foo', cb)
self.bm.trigger_callback('123', '/', id1, ['foo']) self.bm.trigger_callback('123', '/', id1, ['foo'])
self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz']) self.bm.trigger_callback('123', '/foo', id2, ['bar', 'baz'])
self.assertEqual(cb.call_count, 2) assert cb.call_count == 2
cb.assert_any_call('foo') cb.assert_any_call('foo')
cb.assert_any_call('bar', 'baz') cb.assert_any_call('bar', 'baz')
@ -125,26 +138,26 @@ class TestBaseManager(unittest.TestCase):
self.bm.trigger_callback('124', '/', id, ['foo']) self.bm.trigger_callback('124', '/', id, ['foo'])
self.bm.trigger_callback('123', '/foo', id, ['foo']) self.bm.trigger_callback('123', '/foo', id, ['foo'])
self.bm.trigger_callback('123', '/', id + 1, ['foo']) self.bm.trigger_callback('123', '/', id + 1, ['foo'])
self.assertEqual(cb.call_count, 0) assert cb.call_count == 0
def test_get_namespaces(self): def test_get_namespaces(self):
self.assertEqual(list(self.bm.get_namespaces()), []) assert list(self.bm.get_namespaces()) == []
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
namespaces = list(self.bm.get_namespaces()) namespaces = list(self.bm.get_namespaces())
self.assertEqual(len(namespaces), 2) assert len(namespaces) == 2
self.assertIn('/', namespaces) assert '/' in namespaces
self.assertIn('/foo', namespaces) assert '/foo' in namespaces
def test_get_participants(self): def test_get_participants(self):
self.bm.connect('123', '/') self.bm.connect('123', '/')
self.bm.connect('456', '/') self.bm.connect('456', '/')
self.bm.connect('789', '/') self.bm.connect('789', '/')
self.bm.disconnect('789', '/') self.bm.disconnect('789', '/')
self.assertNotIn('789', self.bm.rooms['/'][None]) assert '789' not in self.bm.rooms['/'][None]
participants = list(self.bm.get_participants('/', None)) participants = list(self.bm.get_participants('/', None))
self.assertEqual(len(participants), 2) assert len(participants) == 2
self.assertNotIn('789', participants) assert '789' not in participants
def test_leave_invalid_room(self): def test_leave_invalid_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -153,7 +166,7 @@ class TestBaseManager(unittest.TestCase):
def test_no_room(self): def test_no_room(self):
rooms = self.bm.get_rooms('123', '/foo') rooms = self.bm.get_rooms('123', '/foo')
self.assertEqual([], rooms) assert [] == rooms
def test_close_room(self): def test_close_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -162,7 +175,7 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
self.bm.close_room('bar', '/foo') self.bm.close_room('bar', '/foo')
self.assertNotIn('bar', self.bm.rooms['/foo']) assert 'bar' not in self.bm.rooms['/foo']
def test_close_invalid_room(self): def test_close_invalid_room(self):
self.bm.close_room('bar', '/foo') self.bm.close_room('bar', '/foo')
@ -171,19 +184,17 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.enter_room('123', '/foo', 'bar') self.bm.enter_room('123', '/foo', 'bar')
r = self.bm.get_rooms('123', '/foo') r = self.bm.get_rooms('123', '/foo')
self.assertEqual(len(r), 2) assert len(r) == 2
self.assertIn('123', r) assert '123' in r
self.assertIn('bar', r) assert 'bar' in r
def test_emit_to_sid(self): def test_emit_to_sid(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', room='123')
room='123') self.bm.server._emit_internal.assert_called_once_with(
self.bm.server._emit_internal.assert_called_once_with('123', '123', 'my event', {'foo': 'bar'}, '/foo', None
'my event', )
{'foo': 'bar'},
'/foo', None)
def test_emit_to_room(self): def test_emit_to_room(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -191,15 +202,14 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('456', '/foo') self.bm.connect('456', '/foo')
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', room='bar')
room='bar') assert self.bm.server._emit_internal.call_count == 2
self.assertEqual(self.bm.server._emit_internal.call_count, 2) self.bm.server._emit_internal.assert_any_call(
self.bm.server._emit_internal.assert_any_call('123', 'my event', '123', 'my event', {'foo': 'bar'}, '/foo', None
{'foo': 'bar'}, '/foo', )
None) self.bm.server._emit_internal.assert_any_call(
self.bm.server._emit_internal.assert_any_call('456', 'my event', '456', 'my event', {'foo': 'bar'}, '/foo', None
{'foo': 'bar'}, '/foo', )
None)
def test_emit_to_all(self): def test_emit_to_all(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -209,16 +219,16 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo') self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo')
self.assertEqual(self.bm.server._emit_internal.call_count, 3) assert self.bm.server._emit_internal.call_count == 3
self.bm.server._emit_internal.assert_any_call('123', 'my event', self.bm.server._emit_internal.assert_any_call(
{'foo': 'bar'}, '/foo', '123', 'my event', {'foo': 'bar'}, '/foo', None
None) )
self.bm.server._emit_internal.assert_any_call('456', 'my event', self.bm.server._emit_internal.assert_any_call(
{'foo': 'bar'}, '/foo', '456', 'my event', {'foo': 'bar'}, '/foo', None
None) )
self.bm.server._emit_internal.assert_any_call('789', 'my event', self.bm.server._emit_internal.assert_any_call(
{'foo': 'bar'}, '/foo', '789', 'my event', {'foo': 'bar'}, '/foo', None
None) )
def test_emit_to_all_skip_one(self): def test_emit_to_all_skip_one(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -227,15 +237,16 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', self.bm.emit(
skip_sid='456') 'my event', {'foo': 'bar'}, namespace='/foo', skip_sid='456'
self.assertEqual(self.bm.server._emit_internal.call_count, 2) )
self.bm.server._emit_internal.assert_any_call('123', 'my event', assert self.bm.server._emit_internal.call_count == 2
{'foo': 'bar'}, '/foo', self.bm.server._emit_internal.assert_any_call(
None) '123', 'my event', {'foo': 'bar'}, '/foo', None
self.bm.server._emit_internal.assert_any_call('789', 'my event', )
{'foo': 'bar'}, '/foo', self.bm.server._emit_internal.assert_any_call(
None) '789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_two(self): def test_emit_to_all_skip_two(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
@ -244,24 +255,28 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar') self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo') self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar') self.bm.connect('abc', '/bar')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', self.bm.emit(
skip_sid=['123', '789']) 'my event',
self.assertEqual(self.bm.server._emit_internal.call_count, 1) {'foo': 'bar'},
self.bm.server._emit_internal.assert_any_call('456', 'my event', namespace='/foo',
{'foo': 'bar'}, '/foo', skip_sid=['123', '789'],
None) )
assert self.bm.server._emit_internal.call_count == 1
self.bm.server._emit_internal.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_with_callback(self): def test_emit_with_callback(self):
self.bm.connect('123', '/foo') self.bm.connect('123', '/foo')
self.bm._generate_ack_id = mock.MagicMock() self.bm._generate_ack_id = mock.MagicMock()
self.bm._generate_ack_id.return_value = 11 self.bm._generate_ack_id.return_value = 11
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', self.bm.emit(
callback='cb') 'my event', {'foo': 'bar'}, namespace='/foo', callback='cb'
)
self.bm._generate_ack_id.assert_called_once_with('123', '/foo', 'cb') self.bm._generate_ack_id.assert_called_once_with('123', '/foo', 'cb')
self.bm.server._emit_internal.assert_called_once_with('123', self.bm.server._emit_internal.assert_called_once_with(
'my event', '123', 'my event', {'foo': 'bar'}, '/foo', 11
{'foo': 'bar'}, )
'/foo', 11)
def test_emit_to_invalid_room(self): def test_emit_to_invalid_room(self):
self.bm.emit('my event', {'foo': 'bar'}, namespace='/', room='123') self.bm.emit('my event', {'foo': 'bar'}, namespace='/', room='123')

667
tests/common/test_client.py

File diff suppressed because it is too large

11
tests/common/test_middleware.py

@ -1,6 +1,7 @@
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -27,8 +28,9 @@ class TestMiddleware(unittest.TestCase):
environ = {'PATH_INFO': '/socket.io/'} environ = {'PATH_INFO': '/socket.io/'}
start_response = "foo" start_response = "foo"
m(environ, start_response) m(environ, start_response)
mock_sio_app.handle_request.assert_called_once_with(environ, mock_sio_app.handle_request.assert_called_once_with(
start_response) environ, start_response
)
def test_404(self): def test_404(self):
mock_wsgi_app = None mock_wsgi_app = None
@ -37,6 +39,7 @@ class TestMiddleware(unittest.TestCase):
environ = {'PATH_INFO': '/foo/bar'} environ = {'PATH_INFO': '/foo/bar'}
start_response = mock.MagicMock() start_response = mock.MagicMock()
r = m(environ, start_response) r = m(environ, start_response)
self.assertEqual(r, [b'Not Found']) assert r == [b'Not Found']
start_response.assert_called_once_with( start_response.assert_called_once_with(
"404 Not Found", [('Content-Type', 'text/plain')]) "404 Not Found", [('Content-Type', 'text/plain')]
)

107
tests/common/test_namespace.py

@ -1,5 +1,6 @@
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -19,7 +20,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.trigger_event('connect', 'sid', {'foo': 'bar'}) ns.trigger_event('connect', 'sid', {'foo': 'bar'})
self.assertEqual(result['result'], ('sid', {'foo': 'bar'})) assert result['result'] == ('sid', {'foo': 'bar'})
def test_disconnect_event(self): def test_disconnect_event(self):
result = {} result = {}
@ -31,7 +32,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.trigger_event('disconnect', 'sid') ns.trigger_event('disconnect', 'sid')
self.assertEqual(result['result'], 'sid') assert result['result'] == 'sid'
def test_event(self): def test_event(self):
result = {} result = {}
@ -43,7 +44,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.trigger_event('custom_message', 'sid', {'data': 'data'}) ns.trigger_event('custom_message', 'sid', {'data': 'data'})
self.assertEqual(result['result'], ('sid', {'data': 'data'})) assert result['result'] == ('sid', {'data': 'data'})
def test_event_not_found(self): def test_event_not_found(self):
result = {} result = {}
@ -55,54 +56,86 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo') ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.trigger_event('another_custom_message', 'sid', {'data': 'data'}) ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
self.assertEqual(result, {}) assert result == {}
def test_emit(self): def test_emit(self):
ns = namespace.Namespace('/foo') ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.emit('ev', data='data', room='room', skip_sid='skip', ns.emit('ev', data='data', room='room', skip_sid='skip', callback='cb')
callback='cb')
ns.server.emit.assert_called_with( ns.server.emit.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/foo', 'ev',
callback='cb') data='data',
ns.emit('ev', data='data', room='room', skip_sid='skip', room='room',
namespace='/bar', callback='cb') skip_sid='skip',
namespace='/foo',
callback='cb',
)
ns.emit(
'ev',
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
ns.server.emit.assert_called_with( ns.server.emit.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/bar', 'ev',
callback='cb') data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_send(self): def test_send(self):
ns = namespace.Namespace('/foo') ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.send(data='data', room='room', skip_sid='skip', callback='cb') ns.send(data='data', room='room', skip_sid='skip', callback='cb')
ns.server.send.assert_called_with( ns.server.send.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/foo', 'data',
callback='cb') room='room',
ns.send(data='data', room='room', skip_sid='skip', namespace='/bar', skip_sid='skip',
callback='cb') namespace='/foo',
callback='cb',
)
ns.send(
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
ns.server.send.assert_called_with( ns.server.send.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/bar', 'data',
callback='cb') room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_enter_room(self): def test_enter_room(self):
ns = namespace.Namespace('/foo') ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.enter_room('sid', 'room') ns.enter_room('sid', 'room')
ns.server.enter_room.assert_called_with('sid', 'room', ns.server.enter_room.assert_called_with(
namespace='/foo') 'sid', 'room', namespace='/foo'
)
ns.enter_room('sid', 'room', namespace='/bar') ns.enter_room('sid', 'room', namespace='/bar')
ns.server.enter_room.assert_called_with('sid', 'room', ns.server.enter_room.assert_called_with(
namespace='/bar') 'sid', 'room', namespace='/bar'
)
def test_leave_room(self): def test_leave_room(self):
ns = namespace.Namespace('/foo') ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock()) ns._set_server(mock.MagicMock())
ns.leave_room('sid', 'room') ns.leave_room('sid', 'room')
ns.server.leave_room.assert_called_with('sid', 'room', ns.server.leave_room.assert_called_with(
namespace='/foo') 'sid', 'room', namespace='/foo'
)
ns.leave_room('sid', 'room', namespace='/bar') ns.leave_room('sid', 'room', namespace='/bar')
ns.server.leave_room.assert_called_with('sid', 'room', ns.server.leave_room.assert_called_with(
namespace='/bar') 'sid', 'room', namespace='/bar'
)
def test_close_room(self): def test_close_room(self):
ns = namespace.Namespace('/foo') ns = namespace.Namespace('/foo')
@ -128,11 +161,13 @@ class TestNamespace(unittest.TestCase):
ns.get_session('sid', namespace='/bar') ns.get_session('sid', namespace='/bar')
ns.server.get_session.assert_called_with('sid', namespace='/bar') ns.server.get_session.assert_called_with('sid', namespace='/bar')
ns.save_session('sid', {'a': 'b'}) ns.save_session('sid', {'a': 'b'})
ns.server.save_session.assert_called_with('sid', {'a': 'b'}, ns.server.save_session.assert_called_with(
namespace='/foo') 'sid', {'a': 'b'}, namespace='/foo'
)
ns.save_session('sid', {'a': 'b'}, namespace='/bar') ns.save_session('sid', {'a': 'b'}, namespace='/bar')
ns.server.save_session.assert_called_with('sid', {'a': 'b'}, ns.server.save_session.assert_called_with(
namespace='/bar') 'sid', {'a': 'b'}, namespace='/bar'
)
ns.session('sid') ns.session('sid')
ns.server.session.assert_called_with('sid', namespace='/foo') ns.server.session.assert_called_with('sid', namespace='/foo')
ns.session('sid', namespace='/bar') ns.session('sid', namespace='/bar')
@ -151,20 +186,24 @@ class TestNamespace(unittest.TestCase):
ns._set_client(mock.MagicMock()) ns._set_client(mock.MagicMock())
ns.emit('ev', data='data', callback='cb') ns.emit('ev', data='data', callback='cb')
ns.client.emit.assert_called_with( ns.client.emit.assert_called_with(
'ev', data='data', namespace='/foo', callback='cb') 'ev', data='data', namespace='/foo', callback='cb'
)
ns.emit('ev', data='data', namespace='/bar', callback='cb') ns.emit('ev', data='data', namespace='/bar', callback='cb')
ns.client.emit.assert_called_with( ns.client.emit.assert_called_with(
'ev', data='data', namespace='/bar', callback='cb') 'ev', data='data', namespace='/bar', callback='cb'
)
def test_send_client(self): def test_send_client(self):
ns = namespace.ClientNamespace('/foo') ns = namespace.ClientNamespace('/foo')
ns._set_client(mock.MagicMock()) ns._set_client(mock.MagicMock())
ns.send(data='data', callback='cb') ns.send(data='data', callback='cb')
ns.client.send.assert_called_with( ns.client.send.assert_called_with(
'data', namespace='/foo', callback='cb') 'data', namespace='/foo', callback='cb'
)
ns.send(data='data', namespace='/bar', callback='cb') ns.send(data='data', namespace='/bar', callback='cb')
ns.client.send.assert_called_with( ns.client.send.assert_called_with(
'data', namespace='/bar', callback='cb') 'data', namespace='/bar', callback='cb'
)
def test_disconnect_client(self): def test_disconnect_client(self):
ns = namespace.ClientNamespace('/foo') ns = namespace.ClientNamespace('/foo')

287
tests/common/test_packet.py

@ -3,238 +3,261 @@ import unittest
import six import six
from socketio import packet from socketio import packet
import pytest
class TestPacket(unittest.TestCase): class TestPacket(unittest.TestCase):
def test_encode_default_packet(self): def test_encode_default_packet(self):
pkt = packet.Packet() pkt = packet.Packet()
self.assertEqual(pkt.packet_type, packet.EVENT) assert pkt.packet_type == packet.EVENT
self.assertIsNone(pkt.data) assert pkt.data is None
self.assertIsNone(pkt.namespace) assert pkt.namespace is None
self.assertIsNone(pkt.id) assert pkt.id is None
self.assertEqual(pkt.attachment_count, 0) assert pkt.attachment_count == 0
self.assertEqual(pkt.encode(), '2') assert pkt.encode() == '2'
def test_decode_default_packet(self): def test_decode_default_packet(self):
pkt = packet.Packet(encoded_packet='2') pkt = packet.Packet(encoded_packet='2')
self.assertTrue(pkt.encode(), '2') assert pkt.encode(), '2'
def test_encode_text_event_packet(self): def test_encode_text_event_packet(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('foo')]) packet_type=packet.EVENT, data=[six.text_type('foo')]
self.assertEqual(pkt.packet_type, packet.EVENT) )
self.assertEqual(pkt.data, ['foo']) assert pkt.packet_type == packet.EVENT
self.assertEqual(pkt.encode(), '2["foo"]') assert pkt.data == ['foo']
assert pkt.encode() == '2["foo"]'
def test_decode_text_event_packet(self): def test_decode_text_event_packet(self):
pkt = packet.Packet(encoded_packet='2["foo"]') pkt = packet.Packet(encoded_packet='2["foo"]')
self.assertEqual(pkt.packet_type, packet.EVENT) assert pkt.packet_type == packet.EVENT
self.assertEqual(pkt.data, ['foo']) assert pkt.data == ['foo']
self.assertEqual(pkt.encode(), '2["foo"]') assert pkt.encode() == '2["foo"]'
def test_decode_empty_event_packet(self): def test_decode_empty_event_packet(self):
pkt = packet.Packet(encoded_packet='1') pkt = packet.Packet(encoded_packet='1')
self.assertEqual(pkt.packet_type, packet.DISCONNECT) assert pkt.packet_type == packet.DISCONNECT
# same thing, but with a numeric payload # same thing, but with a numeric payload
pkt = packet.Packet(encoded_packet=1) pkt = packet.Packet(encoded_packet=1)
self.assertEqual(pkt.packet_type, packet.DISCONNECT) assert pkt.packet_type == packet.DISCONNECT
def test_encode_binary_event_packet(self): def test_encode_binary_event_packet(self):
pkt = packet.Packet(packet_type=packet.EVENT, data=b'1234') pkt = packet.Packet(packet_type=packet.EVENT, data=b'1234')
self.assertEqual(pkt.packet_type, packet.BINARY_EVENT) assert pkt.packet_type == packet.BINARY_EVENT
self.assertEqual(pkt.data, b'1234') assert pkt.data == b'1234'
a = ['51-{"_placeholder":true,"num":0}', b'1234'] a = ['51-{"_placeholder":true,"num":0}', b'1234']
b = ['51-{"num":0,"_placeholder":true}', b'1234'] b = ['51-{"num":0,"_placeholder":true}', b'1234']
encoded_packet = pkt.encode() encoded_packet = pkt.encode()
self.assertTrue(encoded_packet == a or encoded_packet == b) assert encoded_packet == a or encoded_packet == b
def test_decode_binary_event_packet(self): def test_decode_binary_event_packet(self):
pkt = packet.Packet(encoded_packet='51-{"_placeholder":true,"num":0}') pkt = packet.Packet(encoded_packet='51-{"_placeholder":true,"num":0}')
self.assertTrue(pkt.add_attachment(b'1234')) assert pkt.add_attachment(b'1234')
self.assertEqual(pkt.packet_type, packet.BINARY_EVENT) assert pkt.packet_type == packet.BINARY_EVENT
self.assertEqual(pkt.data, b'1234') assert pkt.data == b'1234'
def test_encode_text_ack_packet(self): def test_encode_text_ack_packet(self):
pkt = packet.Packet(packet_type=packet.ACK, pkt = packet.Packet(
data=[six.text_type('foo')]) packet_type=packet.ACK, data=[six.text_type('foo')]
self.assertEqual(pkt.packet_type, packet.ACK) )
self.assertEqual(pkt.data, ['foo']) assert pkt.packet_type == packet.ACK
self.assertEqual(pkt.encode(), '3["foo"]') assert pkt.data == ['foo']
assert pkt.encode() == '3["foo"]'
def test_decode_text_ack_packet(self): def test_decode_text_ack_packet(self):
pkt = packet.Packet(encoded_packet='3["foo"]') pkt = packet.Packet(encoded_packet='3["foo"]')
self.assertEqual(pkt.packet_type, packet.ACK) assert pkt.packet_type == packet.ACK
self.assertEqual(pkt.data, ['foo']) assert pkt.data == ['foo']
self.assertEqual(pkt.encode(), '3["foo"]') assert pkt.encode() == '3["foo"]'
def test_encode_binary_ack_packet(self): def test_encode_binary_ack_packet(self):
pkt = packet.Packet(packet_type=packet.ACK, data=b'1234') pkt = packet.Packet(packet_type=packet.ACK, data=b'1234')
self.assertEqual(pkt.packet_type, packet.BINARY_ACK) assert pkt.packet_type == packet.BINARY_ACK
self.assertEqual(pkt.data, b'1234') assert pkt.data == b'1234'
a = ['61-{"_placeholder":true,"num":0}', b'1234'] a = ['61-{"_placeholder":true,"num":0}', b'1234']
b = ['61-{"num":0,"_placeholder":true}', b'1234'] b = ['61-{"num":0,"_placeholder":true}', b'1234']
encoded_packet = pkt.encode() encoded_packet = pkt.encode()
self.assertTrue(encoded_packet == a or encoded_packet == b) assert encoded_packet == a or encoded_packet == b
def test_decode_binary_ack_packet(self): def test_decode_binary_ack_packet(self):
pkt = packet.Packet(encoded_packet='61-{"_placeholder":true,"num":0}') pkt = packet.Packet(encoded_packet='61-{"_placeholder":true,"num":0}')
self.assertTrue(pkt.add_attachment(b'1234')) assert pkt.add_attachment(b'1234')
self.assertEqual(pkt.packet_type, packet.BINARY_ACK) assert pkt.packet_type == packet.BINARY_ACK
self.assertEqual(pkt.data, b'1234') assert pkt.data == b'1234'
def test_invalid_binary_packet(self): def test_invalid_binary_packet(self):
self.assertRaises(ValueError, packet.Packet, packet_type=packet.ERROR, with pytest.raises(ValueError):
data=b'123') packet.Packet(packet_type=packet.ERROR, data=b'123')
def test_encode_namespace(self): def test_encode_namespace(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('foo')], namespace='/bar') packet_type=packet.EVENT,
self.assertEqual(pkt.namespace, '/bar') data=[six.text_type('foo')],
self.assertEqual(pkt.encode(), '2/bar,["foo"]') namespace='/bar',
)
assert pkt.namespace == '/bar'
assert pkt.encode() == '2/bar,["foo"]'
def test_decode_namespace(self): def test_decode_namespace(self):
pkt = packet.Packet(encoded_packet='2/bar,["foo"]') pkt = packet.Packet(encoded_packet='2/bar,["foo"]')
self.assertEqual(pkt.namespace, '/bar') assert pkt.namespace == '/bar'
self.assertEqual(pkt.encode(), '2/bar,["foo"]') assert pkt.encode() == '2/bar,["foo"]'
def test_decode_namespace_with_query_string(self): def test_decode_namespace_with_query_string(self):
# some Socket.IO clients mistakenly attach the query string to the # some Socket.IO clients mistakenly attach the query string to the
# namespace # namespace
pkt = packet.Packet(encoded_packet='2/bar?a=b,["foo"]') pkt = packet.Packet(encoded_packet='2/bar?a=b,["foo"]')
self.assertEqual(pkt.namespace, '/bar') assert pkt.namespace == '/bar'
self.assertEqual(pkt.encode(), '2/bar,["foo"]') assert pkt.encode() == '2/bar,["foo"]'
def test_encode_namespace_no_data(self): def test_encode_namespace_no_data(self):
pkt = packet.Packet(packet_type=packet.EVENT, namespace='/bar') pkt = packet.Packet(packet_type=packet.EVENT, namespace='/bar')
self.assertEqual(pkt.encode(), '2/bar') assert pkt.encode() == '2/bar'
def test_decode_namespace_no_data(self): def test_decode_namespace_no_data(self):
pkt = packet.Packet(encoded_packet='2/bar') pkt = packet.Packet(encoded_packet='2/bar')
self.assertEqual(pkt.namespace, '/bar') assert pkt.namespace == '/bar'
self.assertEqual(pkt.encode(), '2/bar') assert pkt.encode() == '2/bar'
def test_encode_namespace_with_hyphens(self): def test_encode_namespace_with_hyphens(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('foo')], namespace='/b-a-r') packet_type=packet.EVENT,
self.assertEqual(pkt.namespace, '/b-a-r') data=[six.text_type('foo')],
self.assertEqual(pkt.encode(), '2/b-a-r,["foo"]') namespace='/b-a-r',
)
assert pkt.namespace == '/b-a-r'
assert pkt.encode() == '2/b-a-r,["foo"]'
def test_decode_namespace_with_hyphens(self): def test_decode_namespace_with_hyphens(self):
pkt = packet.Packet(encoded_packet='2/b-a-r,["foo"]') pkt = packet.Packet(encoded_packet='2/b-a-r,["foo"]')
self.assertEqual(pkt.namespace, '/b-a-r') assert pkt.namespace == '/b-a-r'
self.assertEqual(pkt.encode(), '2/b-a-r,["foo"]') assert pkt.encode() == '2/b-a-r,["foo"]'
def test_encode_event_with_hyphens(self): def test_encode_event_with_hyphens(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('f-o-o')]) packet_type=packet.EVENT, data=[six.text_type('f-o-o')]
self.assertEqual(pkt.namespace, None) )
self.assertEqual(pkt.encode(), '2["f-o-o"]') assert pkt.namespace is None
assert pkt.encode() == '2["f-o-o"]'
def test_decode_event_with_hyphens(self): def test_decode_event_with_hyphens(self):
pkt = packet.Packet(encoded_packet='2["f-o-o"]') pkt = packet.Packet(encoded_packet='2["f-o-o"]')
self.assertEqual(pkt.namespace, None) assert pkt.namespace is None
self.assertEqual(pkt.encode(), '2["f-o-o"]') assert pkt.encode() == '2["f-o-o"]'
def test_encode_id(self): def test_encode_id(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('foo')], id=123) packet_type=packet.EVENT, data=[six.text_type('foo')], id=123
self.assertEqual(pkt.id, 123) )
self.assertEqual(pkt.encode(), '2123["foo"]') assert pkt.id == 123
assert pkt.encode() == '2123["foo"]'
def test_decode_id(self): def test_decode_id(self):
pkt = packet.Packet(encoded_packet='2123["foo"]') pkt = packet.Packet(encoded_packet='2123["foo"]')
self.assertEqual(pkt.id, 123) assert pkt.id == 123
self.assertEqual(pkt.encode(), '2123["foo"]') assert pkt.encode() == '2123["foo"]'
def test_encode_id_no_data(self): def test_encode_id_no_data(self):
pkt = packet.Packet(packet_type=packet.EVENT, id=123) pkt = packet.Packet(packet_type=packet.EVENT, id=123)
self.assertEqual(pkt.id, 123) assert pkt.id == 123
self.assertIsNone(pkt.data) assert pkt.data is None
self.assertEqual(pkt.encode(), '2123') assert pkt.encode() == '2123'
def test_decode_id_no_data(self): def test_decode_id_no_data(self):
pkt = packet.Packet(encoded_packet='2123') pkt = packet.Packet(encoded_packet='2123')
self.assertEqual(pkt.id, 123) assert pkt.id == 123
self.assertIsNone(pkt.data) assert pkt.data is None
self.assertEqual(pkt.encode(), '2123') assert pkt.encode() == '2123'
def test_encode_namespace_and_id(self): def test_encode_namespace_and_id(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data=[six.text_type('foo')], namespace='/bar', packet_type=packet.EVENT,
id=123) data=[six.text_type('foo')],
self.assertEqual(pkt.namespace, '/bar') namespace='/bar',
self.assertEqual(pkt.id, 123) id=123,
self.assertEqual(pkt.encode(), '2/bar,123["foo"]') )
assert pkt.namespace == '/bar'
assert pkt.id == 123
assert pkt.encode() == '2/bar,123["foo"]'
def test_decode_namespace_and_id(self): def test_decode_namespace_and_id(self):
pkt = packet.Packet(encoded_packet='2/bar,123["foo"]') pkt = packet.Packet(encoded_packet='2/bar,123["foo"]')
self.assertEqual(pkt.namespace, '/bar') assert pkt.namespace == '/bar'
self.assertEqual(pkt.id, 123) assert pkt.id == 123
self.assertEqual(pkt.encode(), '2/bar,123["foo"]') assert pkt.encode() == '2/bar,123["foo"]'
def test_encode_many_binary(self): def test_encode_many_binary(self):
pkt = packet.Packet(packet_type=packet.EVENT, pkt = packet.Packet(
data={'a': six.text_type('123'), packet_type=packet.EVENT,
'b': b'456', data={'a': six.text_type('123'), 'b': b'456', 'c': [b'789', 123]},
'c': [b'789', 123]}) )
self.assertEqual(pkt.packet_type, packet.BINARY_EVENT) assert pkt.packet_type == packet.BINARY_EVENT
ep = pkt.encode() ep = pkt.encode()
self.assertEqual(len(ep), 3) assert len(ep) == 3
self.assertIn(b'456', ep) assert b'456' in ep
self.assertIn(b'789', ep) assert b'789' in ep
def test_encode_many_binary_ack(self): def test_encode_many_binary_ack(self):
pkt = packet.Packet(packet_type=packet.ACK, pkt = packet.Packet(
data={'a': six.text_type('123'), packet_type=packet.ACK,
'b': b'456', data={'a': six.text_type('123'), 'b': b'456', 'c': [b'789', 123]},
'c': [b'789', 123]}) )
self.assertEqual(pkt.packet_type, packet.BINARY_ACK) assert pkt.packet_type == packet.BINARY_ACK
ep = pkt.encode() ep = pkt.encode()
self.assertEqual(len(ep), 3) assert len(ep) == 3
self.assertIn(b'456', ep) assert b'456' in ep
self.assertIn(b'789', ep) assert b'789' in ep
def test_decode_many_binary(self): def test_decode_many_binary(self):
pkt = packet.Packet(encoded_packet=( pkt = packet.Packet(
'52-{"a":"123","b":{"_placeholder":true,"num":0},' encoded_packet=(
'"c":[{"_placeholder":true,"num":1},123]}')) '52-{"a":"123","b":{"_placeholder":true,"num":0},'
self.assertFalse(pkt.add_attachment(b'456')) '"c":[{"_placeholder":true,"num":1},123]}'
self.assertTrue(pkt.add_attachment(b'789')) )
self.assertEqual(pkt.packet_type, packet.BINARY_EVENT) )
self.assertEqual(pkt.data['a'], '123') assert not pkt.add_attachment(b'456')
self.assertEqual(pkt.data['b'], b'456') assert pkt.add_attachment(b'789')
self.assertEqual(pkt.data['c'], [b'789', 123]) assert pkt.packet_type == packet.BINARY_EVENT
assert pkt.data['a'] == '123'
assert pkt.data['b'] == b'456'
assert pkt.data['c'] == [b'789', 123]
def test_decode_many_binary_ack(self): def test_decode_many_binary_ack(self):
pkt = packet.Packet(encoded_packet=( pkt = packet.Packet(
'62-{"a":"123","b":{"_placeholder":true,"num":0},' encoded_packet=(
'"c":[{"_placeholder":true,"num":1},123]}')) '62-{"a":"123","b":{"_placeholder":true,"num":0},'
self.assertFalse(pkt.add_attachment(b'456')) '"c":[{"_placeholder":true,"num":1},123]}'
self.assertTrue(pkt.add_attachment(b'789')) )
self.assertEqual(pkt.packet_type, packet.BINARY_ACK) )
self.assertEqual(pkt.data['a'], '123') assert not pkt.add_attachment(b'456')
self.assertEqual(pkt.data['b'], b'456') assert pkt.add_attachment(b'789')
self.assertEqual(pkt.data['c'], [b'789', 123]) assert pkt.packet_type == packet.BINARY_ACK
assert pkt.data['a'] == '123'
assert pkt.data['b'] == b'456'
assert pkt.data['c'] == [b'789', 123]
def test_decode_too_many_binary_packets(self): def test_decode_too_many_binary_packets(self):
pkt = packet.Packet(encoded_packet=( pkt = packet.Packet(
'62-{"a":"123","b":{"_placeholder":true,"num":0},' encoded_packet=(
'"c":[{"_placeholder":true,"num":1},123]}')) '62-{"a":"123","b":{"_placeholder":true,"num":0},'
self.assertFalse(pkt.add_attachment(b'456')) '"c":[{"_placeholder":true,"num":1},123]}'
self.assertTrue(pkt.add_attachment(b'789')) )
self.assertRaises(ValueError, pkt.add_attachment, b'123') )
assert not pkt.add_attachment(b'456')
assert pkt.add_attachment(b'789')
with pytest.raises(ValueError):
pkt.add_attachment(b'123')
def test_data_is_binary_list(self): def test_data_is_binary_list(self):
pkt = packet.Packet() pkt = packet.Packet()
self.assertFalse(pkt._data_is_binary([six.text_type('foo')])) assert not pkt._data_is_binary([six.text_type('foo')])
self.assertFalse(pkt._data_is_binary([])) assert not pkt._data_is_binary([])
self.assertTrue(pkt._data_is_binary([b'foo'])) assert pkt._data_is_binary([b'foo'])
self.assertTrue(pkt._data_is_binary([six.text_type('foo'), b'bar'])) assert pkt._data_is_binary([six.text_type('foo'), b'bar'])
def test_data_is_binary_dict(self): def test_data_is_binary_dict(self):
pkt = packet.Packet() pkt = packet.Packet()
self.assertFalse(pkt._data_is_binary({'a': six.text_type('foo')})) assert not pkt._data_is_binary({'a': six.text_type('foo')})
self.assertFalse(pkt._data_is_binary({})) assert not pkt._data_is_binary({})
self.assertTrue(pkt._data_is_binary({'a': b'foo'})) assert pkt._data_is_binary({'a': b'foo'})
self.assertTrue(pkt._data_is_binary({'a': six.text_type('foo'), assert pkt._data_is_binary({'a': six.text_type('foo'), 'b': b'bar'})
'b': b'bar'}))

356
tests/common/test_pubsub_manager.py

@ -3,6 +3,7 @@ import unittest
import logging import logging
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -10,6 +11,7 @@ else:
from socketio import base_manager from socketio import base_manager
from socketio import pubsub_manager from socketio import pubsub_manager
import pytest
class TestBaseManager(unittest.TestCase): class TestBaseManager(unittest.TestCase):
@ -22,217 +24,330 @@ class TestBaseManager(unittest.TestCase):
self.pm.initialize() self.pm.initialize()
def test_default_init(self): def test_default_init(self):
self.assertEqual(self.pm.channel, 'socketio') assert self.pm.channel == 'socketio'
self.pm.server.start_background_task.assert_called_once_with( self.pm.server.start_background_task.assert_called_once_with(
self.pm._thread) self.pm._thread
)
def test_custom_init(self): def test_custom_init(self):
pubsub = pubsub_manager.PubSubManager(channel='foo') pubsub = pubsub_manager.PubSubManager(channel='foo')
self.assertEqual(pubsub.channel, 'foo') assert pubsub.channel == 'foo'
self.assertEqual(len(pubsub.host_id), 32) assert len(pubsub.host_id) == 32
def test_write_only_init(self): def test_write_only_init(self):
mock_server = mock.MagicMock() mock_server = mock.MagicMock()
pm = pubsub_manager.PubSubManager(write_only=True) pm = pubsub_manager.PubSubManager(write_only=True)
pm.set_server(mock_server) pm.set_server(mock_server)
pm.initialize() pm.initialize()
self.assertEqual(pm.channel, 'socketio') assert pm.channel == 'socketio'
self.assertEqual(len(pm.host_id), 32) assert len(pm.host_id) == 32
self.assertEqual(pm.server.start_background_task.call_count, 0) assert pm.server.start_background_task.call_count == 0
def test_write_only_default_logger(self): def test_write_only_default_logger(self):
pm = pubsub_manager.PubSubManager(write_only=True) pm = pubsub_manager.PubSubManager(write_only=True)
pm.initialize() pm.initialize()
self.assertEqual(pm.channel, 'socketio') assert pm.channel == 'socketio'
self.assertEqual(len(pm.host_id), 32) assert len(pm.host_id) == 32
self.assertEqual(pm._get_logger(), logging.getLogger('socketio')) assert pm._get_logger() == logging.getLogger('socketio')
def test_write_only_with_provided_logger(self): def test_write_only_with_provided_logger(self):
test_logger = logging.getLogger('new_logger') test_logger = logging.getLogger('new_logger')
pm = pubsub_manager.PubSubManager(write_only=True, pm = pubsub_manager.PubSubManager(write_only=True, logger=test_logger)
logger=test_logger)
pm.initialize() pm.initialize()
self.assertEqual(pm.channel, 'socketio') assert pm.channel == 'socketio'
self.assertEqual(len(pm.host_id), 32) assert len(pm.host_id) == 32
self.assertEqual(pm._get_logger(), test_logger) assert pm._get_logger() == test_logger
def test_emit(self): def test_emit(self):
self.pm.emit('foo', 'bar') self.pm.emit('foo', 'bar')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': None, 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_namespace(self): def test_emit_with_namespace(self):
self.pm.emit('foo', 'bar', namespace='/baz') self.pm.emit('foo', 'bar', namespace='/baz')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/baz', 'room': None, 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_room(self): def test_emit_with_room(self):
self.pm.emit('foo', 'bar', room='baz') self.pm.emit('foo', 'bar', room='baz')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': 'baz', 'skip_sid': None, 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_skip_sid(self): def test_emit_with_skip_sid(self):
self.pm.emit('foo', 'bar', skip_sid='baz') self.pm.emit('foo', 'bar', skip_sid='baz')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': None, 'skip_sid': 'baz', 'method': 'emit',
'callback': None, 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': 'baz',
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_callback(self): def test_emit_with_callback(self):
with mock.patch.object(self.pm, '_generate_ack_id', with mock.patch.object(
return_value='123'): self.pm, '_generate_ack_id', return_value='123'
):
self.pm.emit('foo', 'bar', room='baz', callback='cb') self.pm.emit('foo', 'bar', room='baz', callback='cb')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar', {
'namespace': '/', 'room': 'baz', 'skip_sid': None, 'method': 'emit',
'callback': ('baz', '/', '123'), 'host_id': '123456'}) 'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': ('baz', '/', '123'),
'host_id': '123456',
}
)
def test_emit_with_callback_without_server(self): def test_emit_with_callback_without_server(self):
standalone_pm = pubsub_manager.PubSubManager() standalone_pm = pubsub_manager.PubSubManager()
self.assertRaises(RuntimeError, standalone_pm.emit, 'foo', 'bar', with pytest.raises(RuntimeError):
callback='cb') standalone_pm.emit('foo', 'bar', callback='cb')
def test_emit_with_callback_missing_room(self): def test_emit_with_callback_missing_room(self):
with mock.patch.object(self.pm, '_generate_ack_id', with mock.patch.object(
return_value='123'): self.pm, '_generate_ack_id', return_value='123'
self.assertRaises(ValueError, self.pm.emit, 'foo', 'bar', ):
callback='cb') with pytest.raises(ValueError):
self.pm.emit('foo', 'bar', callback='cb')
def test_emit_with_ignore_queue(self): def test_emit_with_ignore_queue(self):
self.pm.connect('123', '/') self.pm.connect('123', '/')
self.pm.emit('foo', 'bar', room='123', namespace='/', self.pm.emit(
ignore_queue=True) 'foo', 'bar', room='123', namespace='/', ignore_queue=True
)
self.pm._publish.assert_not_called() self.pm._publish.assert_not_called()
self.pm.server._emit_internal.assert_called_once_with('123', 'foo', self.pm.server._emit_internal.assert_called_once_with(
'bar', '/', None) '123', 'foo', 'bar', '/', None
)
def test_can_disconnect(self): def test_can_disconnect(self):
self.pm.connect('123', '/') self.pm.connect('123', '/')
self.assertTrue(self.pm.can_disconnect('123', '/')) assert self.pm.can_disconnect('123', '/')
self.pm.can_disconnect('123', '/foo') self.pm.can_disconnect('123', '/foo')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}) {'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
def test_close_room(self): def test_close_room(self):
self.pm.close_room('foo') self.pm.close_room('foo')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'close_room', 'room': 'foo', 'namespace': '/'}) {'method': 'close_room', 'room': 'foo', 'namespace': '/'}
)
def test_close_room_with_namespace(self): def test_close_room_with_namespace(self):
self.pm.close_room('foo', '/bar') self.pm.close_room('foo', '/bar')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}) {'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}
)
def test_handle_emit(self): def test_handle_emit(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit: with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar'}) self.pm._handle_emit({'event': 'foo', 'data': 'bar'})
super_emit.assert_called_once_with('foo', 'bar', namespace=None, super_emit.assert_called_once_with(
room=None, skip_sid=None, 'foo',
callback=None) 'bar',
namespace=None,
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_namespace(self): def test_handle_emit_with_namespace(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit: with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar', self.pm._handle_emit(
'namespace': '/baz'}) {'event': 'foo', 'data': 'bar', 'namespace': '/baz'}
super_emit.assert_called_once_with('foo', 'bar', namespace='/baz', )
room=None, skip_sid=None, super_emit.assert_called_once_with(
callback=None) 'foo',
'bar',
namespace='/baz',
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_room(self): def test_handle_emit_with_room(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit: with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar', self.pm._handle_emit(
'room': 'baz'}) {'event': 'foo', 'data': 'bar', 'room': 'baz'}
super_emit.assert_called_once_with('foo', 'bar', namespace=None, )
room='baz', skip_sid=None, super_emit.assert_called_once_with(
callback=None) 'foo',
'bar',
namespace=None,
room='baz',
skip_sid=None,
callback=None,
)
def test_handle_emit_with_skip_sid(self): def test_handle_emit_with_skip_sid(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit: with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar', self.pm._handle_emit(
'skip_sid': '123'}) {'event': 'foo', 'data': 'bar', 'skip_sid': '123'}
super_emit.assert_called_once_with('foo', 'bar', namespace=None, )
room=None, skip_sid='123', super_emit.assert_called_once_with(
callback=None) 'foo',
'bar',
namespace=None,
room=None,
skip_sid='123',
callback=None,
)
def test_handle_emit_with_callback(self): def test_handle_emit_with_callback(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit: with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar', self.pm._handle_emit(
'namespace': '/baz', {
'callback': ('sid', '/baz', 123), 'event': 'foo',
'host_id': host_id}) 'data': 'bar',
self.assertEqual(super_emit.call_count, 1) 'namespace': '/baz',
self.assertEqual(super_emit.call_args[0], ('foo', 'bar')) 'callback': ('sid', '/baz', 123),
self.assertEqual(super_emit.call_args[1]['namespace'], '/baz') 'host_id': host_id,
self.assertIsNone(super_emit.call_args[1]['room']) }
self.assertIsNone(super_emit.call_args[1]['skip_sid']) )
self.assertIsInstance(super_emit.call_args[1]['callback'], assert super_emit.call_count == 1
functools.partial) assert super_emit.call_args[0] == ('foo', 'bar')
assert super_emit.call_args[1]['namespace'] == '/baz'
assert super_emit.call_args[1]['room'] is None
assert super_emit.call_args[1]['skip_sid'] is None
assert isinstance(
super_emit.call_args[1]['callback'], functools.partial
)
super_emit.call_args[1]['callback']('one', 2, 'three') super_emit.call_args[1]['callback']('one', 2, 'three')
self.pm._publish.assert_called_once_with( self.pm._publish.assert_called_once_with(
{'method': 'callback', 'host_id': host_id, 'sid': 'sid', {
'namespace': '/baz', 'id': 123, 'args': ('one', 2, 'three')}) 'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/baz',
'id': 123,
'args': ('one', 2, 'three'),
}
)
def test_handle_callback(self): def test_handle_callback(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback') as trigger: with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback', self.pm._handle_callback(
'host_id': host_id, 'sid': 'sid', {
'namespace': '/', 'id': 123, 'method': 'callback',
'args': ('one', 2)}) 'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
trigger.assert_called_once_with('sid', '/', 123, ('one', 2)) trigger.assert_called_once_with('sid', '/', 123, ('one', 2))
def test_handle_callback_bad_host_id(self): def test_handle_callback_bad_host_id(self):
with mock.patch.object(self.pm, 'trigger_callback') as trigger: with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback', self.pm._handle_callback(
'host_id': 'bad', 'sid': 'sid', {
'namespace': '/', 'id': 123, 'method': 'callback',
'args': ('one', 2)}) 'host_id': 'bad',
self.assertEqual(trigger.call_count, 0) 'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
assert trigger.call_count == 0
def test_handle_callback_missing_args(self): def test_handle_callback_missing_args(self):
host_id = self.pm.host_id host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback') as trigger: with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback', self.pm._handle_callback(
'host_id': host_id, 'sid': 'sid', {
'namespace': '/', 'id': 123}) 'method': 'callback',
self.pm._handle_callback({'method': 'callback', 'host_id': host_id,
'host_id': host_id, 'sid': 'sid', 'sid': 'sid',
'namespace': '/'}) 'namespace': '/',
self.pm._handle_callback({'method': 'callback', 'id': 123,
'host_id': host_id, 'sid': 'sid'}) }
self.pm._handle_callback({'method': 'callback', )
'host_id': host_id}) self.pm._handle_callback(
self.assertEqual(trigger.call_count, 0) {
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
}
)
self.pm._handle_callback(
{'method': 'callback', 'host_id': host_id, 'sid': 'sid'}
)
self.pm._handle_callback(
{'method': 'callback', 'host_id': host_id}
)
assert trigger.call_count == 0
def test_handle_disconnect(self): def test_handle_disconnect(self):
self.pm._handle_disconnect({'method': 'disconnect', 'sid': '123', self.pm._handle_disconnect(
'namespace': '/foo'}) {'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
self.pm.server.disconnect.assert_called_once_with(sid='123', )
namespace='/foo', self.pm.server.disconnect.assert_called_once_with(
ignore_queue=True) sid='123', namespace='/foo', ignore_queue=True
)
def test_handle_close_room(self): def test_handle_close_room(self):
with mock.patch.object(base_manager.BaseManager, 'close_room') \ with mock.patch.object(
as super_close_room: base_manager.BaseManager, 'close_room'
self.pm._handle_close_room({'method': 'close_room', ) as super_close_room:
'room': 'foo'}) self.pm._handle_close_room({'method': 'close_room', 'room': 'foo'})
super_close_room.assert_called_once_with(room='foo', super_close_room.assert_called_once_with(
namespace=None) room='foo', namespace=None
)
def test_handle_close_room_with_namespace(self): def test_handle_close_room_with_namespace(self):
with mock.patch.object(base_manager.BaseManager, 'close_room') \ with mock.patch.object(
as super_close_room: base_manager.BaseManager, 'close_room'
self.pm._handle_close_room({'method': 'close_room', ) as super_close_room:
'room': 'foo', 'namespace': '/bar'}) self.pm._handle_close_room(
super_close_room.assert_called_once_with(room='foo', {'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}
namespace='/bar') )
super_close_room.assert_called_once_with(
room='foo', namespace='/bar'
)
def test_background_thread(self): def test_background_thread(self):
self.pm._handle_emit = mock.MagicMock() self.pm._handle_emit = mock.MagicMock()
@ -242,6 +357,7 @@ class TestBaseManager(unittest.TestCase):
def messages(): def messages():
import pickle import pickle
yield {'method': 'emit', 'value': 'foo'} yield {'method': 'emit', 'value': 'foo'}
yield {'missing': 'method'} yield {'missing': 'method'}
yield '{"method": "callback", "value": "bar"}' yield '{"method": "callback", "value": "bar"}'
@ -258,10 +374,14 @@ class TestBaseManager(unittest.TestCase):
pass pass
self.pm._handle_emit.assert_called_once_with( self.pm._handle_emit.assert_called_once_with(
{'method': 'emit', 'value': 'foo'}) {'method': 'emit', 'value': 'foo'}
)
self.pm._handle_callback.assert_called_once_with( self.pm._handle_callback.assert_called_once_with(
{'method': 'callback', 'value': 'bar'}) {'method': 'callback', 'value': 'bar'}
)
self.pm._handle_disconnect.assert_called_once_with( self.pm._handle_disconnect.assert_called_once_with(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}) {'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
self.pm._handle_close_room.assert_called_once_with( self.pm._handle_close_room.assert_called_once_with(
{'method': 'close_room', 'value': 'baz'}) {'method': 'close_room', 'value': 'baz'}
)

422
tests/common/test_server.py

@ -3,6 +3,7 @@ import logging
import unittest import unittest
import six import six
if six.PY3: if six.PY3:
from unittest import mock from unittest import mock
else: else:
@ -12,6 +13,7 @@ from socketio import exceptions
from socketio import namespace from socketio import namespace
from socketio import packet from socketio import packet
from socketio import server from socketio import server
import pytest
@mock.patch('engineio.Server') @mock.patch('engineio.Server')
@ -22,15 +24,16 @@ class TestServer(unittest.TestCase):
def test_create(self, eio): def test_create(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, binary=True, s = server.Server(
async_handlers=True, foo='bar') client_manager=mgr, binary=True, async_handlers=True, foo='bar'
)
s.handle_request({}, None) s.handle_request({}, None)
s.handle_request({}, None) s.handle_request({}, None)
eio.assert_called_once_with(**{'foo': 'bar', 'async_handlers': False}) eio.assert_called_once_with(**{'foo': 'bar', 'async_handlers': False})
self.assertEqual(s.manager, mgr) assert s.manager == mgr
self.assertEqual(s.eio.on.call_count, 3) assert s.eio.on.call_count == 3
self.assertEqual(s.binary, True) assert s.binary
self.assertEqual(s.async_handlers, True) assert s.async_handlers
def test_on_event(self, eio): def test_on_event(self, eio):
s = server.Server() s = server.Server()
@ -41,12 +44,13 @@ class TestServer(unittest.TestCase):
def bar(): def bar():
pass pass
s.on('disconnect', bar) s.on('disconnect', bar)
s.on('disconnect', bar, namespace='/foo') s.on('disconnect', bar, namespace='/foo')
self.assertEqual(s.handlers['/']['connect'], foo) assert s.handlers['/']['connect'] == foo
self.assertEqual(s.handlers['/']['disconnect'], bar) assert s.handlers['/']['disconnect'] == bar
self.assertEqual(s.handlers['/foo']['disconnect'], bar) assert s.handlers['/foo']['disconnect'] == bar
def test_event(self, eio): def test_event(self, eio):
s = server.Server() s = server.Server()
@ -67,86 +71,141 @@ class TestServer(unittest.TestCase):
def disconnect(): def disconnect():
pass pass
self.assertEqual(s.handlers['/']['connect'], connect) assert s.handlers['/']['connect'] == connect
self.assertEqual(s.handlers['/']['foo'], foo) assert s.handlers['/']['foo'] == foo
self.assertEqual(s.handlers['/']['bar'], bar) assert s.handlers['/']['bar'] == bar
self.assertEqual(s.handlers['/foo']['disconnect'], disconnect) assert s.handlers['/foo']['disconnect'] == disconnect
def test_emit(self, eio): def test_emit(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
s.emit('my event', {'foo': 'bar'}, to='room', skip_sid='123', s.emit(
namespace='/foo', callback='cb') 'my event',
{'foo': 'bar'},
to='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
s.manager.emit.assert_called_once_with( s.manager.emit.assert_called_once_with(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
s.emit('my event', {'foo': 'bar'}, room='room', skip_sid='123', '/foo',
namespace='/foo', callback='cb') room='room',
skip_sid='123',
callback='cb',
)
s.emit(
'my event',
{'foo': 'bar'},
room='room',
skip_sid='123',
namespace='/foo',
callback='cb',
)
s.manager.emit.assert_called_with( s.manager.emit.assert_called_with(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_emit_default_namespace(self, eio): def test_emit_default_namespace(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
s.emit('my event', {'foo': 'bar'}, to='room', skip_sid='123', s.emit(
callback='cb') 'my event',
{'foo': 'bar'},
to='room',
skip_sid='123',
callback='cb',
)
s.manager.emit.assert_called_once_with( s.manager.emit.assert_called_once_with(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
s.emit('my event', {'foo': 'bar'}, room='room', skip_sid='123', '/',
callback='cb') room='room',
skip_sid='123',
callback='cb',
)
s.emit(
'my event',
{'foo': 'bar'},
room='room',
skip_sid='123',
callback='cb',
)
s.manager.emit.assert_called_with( s.manager.emit.assert_called_with(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123', 'my event',
callback='cb') {'foo': 'bar'},
'/',
room='room',
skip_sid='123',
callback='cb',
)
def test_send(self, eio): def test_send(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
s.send('foo', to='room', skip_sid='123', namespace='/foo', s.send(
callback='cb') 'foo', to='room', skip_sid='123', namespace='/foo', callback='cb'
)
s.manager.emit.assert_called_once_with( s.manager.emit.assert_called_once_with(
'message', 'foo', '/foo', room='room', skip_sid='123', 'message',
callback='cb') 'foo',
s.send('foo', room='room', skip_sid='123', namespace='/foo', '/foo',
callback='cb') room='room',
skip_sid='123',
callback='cb',
)
s.send(
'foo', room='room', skip_sid='123', namespace='/foo', callback='cb'
)
s.manager.emit.assert_called_with( s.manager.emit.assert_called_with(
'message', 'foo', '/foo', room='room', skip_sid='123', 'message',
callback='cb') 'foo',
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_call(self, eio): def test_call(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
def fake_event_wait(timeout=None): def fake_event_wait(timeout=None):
self.assertEqual(timeout, 60) assert timeout == 60
s.manager.emit.call_args_list[0][1]['callback']('foo', 321) s.manager.emit.call_args_list[0][1]['callback']('foo', 321)
return True return True
s.eio.create_event.return_value.wait = fake_event_wait s.eio.create_event.return_value.wait = fake_event_wait
self.assertEqual(s.call('foo', sid='123'), ('foo', 321)) assert s.call('foo', sid='123') == ('foo', 321)
def test_call_with_timeout(self, eio): def test_call_with_timeout(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
def fake_event_wait(timeout=None): def fake_event_wait(timeout=None):
self.assertEqual(timeout, 12) assert timeout == 12
return False return False
s.eio.create_event.return_value.wait = fake_event_wait s.eio.create_event.return_value.wait = fake_event_wait
self.assertRaises(exceptions.TimeoutError, s.call, 'foo', with pytest.raises(exceptions.TimeoutError):
sid='123', timeout=12) s.call('foo', sid='123', timeout=12)
def test_call_with_broadcast(self, eio): def test_call_with_broadcast(self, eio):
s = server.Server() s = server.Server()
self.assertRaises(ValueError, s.call, 'foo') with pytest.raises(ValueError):
s.call('foo')
def test_call_without_async_handlers(self, eio): def test_call_without_async_handlers(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, async_handlers=False) s = server.Server(client_manager=mgr, async_handlers=False)
self.assertRaises(RuntimeError, s.call, 'foo', with pytest.raises(RuntimeError):
sid='123', timeout=12) s.call('foo', sid='123', timeout=12)
def test_enter_room(self, eio): def test_enter_room(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -199,60 +258,63 @@ class TestServer(unittest.TestCase):
def test_handle_request(self, eio): def test_handle_request(self, eio):
s = server.Server() s = server.Server()
s.handle_request('environ', 'start_response') s.handle_request('environ', 'start_response')
s.eio.handle_request.assert_called_once_with('environ', s.eio.handle_request.assert_called_once_with(
'start_response') 'environ', 'start_response'
)
def test_emit_internal(self, eio): def test_emit_internal(self, eio):
s = server.Server() s = server.Server()
s._emit_internal('123', 'my event', 'my data', namespace='/foo') s._emit_internal('123', 'my event', 'my data', namespace='/foo')
s.eio.send.assert_called_once_with('123', s.eio.send.assert_called_once_with(
'2/foo,["my event","my data"]', '123', '2/foo,["my event","my data"]', binary=False
binary=False) )
def test_emit_internal_with_tuple(self, eio): def test_emit_internal_with_tuple(self, eio):
s = server.Server() s = server.Server()
s._emit_internal('123', 'my event', ('foo', 'bar'), namespace='/foo') s._emit_internal('123', 'my event', ('foo', 'bar'), namespace='/foo')
s.eio.send.assert_called_once_with('123', s.eio.send.assert_called_once_with(
'2/foo,["my event","foo","bar"]', '123', '2/foo,["my event","foo","bar"]', binary=False
binary=False) )
def test_emit_internal_with_list(self, eio): def test_emit_internal_with_list(self, eio):
s = server.Server() s = server.Server()
s._emit_internal('123', 'my event', ['foo', 'bar'], namespace='/foo') s._emit_internal('123', 'my event', ['foo', 'bar'], namespace='/foo')
s.eio.send.assert_called_once_with('123', s.eio.send.assert_called_once_with(
'2/foo,["my event",["foo","bar"]]', '123', '2/foo,["my event",["foo","bar"]]', binary=False
binary=False) )
def test_emit_internal_with_none(self, eio): def test_emit_internal_with_none(self, eio):
s = server.Server() s = server.Server()
s._emit_internal('123', 'my event', None, namespace='/foo') s._emit_internal('123', 'my event', None, namespace='/foo')
s.eio.send.assert_called_once_with('123', '2/foo,["my event"]', s.eio.send.assert_called_once_with(
binary=False) '123', '2/foo,["my event"]', binary=False
)
def test_emit_internal_with_callback(self, eio): def test_emit_internal_with_callback(self, eio):
s = server.Server() s = server.Server()
id = s.manager._generate_ack_id('123', '/foo', 'cb') id = s.manager._generate_ack_id('123', '/foo', 'cb')
s._emit_internal('123', 'my event', 'my data', namespace='/foo', id=id) s._emit_internal('123', 'my event', 'my data', namespace='/foo', id=id)
s.eio.send.assert_called_once_with('123', s.eio.send.assert_called_once_with(
'2/foo,1["my event","my data"]', '123', '2/foo,1["my event","my data"]', binary=False
binary=False) )
def test_emit_internal_default_namespace(self, eio): def test_emit_internal_default_namespace(self, eio):
s = server.Server() s = server.Server()
s._emit_internal('123', 'my event', 'my data') s._emit_internal('123', 'my event', 'my data')
s.eio.send.assert_called_once_with('123', '2["my event","my data"]', s.eio.send.assert_called_once_with(
binary=False) '123', '2["my event","my data"]', binary=False
)
def test_emit_internal_binary(self, eio): def test_emit_internal_binary(self, eio):
s = server.Server(binary=True) s = server.Server(binary=True)
s._emit_internal('123', u'my event', b'my binary data') s._emit_internal('123', u'my event', b'my binary data')
self.assertEqual(s.eio.send.call_count, 2) assert s.eio.send.call_count == 2
def test_transport(self, eio): def test_transport(self, eio):
s = server.Server() s = server.Server()
s.eio.transport = mock.MagicMock(return_value='polling') s.eio.transport = mock.MagicMock(return_value='polling')
s._handle_eio_connect('foo', 'environ') s._handle_eio_connect('foo', 'environ')
self.assertEqual(s.transport('foo'), 'polling') assert s.transport('foo') == 'polling'
s.eio.transport.assert_called_once_with('foo') s.eio.transport.assert_called_once_with('foo')
def test_handle_connect(self, eio): def test_handle_connect(self, eio):
@ -264,9 +326,9 @@ class TestServer(unittest.TestCase):
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
s.manager.connect.assert_called_once_with('123', '/') s.manager.connect.assert_called_once_with('123', '/')
s.eio.send.assert_called_once_with('123', '0', binary=False) s.eio.send.assert_called_once_with('123', '0', binary=False)
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
s._handle_eio_connect('456', 'environ') s._handle_eio_connect('456', 'environ')
self.assertEqual(mgr.initialize.call_count, 1) assert mgr.initialize.call_count == 1
def test_handle_connect_namespace(self, eio): def test_handle_connect_namespace(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -286,11 +348,11 @@ class TestServer(unittest.TestCase):
handler = mock.MagicMock(return_value=False) handler = mock.MagicMock(return_value=False)
s.on('connect', handler) s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret) assert not ret
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_namespace_rejected(self, eio): def test_handle_connect_namespace_rejected(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -299,10 +361,10 @@ class TestServer(unittest.TestCase):
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '4/foo', binary=False) s.eio.send.assert_any_call('123', '4/foo', binary=False)
def test_handle_connect_rejected_always_connect(self, eio): def test_handle_connect_rejected_always_connect(self, eio):
@ -311,11 +373,11 @@ class TestServer(unittest.TestCase):
handler = mock.MagicMock(return_value=False) handler = mock.MagicMock(return_value=False)
s.on('connect', handler) s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret) assert not ret
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
s.eio.send.assert_any_call('123', '0', binary=False) s.eio.send.assert_any_call('123', '0', binary=False)
s.eio.send.assert_any_call('123', '1', binary=False) s.eio.send.assert_any_call('123', '1', binary=False)
@ -326,10 +388,10 @@ class TestServer(unittest.TestCase):
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '0/foo', binary=False) s.eio.send.assert_any_call('123', '0/foo', binary=False)
s.eio.send.assert_any_call('123', '1/foo', binary=False) s.eio.send.assert_any_call('123', '1/foo', binary=False)
@ -337,55 +399,60 @@ class TestServer(unittest.TestCase):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError('fail_reason')) side_effect=exceptions.ConnectionRefusedError('fail_reason')
)
s.on('connect', handler) s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
self.assertEqual(ret, 'fail_reason') assert ret == 'fail_reason'
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_rejected_with_empty_exception(self, eio): def test_handle_connect_rejected_with_empty_exception(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError()) side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler) s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret) assert not ret
handler.assert_called_once_with('123', 'environ') handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1) assert s.manager.connect.call_count == 1
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_connect_namespace_rejected_with_exception(self, eio): def test_handle_connect_namespace_rejected_with_exception(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError(u'fail_reason', 1)) side_effect=exceptions.ConnectionRefusedError(u'fail_reason', 1)
)
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '4/foo,["fail_reason",1]', s.eio.send.assert_any_call(
binary=False) '123', '4/foo,["fail_reason",1]', binary=False
)
def test_handle_connect_namespace_rejected_with_empty_exception(self, eio): def test_handle_connect_namespace_rejected_with_empty_exception(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
handler = mock.MagicMock( handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError()) side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler, namespace='/foo') s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ') ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret) assert ret is None
self.assertEqual(s.manager.connect.call_count, 2) assert s.manager.connect.call_count == 2
self.assertEqual(s.manager.disconnect.call_count, 1) assert s.manager.disconnect.call_count == 1
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '4/foo', binary=False) s.eio.send.assert_any_call('123', '4/foo', binary=False)
def test_handle_disconnect(self, eio): def test_handle_disconnect(self, eio):
@ -397,7 +464,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_disconnect('123') s._handle_eio_disconnect('123')
handler.assert_called_once_with('123') handler.assert_called_once_with('123')
s.manager.disconnect.assert_called_once_with('123', '/') s.manager.disconnect.assert_called_once_with('123', '/')
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_disconnect_namespace(self, eio): def test_handle_disconnect_namespace(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -412,7 +479,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_disconnect('123') s._handle_eio_disconnect('123')
handler.assert_called_once_with('123') handler.assert_called_once_with('123')
handler_namespace.assert_called_once_with('123') handler_namespace.assert_called_once_with('123')
self.assertEqual(s.environ, {}) assert s.environ == {}
def test_handle_disconnect_only_namespace(self, eio): def test_handle_disconnect_only_namespace(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -425,9 +492,9 @@ class TestServer(unittest.TestCase):
s._handle_eio_connect('123', 'environ') s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
s._handle_eio_message('123', '1/foo') s._handle_eio_message('123', '1/foo')
self.assertEqual(handler.call_count, 0) assert handler.call_count == 0
handler_namespace.assert_called_once_with('123') handler_namespace.assert_called_once_with('123')
self.assertEqual(s.environ, {'123': 'environ'}) assert s.environ == {'123': 'environ'}
def test_handle_disconnect_unknown_client(self, eio): def test_handle_disconnect_unknown_client(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -463,9 +530,12 @@ class TestServer(unittest.TestCase):
s.manager.connect('123', '/') s.manager.connect('123', '/')
handler = mock.MagicMock() handler = mock.MagicMock()
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '52-["my message","a",' s._handle_eio_message(
'{"_placeholder":true,"num":1},' '123',
'{"_placeholder":true,"num":0}]') '52-["my message","a",'
'{"_placeholder":true,"num":1},'
'{"_placeholder":true,"num":0}]',
)
s._handle_eio_message('123', b'foo') s._handle_eio_message('123', b'foo')
s._handle_eio_message('123', b'bar') s._handle_eio_message('123', b'bar')
handler.assert_called_once_with('123', 'a', b'bar', b'foo') handler.assert_called_once_with('123', 'a', b'bar', b'foo')
@ -473,11 +543,13 @@ class TestServer(unittest.TestCase):
def test_handle_event_binary_ack(self, eio): def test_handle_event_binary_ack(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr) s = server.Server(client_manager=mgr)
s._handle_eio_message('123', '61-321["my message","a",' s._handle_eio_message(
'{"_placeholder":true,"num":0}]') '123', '61-321["my message","a",' '{"_placeholder":true,"num":0}]'
)
s._handle_eio_message('123', b'foo') s._handle_eio_message('123', b'foo')
mgr.trigger_callback.assert_called_once_with( mgr.trigger_callback.assert_called_once_with(
'123', '/', 321, ['my message', 'a', b'foo']) '123', '/', 321, ['my message', 'a', b'foo']
)
def test_handle_event_with_ack(self, eio): def test_handle_event_with_ack(self, eio):
s = server.Server(async_handlers=False) s = server.Server(async_handlers=False)
@ -486,8 +558,7 @@ class TestServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]') s._handle_eio_message('123', '21000["my message","foo"]')
handler.assert_called_once_with('123', 'foo') handler.assert_called_once_with('123', 'foo')
s.eio.send.assert_called_once_with('123', '31000["foo"]', s.eio.send.assert_called_once_with('123', '31000["foo"]', binary=False)
binary=False)
def test_handle_event_with_ack_none(self, eio): def test_handle_event_with_ack_none(self, eio):
s = server.Server(async_handlers=False) s = server.Server(async_handlers=False)
@ -496,8 +567,7 @@ class TestServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]') s._handle_eio_message('123', '21000["my message","foo"]')
handler.assert_called_once_with('123', 'foo') handler.assert_called_once_with('123', 'foo')
s.eio.send.assert_called_once_with('123', '31000[]', s.eio.send.assert_called_once_with('123', '31000[]', binary=False)
binary=False)
def test_handle_event_with_ack_tuple(self, eio): def test_handle_event_with_ack_tuple(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -506,8 +576,9 @@ class TestServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","a","b","c"]') s._handle_eio_message('123', '21000["my message","a","b","c"]')
handler.assert_called_once_with('123', 'a', 'b', 'c') handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.assert_called_once_with('123', '31000[1,"2",true]', s.eio.send.assert_called_once_with(
binary=False) '123', '31000[1,"2",true]', binary=False
)
def test_handle_event_with_ack_list(self, eio): def test_handle_event_with_ack_list(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
@ -516,13 +587,15 @@ class TestServer(unittest.TestCase):
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","a","b","c"]') s._handle_eio_message('123', '21000["my message","a","b","c"]')
handler.assert_called_once_with('123', 'a', 'b', 'c') handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.assert_called_once_with('123', '31000[[1,"2",true]]', s.eio.send.assert_called_once_with(
binary=False) '123', '31000[[1,"2",true]]', binary=False
)
def test_handle_event_with_ack_binary(self, eio): def test_handle_event_with_ack_binary(self, eio):
mgr = mock.MagicMock() mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, binary=True, s = server.Server(
async_handlers=False) client_manager=mgr, binary=True, async_handlers=False
)
handler = mock.MagicMock(return_value=b'foo') handler = mock.MagicMock(return_value=b'foo')
s.on('my message', handler) s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]') s._handle_eio_message('123', '21000["my message","foo"]')
@ -530,11 +603,13 @@ class TestServer(unittest.TestCase):
def test_handle_error_packet(self, eio): def test_handle_error_packet(self, eio):
s = server.Server() s = server.Server()
self.assertRaises(ValueError, s._handle_eio_message, '123', '4') with pytest.raises(ValueError):
s._handle_eio_message('123', '4')
def test_handle_invalid_packet(self, eio): def test_handle_invalid_packet(self, eio):
s = server.Server() s = server.Server()
self.assertRaises(ValueError, s._handle_eio_message, '123', '9') with pytest.raises(ValueError):
s._handle_eio_message('123', '9')
def test_send_with_ack(self, eio): def test_send_with_ack(self, eio):
s = server.Server() s = server.Server()
@ -553,8 +628,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
cb = mock.MagicMock() cb = mock.MagicMock()
id = s.manager._generate_ack_id('123', '/foo', cb) id = s.manager._generate_ack_id('123', '/foo', cb)
s._emit_internal('123', 'my event', ['foo'], namespace='/foo', s._emit_internal('123', 'my event', ['foo'], namespace='/foo', id=id)
id=id)
s._handle_eio_message('123', '3/foo,1["foo",2]') s._handle_eio_message('123', '3/foo,1["foo",2]')
cb.assert_called_once_with('foo', 2) cb.assert_called_once_with('foo', 2)
@ -574,17 +648,19 @@ class TestServer(unittest.TestCase):
s._handle_eio_connect('123', 'environ') s._handle_eio_connect('123', 'environ')
s.save_session('123', {'foo': 'bar'}) s.save_session('123', {'foo': 'bar'})
with s.session('123') as session: with s.session('123') as session:
self.assertEqual(session, {'foo': 'bar'}) assert session == {'foo': 'bar'}
session['foo'] = 'baz' session['foo'] = 'baz'
session['bar'] = 'foo' session['bar'] = 'foo'
self.assertEqual(s.get_session('123'), {'foo': 'baz', 'bar': 'foo'}) assert s.get_session('123') == {'foo': 'baz', 'bar': 'foo'}
self.assertEqual(fake_session, {'/': {'foo': 'baz', 'bar': 'foo'}}) assert fake_session == {'/': {'foo': 'baz', 'bar': 'foo'}}
with s.session('123', namespace='/ns') as session: with s.session('123', namespace='/ns') as session:
self.assertEqual(session, {}) assert session == {}
session['a'] = 'b' session['a'] = 'b'
self.assertEqual(s.get_session('123', namespace='/ns'), {'a': 'b'}) assert s.get_session('123', namespace='/ns') == {'a': 'b'}
self.assertEqual(fake_session, {'/': {'foo': 'baz', 'bar': 'foo'}, assert fake_session == {
'/ns': {'a': 'b'}}) '/': {'foo': 'baz', 'bar': 'foo'},
'/ns': {'a': 'b'},
}
def test_disconnect(self, eio): def test_disconnect(self, eio):
s = server.Server() s = server.Server()
@ -611,7 +687,7 @@ class TestServer(unittest.TestCase):
s.disconnect('123') s.disconnect('123')
calls = s.eio.send.call_count calls = s.eio.send.call_count
s.disconnect('123') s.disconnect('123')
self.assertEqual(calls, s.eio.send.call_count) assert calls == s.eio.send.call_count
def test_disconnect_twice_namespace(self, eio): def test_disconnect_twice_namespace(self, eio):
s = server.Server() s = server.Server()
@ -620,7 +696,7 @@ class TestServer(unittest.TestCase):
s.disconnect('123', namespace='/foo') s.disconnect('123', namespace='/foo')
calls = s.eio.send.call_count calls = s.eio.send.call_count
s.disconnect('123', namespace='/foo') s.disconnect('123', namespace='/foo')
self.assertEqual(calls, s.eio.send.call_count) assert calls == s.eio.send.call_count
def test_namespace_handler(self, eio): def test_namespace_handler(self, eio):
result = {} result = {}
@ -645,15 +721,15 @@ class TestServer(unittest.TestCase):
s.register_namespace(MyNamespace('/foo')) s.register_namespace(MyNamespace('/foo'))
s._handle_eio_connect('123', 'environ') s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo') s._handle_eio_message('123', '0/foo')
self.assertEqual(result['result'], ('123', 'environ')) assert result['result'] == ('123', 'environ')
s._handle_eio_message('123', '2/foo,["foo","a"]') s._handle_eio_message('123', '2/foo,["foo","a"]')
self.assertEqual(result['result'], ('123', 'a')) assert result['result'] == ('123', 'a')
s._handle_eio_message('123', '2/foo,["bar"]') s._handle_eio_message('123', '2/foo,["bar"]')
self.assertEqual(result['result'], 'bar') assert result['result'] == 'bar'
s._handle_eio_message('123', '2/foo,["baz","a","b"]') s._handle_eio_message('123', '2/foo,["baz","a","b"]')
self.assertEqual(result['result'], ('a', 'b')) assert result['result'] == ('a', 'b')
s.disconnect('123', '/foo') s.disconnect('123', '/foo')
self.assertEqual(result['result'], ('disconnect', '123')) assert result['result'] == ('disconnect', '123')
def test_bad_namespace_handler(self, eio): def test_bad_namespace_handler(self, eio):
class Dummy(object): class Dummy(object):
@ -664,30 +740,35 @@ class TestServer(unittest.TestCase):
return True return True
s = server.Server() s = server.Server()
self.assertRaises(ValueError, s.register_namespace, 123) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, Dummy) s.register_namespace(123)
self.assertRaises(ValueError, s.register_namespace, Dummy()) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, s.register_namespace(Dummy)
namespace.Namespace) with pytest.raises(ValueError):
self.assertRaises(ValueError, s.register_namespace, AsyncNS()) s.register_namespace(Dummy())
with pytest.raises(ValueError):
s.register_namespace(namespace.Namespace)
with pytest.raises(ValueError):
s.register_namespace(AsyncNS())
def test_logger(self, eio): def test_logger(self, eio):
s = server.Server(logger=False) s = server.Server(logger=False)
self.assertEqual(s.logger.getEffectiveLevel(), logging.ERROR) assert s.logger.getEffectiveLevel() == logging.ERROR
s.logger.setLevel(logging.NOTSET) s.logger.setLevel(logging.NOTSET)
s = server.Server(logger=True) s = server.Server(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.INFO) assert s.logger.getEffectiveLevel() == logging.INFO
s.logger.setLevel(logging.WARNING) s.logger.setLevel(logging.WARNING)
s = server.Server(logger=True) s = server.Server(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.WARNING) assert s.logger.getEffectiveLevel() == logging.WARNING
s.logger.setLevel(logging.NOTSET) s.logger.setLevel(logging.NOTSET)
s = server.Server(logger='foo') s = server.Server(logger='foo')
self.assertEqual(s.logger, 'foo') assert s.logger == 'foo'
def test_engineio_logger(self, eio): def test_engineio_logger(self, eio):
server.Server(engineio_logger='foo') server.Server(engineio_logger='foo')
eio.assert_called_once_with(**{'logger': 'foo', eio.assert_called_once_with(
'async_handlers': False}) **{'logger': 'foo', 'async_handlers': False}
)
def test_custom_json(self, eio): def test_custom_json(self, eio):
# Warning: this test cannot run in parallel with other tests, as it # Warning: this test cannot run in parallel with other tests, as it
@ -703,14 +784,17 @@ class TestServer(unittest.TestCase):
return '+++ decoded +++' return '+++ decoded +++'
server.Server(json=CustomJSON) server.Server(json=CustomJSON)
eio.assert_called_once_with(**{'json': CustomJSON, eio.assert_called_once_with(
'async_handlers': False}) **{'json': CustomJSON, 'async_handlers': False}
)
pkt = packet.Packet(packet_type=packet.EVENT,
data={six.text_type('foo'): six.text_type('bar')}) pkt = packet.Packet(
self.assertEqual(pkt.encode(), '2*** encoded ***') packet_type=packet.EVENT,
data={six.text_type('foo'): six.text_type('bar')},
)
assert pkt.encode() == '2*** encoded ***'
pkt2 = packet.Packet(encoded_packet=pkt.encode()) pkt2 = packet.Packet(encoded_packet=pkt.encode())
self.assertEqual(pkt2.data, '+++ decoded +++') assert pkt2.data == '+++ decoded +++'
# restore the default JSON module # restore the default JSON module
packet.Packet.json = json packet.Packet.json = json
@ -720,14 +804,20 @@ class TestServer(unittest.TestCase):
s.manager.connect('123', '/') s.manager.connect('123', '/')
s._handle_eio_message('123', '2["my message","a","b","c"]') s._handle_eio_message('123', '2["my message","a","b","c"]')
s.eio.start_background_task.assert_called_once_with( s.eio.start_background_task.assert_called_once_with(
s._handle_event_internal, s, '123', ['my message', 'a', 'b', 'c'], s._handle_event_internal,
'/', None) s,
'123',
['my message', 'a', 'b', 'c'],
'/',
None,
)
def test_start_background_task(self, eio): def test_start_background_task(self, eio):
s = server.Server() s = server.Server()
s.start_background_task('foo', 'bar', baz='baz') s.start_background_task('foo', 'bar', baz='baz')
s.eio.start_background_task.assert_called_once_with('foo', 'bar', s.eio.start_background_task.assert_called_once_with(
baz='baz') 'foo', 'bar', baz='baz'
)
def test_sleep(self, eio): def test_sleep(self, eio):
s = server.Server() s = server.Server()

2
tox.ini

@ -23,7 +23,7 @@ deps=
six six
flake8 flake8
commands= commands=
flake8 --exclude=".*" --ignore=E402,E722 socketio tests flake8 --exclude=".*" --ignore=W503,E402,E722 socketio tests
[testenv:docs] [testenv:docs]
changedir=docs changedir=docs

Loading…
Cancel
Save