Skip to content

Commit

Permalink
Use Flask-SocketIO test client (#2445)
Browse files Browse the repository at this point in the history
Previously test_sockets_manager.py communicated with a MSColab server
running in a different process. This made it impossible to assert
anything on the server state (e.g. on attributes of the SocketsManager
object) due to the process boundary.

Using a test client also simplifies the test setup quite a bit.
  • Loading branch information
matrss authored Aug 1, 2024
1 parent b4118a4 commit c35c31c
Showing 1 changed file with 20 additions and 54 deletions.
74 changes: 20 additions & 54 deletions tests/_test_mscolab/test_sockets_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@
"""
import os
import pytest
import socket
import socketio
import datetime
import requests
from urllib.parse import urljoin, urlparse

from mslib.msui.icons import icons
from mslib.mscolab.conf import mscolab_settings
Expand All @@ -41,11 +37,10 @@

class Test_Socket_Manager:
@pytest.fixture(autouse=True)
def setup(self, mscolab_app, mscolab_managers, mscolab_server):
def setup(self, mscolab_app, mscolab_managers):
self.app = mscolab_app
sockio, self.cm, self.fm = mscolab_managers
self.sm = sockio.sm
self.url = mscolab_server
self.sockio, self.cm, self.fm = mscolab_managers
self.sm = self.sockio.sm
self.sockets = []
self.userdata = 'UV10@uv10', 'UV10', 'uv10'
self.anotheruserdata = 'UV20@uv20', 'UV20', 'uv20'
Expand All @@ -62,23 +57,9 @@ def setup(self, mscolab_app, mscolab_managers, mscolab_server):
for sock in self.sockets:
sock.disconnect()

def _can_ping_server(self):
parsed_url = urlparse(self.url)
host, port = parsed_url.hostname, parsed_url.port
try:
sock = socket.create_connection((host, port))
success = True
except socket.error:
success = False
finally:
sock.close()
return success

def _connect(self):
sio = socketio.Client(reconnection_attempts=5)
sio = self.sockio.test_client(self.app)
self.sockets.append(sio)
assert self._can_ping_server()
sio.connect(self.url, transports='polling')
sio.emit('connect')
return sio

Expand All @@ -88,13 +69,8 @@ def _new_operation(self, operation_name, description):
return operation

def test_handle_connect(self):
sio = socketio.Client()
assert sio.sid is None
self.sockets.append(sio)
assert self._can_ping_server()
sio.connect(self.url, transports='polling')
sio.emit('connect')
assert len(sio.sid) > 5
sio = self._connect()
assert len(sio.eio_sid) > 5

def test_join_creator_to_operatiom(self):
sio = self._connect()
Expand Down Expand Up @@ -122,14 +98,12 @@ def test_join_collaborator_to_operation(self):

def test_remove_collaborator_from_operation(self):
pytest.skip("get_session_id has None result")
sio = self._connect()
operation = self._new_operation('new_operation', "example description")
sm = SocketsManager(self.cm, self.fm)
sm.join_collaborator_to_operation(self.anotheruser.id, operation.id)
perms = Permission(self.anotheruser.id, operation.id, "collaborator")
assert perms is not None
sm.remove_collaborator_from_operation(self.anotheruser.id, operation.id)
sio.sleep(1)
perms = Permission(self.anotheruser.id, operation.id, "collaborator")
assert perms is None

Expand Down Expand Up @@ -158,7 +132,6 @@ def test_send_message(self):
"message_text": "® non ascii",
"reply_id": -1
})
sio.sleep(1)

with self.app.app_context():
message = Message.query.filter_by(text="message from 1").first()
Expand All @@ -185,7 +158,6 @@ def test_get_messages(self):
"message_text": "message from 1",
"reply_id": -1
})
sio.sleep(5)
with self.app.app_context():
messages = self.cm.get_messages(1)
assert messages[0]["text"] == "message from 1"
Expand Down Expand Up @@ -216,23 +188,21 @@ def test_get_messages_api(self):
"message_text": "message from 1",
"reply_id": -1
})
sio.sleep(1)

token = self.token
data = {
"token": token,
"op_id": self.operation.id,
"timestamp": datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc).isoformat()
}
# returns an array of messages
url = urljoin(self.url, 'messages')
res = requests.get(url, data=data, timeout=(2, 10)).json()
assert len(res["messages"]) == 2
with self.app.test_client() as c:
res = c.get("/messages", data=data)
assert len(res.json["messages"]) == 2

data["token"] = "dummy"
# returns False due to bad authorization
r = requests.get(url, data=data, timeout=(2, 10))
assert r.text == "False"
data["token"] = "dummy"
# returns False due to bad authorization
r = c.get("/messages", data=data)
assert r.text == "False"

def test_edit_message(self):
sio = self._connect()
Expand All @@ -244,7 +214,6 @@ def test_edit_message(self):
"message_text": "Edit this message",
"reply_id": -1
})
sio.sleep(1)
with self.app.app_context():
message = Message.query.filter_by(text="Edit this message").first()
sio.emit('edit-message', {
Expand All @@ -253,16 +222,14 @@ def test_edit_message(self):
"op_id": message.op_id,
"token": self.token
})
sio.sleep(1)
token = self.token
data = {
"token": token,
"op_id": self.operation.id,
"timestamp": datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc).isoformat()
}
# returns an array of messages
url = urljoin(self.url, 'messages')
res = requests.get(url, data=data, timeout=(2, 10)).json()
with self.app.test_client() as c:
res = c.get("messages", data=data).json
assert len(res["messages"]) == 1
messages = res["messages"][0]
assert messages["text"] == "I have updated the message"
Expand All @@ -277,30 +244,29 @@ def test_delete_message(self):
"message_text": "delete this message",
"reply_id": -1
})
sio.sleep(1)

with self.app.app_context():
message = Message.query.filter_by(text="delete this message").first()
sio.emit('delete-message', {
'message_id': message.id,
'op_id': self.operation.id,
'token': self.token
})
sio.sleep(1)

with self.app.app_context():
assert Message.query.filter_by(text="delete this message").count() == 0

def test_upload_file(self):
sio = self._connect()
sio.emit('start', {'token': self.token})
files = {'file': open(icons('16x16'), 'rb')}
data = {
"token": self.token,
"op_id": self.operation.id,
"message_type": int(MessageType.IMAGE)
"message_type": int(MessageType.IMAGE),
"file": open(icons('16x16'), 'rb'),
}
url = urljoin(self.url, 'message_attachment')
requests.post(url, data=data, files=files, timeout=(2, 10))
with self.app.test_client() as c:
c.post("message_attachment", data=data, content_type="multipart/form-data")
upload_dir = os.path.join(mscolab_settings.UPLOAD_FOLDER, str(self.user.id))
assert os.path.exists(upload_dir)
file = os.listdir(upload_dir)[0]
Expand Down

0 comments on commit c35c31c

Please sign in to comment.