test_reservation_guards.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. """Tests for the reservation-deletion guard mechanisms.
  2. 1. _AirbnbClient._had_bookings — stale-replica cache detection
  3. 2. fetch_reservations per-service guard — skip deletions when a service errors
  4. or silently returns 0 reservations while the store has upcoming ones.
  5. 3. fetch_reservations mass-deletion guard — skip deletions when a single run
  6. would remove more than _MAX_DELETIONS_PER_RUN reservations for a service.
  7. """
  8. import time
  9. from datetime import date, timedelta
  10. import pytest
  11. from room_cal.reservations import Reservation
  12. from room_cal.actions.fetch_reservations import fetch_reservations
  13. # ── Helpers ───────────────────────────────────────────────────────────────────
  14. def _airbnb_client():
  15. from room_cal.service_api._airbnb import _AirbnbClient
  16. return _AirbnbClient(cookies='test', listing_id='12345678')
  17. def _days(booked=False):
  18. day = {'day': '2026-07-10', 'priceData': {'price': 100}, 'available': True}
  19. if booked:
  20. day['reservationData'] = {'confirmationCode': 'TEST123'}
  21. return [day]
  22. class _BaseAPI:
  23. """Minimal stub: only get_reservations is called by fetch_reservations."""
  24. async def get_reservations(self, start, end, *, _out_errors=None):
  25. return []
  26. class _ErrorAPI(_BaseAPI):
  27. """Simulates a service throwing an exception (e.g. Booking.com 502)."""
  28. def __init__(self, error_service: str):
  29. self._svc = error_service
  30. async def get_reservations(self, start, end, *, _out_errors=None):
  31. if _out_errors is not None:
  32. _out_errors.add(self._svc)
  33. return []
  34. class _PartialAPI(_BaseAPI):
  35. """Simulates a service returning a partial reservation list (stale replica)."""
  36. def __init__(self, reservations: list[dict]):
  37. self._res = reservations
  38. async def get_reservations(self, start, end, *, _out_errors=None):
  39. return self._res
  40. class _NoopClosed:
  41. """Stand-in for Closed so guard tests don't write closure events to the real store."""
  42. def __init__(self, *a, **k): pass
  43. async def list(self, *a, **k): return []
  44. async def set(self, *a, **k): pass
  45. async def delete(self, *a, **k): pass
  46. # Window used by the integration tests — far enough out to not collide with
  47. # real reservations but still within any plausible sync window.
  48. _CHECKIN = date.today() + timedelta(days=45)
  49. _CHECKOUT = _CHECKIN + timedelta(days=2)
  50. async def _seed(service: str, rid: str) -> None:
  51. await Reservation().set({
  52. 'checkin_date': _CHECKIN,
  53. 'checkout_date': _CHECKOUT,
  54. 'guest_name': 'Test Guest',
  55. 'service': service,
  56. 'reservation_id': rid,
  57. 'service_data': {},
  58. })
  59. async def _exists(rid: str) -> bool:
  60. return await Reservation()._find(rid, _CHECKIN, _CHECKOUT) is not None
  61. async def _delete(rid: str) -> None:
  62. event = await Reservation()._find(rid, _CHECKIN, _CHECKOUT)
  63. if event:
  64. await Reservation().delete(event)
  65. def _remote(service: str, rid: str) -> dict:
  66. """Reservation dict as ServiceAPI.get_reservations would return it."""
  67. return {
  68. 'id': rid,
  69. 'service': service,
  70. 'start_date': _CHECKIN,
  71. 'end_date': _CHECKOUT,
  72. 'guest_name': 'Test Guest',
  73. 'service_data': {},
  74. 'chat_id': None,
  75. 'door_code': None,
  76. }
  77. # ── _had_bookings unit tests ───────────────────────────────────────────────────
  78. class TestHadBookings:
  79. """Unit tests for _AirbnbClient._had_bookings stale-cache detection.
  80. _fetch_month_days is replaced on the instance so no network calls are made.
  81. """
  82. @staticmethod
  83. def _seed(client, key, days):
  84. client._months._data[key] = days
  85. client._months._fetched_at[key] = time.monotonic()
  86. async def test_first_fetch_with_bookings_marks_month(self):
  87. client = _airbnb_client()
  88. async def _fetch(m, y): return _days(booked=True)
  89. client._fetch_month_days = _fetch
  90. await client._months.get(7, 2026)
  91. assert (7, 2026) in client._had_bookings
  92. async def test_first_fetch_without_bookings_does_not_mark(self):
  93. client = _airbnb_client()
  94. async def _fetch(m, y): return _days(booked=False)
  95. client._fetch_month_days = _fetch
  96. await client._months.get(7, 2026)
  97. assert (7, 2026) not in client._had_bookings
  98. async def test_stale_cache_forces_refetch(self):
  99. """Cache shows 0 booked but _had_bookings marks month → refetch triggered."""
  100. client = _airbnb_client()
  101. key = (7, 2026)
  102. client._had_bookings.add(key)
  103. self._seed(client, key, _days(booked=False)) # stale: no bookings
  104. calls = []
  105. async def _fetch(m, y):
  106. calls.append((m, y))
  107. return _days(booked=True)
  108. client._fetch_month_days = _fetch
  109. result = await client._months.get(7, 2026)
  110. assert calls == [(7, 2026)], "expected exactly one refetch"
  111. assert any(d.get('reservationData') for d in result)
  112. async def test_no_refetch_without_prior_bookings(self):
  113. """Cache has 0 booked and _had_bookings has no entry → served from cache."""
  114. client = _airbnb_client()
  115. key = (7, 2026)
  116. self._seed(client, key, _days(booked=False))
  117. calls = []
  118. async def _fetch(m, y):
  119. calls.append((m, y))
  120. return _days(booked=True)
  121. client._fetch_month_days = _fetch
  122. await client._months.get(7, 2026)
  123. assert calls == [], "cache hit should not trigger refetch"
  124. async def test_forced_refetch_confirms_empty_removes_mark(self):
  125. """Forced refetch still shows 0 booked → month removed from _had_bookings."""
  126. client = _airbnb_client()
  127. key = (7, 2026)
  128. client._had_bookings.add(key)
  129. self._seed(client, key, _days(booked=False))
  130. async def _fetch(m, y): return _days(booked=False) # still 0 on refetch
  131. client._fetch_month_days = _fetch
  132. await client._months.get(7, 2026)
  133. assert key not in client._had_bookings, "confirmed empty — guard should be lifted"
  134. async def test_refetch_invalidates_parsed_months_and_cache(self):
  135. """Forcing a refetch must also clear _parsed_months and _cache for that month."""
  136. from room_cal.service_api.types import DayInfo
  137. _dummy = DayInfo(date='2026-07-10', price=100, available=True, booked=False)
  138. client = _airbnb_client()
  139. key = (7, 2026)
  140. client._had_bookings.add(key)
  141. self._seed(client, key, _days(booked=False))
  142. client._parsed_months.add(key)
  143. client._cache['2026-07-10'] = _dummy
  144. client._cache['2026-08-01'] = _dummy # different month — must survive
  145. async def _fetch(m, y): return _days(booked=True)
  146. client._fetch_month_days = _fetch
  147. await client._months.get(7, 2026)
  148. assert key not in client._parsed_months
  149. assert '2026-07-10' not in client._cache
  150. assert '2026-08-01' in client._cache, "different month must not be evicted"
  151. async def test_had_bookings_survives_clear_cache(self):
  152. """_had_bookings must not be cleared by clear_cache() — that's the whole point."""
  153. client = _airbnb_client()
  154. client._had_bookings.add((7, 2026))
  155. client.clear_cache()
  156. assert (7, 2026) in client._had_bookings
  157. # ── fetch_reservations per-service guard integration tests ────────────────────
  158. class TestFetchReservationsGuard:
  159. """Integration tests: real Reservation store, stub API."""
  160. async def test_errored_service_skips_deletion(self):
  161. """When a service throws (e.g. 502), its stored reservations are preserved."""
  162. rid = 'TEST-GUARD-ERROR-001'
  163. await _seed('airbnb', rid)
  164. try:
  165. await fetch_reservations(_CHECKIN, _CHECKOUT, api=_ErrorAPI('airbnb'))
  166. assert await _exists(rid), "reservation must survive when its service errored"
  167. finally:
  168. await _delete(rid)
  169. async def test_silent_zero_return_skips_deletion(self):
  170. """When a service returns [] with stored upcoming reservations, those are preserved."""
  171. rid = 'TEST-GUARD-ZERO-001'
  172. await _seed('airbnb', rid)
  173. try:
  174. await fetch_reservations(_CHECKIN, _CHECKOUT, api=_BaseAPI())
  175. assert await _exists(rid), "reservation must survive when service silently returned 0"
  176. finally:
  177. await _delete(rid)
  178. async def test_no_guard_when_store_is_empty(self):
  179. """Guard does not fire when there are no stored reservations to protect."""
  180. # Nothing seeded — fetch with empty API should succeed without error.
  181. result = await fetch_reservations(_CHECKIN, _CHECKOUT, api=_BaseAPI())
  182. assert result.data == []
  183. # ── fetch_reservations mass-deletion guard integration tests ──────────────────
  184. class TestMassDeletionGuard:
  185. """Integration tests: real Reservation store, stub API returning partial data.
  186. Closed is replaced with a no-op so the tests never write closure events to
  187. the store. The API must return at least one reservation for the service —
  188. otherwise the silent-zero guard fires before the mass-deletion guard.
  189. """
  190. @pytest.fixture(autouse=True)
  191. def _noop_closed(self, monkeypatch):
  192. monkeypatch.setattr('room_cal.actions.fetch_reservations.Closed', _NoopClosed)
  193. async def test_mass_deletion_is_cancelled(self):
  194. """More than _MAX_DELETIONS_PER_RUN pending deletions → all are skipped."""
  195. rids = [f'TEST-GUARD-MASS-00{i}' for i in range(1, 5)]
  196. for rid in rids:
  197. await _seed('airbnb', rid)
  198. try:
  199. # API returns only the first reservation → 3 pending deletions (> 2).
  200. await fetch_reservations(_CHECKIN, _CHECKOUT, api=_PartialAPI([_remote('airbnb', rids[0])]))
  201. for rid in rids:
  202. assert await _exists(rid), f"{rid} must survive a mass-deletion run"
  203. finally:
  204. for rid in rids:
  205. await _delete(rid)
  206. async def test_deletions_at_threshold_proceed(self):
  207. """Exactly _MAX_DELETIONS_PER_RUN pending deletions → deleted normally."""
  208. rids = [f'TEST-GUARD-OK-00{i}' for i in range(1, 4)]
  209. for rid in rids:
  210. await _seed('airbnb', rid)
  211. try:
  212. # API returns only the first reservation → 2 pending deletions (== max).
  213. await fetch_reservations(_CHECKIN, _CHECKOUT, api=_PartialAPI([_remote('airbnb', rids[0])]))
  214. assert await _exists(rids[0]), "returned reservation must remain"
  215. assert not await _exists(rids[1]), "genuine cancellation must be deleted"
  216. assert not await _exists(rids[2]), "genuine cancellation must be deleted"
  217. finally:
  218. for rid in rids:
  219. await _delete(rid)