August 29, 2022

Creating Pseudo Terminals for Test Scripts with tmux

I recently tried to automate a test setup, where the program I tried to automate insisted on having a TTY. Oh no, yet another TTY adventure (previous one) for me ;).

Puppeteering TTYs
Figure 1. Puppeteering TTYs

The program did not interact with a TTY, but it just shut itself down automatically without a TTY. So, I needed a way to create a TTY in my test script.

I searched and searched, and couldn’t find a good utility for it. Either the utilities seem very obscure (download this source, compile it yourself, btw no docs), or you needed to create a python script, etc

Luckily, I found this Unix Stack Exchange answer. The solution: Use tmux to run the program with a pseudo terminal. I would have never thought of that. I use tmux once in a while, but I only knew if is an interactive tool. I would not have though it as a tool for scripting.

Here is how you do it:

# Create a new tmux session
tmux new-session -s 'app-under-test-session' -d -x 140 -y 35
# Create a new tmux windows, where the app is running
tmux new-window -t 'app-under-test-session' -n 'app-window' -d ' > app-log.log'

# Do the test with the app.

# Bonus, stopping the tmux session cleans up sub processes etc as well
tmux kill-session -t 'app-under-test-session'

Bonus: you can inspect the scripted session with tmux attach, like any other tmux session:

tmux attach -t 'app-under-test-session'

Anyway, tmux allowed me to create a pseudo TTY for programs which insist on having a pseudo TTY.

Tags: Unix Development