0
0
PyTesttesting~10 mins

Temporary directory management 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 use pytest's temporary directory fixture.

PyTest
def test_create_file([1]):
    file_path = tmp_path / "test.txt"
    file_path.write_text("hello")
    assert file_path.read_text() == "hello"
Drag options to blanks, or click blank then click option'
Atmp_path
Btempfile
Ctemp_dir
Dtmpdir
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'tmpdir' which is a different fixture returning py.path.local object.
Using undefined fixture names like 'temp_dir' or 'tempfile'.
2fill in blank
medium

Complete the code to create a file inside the pytest temporary directory.

PyTest
def test_write_file(tmp_path):
    file = tmp_path / [1]
    file.write_text("data")
    assert file.read_text() == "data"
Drag options to blanks, or click blank then click option'
Aoutput.txt
B"output.txt"
C'output.txt'
Doutput
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the file name causing syntax errors.
Using a variable name without quotes.
3fill in blank
hard

Fix the error in the test that tries to check if a directory exists in the pytest temp path.

PyTest
def test_dir_exists(tmp_path):
    dir_path = tmp_path / "subdir"
    dir_path.mkdir()
    assert dir_path.[1]()
Drag options to blanks, or click blank then click option'
Aisfile
Bexists
Cis_dir
Disdir
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'exists()' which returns True for files and directories.
Using 'isdir()' which is not a valid pathlib method.
Using 'isfile()' which checks for files, not directories.
4fill in blank
hard

Fill both blanks to create a file and check its size in the pytest temporary directory.

PyTest
def test_file_size(tmp_path):
    file = tmp_path / [1]
    file.write_text("abc")
    size = file.[2]
    assert size == 3
Drag options to blanks, or click blank then click option'
A"data.txt"
Bstat
Cstat().st_size
Dstat().st_size()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'stat' which returns the stat object, not the size.
Using 'stat().st_size()' which is invalid because 'st_size' is an attribute, not a method.
Not quoting the file name.
Trying to get size directly without 'stat()'.
5fill in blank
hard

Fill all three blanks to create a file, write text, and verify the file exists in pytest temp directory.

PyTest
def test_file_creation(tmp_path):
    file = tmp_path / [1]
    file.[2]("hello world")
    assert file.[3]()
Drag options to blanks, or click blank then click option'
A"hello.txt"
Bwrite_text
Cexists
Dread_text
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read_text()' instead of 'exists()' in the assertion.
Not quoting the file name.
Using wrong method names.