Certainly! Below is a comprehensive integration test class for the JoinWheelSessionCommandHandler. This test class is designed to achieve 100% coverage by addressing various scenarios, including successful command execution, error handling, and idempotency.
Assumptions:
- Schemas and Commands: The following schemas and commands are assumed to exist based on your existing tests:
JoinWheelSessionCommand
JoinWheelSessionCommandPayload
ResponseType.JOIN_WHEEL_SESSION
ErrorCode.COMMAND_EXECUTION_ERROR
- WebSocket Endpoints: The WebSocket connection and authentication mechanisms are similar to your existing tests.
- Fixtures: The necessary fixtures such as
client, profile_repo, redis_manager, etc., are available and properly configured.
Test Class: TestJoinWheelSessionCommand
import asyncio
import uuid
from decimal import Decimal
from typing import Tuple, Callable, Optional
import pytest
from async_asgi_testclient import TestClient
from faker import Faker
from profile.constants import CommandType, ErrorCode, WheelContestantSessionStatus, ResponseType
from profile.schemas import (
AuthCommand,
AuthCommandPayload,
JoinWheelSessionCommand,
JoinWheelSessionCommandPayload,
Response,
)
from diamonds_domain.profile.repositories import ProfileRepository
from diamonds_domain.redis_manager import RedisManager
from exceptions import CommandExecutionError
fake = Faker()
@pytest.mark.asyncio
class TestJoinWheelSessionCommand:
@pytest.mark.parametrize("bet", [10, 20, 50, 100])
async def test_join_wheel_session_success(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
bet: int,
) -> None:
"""
Test successful joining of a wheel session with sufficient points.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
# Ensure the user has enough direct points
await profile_repo.update_direct_points(auth_user_uuid, Decimal(bet + 10))
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client:
# Authenticate the user
await ws_client.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.PROFILE
assert resp.response.direct_points >= Decimal(bet)
# Send JoinWheelSessionCommand
await ws_client.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=bet)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate the command execution events
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.JOIN_WHEEL_SESSION
assert resp.response.bet == bet
assert resp.response.status == WheelContestantSessionStatus.CREATED
# Optionally, wait and check if the session is resolved
await asyncio.sleep(1) # Adjust based on session resolution time
# Receive session resolution notification
notification = Response.model_validate_json(await ws_client.receive_text())
assert notification.type == ResponseType.BROADCAST_WHEEL_SESSION
assert notification.response.status in (
WheelContestantSessionStatus.RESOLVED,
WheelContestantSessionStatus.WINNER_DECLARED,
)
# Verify the user's points have been updated
updated_profile = await profile_repo.get_by_auth_user_uuid(auth_user_uuid)
assert updated_profile.direct_points == Decimal(10)
async def test_join_wheel_session_insufficient_points(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
) -> None:
"""
Test joining a wheel session with insufficient direct points.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
# Ensure the user has insufficient direct points
await profile_repo.update_direct_points(auth_user_uuid, Decimal(5))
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client:
# Authenticate the user
await ws_client.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.PROFILE
assert resp.response.direct_points < Decimal(10)
# Send JoinWheelSessionCommand with bet higher than available points
await ws_client.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=10)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate the error response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.ERROR
assert resp.response.message == ErrorCode.COMMAND_EXECUTION_ERROR
async def test_join_wheel_session_no_game(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
mocker: Callable[..., None],
) -> None:
"""
Test joining a wheel session when no game context is available.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
# Mock the context.game to be None
mocker.patch("profile.commands.join_wheel_session.CommandExecutionContext", autospec=True)
from profile.commands.join_wheel_session import CommandExecutionContext
mock_context = CommandExecutionContext()
mock_context.game = None
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client:
# Authenticate the user
await ws_client.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.PROFILE
# Send JoinWheelSessionCommand
await ws_client.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=10)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate the error response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.ERROR
assert resp.response.message == ErrorCode.COMMAND_EXECUTION_ERROR
@pytest.mark.parametrize("bet", [10, 20])
async def test_join_wheel_session_idempotency(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
bet: int,
) -> None:
"""
Test idempotent behavior when joining the same wheel session multiple times.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
# Ensure the user has enough direct points
await profile_repo.update_direct_points(auth_user_uuid, Decimal(bet + 10))
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client:
# Authenticate the user
await ws_client.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.PROFILE
assert resp.response.direct_points >= Decimal(bet)
# Send JoinWheelSessionCommand multiple times
for _ in range(3):
await ws_client.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=bet)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate the command execution events or idempotency confirmation
resp = Response.model_validate_json(await ws_client.receive_text())
if resp.type == ResponseType.JOIN_WHEEL_SESSION:
assert resp.response.bet == bet
assert resp.response.status == WheelContestantSessionStatus.CREATED
elif resp.type == ResponseType.ERROR:
assert resp.response.message == ErrorCode.IDEMPOTENCY_ERROR
# Verify that only one entry exists in the session
# This part depends on your implementation. For example:
session = await redis_manager.get_active_wheel_session()
assert session is not None
contestants = session.contestants
assert len([c for c in contestants if c.auth_user_uuid == auth_user_uuid]) == 1
async def test_join_wheel_session_game_execution_error(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
mocker: Callable[..., None],
) -> None:
"""
Test the scenario where joining the wheel session raises a GameExecutionError.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
# Mock the game.join_session to raise GameExecutionError
mocker.patch(
"profile.commands.join_wheel_session.Game.join_session",
side_effect=CommandExecutionError(code=ErrorCode.COMMAND_EXECUTION_ERROR),
)
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client:
# Authenticate the user
await ws_client.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.PROFILE
# Send JoinWheelSessionCommand
await ws_client.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=10)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate the error response
resp = Response.model_validate_json(await ws_client.receive_text())
assert resp.type == ResponseType.ERROR
assert resp.response.message == ErrorCode.COMMAND_EXECUTION_ERROR
async def test_join_wheel_session_concurrent_joins(
self,
client: TestClient,
profile_repo: ProfileRepository,
redis_manager: RedisManager,
valid_token_and_auth_user_uuid: Tuple[str, uuid.UUID],
valid_connection_state: str,
multiple_users_factory: Callable[[], Tuple[str, uuid.UUID]],
) -> None:
"""
Test multiple users joining the wheel session concurrently.
"""
valid_token, auth_user_uuid = valid_token_and_auth_user_uuid
other_token, other_auth_user_uuid = multiple_users_factory()
# Ensure both users have enough points
await profile_repo.update_direct_points(auth_user_uuid, Decimal(100))
await profile_repo.update_direct_points(other_auth_user_uuid, Decimal(100))
async with client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client1, \
client.websocket_connect(f"/ws/{valid_connection_state}") as ws_client2:
# Authenticate both users
await ws_client1.send_text(
AuthCommand(
payload=AuthCommandPayload(token=valid_token, ref_code=None)
).model_dump_json()
)
await ws_client2.send_text(
AuthCommand(
payload=AuthCommandPayload(token=other_token, ref_code=None)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate profile responses
resp1 = Response.model_validate_json(await ws_client1.receive_text())
resp2 = Response.model_validate_json(await ws_client2.receive_text())
assert resp1.type == ResponseType.PROFILE
assert resp2.type == ResponseType.PROFILE
# Both users send JoinWheelSessionCommand concurrently
await ws_client1.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=50)
).model_dump_json()
)
await ws_client2.send_text(
JoinWheelSessionCommand(
payload=JoinWheelSessionCommandPayload(bet=50)
).model_dump_json()
)
await asyncio.sleep(0.1)
# Receive and validate responses for both users
resp1_cmd = Response.model_validate_json(await ws_client1.receive_text())
resp2_cmd = Response.model_validate_json(await ws_client2.receive_text())
assert resp1_cmd.type == ResponseType.JOIN_WHEEL_SESSION
assert resp2_cmd.type == ResponseType.JOIN_WHEEL_SESSION
# Optionally, wait and check session resolution
await asyncio.sleep(1) # Adjust based on session resolution time
# Receive session resolution notifications
notification1 = Response.model_validate_json(await ws_client1.receive_text())
notification2 = Response.model_validate_json(await ws_client2.receive_text())
assert notification1.type == ResponseType.BROADCAST_WHEEL_SESSION
assert notification2.type == ResponseType.BROADCAST_WHEEL_SESSION
# Verify the session contains both users
session = await redis_manager.get_active_wheel_session()
assert session is not None
contestants = session.contestants
assert len(contestants) >= 2
assert any(c.auth_user_uuid == auth_user_uuid for c in contestants)
assert any(c.auth_user_uuid == other_auth_user_uuid for c in contestants)
# Verify both users' points have been updated correctly
updated_profile1 = await profile_repo.get_by_auth_user_uuid(auth_user_uuid)
updated_profile2 = await profile_repo.get_by_auth_user_uuid(other_auth_user_uuid)
assert updated_profile1.direct_points == Decimal(50)
assert updated_profile2.direct_points == Decimal(50)
Explanation of the Test Class:
-
Imports and Setup:
- Imported necessary modules, fixtures, and classes.
- Initialized a
Faker instance for generating fake data if needed.
-
Test Methods:
-
test_join_wheel_session_success:
- Purpose: Verify that a user with sufficient points can successfully join a wheel session.
- Steps:
- Update the user's direct points to ensure they have enough to place the bet.
- Authenticate the user via WebSocket.
- Send a
JoinWheelSessionCommand with a valid bet.
- Validate that the response indicates a successful join.
- Optionally, wait for the session to resolve and validate the broadcast notification.
- Confirm that the user's points have been deducted appropriately.
-
test_join_wheel_session_insufficient_points:
- Purpose: Ensure that the command fails when the user does not have enough points to place the bet.
- Steps:
- Set the user's direct points to below the required bet.
- Authenticate and send the
JoinWheelSessionCommand.
- Validate that an error response with
COMMAND_EXECUTION_ERROR is received.
-
test_join_wheel_session_no_game:
- Purpose: Test the behavior when there is no active game context.
- Steps:
- Mock the game context to be
None.
- Authenticate and send the
JoinWheelSessionCommand.
- Validate that an error response is received.
-
test_join_wheel_session_idempotency:
- Purpose: Check that sending the same join command multiple times does not create duplicate entries or unintended behavior.
- Steps:
- Authenticate and send the
JoinWheelSessionCommand multiple times.
- Validate that only one successful join response is received and subsequent commands are handled idempotently.
- Optionally, verify that only one contestant exists in the session.
Additional Notes:
-
Concurrency Handling: The test_join_wheel_session_concurrent_joins method demonstrates how to handle multiple WebSocket connections simultaneously to simulate real-world concurrent interactions.
-
Session Resolution: Depending on how session resolution is implemented (timing, event triggers), you may need to adjust the asyncio.sleep durations to ensure that the session state is appropriately updated before assertions.
-
Mocking: The use of mocker.patch allows you to simulate different states and behaviors within your handlers without altering the actual implementation.
-
Idempotency: Ensuring that repeated commands do not adversely affect the system is crucial for maintaining data integrity, especially in scenarios involving network retries or duplicate requests.
This comprehensive test class should cover all critical paths and scenarios for the JoinWheelSessionCommandHandler, ensuring robust and reliable functionality within your FastAPI WebSocket CQRS application.