Author SHA1 Message Date
copilot-swe-agent[bot]andrudolf1 0e43c0fd13 harden playwright test config and assertions
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.12.3) (pull_request) Successful in 36s
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.13) (pull_request) Successful in 34s
Python package / build (flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics, 3.14) (pull_request) Successful in 36s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.12.3) (pull_request) Successful in 33s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.13) (pull_request) Successful in 35s
Python package / build (flake8 . --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics, 3.14) (pull_request) Successful in 36s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.12.3) (pull_request) Successful in 1m43s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.13) (pull_request) Successful in 1m54s
Python package / build (mypy --no-incremental --config-file mypy.ini backend tests, 3.14) (pull_request) Successful in 1m59s
Python package / build (pip list, 3.12.3) (pull_request) Successful in 31s
Python package / build (pip list, 3.13) (pull_request) Successful in 33s
Python package / build (pip list, 3.14) (pull_request) Successful in 31s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.12.3) (pull_request) Successful in 32s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.13) (pull_request) Successful in 36s
Python package / build (python -c "import sys; print(f'Python {sys.version}'); print(f'Build: {sys.version_info}'); print(f'Implementation: {sys.implementation}')", 3.14) (pull_request) Successful in 31s
Python package / tests (pytest, 3.12.3) (pull_request) Canceled after 0s
Python package / tests (pytest, 3.13) (pull_request) Canceled after 0s
Python package / tests (pytest, 3.14) (pull_request) Canceled after 0s
Agent-Logs-Url: https://github.com/rudolf1/brencher/sessions/d019d010-3ca0-4a73-8826-620eef58edab

Co-authored-by: rudolf1 <5525769+rudolf1@users.noreply.github.com>
2026-05-19 20:08:12 +00:00
copilot-swe-agent[bot]andrudolf1 ab01fca841 stabilize dry-run playwright integration
Agent-Logs-Url: https://github.com/rudolf1/brencher/sessions/d019d010-3ca0-4a73-8826-620eef58edab

Co-authored-by: rudolf1 <5525769+rudolf1@users.noreply.github.com>
2026-05-19 20:06:11 +00:00
copilot-swe-agent[bot]andrudolf1 b2782ee220 clarify async taskgroup behavior
Agent-Logs-Url: https://github.com/rudolf1/brencher/sessions/9e719b58-ad2a-4eca-99bf-43c750f71a72

Co-authored-by: rudolf1 <5525769+rudolf1@users.noreply.github.com>
2026-05-19 19:36:56 +00:00
copilot-swe-agent[bot]andrudolf1 1acea85934 add async shutdown cleanup and review fixes
Agent-Logs-Url: https://github.com/rudolf1/brencher/sessions/9e719b58-ad2a-4eca-99bf-43c750f71a72

Co-authored-by: rudolf1 <5525769+rudolf1@users.noreply.github.com>
2026-05-19 19:35:59 +00:00
copilot-swe-agent[bot]andrudolf1 6f3dd6ebd8 refactor app concurrency to asyncio taskgroup
Agent-Logs-Url: https://github.com/rudolf1/brencher/sessions/9e719b58-ad2a-4eca-99bf-43c750f71a72

