Coverage for backend / app / emails / routers / tests.py: 100%

45 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-03-17 21:34 +0000

1"""Router for testing email functionalities in test mode.""" 

2 

3import re 

4 

5from fastapi import APIRouter, HTTPException 

6 

7from app.config import settings 

8from app.emails.email_service import email_service 

9 

10email_test_router = APIRouter(prefix="/test", tags=["testing"]) 

11 

12 

13@email_test_router.get("/emails/{email_address}") 

14def get_test_emails(email_address: str) -> dict: 

15 """Get all test emails sent to a specific address.""" 

16 

17 if not settings.test_mode: 

18 raise HTTPException(status_code=403, detail="Test mode not enabled") 

19 

20 emails = email_service.get_test_emails(email_address) 

21 return {"emails": emails} 

22 

23 

24@email_test_router.get("/verification-link/{email_address}") 

25def get_verification_link(email_address: str) -> dict: 

26 """Extract verification link from the most recent email.""" 

27 

28 if not settings.test_mode: 

29 raise HTTPException(status_code=403, detail="Test mode not enabled") 

30 

31 emails = email_service.get_test_emails(email_address) 

32 if not emails: 

33 raise HTTPException(status_code=404, detail="No emails found") 

34 

35 # Get most recent email 

36 latest_email = emails[-1] 

37 

38 # Extract verification URL from HTML body 

39 base_url = re.escape(settings.frontend_url + "/") + r"[^/]+" 

40 pattern = base_url + r"/\?token=([A-Za-z0-9_\-]+)" 

41 match = re.search(pattern, latest_email["body"]) 

42 

43 if match: 

44 return {"verification_url": match.group(0)} 

45 raise HTTPException(status_code=404, detail="No verification link found") 

46 

47 

48@email_test_router.get("/reset-link/{email_address}") 

49def get_reset_link(email_address: str) -> dict: 

50 """Extract password reset link from the most recent email.""" 

51 

52 if not settings.test_mode: 

53 raise HTTPException(status_code=403, detail="Test mode not enabled") 

54 

55 emails = email_service.get_test_emails(email_address) 

56 if not emails: 

57 raise HTTPException(status_code=404, detail="No emails found") 

58 

59 latest_email = emails[-1] 

60 

61 # Extract reset URL from HTML body 

62 base_url = settings.frontend_url + "/reset-password/?token=" 

63 pattern = re.escape(base_url) + r"([A-Za-z0-9_\-]+)" # Capture the token (assuming token format) 

64 match = re.search(pattern, latest_email["body"]) 

65 

66 if match: 

67 return {"reset_url": base_url + match.group(1)} 

68 raise HTTPException(status_code=404, detail="No reset link found") 

69 

70 

71@email_test_router.delete("/emails") 

72def clear_test_emails() -> dict: 

73 """Clear all test emails.""" 

74 

75 if not settings.test_mode: 

76 raise HTTPException(status_code=403, detail="Test mode not enabled") 

77 

78 email_service.clear_test_emails() 

79 return {"status": "cleared"}