Test subprocess call to list directory contents
Preconditions (3)
✅ Expected Result: The test passes if the subprocess call succeeds with exit code 0 and the output contains the expected file or directory name.
Jump into concepts and practice - no test required
import subprocess import sys import os import pytest def list_directory(): if sys.platform.startswith('win'): cmd = ['cmd', '/c', 'dir'] else: cmd = ['ls'] result = subprocess.run(cmd, capture_output=True, text=True) return result def test_list_directory_contains_this_file(): result = list_directory() assert result.returncode == 0, f"Subprocess failed with code {result.returncode}" # Check that the output contains this test file name this_file = os.path.basename(__file__) assert this_file in result.stdout, f"Output does not contain expected file name '{this_file}'"
The list_directory function runs the system command to list directory contents. It detects the OS to choose the right command (dir for Windows, ls for others).
We use subprocess.run with capture_output=True and text=True to get the output as a string.
The test test_list_directory_contains_this_file calls this function, then asserts the return code is 0, meaning success.
It also asserts that the output contains the current test file name, ensuring the command listed the directory contents correctly.
Assertions include messages to help understand failures.
Now add data-driven testing with 3 different commands: 'ls' or 'dir', 'echo Hello', and an invalid command to test failure.
import subprocess
def test_echo():
result = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
assert result.stdout == 'hello\n'
import subprocess
def test_fail():
result = subprocess.run(['false'], capture_output=True, text=True)
assert result.returncode == 0
result = subprocess.run(['mycmd'], capture_output=True, text=True)