Challenge - 5 Problems
Subprocess Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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)
Attempts:
2 left
💡 Hint
Remember that echo adds a newline and capture_output=True captures stdout as bytes or text.
✗ Incorrect
The subprocess.run with capture_output=True and text=True returns stdout as a string including the newline added by echo command.
❓ assertion
intermediate2: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?
Attempts:
2 left
💡 Hint
The 'false' command always exits with code 1 and produces no output.
✗ Incorrect
The 'false' command returns exit code 1, so checking result.returncode == 1 is correct.
🔧 Debug
advanced2: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
Attempts:
2 left
💡 Hint
Check the type of result.stdout when capture_output=True is used without text=True.
✗ Incorrect
Without text=True, result.stdout is bytes, so searching a string in bytes fails causing the assertion to fail.
❓ framework
advanced2:00remaining
Best pytest fixture for subprocess cleanup
Which pytest fixture is best to ensure subprocesses are terminated after tests?
Attempts:
2 left
💡 Hint
Subprocesses should be cleaned after each test function to avoid interference.
✗ Incorrect
Using scope='function' ensures cleanup runs after each test function, preventing subprocess leaks.
🧠 Conceptual
expert2:00remaining
Why use subprocess.check_output in tests?
What is the main advantage of using subprocess.check_output over subprocess.run in pytest tests?
Attempts:
2 left
💡 Hint
Think about how exceptions help in test failures.
✗ Incorrect
subprocess.check_output raises CalledProcessError if the command exits with non-zero code, making test failures explicit.