Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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'.
✗ Incorrect
The pytest fixture for a temporary directory path object is named 'tmp_path'.
2fill in blank
mediumComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the file name causing syntax errors.
Using a variable name without quotes.
✗ Incorrect
File names must be strings with quotes in Python, so use "output.txt".
3fill in blank
hardFix 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'
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.
✗ Incorrect
The correct method to check if a path is a directory is 'is_dir()' with an underscore.
4fill in blank
hardFill 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'
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()'.
✗ Incorrect
The file name must be a string literal. To get file size, use 'stat().st_size' which directly returns the integer size.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'read_text()' instead of 'exists()' in the assertion.
Not quoting the file name.
Using wrong method names.
✗ Incorrect
Use a string file name, write_text() to write, and exists() to check file presence.