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

186
tests/asyncio/test_asyncio_manager.py

@ -3,6 +3,7 @@ import sys
import unittest
import six
if six.PY3:
from unittest import mock
else:
@ -38,26 +39,28 @@ class TestAsyncManager(unittest.TestCase):
def test_connect(self):
self.bm.connect('123', '/foo')
self.assertIn(None, self.bm.rooms['/foo'])
self.assertIn('123', self.bm.rooms['/foo'])
self.assertIn('123', self.bm.rooms['/foo'][None])
self.assertIn('123', self.bm.rooms['/foo']['123'])
self.assertEqual(self.bm.rooms['/foo'], {None: {'123': True},
'123': {'123': True}})
assert None in self.bm.rooms['/foo']
assert '123' in self.bm.rooms['/foo']
assert '123' in self.bm.rooms['/foo'][None]
assert '123' in self.bm.rooms['/foo']['123']
assert self.bm.rooms['/foo'] == {
None: {'123': True},
'123': {'123': True},
}
def test_pre_disconnect(self):
self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo')
self.bm.pre_disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123']})
self.assertFalse(self.bm.is_connected('123', '/foo'))
assert self.bm.pending_disconnect == {'/foo': ['123']}
assert not self.bm.is_connected('123', '/foo')
self.bm.pre_disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123', '456']})
self.assertFalse(self.bm.is_connected('456', '/foo'))
assert self.bm.pending_disconnect == {'/foo': ['123', '456']}
assert not self.bm.is_connected('456', '/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.assertEqual(self.bm.pending_disconnect, {})
assert self.bm.pending_disconnect == {}
def test_disconnect(self):
self.bm.connect('123', '/foo')
@ -65,26 +68,32 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True},
'baz': {'456': True}})
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
'baz': {'456': True},
}
def test_disconnect_default_namespace(self):
self.bm.connect('123', '/')
self.bm.connect('123', '/foo')
self.bm.connect('456', '/')
self.bm.connect('456', '/foo')
self.assertTrue(self.bm.is_connected('123', '/'))
self.assertTrue(self.bm.is_connected('123', '/foo'))
assert self.bm.is_connected('123', '/')
assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/')
self.assertFalse(self.bm.is_connected('123', '/'))
self.assertTrue(self.bm.is_connected('123', '/foo'))
assert not self.bm.is_connected('123', '/')
assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/foo')
self.assertFalse(self.bm.is_connected('123', '/foo'))
self.assertEqual(self.bm.rooms['/'], {None: {'456': True},
'456': {'456': True}})
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True}})
assert not self.bm.is_connected('123', '/foo')
assert self.bm.rooms['/'] == {
None: {'456': True},
'456': {'456': True},
}
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_twice(self):
self.bm.connect('123', '/')
@ -95,10 +104,14 @@ class TestAsyncManager(unittest.TestCase):
self.bm.disconnect('123', '/foo')
self.bm.disconnect('123', '/')
self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True},
'456': {'456': True}})
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True}})
assert self.bm.rooms['/'] == {
None: {'456': True},
'456': {'456': True},
}
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_all(self):
self.bm.connect('123', '/foo')
@ -107,7 +120,7 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo')
self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.rooms, {})
assert self.bm.rooms == {}
def test_disconnect_with_callbacks(self):
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', '/foo', 'g')
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.assertNotIn('123', self.bm.callbacks)
assert '123' not in self.bm.callbacks
def test_trigger_sync_callback(self):
self.bm.connect('123', '/')
@ -127,7 +140,7 @@ class TestAsyncManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb)
_run(self.bm.trigger_callback('123', '/', id1, ['foo']))
_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('bar', 'baz')
@ -139,7 +152,7 @@ class TestAsyncManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb)
_run(self.bm.trigger_callback('123', '/', id1, ['foo']))
_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('bar', 'baz')
@ -152,26 +165,26 @@ class TestAsyncManager(unittest.TestCase):
_run(self.bm.trigger_callback('124', '/', id, ['foo']))
_run(self.bm.trigger_callback('123', '/foo', id, ['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):
self.assertEqual(list(self.bm.get_namespaces()), [])
assert list(self.bm.get_namespaces()) == []
self.bm.connect('123', '/')
self.bm.connect('123', '/foo')
namespaces = list(self.bm.get_namespaces())
self.assertEqual(len(namespaces), 2)
self.assertIn('/', namespaces)
self.assertIn('/foo', namespaces)
assert len(namespaces) == 2
assert '/' in namespaces
assert '/foo' in namespaces
def test_get_participants(self):
self.bm.connect('123', '/')
self.bm.connect('456', '/')
self.bm.connect('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))
self.assertEqual(len(participants), 2)
self.assertNotIn('789', participants)
assert len(participants) == 2
assert '789' not in participants
def test_leave_invalid_room(self):
self.bm.connect('123', '/foo')
@ -180,7 +193,7 @@ class TestAsyncManager(unittest.TestCase):
def test_no_room(self):
rooms = self.bm.get_rooms('123', '/foo')
self.assertEqual([], rooms)
assert [] == rooms
def test_close_room(self):
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')
_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):
self.bm.close_room('bar', '/foo')
@ -198,17 +211,21 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('123', '/foo')
self.bm.enter_room('123', '/foo', 'bar')
r = self.bm.get_rooms('123', '/foo')
self.assertEqual(len(r), 2)
self.assertIn('123', r)
self.assertIn('bar', r)
assert len(r) == 2
assert '123' in r
assert 'bar' in r
def test_emit_to_sid(self):
self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
room='123'))
_run(
self.bm.emit(
'my event', {'foo': 'bar'}, namespace='/foo', room='123'
)
)
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):
self.bm.connect('123', '/foo')
@ -216,13 +233,18 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('456', '/foo')
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
room='bar'))
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 2)
_run(
self.bm.emit(
'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(
'123', 'my event', {'foo': 'bar'}, '/foo', None)
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
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):
self.bm.connect('123', '/foo')
@ -232,13 +254,16 @@ class TestAsyncManager(unittest.TestCase):
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
_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(
'123', 'my event', {'foo': 'bar'}, '/foo', None)
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
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(
'789', 'my event', {'foo': 'bar'}, '/foo', None)
'789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_one(self):
self.bm.connect('123', '/foo')
@ -247,13 +272,18 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
skip_sid='456'))
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 2)
_run(
self.bm.emit(
'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(
'123', 'my event', {'foo': 'bar'}, '/foo', None)
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
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):
self.bm.connect('123', '/foo')
@ -262,25 +292,37 @@ class TestAsyncManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
skip_sid=['123', '789']))
self.assertEqual(self.bm.server._emit_internal.mock.call_count, 1)
_run(
self.bm.emit(
'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(
'456', 'my event', {'foo': 'bar'}, '/foo', None)
'456', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_with_callback(self):
self.bm.connect('123', '/foo')
self.bm._generate_ack_id = mock.MagicMock()
self.bm._generate_ack_id.return_value = 11
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
callback='cb'))
_run(
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.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):
_run(self.bm.emit('my event', {'foo': 'bar'}, namespace='/',
room='123'))
_run(
self.bm.emit('my event', {'foo': 'bar'}, namespace='/', room='123')
)
def test_emit_to_invalid_namespace(self):
_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 six
if six.PY3:
from unittest import mock
else:
@ -39,7 +40,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
_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):
result = {}
@ -51,7 +52,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
_run(ns.trigger_event('disconnect', 'sid'))
self.assertEqual(result['result'], 'sid')
assert result['result'] == 'sid'
def test_sync_event(self):
result = {}
@ -63,7 +64,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
_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):
result = {}
@ -75,7 +76,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
_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):
result = {}
@ -86,25 +87,47 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
_run(ns.trigger_event('another_custom_message', 'sid',
{'data': 'data'}))
self.assertEqual(result, {})
_run(
ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
)
assert result == {}
def test_emit(self):
ns = asyncio_namespace.AsyncNamespace('/foo')
mock_server = mock.MagicMock()
mock_server.emit = AsyncMock()
ns._set_server(mock_server)
_run(ns.emit('ev', data='data', room='room', skip_sid='skip',
callback='cb'))
_run(
ns.emit(
'ev', data='data', room='room', skip_sid='skip', callback='cb'
)
)
ns.server.emit.mock.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/foo',
callback='cb')
_run(ns.emit('ev', data='data', room='room', skip_sid='skip',
namespace='/bar', callback='cb'))
'ev',
data='data',
room='room',
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(
'ev', data='data', room='room', skip_sid='skip', namespace='/bar',
callback='cb')
'ev',
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_send(self):
ns = asyncio_namespace.AsyncNamespace('/foo')
@ -113,33 +136,52 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_server(mock_server)
_run(ns.send(data='data', room='room', skip_sid='skip', callback='cb'))
ns.server.send.mock.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/foo',
callback='cb')
_run(ns.send(data='data', room='room', skip_sid='skip',
namespace='/bar', callback='cb'))
'data',
room='room',
skip_sid='skip',
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(
'data', room='room', skip_sid='skip', namespace='/bar',
callback='cb')
'data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_enter_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo')
ns._set_server(mock.MagicMock())
ns.enter_room('sid', 'room')
ns.server.enter_room.assert_called_with('sid', 'room',
namespace='/foo')
ns.server.enter_room.assert_called_with(
'sid', 'room', namespace='/foo'
)
ns.enter_room('sid', 'room', namespace='/bar')
ns.server.enter_room.assert_called_with('sid', 'room',
namespace='/bar')
ns.server.enter_room.assert_called_with(
'sid', 'room', namespace='/bar'
)
def test_leave_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo')
ns._set_server(mock.MagicMock())
ns.leave_room('sid', 'room')
ns.server.leave_room.assert_called_with('sid', 'room',
namespace='/foo')
ns.server.leave_room.assert_called_with(
'sid', 'room', namespace='/foo'
)
ns.leave_room('sid', 'room', namespace='/bar')
ns.server.leave_room.assert_called_with('sid', 'room',
namespace='/bar')
ns.server.leave_room.assert_called_with(
'sid', 'room', namespace='/bar'
)
def test_close_room(self):
ns = asyncio_namespace.AsyncNamespace('/foo')
@ -170,11 +212,13 @@ class TestAsyncNamespace(unittest.TestCase):
_run(ns.get_session('sid', namespace='/bar'))
ns.server.get_session.mock.assert_called_with('sid', namespace='/bar')
_run(ns.save_session('sid', {'a': 'b'}))
ns.server.save_session.mock.assert_called_with('sid', {'a': 'b'},
namespace='/foo')
ns.server.save_session.mock.assert_called_with(
'sid', {'a': 'b'}, namespace='/foo'
)
_run(ns.save_session('sid', {'a': 'b'}, namespace='/bar'))
ns.server.save_session.mock.assert_called_with('sid', {'a': 'b'},
namespace='/bar')
ns.server.save_session.mock.assert_called_with(
'sid', {'a': 'b'}, namespace='/bar'
)
ns.session('sid')
ns.server.session.assert_called_with('sid', namespace='/foo')
ns.session('sid', namespace='/bar')
@ -200,7 +244,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock())
_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):
result = {}
@ -212,7 +256,7 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock())
_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):
result = {}
@ -223,9 +267,10 @@ class TestAsyncNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_client(mock.MagicMock())
_run(ns.trigger_event('another_custom_message', 'sid',
{'data': 'data'}))
self.assertEqual(result, {})
_run(
ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
)
assert result == {}
def test_emit_client(self):
ns = asyncio_namespace.AsyncClientNamespace('/foo')
@ -234,10 +279,12 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_client(mock_client)
_run(ns.emit('ev', data='data', callback='cb'))
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'))
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):
ns = asyncio_namespace.AsyncClientNamespace('/foo')
@ -246,10 +293,12 @@ class TestAsyncNamespace(unittest.TestCase):
ns._set_client(mock_client)
_run(ns.send(data='data', callback='cb'))
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'))
ns.client.send.mock.assert_called_with(
'data', namespace='/bar', callback='cb')
'data', namespace='/bar', callback='cb'
)
def test_disconnect_client(self):
ns = asyncio_namespace.AsyncClientNamespace('/foo')

