test_refresh_cookies.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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_install_chrome(chrome_installed):
  56. """npm run install-browsers puts Chromium binaries in the expected location."""
  57. def test_refresh_cookies_headless(chrome_installed):
  58. """Cookie-refresh machinery: Chromium must launch and write cookies.
  59. Pass — cookies updated and API call succeeds.
  60. Pass + warn — script ran correctly but session is stale (exit 2), cookies
  61. unchanged, or API auth failed after writing cookies.
  62. Fail — unexpected error or non-zero exit.
  63. """
  64. data = _data_home()
  65. airbnb_env = data / 'airbnb.env'
  66. booking_env = data / 'booking.env'
  67. before = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  68. result = _npm_run('refresh-all', timeout=60, extra_env={'HEADLESS': '1'})
  69. output = f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  70. if result.returncode == 2:
  71. warnings.warn(
  72. 'Session is stale — run `refresh-creds` to re-authenticate.\n' + output,
  73. UserWarning,
  74. stacklevel=1,
  75. )
  76. return
  77. if result.returncode != 0:
  78. pytest.fail(f'npm run refresh-all exited {result.returncode}\n' + output)
  79. after = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  80. if not any(after[p] != before[p] for p in (airbnb_env, booking_env)):
  81. warnings.warn(
  82. 'refresh-all exited 0 but neither airbnb.env nor booking.env changed.',
  83. UserWarning,
  84. stacklevel=1,
  85. )
  86. return
  87. try:
  88. from room_cal.service_api import ServiceAPI
  89. api = ServiceAPI()
  90. asyncio.run(api.get_prices(date.today() + timedelta(days=1)))
  91. except ServiceAuthError as exc:
  92. warnings.warn(
  93. f'Cookies were updated but API auth failed ({exc}); session may be invalid.',
  94. UserWarning,
  95. stacklevel=1,
  96. )
  97. # ---------------------------------------------------------------------------
  98. # Live auto-login test — opt-in only, not run in normal CI
  99. # Set BOOKING_LIVE_TEST=1 to enable.
  100. # Requires BOOKING_EMAIL and BOOKING_PASSWORD in booking.env.
  101. # ---------------------------------------------------------------------------
  102. def _booking_env_credentials() -> tuple[str, str]:
  103. """Return (email, password) from booking.env, or ('', '') if absent."""
  104. env_path = _data_home() / 'booking.env'
  105. if not env_path.exists():
  106. return '', ''
  107. text = env_path.read_text()
  108. email = next((m.group(1) for m in [re.search(r'^BOOKING_EMAIL=(\S+)', text, re.M)] if m), '')
  109. password = next((m.group(1) for m in [re.search(r'^BOOKING_PASSWORD=(\S+)', text, re.M)] if m), '')
  110. return email, password
  111. @pytest.mark.skipif(
  112. not os.environ.get('BOOKING_LIVE_TEST'),
  113. reason='Set BOOKING_LIVE_TEST=1 to run live Booking.com auto-login test',
  114. )
  115. def test_booking_auto_login(chrome_installed):
  116. """Full auto-login flow from an empty session.
  117. Wipes the Booking.com Playwright profile and blanks the session credentials
  118. in a temporary DATA_HOME, then runs refresh-booking. Asserts that fresh
  119. cookies and a session token are written, and that the API can make a live
  120. calendar call with them.
  121. """
  122. email, password = _booking_env_credentials()
  123. if not email or not password:
  124. pytest.skip('BOOKING_EMAIL and BOOKING_PASSWORD must be set in booking.env')
  125. real_data = _data_home()
  126. booking_env_src = real_data / 'booking.env'
  127. with tempfile.TemporaryDirectory(prefix='room_cal_login_test_') as tmp:
  128. tmp_path = Path(tmp)
  129. # Copy booking.env into the temp DATA_HOME, stripping session credentials
  130. # so the script has no valid session to reuse.
  131. src_text = booking_env_src.read_text() if booking_env_src.exists() else ''
  132. stripped = re.sub(r'^(BOOKING_COOKIES|BOOKING_SESSION|BOOKING_CSRF_TOKEN)=.*$', r'\1=', src_text, flags=re.M)
  133. (tmp_path / 'booking.env').write_text(stripped)
  134. # Copy browsers so the test doesn't re-download Chromium.
  135. browsers_src = _browsers_path()
  136. if browsers_src.exists():
  137. shutil.copytree(browsers_src, tmp_path / '.playwright-browsers', symlinks=True)
  138. # Clear the login-attempts counter so rate limiting doesn't interfere.
  139. attempts_file = tmp_path / 'booking-login-attempts.json'
  140. if attempts_file.exists():
  141. attempts_file.unlink()
  142. result = _npm_run('refresh-booking', timeout=180, extra_env={
  143. 'ROOM_CAL_DATA_HOME': str(tmp_path),
  144. 'PLAYWRIGHT_BROWSERS_PATH': str(tmp_path / '.playwright-browsers'),
  145. })
  146. output = f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  147. assert result.returncode == 0, f'refresh-booking exited {result.returncode}\n{output}'
  148. new_text = (tmp_path / 'booking.env').read_text()
  149. new_cookies = re.search(r'^BOOKING_COOKIES=(\S+)', new_text, re.M)
  150. new_session = re.search(r'^BOOKING_SESSION=(\S+)', new_text, re.M)
  151. assert new_cookies and new_cookies.group(1), f'No BOOKING_COOKIES written\n{output}'
  152. assert new_session and new_session.group(1), f'No BOOKING_SESSION written\n{output}'
  153. # Copy fresh credentials into the real DATA_HOME so the API call below uses them.
  154. booking_env_src.write_text(new_text)
  155. from room_cal.service_api import ServiceAPI
  156. api = ServiceAPI()
  157. prices = asyncio.run(api.get_prices(date.today() + timedelta(days=1)))
  158. booking_prices = {d: p for d, p in prices.items() if d}
  159. assert booking_prices, 'API returned no prices after auto-login — session may not have been accepted'