python-jejakmasjid 0.2.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/PKG-INFO +1 -1
  2. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/pyproject.toml +1 -1
  3. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/__init__.py +30 -2
  4. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/client.py +139 -8
  5. python_jejakmasjid-0.3.1/src/jejakmasjid/constants.py +27 -0
  6. python_jejakmasjid-0.3.1/src/jejakmasjid/exceptions.py +14 -0
  7. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/PKG-INFO +1 -1
  8. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/SOURCES.txt +1 -0
  9. python_jejakmasjid-0.3.1/tests/test_auth.py +158 -0
  10. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/tests/test_client.py +6 -6
  11. python_jejakmasjid-0.2.0/src/jejakmasjid/constants.py +0 -17
  12. python_jejakmasjid-0.2.0/src/jejakmasjid/exceptions.py +0 -6
  13. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/LICENSE +0 -0
  14. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/README.md +0 -0
  15. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/setup.cfg +0 -0
  16. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/__main__.py +0 -0
  17. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/cli.py +0 -0
  18. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/geo.py +0 -0
  19. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/jejakmasjid/models.py +0 -0
  20. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/dependency_links.txt +0 -0
  21. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/entry_points.txt +0 -0
  22. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/requires.txt +0 -0
  23. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/src/python_jejakmasjid.egg-info/top_level.txt +0 -0
  24. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/tests/test_cli.py +0 -0
  25. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/tests/test_geo.py +0 -0
  26. {python_jejakmasjid-0.2.0 → python_jejakmasjid-0.3.1}/tests/test_models.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-jejakmasjid
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: Asynchronous Python client for the Jejak Masjid API
5
5
  Author: Zubir Jamal
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-jejakmasjid"
7
- version = "0.2.0"
7
+ version = "0.3.1"
8
8
  description = "Asynchronous Python client for the Jejak Masjid API"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -1,9 +1,20 @@
1
1
  """Asynchronous Python client for Jejak Masjid."""
2
2
  from __future__ import annotations
3
3
 
