0
0
PyTesttesting~5 mins

Subprocess testing in PyTest

Choose your learning style9 modes available
Introduction

Subprocess testing helps check if programs run other programs correctly. It makes sure the commands and outputs are right.

When your program runs a shell command and you want to check its output.
When you want to test if an external script or tool is called properly.
When you need to verify error messages from a subprocess.
When you want to check the return code of a command your program runs.
When you want to simulate running commands without actually running them.
Syntax
PyTest
import subprocess

result = subprocess.run(['command', 'arg1', 'arg2'], capture_output=True, text=True)
print(result.stdout)
print(result.returncode)

subprocess.run() runs a command and waits for it to finish.

capture_output=True captures the output so you can check it.

Examples
This runs the echo hello command and prints its output.
PyTest
import subprocess

result = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
print(result.stdout)
This tries to list a missing folder, then prints the error message and return code.
PyTest
import subprocess

result = subprocess.run(['ls', '/nonexistent'], capture_output=True, text=True)
print(result.stderr)
print(result.returncode)
This checks the Python version by running python --version.
PyTest
import subprocess

result = subprocess.run(['python', '--version'], capture_output=True, text=True)
print(result.stdout.strip())
Sample Program

This test runs the echo hello command and checks if it returns 0 (success) and outputs 'hello'.

PyTest
import subprocess

def test_echo_hello():
    result = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
    assert result.returncode == 0
    assert result.stdout.strip() == 'hello'

if __name__ == '__main__':
    test_echo_hello()
    print('Test passed')
OutputSuccess
Important Notes

Always use capture_output=True and text=True to get readable output.

Check returncode to know if the command succeeded (0 means success).

Use strip() to remove extra spaces or newlines from output before asserting.

Summary

Subprocess testing checks commands run by your program.

Use subprocess.run() with capture_output=True to get output.

Assert on stdout, stderr, and returncode to verify behavior.