import asyncio
from pathlib import Path
import pytest
from src.core.browser_controller_async import BrowserControllerAsync
CHAT_FIXTURE = """
Chat Fixture
"""
@pytest.mark.asyncio
@pytest.mark.e2e
async def test_browser_controller_async_send_and_receive(tmp_path: Path):
fixture_file = tmp_path / "chat_fixture.html"
fixture_file.write_text(CHAT_FIXTURE, encoding="utf-8")
controller = BrowserControllerAsync(
selectors={
"chat_input": "#chat-input",
"send_button": "#send-btn",
"chat_messages": "#messages .message",
},
output_dir=str(tmp_path),
headless=True,
)
started = await controller.start(fixture_file.resolve().as_uri())
if not started:
pytest.skip(f"Playwright browser unavailable: {controller.last_error}")
try:
assert await controller.send_message("ciao")
response = None
for _ in range(20):
messages = await controller.get_chat_messages()
bot_messages = [m for m in messages if m.get("sender") == "bot"]
if bot_messages:
response = bot_messages[-1].get("text")
break
await asyncio.sleep(0.25)
assert response is not None
assert "Echo: ciao" in response
messages = await controller.get_chat_messages()
assert any(m.get("sender") == "user" and "ciao" in m.get("text", "") for m in messages)
assert any(m.get("sender") == "bot" and "Echo: ciao" in m.get("text", "") for m in messages)
screenshot_path = await controller.capture_screenshot("e2e_async_chat")
assert screenshot_path
assert Path(screenshot_path).exists()
finally:
await controller.cleanup()