4
- from .client import JejakMasjidClient, async_fetch_nearby, parse_places
4
+ from .client import (
5
+ JejakMasjidClient,
6
+ async_fetch_nearby,
7
+ async_fetch_user_profile,
8
+ async_send_email_otp,
9
+ async_verify_email_otp,
10
+ parse_places,
11
+ )
5
12
  from .constants import (
6
13
  API_BASE,
14
+ AUTH_SEND_OTP_PATH,
15
+ AUTH_SEND_OTP_URL,
16
+ AUTH_VERIFY_OTP_PATH,
17
+ AUTH_VERIFY_OTP_URL,
7
18
  DEFAULT_TIMEOUT_SECONDS,
8
19
  DEFAULT_USER_AGENT,
9
20
  FALLBACK_NEARBY_URL,
@@ -14,8 +25,14 @@ from .constants import (
14
25
  NEARBY_URL,
15
26
  PLACE_TYPES,
16
27
  PRIMARY_NEARBY_URL,
28
+ USER_PROFILE_PATH,
29
+ USER_PROFILE_URL,
30
+ )
31
+ from .exceptions import (
32
+ JejakMasjidAuthError,
33
+ JejakMasjidConnectionError,
34
+ JejakMasjidError,
17
35
  )
18
- from .exceptions import JejakMasjidError
19
36
  from .geo import (
20
37
  DIRECTIONS,
21
38
  haversine_km,
@@ -28,13 +45,19 @@ from .models import Place
28
45
 
29
46
  __all__ = [
30
47
  "API_BASE",
48
+ "AUTH_SEND_OTP_PATH",
49
+ "AUTH_SEND_OTP_URL",
50
+ "AUTH_VERIFY_OTP_PATH",
51
+ "AUTH_VERIFY_OTP_URL",
31
52
  "DEFAULT_TIMEOUT_SECONDS",
32
53
  "DEFAULT_USER_AGENT",
33
54
  "DIRECTIONS",
34
55
  "FALLBACK_NEARBY_URL",
35
56
  "HA_V1_NEARBY_PATH",
36
57
  "HEALTH_URL",
58
+ "JejakMasjidAuthError",
37
59
  "JejakMasjidClient",
60
+ "JejakMasjidConnectionError",
38
61
  "JejakMasjidError",
39
62
  "LEGACY_NEARBY_PATH",
40
63
  "NEARBY_PATH",
@@ -42,7 +65,12 @@ __all__ = [
42
65
  "PLACE_TYPES",
43
66
  "PRIMARY_NEARBY_URL",
44
67
  "Place",
68
+ "USER_PROFILE_PATH",
69
+ "USER_PROFILE_URL",
45
70
  "async_fetch_nearby",
71
+ "async_fetch_user_profile",
72
+ "async_send_email_otp",
73
+ "async_verify_email_otp",
46
74
  "haversine_km",
47
75
  "parse_places",
48
76
  "place_type",
@@ -7,12 +7,15 @@ from typing import Any
7
7
  import aiohttp
8
8
 
9
9
  from .constants import (
10
+ AUTH_SEND_OTP_URL,
11
+ AUTH_VERIFY_OTP_URL,
10
12
  DEFAULT_TIMEOUT_SECONDS,
11
13
  DEFAULT_USER_AGENT,
12
14
  FALLBACK_NEARBY_URL,
13
15
  PRIMARY_NEARBY_URL,
16
+ USER_PROFILE_URL,
14
17
  )
15
- from .exceptions import JejakMasjidError
18
+ from .exceptions import JejakMasjidAuthError, JejakMasjidConnectionError, JejakMasjidError
16
19
  from .geo import place_type, project_coordinates, type_from_payload
17
20
 
18
21
  _LOGGER = logging.getLogger(__name__)
@@ -169,8 +172,8 @@ async def async_fetch_nearby(
169
172
 
170
173
  timeout = aiohttp.ClientTimeout(total=timeout_seconds)
171
174
 
172
- # 1. Attempt primary dedicated endpoint
173
- params = {"lat": f"{lat:.4f}", "lng": f"{lon:.4f}"}
175
+ # 1. Attempt primary endpoint (original map nearby API)
176
+ params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
174
177
  try:
175
178
  async with session.get(primary_url, params=params, headers=req_headers, timeout=timeout) as resp:
176
179
  if resp.status == 200:
@@ -178,17 +181,16 @@ async def async_fetch_nearby(
178
181
  return parse_places(payload, origin_lat=lat, origin_lon=lon)
179
182
  if resp.status != 404 or endpoint_url:
180
183
  raise JejakMasjidError(f"Jejak Masjid answered HTTP {resp.status}")
181
- _LOGGER.warning("Dedicated endpoint returned 404, falling back to legacy endpoint")
184
+ _LOGGER.warning("Primary endpoint returned 404, falling back to secondary endpoint")
182
185
  except (aiohttp.ClientError, TimeoutError, ValueError) as err:
183
186
  if endpoint_url:
184
187
  raise JejakMasjidError(f"Cannot reach Jejak Masjid: {err}") from err
185
- _LOGGER.warning("Dedicated endpoint failed (%s), falling back to legacy endpoint", err)
188
+ _LOGGER.warning("Primary endpoint failed (%s), falling back to secondary endpoint", err)
186
189
 
187
- # 2. Fallback to legacy endpoint if primary returned 404 or connection failed
188
- fallback_params = {"lat": f"{lat:.3f}", "lng": f"{lon:.3f}", "radius": str(radius_km)}
190
+ # 2. Fallback to secondary endpoint if primary returned 404 or connection failed
189
191
  try:
190
192
  async with session.get(
191
- FALLBACK_NEARBY_URL, params=fallback_params, headers=req_headers, timeout=timeout
193
+ FALLBACK_NEARBY_URL, params=params, headers=req_headers, timeout=timeout
192
194
  ) as resp:
193
195
  if resp.status != 200:
194
196
  raise JejakMasjidError(f"Jejak Masjid fallback answered HTTP {resp.status}")
@@ -236,3 +238,132 @@ class JejakMasjidClient:
236
238
  user_agent=self._user_agent,
237
239
  headers=headers,
238
240
  )
241
+
242
+ async def send_email_otp(self, email: str) -> dict[str, Any]:
243
+ """Request email OTP verification for user login."""
244
+ return await async_send_email_otp(
245
+ self._session,
246
+ email,
247
+ user_agent=self._user_agent,
248
+ )
249
+
250
+ async def verify_email_otp(self, email: str, otp: str) -> str:
251
+ """Verify emailed OTP and save session token."""
252
+ _data, token = await async_verify_email_otp(
253
+ self._session,
254
+ email,
255
+ otp,
256
+ user_agent=self._user_agent,
257
+ )
258
+ self._api_key = token
259
+ return token
260
+
261
+ async def fetch_user_profile(self, token: str | None = None) -> dict[str, Any]:
262
+ """Fetch user profile and journey statistics."""
263
+ auth_token = token or self._api_key
264
+ if not auth_token:
265
+ raise JejakMasjidAuthError("No authentication token provided or configured")
266
+ return await async_fetch_user_profile(
267
+ self._session,
268
+ auth_token,
269
+ user_agent=self._user_agent,
270
+ )
271
+
272
+
273
+ async def async_send_email_otp(
274
+ session: aiohttp.ClientSession,
275
+ email: str,
276
+ *,
277
+ endpoint_url: str = AUTH_SEND_OTP_URL,
278
+ user_agent: str = DEFAULT_USER_AGENT,
279
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
280
+ ) -> dict[str, Any]:
281
+ """Request an email verification code for user authentication."""
282
+ headers = {"User-Agent": user_agent}
283
+ payload = {"email": email.strip().lower(), "type": "sign-in"}
284
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
285
+
286
+ try:
287
+ async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
288
+ data = await resp.json(content_type=None) or {}
289
+ if resp.status >= 400:
290
+ raise JejakMasjidAuthError(
291
+ f"Send OTP failed with HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
292
+ )
293
+ return data
294
+ except aiohttp.ClientError as err:
295
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
296
+ except TimeoutError as err:
297
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
298
+ except ValueError as err:
299
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
300
+
301
+
302
+ async def async_verify_email_otp(
303
+ session: aiohttp.ClientSession,
304
+ email: str,
305
+ otp: str,
306
+ *,
307
+ endpoint_url: str = AUTH_VERIFY_OTP_URL,
308
+ user_agent: str = DEFAULT_USER_AGENT,
309
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
310
+ ) -> tuple[dict[str, Any], str]:
311
+ """Exchange emailed OTP for a user session token.
312
+
313
+ Returns tuple of (response_json, token_string).
314
+ """
315
+ headers = {"User-Agent": user_agent}
316
+ payload = {"email": email.strip().lower(), "otp": otp.strip()}
317
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
318
+
319
+ try:
320
+ async with session.post(endpoint_url, json=payload, headers=headers, timeout=timeout) as resp:
321
+ data = await resp.json(content_type=None) or {}
322
+ if resp.status >= 400:
323
+ raise JejakMasjidAuthError(
324
+ f"Invalid OTP or authentication refused (HTTP {resp.status}): {data.get('message') or data.get('code') or resp.status}"
325
+ )
326
+ header_token = resp.headers.get("set-auth-token")
327
+ token = header_token or data.get("token")
328
+ if not token:
329
+ raise JejakMasjidAuthError("No authentication token returned by Jejak Masjid")
330
+ return data, token
331
+ except aiohttp.ClientError as err:
332
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid auth service: {err}") from err
333
+ except TimeoutError as err:
334
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid auth service: {err}") from err
335
+ except ValueError as err:
336
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
337
+
338
+
339
+ async def async_fetch_user_profile(
340
+ session: aiohttp.ClientSession,
341
+ token: str,
342
+ *,
343
+ endpoint_url: str = USER_PROFILE_URL,
344
+ user_agent: str = DEFAULT_USER_AGENT,
345
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
346
+ ) -> dict[str, Any]:
347
+ """Fetch user profile, journey statistics, streaks, and achievements."""
348
+ headers = {
349
+ "User-Agent": user_agent,
350
+ "Authorization": f"Bearer {token.strip()}",
351
+ }
352
+ timeout = aiohttp.ClientTimeout(total=timeout_seconds)
353
+
354
+ try:
355
+ async with session.get(endpoint_url, headers=headers, timeout=timeout) as resp:
356
+ if resp.status == 401:
357
+ raise JejakMasjidAuthError("Jejak Masjid session token expired or revoked (HTTP 401)")
358
+ data = await resp.json(content_type=None) or {}
359
+ if resp.status >= 400:
360
+ raise JejakMasjidError(
361
+ f"Profile request answered HTTP {resp.status}: {data.get('message') or data.get('code') or resp.status}"
362
+ )
363
+ return data
364
+ except aiohttp.ClientError as err:
365
+ raise JejakMasjidConnectionError(f"Cannot reach Jejak Masjid profile service: {err}") from err
366
+ except TimeoutError as err:
367
+ raise JejakMasjidConnectionError(f"Timeout reaching Jejak Masjid profile service: {err}") from err
368
+ except ValueError as err:
369
+ raise JejakMasjidError(f"Invalid JSON response from Jejak Masjid: {err}") from err
@@ -0,0 +1,27 @@
1
+ """Constants for the Jejak Masjid client library."""
2
+ from __future__ import annotations
3
+
4
+ API_BASE = "https://apiv2.jejakmasjid.my"
5
+ MAP_NEARBY_PATH = "/api/map/nearby"
6
+ HA_V1_NEARBY_PATH = "/api/ha/v1/masjids/nearby"
7
+ LEGACY_NEARBY_PATH = MAP_NEARBY_PATH
8
+ NEARBY_PATH = MAP_NEARBY_PATH
9
+
10
+ # Original map nearby is primary; HA v1 is ready as fallback/future
11
+ PRIMARY_NEARBY_URL = f"{API_BASE}{MAP_NEARBY_PATH}"
12
+ FALLBACK_NEARBY_URL = f"{API_BASE}{HA_V1_NEARBY_PATH}"
13
+ NEARBY_URL = PRIMARY_NEARBY_URL
14
+ HEALTH_URL = f"{API_BASE}/"
15
+
16
+ DEFAULT_TIMEOUT_SECONDS = 20
17
+ DEFAULT_USER_AGENT = "python-jejakmasjid/0.3.1 (+https://github.com/zubirjamal/python-jejakmasjid)"
18
+
19
+ AUTH_SEND_OTP_PATH = "/api/auth/email-otp/send-verification-otp"
20
+ AUTH_VERIFY_OTP_PATH = "/api/auth/sign-in/email-otp"
21
+ USER_PROFILE_PATH = "/api/user/profile"
22
+
23
+ AUTH_SEND_OTP_URL = f"{API_BASE}{AUTH_SEND_OTP_PATH}"
24
+ AUTH_VERIFY_OTP_URL = f"{API_BASE}{AUTH_VERIFY_OTP_PATH}"
25
+ USER_PROFILE_URL = f"{API_BASE}{USER_PROFILE_PATH}"
26
+
27
+ PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
@@ -0,0 +1,14 @@
1
+ """Exceptions for the Jejak Masjid client library."""
2
+ from __future__ import annotations
3
+
4
+
5
+ class JejakMasjidError(Exception):
6
+ """The API could not be reached or answered with something unexpected."""
7
+
8
+
9
+ class JejakMasjidAuthError(JejakMasjidError):
10
+ """Authentication failed or session token expired/invalid."""
11
+
12
+
13
+ class JejakMasjidConnectionError(JejakMasjidError):
14
+ """Network connection or timeout failure."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-jejakmasjid
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: Asynchronous Python client for the Jejak Masjid API
5
5
  Author: Zubir Jamal
6
6
  License: MIT
@@ -15,6 +15,7 @@ src/python_jejakmasjid.egg-info/dependency_links.txt
15
15
  src/python_jejakmasjid.egg-info/entry_points.txt
16
16
  src/python_jejakmasjid.egg-info/requires.txt
17
17
  src/python_jejakmasjid.egg-info/top_level.txt
18
+ tests/test_auth.py
18
19
  tests/test_cli.py
19
20
  tests/test_client.py
20
21
  tests/test_geo.py
@@ -0,0 +1,158 @@
1
+ """Unit tests for Jejak Masjid email OTP authentication and user profile retrieval."""
2
+ from __future__ import annotations
3
+
4
+ from unittest.mock import AsyncMock, MagicMock
5
+
6
+ import aiohttp
7
+ import pytest
8
+
9
+ from jejakmasjid import (
10
+ JejakMasjidAuthError,
11
+ JejakMasjidClient,
12
+ JejakMasjidConnectionError,
13
+ async_fetch_user_profile,
14
+ async_send_email_otp,
15
+ async_verify_email_otp,
16
+ )
17
+
18
+
19
+ @pytest.fixture
20
+ def mock_session():
21
+ """Mock aiohttp.ClientSession."""
22
+ session = MagicMock(spec=aiohttp.ClientSession)
23
+ return session
24
+
25
+
26
+ async def test_send_email_otp_success(mock_session):
27
+ """Test successful email OTP request."""
28
+ mock_resp = MagicMock()
29
+ mock_resp.status = 200
30
+ mock_resp.json = AsyncMock(return_value={"status": "ok", "message": "OTP sent"})
31
+
32
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
33
+
34
+ res = await async_send_email_otp(mock_session, "user@example.com")
35
+ assert res["status"] == "ok"
36
+ mock_session.post.assert_called_once()
37
+ _call_args, call_kwargs = mock_session.post.call_args
38
+ assert call_kwargs["json"] == {"email": "user@example.com", "type": "sign-in"}
39
+
40
+
41
+ async def test_send_email_otp_failure(mock_session):
42
+ """Test OTP request refusal raises JejakMasjidAuthError."""
43
+ mock_resp = MagicMock()
44
+ mock_resp.status = 400
45
+ mock_resp.json = AsyncMock(return_value={"code": "INVALID_EMAIL", "message": "Email rejected"})
46
+
47
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
48
+
49
+ with pytest.raises(JejakMasjidAuthError, match="Send OTP failed"):
50
+ await async_send_email_otp(mock_session, "invalid-email")
51
+
52
+
53
+ async def test_verify_email_otp_header_token(mock_session):
54
+ """Test verifying OTP when token is returned in response header."""
55
+ mock_resp = MagicMock()
56
+ mock_resp.status = 200
57
+ mock_resp.headers = {"set-auth-token": "jwt-token-from-header"}
58
+ mock_resp.json = AsyncMock(return_value={"user": {"id": "123"}})
59
+
60
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
61
+
62
+ data, token = await async_verify_email_otp(mock_session, "user@example.com", "123456")
63
+ assert token == "jwt-token-from-header"
64
+ assert data["user"]["id"] == "123"
65
+
66
+
67
+ async def test_verify_email_otp_body_token(mock_session):
68
+ """Test verifying OTP when token is returned in JSON body."""
69
+ mock_resp = MagicMock()
70
+ mock_resp.status = 200
71
+ mock_resp.headers = {}
72
+ mock_resp.json = AsyncMock(return_value={"token": "jwt-token-from-body"})
73
+
74
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
75
+
76
+ _data, token = await async_verify_email_otp(mock_session, "user@example.com", "123456")
77
+ assert token == "jwt-token-from-body"
78
+
79
+
80
+ async def test_verify_email_otp_invalid(mock_session):
81
+ """Test invalid OTP raises JejakMasjidAuthError."""
82
+ mock_resp = MagicMock()
83
+ mock_resp.status = 400
84
+ mock_resp.json = AsyncMock(return_value={"code": "INVALID_OTP"})
85
+
86
+ mock_session.post.return_value.__aenter__.return_value = mock_resp
87
+
88
+ with pytest.raises(JejakMasjidAuthError, match="Invalid OTP"):
89
+ await async_verify_email_otp(mock_session, "user@example.com", "wrong")
90
+
91
+
92
+ async def test_fetch_user_profile_success(mock_session):
93
+ """Test fetching user profile with valid Bearer token."""
94
+ mock_resp = MagicMock()
95
+ mock_resp.status = 200
96
+ profile_data = {
97
+ "profile": {
98
+ "totalCheckIns": 12,
99
+ "uniqueMasjidsVisited": 8,
100
+ "currentStreak": 5,
101
+ "totalPoints": 420,
102
+ },
103
+ "rank": {"globalRank": 150},
104
+ }
105
+ mock_resp.json = AsyncMock(return_value=profile_data)
106
+
107
+ mock_session.get.return_value.__aenter__.return_value = mock_resp
108
+
109
+ res = await async_fetch_user_profile(mock_session, "valid-token")
110
+ assert res["profile"]["totalCheckIns"] == 12
111
+ assert res["rank"]["globalRank"] == 150
112
+
113
+ _call_args, call_kwargs = mock_session.get.call_args
114
+ assert call_kwargs["headers"]["Authorization"] == "Bearer valid-token"
115
+
116
+
117
+ async def test_fetch_user_profile_unauthorized(mock_session):
118
+ """Test expired token (401) raises JejakMasjidAuthError."""
119
+ mock_resp = MagicMock()
120
+ mock_resp.status = 401
121
+ mock_resp.json = AsyncMock(return_value={"error": "Unauthorized"})
122
+
123
+ mock_session.get.return_value.__aenter__.return_value = mock_resp
124
+
125
+ with pytest.raises(JejakMasjidAuthError, match="token expired"):
126
+ await async_fetch_user_profile(mock_session, "expired-token")
127
+
128
+
129
+ async def test_client_class_auth_flow(mock_session):
130
+ """Test high-level JejakMasjidClient auth methods."""
131
+ client = JejakMasjidClient(mock_session)
132
+
133
+ # 1. Send OTP
134
+ mock_post_resp = MagicMock()
135
+ mock_post_resp.status = 200
136
+ mock_post_resp.json = AsyncMock(return_value={"status": "ok"})
137
+ mock_session.post.return_value.__aenter__.return_value = mock_post_resp
138
+
139
+ await client.send_email_otp("user@example.com")
140
+
141
+ # 2. Verify OTP
142
+ mock_verify_resp = MagicMock()
143
+ mock_verify_resp.status = 200
144
+ mock_verify_resp.headers = {}
145
+ mock_verify_resp.json = AsyncMock(return_value={"token": "client-saved-token"})
146
+ mock_session.post.return_value.__aenter__.return_value = mock_verify_resp
147
+
148
+ token = await client.verify_email_otp("user@example.com", "999999")
149
+ assert token == "client-saved-token"
150
+
151
+ # 3. Fetch profile with automatically saved token
152
+ mock_get_resp = MagicMock()
153
+ mock_get_resp.status = 200
154
+ mock_get_resp.json = AsyncMock(return_value={"profile": {"totalPoints": 999}})
155
+ mock_session.get.return_value.__aenter__.return_value = mock_get_resp
156
+
157
+ profile = await client.fetch_user_profile()
158
+ assert profile["profile"]["totalPoints"] == 999
@@ -95,14 +95,14 @@ def test_parse_ha_v1_masjids():
95
95
  async def test_async_fetch_nearby_primary_success():
96
96
  mock_resp = AsyncMock()
97
97
  mock_resp.status = 200
98
- mock_resp.json = AsyncMock(return_value=MOCK_HA_V1_PAYLOAD)
98
+ mock_resp.json = AsyncMock(return_value=MOCK_LEGACY_PAYLOAD)
99
99
 
100
100
  mock_session = MagicMock()
101
101
  mock_session.get.return_value.__aenter__.return_value = mock_resp
102
102
 
103
- places = await async_fetch_nearby(mock_session, 3.1390, 101.6869, 5)
103
+ places = await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
104
104
  assert len(places) == 2
105
- assert places[0]["id"] == "surau-kl-sentral-kuala-lumpur"
105
+ assert places[0]["id"] == "place-1"
106
106
 
107
107
  # Verify primary URL was called
108
108
  call_args = mock_session.get.call_args_list[0]
@@ -116,14 +116,14 @@ async def test_async_fetch_nearby_fallback_on_404():
116
116
 
117
117
  resp_200 = AsyncMock()
118
118
  resp_200.status = 200
119
- resp_200.json = AsyncMock(return_value=MOCK_LEGACY_PAYLOAD)
119
+ resp_200.json = AsyncMock(return_value=MOCK_HA_V1_PAYLOAD)
120
120
 
121
121
  mock_session = MagicMock()
122
122
  mock_session.get.return_value.__aenter__.side_effect = [resp_404, resp_200]
123
123
 
124
- places = await async_fetch_nearby(mock_session, 3.02, 101.79, 3)
124
+ places = await async_fetch_nearby(mock_session, 3.1390, 101.6869, 5)
125
125
  assert len(places) == 2
126
- assert places[0]["id"] == "place-1"
126
+ assert places[0]["id"] == "surau-kl-sentral-kuala-lumpur"
127
127
 
128
128
  # Verify both URLs were attempted
129
129
  assert mock_session.get.call_count == 2
@@ -1,17 +0,0 @@
1
- """Constants for the Jejak Masjid client library."""
2
- from __future__ import annotations
3
-
4
- API_BASE = "https://apiv2.jejakmasjid.my"
5
- HA_V1_NEARBY_PATH = "/api/ha/v1/masjids/nearby"
6
- LEGACY_NEARBY_PATH = "/api/map/nearby"
7
- NEARBY_PATH = HA_V1_NEARBY_PATH
8
-
9
- PRIMARY_NEARBY_URL = f"{API_BASE}{HA_V1_NEARBY_PATH}"
10
- FALLBACK_NEARBY_URL = f"{API_BASE}{LEGACY_NEARBY_PATH}"
11
- NEARBY_URL = PRIMARY_NEARBY_URL
12
- HEALTH_URL = f"{API_BASE}/"
13
-
14
- DEFAULT_TIMEOUT_SECONDS = 20
15
- DEFAULT_USER_AGENT = "python-jejakmasjid/0.2.0 (+https://github.com/zubirjamal/python-jejakmasjid)"
16
-
17
- PLACE_TYPES = ["masjid", "surau", "madrasah", "other"]
@@ -1,6 +0,0 @@
1
- """Exceptions for the Jejak Masjid client library."""
2
- from __future__ import annotations
3
-
4
-
5
- class JejakMasjidError(Exception):
6
- """The API could not be reached or answered with something unexpected."""