0
0
PyTesttesting~15 mins

Subprocess testing in PyTest - Build an Automation Script

Choose your learning style9 modes available
Test subprocess call to list directory contents
Preconditions (3)
Step 1: Write a Python function that uses subprocess.run to execute 'ls' (Linux/macOS) or 'dir' (Windows) command
Step 2: Capture the output of the subprocess call
Step 3: Write a pytest test function to call this function
Step 4: Assert that the subprocess call returns exit code 0
Step 5: Assert that the output contains at least one known file or directory name (e.g., the current script file or folder)
✅ Expected Result: The test passes if the subprocess call succeeds with exit code 0 and the output contains the expected file or directory name.
Automation Requirements - pytest
Assertions Needed:
Assert subprocess returncode is 0
Assert output contains expected file or directory name
Best Practices:
Use subprocess.run with capture_output=True and text=True for easy output handling
Use pytest fixtures if needed for setup
Avoid hardcoding OS-specific commands; use platform detection
Use clear and descriptive assertion messages
Automated Solution
PyTest
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.

Common Mistakes - 3 Pitfalls
Using subprocess.call instead of subprocess.run
{'mistake': "Hardcoding 'ls' command without OS check", 'why_bad': "The 'ls' command does not work on Windows, causing test failures on that platform.", 'correct_approach': "Detect the OS using sys.platform and choose 'dir' for Windows and 'ls' for others."}
Not checking subprocess return code before using output
Bonus Challenge

Now add data-driven testing with 3 different commands: 'ls' or 'dir', 'echo Hello', and an invalid command to test failure.

Show Hint