0
0
PyTesttesting~20 mins

Subprocess testing in PyTest - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Subprocess Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of subprocess.run with capture
What is the output of this pytest test when running the subprocess call?
PyTest
import subprocess

def test_echo():
    result = subprocess.run(['echo', 'hello'], capture_output=True, text=True)
    assert result.stdout == 'hello\n'
    print(result.stdout)
Ahello
Bhello\n
C['hello']
DNone
Attempts:
2 left
💡 Hint
Remember that echo adds a newline and capture_output=True captures stdout as bytes or text.
assertion
intermediate
2:00remaining
Correct assertion for subprocess error
Which assertion correctly checks that a subprocess call failed with exit code 1?
PyTest
import subprocess

def test_fail():
    result = subprocess.run(['false'])
    # Which assertion is correct here?
Aassert result.returncode == 1
Bassert result.returncode == 0
Cassert result.stdout == 'error'
Dassert result.stderr == 'failed'
Attempts:
2 left
💡 Hint
The 'false' command always exits with code 1 and produces no output.
🔧 Debug
advanced
2:00remaining
Identify the bug in subprocess test
Why does this pytest test fail unexpectedly?
PyTest
import subprocess

def test_ls():
    result = subprocess.run(['ls', '-l'], capture_output=True)
    assert b'README.md' in result.stdout
AThe 'ls' command is not available on Windows
Bcapture_output=True disables stdout
Cresult.stdout is bytes, so 'README.md' in bytes fails
DThe assertion syntax is invalid
Attempts:
2 left
💡 Hint
Check the type of result.stdout when capture_output=True is used without text=True.
framework
advanced
2:00remaining
Best pytest fixture for subprocess cleanup
Which pytest fixture is best to ensure subprocesses are terminated after tests?
A
@pytest.fixture(autouse=True)
def cleanup_subprocess():
    yield
    # terminate subprocesses here
B
@pytest.fixture(scope='session')
def cleanup_subprocess():
    # terminate subprocesses here
C
@pytest.fixture(scope='module')
def cleanup_subprocess():
    yield
    # terminate subprocesses here
D
@pytest.fixture(scope='function')
def cleanup_subprocess():
    yield
    # terminate subprocesses here
Attempts:
2 left
💡 Hint
Subprocesses should be cleaned after each test function to avoid interference.
🧠 Conceptual
expert
2:00remaining
Why use subprocess.check_output in tests?
What is the main advantage of using subprocess.check_output over subprocess.run in pytest tests?
Acheck_output raises an exception if the command fails, simplifying error detection
Bcheck_output automatically retries failed commands
Ccheck_output runs commands asynchronously
Dcheck_output captures stderr by default, unlike run
Attempts:
2 left
💡 Hint
Think about how exceptions help in test failures.