test_refresh_cookies.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import asyncio
  2. import os
  3. import re
  4. import shutil
  5. import subprocess
  6. import tempfile
  7. import warnings
  8. from datetime import date, timedelta
  9. from importlib.resources import files
  10. from pathlib import Path
  11. import pytest
  12. from room_cal._utils import data_home as _data_home, get_config
  13. from room_cal.service_api.types import ServiceAuthError
  14. def _ts_dir() -> Path:
  15. return Path(str(files('room_cal.service_api').joinpath('typescript')))
  16. def _browsers_path() -> Path:
  17. return _data_home() / '.playwright-browsers'
  18. def _npm_env() -> dict:
  19. env = os.environ.copy()
  20. env.setdefault('ROOM_CAL_DATA_HOME', str(_data_home()))
  21. env['PLAYWRIGHT_BROWSERS_PATH'] = str(_browsers_path())
  22. return env
  23. def _npm_run(script: str, timeout: int, extra_env: dict | None = None) -> subprocess.CompletedProcess:
  24. ts_dir = _ts_dir()
  25. if not (ts_dir / 'node_modules').exists():
  26. subprocess.run(['npm', 'install'], cwd=ts_dir, check=True, capture_output=True)
  27. env = _npm_env()
  28. if extra_env:
  29. env.update(extra_env)
  30. try:
  31. return subprocess.run(
  32. ['npm', 'run', script],
  33. cwd=ts_dir,
  34. env=env,
  35. capture_output=True,
  36. text=True,
  37. timeout=timeout,
  38. )
  39. except subprocess.TimeoutExpired as exc:
  40. pytest.fail(f'npm run {script} timed out after {exc.timeout}s')
  41. except Exception as exc:
  42. pytest.fail(f'Failed to launch npm run {script}: {exc}')
  43. @pytest.fixture(scope='session')
  44. def chrome_installed():
  45. result = _npm_run('install-browsers', timeout=30)
  46. if result.returncode != 0:
  47. pytest.fail(
  48. f'npm run install-browsers failed (exit {result.returncode})\n'
  49. f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  50. )
  51. browsers = _browsers_path()
  52. chromium_dirs = [p for p in browsers.iterdir() if p.is_dir() and 'chromium' in p.name] if browsers.exists() else []
  53. if not chromium_dirs:
  54. pytest.fail(f'install-browsers exited 0 but no chromium dirs found in {browsers}')
  55. def test_refresh_all_flags_match_config():
  56. """ENABLED flags in refresh-all.ts must match disabled in config.json, with full coverage."""
  57. ts_path = _ts_dir() / 'scripts' / 'refresh-all.ts'
  58. src = ts_path.read_text()
  59. # Parse: ENABLED: Record<string, boolean> = { key: true/false, ... }
  60. block = re.search(r'const ENABLED[^=]*=\s*\{([^}]+)\}', src)
  61. assert block, 'Could not find ENABLED block in refresh-all.ts'
  62. ts_flags: dict[str, bool] = {}
  63. for m in re.finditer(r'(\w+)\s*:\s*(true|false)', block.group(1)):
  64. ts_flags[m.group(1)] = m.group(2) == 'true'
  65. cfg_services = get_config().services
  66. cfg_keys = set(cfg_services.keys())
  67. ts_keys = set(ts_flags.keys())
  68. missing = cfg_keys - ts_keys
  69. assert not missing, f'Services in config.json missing from refresh-all.ts ENABLED: {missing}'
  70. extra = ts_keys - cfg_keys
  71. assert not extra, f'Services in refresh-all.ts ENABLED not in config.json: {extra}'
  72. mismatches = {
  73. k for k in cfg_keys
  74. if ts_flags[k] != (not cfg_services[k].disabled)
  75. }
  76. assert not mismatches, (
  77. f'ENABLED flags in refresh-all.ts do not match config.json disabled for: {mismatches}\n'
  78. + '\n'.join(f' {k}: ts={ts_flags[k]} config_disabled={cfg_services[k].disabled}' for k in sorted(mismatches))
  79. )
  80. def test_install_chrome(chrome_installed):
  81. """npm run install-browsers puts Chromium binaries in the expected location."""
  82. def test_refresh_cookies_headless(chrome_installed):
  83. """Cookie-refresh machinery: Chromium must launch and write cookies.
  84. Pass — cookies updated and API call succeeds.
  85. Pass + warn — script ran correctly but session is stale (exit 2), cookies
  86. unchanged, or API auth failed after writing cookies.
  87. Fail — unexpected error or non-zero exit.
  88. """
  89. data = _data_home()
  90. airbnb_env = data / 'airbnb.env'
  91. booking_env = data / 'booking.env'
  92. before = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  93. result = _npm_run('refresh-all', timeout=60, extra_env={'HEADLESS': '1'})
  94. output = f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  95. if result.returncode == 2:
  96. warnings.warn(
  97. 'Session is stale — run `refresh-creds` to re-authenticate.\n' + output,
  98. UserWarning,
  99. stacklevel=1,
  100. )
  101. return
  102. if result.returncode != 0:
  103. pytest.fail(f'npm run refresh-all exited {result.returncode}\n' + output)
  104. after = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  105. if not any(after[p] != before[p] for p in (airbnb_env, booking_env)):
  106. warnings.warn(
  107. 'refresh-all exited 0 but neither airbnb.env nor booking.env changed.',
  108. UserWarning,
  109. stacklevel=1,
  110. )
  111. return
  112. try:
  113. from room_cal.service_api import ServiceAPI
  114. api = ServiceAPI()
  115. asyncio.run(api.get_prices(date.today() + timedelta(days=1)))
  116. except ServiceAuthError as exc:
  117. warnings.warn(
  118. f'Cookies were updated but API auth failed ({exc}); session may be invalid.',
  119. UserWarning,
  120. stacklevel=1,
  121. )
  122. # ---------------------------------------------------------------------------
  123. # Live auto-login test — opt-in only, not run in normal CI
  124. # Set BOOKING_LIVE_TEST=1 to enable.
  125. # Requires BOOKING_EMAIL and BOOKING_PASSWORD in booking.env.
  126. # ---------------------------------------------------------------------------
  127. def _booking_env_credentials() -> tuple[str, str]:
  128. """Return (email, password) from booking.env, or ('', '') if absent."""
  129. env_path = _data_home() / 'booking.env'
  130. if not env_path.exists():
  131. return '', ''
  132. text = env_path.read_text()
  133. email = next((m.group(1) for m in [re.search(r'^BOOKING_EMAIL=(\S+)', text, re.M)] if m), '')
  134. password = next((m.group(1) for m in [re.search(r'^BOOKING_PASSWORD=(\S+)', text, re.M)] if m), '')
  135. return email, password
  136. @pytest.mark.skipif(
  137. not os.environ.get('BOOKING_LIVE_TEST'),
  138. reason='Set BOOKING_LIVE_TEST=1 to run live Booking.com auto-login test',
  139. )
  140. def test_booking_auto_login(chrome_installed):
  141. """Full auto-login flow from an empty session.
  142. Wipes the Booking.com Playwright profile and blanks the session credentials
  143. in a temporary DATA_HOME, then runs refresh-booking. Asserts that fresh
  144. cookies and a session token are written, and that the API can make a live
  145. calendar call with them.
  146. """
  147. email, password = _booking_env_credentials()
  148. if not email or not password:
  149. pytest.skip('BOOKING_EMAIL and BOOKING_PASSWORD must be set in booking.env')
  150. real_data = _data_home()
  151. booking_env_src = real_data / 'booking.env'
  152. with tempfile.TemporaryDirectory(prefix='room_cal_login_test_') as tmp:
  153. tmp_path = Path(tmp)
  154. # Copy booking.env into the temp DATA_HOME, stripping session credentials
  155. # so the script has no valid session to reuse.
  156. src_text = booking_env_src.read_text() if booking_env_src.exists() else ''
  157. stripped = re.sub(r'^(BOOKING_COOKIES|BOOKING_SESSION|BOOKING_CSRF_TOKEN)=.*$', r'\1=', src_text, flags=re.M)
  158. (tmp_path / 'booking.env').write_text(stripped)
  159. # Copy browsers so the test doesn't re-download Chromium.
  160. browsers_src = _browsers_path()
  161. if browsers_src.exists():
  162. shutil.copytree(browsers_src, tmp_path / '.playwright-browsers', symlinks=True)
  163. # Clear the login-attempts counter so rate limiting doesn't interfere.
  164. attempts_file = tmp_path / 'booking-login-attempts.json'
  165. if attempts_file.exists():
  166. attempts_file.unlink()
  167. result = _npm_run('refresh-booking', timeout=180, extra_env={
  168. 'ROOM_CAL_DATA_HOME': str(tmp_path),
  169. 'PLAYWRIGHT_BROWSERS_PATH': str(tmp_path / '.playwright-browsers'),
  170. })
  171. output = f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  172. assert result.returncode == 0, f'refresh-booking exited {result.returncode}\n{output}'
  173. new_text = (tmp_path / 'booking.env').read_text()
  174. new_cookies = re.search(r'^BOOKING_COOKIES=(\S+)', new_text, re.M)
  175. new_session = re.search(r'^BOOKING_SESSION=(\S+)', new_text, re.M)
  176. assert new_cookies and new_cookies.group(1), f'No BOOKING_COOKIES written\n{output}'
  177. assert new_session and new_session.group(1), f'No BOOKING_SESSION written\n{output}'
  178. # Copy fresh credentials into the real DATA_HOME so the API call below uses them.
  179. booking_env_src.write_text(new_text)
  180. from room_cal.service_api import ServiceAPI
  181. api = ServiceAPI()
  182. prices = asyncio.run(api.get_prices(date.today() + timedelta(days=1)))
  183. booking_prices = {d: p for d, p in prices.items() if d}
  184. assert booking_prices, 'API returned no prices after auto-login — session may not have been accepted'