Co-authored-by: rudolf1 <5525769+rudolf1@users.noreply.github.com>
2026-05-19 19:34:46 +00:00
copilot-swe-agent[bot] efe49119a3 Initial plan 2026-05-19 19:02:30 +00:00
12 changed files with 273 additions and 602 deletions
+3 -9
View File
@@ -1,14 +1,10 @@
FROM nginx:1.27-alpine
COPY .git /tmp/repo/.git
# Configure nginx to listen on 5001 to match container port expectations.
RUN sed -i 's/listen 80;/listen 5001;/' /etc/nginx/conf.d/default.conf
# Build a custom landing page directly in the image and inject git revision.
# Build a custom landing page directly in the image.
RUN set -eux; \
apk add --no-cache --virtual .git-deps git; \
GIT_REVISION="$(git --git-dir=/tmp/repo/.git rev-parse --short HEAD 2>/dev/null || echo unknown)"; \
{ \
echo '<!doctype html>'; \
echo '<html lang="en">'; \
@@ -21,11 +17,9 @@ RUN set -eux; \
echo ' <h1>Nginx Is Running</h1>'; \
echo ' <p>Custom landing page for the Brencher test app container.</p>'; \
echo ' <p>Port: 5001</p>'; \
echo " <p>Git revision: ${GIT_REVISION}</p>"; \
echo ' <p>Git revision: unknown</p>'; \
echo '</body>'; \
echo '</html>'; \
} > /usr/share/nginx/html/index.html; \
rm -rf /tmp/repo/.git; \
apk del .git-deps
} > /usr/share/nginx/html/index.html
EXPOSE 5001
+72 -21
View File
@@ -1,8 +1,8 @@
import asyncio
import logging
import os
import signal
import sys
import threading
import traceback
from typing import Any, Callable, Dict, List, Optional
@@ -27,9 +27,12 @@ class App:
def __init__(self, environments: Dict[str, Environment]) -> None:
self.environments: Dict[str, Environment] = {id: wrap_in_cached(e) for id, e in environments.items()}
self.state_lock = threading.Lock()
self.environment_update_event = threading.Event()
self.environment_update_event = asyncio.Event()
self.environment_update_version = 0
self.emit_callback: Optional[Callable[[], None]] = None
self.reset_requested = False
self.shutdown_event = asyncio.Event()
self.web_app: Any = None
def get_local_envs_to_emit(self) -> Dict[str, Dict[str, Any]]:
env_dtos: Dict[str, Dict[str, Any]] = {}
@@ -88,35 +91,83 @@ class App:
return branches
def processing_thread(self) -> None:
while True:
async def processing_loop(self) -> None:
while not self.shutdown_event.is_set():
import processing
emit = self.emit_callback or (lambda: None)
update_version = self.environment_update_version
with self.state_lock:
logger.info(f"Processing")
if processing.process_all_jobs(list(self.environments.values()), emit):
self.environment_update_event.wait(timeout=1 * 5)
else:
self.environment_update_event.wait(timeout=1 * 60)
self.environment_update_event.clear()
logger.info("Processing")
if self.reset_requested:
await asyncio.to_thread(processing.reset_caches, list(self.environments.values()))
self.reset_requested = False
has_error = await asyncio.to_thread(processing.process_all_jobs, list(self.environments.values()), emit)
if self.shutdown_event.is_set():
return
# Skip the wait when a newer update arrived while the current processing pass was running.
if self.environment_update_version != update_version:
continue
timeout = 5 if has_error else 60
try:
await asyncio.wait_for(self.environment_update_event.wait(), timeout=timeout)
except asyncio.TimeoutError:
pass
self.environment_update_event.clear()
def run(self) -> None:
processing = threading.Thread(target=self.processing_thread)
processing.daemon = True
processing.start()
def notify_environment_update(self) -> None:
self.environment_update_version += 1
self.environment_update_event.set()
def request_reset(self) -> None:
self.reset_requested = True
def stop(self) -> None:
self.shutdown_event.set()
self.notify_environment_update()
if self.web_app is not None:
self.web_app.stop()
async def runAsync(self) -> None:
await self.processing_loop()
async def runHeadlessAsync(self) -> None:
await self.processing_loop()
def runHeadless(self) -> None:
"""Run the processing loop on the current thread; blocks forever."""
self.processing_thread()
"""Run the processing loop until cancelled; blocks forever."""
asyncio.run(self.runHeadlessAsync())
def runWeb(self, port: int) -> None:
async def _run_web_server(self, web_app: Any) -> None:
"""Raise a sentinel exception when the server stops so TaskGroup cancels processing."""
await web_app.start_async()
raise _WebServerStopped()
async def runWebAsync(self, port: int) -> None:
import web
web_app = web.WebApp(core=self, port=port)
self.web_app = web_app
self.emit_callback = web_app.emit_envs
self.run()
web_app.start()
try:
# Keep processing and web serving coupled so shutdown or fatal failure tears down the whole app.
async with asyncio.TaskGroup() as task_group:
task_group.create_task(self.processing_loop())
task_group.create_task(self._run_web_server(web_app))
except* _WebServerStopped:
pass
finally:
self.emit_callback = None
self.web_app = None
def runWeb(self, port: int) -> None:
asyncio.run(self.runWebAsync(port))
def run(self) -> None:
asyncio.run(self.runAsync())
class _WebServerStopped(Exception):
pass
if __name__ == '__main__':
cli_env_ids_list = sys.argv[1:]
+2 -1
View File
@@ -279,7 +279,8 @@ class DockerSwarmDeploy(AbstractStep[str]):
swarmEnv = {k: v for k, v in dotenv_values(os.path.join(os.path.dirname(tmp_compose_path), ".env")).items()
if v is not None}
# merge_dicts(swarmEnv, env)
result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.path.dirname(tmp_compose_path), env=swarmEnv)
result = subprocess.run(cmd, capture_output=True, text=True)
# , cwd=os.path.dirname(tmp_compose_path), env=swarmEnv)
os.remove(tmp_compose_path)
if result.returncode != 0:
logger.error(f"Stack deploy failed: {result.stderr}")
+45 -36
View File
@@ -11,11 +11,8 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from app import App
from enironment import SharedStateConflictError, get_step
from utils import custom_json_dumps
from processing import reset_caches
from secondary import SecondaryManager
from steps.step import CachingStep
logger = logging.getLogger(__name__)
@@ -48,11 +45,12 @@ class WebApp:
self.ws_connections: Dict[WebSocket, Dict[str, Any]] = {}
self._event_loop: Optional[asyncio.AbstractEventLoop] = None
self._server: Any = None
self.secondaryManager: Optional[SecondaryManager] = None
@asynccontextmanager
async def lifespan(fastapi_app: FastAPI) -> AsyncIterator[None]:
self._event_loop = asyncio.get_event_loop()
self._event_loop = asyncio.get_running_loop()
self.secondaryManager = SecondaryManager(
urls=os.getenv("SECONDARY_BRENCHER", ""),
on_update=lambda: self.broadcast_all(),
@@ -94,10 +92,20 @@ class WebApp:
merged = _merge_dicts(merged, connector.branches)
return merged
# --- Async scheduling from sync threads ---
# --- Async scheduling from sync callbacks ---
def _schedule_async(self, coro: Any) -> None:
if self._event_loop is not None and self._event_loop.is_running():
if self._event_loop is None or not self._event_loop.is_running():
logger.warning("Dropping scheduled coroutine because the web event loop is not running")
coro.close()
return
try:
running_loop = asyncio.get_running_loop()
except RuntimeError:
running_loop = None
if running_loop is self._event_loop:
self._event_loop.create_task(coro)
else:
asyncio.run_coroutine_threadsafe(coro, self._event_loop)
# --- Broadcasting ---
@@ -134,7 +142,7 @@ class WebApp:
await self.broadcast("error", data)
def emit_envs(self) -> None:
"""Sync callback used by App's processing thread to push updates to clients."""
"""Sync callback used by App's processing loop to push updates to clients."""
self._schedule_async(self.broadcast_branches(self.get_global_branches_to_emit()))
self._schedule_async(self.broadcast_environments(self.get_global_envs_to_emit()))
@@ -179,42 +187,26 @@ class WebApp:
await self.secondaryManager.send({"update": update_data})
id = update_data.get('id', '')
if id == '':
reset_caches(list(self.core.environments.values()))
self.core.request_reset()
elif id not in self.core.environments.keys() and id not in {j for it in self.secondaryManager or [] for j in it.environments.keys()}:
logger.warning(f"Received update for unknown environment id {id}")
continue
elif id in self.core.environments.keys():
env = self.core.environments.get(id, None)
expected_token = update_data.get('token', '')
try:
if 'branches' in update_data:
if not env:
raise RuntimeError(f"Unknown env {update_data.get('id', '')}")
env.state.set_branches(update_data.get('branches', []), expected_token=expected_token)
if 'dry' in update_data:
if not env:
raise RuntimeError(f"Unknown env {update_data.get('id', '')}")
env.state.set_dry(bool(update_data['dry']), expected_token)
except SharedStateConflictError as conflict:
# if env:
# current_state = env.state.progress()
# await self.broadcast_error({
# 'code': 'BRANCH_STATE_CONFLICT',
# 'envId': id,
# 'message': str(conflict),
# 'current_state': {
# 'branches': current_state.branches,
# 'token': current_state.token,
# },
# })
continue
if 'branches' in update_data:
if not env:
raise RuntimeError(f"Unknown env {update_data.get('id', '')}")
env.state.set_branches(update_data.get('branches', []), expected_token=expected_token)
if 'dry' in update_data:
if not env:
raise RuntimeError(f"Unknown env {update_data.get('id', '')}")
env.state.set_dry(bool(update_data['dry']), expected_token)
if env:
p = get_step(env.pipeline, type(env.state))
if isinstance(p, CachingStep):
p.reset()
self.core.request_reset()
logger.info(f"Updated environment {env.id} branches to {update_data.get('branches')}, dry={update_data.get('dry')}")
self.core.environment_update_event.set()
self.core.notify_environment_update()
await self.broadcast_environments(self.get_global_envs_to_emit())
@@ -226,6 +218,23 @@ class WebApp:
# --- Run ---
def start(self) -> None:
async def start_async(self) -> None:
import uvicorn
uvicorn.run(self.app, host='0.0.0.0', port=self.port, log_level='info')
config = uvicorn.Config(self.app, host='0.0.0.0', port=self.port, log_level='info')
self._server = uvicorn.Server(config)
try:
await self._server.serve()
except asyncio.CancelledError:
self._server.should_exit = True
raise
def start(self) -> None:
asyncio.run(self.start_async())
def stop(self) -> None:
if self._server is None:
return
if self._event_loop is not None and self._event_loop.is_running():
self._event_loop.call_soon_threadsafe(lambda: setattr(self._server, "should_exit", True))
else:
self._server.should_exit = True
+3 -21
View File
@@ -137,20 +137,9 @@ function escapeHtml(str) {
}
let renderedBranches = []
let renderedDryRunState = {}
let renderedColumnsSignature = ''
function getColumnsSignature() {
return JSON.stringify(columnsByEnv);
}
function renderBranches() {
const columnsSignature = getColumnsSignature();
if (
JSON.stringify(filteredBranches) === JSON.stringify(renderedBranches) &&
JSON.stringify(dryRunByEnv) === JSON.stringify(renderedDryRunState) &&
columnsSignature === renderedColumnsSignature
) {
if (JSON.stringify(filteredBranches) === JSON.stringify(renderedBranches) && JSON.stringify(dryRunByEnv) === JSON.stringify(renderedDryRunState)) {
return
}
checkForPendingChanges();
@@ -263,9 +252,8 @@ function renderBranches() {
filterBranches();
};
});
renderedBranches = [...filteredBranches];
renderedBranches = filteredBranches;
renderedDryRunState = {...dryRunByEnv};
renderedColumnsSignature = columnsSignature;
}
function updateBranchCommit(envId, branch, commit) {
@@ -482,13 +470,9 @@ function setupWebSockets() {
if (message.error && message.error.code === 'BRANCH_STATE_CONFLICT' && message.error.envId) {
const envId = message.error.envId;
const current = message.error.current_state || {};
const hadLocalSelection = Object.prototype.hasOwnProperty.call(selectedBranchesByEnv, envId);
if (Array.isArray(current.branches)) {
selectedBranchesByEnv[envId] = [...current.branches];
serverSelectedBranchesByEnv[envId] = [...current.branches];
// Preserve the user's pending edits if they already changed selection locally.
if (!hadLocalSelection) {
selectedBranchesByEnv[envId] = [...current.branches];
}
}
if (typeof current.token === 'string') {
serverTokenByEnv[envId] = current.token;
@@ -519,8 +503,6 @@ function updateEnvironment() {
if (JSON.stringify(localSel) !== JSON.stringify(serverSel)) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ update: { id: envId, branches: selectedBranchesByEnv[envId], token: serverTokenByEnv[envId] } }));
// Keep pending-state tracking aligned with what we just submitted.
serverSelectedBranchesByEnv[envId] = [...(selectedBranchesByEnv[envId] || [])];
}
branchFilter.value = '';
}
+20
View File
@@ -1,8 +1,28 @@
import subprocess
from pathlib import Path
from enironment import Environment
from steps.docker_plain import DockerImageBuild, DockerContainerCheck, DockerContainerDeploy
from steps.git import GitClone, CheckoutMerged, GitUnmerge
from steps.shared_state import SharedStateHolderInMemory
REPO_ROOT = Path(__file__).resolve().parents[2]
def _git_output(*args: str) -> str:
try:
return subprocess.check_output(
["git", "-C", str(REPO_ROOT), *args],
text=True,
stderr=subprocess.STDOUT,
).strip()
except subprocess.CalledProcessError as exc:
raise RuntimeError(f"Unable to read git metadata for nginx test config: {' '.join(args)}\n{exc.output}") from exc
CURRENT_BRANCH = _git_output("rev-parse", "--abbrev-ref", "HEAD")
CURRENT_COMMIT = _git_output("rev-parse", "HEAD")
clone = GitClone(url="https://github.com/rudolf1/brencher.git")
container_check = DockerContainerCheck(
-101
View File
@@ -20,25 +20,6 @@ class BrencherPage:
button.wait_for(state="visible", timeout=10000)
return button
def _apply_changes_button(self) -> Locator:
button = self._page.locator("#apply-changes")
button.wait_for(state="visible", timeout=10000)
return button
def _branch_checkbox(self, branch_name: str) -> Locator:
checkbox = self._page.locator(
f'input[type="checkbox"][data-env="{self._env_id}"][value="{branch_name}"]'
)
checkbox.wait_for(state="visible", timeout=10000)
return checkbox
def _desired_commit_select(self, branch_name: str) -> Locator:
select = self._page.locator(
f'select.desired-commit[data-env="{self._env_id}"][data-branch="{branch_name}"]'
)
select.wait_for(state="visible", timeout=10000)
return select
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}"
@@ -48,39 +29,6 @@ class BrencherPage:
self._dry_run_button().click()
self._logger.info("Clicked dry-run button to disable dry run")
def set_branch_unselected(self, branch_name: str) -> None:
checkbox = self._branch_checkbox(branch_name)
if checkbox.is_checked():
checkbox.uncheck()
self._logger.info("Unchecked branch '%s'", branch_name)
def set_branch_desired_commit(self, branch_name: str, commit_hash: str) -> None:
self._desired_commit_select(branch_name).select_option(value=commit_hash)
self._logger.info("Set desired commit for branch '%s' to '%s'", branch_name, commit_hash)
def set_apply_changes(self) -> None:
self._apply_changes_button().click()
self._logger.info("Clicked Apply Changes")
def set_simulate_branch_state_conflict(self) -> None:
self._page.evaluate(
"""({ envId }) => {
const currentToken =
(typeof serverTokenByEnv !== 'undefined' && serverTokenByEnv[envId])
? serverTokenByEnv[envId]
: 'server-token';
const staleToken = `${currentToken}-stale`;
if (typeof serverTokenByEnv !== 'undefined') {
// Simulate stale client-side token so next apply uses an outdated value.
serverTokenByEnv[envId] = staleToken;
}
}""",
{
"envId": self._env_id,
},
)
self._logger.info("Set stale branch token for '%s'", self._env_id)
def click_refresh(self) -> None:
self._page.locator("#refresh-branches").click()
self._logger.info("Clicked refresh button")
@@ -98,55 +46,6 @@ class BrencherPage:
timeout=10000,
)
def verify_apply_changes_visible(self) -> None:
self._page.wait_for_function(
"""() => {
const btn = document.querySelector('#apply-changes');
return !!btn && !btn.classList.contains('hidden');
}""",
timeout=10000,
)
self._logger.info("Apply Changes button is visible")
def verify_apply_changes_hidden(self) -> None:
self._page.wait_for_function(
"""() => {
const btn = document.querySelector('#apply-changes');
return !!btn && btn.classList.contains('hidden');
}""",
timeout=10000,
)
self._logger.info("Apply Changes button is hidden")
def verify_branch_column_value(self, branch_name: str, column_name: str, expected_value: str, timeout_ms: int = 10000) -> None:
self._page.wait_for_function(
"""({ envId, branchName, columnName, expectedValue }) => {
const row = document.querySelector(`tr.branch-row[data-env="${envId}"][data-branch="${branchName}"]`);
if (!row) return false;
const table = row.closest('table.branches-table');
if (!table) return false;
const headers = [...table.querySelectorAll('thead th')].map(th => (th.textContent || '').trim());
const colIdx = headers.indexOf(columnName);
if (colIdx === -1) return false;
const cells = [...row.querySelectorAll('td')];
if (cells.length <= colIdx) return false;
return ((cells[colIdx].textContent || '').trim() === expectedValue);
}""",
arg={
"envId": self._env_id,
"branchName": branch_name,
"columnName": column_name,
"expectedValue": expected_value,
},
timeout=timeout_ms,
)
self._logger.info(
"Verified column '%s' for branch '%s' equals '%s'",
column_name,
branch_name,
expected_value,
)
def verify_pipeline_step_status(self, step_name: str, expected_status: str, timeout_ms: int = 10000) -> None:
"""
Verify that a pipeline step reaches the expected status by polling the page DOM.
+52
View File
@@ -0,0 +1,52 @@
import asyncio
import sys
import types
from typing import Callable
import pytest
from enironment import Environment
import processing
from app import App
class TestAppAsyncio:
@pytest.mark.asyncio
async def test_run_web_async_stops_processing_when_server_exits(self, monkeypatch: pytest.MonkeyPatch) -> None:
process_calls = 0
emit_calls = 0
processing_started = asyncio.Event()
loop = asyncio.get_running_loop()
web_app_args: dict[str, object] = {}
def fake_process_all_jobs(environments: list[Environment], onupdate: Callable[[], None]) -> bool:
nonlocal process_calls
process_calls += 1
assert environments == []
onupdate()
loop.call_soon_threadsafe(processing_started.set)
return False
class FakeWebApp:
def __init__(self, core: App, port: int) -> None:
web_app_args["core"] = core
web_app_args["port"] = port
def emit_envs(self) -> None:
nonlocal emit_calls
emit_calls += 1
async def start_async(self) -> None:
await asyncio.wait_for(processing_started.wait(), timeout=1)
monkeypatch.setattr(processing, "process_all_jobs", fake_process_all_jobs)
monkeypatch.setitem(sys.modules, "web", types.SimpleNamespace(WebApp=FakeWebApp))
app = App({})
await asyncio.wait_for(app.runWebAsync(5001), timeout=1)
assert process_calls >= 1
assert emit_calls >= 1
assert web_app_args == {"core": app, "port": 5001}
assert app.emit_callback is None
-127
View File
@@ -1,127 +0,0 @@
import logging
import threading
import time
from typing import Any, Generator
import docker
import pytest
import requests
import socket
from app import App
from tests.configs import nginx
from tests.conftest import EventuallyFn, assert_equal
from tests.playwright_helper import brencher_page
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
APP_PORT = 5003
APP_URL = f"http://localhost:{APP_PORT}"
CONTAINER_NAME = "test_plain-container"
# Module-level reference to server thread to ensure proper cleanup
_server_thread: threading.Thread | None = None
def _is_port_free(port: int, timeout: float = 5.0) -> bool:
"""Check if a port is available for binding."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
result = sock.connect_ex(('127.0.0.1', port))
sock.close()
if result != 0:
return True
except Exception:
return True
time.sleep(0.1)
return False
class TestApplyChangesPlaywright:
@pytest.fixture(autouse=True)
def setup_teardown(self) -> Generator[None, Any, None]:
global _server_thread
def stop_and_remove_container() -> None:
client = docker.from_env()
try:
container = client.containers.get(CONTAINER_NAME)
container.stop(timeout=10)
container.remove(force=True)
logger.info("Container %s stopped and removed", CONTAINER_NAME)
except Exception:
logger.info("Container %s not found, no need to stop/remove", CONTAINER_NAME)
# Ensure port is free before starting
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
yield None
# Clean up server thread
if _server_thread and _server_thread.is_alive():
_server_thread.join(timeout=2.0)
logger.info("Waited for server thread to finish")
# Ensure port is free after test
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
_server_thread = None
def test_apply_button_hides_after_apply_branch_change(self, eventually: EventuallyFn) -> None:
global _server_thread
# Start app with one pre-selected branch so unchecking creates pending changes.
env = nginx.test_local1
env.state.set_branches([("test/main", "HEAD")])
env.state.set_dry(True)
app = App({env.id: env})
_server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
_server_thread.start()
eventually(
lambda: assert_equal(
requests.get(f"{APP_URL}/state", timeout=5).status_code,
200,
"Server did not respond with 200 OK within timeout",
)
)
with brencher_page(APP_URL, env.id) as page:
page.set_branch_unselected("test/main")
page.verify_apply_changes_visible()
page.set_apply_changes()
eventually(lambda: page.verify_apply_changes_hidden(), timeout=10, interval=0.5)
def test_apply_button_reappears_on_branch_conflict(self, eventually: EventuallyFn) -> None:
global _server_thread
env = nginx.test_local1
env.state.set_branches([("test/main", "HEAD")])
env.state.set_dry(True)
app = App({env.id: env})
_server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
_server_thread.start()
eventually(
lambda: assert_equal(
requests.get(f"{APP_URL}/state", timeout=5).status_code,
200,
"Server did not respond with 200 OK within timeout",
)
)
with brencher_page(APP_URL, env.id) as page:
page.set_branch_unselected("test/main")
page.verify_apply_changes_visible()
# Set stale token in client JS object so backend returns a real conflict on apply.
page.set_simulate_branch_state_conflict()
page.set_apply_changes()
eventually(lambda: page.verify_apply_changes_visible(), timeout=10, interval=0.5)
+21 -21
View File
@@ -1,7 +1,7 @@
import asyncio
import json
import logging
import threading
from contextlib import suppress
from typing import Any, Generator
import docker
@@ -36,30 +36,30 @@ class TestDockerContainer:
logger.info(f"Starting")
app = App({"brencher_local1": brencher_local1.brencher_local1})
# app.runWeb(5001)
processing = threading.Thread(target=lambda: app.runWeb(5001), daemon=True)
processing.start()
processing = asyncio.create_task(app.runWebAsync(5001))
try:
eventually(
lambda: assert_equal(requests.get("http://localhost:5001/state", timeout=5000).status_code, 200, "Server did not respond with 200 OK within timeout"),
20.0,
1.0,
)
# await asyncio.sleep(5000)
state_data = requests.get("http://localhost:5001/state", timeout=5000).json()
logger.info(f"Application state: {json.dumps(state_data, indent=2)}")
eventually(
lambda: assert_equal(requests.get("http://localhost:5001/state", timeout=5000).status_code, 200, "Server did not respond with 200 OK within timeout"),
20.0,
1.0,
)
branches_data = requests.get("http://localhost:5001/branches", timeout=5000).json()
logger.info(f"Application branches: {json.dumps(branches_data, indent=2)}")
assert "brencher_local1" in state_data, "Missing 'brencher_local1' field in response"
assert len(state_data["brencher_local1"]["pipeline"]) > 0, "Steps defined for 'brencher_local1' are empty"
state_data = requests.get("http://localhost:5001/state", timeout=5000).json()
logger.info(f"Application state: {json.dumps(state_data, indent=2)}")
branches_data = requests.get("http://localhost:5001/branches", timeout=5000).json()
logger.info(f"Application branches: {json.dumps(branches_data, indent=2)}")
assert "brencher_local1" in state_data, "Missing 'brencher_local1' field in response"
assert len(state_data["brencher_local1"]["pipeline"]) > 0, "Steps defined for 'brencher_local1' are empty"
assert "brencher_local1" in branches_data, "Missing 'brencher_local1' field in response"
assert len(branches_data["brencher_local1"]) > 0, "No branches found for 'brencher_local1'"
assert "brencher_local1" in branches_data, "Missing 'brencher_local1' field in response"
assert len(branches_data["brencher_local1"]) > 0, "No branches found for 'brencher_local1'"
finally:
processing.cancel()
with suppress(asyncio.CancelledError):
await processing
assert processing.cancelled()
# TODO Verify DockerContainerDeploy step status is running and has correct image and ports
# {
-182
View File
@@ -1,182 +0,0 @@
import logging
import socket
import threading
import time
from typing import Any, Generator
import docker
import pytest
import requests
from app import App
from tests.configs import nginx
from tests.conftest import EventuallyFn, assert_equal
from tests.playwright_helper import brencher_page
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
APP_PORT = 5004
APP_URL = f"http://localhost:{APP_PORT}"
CONTAINER_NAME = "test_plain-container"
TARGET_BRANCH = "test/main"
_server_thread: threading.Thread | None = None
def _is_port_free(port: int, timeout: float = 5.0) -> bool:
"""Check if a port is available for binding."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
result = sock.connect_ex(("127.0.0.1", port))
sock.close()
if result != 0:
return True
except Exception:
return True
time.sleep(0.1)
return False
def _get_state() -> dict[str, Any]:
response = requests.get(f"{APP_URL}/state", timeout=5)
assert response.status_code == 200, f"Expected status 200 from /state, got {response.status_code}"
data = response.json()
assert isinstance(data, dict), f"Expected dict from /state, got {type(data)}"
return data
def _get_deployed_short_hash(env_id: str, branch: str) -> str:
state = _get_state()
env_state = state.get(env_id)
assert isinstance(env_state, dict), f"No environment state for {env_id}: {state}"
pipeline = env_state.get("pipeline")
assert isinstance(pipeline, list), f"Pipeline is not list for {env_id}: {env_state}"
step = next((p for p in pipeline if p.get("name") == "GitUnmerge"), None)
assert isinstance(step, dict), f"GitUnmerge step not found in pipeline: {pipeline}"
assert not bool(step.get("is_running")), f"GitUnmerge is still running: {step}"
status = step.get("status")
assert isinstance(status, dict), f"GitUnmerge status is not an object: {status}"
columns = status.get("columns")
assert isinstance(columns, dict), f"GitUnmerge columns missing: {status}"
deployed = columns.get("Deployed")
assert isinstance(deployed, dict), f"Deployed column missing: {columns}"
value = deployed.get(branch)
assert isinstance(value, str) and len(value) == 8, f"Deployed value for {branch} invalid: {value}"
return value
def _pick_target_commit(env_id: str, branch: str) -> str:
response = requests.get(f"{APP_URL}/branches", timeout=5)
assert response.status_code == 200, f"Expected status 200 from /branches, got {response.status_code}"
data = response.json()
assert isinstance(data, dict), f"Expected dict from /branches, got {type(data)}"
env_branches = data.get(env_id, {})
assert isinstance(env_branches, dict), f"Expected env branch map for {env_id}, got {env_branches}"
commits = env_branches.get(branch, [])
assert isinstance(commits, list), f"Expected commits list for {branch}, got {commits}"
for commit in commits:
if not isinstance(commit, dict):
continue
hexsha = commit.get("hexsha")
if isinstance(hexsha, str) and len(hexsha) >= 8:
return hexsha
raise AssertionError(f"Unable to find any commit for branch {branch}.")
def _assert_deployed_hash_available(env_id: str, branch: str) -> None:
value = _get_deployed_short_hash(env_id, branch)
assert isinstance(value, str) and len(value) == 8
class TestDeployColumnPlaywright:
@pytest.fixture(autouse=True)
def setup_teardown(self) -> Generator[None, Any, None]:
global _server_thread
def stop_and_remove_container() -> None:
client = docker.from_env()
try:
container = client.containers.get(CONTAINER_NAME)
container.stop(timeout=10)
container.remove(force=True)
logger.info("Container %s stopped and removed", CONTAINER_NAME)
except Exception:
logger.info("Container %s not found, no need to stop/remove", CONTAINER_NAME)
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
yield None
if _server_thread and _server_thread.is_alive():
_server_thread.join(timeout=2.0)
logger.info("Waited for server thread to finish")
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
_server_thread = None
def test_deployed_column_updates_after_apply_changes_and_deploy(self, eventually: EventuallyFn) -> None:
global _server_thread
env = nginx.test_local1
env.state.set_branches([(TARGET_BRANCH, "HEAD")])
env.state.set_dry(True)
app = App({env.id: env})
_server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
_server_thread.start()
eventually(
lambda: assert_equal(
requests.get(f"{APP_URL}/state", timeout=5).status_code,
200,
"Server did not respond with 200 OK within timeout",
),
timeout=20,
interval=0.5,
)
target_commit = _pick_target_commit(env.id, TARGET_BRANCH)
with brencher_page(APP_URL, env.id) as page:
page.verify_dry_run_on()
page.set_branch_desired_commit(TARGET_BRANCH, target_commit)
page.verify_apply_changes_visible()
page.set_apply_changes()
eventually(lambda: page.verify_apply_changes_hidden(), timeout=20, interval=0.5)
page.set_dry_run_off()
eventually(lambda: page.verify_dry_run_off(), timeout=20, interval=0.5)
page.click_refresh()
eventually(
lambda: _assert_deployed_hash_available(env.id, TARGET_BRANCH),
timeout=90,
interval=1.0,
)
deployed_short_hash = _get_deployed_short_hash(env.id, TARGET_BRANCH)
eventually(
lambda: page.verify_branch_column_value(TARGET_BRANCH, "Deployed", deployed_short_hash),
timeout=30,
interval=0.5,
)
+55 -83
View File
@@ -1,7 +1,5 @@
import logging
import threading
import time
import socket
from typing import Any, Callable, Generator, TypeVar
import docker
@@ -19,32 +17,10 @@ APP_PORT = 5003
APP_URL = f"http://localhost:{APP_PORT}"
CONTAINER_NAME = "test_plain-container"
# Module-level reference to server thread to ensure proper cleanup
_server_thread: threading.Thread | None = None
def _is_port_free(port: int, timeout: float = 5.0) -> bool:
"""Check if a port is available for binding."""
deadline = time.time() + timeout
while time.time() < deadline:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
result = sock.connect_ex(('127.0.0.1', port))
sock.close()
if result != 0:
return True
except Exception:
return True
time.sleep(0.1)
return False
class TestDryRunPlaywright:
@pytest.fixture(autouse=True)
def setup_teardown(self) -> Generator[None, Any, None]:
global _server_thread
def stop_and_remove_container() -> None:
client = docker.from_env()
try:
@@ -54,79 +30,75 @@ class TestDryRunPlaywright:
logger.info(f"Container {CONTAINER_NAME} stopped and removed")
except Exception:
logger.info(f"Container {CONTAINER_NAME} not found, no need to stop/remove")
# Ensure port is free before starting
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
yield None
# Clean up server thread
if _server_thread and _server_thread.is_alive():
_server_thread.join(timeout=2.0)
logger.info("Waited for server thread to finish")
# Ensure port is free after test
_is_port_free(APP_PORT, timeout=5.0)
stop_and_remove_container()
_server_thread = None
def test_dry_run_prevents_deploy_until_disabled(self, eventually: EventuallyFn) -> None:
global _server_thread
# Start app with nginx_local1 with main branch pre-selected and dry mode on.
env = nginx.test_local1
env.state.set_branches([("test/main", "HEAD")])
env.state.set_branches([(nginx.CURRENT_BRANCH, nginx.CURRENT_COMMIT)])
env.state.set_dry(True)
app = App({env.id: env})
_server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
_server_thread.start()
server_thread = threading.Thread(target=lambda: app.runWeb(APP_PORT), daemon=True)
server_thread.start()
try:
# Wait for server to be up
eventually(lambda: assert_equal(requests.get(f"{APP_URL}/state", timeout=5).status_code, 200, "Server did not respond with 200 OK within timeout"))
logger.info("Server is up")
# Wait for server to be up
eventually(lambda: assert_equal(requests.get(f"{APP_URL}/state", timeout=5).status_code, 200, "Server did not respond with 200 OK within timeout"))
logger.info("Server is up")
# Wait for the pipeline to stabilize with dry=True:
# DockerContainerDeploy should return status="dry-run"
with brencher_page(APP_URL, env.id) as page:
eventually(
lambda: check_state(APP_URL, lambda s: assert_equal(next(
p for p in s[env.id]["pipeline"] if p["name"] == "SharedStateHolderInMemory"
)["status"]['dry'], True, "Pipeline step status is not 'running'")),
)
# Wait for the pipeline to stabilize with dry=True:
# DockerContainerDeploy should return status="dry-run"
with brencher_page(APP_URL, env.id) as page:
eventually(
lambda: check_state(APP_URL, lambda s: assert_equal(next(
p for p in s[env.id]["pipeline"] if p["name"] == "SharedStateHolderInMemory"
)["status"]['dry'], True, "Pipeline step status is not 'running'")),
)
# page.verify_pipeline_step_status("DockerContainerDeploy", "dry-run")
logger.info("Pipeline is in dry-run mode")
# page.verify_pipeline_step_status("DockerContainerDeploy", "dry-run")
logger.info("Pipeline is in dry-run mode")
# Verify no real container was created
docker_client = docker.from_env()
real_containers = docker_client.containers.list(filters={"name": CONTAINER_NAME}, all=True)
assert len(real_containers) == 0, "Container should NOT exist during dry run"
# Verify no real container was created
docker_client = docker.from_env()
real_containers = docker_client.containers.list(filters={"name": CONTAINER_NAME}, all=True)
assert len(real_containers) == 0, "Container should NOT exist during dry run"
# Disable dry run from the UI.
page.verify_dry_run_on()
page.set_dry_run_off()
page.verify_dry_run_off()
# Disable dry run from the UI.
page.verify_dry_run_on()
page.set_dry_run_off()
page.verify_dry_run_off()
page.click_refresh() # TODO Remove it
# Wait for pipeline to re-run and actually deploy the container
eventually(
lambda: check_state(APP_URL, lambda s: assert_equal(next(
p for p in s[env.id]["pipeline"] if p["name"] =="SharedStateHolderInMemory"
)["status"]['dry'], False, "Pipeline step status is not 'running'")),
)
# Wait for pipeline to re-run and actually deploy the container
eventually(
lambda: check_state(APP_URL, lambda s: assert_equal(next(
p for p in s[env.id]["pipeline"] if p["name"] =="SharedStateHolderInMemory"
)["status"]['dry'], False, "Pipeline step status is not 'running'")),
)
# Wait for pipeline to re-run and actually deploy the container
eventually(
lambda: check_state(APP_URL, lambda s: assert_equal({p["name"] for p in s[env.id]["pipeline"] if bool(p['is_running'])}, set(), "Pipeline still running")),
timeout=20,
interval=1.0,
)
# page.verify_pipeline_step_status("DockerContainerDeploy", "running")
logger.info("Container deployed and running after dry run disabled")
# Wait for the real container to be created and started.
eventually(
lambda: _assert_container_running(docker_client),
# Allow time for a cold image build and first container start on CI runners.
timeout=180,
interval=5.0,
)
# page.verify_pipeline_step_status("DockerContainerDeploy", "running")
logger.info("Container deployed and running after dry run disabled")
# Final sanity: real container must exist and be running
containers = docker_client.containers.list(filters={"name": CONTAINER_NAME})
assert len(containers) == 1, "Container should exist and be running after deploy"
assert containers[0].status == "running"
# Final sanity: real container must exist and be running
containers = docker_client.containers.list(filters={"name": CONTAINER_NAME})
assert len(containers) == 1, "Container should exist and be running after deploy"
assert containers[0].status == "running"
finally:
app.stop()
server_thread.join(timeout=30)
if server_thread.is_alive():
logger.warning("App server thread did not stop within 30 seconds")
def _assert_container_running(docker_client: docker.DockerClient) -> None:
containers = docker_client.containers.list(filters={"name": CONTAINER_NAME}, all=True)
assert len(containers) > 0, "Container should exist after deploy"
assert_equal({container.status for container in containers}, {"running"}, "Container should be running after deploy")