From ca229ea13704cd379d507687a7a46f0d98a88a85 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Mon, 30 Nov 2026 20:04:14 -0600 Subject: [PATCH] Examples(test): Drive Python pdb from Java why: An interactive tutorial needs to show how to establish what ran. what: Drive pdb in a real pane, check the evaluated row, and verify the resumed application wrote the expected value. --- CHANGELOG.md | 4 ++ examples/README.md | 23 ++++++ .../github/libtmux/examples/DebugPython.java | 71 +++++++++++++++++++ .../io/github/libtmux/examples/MainsTest.java | 39 ++++++++-- 4 files changed, 133 insertions(+), 4 deletions(-) create mode 100644 examples/src/main/java/io/github/libtmux/examples/DebugPython.java diff --git a/CHANGELOG.md b/CHANGELOG.md index df95979db..5e6abbd18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,10 @@ release that first shipped the module. ### Documented +- **`DebugPython` inspects a paused Python program.** The Java example checks + the complete pdb output line, then verifies the file Python wrote after + resuming. (#172) + - **The Kotlin and Scala quick starts now run as standalone programs.** Each includes its build file and starts a private tmux session using the published libraries. (#203) diff --git a/examples/README.md b/examples/README.md index 443ef4484..a9eda77f5 100644 --- a/examples/README.md +++ b/examples/README.md @@ -8,6 +8,7 @@ programs with a `main`, short enough to read in one go and real enough to run. | example | shows | | --- | --- | | [`BuildAWorkspace`](src/main/java/io/github/libtmux/examples/BuildAWorkspace.java) | making a session, a window, a split, and choosing a layout | +| [`DebugPython`](#inspect-a-paused-python-program) | evaluating a value in pdb and checking the result after resuming Python | | [`FindPanesRunning`](src/main/java/io/github/libtmux/examples/FindPanesRunning.java) | typed filters over a capture, without asking tmux twice | | [`WatchPaneOutput`](src/main/java/io/github/libtmux/examples/WatchPaneOutput.java) | control mode: reading `%output` as tmux pushes it | | [`WatchWhatChanges`](src/main/java/io/github/libtmux/examples/WatchWhatChanges.java) | control mode: typed notifications as the server changes | @@ -49,6 +50,28 @@ $ java -cp examples/build/classes/java/main:libtmux/build/classes/java/main \ The Scala programs take the tmux executable, socket path and configuration file as their arguments. The Cats programs run their `IO` in `main`. +## Inspect a paused Python program + +[`DebugPython.java`](src/main/java/io/github/libtmux/examples/DebugPython.java) +runs Python's standard-library debugger on a private tmux server. Run from the +checkout with JDK 25 or newer, tmux, and `python3` on `PATH`. + +```console +$ ./gradlew :examples:compileJava +``` + +```console +$ java -cp examples/build/classes/java/main:libtmux/build/classes/java/main \ + io.github.libtmux.examples.DebugPython +``` + +pdb prints `result: 42` from a Python expression. The program checks that +complete screen line, sends `continue`, then reads the file Python wrote after +resuming. The Java program prints `Debugger printed 42` and `Program wrote 42`. + +Pass `43` after the class name to see the check reject it and report the screen. +Both runs close the private server and remove the temporary debuggee files. + ## Next - [`libtmux`](../libtmux/) ยท [Getting started](../docs/guide/getting-started.md) diff --git a/examples/src/main/java/io/github/libtmux/examples/DebugPython.java b/examples/src/main/java/io/github/libtmux/examples/DebugPython.java new file mode 100644 index 000000000..96ccdcd96 --- /dev/null +++ b/examples/src/main/java/io/github/libtmux/examples/DebugPython.java @@ -0,0 +1,71 @@ +package io.github.libtmux.examples; + +import io.github.libtmux.Pane; +import io.github.libtmux.Server; +import io.github.libtmux.ServerLaunch; +import io.github.libtmux.TextWait; +import io.github.libtmux.WakeReason; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; + +/** Inspects a paused Python program in pdb and verifies what it writes after resuming. */ +public final class DebugPython { + + private static final Duration TIMEOUT = Duration.ofSeconds(5); + private static final Path DEV_ROOT = Path.of("/tmp/libtmux-java-dev"); + private static final Path TEST_ROOT = Path.of("/tmp/libtmux-java-test"); + private static final String DEBUGGEE = """ + import pdb + from pathlib import Path + + values = [11, 13, 18] + pdb.Pdb(readrc=False).set_trace() + Path("result").write_text(str(sum(values)), encoding="utf-8") + """; + + private DebugPython() {} + + public static void main(String[] args) throws IOException, InterruptedException { + int expected = args.length == 0 ? 42 : Integer.parseInt(args[0]); + Path root = + args.length < 2 ? DEV_ROOT : Path.of(args[1]).toAbsolutePath().normalize(); + if (!root.startsWith(DEV_ROOT) && !root.startsWith(TEST_ROOT)) { + throw new IllegalArgumentException("Choose a directory under " + DEV_ROOT + " or " + TEST_ROOT); + } + Path directory = Files.createTempDirectory(Files.createDirectories(root), "pdb-"); + Path result = directory.resolve("result"); + try (Server server = Server.start(ServerLaunch.builder().root(root).build())) { + server.globalOptions().set("remain-on-exit", "on"); + Pane pane = server.newSession(session -> session.in(directory).running("python3", "-I", "-c", DEBUGGEE)) + .activePane() + .orElseThrow(); + + TextWait prompt = pane.watchText("(Pdb)", TIMEOUT); + if (prompt.output().stream().map(String::stripTrailing).noneMatch("(Pdb)"::equals)) { + throw new IllegalStateException("pdb did not start: " + prompt); + } + + pane.sendLine("!print('result:', sum(values))"); + TextWait inspected = pane.watchText("result: ", TIMEOUT); + if (!inspected.output().contains("result: " + expected)) { + throw new IllegalStateException("Expected result: " + expected + ", screen: " + inspected); + } + System.out.println("Debugger printed " + expected); + + pane.sendLine("continue"); + if (pane.await(Pane::dead, TIMEOUT) != WakeReason.SIGNALLED) { + throw new IllegalStateException("Python did not exit"); + } + String written = Files.readString(result); + if (!written.equals(Integer.toString(expected))) { + throw new IllegalStateException("Expected file to contain " + expected + ", found " + written); + } + System.out.println("Program wrote " + written); + } finally { + Files.deleteIfExists(result); + Files.delete(directory); + } + } +} diff --git a/examples/src/test/java/io/github/libtmux/examples/MainsTest.java b/examples/src/test/java/io/github/libtmux/examples/MainsTest.java index a2156c003..731307f5c 100644 --- a/examples/src/test/java/io/github/libtmux/examples/MainsTest.java +++ b/examples/src/test/java/io/github/libtmux/examples/MainsTest.java @@ -23,6 +23,8 @@ import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Every example's own {@code main}, in its own JVM, as a reader would run it. @@ -44,6 +46,7 @@ void everyExampleIsLaunched() throws IOException { assertEquals( List.of( "BuildAWorkspace", + "DebugPython", "FindPanesRunning", "RunACommand", "ServeTmuxOverMcp", @@ -62,6 +65,30 @@ void buildAWorkspace(Server server, TmuxSocketPath socket) throws Exception { assertTrue(server.hasSession("work")); } + @Test + void debugPythonRunsAndChecksTheDebuggee() throws Exception { + Path root = Path.of(System.getProperty("java.io.tmpdir"), "pdb-ok"); + String out = launch("DebugPython", "42", root.toString()); + + assertEquals("Debugger printed 42\nProgram wrote 42\n", out); + try (var children = Files.list(root)) { + assertTrue(children.findAny().isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(ints = {43, 4}) + void debugPythonRejectsAnIncorrectAnswerAndCleansUp(int expected) throws Exception { + Path root = Path.of(System.getProperty("java.io.tmpdir"), "pdb-" + expected); + String out = launchExpecting(1, "DebugPython", Integer.toString(expected), root.toString()); + + assertTrue(out.contains("Expected result: " + expected), out); + assertTrue(out.contains("result: 42"), out); + try (var children = Files.list(root)) { + assertTrue(children.findAny().isEmpty()); + } + } + @Test void findPanesRunning(TmuxSocketPath socket) throws Exception { String out = launch("FindPanesRunning", socket.path().toString(), "no-such-command-anywhere"); @@ -140,16 +167,20 @@ private static String launch(String program, String... args) throws Exception { } static String launchApiProgram(String program) throws Exception { - return launch(Duration.ofSeconds(60), false, List.of(), program); + return launch(Duration.ofSeconds(60), false, List.of(), 0, program); } /** Runs the example's {@code main} in a fresh JVM and returns what it printed. */ private static String launch(Duration deadline, String program, String... args) throws Exception { - return launch(deadline, true, List.of(), program, args); + return launch(deadline, true, List.of(), 0, program, args); + } + + private static String launchExpecting(int exit, String program, String... args) throws Exception { + return launch(Duration.ofSeconds(60), true, List.of(), exit, program, args); } private static String launch( - Duration deadline, boolean combineError, List prefix, String program, String... args) + Duration deadline, boolean combineError, List prefix, int exit, String program, String... args) throws Exception { List command = new ArrayList<>(prefix); command.addAll(List.of( @@ -184,7 +215,7 @@ private static String launch( fail(program + " did not exit within " + deadline + ", and printed:\n" + text(printed)); } String out = text(printed); - assertEquals(0, process.exitValue(), program + " printed:\n" + out); + assertEquals(exit, process.exitValue(), program + " printed:\n" + out); return out; }