|
| 1 | +"""Tests for server-side Plausible analytics tracking.""" |
| 2 | + |
| 3 | +from unittest.mock import AsyncMock, MagicMock, patch |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from api.analytics import PLATFORM_PATTERNS, detect_platform, track_og_image |
| 8 | + |
| 9 | + |
| 10 | +class TestDetectPlatform: |
| 11 | + """Tests for platform detection from User-Agent.""" |
| 12 | + |
| 13 | + def test_detects_twitter(self) -> None: |
| 14 | + """Should detect Twitter bot.""" |
| 15 | + assert detect_platform("Twitterbot/1.0") == "twitter" |
| 16 | + |
| 17 | + def test_detects_whatsapp(self) -> None: |
| 18 | + """Should detect WhatsApp.""" |
| 19 | + assert detect_platform("WhatsApp/2.21.4.22") == "whatsapp" |
| 20 | + |
| 21 | + def test_detects_facebook(self) -> None: |
| 22 | + """Should detect Facebook.""" |
| 23 | + assert detect_platform("facebookexternalhit/1.1") == "facebook" |
| 24 | + |
| 25 | + def test_detects_linkedin(self) -> None: |
| 26 | + """Should detect LinkedIn.""" |
| 27 | + assert detect_platform("LinkedInBot/1.0") == "linkedin" |
| 28 | + |
| 29 | + def test_detects_slack(self) -> None: |
| 30 | + """Should detect Slack.""" |
| 31 | + assert detect_platform("Slackbot-LinkExpanding 1.0") == "slack" |
| 32 | + |
| 33 | + def test_detects_discord(self) -> None: |
| 34 | + """Should detect Discord.""" |
| 35 | + assert detect_platform("Mozilla/5.0 (compatible; Discordbot/2.0)") == "discord" |
| 36 | + |
| 37 | + def test_detects_telegram(self) -> None: |
| 38 | + """Should detect Telegram.""" |
| 39 | + assert detect_platform("TelegramBot/1.0") == "telegram" |
| 40 | + |
| 41 | + def test_detects_teams(self) -> None: |
| 42 | + """Should detect Microsoft Teams.""" |
| 43 | + assert detect_platform("Mozilla/5.0 Microsoft Teams") == "teams" |
| 44 | + |
| 45 | + def test_detects_google(self) -> None: |
| 46 | + """Should detect Googlebot.""" |
| 47 | + assert detect_platform("Mozilla/5.0 (compatible; Googlebot/2.1)") == "google" |
| 48 | + |
| 49 | + def test_returns_unknown_for_regular_browser(self) -> None: |
| 50 | + """Should return unknown for regular browsers.""" |
| 51 | + assert detect_platform("Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0") == "unknown" |
| 52 | + |
| 53 | + def test_returns_unknown_for_empty_string(self) -> None: |
| 54 | + """Should return unknown for empty User-Agent.""" |
| 55 | + assert detect_platform("") == "unknown" |
| 56 | + |
| 57 | + def test_case_insensitive(self) -> None: |
| 58 | + """Should match case-insensitively.""" |
| 59 | + assert detect_platform("TWITTERBOT/1.0") == "twitter" |
| 60 | + assert detect_platform("twitterbot/1.0") == "twitter" |
| 61 | + |
| 62 | + def test_all_platforms_have_patterns(self) -> None: |
| 63 | + """Should have 27 platform patterns defined.""" |
| 64 | + assert len(PLATFORM_PATTERNS) == 27 |
| 65 | + |
| 66 | + |
| 67 | +class TestTrackOgImage: |
| 68 | + """Tests for og:image tracking function.""" |
| 69 | + |
| 70 | + @pytest.fixture |
| 71 | + def mock_request(self) -> MagicMock: |
| 72 | + """Create a mock FastAPI request.""" |
| 73 | + request = MagicMock() |
| 74 | + request.headers = {"user-agent": "Twitterbot/1.0", "x-forwarded-for": "1.2.3.4"} |
| 75 | + request.client = MagicMock() |
| 76 | + request.client.host = "127.0.0.1" |
| 77 | + return request |
| 78 | + |
| 79 | + def test_creates_async_task(self, mock_request: MagicMock) -> None: |
| 80 | + """Should create background task without blocking.""" |
| 81 | + with patch("api.analytics.asyncio.create_task") as mock_create_task: |
| 82 | + track_og_image(mock_request, page="home") |
| 83 | + mock_create_task.assert_called_once() |
| 84 | + |
| 85 | + def test_home_page_url(self, mock_request: MagicMock) -> None: |
| 86 | + """Should build correct URL for home page.""" |
| 87 | + with patch("api.analytics.asyncio.create_task") as mock_create_task: |
| 88 | + track_og_image(mock_request, page="home") |
| 89 | + call_args = mock_create_task.call_args[0][0] |
| 90 | + # The coroutine should be called with home URL |
| 91 | + assert call_args is not None |
| 92 | + |
| 93 | + def test_catalog_page_url(self, mock_request: MagicMock) -> None: |
| 94 | + """Should build correct URL for catalog page.""" |
| 95 | + with patch("api.analytics._send_plausible_event", new_callable=AsyncMock): |
| 96 | + with patch("api.analytics.asyncio.create_task") as mock_create_task: |
| 97 | + track_og_image(mock_request, page="catalog") |
| 98 | + mock_create_task.assert_called_once() |
| 99 | + |
| 100 | + def test_spec_overview_url(self, mock_request: MagicMock) -> None: |
| 101 | + """Should build correct URL for spec overview.""" |
| 102 | + with patch("api.analytics.asyncio.create_task"): |
| 103 | + # Should not raise even with spec_overview page |
| 104 | + track_og_image(mock_request, page="spec_overview", spec="scatter-basic") |
| 105 | + |
| 106 | + def test_spec_detail_url(self, mock_request: MagicMock) -> None: |
| 107 | + """Should build correct URL for spec detail.""" |
| 108 | + with patch("api.analytics.asyncio.create_task"): |
| 109 | + track_og_image(mock_request, page="spec_detail", spec="scatter-basic", library="matplotlib") |
| 110 | + |
| 111 | + def test_fallback_url_when_spec_none(self, mock_request: MagicMock) -> None: |
| 112 | + """Should fallback to home URL when spec is None for spec-based page.""" |
| 113 | + with patch("api.analytics.asyncio.create_task"): |
| 114 | + # Should not raise - falls back to home URL |
| 115 | + track_og_image(mock_request, page="spec_overview", spec=None) |
| 116 | + |
| 117 | + def test_includes_filter_props(self, mock_request: MagicMock) -> None: |
| 118 | + """Should include filter parameters in props.""" |
| 119 | + with patch("api.analytics.asyncio.create_task"): |
| 120 | + track_og_image(mock_request, page="home", filters={"lib": "plotly", "dom": "statistics"}) |
| 121 | + |
| 122 | + def test_uses_x_forwarded_for(self) -> None: |
| 123 | + """Should use X-Forwarded-For header for client IP.""" |
| 124 | + request = MagicMock() |
| 125 | + request.headers = {"user-agent": "Twitterbot/1.0", "x-forwarded-for": "5.6.7.8"} |
| 126 | + request.client = None |
| 127 | + |
| 128 | + with patch("api.analytics.asyncio.create_task"): |
| 129 | + track_og_image(request, page="home") |
| 130 | + |
| 131 | + def test_fallback_to_client_host(self) -> None: |
| 132 | + """Should fallback to client.host when X-Forwarded-For not present.""" |
| 133 | + request = MagicMock() |
| 134 | + request.headers = {"user-agent": "Twitterbot/1.0"} |
| 135 | + request.client = MagicMock() |
| 136 | + request.client.host = "10.0.0.1" |
| 137 | + |
| 138 | + with patch("api.analytics.asyncio.create_task"): |
| 139 | + track_og_image(request, page="home") |
| 140 | + |
| 141 | + def test_handles_missing_client(self) -> None: |
| 142 | + """Should handle missing client gracefully.""" |
| 143 | + request = MagicMock() |
| 144 | + request.headers = {"user-agent": "Twitterbot/1.0"} |
| 145 | + request.client = None |
| 146 | + |
| 147 | + with patch("api.analytics.asyncio.create_task"): |
| 148 | + track_og_image(request, page="home") |
| 149 | + |
| 150 | + |
| 151 | +class TestSendPlausibleEvent: |
| 152 | + """Tests for Plausible API call.""" |
| 153 | + |
| 154 | + @pytest.mark.asyncio |
| 155 | + async def test_sends_correct_payload(self) -> None: |
| 156 | + """Should send correct payload to Plausible.""" |
| 157 | + from api.analytics import _send_plausible_event |
| 158 | + |
| 159 | + with patch("api.analytics.httpx.AsyncClient") as mock_client_class: |
| 160 | + mock_client = AsyncMock() |
| 161 | + mock_client_class.return_value.__aenter__.return_value = mock_client |
| 162 | + |
| 163 | + await _send_plausible_event( |
| 164 | + user_agent="Twitterbot/1.0", |
| 165 | + client_ip="1.2.3.4", |
| 166 | + name="og_image_view", |
| 167 | + url="https://pyplots.ai/", |
| 168 | + props={"page": "home", "platform": "twitter"}, |
| 169 | + ) |
| 170 | + |
| 171 | + mock_client.post.assert_called_once() |
| 172 | + call_kwargs = mock_client.post.call_args[1] |
| 173 | + assert call_kwargs["json"]["name"] == "og_image_view" |
| 174 | + assert call_kwargs["json"]["domain"] == "pyplots.ai" |
| 175 | + |
| 176 | + @pytest.mark.asyncio |
| 177 | + async def test_handles_network_error(self) -> None: |
| 178 | + """Should handle network errors gracefully.""" |
| 179 | + from api.analytics import _send_plausible_event |
| 180 | + |
| 181 | + with patch("api.analytics.httpx.AsyncClient") as mock_client_class: |
| 182 | + mock_client = AsyncMock() |
| 183 | + mock_client.post.side_effect = Exception("Network error") |
| 184 | + mock_client_class.return_value.__aenter__.return_value = mock_client |
| 185 | + |
| 186 | + # Should not raise |
| 187 | + await _send_plausible_event( |
| 188 | + user_agent="Twitterbot/1.0", |
| 189 | + client_ip="1.2.3.4", |
| 190 | + name="og_image_view", |
| 191 | + url="https://pyplots.ai/", |
| 192 | + props={}, |
| 193 | + ) |
0 commit comments