0
0
PyTesttesting~10 mins

File system testing with tmp_path 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 create a new file in the temporary directory using tmp_path.

PyTest
def test_create_file(tmp_path):
    file = tmp_path / [1]
    file.write_text("Hello")
    assert file.read_text() == "Hello"
Drag options to blanks, or click blank then click option'
Atest.txt
B"test.txt"
Ctmp_file
D"tmp_file"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the file name.
Using a variable name without quotes.
2fill in blank
medium

Complete the code to check if the file exists after creation.

PyTest
def test_file_exists(tmp_path):
    file = tmp_path / "data.txt"
    file.write_text("data")
    assert file.[1]()
Drag options to blanks, or click blank then click option'
Aopen
Bis_file
Cis_dir
Dexists
Attempts:
3 left
💡 Hint
Common Mistakes
Using is_file() which checks if it is a file but not if it exists.
Using is_dir() which checks for directories.
3fill in blank
hard

Fix the error in the code to write and read text from a file using tmp_path.

PyTest
def test_write_read(tmp_path):
    file = tmp_path / "log.txt"
    file.[1]("Test log")
    content = file.read_text()
    assert content == "Test log"
Drag options to blanks, or click blank then click option'
Awrite_text
Bwrite
Cwrite_bytes
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Using write() which is not a method of Path objects.
Using write_bytes() which expects bytes, not string.
4fill in blank
hard

Fill both blanks to create a subdirectory and check if it is a directory.

PyTest
def test_subdir(tmp_path):
    subdir = tmp_path / [1]
    subdir.[2]()
    assert subdir.is_dir()
Drag options to blanks, or click blank then click option'
A"subfolder"
Bmkdir
Cmakedirs
D"folder"
Attempts:
3 left
💡 Hint
Common Mistakes
Using makedirs() which is not a method of Path objects.
Not putting the folder name in quotes.
5fill in blank
hard

Fill all three blanks to create a file, write text, and verify its size is greater than zero.

PyTest
def test_file_size(tmp_path):
    file = tmp_path / [1]
    file.[2]("content")
    assert file.stat().st_size [3] 0
Drag options to blanks, or click blank then click option'
A"output.txt"
Bwrite_text
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of > for size comparison.
Forgetting quotes around the file name.