test_reservation_guards.py 10 KB

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