From 65e1e2d3c9a8453e9563178cb9743f7cda494382 Mon Sep 17 00:00:00 2001 From: zackees Date: Sun, 12 Apr 2026 07:42:20 -0700 Subject: [PATCH] fix(tests): re-enable skipped tests from Rust migration (#39) - Delete MicrophoneHttpsIntegrationTest class (HTTPS dropped in PR #48) - Keep MicrophoneDemoValidationTest for micdemo.html content validation - Remove #39 tracking references from skip markers - Add test_http_server.py: HTTP smoke test using the Rust CLI binary - Fix pre-existing pyright errors (playwright import suppressions) - Fix pre-existing black formatting in playwright module --- src/fastled/playwright/playwright_browser.py | 4 +- tests/integration/test_animartrix_e2e.py | 2 +- tests/integration/test_microphone_https.py | 294 +------------------ tests/unit/test_cli.py | 2 +- tests/unit/test_http_server.py | 167 +++++++++++ 5 files changed, 179 insertions(+), 290 deletions(-) create mode 100644 tests/unit/test_http_server.py diff --git a/src/fastled/playwright/playwright_browser.py b/src/fastled/playwright/playwright_browser.py index 1f980e47..bb66d74c 100644 --- a/src/fastled/playwright/playwright_browser.py +++ b/src/fastled/playwright/playwright_browser.py @@ -135,7 +135,9 @@ async def start(self) -> None: """Start the Playwright browser.""" if self.browser is None and self.context is None: - from playwright.async_api import async_playwright + from playwright.async_api import ( # type: ignore[reportMissingImports] + async_playwright, + ) self.playwright = async_playwright() playwright = await self.playwright.start() diff --git a/tests/integration/test_animartrix_e2e.py b/tests/integration/test_animartrix_e2e.py index f980da06..05dd8e62 100644 --- a/tests/integration/test_animartrix_e2e.py +++ b/tests/integration/test_animartrix_e2e.py @@ -17,7 +17,7 @@ from pathlib import Path import pytest # type: ignore[reportMissingImports] -from playwright.async_api import async_playwright +from playwright.async_api import async_playwright # type: ignore[reportMissingImports] from fastled import Test diff --git a/tests/integration/test_microphone_https.py b/tests/integration/test_microphone_https.py index 65680398..a8e245d3 100644 --- a/tests/integration/test_microphone_https.py +++ b/tests/integration/test_microphone_https.py @@ -1,298 +1,18 @@ """ -Integration tests for microphone access over HTTPS vs HTTP. +Validation tests for the microphone demo HTML file. -These tests verify that: -1. Microphone API (getUserMedia) is available over HTTPS -2. Microphone API is blocked/unavailable over HTTP in secure contexts -3. The server correctly serves content over HTTPS with SSL certificates -4. HTTP fallback mode explicitly disables secure features +These tests verify that micdemo.html exists and has the expected content +(getUserMedia API usage, error handling, etc.). -Note: These tests use Playwright to run actual browser automation tests. +Note: HTTPS-specific browser integration tests were removed after the +HTTPS server was dropped in favour of HTTP-only (PR #48). Localhost is +a secure context in all modern browsers, so the microphone API works +over plain HTTP on localhost. """ -import asyncio -import random -import time import unittest from pathlib import Path -import pytest -from playwright.async_api import async_playwright - -from fastled import Test - -HERE = Path(__file__).parent -# Use the micdemo.html file for testing microphone access -DEMO_DIR = Path(__file__).parent.parent.parent / "demo" -MICDEMO_HTML = DEMO_DIR / "micdemo.html" - -# Use random ports to avoid conflicts -BASE_PORT = random.randint(9000, 9100) - - -@pytest.mark.skip(reason="HTTPS server timeout on CI — tracked in #39") -class MicrophoneHttpsIntegrationTest(unittest.TestCase): - """Integration tests for microphone access requiring HTTPS.""" - - def test_microphone_available_over_https(self): - """Test that navigator.mediaDevices.getUserMedia is available over HTTPS. - - This test: - 1. Starts an HTTPS server with SSL certificates - 2. Launches a Playwright browser - 3. Navigates to the HTTPS localhost URL serving micdemo.html - 4. Verifies that navigator.mediaDevices.getUserMedia exists - 5. Verifies that the page is served in a secure context - """ - # Run the async test - asyncio.run(self._test_microphone_available_over_https_async()) - - async def _test_microphone_available_over_https_async(self): - """Async implementation of HTTPS microphone availability test.""" - port = BASE_PORT - # Start HTTPS server - proc = Test.spawn_http_server( - DEMO_DIR, - port=port, - open_browser=False, - enable_https=True, - ) - - try: - # Wait for server to start - time.sleep(2) - - server_url = f"https://localhost:{port}/micdemo.html" - - # Launch Playwright browser - async with async_playwright() as p: - # Launch with args to accept self-signed certificates - browser = await p.chromium.launch( - headless=True, - args=[ - "--ignore-certificate-errors", - "--allow-insecure-localhost", - ], - ) - - try: - context = await browser.new_context( - ignore_https_errors=True, # Accept self-signed cert - ) - page = await context.new_page() - - # Navigate to HTTPS URL - response = await page.goto( - server_url, wait_until="domcontentloaded", timeout=10000 - ) - - # Verify we got a successful response - self.assertIsNotNone(response, "Failed to load HTTPS page") - assert response is not None # Type narrowing for pyright - self.assertEqual( - response.status, - 200, - f"Expected 200 status, got {response.status}", - ) - - # Check if we're in a secure context - is_secure_context = await page.evaluate("window.isSecureContext") - self.assertTrue( - is_secure_context, - "Page should be in a secure context over HTTPS", - ) - - # Check if mediaDevices API exists - has_media_devices = await page.evaluate( - "typeof navigator.mediaDevices !== 'undefined' && " - "typeof navigator.mediaDevices.getUserMedia === 'function'" - ) - self.assertTrue( - has_media_devices, - "navigator.mediaDevices.getUserMedia should be available over HTTPS", - ) - - # Check protocol - protocol = await page.evaluate("window.location.protocol") - self.assertEqual( - protocol, "https:", f"Expected https: protocol, got {protocol}" - ) - - print(f"✅ HTTPS microphone API test passed: {server_url}") - - finally: - await browser.close() - - finally: - # Stop the server - proc.terminate() - time.sleep(1) - - def test_microphone_context_over_http(self): - """Test that secure context is not available over plain HTTP. - - This test: - 1. Starts an HTTP server (HTTPS disabled) - 2. Launches a Playwright browser - 3. Navigates to the HTTP localhost URL - 4. Verifies that the page is NOT in a secure context - 5. Documents the expected behavior for mediaDevices API over HTTP - - Note: localhost is treated as a secure context by some browsers even over HTTP, - but the getUserMedia API may still be restricted or require additional permissions. - """ - # Run the async test - asyncio.run(self._test_microphone_context_over_http_async()) - - async def _test_microphone_context_over_http_async(self): - """Async implementation of HTTP microphone context test.""" - port = BASE_PORT + 10 - # Start HTTP server (disable HTTPS) - proc = Test.spawn_http_server( - DEMO_DIR, - port=port, - open_browser=False, - enable_https=False, # Force HTTP mode - ) - - try: - # Wait for server to start - time.sleep(2) - - server_url = f"http://localhost:{port}/micdemo.html" - - # Launch Playwright browser - async with async_playwright() as p: - browser = await p.chromium.launch(headless=True) - - try: - context = await browser.new_context() - page = await context.new_page() - - # Navigate to HTTP URL - response = await page.goto( - server_url, wait_until="domcontentloaded", timeout=10000 - ) - - # Verify we got a successful response - self.assertIsNotNone(response, "Failed to load HTTP page") - assert response is not None # Type narrowing for pyright - self.assertEqual( - response.status, - 200, - f"Expected 200 status, got {response.status}", - ) - - # Check protocol - protocol = await page.evaluate("window.location.protocol") - self.assertEqual( - protocol, "http:", f"Expected http: protocol, got {protocol}" - ) - - # Note: localhost is often treated as a "potentially trustworthy" origin - # even over HTTP, so isSecureContext might be true - is_secure_context = await page.evaluate("window.isSecureContext") - - # Check if mediaDevices API exists - has_media_devices = await page.evaluate( - "typeof navigator.mediaDevices !== 'undefined' && " - "typeof navigator.mediaDevices.getUserMedia === 'function'" - ) - - # Document the findings - print(f"📊 HTTP context test results for {server_url}:") - print(f" - Protocol: {protocol}") - print(f" - isSecureContext: {is_secure_context}") - print(f" - mediaDevices API available: {has_media_devices}") - - # The key insight: even if the API exists, actual microphone permission - # requests may be blocked or require user interaction. The browser - # may treat localhost specially. - if is_secure_context: - print( - " â„šī¸ Note: localhost is treated as secure context by browsers" - ) - - print(f"✅ HTTP context documentation test passed: {server_url}") - - finally: - await browser.close() - - finally: - # Stop the server - proc.terminate() - time.sleep(1) - - def test_https_certificate_validation(self): - """Test that HTTPS server properly loads and uses SSL certificates. - - This test: - 1. Starts an HTTPS server - 2. Connects with Playwright - 3. Verifies the connection uses HTTPS - 4. Validates that the server has proper SSL certificate configuration - """ - asyncio.run(self._test_https_certificate_validation_async()) - - async def _test_https_certificate_validation_async(self): - """Async implementation of HTTPS certificate validation test.""" - port = BASE_PORT + 20 - # Start HTTPS server - proc = Test.spawn_http_server( - DEMO_DIR, - port=port, - open_browser=False, - enable_https=True, - ) - - try: - # Wait for server to start - time.sleep(2) - - server_url = f"https://localhost:{port}/micdemo.html" - - # Launch Playwright browser - async with async_playwright() as p: - browser = await p.chromium.launch( - headless=True, - args=[ - "--ignore-certificate-errors", - "--allow-insecure-localhost", - ], - ) - - try: - context = await browser.new_context( - ignore_https_errors=True, - ) - page = await context.new_page() - - # Navigate to HTTPS URL - response = await page.goto( - server_url, wait_until="domcontentloaded", timeout=10000 - ) - - # Verify successful HTTPS connection - self.assertIsNotNone(response) - assert response is not None # Type narrowing for pyright - self.assertEqual(response.status, 200) - - # Verify protocol is HTTPS - protocol = await page.evaluate("window.location.protocol") - self.assertEqual( - protocol, "https:", "Server should serve content over HTTPS" - ) - - print(f"✅ HTTPS certificate validation test passed: {server_url}") - - finally: - await browser.close() - - finally: - # Stop the server - proc.terminate() - time.sleep(1) - class MicrophoneDemoValidationTest(unittest.TestCase): """Tests for the microphone demo HTML file.""" diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 5fb1adc8..b5af318a 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -15,7 +15,7 @@ @pytest.mark.skipif( os.environ.get("CI") == "true", - reason="Requires full WASM toolchain (emscripten + esbuild) — tracked in #39", + reason="Requires full WASM toolchain (emscripten + esbuild)", ) class MainTester(unittest.TestCase): """Main tester class.""" diff --git a/tests/unit/test_http_server.py b/tests/unit/test_http_server.py new file mode 100644 index 00000000..68dc77c6 --- /dev/null +++ b/tests/unit/test_http_server.py @@ -0,0 +1,167 @@ +""" +Smoke test for the Rust HTTP server spawned via the fastled CLI. + +Replaces the deleted HTTPS integration tests (PR #48 dropped HTTPS support). +This test verifies that the server can serve static files over HTTP. +""" + +import re +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path + +import httpx +import pytest # type: ignore[reportMissingImports] + +from fastled.interrupts import handle_keyboard_interrupt + + +def _find_rust_cli() -> Path | None: + """Locate the *Rust* fastled CLI binary (not the Python shim). + + The Rust binary handles ``--serve-dir`` natively. To distinguish it + from the Python entry-point shim (which is also called ``fastled.exe``), + we run a quick ``--serve-dir`` probe on any candidate before accepting it. + """ + exe_name = "fastled.exe" if sys.platform == "win32" else "fastled" + + candidates: list[Path] = [] + + # 1. Walk up from this test file looking for a Cargo workspace root. + current = Path(__file__).resolve().parent + for _ in range(10): + if (current / "Cargo.toml").is_file(): + # Prefer target/debug and target/release (direct cargo build output) + # over target//debug which may contain maturin wrappers. + for profile in ("debug", "release"): + candidate = current / "target" / profile / exe_name + if candidate.is_file(): + candidates.append(candidate) + # Then check platform-specific target dirs as fallback. + target_dir = current / "target" + if target_dir.is_dir(): + for arch_dir in target_dir.iterdir(): + if arch_dir.is_dir() and not arch_dir.name.startswith("."): + for profile in ("debug", "release"): + c = arch_dir / profile / exe_name + if c.is_file(): + candidates.append(c) + break + parent = current.parent + if parent == current: + break + current = parent + + # 2. Sibling of the running interpreter. + interpreter_sibling = Path(sys.executable).resolve().parent / exe_name + if interpreter_sibling.is_file(): + candidates.append(interpreter_sibling) + + # Prefer larger binaries (the Rust debug build is ~100 MB; the maturin + # wrapper is ~3 MB; the Python shim is ~40 KB). + candidates.sort(key=lambda p: p.stat().st_size, reverse=True) + + for candidate in candidates: + # The true Rust CLI debug build is 50+ MB. Maturin wrappers and + # Python shims are much smaller. + if candidate.stat().st_size < 10_000_000: + continue + # Quick probe: the Rust binary help starts with "FastLED WASM". + try: + cp = subprocess.run( + [str(candidate), "--help"], + capture_output=True, + timeout=5, + ) + help_text = cp.stdout.decode("utf-8", errors="replace") + if "FastLED WASM" in help_text and "--serve-dir" in help_text: + return candidate + except KeyboardInterrupt as ki: + handle_keyboard_interrupt(ki) + except Exception: + continue + + return None + + +_RUST_CLI = _find_rust_cli() + + +@pytest.mark.skipif( + _RUST_CLI is None, + reason="Rust fastled CLI binary not found", +) +class HttpServerSmokeTest(unittest.TestCase): + """Basic smoke test: spawn the Rust HTTP server, fetch index.html, verify 200.""" + + @pytest.mark.timeout(30) + def test_serve_index_html(self) -> None: + """Spawn the HTTP server in a temp directory and fetch index.html.""" + assert _RUST_CLI is not None # guarded by skipif + with tempfile.TemporaryDirectory() as tmpdir: + index_path = Path(tmpdir) / "index.html" + index_path.write_text( + "

FastLED HTTP smoke test

", + encoding="utf-8", + ) + + proc = subprocess.Popen( + [str(_RUST_CLI), "--serve-dir", str(tmpdir)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + try: + # Parse the port the server chose from its stdout. + actual_port: int | None = None + assert proc.stdout is not None + for _ in range(50): + raw = proc.stdout.readline() + if not raw: + break + line = raw.decode("utf-8", errors="replace") + m = re.search(r"http://[\d.]+:(\d+)", line) + if m: + actual_port = int(m.group(1)) + break + + self.assertIsNotNone( + actual_port, "Failed to detect the server port from stdout" + ) + assert actual_port is not None # narrow type for pyright + + # Wait for the server to become responsive. + deadline = time.time() + 10 + resp: httpx.Response | None = None + while time.time() < deadline: + try: + resp = httpx.get( + f"http://localhost:{actual_port}/index.html", timeout=2 + ) + if resp.status_code == 200: + break + except httpx.HTTPError: + resp = None + time.sleep(0.2) + + self.assertIsNotNone(resp, "Server did not respond in time") + assert resp is not None # narrow type for pyright + self.assertEqual( + resp.status_code, 200, f"Expected 200, got {resp.status_code}" + ) + self.assertIn("FastLED HTTP smoke test", resp.text) + finally: + proc.terminate() + try: + proc.wait(timeout=5) + except KeyboardInterrupt as ki: + handle_keyboard_interrupt(ki) + except OSError: + proc.kill() + + +if __name__ == "__main__": + unittest.main()