"""Regressions for the Ravin portal and its October 2026 Moodle theme.""" import email.message import io import json import sys import tempfile import unittest from contextlib import redirect_stderr from pathlib import Path from types import SimpleNamespace from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src')) from ravin.auth import _capture_browser_session, _authenticated_browser_session, _select_login_tab from ravin.client import MoodleClient from ravin.models import MoodleError class BrowserUpdateTests(unittest.TestCase): def capture(self, *, captcha=False, existing_session=False, new_tab=False, invalid_key=False, use_zen=False): test = self class Element: def __init__(self, visible): self.visible = visible def is_displayed(self): return self.visible def get_attribute(self, name): return 'https://lms.example/moodle/login_student_user/162/' if name == 'href' else None def click(self): driver.launch() class Driver: current_url = 'about:blank' awaiting_captcha = captcha quit_called = False launches = 0 def __init__(self): self.window_handles = ['portal'] self.current_window_handle = 'portal' self.switch_to = SimpleNamespace(window=self.switch_window) def switch_window(self, handle): self.current_window_handle = handle self.current_url = 'https://training.example/my/' def launch(self): self.launches += 1 test.assertEqual(self.launches, 1, 'SSO link must only be activated once') if new_tab: self.window_handles.append('moodle') elif invalid_key: self.current_url = 'https://training.example/auth/userkey/login.php?key=synthetic' else: self.current_url = 'https://training.example/my/' def get(self, url): test.assertNotIn('login_student_user', url, 'Use the portal link instead of direct navigation') self.current_url = url def execute_script(self, script, *args): if script == 'arguments[0].click();': args[0].click() return None test.assertFalse(args, 'CAPTCHA form must not be auto-submitted') if 'navigator.userAgent' in script: return 'Synthetic Browser/1' test.assertNotIn('logout.php', script) test.assertIn('M.cfg.sesskey', script) return self.current_url == 'https://training.example/my/' or ( existing_session and self.current_url == 'https://training.example/my/courses.php' ) def find_elements(self, by, selector): if 'invalidkey' in selector: return [Element(True)] if '/auth/userkey/' in self.current_url else [] if 'login_student_user' in selector: return [] if self.awaiting_captcha else [Element(False)] if 'captcha' in selector and self.awaiting_captcha: return [Element(True)] return [] def get_cookies(self): return [{'name': 'MoodleSession', 'value': 'synthetic'}] def quit(self): self.quit_called = True driver = Driver() output = io.StringIO() with tempfile.TemporaryDirectory() as directory: args = SimpleNamespace( site='https://training.example', login_url='https://lms.example/', browser_executable=None, browser_profile=Path(directory) / 'profile', login_timeout=30, env_values={'RAVIN_USERNAME': 'synthetic', 'RAVIN_PASSWORD': 'synthetic'}, ) with patch('ravin.auth._find_browser_executable', return_value=Path('/synthetic/zen' if use_zen else '/synthetic/chrome')), \ patch('selenium.webdriver.Chrome', return_value=driver), \ patch('selenium.webdriver.Firefox', return_value=driver), \ patch('selenium.webdriver.firefox.service.Service'), \ patch('ravin.auth._capture_chromium_session', return_value=('Synthetic Browser/1', 'MoodleSession=synthetic')) as fallback, \ patch('ravin.auth.time.sleep', side_effect=lambda _: setattr(driver, 'awaiting_captcha', False)), \ redirect_stderr(output): if invalid_key and not use_zen: with self.assertRaisesRegex(MoodleError, 'invalidkey'): _capture_browser_session(args) self.assertTrue(driver.quit_called) self.assertEqual(driver.launches, 1) self.assertNotIn('key=synthetic', output.getvalue()) return output.getvalue() result = _capture_browser_session(args) if invalid_key and use_zen: fallback.assert_called_once_with(args, [{'name': 'MoodleSession', 'value': 'synthetic'}]) else: fallback.assert_not_called() self.assertTrue(driver.quit_called) self.assertEqual(result, ('Synthetic Browser/1', 'MoodleSession=synthetic')) self.assertEqual(driver.launches, 0 if existing_session else 1) return output.getvalue() def test_hidden_launch_link_and_theme_without_logout_link(self): self.capture() def test_captcha_waits_for_human_without_submitting_stored_credentials(self): self.assertIn('CAPTCHA detected', self.capture(captcha=True)) def test_existing_profile_session_skips_portal_launch(self): self.capture(existing_session=True) def test_new_login_tab_is_followed_without_relaunching(self): self.capture(new_tab=True) def test_invalid_key_is_reported_without_replaying_the_link(self): self.capture(invalid_key=True) def test_zen_invalid_key_switches_engine_with_portal_session(self): self.assertIn('switching to Chromium', self.capture(invalid_key=True, use_zen=True)) def test_session_from_another_origin_is_not_captured(self): driver = SimpleNamespace(current_url='https://another.example/my/') self.assertIsNone(_authenticated_browser_session(driver, 'https://training.example')) def test_closed_browser_reports_actionable_error(self): with self.assertRaisesRegex(MoodleError, 'browser was closed'): _select_login_tab(SimpleNamespace(window_handles=[]), {'portal'}) def test_closed_active_tab_switches_to_remaining_tab(self): from selenium.common.exceptions import NoSuchWindowException class Driver: window_handles = ['moodle'] @property def current_window_handle(self): raise NoSuchWindowException() switched = [] driver = Driver() driver.switch_to = SimpleNamespace(window=switched.append) self.assertEqual(_select_login_tab(driver, {'moodle', 'portal'}), {'moodle'}) self.assertEqual(switched, ['moodle']) class ScanUpdateTests(unittest.TestCase): def setUp(self): self.client = MoodleClient('https://training.example', cookie_header='MoodleSession=synthetic') def test_browser_session_accepts_new_theme_without_logout_link(self): page = '' with patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)): self.assertEqual(self.client.authenticate(), 'browser-session') def test_guest_session_with_sesskey_is_rejected(self): for user in (0, -1, None): page = '' with self.subTest(user=user), patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)): with self.assertRaises(MoodleError): self.client.authenticate() def test_login_or_unrecognized_page_cannot_become_empty_course(self): for page, url in ( ('
', 'https://lms.example/employee/user/login/'), ('