|
| 1 | +# Unit tests for wallet_osparc_credits.py subscribe and unsubscribe functions |
| 2 | +import asyncio |
| 3 | +from unittest.mock import AsyncMock, patch |
| 4 | + |
| 5 | +import pytest |
| 6 | +from models_library.wallets import WalletID |
| 7 | +from simcore_service_webserver.notifications import wallet_osparc_credits |
| 8 | + |
| 9 | + |
| 10 | +@pytest.fixture |
| 11 | +def app_with_wallets(): |
| 12 | + app = { |
| 13 | + "wallet_subscription_lock": asyncio.Lock(), |
| 14 | + "wallet_subscriptions": {}, |
| 15 | + } |
| 16 | + return app |
| 17 | + |
| 18 | + |
| 19 | +@pytest.fixture |
| 20 | +def wallet_id(): |
| 21 | + return WalletID(1) |
| 22 | + |
| 23 | + |
| 24 | +async def test_subscribe_first_and_second(app_with_wallets, wallet_id): |
| 25 | + app = app_with_wallets |
| 26 | + app["wallet_subscriptions"][wallet_id] = 0 |
| 27 | + mock_rabbit = AsyncMock() |
| 28 | + with patch( |
| 29 | + "simcore_service_webserver.notifications.wallet_osparc_credits.get_rabbitmq_client", |
| 30 | + return_value=mock_rabbit, |
| 31 | + ): |
| 32 | + await wallet_osparc_credits.subscribe(app, wallet_id) |
| 33 | + mock_rabbit.add_topics.assert_awaited_once() |
| 34 | + # Second subscribe should not call add_topics again |
| 35 | + await wallet_osparc_credits.subscribe(app, wallet_id) |
| 36 | + assert mock_rabbit.add_topics.await_count == 1 |
| 37 | + assert app["wallet_subscriptions"][wallet_id] == 2 |
| 38 | + |
| 39 | + |
| 40 | +async def test_unsubscribe_last_and_not_last(app_with_wallets, wallet_id): |
| 41 | + app = app_with_wallets |
| 42 | + app["wallet_subscriptions"][wallet_id] = 2 |
| 43 | + mock_rabbit = AsyncMock() |
| 44 | + with patch( |
| 45 | + "simcore_service_webserver.notifications.wallet_osparc_credits.get_rabbitmq_client", |
| 46 | + return_value=mock_rabbit, |
| 47 | + ): |
| 48 | + # Not last unsubscribe |
| 49 | + await wallet_osparc_credits.unsubscribe(app, wallet_id) |
| 50 | + mock_rabbit.remove_topics.assert_not_awaited() |
| 51 | + assert app["wallet_subscriptions"][wallet_id] == 1 |
| 52 | + # Last unsubscribe |
| 53 | + await wallet_osparc_credits.unsubscribe(app, wallet_id) |
| 54 | + mock_rabbit.remove_topics.assert_awaited_once() |
| 55 | + assert app["wallet_subscriptions"][wallet_id] == 0 |
| 56 | + |
| 57 | + |
| 58 | +async def test_unsubscribe_when_not_subscribed(app_with_wallets, wallet_id): |
| 59 | + app = app_with_wallets |
| 60 | + # wallet_id not present |
| 61 | + mock_rabbit = AsyncMock() |
| 62 | + with patch( |
| 63 | + "simcore_service_webserver.notifications.wallet_osparc_credits.get_rabbitmq_client", |
| 64 | + return_value=mock_rabbit, |
| 65 | + ): |
| 66 | + await wallet_osparc_credits.unsubscribe(app, wallet_id) |
| 67 | + mock_rabbit.remove_topics.assert_not_awaited() |
| 68 | + assert app["wallet_subscriptions"].get(wallet_id, 0) == 0 |
0 commit comments