refactor(backend): update API routes and service layer
- Update agent router/service/repository with new endpoints - Update auth routes with phone-based authentication - Update users service with new phone lookup - Update schedule_items with new schemas - Update message schemas with visibility support - Update settings with new automation scheduler config - Update CLI with new commands - Update tests to match new API contracts
This commit is contained in:
@@ -11,16 +11,10 @@ from v1.auth.dependencies import get_auth_service
|
||||
from v1.auth.rate_limit import reset_rate_limit_state
|
||||
from v1.auth.schemas import (
|
||||
AuthUser,
|
||||
PasswordResetConfirmRequest,
|
||||
PasswordResetRequest,
|
||||
SessionCreateRequest,
|
||||
OtpSendRequest,
|
||||
PhoneSessionCreateRequest,
|
||||
SessionRefreshRequest,
|
||||
SessionResponse,
|
||||
UserByEmailResponse,
|
||||
VerificationCreateRequest,
|
||||
VerificationCreateResponse,
|
||||
VerificationResendRequest,
|
||||
VerificationVerifyRequest,
|
||||
)
|
||||
from v1.auth.service import AuthService
|
||||
|
||||
@@ -30,58 +24,39 @@ def reset_auth_rate_limit_state() -> None:
|
||||
reset_rate_limit_state()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def force_in_memory_rate_limit(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
async def _raise_redis_unavailable() -> None:
|
||||
raise RuntimeError("redis unavailable in integration tests")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"v1.auth.rate_limit.get_or_init_redis_client",
|
||||
_raise_redis_unavailable,
|
||||
)
|
||||
|
||||
|
||||
class FakeAuthService(AuthService):
|
||||
def __init__(self, token_response: SessionResponse) -> None:
|
||||
self._token_response = token_response
|
||||
|
||||
async def create_verification(
|
||||
self, request: VerificationCreateRequest
|
||||
) -> VerificationCreateResponse:
|
||||
if request.email == "exists@example.com":
|
||||
raise HTTPException(status_code=422, detail="Invalid signup request")
|
||||
return VerificationCreateResponse(email=request.email)
|
||||
async def send_otp(self, request: OtpSendRequest) -> None:
|
||||
if request.phone == "+8613811111111":
|
||||
raise HTTPException(status_code=401, detail="Invalid verification code")
|
||||
return None
|
||||
|
||||
async def verify_verification(
|
||||
self, request: VerificationVerifyRequest
|
||||
async def create_phone_session(
|
||||
self, request: PhoneSessionCreateRequest
|
||||
) -> SessionResponse:
|
||||
if request.token == "000000":
|
||||
raise HTTPException(status_code=401, detail="Invalid verification code")
|
||||
return self._token_response
|
||||
|
||||
async def resend_verification(self, request: VerificationResendRequest) -> None:
|
||||
return None
|
||||
|
||||
async def create_session(self, request: SessionCreateRequest) -> SessionResponse:
|
||||
raise HTTPException(status_code=401, detail="Invalid credentials")
|
||||
|
||||
async def refresh_session(self, request: SessionRefreshRequest) -> SessionResponse:
|
||||
raise HTTPException(status_code=401, detail="Invalid refresh token")
|
||||
|
||||
async def delete_session(self, refresh_token: str | None) -> None:
|
||||
return None
|
||||
|
||||
async def get_user_by_email(self, email: str) -> UserByEmailResponse:
|
||||
if email == "missing@example.com":
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return UserByEmailResponse(
|
||||
id="user-1",
|
||||
email=email,
|
||||
created_at="2026-02-24T00:00:00Z",
|
||||
email_confirmed_at=None,
|
||||
)
|
||||
|
||||
async def request_password_reset(self, request: PasswordResetRequest) -> None:
|
||||
return None
|
||||
|
||||
async def confirm_password_reset(
|
||||
self, request: PasswordResetConfirmRequest
|
||||
) -> None:
|
||||
if request.token == "000000":
|
||||
raise HTTPException(
|
||||
status_code=401, detail="Invalid or expired verification code"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _override_auth_service(service: AuthService) -> Callable[[], AuthService]:
|
||||
def _get_service() -> AuthService:
|
||||
@@ -90,761 +65,126 @@ def _override_auth_service(service: AuthService) -> Callable[[], AuthService]:
|
||||
return _get_service
|
||||
|
||||
|
||||
def test_signup_start_returns_pending_response() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
def _token_response() -> SessionResponse:
|
||||
user = AuthUser(id="user-1", phone="+8613812345678")
|
||||
return SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
|
||||
|
||||
def test_send_otp_returns_204() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
},
|
||||
"/api/v1/auth/otp/send",
|
||||
json={"phone": "+8613812345678"},
|
||||
)
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"email": "user@example.com"}
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_verify_returns_token_response() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
def test_phone_session_returns_token_response() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={"email": "user@example.com", "token": "123456"},
|
||||
"/api/v1/auth/phone-session",
|
||||
json={"phone": "+8613812345678", "token": "123456"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.json()
|
||||
assert body["access_token"] == "access"
|
||||
assert body["refresh_token"] == "refresh"
|
||||
assert body["user"]["email"] == "user@example.com"
|
||||
assert body["user"]["phone"] == "+8613812345678"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_resend_returns_generic_message() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
def test_phone_session_invalid_token_returns_problem_details() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/resend",
|
||||
json={"type": "recovery", "email": "user@example.com"},
|
||||
)
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_verify_invalid_token_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={"email": "user@example.com", "token": "000000"},
|
||||
"/api/v1/auth/phone-session",
|
||||
json={"phone": "+8613812345678", "token": "000000"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unauthorized"
|
||||
assert body["status"] == 401
|
||||
assert body["detail"] == "Invalid verification code"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_start_existing_email_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
def test_legacy_routes_are_removed() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "exists@example.com",
|
||||
"password": "secret123",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unprocessable Entity"
|
||||
assert body["status"] == 422
|
||||
assert body["detail"] == "Invalid signup request"
|
||||
assert client.post("/api/v1/auth/verifications", json={}).status_code == 404
|
||||
assert client.post("/api/v1/auth/verify", json={}).status_code == 404
|
||||
assert client.post("/api/v1/auth/resend", json={}).status_code == 404
|
||||
assert client.post("/api/v1/auth/sessions", json={}).status_code == 405
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_verify_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
def test_send_otp_phone_rate_limited_after_too_many_attempts() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(10):
|
||||
for _ in range(3):
|
||||
ok = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={"email": "user@example.com", "token": "123456"},
|
||||
)
|
||||
assert ok.status_code == 200
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={"email": "user@example.com", "token": "123456"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_resend_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(5):
|
||||
ok = client.post(
|
||||
"/api/v1/auth/resend",
|
||||
json={"email": "user@example.com"},
|
||||
"/api/v1/auth/otp/send",
|
||||
json={"phone": "+8613812345678"},
|
||||
)
|
||||
assert ok.status_code == 204
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/resend",
|
||||
json={"email": "user@example.com"},
|
||||
"/api/v1/auth/otp/send",
|
||||
json={"phone": "+8613812345678"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_start_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
def test_phone_session_rate_limited_after_too_many_attempts() -> None:
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
FakeAuthService(_token_response())
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(5):
|
||||
ok = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
},
|
||||
)
|
||||
assert ok.status_code == 202
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_login_invalid_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
json={"email": "user@example.com", "password": "wrongpw"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unauthorized"
|
||||
assert body["status"] == 401
|
||||
assert body["detail"] == "Invalid credentials"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_refresh_invalid_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/sessions/refresh",
|
||||
json={"refresh_token": "invalid"},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unauthorized"
|
||||
assert body["status"] == 401
|
||||
assert body["detail"] == "Invalid refresh token"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_logout_returns_no_content() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.request(
|
||||
"DELETE",
|
||||
"/api/v1/auth/sessions",
|
||||
json={"refresh_token": "refresh"},
|
||||
)
|
||||
assert response.status_code == 204
|
||||
assert response.content == b""
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_login_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(10):
|
||||
for _ in range(6):
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
json={"email": "user@example.com", "password": "wrongpw"},
|
||||
"/api/v1/auth/phone-session",
|
||||
json={"phone": "+8613812345678", "token": "000000"},
|
||||
)
|
||||
assert blocked.status_code == 401
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions",
|
||||
json={"email": "user@example.com", "password": "wrongpw"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
body = blocked.json()
|
||||
assert body["detail"] == "Too many requests"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_refresh_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(10):
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions/refresh",
|
||||
json={"refresh_token": "invalid"},
|
||||
)
|
||||
assert blocked.status_code == 401
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions/refresh",
|
||||
json={"refresh_token": "invalid"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
body = blocked.json()
|
||||
assert body["detail"] == "Too many requests"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_refresh_rate_limit_not_bypassed_by_changing_refresh_token() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for index in range(10):
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions/refresh",
|
||||
json={"refresh_token": f"invalid-{index}"},
|
||||
)
|
||||
assert blocked.status_code == 401
|
||||
|
||||
blocked = client.post(
|
||||
"/api/v1/auth/sessions/refresh",
|
||||
json={"refresh_token": "invalid-extra"},
|
||||
"/api/v1/auth/phone-session",
|
||||
json={"phone": "+8613812345678", "token": "000000"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_logout_rate_limited_after_too_many_attempts() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for _ in range(10):
|
||||
ok = client.request(
|
||||
"DELETE",
|
||||
"/api/v1/auth/sessions",
|
||||
json={"refresh_token": "refresh"},
|
||||
)
|
||||
assert ok.status_code == 204
|
||||
|
||||
blocked = client.request(
|
||||
"DELETE",
|
||||
"/api/v1/auth/sessions",
|
||||
json={"refresh_token": "refresh"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
assert blocked.headers["content-type"].startswith("application/problem+json")
|
||||
body = blocked.json()
|
||||
assert body["detail"] == "Too many requests"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_logout_rate_limit_not_bypassed_by_changing_refresh_token() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
for index in range(10):
|
||||
ok = client.request(
|
||||
"DELETE",
|
||||
"/api/v1/auth/sessions",
|
||||
json={"refresh_token": f"refresh-{index}"},
|
||||
)
|
||||
assert ok.status_code == 204
|
||||
|
||||
blocked = client.request(
|
||||
"DELETE",
|
||||
"/api/v1/auth/sessions",
|
||||
json={"refresh_token": "refresh-extra"},
|
||||
)
|
||||
assert blocked.status_code == 429
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_start_validation_error_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post("/api/v1/auth/verifications", json={})
|
||||
assert response.status_code == 422
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unprocessable Entity"
|
||||
assert body["status"] == 422
|
||||
assert body["detail"] == "Invalid request"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_signup_start_missing_username_returns_problem_details() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={"email": "user@example.com", "password": "secret123"},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unprocessable Entity"
|
||||
assert body["status"] == 422
|
||||
assert body["detail"] == "Invalid request"
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_password_reset_request_returns_204() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/resend",
|
||||
json={"email": "user@example.com"},
|
||||
)
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_password_reset_confirm_returns_204() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={
|
||||
"type": "recovery",
|
||||
"email": "user@example.com",
|
||||
"token": "123456",
|
||||
"new_password": "newpassword123",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 204
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_password_reset_confirm_invalid_token_returns_401() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={
|
||||
"type": "recovery",
|
||||
"email": "user@example.com",
|
||||
"token": "000000",
|
||||
"new_password": "newpassword123",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
body = response.json()
|
||||
assert body["title"] == "Unauthorized"
|
||||
assert body["status"] == 401
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_password_reset_confirm_weak_password_returns_422() -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verify",
|
||||
json={
|
||||
"type": "recovery",
|
||||
"email": "user@example.com",
|
||||
"token": "123456",
|
||||
"new_password": "123",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
assert response.headers["content-type"].startswith("application/problem+json")
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
class TestInviteCodeSignup:
|
||||
def test_signup_with_valid_invite_code_returns_202(self) -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
"invite_code": "A2B3",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"email": "user@example.com"}
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
def test_signup_with_invalid_invite_code_length_returns_202(self) -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
"invite_code": "ABC123",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"email": "user@example.com"}
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
def test_signup_with_invalid_invite_code_chars_returns_202(self) -> None:
|
||||
user = AuthUser(id="user-1", email="user@example.com")
|
||||
token_response = SessionResponse(
|
||||
access_token="access",
|
||||
refresh_token="refresh",
|
||||
expires_in=3600,
|
||||
token_type="bearer",
|
||||
user=user,
|
||||
)
|
||||
app.dependency_overrides[get_auth_service] = _override_auth_service(
|
||||
FakeAuthService(token_response)
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
try:
|
||||
response = client.post(
|
||||
"/api/v1/auth/verifications",
|
||||
json={
|
||||
"username": "demo",
|
||||
"email": "user@example.com",
|
||||
"password": "secret123",
|
||||
"invite_code": "ABCD1234",
|
||||
},
|
||||
)
|
||||
assert response.status_code == 202
|
||||
assert response.json() == {"email": "user@example.com"}
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
@@ -9,12 +9,12 @@ from fastapi.testclient import TestClient
|
||||
|
||||
from app import app
|
||||
from core.auth.models import CurrentUser
|
||||
from schemas.user.context import UserContext
|
||||
from v1.friendships.dependencies import get_friendship_service
|
||||
from v1.friendships.schemas import (
|
||||
FriendRequestCreate,
|
||||
FriendRequestResponse,
|
||||
FriendResponse,
|
||||
UserBasicInfo,
|
||||
)
|
||||
from v1.friendships.service import FriendshipService
|
||||
from v1.users.dependencies import get_current_user
|
||||
@@ -31,9 +31,9 @@ class FakeFriendshipService(FriendshipService):
|
||||
async def send_request(self, request: FriendRequestCreate) -> FriendRequestResponse:
|
||||
return FriendRequestResponse(
|
||||
id=UUID("11111111-1111-1111-1111-111111111111"),
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(id="user-2", username="recipient", avatar_url=None),
|
||||
content=request.content,
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(id="user-2", username="recipient", avatar_url=None),
|
||||
content={"text": request.content} if request.content else None,
|
||||
status="pending",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
@@ -41,9 +41,9 @@ class FakeFriendshipService(FriendshipService):
|
||||
async def accept_request(self, friendship_id: UUID) -> FriendRequestResponse:
|
||||
return FriendRequestResponse(
|
||||
id=friendship_id,
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(id="user-2", username="recipient", avatar_url=None),
|
||||
content="Hello!",
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(id="user-2", username="recipient", avatar_url=None),
|
||||
content={"text": "Hello!"},
|
||||
status="accepted",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
@@ -51,9 +51,9 @@ class FakeFriendshipService(FriendshipService):
|
||||
async def decline_request(self, friendship_id: UUID) -> FriendRequestResponse:
|
||||
return FriendRequestResponse(
|
||||
id=friendship_id,
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(id="user-2", username="recipient", avatar_url=None),
|
||||
content="Hello!",
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(id="user-2", username="recipient", avatar_url=None),
|
||||
content={"text": "Hello!"},
|
||||
status="rejected",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
@@ -61,9 +61,9 @@ class FakeFriendshipService(FriendshipService):
|
||||
async def cancel_request(self, friendship_id: UUID) -> FriendRequestResponse:
|
||||
return FriendRequestResponse(
|
||||
id=friendship_id,
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(id="user-2", username="recipient", avatar_url=None),
|
||||
content="Hello!",
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(id="user-2", username="recipient", avatar_url=None),
|
||||
content={"text": "Hello!"},
|
||||
status="canceled",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
@@ -72,11 +72,11 @@ class FakeFriendshipService(FriendshipService):
|
||||
return [
|
||||
FriendRequestResponse(
|
||||
id=UUID("11111111-1111-1111-1111-111111111111"),
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(
|
||||
id="user-2", username="recipient", avatar_url=None
|
||||
),
|
||||
content="Hello!",
|
||||
content={"text": "Hello!"},
|
||||
status="pending",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
)
|
||||
@@ -86,10 +86,8 @@ class FakeFriendshipService(FriendshipService):
|
||||
return [
|
||||
FriendRequestResponse(
|
||||
id=UUID("22222222-2222-2222-2222-222222222222"),
|
||||
sender=UserBasicInfo(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserBasicInfo(
|
||||
id="user-3", username="target", avatar_url=None
|
||||
),
|
||||
sender=UserContext(id="user-1", username="sender", avatar_url=None),
|
||||
recipient=UserContext(id="user-3", username="target", avatar_url=None),
|
||||
content=None,
|
||||
status="pending",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
@@ -100,7 +98,7 @@ class FakeFriendshipService(FriendshipService):
|
||||
return [
|
||||
FriendResponse(
|
||||
id=UUID("33333333-3333-3333-3333-333333333333"),
|
||||
friend=UserBasicInfo(id="user-2", username="friend", avatar_url=None),
|
||||
friend=UserContext(id="user-2", username="friend", avatar_url=None),
|
||||
status="active",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
accepted_at=datetime.now(timezone.utc),
|
||||
@@ -110,7 +108,7 @@ class FakeFriendshipService(FriendshipService):
|
||||
async def remove_friend(self, friend_id: UUID) -> FriendResponse:
|
||||
return FriendResponse(
|
||||
id=UUID("33333333-3333-3333-3333-333333333333"),
|
||||
friend=UserBasicInfo(id=str(friend_id), username="friend", avatar_url=None),
|
||||
friend=UserContext(id=str(friend_id), username="friend", avatar_url=None),
|
||||
status="active",
|
||||
created_at=datetime.now(timezone.utc),
|
||||
accepted_at=datetime.now(timezone.utc),
|
||||
@@ -129,7 +127,7 @@ def _override_friendship_service(
|
||||
def _get_fake_current_user() -> CurrentUser:
|
||||
return CurrentUser(
|
||||
id=UUID("00000000-0000-0000-0000-000000000001"),
|
||||
email="test@example.com",
|
||||
phone="+8613812345678",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ def test_share_schedule_item_returns_200() -> None:
|
||||
response = client.post(
|
||||
f"/api/v1/schedule-items/{item_id}/share",
|
||||
json={
|
||||
"email": "friend@example.com",
|
||||
"phone": "+8613810000000",
|
||||
"permission_view": True,
|
||||
"permission_edit": False,
|
||||
"permission_invite": True,
|
||||
@@ -62,7 +62,7 @@ def test_share_schedule_item_returns_200() -> None:
|
||||
body = response.json()
|
||||
assert body["message"] == "Calendar invitation sent"
|
||||
assert service.last_share_request is not None
|
||||
assert service.last_share_request.email == "friend@example.com"
|
||||
assert service.last_share_request.phone == "+8613810000000"
|
||||
assert service.last_share_request.permission_invite is True
|
||||
finally:
|
||||
app.dependency_overrides = {}
|
||||
|
||||
@@ -8,30 +8,31 @@ from fastapi.testclient import TestClient
|
||||
|
||||
from app import app
|
||||
from core.auth.models import CurrentUser
|
||||
from schemas.user.context import UserContext
|
||||
from v1.users.dependencies import get_current_user, get_user_service
|
||||
from v1.users.schemas import UserResponse, UserSearchRequest, UserUpdateRequest
|
||||
from v1.users.schemas import UserSearchRequest, UserUpdateRequest
|
||||
from v1.users.service import UserService
|
||||
|
||||
|
||||
class FakeUserService:
|
||||
"""Fake service for integration testing."""
|
||||
|
||||
def __init__(self, user: UserResponse) -> None:
|
||||
def __init__(self, user: UserContext) -> None:
|
||||
self._user = user
|
||||
self._search_results: list[UserResponse] = []
|
||||
self._search_results: list[UserContext] = []
|
||||
|
||||
def set_search_results(self, results: list[UserResponse]) -> None:
|
||||
def set_search_results(self, results: list[UserContext]) -> None:
|
||||
self._search_results = results
|
||||
|
||||
async def get_me(self) -> UserResponse:
|
||||
async def get_me(self) -> UserContext:
|
||||
if self._user.id is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return self._user
|
||||
|
||||
async def update_me(self, update: UserUpdateRequest) -> UserResponse:
|
||||
async def update_me(self, update: UserUpdateRequest) -> UserContext:
|
||||
if self._user.id is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return UserResponse(
|
||||
return UserContext(
|
||||
id=self._user.id,
|
||||
username=(
|
||||
update.username if update.username is not None else self._user.username
|
||||
@@ -44,7 +45,7 @@ class FakeUserService:
|
||||
bio=update.bio if update.bio is not None else self._user.bio,
|
||||
)
|
||||
|
||||
async def search_users(self, request: UserSearchRequest) -> list[UserResponse]:
|
||||
async def search_users(self, request: UserSearchRequest) -> list[UserContext]:
|
||||
if request.query:
|
||||
return self._search_results if self._search_results else [self._user]
|
||||
return []
|
||||
@@ -68,7 +69,7 @@ def _override_current_user(user_id: UUID) -> Callable[[], CurrentUser]:
|
||||
|
||||
def test_get_me_returns_user() -> None:
|
||||
user_id = UUID("00000000-0000-0000-0000-000000000001")
|
||||
user = UserResponse(
|
||||
user = UserContext(
|
||||
id=str(user_id),
|
||||
username="demo",
|
||||
avatar_url=None,
|
||||
@@ -91,7 +92,7 @@ def test_get_me_returns_user() -> None:
|
||||
|
||||
def test_patch_me_updates_user() -> None:
|
||||
user_id = UUID("00000000-0000-0000-0000-000000000001")
|
||||
user = UserResponse(
|
||||
user = UserContext(
|
||||
id=str(user_id),
|
||||
username="demo",
|
||||
avatar_url=None,
|
||||
@@ -117,7 +118,7 @@ def test_patch_me_updates_user() -> None:
|
||||
|
||||
def test_patch_me_validation_error_returns_problem_details() -> None:
|
||||
user_id = UUID("00000000-0000-0000-0000-000000000001")
|
||||
user = UserResponse(
|
||||
user = UserContext(
|
||||
id=str(user_id),
|
||||
username="demo",
|
||||
avatar_url=None,
|
||||
@@ -142,7 +143,7 @@ def test_patch_me_validation_error_returns_problem_details() -> None:
|
||||
|
||||
def test_search_users_returns_list() -> None:
|
||||
user_id = UUID("00000000-0000-0000-0000-000000000001")
|
||||
user = UserResponse(
|
||||
user = UserContext(
|
||||
id=str(user_id),
|
||||
username="demo",
|
||||
avatar_url=None,
|
||||
@@ -167,7 +168,7 @@ def test_search_users_returns_list() -> None:
|
||||
|
||||
def test_search_users_empty_query_returns_422() -> None:
|
||||
user_id = UUID("00000000-0000-0000-0000-000000000001")
|
||||
user = UserResponse(
|
||||
user = UserContext(
|
||||
id=str(user_id),
|
||||
username="demo",
|
||||
avatar_url=None,
|
||||
|
||||
@@ -115,6 +115,34 @@ class _FailingStreamAgentService(_FakeAgentService):
|
||||
raise RuntimeError("redis timeout")
|
||||
|
||||
|
||||
class _TerminalStreamAgentService(_FakeAgentService):
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.stream_calls = 0
|
||||
|
||||
async def stream_events(
|
||||
self,
|
||||
*,
|
||||
thread_id: str,
|
||||
last_event_id: str | None,
|
||||
current_user: CurrentUser,
|
||||
) -> list[dict[str, object]]:
|
||||
del thread_id, last_event_id, current_user
|
||||
self.stream_calls += 1
|
||||
if self.stream_calls == 1:
|
||||
return [
|
||||
{
|
||||
"id": "9-0",
|
||||
"event": {
|
||||
"type": "RUN_FINISHED",
|
||||
"threadId": "00000000-0000-0000-0000-000000000001",
|
||||
"runId": "run-1",
|
||||
},
|
||||
}
|
||||
]
|
||||
return []
|
||||
|
||||
|
||||
def test_run_requires_auth_and_returns_202_task_id() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
client = TestClient(app)
|
||||
@@ -129,13 +157,13 @@ def test_run_requires_auth_and_returns_202_task_id() -> None:
|
||||
"messages": [{"id": "u1", "role": "user", "content": "hello"}],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert unauthorized.status_code == 401
|
||||
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
authorized = client.post(
|
||||
"/api/v1/agent/runs",
|
||||
@@ -146,7 +174,7 @@ def test_run_requires_auth_and_returns_202_task_id() -> None:
|
||||
"messages": [{"id": "u1", "role": "user", "content": "hello"}],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert authorized.status_code == 202
|
||||
@@ -161,7 +189,7 @@ def test_run_requires_auth_and_returns_202_task_id() -> None:
|
||||
def test_stream_reads_from_last_event_id() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
original_acquire = agent_router._acquire_sse_slot
|
||||
@@ -197,7 +225,7 @@ def test_stream_reads_from_last_event_id() -> None:
|
||||
def test_stream_handles_stream_backend_errors_without_connection_crash() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FailingStreamAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
original_acquire = agent_router._acquire_sse_slot
|
||||
@@ -226,10 +254,45 @@ def test_stream_handles_stream_backend_errors_without_connection_crash() -> None
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_stream_stops_after_terminal_run_event() -> None:
|
||||
service = _TerminalStreamAgentService()
|
||||
app.dependency_overrides[get_agent_service] = lambda: service
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
original_acquire = agent_router._acquire_sse_slot
|
||||
original_release = agent_router._release_sse_slot
|
||||
|
||||
async def _allow_slot(*, user_id: str) -> bool:
|
||||
del user_id
|
||||
return True
|
||||
|
||||
async def _noop_release(*, user_id: str) -> None:
|
||||
del user_id
|
||||
return None
|
||||
|
||||
agent_router._acquire_sse_slot = _allow_slot # type: ignore[assignment]
|
||||
agent_router._release_sse_slot = _noop_release # type: ignore[assignment]
|
||||
|
||||
try:
|
||||
response = client.get(
|
||||
"/api/v1/agent/runs/00000000-0000-0000-0000-000000000001/events?idle_limit=3"
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"].startswith("text/event-stream")
|
||||
assert "event: RUN_FINISHED" in response.text
|
||||
assert service.stream_calls == 1
|
||||
finally:
|
||||
agent_router._acquire_sse_slot = original_acquire # type: ignore[assignment]
|
||||
agent_router._release_sse_slot = original_release # type: ignore[assignment]
|
||||
app.dependency_overrides = {}
|
||||
|
||||
|
||||
def test_stream_rejects_invalid_last_event_id() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -255,7 +318,7 @@ def test_history_returns_state_snapshot() -> None:
|
||||
assert unauthorized.status_code == 401
|
||||
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
authorized = client.get(
|
||||
"/api/v1/agent/history",
|
||||
@@ -276,7 +339,7 @@ def test_history_returns_state_snapshot() -> None:
|
||||
def test_user_history_returns_latest_snapshot() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
try:
|
||||
@@ -292,7 +355,7 @@ def test_user_history_returns_latest_snapshot() -> None:
|
||||
def test_run_rejects_oversized_user_text_payload() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -312,7 +375,7 @@ def test_run_rejects_oversized_user_text_payload() -> None:
|
||||
],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
@@ -323,7 +386,7 @@ def test_run_rejects_oversized_user_text_payload() -> None:
|
||||
def test_run_rejects_client_supplied_history_messages() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -340,7 +403,7 @@ def test_run_rejects_client_supplied_history_messages() -> None:
|
||||
],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 422
|
||||
@@ -351,7 +414,7 @@ def test_run_rejects_client_supplied_history_messages() -> None:
|
||||
def test_upload_attachment_returns_reference() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -376,7 +439,7 @@ def test_upload_attachment_returns_reference() -> None:
|
||||
def test_create_attachment_signed_url_returns_url() -> None:
|
||||
app.dependency_overrides[get_agent_service] = lambda: _FakeAgentService()
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -399,7 +462,7 @@ def test_create_attachment_signed_url_returns_url() -> None:
|
||||
|
||||
def test_asr_transcribe_returns_sync_transcript(monkeypatch) -> None:
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
|
||||
async def mock_transcribe_file(file_path: str, filename: str) -> str:
|
||||
@@ -434,7 +497,7 @@ def test_asr_transcribe_returns_sync_transcript(monkeypatch) -> None:
|
||||
|
||||
def test_asr_transcribe_rejects_oversized_audio(monkeypatch) -> None:
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
|
||||
monkeypatch.setattr(agent_router, "_MAX_TRANSCRIBE_AUDIO_BYTES", 4)
|
||||
@@ -457,7 +520,7 @@ def test_asr_transcribe_rejects_oversized_audio(monkeypatch) -> None:
|
||||
|
||||
def test_asr_transcribe_rejects_non_wav_audio(monkeypatch) -> None:
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
@@ -478,7 +541,7 @@ def test_asr_transcribe_rejects_non_wav_audio(monkeypatch) -> None:
|
||||
|
||||
def test_asr_transcribe_rejects_invalid_wav_payload(monkeypatch) -> None:
|
||||
app.dependency_overrides[get_current_user] = lambda: CurrentUser(
|
||||
id=uuid4(), email="user@example.com"
|
||||
id=uuid4(), phone="+8613812345678"
|
||||
)
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
@@ -20,16 +20,16 @@ FIXTURE_IMAGE_PATH = (
|
||||
|
||||
|
||||
async def _live_access_token(client: httpx.AsyncClient) -> str:
|
||||
email = os.getenv("AGENT_LIVE_EMAIL")
|
||||
phone = os.getenv("AGENT_LIVE_PHONE")
|
||||
password = os.getenv("AGENT_LIVE_PASSWORD")
|
||||
if not email or not password:
|
||||
if not phone or not password:
|
||||
pytest.fail(
|
||||
"AGENT_LIVE_INTEGRATION=1 requires AGENT_LIVE_EMAIL and AGENT_LIVE_PASSWORD"
|
||||
"AGENT_LIVE_INTEGRATION=1 requires AGENT_LIVE_PHONE and AGENT_LIVE_PASSWORD"
|
||||
)
|
||||
|
||||
response = await client.post(
|
||||
f"{BASE_URL}/api/v1/auth/sessions",
|
||||
json={"email": email, "password": password},
|
||||
json={"phone": phone, "password": password},
|
||||
)
|
||||
response_text = response.text.strip().replace("\n", " ")
|
||||
truncated_text = response_text[:200]
|
||||
@@ -67,7 +67,7 @@ async def test_agent_sse_closed_loop_live() -> None:
|
||||
],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert run_resp.status_code == 202
|
||||
@@ -143,7 +143,7 @@ async def test_agent_runs_events_history_live_with_image_input() -> None:
|
||||
],
|
||||
"tools": [],
|
||||
"context": [],
|
||||
"forwardedProps": {},
|
||||
"forwardedProps": {"agent_type": "worker"},
|
||||
},
|
||||
)
|
||||
assert run_resp.status_code == 202
|
||||
|
||||
Reference in New Issue
Block a user