from contextlib import closing
from contree_client.models import EventDataStream
from contree_sdk import ContreeSession, create_sandbox_session
def main() -> None:
with create_sandbox_session(
image="tag:alpine:latest",
session_type=ContreeSession,
) as session:
run_variant(session, expect_failure=False, disconnect=True)
run_variant(session, expect_failure=True, disconnect=False)
print("Observed the successful and nonzero test outcomes.")
def run_variant(session, *, expect_failure: bool, disconnect: bool) -> None:
command = TEST_SUITE.replace(
"# OPTIONAL_FAILURE", "check deliberate-failure false" if expect_failure else ""
)
operation = session.spawn(shell=command, disposable=True, timeout=30, truncate_output_at=1048576)
label = "expected failure" if expect_failure else "success"
print(f"\n--- {label}: operation {operation.uuid} ---", flush=True)
cursor = None
try:
completed = False
if disconnect:
cursor, completed = consume_events(session.client, operation.uuid, disconnect_after=5)
if not completed:
if cursor is not None:
print(f"[client] resume after event {cursor}", flush=True)
_, completed = consume_events(session.client, operation.uuid, cursor=cursor)
result = operation.wait(timeout=45)
expected_exit = 1 if expect_failure else 0
if result.state.exit_code != expected_exit or result.state.timed_out is True:
raise RuntimeError(f"Unexpected test outcome: {result.state}")
if result.state.signal not in (-1, None, ...):
raise RuntimeError(f"Test process was interrupted: {result.state}")
if result.stdout.truncated is True or result.stderr.truncated is True:
raise RuntimeError("Test output was truncated")
expected_summary = "SUMMARY passed=2 failed=1" if expect_failure else "SUMMARY passed=2 failed=0"
if expected_summary not in result.stdout.as_text():
raise RuntimeError("Test suite returned an unexpected summary")
if expect_failure and "FAIL deliberate-failure" not in result.stderr.as_text():
raise RuntimeError("Failing test did not report its expected stderr")
if not completed:
raise RuntimeError("Event log ended without a completion event")
print(f"[final] operation=SUCCESS process_exit={result.state.exit_code}")
finally:
operation.shutdown()
def consume_events(client, operation_id, *, cursor=None, disconnect_after=None):
processed = 0
completed = False
# This is the transport iterator, so closing it really closes the HTTP stream.
with closing(client.follow_operation_events(operation_id, last_event_id=cursor, timeout=45)) as events:
for event in events:
if cursor is not None and event.id <= cursor:
continue
if event.type in {"stdout", "stderr"}:
if not isinstance(event.data, EventDataStream):
raise RuntimeError("Output event has an unexpected payload")
print(f"[{event.type}] {event.data.as_text()}", end="", flush=True)
elif event.type in {"spawn", "exit", "completion"}:
print(f"[event] {event.type} id={event.id}", flush=True)
# Commit only after decoding and displaying the complete event.
cursor = event.id
processed += 1
completed = event.type == "completion"
if disconnect_after is not None and processed >= disconnect_after:
print(f"[client] disconnect after processed event {cursor}", flush=True)
break
return cursor, completed
TEST_SUITE = r"""
set -u
passed=0
failed=0
check() {
label=$1
shift
if "$@"; then
printf 'PASS %s\n' "$label"
passed=$((passed + 1))
else
printf 'FAIL %s\n' "$label" >&2
failed=$((failed + 1))
fi
sleep 1
}
check arithmetic test $((2 + 2)) -eq 4
printf 'alpha\n' > /tmp/fixture.txt
check file-content grep -qx alpha /tmp/fixture.txt
# OPTIONAL_FAILURE
printf 'SUMMARY passed=%s failed=%s\n' "$passed" "$failed"
test "$failed" -eq 0
"""
main()