from __future__ import annotations import json import httpx import pytest from fastapi import FastAPI from fastapi.testclient import TestClient from app.api import httpsms def make_app() -> FastAPI: app = FastAPI() app.include_router(httpsms.router) return app def test_sms_requires_configured_api_key(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.delenv("HTTPSMS_API_KEY", raising=False) with TestClient(make_app()) as client: response = client.post("/v1/sms/send", json={ "from": "+2348012345678", "to": "+2348098765432", "content": "test" }) assert response.status_code == 503 def test_sms_validates_e164_phone_numbers() -> None: with TestClient(make_app()) as client: response = client.post("/v1/sms/send", json={ "from": "08012345678", "to": "+2348098765432", "content": "test" }) assert response.status_code == 422 def test_sms_forwards_official_request(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("HTTPSMS_API_KEY", "test-secret") monkeypatch.setenv("HTTPSMS_API_BASE_URL", "https://api.httpsms.com") seen: dict[str, object] = {} async def handler(request: httpx.Request) -> httpx.Response: seen["url"] = str(request.url) seen["headers"] = dict(request.headers) seen["body"] = json.loads(request.content) return httpx.Response(202, json={"id": "msg-test", "status": "queued"}) original_client = httpx.AsyncClient def mock_client(**kwargs: object) -> httpx.AsyncClient: return original_client(transport=httpx.MockTransport(handler), **kwargs) monkeypatch.setattr(httpsms.httpx, "AsyncClient", mock_client) with TestClient(make_app()) as client: response = client.post("/v1/sms/send", json={ "from": "+2348012345678", "to": "+2348098765432", "content": "hello" }) assert response.status_code == 200 assert seen["url"] == "https://api.httpsms.com/v1/messages/send" assert seen["headers"]["x-api-key"] == "test-secret" assert seen["body"] == { "from": "+2348012345678", "to": "+2348098765432", "content": "hello" } assert response.json()["result"]["id"] == "msg-test" def test_sms_rejects_non_https_upstream(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("HTTPSMS_API_KEY", "test-secret") monkeypatch.setenv("HTTPSMS_API_BASE_URL", "http://127.0.0.1:8000") with TestClient(make_app()) as client: response = client.post("/v1/sms/send", json={ "from": "+2348012345678", "to": "+2348098765432", "content": "hello" }) assert response.status_code == 503