Skip to content

Commit 3b17f88

Browse files
committed
refactor
1 parent d650b23 commit 3b17f88

File tree

7 files changed

+146
-166
lines changed

7 files changed

+146
-166
lines changed

packages/pytest-simcore/src/pytest_simcore/socketio_client.py

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import pytest
1010
import socketio
1111
from aiohttp.test_utils import TestClient
12+
from pytest_simcore.helpers.logging_tools import log_context
1213
from servicelib.aiohttp import status
1314
from yarl import URL
1415

@@ -56,18 +57,19 @@ async def create_socketio_connection(
5657
security_cookie_factory: Callable[[TestClient | None], Awaitable[str]],
5758
client_session_id_factory: Callable[[], str],
5859
) -> AsyncIterable[
59-
Callable[[str | None, TestClient | None], Awaitable[socketio.AsyncClient]]
60+
Callable[
61+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
62+
]
6063
]:
6164
clients: list[socketio.AsyncClient] = []
6265

6366
async def _connect(
6467
client_session_id: str | None = None, client: TestClient | None = None
65-
) -> socketio.AsyncClient:
68+
) -> tuple[socketio.AsyncClient, str]:
6669
if client_session_id is None:
6770
client_session_id = client_session_id_factory()
6871

6972
sio = socketio.AsyncClient(ssl_verify=False)
70-
# enginio 3.10.0 introduced ssl verification
7173
assert client_session_id
7274
url = str(
7375
URL(socketio_url_factory(client)).with_query(
@@ -80,21 +82,28 @@ async def _connect(
8082
# WARNING: engineio fails with empty cookies. Expects "key=value"
8183
headers.update({"Cookie": cookie})
8284

83-
print(f"--> Connecting socketio client to {url} ...")
84-
await sio.connect(url, headers=headers, wait_timeout=10)
85-
assert sio.sid
86-
print("... connection done")
85+
with log_context(logging.INFO, f"socketio_client: connecting to {url}"):
86+
print(f"--> Connecting socketio client to {url} ...")
87+
sio.on(
88+
"connect",
89+
handler=lambda: logger.info("Connected successfully with %s", sio.sid),
90+
)
91+
sio.on(
92+
"disconnect",
93+
handler=lambda: logger.info("Disconnected from %s", sio.sid),
94+
)
95+
await sio.connect(url, headers=headers, wait_timeout=10)
96+
assert sio.sid
8797
clients.append(sio)
88-
return sio
98+
return sio, client_session_id
8999

90100
yield _connect
91101

92102
# cleans up clients produce by _connect(*) calls
93103
for sio in clients:
94104
if sio.connected:
95-
print(f"<--Disconnecting socketio client {sio}")
96-
await sio.disconnect()
97-
await sio.wait()
98-
print(f"... disconnection from {sio} done.")
99-
assert not sio.connected
105+
with log_context(logging.INFO, f"socketio_client: disconnecting {sio}"):
106+
await sio.disconnect()
107+
await sio.wait()
108+
assert not sio.connected
100109
assert not sio.sid

services/web/server/tests/integration/01/test_garbage_collection.py

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -360,13 +360,15 @@ class SioConnectionData(NamedTuple):
360360
async def connect_to_socketio(
361361
client: TestClient,
362362
user,
363-
socketio_client_factory: Callable[..., Awaitable[socketio.AsyncClient]],
363+
socketio_client_factory: Callable[
364+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
365+
],
364366
) -> SioConnectionData:
365367
"""Connect a user to a socket.io"""
366368
assert client.app
367369
socket_registry = get_registry(client.app)
368370
cur_client_session_id = f"{uuid4()}"
369-
sio = await socketio_client_factory(cur_client_session_id, client)
371+
sio, *_ = await socketio_client_factory(cur_client_session_id, client)
370372
resource_key: UserSessionDict = {
371373
"user_id": str(user["id"]),
372374
"client_session_id": cur_client_session_id,
@@ -516,7 +518,9 @@ async def assert_one_owner_for_project(
516518
async def test_t1_while_guest_is_connected_no_resources_are_removed(
517519
disable_garbage_collector_task: None,
518520
client: TestClient,
519-
create_socketio_connection: Callable,
521+
create_socketio_connection: Callable[
522+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
523+
],
520524
aiopg_engine: aiopg.sa.engine.Engine,
521525
tests_data_dir: Path,
522526
osparc_product_name: str,
@@ -547,7 +551,9 @@ async def test_t1_while_guest_is_connected_no_resources_are_removed(
547551
async def test_t2_cleanup_resources_after_browser_is_closed(
548552
disable_garbage_collector_task: None,
549553
client: TestClient,
550-
create_socketio_connection: Callable,
554+
create_socketio_connection: Callable[
555+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
556+
],
551557
aiopg_engine: aiopg.sa.engine.Engine,
552558
tests_data_dir: Path,
553559
osparc_product_name: str,
@@ -600,7 +606,9 @@ async def test_t2_cleanup_resources_after_browser_is_closed(
600606

601607
async def test_t3_gc_will_not_intervene_for_regular_users_and_their_resources(
602608
client: TestClient,
603-
create_socketio_connection: Callable,
609+
create_socketio_connection: Callable[
610+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
611+
],
604612
aiopg_engine: aiopg.sa.engine.Engine,
605613
fake_project: dict,
606614
tests_data_dir: Path,

services/web/server/tests/integration/02/notifications/test_rabbitmq_consumers.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ async def test_log_workflow(
208208
rabbitmq_publisher: RabbitMQClient,
209209
subscribe_to_logs: bool,
210210
create_socketio_connection: Callable[
211-
[str | None, TestClient | None], Awaitable[socketio.AsyncClient]
211+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
212212
],
213213
# user
214214
sender_same_user_id: bool,
@@ -223,7 +223,7 @@ async def test_log_workflow(
223223
RabbitMQ (TOPIC) --> Webserver --> Redis --> webclient (socketio)
224224
225225
"""
226-
socket_io_conn = await create_socketio_connection(None, client)
226+
socket_io_conn, *_ = await create_socketio_connection(None, client)
227227

228228
mock_log_handler = mocker.MagicMock()
229229
socket_io_conn.on(SOCKET_IO_LOG_EVENT, handler=mock_log_handler)
@@ -316,7 +316,7 @@ async def test_progress_non_computational_workflow(
316316
client: TestClient,
317317
rabbitmq_publisher: RabbitMQClient,
318318
create_socketio_connection: Callable[
319-
[str | None, TestClient | None], Awaitable[socketio.AsyncClient]
319+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
320320
],
321321
subscribe_to_logs: bool,
322322
progress_type: ProgressType,
@@ -332,7 +332,7 @@ async def test_progress_non_computational_workflow(
332332
RabbitMQ (TOPIC) --> Webserver --> Redis --> webclient (socketio)
333333
334334
"""
335-
socket_io_conn = await create_socketio_connection(None, client)
335+
socket_io_conn, *_ = await create_socketio_connection(None, client)
336336

337337
mock_progress_handler = mocker.MagicMock()
338338
socket_io_conn.on(
@@ -374,7 +374,7 @@ async def test_progress_computational_workflow(
374374
rabbitmq_publisher: RabbitMQClient,
375375
user_project: ProjectDict,
376376
create_socketio_connection: Callable[
377-
[str | None, TestClient | None], Awaitable[socketio.AsyncClient]
377+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
378378
],
379379
mocker: MockerFixture,
380380
aiopg_engine: aiopg.sa.Engine,
@@ -391,7 +391,7 @@ async def test_progress_computational_workflow(
391391
Redis --> webclient (socketio)
392392
393393
"""
394-
socket_io_conn = await create_socketio_connection(None, client)
394+
socket_io_conn, *_ = await create_socketio_connection(None, client)
395395

396396
mock_progress_handler = mocker.MagicMock()
397397
socket_io_conn.on(SOCKET_IO_NODE_UPDATED_EVENT, handler=mock_progress_handler)
@@ -499,7 +499,7 @@ async def test_event_workflow(
499499
client: TestClient,
500500
rabbitmq_publisher: RabbitMQClient,
501501
create_socketio_connection: Callable[
502-
[str | None, TestClient | None], Awaitable[socketio.AsyncClient]
502+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
503503
],
504504
# user
505505
sender_same_user_id: bool,
@@ -512,7 +512,7 @@ async def test_event_workflow(
512512
RabbitMQ --> Webserver --> Redis --> webclient (socketio)
513513
514514
"""
515-
socket_io_conn = await create_socketio_connection(None, client)
515+
socket_io_conn, *_ = await create_socketio_connection(None, client)
516516
mock_event_handler = mocker.MagicMock()
517517
socket_io_conn.on(SOCKET_IO_EVENT, handler=mock_event_handler)
518518

services/web/server/tests/unit/with_dbs/02/test_projects_crud_handlers__delete.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from unittest.mock import MagicMock, call
1212

1313
import pytest
14+
import socketio
1415
import sqlalchemy as sa
1516
from aiohttp.test_utils import TestClient
1617
from faker import Faker
@@ -142,8 +143,9 @@ async def test_delete_multiple_opened_project_forbidden(
142143
user_project: ProjectDict,
143144
mocked_dynamic_services_interface,
144145
create_dynamic_service_mock: Callable[..., Awaitable[DynamicServiceGet]],
145-
create_socketio_connection: Callable,
146-
client_session_id_factory: Callable[[], str],
146+
create_socketio_connection: Callable[
147+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
148+
],
147149
user_role: UserRole,
148150
expected_ok: HTTPStatus,
149151
expected_forbidden: HTTPStatus,
@@ -155,9 +157,9 @@ async def test_delete_multiple_opened_project_forbidden(
155157
user_id=logged_user["id"], project_id=user_project["uuid"]
156158
)
157159
# open project in tab1
158-
client_session_id1 = client_session_id_factory()
159160
try:
160-
await create_socketio_connection(client_session_id1)
161+
sio, client_session_id1 = await create_socketio_connection(None, client)
162+
assert sio
161163
except SocketConnectionError:
162164
if user_role != UserRole.ANONYMOUS:
163165
pytest.fail("socket io connection should not fail")
@@ -174,9 +176,10 @@ async def test_delete_multiple_opened_project_forbidden(
174176
mocked_notifications_plugin["subscribe"].assert_not_called()
175177

176178
# delete project in tab2
177-
client_session_id2 = client_session_id_factory()
178179
try:
179-
await create_socketio_connection(client_session_id2)
180+
sio_2, client_session_id2 = await create_socketio_connection(None, client)
181+
assert sio_2
182+
assert client_session_id2 != client_session_id1
180183
except SocketConnectionError:
181184
if user_role != UserRole.ANONYMOUS:
182185
pytest.fail("socket io connection should not fail")

services/web/server/tests/unit/with_dbs/02/test_projects_states_handlers.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ class _SocketHandlers(TypedDict):
171171
@pytest.fixture
172172
async def create_socketio_connection_with_handlers(
173173
create_socketio_connection: Callable[
174-
[str | None, TestClient | None], Awaitable[socketio.AsyncClient]
174+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
175175
],
176176
mocker: MockerFixture,
177177
) -> Callable[
@@ -180,7 +180,7 @@ async def create_socketio_connection_with_handlers(
180180
async def _(
181181
client: TestClient, client_id: str
182182
) -> tuple[socketio.AsyncClient, _SocketHandlers]:
183-
sio = await create_socketio_connection(client_id, client)
183+
sio, *_ = await create_socketio_connection(client_id, client)
184184
assert sio.sid
185185

186186
event_handlers = _SocketHandlers(
@@ -1175,18 +1175,17 @@ async def test_get_active_project(
11751175
client: TestClient,
11761176
logged_user: UserInfoDict,
11771177
user_project: ProjectDict,
1178-
client_session_id_factory: Callable[[], str],
11791178
expected: int,
1180-
create_socketio_connection: Callable,
1179+
create_socketio_connection: Callable[
1180+
[str | None, TestClient | None], Awaitable[tuple[socketio.AsyncClient, str]]
1181+
],
11811182
mocked_dynamic_services_interface: dict[str, mock.Mock],
11821183
mock_catalog_api: dict[str, mock.Mock],
11831184
mocked_notifications_plugin: dict[str, mock.Mock],
11841185
):
11851186
# login with socket using client session id
1186-
client_id1 = client_session_id_factory()
1187-
sio = None
11881187
try:
1189-
sio = await create_socketio_connection(client_id1)
1188+
sio, client_id1 = await create_socketio_connection(None, client)
11901189
assert sio.sid
11911190
except SocketConnectionError:
11921191
if expected == status.HTTP_200_OK:
@@ -1230,9 +1229,8 @@ async def test_get_active_project(
12301229
mocked_notifications_plugin["subscribe"].assert_not_called()
12311230

12321231
# login with socket using client session id2
1233-
client_id2 = client_session_id_factory()
12341232
try:
1235-
sio = await create_socketio_connection(client_id2)
1233+
sio, client_id2 = await create_socketio_connection(None, client)
12361234
assert sio.sid
12371235
except SocketConnectionError:
12381236
if expected == status.HTTP_200_OK:

0 commit comments

Comments
 (0)