404
tests/asyncio/test_asyncio_pubsub_manager.py

@ -4,6 +4,7 @@ import sys
import unittest
import six
if six.PY3:
from unittest import mock
else:
@ -11,6 +12,7 @@ else:
from socketio import asyncio_manager
from socketio import asyncio_pubsub_manager
import pytest
def AsyncMock(*args, **kwargs):
@ -42,210 +44,369 @@ class TestAsyncPubSubManager(unittest.TestCase):
self.pm.initialize()
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._thread)
self.pm._thread
)
def test_custom_init(self):
pubsub = asyncio_pubsub_manager.AsyncPubSubManager(channel='foo')
self.assertEqual(pubsub.channel, 'foo')
self.assertEqual(len(pubsub.host_id), 32)
assert pubsub.channel == 'foo'
assert len(pubsub.host_id) == 32
def test_write_only_init(self):
mock_server = mock.MagicMock()
pm = asyncio_pubsub_manager.AsyncPubSubManager(write_only=True)
pm.set_server(mock_server)
pm.initialize()
self.assertEqual(pm.channel, 'socketio')
self.assertEqual(len(pm.host_id), 32)
self.assertEqual(pm.server.start_background_task.call_count, 0)
assert pm.channel == 'socketio'
assert len(pm.host_id) == 32
assert pm.server.start_background_task.call_count == 0
def test_emit(self):
_run(self.pm.emit('foo', 'bar'))
self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': None, 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_namespace(self):
_run(self.pm.emit('foo', 'bar', namespace='/baz'))
self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/baz', 'room': None, 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_room(self):
_run(self.pm.emit('foo', 'bar', room='baz'))
self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': 'baz', 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_skip_sid(self):
_run(self.pm.emit('foo', 'bar', skip_sid='baz'))
self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': None, 'skip_sid': 'baz',
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': 'baz',
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_callback(self):
with mock.patch.object(self.pm, '_generate_ack_id',
return_value='123'):
with mock.patch.object(
self.pm, '_generate_ack_id', return_value='123'
):
_run(self.pm.emit('foo', 'bar', room='baz', callback='cb'))
self.pm._publish.mock.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': 'baz', 'skip_sid': None,
'callback': ('baz', '/', '123'), 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': ('baz', '/', '123'),
'host_id': '123456',
}
)
def test_emit_with_callback_without_server(self):
standalone_pm = asyncio_pubsub_manager.AsyncPubSubManager()
self.assertRaises(RuntimeError, _run,
standalone_pm.emit('foo', 'bar', callback='cb'))
with pytest.raises(RuntimeError):
_run(standalone_pm.emit('foo', 'bar', callback='cb'))
def test_emit_with_callback_missing_room(self):
with mock.patch.object(self.pm, '_generate_ack_id',
return_value='123'):
self.assertRaises(ValueError, _run,
self.pm.emit('foo', 'bar', callback='cb'))
with mock.patch.object(
self.pm, '_generate_ack_id', return_value='123'
):
with pytest.raises(ValueError):
_run(self.pm.emit('foo', 'bar', callback='cb'))
def test_emit_with_ignore_queue(self):
self.pm.connect('123', '/')
_run(self.pm.emit('foo', 'bar', room='123', namespace='/',
ignore_queue=True))
_run(
self.pm.emit(
'foo', 'bar', room='123', namespace='/', ignore_queue=True
)
)
self.pm._publish.mock.assert_not_called()
self.pm.server._emit_internal.mock.assert_called_once_with(
'123', 'foo', 'bar', '/', None)
'123', 'foo', 'bar', '/', None
)
def test_can_disconnect(self):
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'))
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):
_run(self.pm.close_room('foo'))
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):
_run(self.pm.close_room('foo', '/bar'))
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):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit',
new=AsyncMock()) as super_emit:
with mock.patch.object(
asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar'}))
super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room=None,
skip_sid=None, callback=None)
self.pm,
'foo',
'bar',
namespace=None,
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_namespace(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit',
new=AsyncMock()) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'namespace': '/baz'}))
with mock.patch.object(
asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'namespace': '/baz'}
)
)
super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace='/baz', room=None,
skip_sid=None, callback=None)
self.pm,
'foo',
'bar',
namespace='/baz',
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_room(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit',
new=AsyncMock()) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'room': 'baz'}))
with mock.patch.object(
asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'room': 'baz'}
)
)
super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room='baz',
skip_sid=None, callback=None)
self.pm,
'foo',
'bar',
namespace=None,
room='baz',
skip_sid=None,
callback=None,
)
def test_handle_emit_with_skip_sid(self):
with mock.patch.object(asyncio_manager.AsyncManager, 'emit',
new=AsyncMock()) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'skip_sid': '123'}))
with mock.patch.object(
asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'skip_sid': '123'}
)
)
super_emit.mock.assert_called_once_with(
self.pm, 'foo', 'bar', namespace=None, room=None,
skip_sid='123', callback=None)
self.pm,
'foo',
'bar',
namespace=None,
room=None,
skip_sid='123',
callback=None,
)
def test_handle_emit_with_callback(self):
host_id = self.pm.host_id
with mock.patch.object(asyncio_manager.AsyncManager, 'emit',
new=AsyncMock()) as super_emit:
_run(self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'namespace': '/baz',
'callback': ('sid', '/baz', 123),
'host_id': '123456'}))
self.assertEqual(super_emit.mock.call_count, 1)
self.assertEqual(super_emit.mock.call_args[0],
(self.pm, 'foo', 'bar'))
self.assertEqual(super_emit.mock.call_args[1]['namespace'], '/baz')
self.assertIsNone(super_emit.mock.call_args[1]['room'])
self.assertIsNone(super_emit.mock.call_args[1]['skip_sid'])
self.assertIsInstance(super_emit.mock.call_args[1]['callback'],
functools.partial)
with mock.patch.object(
asyncio_manager.AsyncManager, 'emit', new=AsyncMock()
) as super_emit:
_run(
self.pm._handle_emit(
{
'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'callback': ('sid', '/baz', 123),
'host_id': '123456',
}
)
)
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'))
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):
host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback',
new=AsyncMock()) as trigger:
_run(self.pm._handle_callback({'method': 'callback',
'host_id': host_id, 'sid': 'sid',
'namespace': '/', 'id': 123,
'args': ('one', 2)}))
with mock.patch.object(
self.pm, 'trigger_callback', new=AsyncMock()
) as trigger:
_run(
self.pm._handle_callback(
{
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
)
trigger.mock.assert_called_once_with('sid', '/', 123, ('one', 2))
def test_handle_callback_bad_host_id(self):
with mock.patch.object(self.pm, 'trigger_callback',
new=AsyncMock()) as trigger:
_run(self.pm._handle_callback({'method': 'callback',
'host_id': 'bad', 'sid': 'sid',
'namespace': '/', 'id': 123,
'args': ('one', 2)}))
self.assertEqual(trigger.mock.call_count, 0)
with mock.patch.object(
self.pm, 'trigger_callback', new=AsyncMock()
) as trigger:
_run(
self.pm._handle_callback(
{
'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):
host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback',
new=AsyncMock()) as trigger:
_run(self.pm._handle_callback({'method': 'callback',
'host_id': host_id, 'sid': 'sid',
'namespace': '/', 'id': 123}))
_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}))
self.assertEqual(trigger.mock.call_count, 0)
with mock.patch.object(
self.pm, 'trigger_callback', new=AsyncMock()
) as trigger:
_run(
self.pm._handle_callback(
{
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
}
)
)
_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):
_run(self.pm._handle_disconnect({'method': 'disconnect', 'sid': '123',
'namespace': '/foo'}))
_run(
self.pm._handle_disconnect(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
)
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):
with mock.patch.object(asyncio_manager.AsyncManager, 'close_room',
new=AsyncMock()) as super_close_room:
_run(self.pm._handle_close_room({'method': 'close_room',
'room': 'foo'}))
with mock.patch.object(
asyncio_manager.AsyncManager, 'close_room', new=AsyncMock()
) as super_close_room:
_run(
self.pm._handle_close_room(
{'method': 'close_room', 'room': 'foo'}
)
)
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):
with mock.patch.object(asyncio_manager.AsyncManager, 'close_room',
new=AsyncMock()) as super_close_room:
_run(self.pm._handle_close_room({'method': 'close_room',
'room': 'foo',
'namespace': '/bar'}))
with mock.patch.object(
asyncio_manager.AsyncManager, 'close_room', new=AsyncMock()
) as super_close_room:
_run(
self.pm._handle_close_room(
{
'method': 'close_room',
'room': 'foo',
'namespace': '/bar',
}
)
)
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):
self.pm._handle_emit = AsyncMock()
@ -255,6 +416,7 @@ class TestAsyncPubSubManager(unittest.TestCase):
def messages():
import pickle
yield {'method': 'emit', 'value': 'foo'}
yield {'missing': 'method'}
yield '{"method": "callback", "value": "bar"}'
@ -271,10 +433,14 @@ class TestAsyncPubSubManager(unittest.TestCase):
pass
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(
{'method': 'callback', 'value': 'bar'})
{'method': 'callback', 'value': 'bar'}
)
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(
{'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
from socketio import asyncio_redis_manager
import pytest
@unittest.skipIf(sys.version_info < (3, 5), 'only for Python 3.5+')
class TestAsyncRedisManager(unittest.TestCase):
def test_default_url(self):
self.assertEqual(asyncio_redis_manager._parse_redis_url('redis://'),
('localhost', 6379, None, 0, False))
assert asyncio_redis_manager._parse_redis_url('redis://') == (
'localhost',
6379,
None,
0,
False,
)
def test_only_host_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host'),
('redis.host', 6379, None, 0, False))
assert asyncio_redis_manager._parse_redis_url(
'redis://redis.host'
) == ('redis.host', 6379, None, 0, False)
def test_no_db_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host:123/1'),
('redis.host', 123, None, 1, False))
assert asyncio_redis_manager._parse_redis_url(
'redis://redis.host:123/1'
) == ('redis.host', 123, None, 1, False)
def test_no_port_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://redis.host/1'),
('redis.host', 6379, None, 1, False))
assert asyncio_redis_manager._parse_redis_url(
'redis://redis.host/1'
) == ('redis.host', 6379, None, 1, False)
def test_password(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:[email protected]/1'),
('redis.host', 6379, 'pw', 1, False))
assert asyncio_redis_manager._parse_redis_url(
'redis://:[email protected]/1'
) == ('redis.host', 6379, 'pw', 1, False)
def test_no_host_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:123/1'),
('localhost', 123, None, 1, False))
assert asyncio_redis_manager._parse_redis_url('redis://:123/1') == (
'localhost',
123,
None,
1,
False,
)
def test_no_host_password_url(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('redis://:pw@:123/1'),
('localhost', 123, 'pw', 1, False))
assert asyncio_redis_manager._parse_redis_url(
'redis://:pw@:123/1'
) == ('localhost', 123, 'pw', 1, False)
def test_bad_port_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url,
'redis://localhost:abc/1')
with pytest.raises(ValueError):
asyncio_redis_manager._parse_redis_url('redis://localhost:abc/1')
def test_bad_db_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url,
'redis://localhost:abc/z')
with pytest.raises(ValueError):
asyncio_redis_manager._parse_redis_url('redis://localhost:abc/z')
def test_bad_scheme_url(self):
self.assertRaises(ValueError, asyncio_redis_manager._parse_redis_url,
'http://redis.host:123/1')
with pytest.raises(ValueError):
asyncio_redis_manager._parse_redis_url('http://redis.host:123/1')
def test_ssl_scheme(self):
self.assertEqual(
asyncio_redis_manager._parse_redis_url('rediss://'),
('localhost', 6379, None, 0, True)
assert asyncio_redis_manager._parse_redis_url('rediss://') == (
'localhost',
6379,
None,
0,
True,
)

477
tests/asyncio/test_asyncio_server.py

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

197
tests/common/test_base_manager.py

@ -1,6 +1,7 @@
import unittest
import six
if six.PY3:
from unittest import mock
else:
@ -18,26 +19,28 @@ class TestBaseManager(unittest.TestCase):
def test_connect(self):
self.bm.connect('123', '/foo')
self.assertIn(None, self.bm.rooms['/foo'])
self.assertIn('123', self.bm.rooms['/foo'])
self.assertIn('123', self.bm.rooms['/foo'][None])
self.assertIn('123', self.bm.rooms['/foo']['123'])
self.assertEqual(self.bm.rooms['/foo'], {None: {'123': True},
'123': {'123': True}})
assert None in self.bm.rooms['/foo']
assert '123' in self.bm.rooms['/foo']
assert '123' in self.bm.rooms['/foo'][None]
assert '123' in self.bm.rooms['/foo']['123']
assert self.bm.rooms['/foo'] == {
None: {'123': True},
'123': {'123': True},
}
def test_pre_disconnect(self):
self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo')
self.bm.pre_disconnect('123', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123']})
self.assertFalse(self.bm.is_connected('123', '/foo'))
assert self.bm.pending_disconnect == {'/foo': ['123']}
assert not self.bm.is_connected('123', '/foo')
self.bm.pre_disconnect('456', '/foo')
self.assertEqual(self.bm.pending_disconnect, {'/foo': ['123', '456']})
self.assertFalse(self.bm.is_connected('456', '/foo'))
assert self.bm.pending_disconnect == {'/foo': ['123', '456']}
assert not self.bm.is_connected('456', '/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.assertEqual(self.bm.pending_disconnect, {})
assert self.bm.pending_disconnect == {}
def test_disconnect(self):
self.bm.connect('123', '/foo')
@ -45,26 +48,32 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('123', '/foo', 'bar')
self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True},
'baz': {'456': True}})
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
'baz': {'456': True},
}
def test_disconnect_default_namespace(self):
self.bm.connect('123', '/')
self.bm.connect('123', '/foo')
self.bm.connect('456', '/')
self.bm.connect('456', '/foo')
self.assertTrue(self.bm.is_connected('123', '/'))
self.assertTrue(self.bm.is_connected('123', '/foo'))
assert self.bm.is_connected('123', '/')
assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/')
self.assertFalse(self.bm.is_connected('123', '/'))
self.assertTrue(self.bm.is_connected('123', '/foo'))
assert not self.bm.is_connected('123', '/')
assert self.bm.is_connected('123', '/foo')
self.bm.disconnect('123', '/foo')
self.assertFalse(self.bm.is_connected('123', '/foo'))
self.assertEqual(self.bm.rooms['/'], {None: {'456': True},
'456': {'456': True}})
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True}})
assert not self.bm.is_connected('123', '/foo')
assert self.bm.rooms['/'] == {
None: {'456': True},
'456': {'456': True},
}
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_twice(self):
self.bm.connect('123', '/')
@ -75,10 +84,14 @@ class TestBaseManager(unittest.TestCase):
self.bm.disconnect('123', '/foo')
self.bm.disconnect('123', '/')
self.bm.disconnect('123', '/foo')
self.assertEqual(self.bm.rooms['/'], {None: {'456': True},
'456': {'456': True}})
self.assertEqual(self.bm.rooms['/foo'], {None: {'456': True},
'456': {'456': True}})
assert self.bm.rooms['/'] == {
None: {'456': True},
'456': {'456': True},
}
assert self.bm.rooms['/foo'] == {
None: {'456': True},
'456': {'456': True},
}
def test_disconnect_all(self):
self.bm.connect('123', '/foo')
@ -87,7 +100,7 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'baz')
self.bm.disconnect('123', '/foo')
self.bm.disconnect('456', '/foo')
self.assertEqual(self.bm.rooms, {})
assert self.bm.rooms == {}
def test_disconnect_with_callbacks(self):
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', '/foo', 'g')
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.assertNotIn('123', self.bm.callbacks)
assert '123' not in self.bm.callbacks
def test_disconnect_bad_namespace(self):
self.bm.connect('123', '/')
@ -112,7 +125,7 @@ class TestBaseManager(unittest.TestCase):
id2 = self.bm._generate_ack_id('123', '/foo', cb)
self.bm.trigger_callback('123', '/', id1, ['foo'])
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('bar', 'baz')
@ -125,26 +138,26 @@ class TestBaseManager(unittest.TestCase):
self.bm.trigger_callback('124', '/', id, ['foo'])
self.bm.trigger_callback('123', '/foo', id, ['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):
self.assertEqual(list(self.bm.get_namespaces()), [])
assert list(self.bm.get_namespaces()) == []
self.bm.connect('123', '/')
self.bm.connect('123', '/foo')
namespaces = list(self.bm.get_namespaces())
self.assertEqual(len(namespaces), 2)
self.assertIn('/', namespaces)
self.assertIn('/foo', namespaces)
assert len(namespaces) == 2
assert '/' in namespaces
assert '/foo' in namespaces
def test_get_participants(self):
self.bm.connect('123', '/')
self.bm.connect('456', '/')
self.bm.connect('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))
self.assertEqual(len(participants), 2)
self.assertNotIn('789', participants)
assert len(participants) == 2
assert '789' not in participants
def test_leave_invalid_room(self):
self.bm.connect('123', '/foo')
@ -153,7 +166,7 @@ class TestBaseManager(unittest.TestCase):
def test_no_room(self):
rooms = self.bm.get_rooms('123', '/foo')
self.assertEqual([], rooms)
assert [] == rooms
def test_close_room(self):
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.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):
self.bm.close_room('bar', '/foo')
@ -171,19 +184,17 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('123', '/foo')
self.bm.enter_room('123', '/foo', 'bar')
r = self.bm.get_rooms('123', '/foo')
self.assertEqual(len(r), 2)
self.assertIn('123', r)
self.assertIn('bar', r)
assert len(r) == 2
assert '123' in r
assert 'bar' in r
def test_emit_to_sid(self):
self.bm.connect('123', '/foo')
self.bm.connect('456', '/foo')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
room='123')
self.bm.server._emit_internal.assert_called_once_with('123',
'my event',
{'foo': 'bar'},
'/foo', None)
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', room='123')
self.bm.server._emit_internal.assert_called_once_with(
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_room(self):
self.bm.connect('123', '/foo')
@ -191,15 +202,14 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('456', '/foo')
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
room='bar')
self.assertEqual(self.bm.server._emit_internal.call_count, 2)
self.bm.server._emit_internal.assert_any_call('123', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.server._emit_internal.assert_any_call('456', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo', room='bar')
assert self.bm.server._emit_internal.call_count == 2
self.bm.server._emit_internal.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all(self):
self.bm.connect('123', '/foo')
@ -209,16 +219,16 @@ class TestBaseManager(unittest.TestCase):
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo')
self.assertEqual(self.bm.server._emit_internal.call_count, 3)
self.bm.server._emit_internal.assert_any_call('123', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.server._emit_internal.assert_any_call('456', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.server._emit_internal.assert_any_call('789', 'my event',
{'foo': 'bar'}, '/foo',
None)
assert self.bm.server._emit_internal.call_count == 3
self.bm.server._emit_internal.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.assert_any_call(
'456', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.assert_any_call(
'789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_one(self):
self.bm.connect('123', '/foo')
@ -227,15 +237,16 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
self.bm.emit('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',
{'foo': 'bar'}, '/foo',
None)
self.bm.server._emit_internal.assert_any_call('789', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.emit(
'my event', {'foo': 'bar'}, namespace='/foo', skip_sid='456'
)
assert self.bm.server._emit_internal.call_count == 2
self.bm.server._emit_internal.assert_any_call(
'123', 'my event', {'foo': 'bar'}, '/foo', None
)
self.bm.server._emit_internal.assert_any_call(
'789', 'my event', {'foo': 'bar'}, '/foo', None
)
def test_emit_to_all_skip_two(self):
self.bm.connect('123', '/foo')
@ -244,24 +255,28 @@ class TestBaseManager(unittest.TestCase):
self.bm.enter_room('456', '/foo', 'bar')
self.bm.connect('789', '/foo')
self.bm.connect('abc', '/bar')
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
skip_sid=['123', '789'])
self.assertEqual(self.bm.server._emit_internal.call_count, 1)
self.bm.server._emit_internal.assert_any_call('456', 'my event',
{'foo': 'bar'}, '/foo',
None)
self.bm.emit(
'my event',
{'foo': 'bar'},
namespace='/foo',
skip_sid=['123', '789'],
)
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):
self.bm.connect('123', '/foo')
self.bm._generate_ack_id = mock.MagicMock()
self.bm._generate_ack_id.return_value = 11
self.bm.emit('my event', {'foo': 'bar'}, namespace='/foo',
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.server._emit_internal.assert_called_once_with('123',
'my event',
{'foo': 'bar'},
'/foo', 11)
self.bm.server._emit_internal.assert_called_once_with(
'123', 'my event', {'foo': 'bar'}, '/foo', 11
)
def test_emit_to_invalid_room(self):
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 six
if six.PY3:
from unittest import mock
else:
@ -27,8 +28,9 @@ class TestMiddleware(unittest.TestCase):
environ = {'PATH_INFO': '/socket.io/'}
start_response = "foo"
m(environ, start_response)
mock_sio_app.handle_request.assert_called_once_with(environ,
start_response)
mock_sio_app.handle_request.assert_called_once_with(
environ, start_response
)
def test_404(self):
mock_wsgi_app = None
@ -37,6 +39,7 @@ class TestMiddleware(unittest.TestCase):
environ = {'PATH_INFO': '/foo/bar'}
start_response = mock.MagicMock()
r = m(environ, start_response)
self.assertEqual(r, [b'Not Found'])
assert r == [b'Not Found']
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 six
if six.PY3:
from unittest import mock
else:
@ -19,7 +20,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
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):
result = {}
@ -31,7 +32,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
ns.trigger_event('disconnect', 'sid')
self.assertEqual(result['result'], 'sid')
assert result['result'] == 'sid'
def test_event(self):
result = {}
@ -43,7 +44,7 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
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):
result = {}
@ -55,54 +56,86 @@ class TestNamespace(unittest.TestCase):
ns = MyNamespace('/foo')
ns._set_server(mock.MagicMock())
ns.trigger_event('another_custom_message', 'sid', {'data': 'data'})
self.assertEqual(result, {})
assert result == {}
def test_emit(self):
ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock())
ns.emit('ev', data='data', room='room', skip_sid='skip',
callback='cb')
ns.emit('ev', data='data', room='room', skip_sid='skip', callback='cb')
ns.server.emit.assert_called_with(
'ev', data='data', room='room', skip_sid='skip', namespace='/foo',
callback='cb')
ns.emit('ev', data='data', room='room', skip_sid='skip',
namespace='/bar', callback='cb')
'ev',
data='data',
room='room',
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(
'ev', data='data', room='room', skip_sid='skip', namespace='/bar',
callback='cb')
'ev',
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_send(self):
ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock())
ns.send(data='data', room='room', skip_sid='skip', callback='cb')
ns.server.send.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/foo',
callback='cb')
ns.send(data='data', room='room', skip_sid='skip', namespace='/bar',
callback='cb')
'data',
room='room',
skip_sid='skip',
namespace='/foo',
callback='cb',
)
ns.send(
data='data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
ns.server.send.assert_called_with(
'data', room='room', skip_sid='skip', namespace='/bar',
callback='cb')
'data',
room='room',
skip_sid='skip',
namespace='/bar',
callback='cb',
)
def test_enter_room(self):
ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock())
ns.enter_room('sid', 'room')
ns.server.enter_room.assert_called_with('sid', 'room',
namespace='/foo')
ns.server.enter_room.assert_called_with(
'sid', 'room', namespace='/foo'
)
ns.enter_room('sid', 'room', namespace='/bar')
ns.server.enter_room.assert_called_with('sid', 'room',
namespace='/bar')
ns.server.enter_room.assert_called_with(
'sid', 'room', namespace='/bar'
)
def test_leave_room(self):
ns = namespace.Namespace('/foo')
ns._set_server(mock.MagicMock())
ns.leave_room('sid', 'room')
ns.server.leave_room.assert_called_with('sid', 'room',
namespace='/foo')
ns.server.leave_room.assert_called_with(
'sid', 'room', namespace='/foo'
)
ns.leave_room('sid', 'room', namespace='/bar')
ns.server.leave_room.assert_called_with('sid', 'room',
namespace='/bar')
ns.server.leave_room.assert_called_with(
'sid', 'room', namespace='/bar'
)
def test_close_room(self):
ns = namespace.Namespace('/foo')
@ -128,11 +161,13 @@ class TestNamespace(unittest.TestCase):
ns.get_session('sid', namespace='/bar')
ns.server.get_session.assert_called_with('sid', namespace='/bar')
ns.save_session('sid', {'a': 'b'})
ns.server.save_session.assert_called_with('sid', {'a': 'b'},
namespace='/foo')
ns.server.save_session.assert_called_with(
'sid', {'a': 'b'}, namespace='/foo'
)
ns.save_session('sid', {'a': 'b'}, namespace='/bar')
ns.server.save_session.assert_called_with('sid', {'a': 'b'},
namespace='/bar')
ns.server.save_session.assert_called_with(
'sid', {'a': 'b'}, namespace='/bar'
)
ns.session('sid')
ns.server.session.assert_called_with('sid', namespace='/foo')
ns.session('sid', namespace='/bar')
@ -151,20 +186,24 @@ class TestNamespace(unittest.TestCase):
ns._set_client(mock.MagicMock())
ns.emit('ev', data='data', callback='cb')
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.client.emit.assert_called_with(
'ev', data='data', namespace='/bar', callback='cb')
'ev', data='data', namespace='/bar', callback='cb'
)
def test_send_client(self):
ns = namespace.ClientNamespace('/foo')
ns._set_client(mock.MagicMock())
ns.send(data='data', callback='cb')
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.client.send.assert_called_with(
'data', namespace='/bar', callback='cb')
'data', namespace='/bar', callback='cb'
)
def test_disconnect_client(self):
ns = namespace.ClientNamespace('/foo')

