Spaces:
Running
Running
File size: 2,671 Bytes
943334e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | 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
|