This commit is contained in:
2026-05-09 20:45:47 +02:00
parent b5e8153a00
commit 2e84fb0ad4
4 changed files with 153 additions and 68 deletions
@@ -0,0 +1,53 @@
---
name: playwright-brencher
description: "Write or refactor Playwright tests for brencher UI. Use when creating page helpers, extracting browser code from tests, or enforcing set_/verify_ method naming."
---
# Playwright Brencher Conventions
Use this skill when writing or refactoring Playwright tests in this repository.
## Required API Shape
Create and use a context manager in this style:
```python
with brencher_page(APP_URL) as page:
page.verify_dry_run_on()
page.set_dry_run_off()
page.verify_dry_run_off()
```
## Naming Rules
1. Action methods that change UI/application state must use `set_...` names.
2. Verification methods (assertions, waits, checks) must use `verify_...` names.
3. Keep low-level selector helpers private (prefix `_`).
4. Prefer one page-object class per screen/area (`BrencherPage` for the current app page).
## Structure Rules
1. Put shared Playwright helpers in `tests/playwright_helper.py`.
2. Keep tests focused on scenario flow; move DOM selectors and waiting logic into page helper methods.
3. Use context manager functions to own Playwright/browser lifecycle.
4. Inline trivial one-use logic where it improves readability and does not duplicate behavior.
## Method Guidance
Recommended style for page object methods:
- `set_*`: click/toggle/type actions.
- `verify_*`: assert visible state, button title/text, or wait until target state is reached.
Example method names:
- `set_dry_run_off`
- `verify_dry_run_on`
- `verify_dry_run_off`
## Review Checklist
1. Test uses `with brencher_page(...) as page` style.
2. No direct `sync_playwright()` block remains in the test body when helper abstraction is intended.
3. Action and verification methods follow `set_` / `verify_` naming.
4. Selector details are encapsulated in private helper methods.
+5 -5
View File
@@ -36,15 +36,15 @@ class EventuallyFn(Protocol):
def eventually() -> EventuallyFn:
def _eventually(assert_fn: Callable[[], bool], timeout: float = 2.0, interval: float = 0.05) -> None:
deadline = time.monotonic() + timeout
last_error = None
last_error: BaseException | None = None
while time.monotonic() < deadline:
try:
res = assert_fn()
if res:
if assert_fn():
return
except AssertionError as err:
last_error = None
except Exception as err:
last_error = err
time.sleep(interval)
time.sleep(interval)
raise AssertionError(f"Condition not met within {timeout:.2f}s") from last_error
+65
View File
@@ -0,0 +1,65 @@
import logging
from contextlib import contextmanager
from typing import Generator
from playwright.sync_api import Locator, Page, sync_playwright
logger = logging.getLogger(__name__)
class BrencherPage:
def __init__(self, page: Page, env_id: str, action_logger: logging.Logger) -> None:
self._page = page
self._env_id = env_id
self._logger = action_logger
def _dry_run_button(self) -> Locator:
button = self._page.locator(f'h3:has-text("{self._env_id}") button.dry-run-btn')
button.wait_for(state="visible", timeout=10000)
return button
def verify_dry_run_on(self) -> None:
btn_title = self._dry_run_button().get_attribute("title") or ""
assert "Dry run on" in btn_title, f"Expected dry run to be active, got title: {btn_title!r}"
self._logger.info(f"Dry-run button title before click: {btn_title!r}")
def set_dry_run_off(self) -> None:
self._dry_run_button().click()
self._logger.info("Clicked dry-run button to disable dry run")
def click_refresh(self) -> None:
self._page.locator("#refresh-branches").click()
self._logger.info("Clicked refresh button")
def verify_dry_run_off(self) -> None:
self._page.wait_for_function(
"""(targetEnvId) => {
const h3s = [...document.querySelectorAll('h3.env-title')];
const h3 = h3s.find(el => el.textContent.includes(targetEnvId));
if (!h3) return false;
const btn = h3.querySelector('button.dry-run-btn');
return btn && !btn.title.includes('Dry run on');
}""",
arg=self._env_id,
timeout=10000,
)
@contextmanager
def brencher_page(
app_link: str,
env_id: str = "brencher_local1",
action_logger: logging.Logger | None = None,
) -> Generator[BrencherPage, None, None]:
active_logger = action_logger or logger
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=True)
page = browser.new_page()
page.goto(app_link)
page.wait_for_load_state("networkidle")
try:
yield BrencherPage(page, env_id, active_logger)
finally:
browser.close()
+30 -63
View File
@@ -1,13 +1,13 @@
import logging
import threading
from typing import Any, Generator
from typing import Any, Callable, Generator
import docker
import pytest
import requests
from playwright.sync_api import Page, sync_playwright
from app import App
from .conftest import EventuallyFn
from .playwright_helper import brencher_page
from configs import brencher_local1
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
@@ -19,14 +19,10 @@ ENV_ID = "brencher_local1"
CONTAINER_NAME = "brencher_plain-container"
def _get_pipeline_step(state_data: Any, env_id: str, step_name: str) -> Any:
pipeline = state_data[env_id]["pipeline"]
for step in pipeline:
if step["name"] == step_name:
return step
return None
def _check_state(url: str, predicate: Callable[[Any], bool]) -> bool:
state_data = requests.get(f"{url}/state", timeout=5).json()
return predicate(state_data)
@pytest.mark.skip
class TestDryRunPlaywright:
@pytest.fixture(autouse=True)
@@ -41,9 +37,11 @@ class TestDryRunPlaywright:
logger.info(f"Container {CONTAINER_NAME} stopped and removed")
def test_dry_run_prevents_deploy_until_disabled(self, eventually: EventuallyFn) -> None:
# Start app with brencher_local1 with main branch pre-selected.
# App starts with dry=True by default (SharedStateHolderInMemory default).
app = App({"brencher_local1": brencher_local1.brencher_local1})
# Start app with brencher_local1 with main branch pre-selected and dry mode on.
env = brencher_local1.brencher_local1
env.state.set_branches([("main", "HEAD")])
env.state.set_dry(True)
app = App({"brencher_local1": env})
server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
server_thread.start()
@@ -57,14 +55,13 @@ class TestDryRunPlaywright:
# Wait for the pipeline to stabilize with dry=True:
# DockerContainerDeploy should return status="dry-run"
def _deploy_is_dry_run() -> bool:
state_data = requests.get(f"{APP_URL}/state", timeout=5).json()
step = _get_pipeline_step(state_data, ENV_ID, "DockerContainerDeploy")
if step is None or step.get("error"):
return False
return step["status"].get("status") == "dry-run"
eventually(_deploy_is_dry_run, timeout=120.0, interval=2.0)
eventually(
lambda: _check_state(APP_URL, lambda s: next(
p for p in s[ENV_ID]["pipeline"] if p["name"] == "DockerContainerDeploy"
)["status"].get("status") == "dry-run"),
timeout=120.0,
interval=2.0,
)
logger.info("Pipeline is in dry-run mode")
# Verify no real container was created
@@ -72,51 +69,21 @@ class TestDryRunPlaywright:
real_containers = docker_client.containers.list(filters={"name": CONTAINER_NAME}, all=True)
assert len(real_containers) == 0, "Container should NOT exist during dry run"
# Open browser and click the dry-run button to disable dry run
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page: Page = browser.new_page()
page.goto(APP_URL)
page.wait_for_load_state("networkidle")
# The dry-run button shows ⏸ when active (dry=True) and ▶ when disabled (dry=False).
# It is inside the h3 heading for brencher_local1.
dry_run_btn = page.locator(f'h3:has-text("{ENV_ID}") button.dry-run-btn')
dry_run_btn.wait_for(state="visible", timeout=10000)
# Verify button indicates dry-run is currently active (title contains "Dry run on")
btn_title = dry_run_btn.get_attribute("title") or ""
assert "Dry run on" in btn_title, f"Expected dry run to be active, got title: {btn_title!r}"
logger.info(f"Dry-run button title before click: {btn_title!r}")
# Click to disable dry run
dry_run_btn.click()
logger.info("Clicked dry-run button to disable dry run")
# Wait for button to update to "Running" state (title no longer says "Dry run on")
page.wait_for_function(
"""(envId) => {
const h3s = [...document.querySelectorAll('h3.env-title')];
const h3 = h3s.find(el => el.textContent.includes(envId));
if (!h3) return false;
const btn = h3.querySelector('button.dry-run-btn');
return btn && !btn.title.includes('Dry run on');
}""",
arg=ENV_ID,
timeout=10000,
)
browser.close()
# Open browser and disable dry run from the UI.
with brencher_page(APP_URL) as page:
page.verify_dry_run_on()
page.set_dry_run_off()
page.verify_dry_run_off()
page.click_refresh()
# Wait for pipeline to re-run and actually deploy the container
def _deploy_is_running() -> bool:
state_data = requests.get(f"{APP_URL}/state", timeout=5).json()
step = _get_pipeline_step(state_data, ENV_ID, "DockerContainerDeploy")
if step is None or step.get("error"):
return False
return step["status"].get("status") == "running"
eventually(_deploy_is_running, timeout=300.0, interval=5.0)
eventually(
lambda: _check_state(APP_URL, lambda s: next(
p for p in s[ENV_ID]["pipeline"] if p["name"] == "DockerContainerDeploy"
)["status"].get("status") == "running"),
timeout=300.0,
interval=5.0,
)
logger.info("Container deployed and running after dry run disabled")
# Final sanity: real container must exist and be running