test_ita_preflight.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. """Offline regression for Italy form readiness; never contact the real site."""
  2. import io
  3. import json
  4. from contextlib import redirect_stdout
  5. from types import SimpleNamespace
  6. from unittest import TestCase
  7. from unittest.mock import Mock, patch
  8. from plugins import ita_plugin as session
  9. from plugins import ita_plugin as turnstile
  10. from test.test_debug_ita_calendar_gate import booking_preflight_snapshot
  11. class PreflightWaitTests(TestCase):
  12. def run_wait(self, raw, **kwargs):
  13. page = SimpleNamespace(run_js=Mock(return_value=raw))
  14. with patch.object(session.time, 'monotonic', side_effect=[0, 0, 121]), \
  15. patch.object(session.time, 'sleep'):
  16. return session.wait_for_booking_preflight(page, script='offline', **kwargs)
  17. def test_timeout_distinguishes_token_and_button(self):
  18. for token, disabled, expected in (
  19. (False, False, 'turnstile_token_pending'),
  20. (True, True, 'avanti_disabled'),
  21. (False, True, 'turnstile_and_avanti_pending'),
  22. ):
  23. with self.subTest(expected=expected), redirect_stdout(io.StringIO()):
  24. with self.assertRaises(session.CalendarGateError) as raised:
  25. self.run_wait(booking_preflight_snapshot(
  26. turnstileTokenPresent=token, avantiDisabled=disabled))
  27. self.assertIn(expected, str(raised.exception))
  28. def test_production_default_diagnostic_survives_timeout_without_private_values(self):
  29. raw = booking_preflight_snapshot(turnstileTokenPresent=False)
  30. raw.update(token='PRIVATE-TOKEN', email='private@example.test',
  31. turnstileApiPresent=True, documentVisible=False)
  32. output = io.StringIO()
  33. with redirect_stdout(output), self.assertRaises(session.CalendarGateError):
  34. self.run_wait(raw)
  35. lines = [line.split('=', 1)[1] for line in output.getvalue().splitlines()
  36. if line.startswith('ITA_BOOK_PREFLIGHT_DIAGNOSTIC=')]
  37. self.assertTrue(lines)
  38. payload = json.loads(lines[-1])
  39. self.assertEqual(payload['outcome'], 'timeout')
  40. self.assertFalse(payload['turnstileTokenPresent'])
  41. self.assertFalse(payload['avantiDisabled'])
  42. self.assertTrue(payload['turnstileApiPresent'])
  43. self.assertNotIn('PRIVATE-TOKEN', output.getvalue())
  44. self.assertNotIn('private@example.test', output.getvalue())
  45. def test_ready_never_invokes_recovery(self):
  46. action = Mock()
  47. with redirect_stdout(io.StringIO()):
  48. self.run_wait(booking_preflight_snapshot(), wait_action=action)
  49. action.assert_not_called()
  50. def test_bad_structure_never_invokes_recovery(self):
  51. action = Mock()
  52. with redirect_stdout(io.StringIO()), self.assertRaises(session.CalendarGateError):
  53. self.run_wait(booking_preflight_snapshot(formPresent=False), wait_action=action)
  54. action.assert_not_called()
  55. def test_session_guard_runs_before_dom_read(self):
  56. current = Mock(side_effect=session.CalendarGateError('session changed'))
  57. page = SimpleNamespace(run_js=Mock())
  58. with self.assertRaises(session.CalendarGateError):
  59. session.wait_for_booking_preflight(page, script='offline', check_current=current)
  60. page.run_js.assert_not_called()
  61. def test_wait_action_does_not_substitute_for_a_new_ready_snapshot(self):
  62. raw = booking_preflight_snapshot(turnstileTokenPresent=False)
  63. action = Mock(return_value=True)
  64. with redirect_stdout(io.StringIO()), self.assertRaises(session.CalendarGateError):
  65. self.run_wait(raw, wait_action=action)
  66. action.assert_called_once()
  67. def test_bad_dynamic_boolean_is_not_hidden_by_wait_validation(self):
  68. for field in ('turnstileTokenPresent', 'avantiDisabled'):
  69. with self.subTest(field=field), redirect_stdout(io.StringIO()), \
  70. self.assertRaisesRegex(session.CalendarGateError, field):
  71. self.run_wait(booking_preflight_snapshot(**{field: 'private-string'}))
  72. def test_dom_exception_is_redacted(self):
  73. page = SimpleNamespace(run_js=Mock(side_effect=ValueError('PRIVATE_JS_VALUE')))
  74. output = io.StringIO()
  75. with redirect_stdout(output), self.assertRaisesRegex(session.CalendarGateError, 'read_failed') as raised:
  76. session.wait_for_booking_preflight(page, script='offline')
  77. self.assertNotIn('PRIVATE_JS_VALUE', str(raised.exception) + output.getvalue())
  78. def test_wait_can_observe_readiness_after_recovery(self):
  79. page = SimpleNamespace(run_js=Mock(side_effect=[
  80. booking_preflight_snapshot(turnstileTokenPresent=False), booking_preflight_snapshot()]))
  81. action = Mock()
  82. with patch.object(session.time, 'monotonic', side_effect=[0, 0, 1]), \
  83. patch.object(session.time, 'sleep'), redirect_stdout(io.StringIO()):
  84. result = session.wait_for_booking_preflight(page, script='offline', wait_action=action)
  85. self.assertTrue(result['turnstileTokenPresent'])
  86. self.assertEqual(page.run_js.call_count, 2)
  87. action.assert_called_once()
  88. class TurnstileRecoveryTests(TestCase):
  89. def setUp(self):
  90. self.page = SimpleNamespace(title='Booking - Prenot@Mi', refresh=Mock(), run_js=Mock())
  91. self.guard = Mock()
  92. self.recovery = turnstile.ItalyTurnstileRecovery(self.page, check_current=self.guard)
  93. self.helper = Mock()
  94. self.helper.click_verification_button.return_value = True
  95. self.factory = patch.object(turnstile, 'CloudflareBypasser', return_value=self.helper)
  96. self.factory_mock = self.factory.start()
  97. self.addCleanup(self.factory.stop)
  98. def attempt(self, elapsed=5, remaining=100, raw=None, stage=None):
  99. self.recovery(raw if raw is not None else booking_preflight_snapshot(turnstileTokenPresent=False),
  100. stage=stage or session.BookingPreflightStage.BEFORE_OTP_SEND,
  101. elapsed=elapsed, remaining=remaining)
  102. def test_reuses_vfs_widget_method_not_title_based_bypass(self):
  103. with redirect_stdout(io.StringIO()):
  104. self.attempt()
  105. self.factory_mock.assert_called_once_with(self.page, log=False)
  106. self.helper.click_verification_button.assert_called_once_with(is_dfs=False)
  107. self.helper.bypass.assert_not_called()
  108. self.page.refresh.assert_not_called()
  109. self.page.run_js.assert_not_called()
  110. self.assertEqual(self.guard.call_count, 2)
  111. def test_waits_initially_and_leaves_successful_widget_untouched(self):
  112. self.attempt(elapsed=4)
  113. self.attempt(elapsed=5, remaining=1)
  114. self.attempt(raw=booking_preflight_snapshot(avantiDisabled=True))
  115. self.attempt(raw=booking_preflight_snapshot())
  116. self.factory_mock.assert_not_called()
  117. def test_attempt_budget_and_interval_apply_even_if_control_cannot_be_clicked(self):
  118. self.helper.click_verification_button.return_value = False
  119. with redirect_stdout(io.StringIO()):
  120. for seconds in (5, 5.5, 10, 15, 16, 25, 35, 55, 100):
  121. self.attempt(elapsed=seconds)
  122. self.assertEqual(self.recovery.attempts, 3)
  123. self.assertEqual(self.helper.click_verification_button.call_count, 3)
  124. def test_stage_change_does_not_reset_total_attempt_budget(self):
  125. with redirect_stdout(io.StringIO()):
  126. for seconds in (5, 15, 25):
  127. self.attempt(elapsed=seconds)
  128. self.attempt(elapsed=5, stage=session.BookingPreflightStage.AFTER_OTP_SEND)
  129. self.assertEqual(self.helper.click_verification_button.call_count, 3)
  130. def test_wrong_form_or_missing_field_cannot_interact(self):
  131. for changes in ({'formPresent': False}, {'pathMatches': False}, {'turnstileCount': 2}):
  132. with self.subTest(changes=changes), self.assertRaises(session.CalendarGateError):
  133. self.attempt(raw=booking_preflight_snapshot(turnstileTokenPresent=False, **changes))
  134. self.factory_mock.assert_not_called()
  135. def test_session_change_prevents_interaction(self):
  136. self.guard.side_effect = session.CalendarGateError('session changed')
  137. with self.assertRaises(session.CalendarGateError):
  138. self.attempt()
  139. self.factory_mock.assert_not_called()
  140. def test_helper_errors_are_bounded_and_do_not_leak_browser_data(self):
  141. self.helper.click_verification_button.side_effect = RuntimeError('PRIVATE_BROWSER_DATA')
  142. output = io.StringIO()
  143. with redirect_stdout(output):
  144. self.attempt()
  145. payload = json.loads(output.getvalue().split('=', 1)[1])
  146. self.assertTrue(payload['helperFailed'])
  147. self.assertFalse(payload['clicked'])
  148. self.assertNotIn('PRIVATE_BROWSER_DATA', output.getvalue())
  149. self.assertEqual(self.recovery.attempts, 1)
  150. def test_interaction_success_alone_cannot_release_preflight(self):
  151. page = SimpleNamespace(run_js=Mock(return_value=booking_preflight_snapshot(turnstileTokenPresent=False)))
  152. with patch.object(session.time, 'monotonic', side_effect=[0, 5, 121]), \
  153. patch.object(session.time, 'sleep'), redirect_stdout(io.StringIO()):
  154. with self.assertRaisesRegex(session.CalendarGateError, 'turnstile_token_pending'):
  155. session.wait_for_booking_preflight(page, script='offline', wait_action=self.recovery)
  156. self.helper.click_verification_button.assert_called_once()