0
0
PyTesttesting~10 mins

Subprocess testing in PyTest - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to run a subprocess command that lists files.

PyTest
import subprocess

def test_list_files():
    result = subprocess.run(['ls', '[1]'], capture_output=True, text=True)
    assert result.returncode == 0
Drag options to blanks, or click blank then click option'
A-z
B-a
C-x
D-l
Attempts:
3 left
💡 Hint
Common Mistakes
Using an invalid option that causes the subprocess to fail.
Forgetting to capture output which is needed for assertions.
2fill in blank
medium

Complete the code to check that the subprocess output contains the word 'test'.

PyTest
import subprocess

def test_output_contains_test():
    result = subprocess.run(['echo', 'this is a test'], capture_output=True, text=True)
    assert [1] in result.stdout
Drag options to blanks, or click blank then click option'
A'test'
B'Test'
C'TEST'
D'testing'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different case which causes the assertion to fail.
Checking for a substring not present in the output.
3fill in blank
hard

Fix the error in the subprocess call to correctly capture output as text.

PyTest
import subprocess

def test_capture_text():
    result = subprocess.run(['echo', 'hello'], [1]=True, capture_output=True)
    assert result.stdout.strip() == 'hello'
Drag options to blanks, or click blank then click option'
Atext
Bencoding
Cshell
Duniversal_newlines
Attempts:
3 left
💡 Hint
Common Mistakes
Using text=True in older Python versions where it is unsupported.
Not setting any argument, causing output to be bytes.
4fill in blank
hard

Fill both blanks to run a subprocess that checks Python version and asserts success.

PyTest
import subprocess

def test_python_version():
    result = subprocess.run(['[1]', '[2]'], capture_output=True, text=True)
    assert result.returncode == 0
Drag options to blanks, or click blank then click option'
Apython3
Bpython
C--version
D-V
Attempts:
3 left
💡 Hint
Common Mistakes
Using python3 when only python is available.
Using an invalid flag that causes the command to fail.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension filtering files ending with '.py'.

PyTest
import subprocess

def test_list_python_files():
    result = subprocess.run(['ls'], capture_output=True, text=True)
    files = { [1]: True for [2] in result.stdout.splitlines() if [3].endswith('.py') }
    assert 'test_script.py' in files
Drag options to blanks, or click blank then click option'
Afile
Bf
Cfilename
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently causing NameError.
Not filtering files ending with '.py' correctly.