287
tests/common/test_packet.py

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

356
tests/common/test_pubsub_manager.py

@ -3,6 +3,7 @@ import unittest
import logging
import six
if six.PY3:
from unittest import mock
else:
@ -10,6 +11,7 @@ else:
from socketio import base_manager
from socketio import pubsub_manager
import pytest
class TestBaseManager(unittest.TestCase):
@ -22,217 +24,330 @@ class TestBaseManager(unittest.TestCase):
self.pm.initialize()
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._thread)
self.pm._thread
)
def test_custom_init(self):
pubsub = pubsub_manager.PubSubManager(channel='foo')
self.assertEqual(pubsub.channel, 'foo')
self.assertEqual(len(pubsub.host_id), 32)
assert pubsub.channel == 'foo'
assert len(pubsub.host_id) == 32
def test_write_only_init(self):
mock_server = mock.MagicMock()
pm = pubsub_manager.PubSubManager(write_only=True)
pm.set_server(mock_server)
pm.initialize()
self.assertEqual(pm.channel, 'socketio')
self.assertEqual(len(pm.host_id), 32)
self.assertEqual(pm.server.start_background_task.call_count, 0)
assert pm.channel == 'socketio'
assert len(pm.host_id) == 32
assert pm.server.start_background_task.call_count == 0
def test_write_only_default_logger(self):
pm = pubsub_manager.PubSubManager(write_only=True)
pm.initialize()
self.assertEqual(pm.channel, 'socketio')
self.assertEqual(len(pm.host_id), 32)
self.assertEqual(pm._get_logger(), logging.getLogger('socketio'))
assert pm.channel == 'socketio'
assert len(pm.host_id) == 32
assert pm._get_logger() == logging.getLogger('socketio')
def test_write_only_with_provided_logger(self):
test_logger = logging.getLogger('new_logger')
pm = pubsub_manager.PubSubManager(write_only=True,
logger=test_logger)
pm = pubsub_manager.PubSubManager(write_only=True, logger=test_logger)
pm.initialize()
self.assertEqual(pm.channel, 'socketio')
self.assertEqual(len(pm.host_id), 32)
self.assertEqual(pm._get_logger(), test_logger)
assert pm.channel == 'socketio'
assert len(pm.host_id) == 32
assert pm._get_logger() == test_logger
def test_emit(self):
self.pm.emit('foo', 'bar')
self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': None, 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_namespace(self):
self.pm.emit('foo', 'bar', namespace='/baz')
self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/baz', 'room': None, 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'room': None,
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_room(self):
self.pm.emit('foo', 'bar', room='baz')
self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': 'baz', 'skip_sid': None,
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_skip_sid(self):
self.pm.emit('foo', 'bar', skip_sid='baz')
self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': None, 'skip_sid': 'baz',
'callback': None, 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': None,
'skip_sid': 'baz',
'callback': None,
'host_id': '123456',
}
)
def test_emit_with_callback(self):
with mock.patch.object(self.pm, '_generate_ack_id',
return_value='123'):
with mock.patch.object(
self.pm, '_generate_ack_id', return_value='123'
):
self.pm.emit('foo', 'bar', room='baz', callback='cb')
self.pm._publish.assert_called_once_with(
{'method': 'emit', 'event': 'foo', 'data': 'bar',
'namespace': '/', 'room': 'baz', 'skip_sid': None,
'callback': ('baz', '/', '123'), 'host_id': '123456'})
{
'method': 'emit',
'event': 'foo',
'data': 'bar',
'namespace': '/',
'room': 'baz',
'skip_sid': None,
'callback': ('baz', '/', '123'),
'host_id': '123456',
}
)
def test_emit_with_callback_without_server(self):
standalone_pm = pubsub_manager.PubSubManager()
self.assertRaises(RuntimeError, standalone_pm.emit, 'foo', 'bar',
callback='cb')
with pytest.raises(RuntimeError):
standalone_pm.emit('foo', 'bar', callback='cb')
def test_emit_with_callback_missing_room(self):
with mock.patch.object(self.pm, '_generate_ack_id',
return_value='123'):
self.assertRaises(ValueError, self.pm.emit, 'foo', 'bar',
callback='cb')
with mock.patch.object(
self.pm, '_generate_ack_id', return_value='123'
):
with pytest.raises(ValueError):
self.pm.emit('foo', 'bar', callback='cb')
def test_emit_with_ignore_queue(self):
self.pm.connect('123', '/')
self.pm.emit('foo', 'bar', room='123', namespace='/',
ignore_queue=True)
self.pm.emit(
'foo', 'bar', room='123', namespace='/', ignore_queue=True
)
self.pm._publish.assert_not_called()
self.pm.server._emit_internal.assert_called_once_with('123', 'foo',
'bar', '/', None)
self.pm.server._emit_internal.assert_called_once_with(
'123', 'foo', 'bar', '/', None
)
def test_can_disconnect(self):
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._publish.assert_called_once_with(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'})
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
def test_close_room(self):
self.pm.close_room('foo')
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):
self.pm.close_room('foo', '/bar')
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):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar'})
super_emit.assert_called_once_with('foo', 'bar', namespace=None,
room=None, skip_sid=None,
callback=None)
super_emit.assert_called_once_with(
'foo',
'bar',
namespace=None,
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_namespace(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'namespace': '/baz'})
super_emit.assert_called_once_with('foo', 'bar', namespace='/baz',
room=None, skip_sid=None,
callback=None)
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'namespace': '/baz'}
)
super_emit.assert_called_once_with(
'foo',
'bar',
namespace='/baz',
room=None,
skip_sid=None,
callback=None,
)
def test_handle_emit_with_room(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'room': 'baz'})
super_emit.assert_called_once_with('foo', 'bar', namespace=None,
room='baz', skip_sid=None,
callback=None)
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'room': 'baz'}
)
super_emit.assert_called_once_with(
'foo',
'bar',
namespace=None,
room='baz',
skip_sid=None,
callback=None,
)
def test_handle_emit_with_skip_sid(self):
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'skip_sid': '123'})
super_emit.assert_called_once_with('foo', 'bar', namespace=None,
room=None, skip_sid='123',
callback=None)
self.pm._handle_emit(
{'event': 'foo', 'data': 'bar', 'skip_sid': '123'}
)
super_emit.assert_called_once_with(
'foo',
'bar',
namespace=None,
room=None,
skip_sid='123',
callback=None,
)
def test_handle_emit_with_callback(self):
host_id = self.pm.host_id
with mock.patch.object(base_manager.BaseManager, 'emit') as super_emit:
self.pm._handle_emit({'event': 'foo', 'data': 'bar',
'namespace': '/baz',
'callback': ('sid', '/baz', 123),
'host_id': host_id})
self.assertEqual(super_emit.call_count, 1)
self.assertEqual(super_emit.call_args[0], ('foo', 'bar'))
self.assertEqual(super_emit.call_args[1]['namespace'], '/baz')
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'],
functools.partial)
self.pm._handle_emit(
{
'event': 'foo',
'data': 'bar',
'namespace': '/baz',
'callback': ('sid', '/baz', 123),
'host_id': host_id,
}
)
assert super_emit.call_count == 1
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')
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):
host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback',
'host_id': host_id, 'sid': 'sid',
'namespace': '/', 'id': 123,
'args': ('one', 2)})
self.pm._handle_callback(
{
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
trigger.assert_called_once_with('sid', '/', 123, ('one', 2))
def test_handle_callback_bad_host_id(self):
with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback',
'host_id': 'bad', 'sid': 'sid',
'namespace': '/', 'id': 123,
'args': ('one', 2)})
self.assertEqual(trigger.call_count, 0)
self.pm._handle_callback(
{
'method': 'callback',
'host_id': 'bad',
'sid': 'sid',
'namespace': '/',
'id': 123,
'args': ('one', 2),
}
)
assert trigger.call_count == 0
def test_handle_callback_missing_args(self):
host_id = self.pm.host_id
with mock.patch.object(self.pm, 'trigger_callback') as trigger:
self.pm._handle_callback({'method': 'callback',
'host_id': host_id, 'sid': 'sid',
'namespace': '/', 'id': 123})
self.pm._handle_callback({'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})
self.assertEqual(trigger.call_count, 0)
self.pm._handle_callback(
{
'method': 'callback',
'host_id': host_id,
'sid': 'sid',
'namespace': '/',
'id': 123,
}
)
self.pm._handle_callback(
{
'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):
self.pm._handle_disconnect({'method': 'disconnect', 'sid': '123',
'namespace': '/foo'})
self.pm.server.disconnect.assert_called_once_with(sid='123',
namespace='/foo',
ignore_queue=True)
self.pm._handle_disconnect(
{'method': 'disconnect', 'sid': '123', 'namespace': '/foo'}
)
self.pm.server.disconnect.assert_called_once_with(
sid='123', namespace='/foo', ignore_queue=True
)
def test_handle_close_room(self):
with mock.patch.object(base_manager.BaseManager, 'close_room') \
as super_close_room:
self.pm._handle_close_room({'method': 'close_room',
'room': 'foo'})
super_close_room.assert_called_once_with(room='foo',
namespace=None)
with mock.patch.object(
base_manager.BaseManager, 'close_room'
) as super_close_room:
self.pm._handle_close_room({'method': 'close_room', 'room': 'foo'})
super_close_room.assert_called_once_with(
room='foo', namespace=None
)
def test_handle_close_room_with_namespace(self):
with mock.patch.object(base_manager.BaseManager, 'close_room') \
as super_close_room:
self.pm._handle_close_room({'method': 'close_room',
'room': 'foo', 'namespace': '/bar'})
super_close_room.assert_called_once_with(room='foo',
namespace='/bar')
with mock.patch.object(
base_manager.BaseManager, 'close_room'
) as super_close_room:
self.pm._handle_close_room(
{'method': 'close_room', 'room': 'foo', 'namespace': '/bar'}
)
super_close_room.assert_called_once_with(
room='foo', namespace='/bar'
)
def test_background_thread(self):
self.pm._handle_emit = mock.MagicMock()
@ -242,6 +357,7 @@ class TestBaseManager(unittest.TestCase):
def messages():
import pickle
yield {'method': 'emit', 'value': 'foo'}
yield {'missing': 'method'}
yield '{"method": "callback", "value": "bar"}'
@ -258,10 +374,14 @@ class TestBaseManager(unittest.TestCase):
pass
self.pm._handle_emit.assert_called_once_with(
{'method': 'emit', 'value': 'foo'})
{'method': 'emit', 'value': 'foo'}
)
self.pm._handle_callback.assert_called_once_with(
{'method': 'callback', 'value': 'bar'})
{'method': 'callback', 'value': 'bar'}
)
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(
{'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 six
if six.PY3:
from unittest import mock
else:
@ -12,6 +13,7 @@ from socketio import exceptions
from socketio import namespace
from socketio import packet
from socketio import server
import pytest
@mock.patch('engineio.Server')
@ -22,15 +24,16 @@ class TestServer(unittest.TestCase):
def test_create(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, binary=True,
async_handlers=True, foo='bar')
s = server.Server(
client_manager=mgr, binary=True, async_handlers=True, foo='bar'
)
s.handle_request({}, None)
s.handle_request({}, None)
eio.assert_called_once_with(**{'foo': 'bar', 'async_handlers': False})
self.assertEqual(s.manager, mgr)
self.assertEqual(s.eio.on.call_count, 3)
self.assertEqual(s.binary, True)
self.assertEqual(s.async_handlers, True)
assert s.manager == mgr
assert s.eio.on.call_count == 3
assert s.binary
assert s.async_handlers
def test_on_event(self, eio):
s = server.Server()
@ -41,12 +44,13 @@ class TestServer(unittest.TestCase):
def bar():
pass
s.on('disconnect', bar)
s.on('disconnect', bar, namespace='/foo')
self.assertEqual(s.handlers['/']['connect'], foo)
self.assertEqual(s.handlers['/']['disconnect'], bar)
self.assertEqual(s.handlers['/foo']['disconnect'], bar)
assert s.handlers['/']['connect'] == foo
assert s.handlers['/']['disconnect'] == bar
assert s.handlers['/foo']['disconnect'] == bar
def test_event(self, eio):
s = server.Server()
@ -67,86 +71,141 @@ class TestServer(unittest.TestCase):
def disconnect():
pass
self.assertEqual(s.handlers['/']['connect'], connect)
self.assertEqual(s.handlers['/']['foo'], foo)
self.assertEqual(s.handlers['/']['bar'], bar)
self.assertEqual(s.handlers['/foo']['disconnect'], disconnect)
assert s.handlers['/']['connect'] == connect
assert s.handlers['/']['foo'] == foo
assert s.handlers['/']['bar'] == bar
assert s.handlers['/foo']['disconnect'] == disconnect
def test_emit(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
s.emit('my event', {'foo': 'bar'}, to='room', 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.assert_called_once_with(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123',
callback='cb')
s.emit('my event', {'foo': 'bar'}, room='room', skip_sid='123',
namespace='/foo', callback='cb')
'my event',
{'foo': 'bar'},
'/foo',
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(
'my event', {'foo': 'bar'}, '/foo', room='room', skip_sid='123',
callback='cb')
'my event',
{'foo': 'bar'},
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_emit_default_namespace(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
s.emit('my event', {'foo': 'bar'}, to='room', skip_sid='123',
callback='cb')
s.emit(
'my event',
{'foo': 'bar'},
to='room',
skip_sid='123',
callback='cb',
)
s.manager.emit.assert_called_once_with(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123',
callback='cb')
s.emit('my event', {'foo': 'bar'}, room='room', skip_sid='123',
callback='cb')
'my event',
{'foo': 'bar'},
'/',
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(
'my event', {'foo': 'bar'}, '/', room='room', skip_sid='123',
callback='cb')
'my event',
{'foo': 'bar'},
'/',
room='room',
skip_sid='123',
callback='cb',
)
def test_send(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
s.send('foo', to='room', skip_sid='123', namespace='/foo',
callback='cb')
s.send(
'foo', to='room', skip_sid='123', namespace='/foo', callback='cb'
)
s.manager.emit.assert_called_once_with(
'message', 'foo', '/foo', room='room', skip_sid='123',
callback='cb')
s.send('foo', room='room', skip_sid='123', namespace='/foo',
callback='cb')
'message',
'foo',
'/foo',
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(
'message', 'foo', '/foo', room='room', skip_sid='123',
callback='cb')
'message',
'foo',
'/foo',
room='room',
skip_sid='123',
callback='cb',
)
def test_call(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
def fake_event_wait(timeout=None):
self.assertEqual(timeout, 60)
assert timeout == 60
s.manager.emit.call_args_list[0][1]['callback']('foo', 321)
return True
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):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
def fake_event_wait(timeout=None):
self.assertEqual(timeout, 12)
assert timeout == 12
return False
s.eio.create_event.return_value.wait = fake_event_wait
self.assertRaises(exceptions.TimeoutError, s.call, 'foo',
sid='123', timeout=12)
with pytest.raises(exceptions.TimeoutError):
s.call('foo', sid='123', timeout=12)
def test_call_with_broadcast(self, eio):
s = server.Server()
self.assertRaises(ValueError, s.call, 'foo')
with pytest.raises(ValueError):
s.call('foo')
def test_call_without_async_handlers(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, async_handlers=False)
self.assertRaises(RuntimeError, s.call, 'foo',
sid='123', timeout=12)
with pytest.raises(RuntimeError):
s.call('foo', sid='123', timeout=12)
def test_enter_room(self, eio):
mgr = mock.MagicMock()
@ -199,60 +258,63 @@ class TestServer(unittest.TestCase):
def test_handle_request(self, eio):
s = server.Server()
s.handle_request('environ', 'start_response')
s.eio.handle_request.assert_called_once_with('environ',
'start_response')
s.eio.handle_request.assert_called_once_with(
'environ', 'start_response'
)
def test_emit_internal(self, eio):
s = server.Server()
s._emit_internal('123', 'my event', 'my data', namespace='/foo')
s.eio.send.assert_called_once_with('123',
'2/foo,["my event","my data"]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2/foo,["my event","my data"]', binary=False
)
def test_emit_internal_with_tuple(self, eio):
s = server.Server()
s._emit_internal('123', 'my event', ('foo', 'bar'), namespace='/foo')
s.eio.send.assert_called_once_with('123',
'2/foo,["my event","foo","bar"]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2/foo,["my event","foo","bar"]', binary=False
)
def test_emit_internal_with_list(self, eio):
s = server.Server()
s._emit_internal('123', 'my event', ['foo', 'bar'], namespace='/foo')
s.eio.send.assert_called_once_with('123',
'2/foo,["my event",["foo","bar"]]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2/foo,["my event",["foo","bar"]]', binary=False
)
def test_emit_internal_with_none(self, eio):
s = server.Server()
s._emit_internal('123', 'my event', None, namespace='/foo')
s.eio.send.assert_called_once_with('123', '2/foo,["my event"]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2/foo,["my event"]', binary=False
)
def test_emit_internal_with_callback(self, eio):
s = server.Server()
id = s.manager._generate_ack_id('123', '/foo', 'cb')
s._emit_internal('123', 'my event', 'my data', namespace='/foo', id=id)
s.eio.send.assert_called_once_with('123',
'2/foo,1["my event","my data"]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2/foo,1["my event","my data"]', binary=False
)
def test_emit_internal_default_namespace(self, eio):
s = server.Server()
s._emit_internal('123', 'my event', 'my data')
s.eio.send.assert_called_once_with('123', '2["my event","my data"]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '2["my event","my data"]', binary=False
)
def test_emit_internal_binary(self, eio):
s = server.Server(binary=True)
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):
s = server.Server()
s.eio.transport = mock.MagicMock(return_value='polling')
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')
def test_handle_connect(self, eio):
@ -264,9 +326,9 @@ class TestServer(unittest.TestCase):
handler.assert_called_once_with('123', 'environ')
s.manager.connect.assert_called_once_with('123', '/')
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')
self.assertEqual(mgr.initialize.call_count, 1)
assert mgr.initialize.call_count == 1
def test_handle_connect_namespace(self, eio):
mgr = mock.MagicMock()
@ -286,11 +348,11 @@ class TestServer(unittest.TestCase):
handler = mock.MagicMock(return_value=False)
s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret)
assert not ret
handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {})
assert s.manager.connect.call_count == 1
assert s.manager.disconnect.call_count == 1
assert s.environ == {}
def test_handle_connect_namespace_rejected(self, eio):
mgr = mock.MagicMock()
@ -299,10 +361,10 @@ class TestServer(unittest.TestCase):
s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret)
self.assertEqual(s.manager.connect.call_count, 2)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {'123': 'environ'})
assert ret is None
assert s.manager.connect.call_count == 2
assert s.manager.disconnect.call_count == 1
assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '4/foo', binary=False)
def test_handle_connect_rejected_always_connect(self, eio):
@ -311,11 +373,11 @@ class TestServer(unittest.TestCase):
handler = mock.MagicMock(return_value=False)
s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret)
assert not ret
handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {})
assert s.manager.connect.call_count == 1
assert s.manager.disconnect.call_count == 1
assert s.environ == {}
s.eio.send.assert_any_call('123', '0', 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')
ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret)
self.assertEqual(s.manager.connect.call_count, 2)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {'123': 'environ'})
assert ret is None
assert s.manager.connect.call_count == 2
assert s.manager.disconnect.call_count == 1
assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '0/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()
s = server.Server(client_manager=mgr)
handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError('fail_reason'))
side_effect=exceptions.ConnectionRefusedError('fail_reason')
)
s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ')
self.assertEqual(ret, 'fail_reason')
assert ret == 'fail_reason'
handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {})
assert s.manager.connect.call_count == 1
assert s.manager.disconnect.call_count == 1
assert s.environ == {}
def test_handle_connect_rejected_with_empty_exception(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError())
side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler)
ret = s._handle_eio_connect('123', 'environ')
self.assertFalse(ret)
assert not ret
handler.assert_called_once_with('123', 'environ')
self.assertEqual(s.manager.connect.call_count, 1)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {})
assert s.manager.connect.call_count == 1
assert s.manager.disconnect.call_count == 1
assert s.environ == {}
def test_handle_connect_namespace_rejected_with_exception(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
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')
ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret)
self.assertEqual(s.manager.connect.call_count, 2)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {'123': 'environ'})
s.eio.send.assert_any_call('123', '4/foo,["fail_reason",1]',
binary=False)
assert ret is None
assert s.manager.connect.call_count == 2
assert s.manager.disconnect.call_count == 1
assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call(
'123', '4/foo,["fail_reason",1]', binary=False
)
def test_handle_connect_namespace_rejected_with_empty_exception(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
handler = mock.MagicMock(
side_effect=exceptions.ConnectionRefusedError())
side_effect=exceptions.ConnectionRefusedError()
)
s.on('connect', handler, namespace='/foo')
ret = s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/foo')
self.assertIsNone(ret)
self.assertEqual(s.manager.connect.call_count, 2)
self.assertEqual(s.manager.disconnect.call_count, 1)
self.assertEqual(s.environ, {'123': 'environ'})
assert ret is None
assert s.manager.connect.call_count == 2
assert s.manager.disconnect.call_count == 1
assert s.environ == {'123': 'environ'}
s.eio.send.assert_any_call('123', '4/foo', binary=False)
def test_handle_disconnect(self, eio):
@ -397,7 +464,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_disconnect('123')
handler.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):
mgr = mock.MagicMock()
@ -412,7 +479,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_disconnect('123')
handler.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):
mgr = mock.MagicMock()
@ -425,9 +492,9 @@ class TestServer(unittest.TestCase):
s._handle_eio_connect('123', 'environ')
s._handle_eio_message('123', '0/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')
self.assertEqual(s.environ, {'123': 'environ'})
assert s.environ == {'123': 'environ'}
def test_handle_disconnect_unknown_client(self, eio):
mgr = mock.MagicMock()
@ -463,9 +530,12 @@ class TestServer(unittest.TestCase):
s.manager.connect('123', '/')
handler = mock.MagicMock()
s.on('my message', handler)
s._handle_eio_message('123', '52-["my message","a",'
'{"_placeholder":true,"num":1},'
'{"_placeholder":true,"num":0}]')
s._handle_eio_message(
'123',
'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'bar')
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):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr)
s._handle_eio_message('123', '61-321["my message","a",'
'{"_placeholder":true,"num":0}]')
s._handle_eio_message(
'123', '61-321["my message","a",' '{"_placeholder":true,"num":0}]'
)
s._handle_eio_message('123', b'foo')
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):
s = server.Server(async_handlers=False)
@ -486,8 +558,7 @@ class TestServer(unittest.TestCase):
s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]')
handler.assert_called_once_with('123', 'foo')
s.eio.send.assert_called_once_with('123', '31000["foo"]',
binary=False)
s.eio.send.assert_called_once_with('123', '31000["foo"]', binary=False)
def test_handle_event_with_ack_none(self, eio):
s = server.Server(async_handlers=False)
@ -496,8 +567,7 @@ class TestServer(unittest.TestCase):
s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]')
handler.assert_called_once_with('123', 'foo')
s.eio.send.assert_called_once_with('123', '31000[]',
binary=False)
s.eio.send.assert_called_once_with('123', '31000[]', binary=False)
def test_handle_event_with_ack_tuple(self, eio):
mgr = mock.MagicMock()
@ -506,8 +576,9 @@ class TestServer(unittest.TestCase):
s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","a","b","c"]')
handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.assert_called_once_with('123', '31000[1,"2",true]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '31000[1,"2",true]', binary=False
)
def test_handle_event_with_ack_list(self, eio):
mgr = mock.MagicMock()
@ -516,13 +587,15 @@ class TestServer(unittest.TestCase):
s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","a","b","c"]')
handler.assert_called_once_with('123', 'a', 'b', 'c')
s.eio.send.assert_called_once_with('123', '31000[[1,"2",true]]',
binary=False)
s.eio.send.assert_called_once_with(
'123', '31000[[1,"2",true]]', binary=False
)
def test_handle_event_with_ack_binary(self, eio):
mgr = mock.MagicMock()
s = server.Server(client_manager=mgr, binary=True,
async_handlers=False)
s = server.Server(
client_manager=mgr, binary=True, async_handlers=False
)
handler = mock.MagicMock(return_value=b'foo')
s.on('my message', handler)
s._handle_eio_message('123', '21000["my message","foo"]')
@ -530,11 +603,13 @@ class TestServer(unittest.TestCase):
def test_handle_error_packet(self, eio):
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):
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):
s = server.Server()
@ -553,8 +628,7 @@ class TestServer(unittest.TestCase):
s._handle_eio_message('123', '0/foo')
cb = mock.MagicMock()
id = s.manager._generate_ack_id('123', '/foo', cb)
s._emit_internal('123', 'my event', ['foo'], namespace='/foo',
id=id)
s._emit_internal('123', 'my event', ['foo'], namespace='/foo', id=id)
s._handle_eio_message('123', '3/foo,1["foo",2]')
cb.assert_called_once_with('foo', 2)
@ -574,17 +648,19 @@ class TestServer(unittest.TestCase):
s._handle_eio_connect('123', 'environ')
s.save_session('123', {'foo': 'bar'})
with s.session('123') as session:
self.assertEqual(session, {'foo': 'bar'})
assert session == {'foo': 'bar'}
session['foo'] = 'baz'
session['bar'] = 'foo'
self.assertEqual(s.get_session('123'), {'foo': 'baz', 'bar': 'foo'})
self.assertEqual(fake_session, {'/': {'foo': 'baz', 'bar': 'foo'}})
assert s.get_session('123') == {'foo': 'baz', 'bar': 'foo'}
assert fake_session == {'/': {'foo': 'baz', 'bar': 'foo'}}
with s.session('123', namespace='/ns') as session:
self.assertEqual(session, {})
assert session == {}
session['a'] = 'b'
self.assertEqual(s.get_session('123', namespace='/ns'), {'a': 'b'})
self.assertEqual(fake_session, {'/': {'foo': 'baz', 'bar': 'foo'},
'/ns': {'a': 'b'}})
assert s.get_session('123', namespace='/ns') == {'a': 'b'}
assert fake_session == {
'/': {'foo': 'baz', 'bar': 'foo'},
'/ns': {'a': 'b'},
}
def test_disconnect(self, eio):
s = server.Server()
@ -611,7 +687,7 @@ class TestServer(unittest.TestCase):
s.disconnect('123')
calls = s.eio.send.call_count
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):
s = server.Server()
@ -620,7 +696,7 @@ class TestServer(unittest.TestCase):
s.disconnect('123', namespace='/foo')
calls = s.eio.send.call_count
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):
result = {}
@ -645,15 +721,15 @@ class TestServer(unittest.TestCase):
s.register_namespace(MyNamespace('/foo'))
s._handle_eio_connect('123', 'environ')
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"]')
self.assertEqual(result['result'], ('123', 'a'))
assert result['result'] == ('123', 'a')
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"]')
self.assertEqual(result['result'], ('a', 'b'))
assert result['result'] == ('a', 'b')
s.disconnect('123', '/foo')
self.assertEqual(result['result'], ('disconnect', '123'))
assert result['result'] == ('disconnect', '123')
def test_bad_namespace_handler(self, eio):
class Dummy(object):
@ -664,30 +740,35 @@ class TestServer(unittest.TestCase):
return True
s = server.Server()
self.assertRaises(ValueError, s.register_namespace, 123)
self.assertRaises(ValueError, s.register_namespace, Dummy)
self.assertRaises(ValueError, s.register_namespace, Dummy())
self.assertRaises(ValueError, s.register_namespace,
namespace.Namespace)
self.assertRaises(ValueError, s.register_namespace, AsyncNS())
with pytest.raises(ValueError):
s.register_namespace(123)
with pytest.raises(ValueError):
s.register_namespace(Dummy)
with pytest.raises(ValueError):
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):
s = server.Server(logger=False)
self.assertEqual(s.logger.getEffectiveLevel(), logging.ERROR)
assert s.logger.getEffectiveLevel() == logging.ERROR
s.logger.setLevel(logging.NOTSET)
s = server.Server(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.INFO)
assert s.logger.getEffectiveLevel() == logging.INFO
s.logger.setLevel(logging.WARNING)
s = server.Server(logger=True)
self.assertEqual(s.logger.getEffectiveLevel(), logging.WARNING)
assert s.logger.getEffectiveLevel() == logging.WARNING
s.logger.setLevel(logging.NOTSET)
s = server.Server(logger='foo')
self.assertEqual(s.logger, 'foo')
assert s.logger == 'foo'
def test_engineio_logger(self, eio):
server.Server(engineio_logger='foo')
eio.assert_called_once_with(**{'logger': 'foo',
'async_handlers': False})
eio.assert_called_once_with(
**{'logger': 'foo', 'async_handlers': False}
)
def test_custom_json(self, eio):
# Warning: this test cannot run in parallel with other tests, as it
@ -703,14 +784,17 @@ class TestServer(unittest.TestCase):
return '+++ decoded +++'
server.Server(json=CustomJSON)
eio.assert_called_once_with(**{'json': CustomJSON,
'async_handlers': False})
pkt = packet.Packet(packet_type=packet.EVENT,
data={six.text_type('foo'): six.text_type('bar')})
self.assertEqual(pkt.encode(), '2*** encoded ***')
eio.assert_called_once_with(
**{'json': CustomJSON, 'async_handlers': False}
)
pkt = packet.Packet(
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())
self.assertEqual(pkt2.data, '+++ decoded +++')
assert pkt2.data == '+++ decoded +++'
# restore the default JSON module
packet.Packet.json = json
@ -720,14 +804,20 @@ class TestServer(unittest.TestCase):
s.manager.connect('123', '/')
s._handle_eio_message('123', '2["my message","a","b","c"]')
s.eio.start_background_task.assert_called_once_with(
s._handle_event_internal, s, '123', ['my message', 'a', 'b', 'c'],
'/', None)
s._handle_event_internal,
s,
'123',
['my message', 'a', 'b', 'c'],
'/',
None,
)
def test_start_background_task(self, eio):
s = server.Server()
s.start_background_task('foo', 'bar', baz='baz')
s.eio.start_background_task.assert_called_once_with('foo', 'bar',
baz='baz')
s.eio.start_background_task.assert_called_once_with(
'foo', 'bar', baz='baz'
)
def test_sleep(self, eio):
s = server.Server()

2
tox.ini

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

Loading…
Cancel
Save