|
| 1 | +"""Tests for the tokens API.""" |
| 2 | + |
| 3 | +import pytest |
| 4 | +from unittest.mock import AsyncMock, patch, MagicMock |
| 5 | +from decart import DecartClient, TokenCreateError |
| 6 | + |
| 7 | + |
| 8 | +@pytest.mark.asyncio |
| 9 | +async def test_create_token() -> None: |
| 10 | + """Creates a client token successfully.""" |
| 11 | + client = DecartClient(api_key="test-api-key") |
| 12 | + |
| 13 | + mock_response = AsyncMock() |
| 14 | + mock_response.ok = True |
| 15 | + mock_response.json = AsyncMock( |
| 16 | + return_value={"apiKey": "ek_test123", "expiresAt": "2024-12-15T12:10:00Z"} |
| 17 | + ) |
| 18 | + |
| 19 | + mock_session = MagicMock() |
| 20 | + mock_session.post = MagicMock( |
| 21 | + return_value=AsyncMock(__aenter__=AsyncMock(return_value=mock_response)) |
| 22 | + ) |
| 23 | + |
| 24 | + with patch.object(client, "_get_session", AsyncMock(return_value=mock_session)): |
| 25 | + result = await client.tokens.create() |
| 26 | + |
| 27 | + assert result.api_key == "ek_test123" |
| 28 | + assert result.expires_at == "2024-12-15T12:10:00Z" |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.asyncio |
| 32 | +async def test_create_token_401_error() -> None: |
| 33 | + """Handles 401 error.""" |
| 34 | + client = DecartClient(api_key="test-api-key") |
| 35 | + |
| 36 | + mock_response = AsyncMock() |
| 37 | + mock_response.ok = False |
| 38 | + mock_response.status = 401 |
| 39 | + mock_response.text = AsyncMock(return_value="Invalid API key") |
| 40 | + |
| 41 | + mock_session = MagicMock() |
| 42 | + mock_session.post = MagicMock( |
| 43 | + return_value=AsyncMock(__aenter__=AsyncMock(return_value=mock_response)) |
| 44 | + ) |
| 45 | + |
| 46 | + with patch.object(client, "_get_session", AsyncMock(return_value=mock_session)): |
| 47 | + with pytest.raises(TokenCreateError, match="Failed to create token"): |
| 48 | + await client.tokens.create() |
| 49 | + |
| 50 | + |
| 51 | +@pytest.mark.asyncio |
| 52 | +async def test_create_token_403_error() -> None: |
| 53 | + """Handles 403 error.""" |
| 54 | + client = DecartClient(api_key="test-api-key") |
| 55 | + |
| 56 | + mock_response = AsyncMock() |
| 57 | + mock_response.ok = False |
| 58 | + mock_response.status = 403 |
| 59 | + mock_response.text = AsyncMock(return_value="Cannot create token from client token") |
| 60 | + |
| 61 | + mock_session = MagicMock() |
| 62 | + mock_session.post = MagicMock( |
| 63 | + return_value=AsyncMock(__aenter__=AsyncMock(return_value=mock_response)) |
| 64 | + ) |
| 65 | + |
| 66 | + with patch.object(client, "_get_session", AsyncMock(return_value=mock_session)): |
| 67 | + with pytest.raises(TokenCreateError, match="Failed to create token"): |
| 68 | + await client.tokens.create() |
0 commit comments