352 lines
11 KiB
Python
352 lines
11 KiB
Python
# test_api_client.py
|
|
"""
|
|
Tests for APIClient using aioresponses for HTTP mocking.
|
|
No real network requests — all tests are fast and deterministic.
|
|
"""
|
|
|
|
import asyncio
|
|
import re
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
from aiohttp import ClientError, ClientResponseError
|
|
from aioresponses import aioresponses
|
|
|
|
from api_client import APIClient, MaxRetriesExceededError
|
|
|
|
|
|
@pytest.fixture
|
|
async def api_client():
|
|
"""Create client instance for testing with cleanup."""
|
|
client = APIClient(
|
|
base_url="https://api.test.com",
|
|
max_retries=3,
|
|
rate_limit=10,
|
|
base_delay=0.01, # Fast for tests
|
|
)
|
|
yield client
|
|
# Cleanup: close session after each test
|
|
await client.close()
|
|
|
|
|
|
# ==================== URL validation tests ====================
|
|
|
|
def test_valid_url_with_https():
|
|
"""Test that valid HTTPS URL is accepted."""
|
|
client = APIClient("https://api.example.com")
|
|
assert client.base_url == "https://api.example.com"
|
|
|
|
|
|
def test_valid_url_with_http():
|
|
"""Test that valid HTTP URL is accepted."""
|
|
client = APIClient("http://api.example.com")
|
|
assert client.base_url == "http://api.example.com"
|
|
|
|
|
|
def test_trailing_slash_is_stripped():
|
|
"""Test that trailing slash is stripped from base_url."""
|
|
client = APIClient("https://api.example.com/")
|
|
assert client.base_url == "https://api.example.com"
|
|
|
|
|
|
def test_invalid_url_scheme_raises_error():
|
|
"""Test that non-http/https schemes raise ValueError."""
|
|
with pytest.raises(ValueError) as exc:
|
|
APIClient("ftp://api.example.com")
|
|
|
|
assert "Invalid URL scheme" in str(exc.value)
|
|
assert "ftp" in str(exc.value)
|
|
|
|
|
|
def test_invalid_url_scheme_javascript_raises_error():
|
|
"""Test that javascript: URL raises ValueError (security)."""
|
|
with pytest.raises(ValueError) as exc:
|
|
APIClient("javascript:alert(1)")
|
|
|
|
assert "Invalid URL scheme" in str(exc.value)
|
|
|
|
|
|
def test_invalid_url_no_hostname_raises_error():
|
|
"""Test that URL without hostname raises ValueError."""
|
|
with pytest.raises(ValueError) as exc:
|
|
APIClient("not-a-url")
|
|
|
|
assert "Invalid URL" in str(exc.value)
|
|
|
|
|
|
def test_invalid_url_empty_netloc_raises_error():
|
|
"""Test that URL with empty netloc raises ValueError."""
|
|
with pytest.raises(ValueError) as exc:
|
|
APIClient("https://")
|
|
|
|
assert "Invalid URL" in str(exc.value)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_successful_get_request(api_client):
|
|
"""Test successful GET request returns JSON."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/users/1", payload={"id": 1, "name": "Test"})
|
|
|
|
result = await api_client.get("/users/1")
|
|
|
|
assert result == {"id": 1, "name": "Test"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_successful_post_request(api_client):
|
|
"""Test successful POST request."""
|
|
with aioresponses() as m:
|
|
m.post(
|
|
"https://api.test.com/users",
|
|
payload={"id": 2, "created": True},
|
|
status=201,
|
|
)
|
|
|
|
result = await api_client.post("/users", json={"name": "New"})
|
|
|
|
assert result == {"id": 2, "created": True}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_on_500(api_client):
|
|
"""Test retry mechanism on 500 server error."""
|
|
with aioresponses() as m:
|
|
# First 2 requests fail with 500, third succeeds
|
|
m.get("https://api.test.com/flaky", status=500)
|
|
m.get("https://api.test.com/flaky", status=500)
|
|
m.get("https://api.test.com/flaky", payload={"success": True})
|
|
|
|
result = await api_client.get("/flaky")
|
|
|
|
assert result == {"success": True}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_on_429_rate_limit(api_client):
|
|
"""Test retry mechanism on 429 rate limit."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/throttled", status=429, headers={"Retry-After": "1"})
|
|
m.get("https://api.test.com/throttled", payload={"ok": True})
|
|
|
|
result = await api_client.get("/throttled")
|
|
|
|
assert result == {"ok": True}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_on_network_timeout(api_client):
|
|
"""Test retry on asyncio.TimeoutError (network timeout)."""
|
|
with aioresponses() as m:
|
|
# First call times out, second succeeds
|
|
m.get("https://api.test.com/slow", timeout=True)
|
|
m.get("https://api.test.com/slow", payload={"data": "value"})
|
|
|
|
result = await api_client.get("/slow")
|
|
|
|
assert result == {"data": "value"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_retry_on_connection_error(api_client):
|
|
"""Test retry on aiohttp.ClientError."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/unstable", exception=ClientError("Connection lost"))
|
|
m.get("https://api.test.com/unstable", payload={"recovered": True})
|
|
|
|
result = await api_client.get("/unstable")
|
|
|
|
assert result == {"recovered": True}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_max_retries_exceeded(api_client):
|
|
"""Test that MaxRetriesExceededError is raised after all retries fail."""
|
|
with aioresponses() as m:
|
|
# All requests fail with 500
|
|
for _ in range(10): # More than max_retries
|
|
m.get("https://api.test.com/fail", status=500)
|
|
|
|
with pytest.raises(MaxRetriesExceededError):
|
|
await api_client.get("/fail")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_should_retry_on_4xx_errors():
|
|
"""Test that 4xx errors (except 429) are NOT retried."""
|
|
client = APIClient("https://api.test.com")
|
|
|
|
# 404 should not be retried
|
|
assert not client._should_retry(None, 404)
|
|
# 400 should not be retried
|
|
assert not client._should_retry(None, 400)
|
|
# 403 should not be retried
|
|
assert not client._should_retry(None, 403)
|
|
# But 429 should be retried
|
|
assert client._should_retry(None, 429)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_should_retry_on_5xx_errors():
|
|
"""Test that 5xx errors ARE retried."""
|
|
client = APIClient("https://api.test.com")
|
|
|
|
assert client._should_retry(None, 500)
|
|
assert client._should_retry(None, 502)
|
|
assert client._should_retry(None, 503)
|
|
assert client._should_retry(None, 504)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_should_retry_on_network_errors():
|
|
"""Test that network errors ARE retried."""
|
|
import asyncio
|
|
from aiohttp import ClientError
|
|
|
|
client = APIClient("https://api.test.com")
|
|
|
|
assert client._should_retry(asyncio.TimeoutError(), None)
|
|
assert client._should_retry(ClientError(), None)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_rate_limiting(api_client):
|
|
"""Test that rate limiter restricts concurrent requests."""
|
|
with aioresponses() as m:
|
|
# Set up responses
|
|
for i in range(5):
|
|
m.get(f"https://api.test.com/item/{i}", payload={"id": i})
|
|
|
|
# Make 5 concurrent requests
|
|
tasks = [api_client.get(f"/item/{i}") for i in range(5)]
|
|
results = await asyncio.gather(*tasks)
|
|
|
|
assert len(results) == 5
|
|
assert [r["id"] for r in results] == [0, 1, 2, 3, 4]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_session_reuse(api_client):
|
|
"""Test that session is reused across requests."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/first", payload={"ok": True})
|
|
m.get("https://api.test.com/second", payload={"ok": True})
|
|
|
|
await api_client.get("/first")
|
|
session1 = api_client._session
|
|
|
|
await api_client.get("/second")
|
|
session2 = api_client._session
|
|
|
|
# Same session instance
|
|
assert session1 is session2
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_context_manager():
|
|
"""Test that context manager closes session."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/test", payload={"ok": True})
|
|
|
|
async with APIClient("https://api.test.com") as client:
|
|
result = await client.get("/test")
|
|
assert result == {"ok": True}
|
|
# Session is open
|
|
assert not client._session.closed
|
|
|
|
# Session is closed after context exit
|
|
assert client._session.closed
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_put_and_delete_methods():
|
|
"""Test PUT and DELETE HTTP methods."""
|
|
with aioresponses() as m:
|
|
m.put("https://api.test.com/items/1", payload={"updated": True})
|
|
m.delete("https://api.test.com/items/1", status=204)
|
|
|
|
client = APIClient("https://api.test.com")
|
|
|
|
put_result = await client.put("/items/1", json={"name": "Updated"})
|
|
assert put_result == {"updated": True}
|
|
|
|
# DELETE with 204 returns no content (json() would fail)
|
|
m.delete("https://api.test.com/items/2", payload={"deleted": True}, status=200)
|
|
delete_result = await client.delete("/items/2")
|
|
assert delete_result == {"deleted": True}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_base_url_trailing_slash():
|
|
"""Test that trailing slash in base_url is handled correctly."""
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/test", payload={"ok": True})
|
|
|
|
# Trailing slash should be stripped
|
|
client = APIClient("https://api.test.com/")
|
|
result = await client.get("/test")
|
|
|
|
assert result == {"ok": True}
|
|
|
|
|
|
# ==================== Parameterized tests for retryable statuses ====================
|
|
|
|
@pytest.mark.parametrize("status", [429, 500, 502, 503, 504])
|
|
@pytest.mark.asyncio
|
|
async def test_retryable_status_codes(api_client, status):
|
|
"""Test that all specified status codes are retried."""
|
|
with aioresponses() as m:
|
|
# First call fails with retryable status, second succeeds
|
|
m.get("https://api.test.com/retry", status=status)
|
|
m.get("https://api.test.com/retry", payload={"success": True})
|
|
|
|
result = await api_client.get("/retry")
|
|
|
|
# Success means retry worked (first response was error, second was success)
|
|
assert result == {"success": True}
|
|
|
|
|
|
# ==================== Edge cases ====================
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_exponential_backoff_increases_delay():
|
|
"""Test that backoff delay increases with each retry attempt."""
|
|
client = APIClient("https://api.test.com", base_delay=0.1, max_delay=10.0)
|
|
|
|
delays = [client._calculate_delay(i) for i in range(5)]
|
|
|
|
# Delays should generally increase (not strict due to jitter)
|
|
# But max delay should be bounded
|
|
assert all(d <= client.max_delay for d in delays)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_empty_response_body(api_client):
|
|
"""Test handling of responses with empty body."""
|
|
with aioresponses() as m:
|
|
# 204 No Content typically has no body
|
|
m.get("https://api.test.com/empty", status=204, body="")
|
|
|
|
|
|
# ==================== Logging tests ====================
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_logging_on_success(api_client, caplog):
|
|
"""Test that successful requests are logged."""
|
|
import logging
|
|
caplog.set_level(logging.INFO)
|
|
|
|
with aioresponses() as m:
|
|
m.get("https://api.test.com/test", payload={"ok": True})
|
|
|
|
await api_client.get("/test")
|
|
|
|
# Check for success log
|
|
assert any("Success" in record.message for record in caplog.records)
|
|
|
|
|
|
# ==================== Configuration ====================
|
|
|
|
# Run tests with: pytest test_api_client.py -v
|
|
# Run with coverage: pytest test_api_client.py --cov=api_client --cov-report=html
|