test_refresh_cookies.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. import asyncio
  2. import os
  3. import re
  4. import subprocess
  5. import warnings
  6. from datetime import date, timedelta
  7. from importlib.resources import files
  8. from pathlib import Path
  9. import pytest
  10. from room_cal._utils import data_home as _data_home, get_config
  11. from room_cal.service_api.types import ServiceAuthError
  12. def _ts_dir() -> Path:
  13. return Path(str(files('room_cal.service_api').joinpath('typescript')))
  14. def _browsers_path() -> Path:
  15. return _data_home() / '.playwright-browsers'
  16. def _npm_env() -> dict:
  17. env = os.environ.copy()
  18. env.setdefault('ROOM_CAL_DATA_HOME', str(_data_home()))
  19. env['PLAYWRIGHT_BROWSERS_PATH'] = str(_browsers_path())
  20. return env
  21. def _npm_run(script: str, timeout: int, extra_env: dict | None = None) -> subprocess.CompletedProcess:
  22. ts_dir = _ts_dir()
  23. if not (ts_dir / 'node_modules').exists():
  24. subprocess.run(['npm', 'install'], cwd=ts_dir, check=True, capture_output=True)
  25. env = _npm_env()
  26. if extra_env:
  27. env.update(extra_env)
  28. try:
  29. return subprocess.run(
  30. ['npm', 'run', script],
  31. cwd=ts_dir,
  32. env=env,
  33. capture_output=True,
  34. text=True,
  35. timeout=timeout,
  36. )
  37. except subprocess.TimeoutExpired as exc:
  38. pytest.fail(f'npm run {script} timed out after {exc.timeout}s')
  39. except Exception as exc:
  40. pytest.fail(f'Failed to launch npm run {script}: {exc}')
  41. @pytest.fixture(scope='session')
  42. def chrome_installed():
  43. result = _npm_run('install-browsers', timeout=30)
  44. if result.returncode != 0:
  45. pytest.fail(
  46. f'npm run install-browsers failed (exit {result.returncode})\n'
  47. f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  48. )
  49. browsers = _browsers_path()
  50. chromium_dirs = [p for p in browsers.iterdir() if p.is_dir() and 'chromium' in p.name] if browsers.exists() else []
  51. if not chromium_dirs:
  52. pytest.fail(f'install-browsers exited 0 but no chromium dirs found in {browsers}')
  53. def test_refresh_all_flags_match_config():
  54. """ENABLED flags in refresh-all.ts must match disabled in config.json, with full coverage."""
  55. ts_path = _ts_dir() / 'scripts' / 'refresh-all.ts'
  56. src = ts_path.read_text()
  57. # Parse: ENABLED: Record<string, boolean> = { key: true/false, ... }
  58. block = re.search(r'const ENABLED[^=]*=\s*\{([^}]+)\}', src)
  59. assert block, 'Could not find ENABLED block in refresh-all.ts'
  60. ts_flags: dict[str, bool] = {}
  61. for m in re.finditer(r'(\w+)\s*:\s*(true|false)', block.group(1)):
  62. ts_flags[m.group(1)] = m.group(2) == 'true'
  63. cfg_services = get_config().services
  64. cfg_keys = set(cfg_services.keys())
  65. ts_keys = set(ts_flags.keys())
  66. missing = cfg_keys - ts_keys
  67. assert not missing, f'Services in config.json missing from refresh-all.ts ENABLED: {missing}'
  68. extra = ts_keys - cfg_keys
  69. assert not extra, f'Services in refresh-all.ts ENABLED not in config.json: {extra}'
  70. mismatches = {
  71. k for k in cfg_keys
  72. if ts_flags[k] != (not cfg_services[k].disabled)
  73. }
  74. assert not mismatches, (
  75. f'ENABLED flags in refresh-all.ts do not match config.json disabled for: {mismatches}\n'
  76. + '\n'.join(f' {k}: ts={ts_flags[k]} config_disabled={cfg_services[k].disabled}' for k in sorted(mismatches))
  77. )
  78. def test_install_chrome(chrome_installed):
  79. """npm run install-browsers puts Chromium binaries in the expected location."""
  80. def test_refresh_cookies_headless(chrome_installed):
  81. """Cookie-refresh machinery: Chromium must launch and write cookies.
  82. Pass — cookies updated and API call succeeds.
  83. Pass + warn — script ran correctly but session is stale (exit 2), cookies
  84. unchanged, or API auth failed after writing cookies.
  85. Fail — unexpected error or non-zero exit.
  86. """
  87. data = _data_home()
  88. airbnb_env = data / 'airbnb.env'
  89. booking_env = data / 'booking.env'
  90. before = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  91. result = _npm_run('refresh-all', timeout=60, extra_env={'HEADLESS': '1'})
  92. output = f'stdout:\n{result.stdout}\nstderr:\n{result.stderr}'
  93. if result.returncode == 2:
  94. warnings.warn(
  95. 'Session is stale — run `refresh-creds` to re-authenticate.\n' + output,
  96. UserWarning,
  97. stacklevel=1,
  98. )
  99. return
  100. if result.returncode != 0:
  101. pytest.fail(f'npm run refresh-all exited {result.returncode}\n' + output)
  102. after = {p: p.read_text() if p.exists() else None for p in (airbnb_env, booking_env)}
  103. if not any(after[p] != before[p] for p in (airbnb_env, booking_env)):
  104. warnings.warn(
  105. 'refresh-all exited 0 but neither airbnb.env nor booking.env changed.',
  106. UserWarning,
  107. stacklevel=1,
  108. )
  109. return
  110. try:
  111. from room_cal.service_api import ServiceAPI
  112. api = ServiceAPI()
  113. asyncio.run(api.get_prices(date.today() + timedelta(days=1)))
  114. except ServiceAuthError as exc:
  115. warnings.warn(
  116. f'Cookies were updated but API auth failed ({exc}); session may be invalid.',
  117. UserWarning,
  118. stacklevel=1,
  119. )