0
0
PyTesttesting~10 mins

tmp_path and tmp_path_factory 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 the pytest fixture that provides a temporary directory as a pathlib.Path object.

PyTest
def test_create_file([1]):
    file = [1] / "test.txt"
    file.write_text("hello")
    assert file.read_text() == "hello"
Drag options to blanks, or click blank then click option'
Atmpdir
Btmp_path_factory
Ctmp_path
Dtmpfile
Attempts:
3 left
💡 Hint
Common Mistakes
Using tmp_path_factory directly in the test function instead of tmp_path.
Using tmpdir which returns a py.path.local object, not pathlib.Path.
2fill in blank
medium

Complete the code to create a new temporary directory inside the base temporary directory using tmp_path_factory.

PyTest
def test_new_temp_dir(tmp_path_factory):
    new_dir = tmp_path_factory.[1]("mydir")
    assert new_dir.exists() and new_dir.is_dir()
Drag options to blanks, or click blank then click option'
Amktemp
Bmkdir
Cmakedir
Dnewdir
Attempts:
3 left
💡 Hint
Common Mistakes
Using mkdir which is a pathlib method, not a tmp_path_factory method.
Trying to create the directory manually instead of using mktemp.
3fill in blank
hard

Fix the error in the test code to correctly create a file inside the temporary directory provided by tmp_path.

PyTest
def test_write_file(tmp_path):
    file_path = tmp_path / "data.txt"
    with open([1], "w") as f:
        f.write("data")
    assert file_path.read_text() == "data"
Drag options to blanks, or click blank then click option'
Atmp_path
Bfile_path
C"data.txt"
Dtmp_path / "data.txt"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing just the directory path tmp_path to open().
Passing the filename string instead of the full path.
4fill in blank
hard

Fill both blanks to create a new temporary directory and a file inside it using tmp_path_factory.

PyTest
def test_tmp_path_factory(tmp_path_factory):
    temp_dir = tmp_path_factory.[1]("session")
    file = temp_dir / [2]
    file.write_text("hello")
    assert file.read_text() == "hello"
Drag options to blanks, or click blank then click option'
Amktemp
B"test.txt"
C"data.log"
Dmkdir
Attempts:
3 left
💡 Hint
Common Mistakes
Using mkdir instead of mktemp for tmp_path_factory.
Using a method name instead of a string for the filename.
5fill in blank
hard

Fill all three blanks to create a temporary directory, a file inside it, and assert the file content using tmp_path_factory.

PyTest
def test_full_tmp_path_factory(tmp_path_factory):
    dir_path = tmp_path_factory.[1]("run")
    file_path = dir_path / [2]
    file_path.write_text([3])
    assert file_path.read_text() == "pytest rocks"
Drag options to blanks, or click blank then click option'
Amktemp
B"output.txt"
C"pytest rocks"
Dmkdir
Attempts:
3 left
💡 Hint
Common Mistakes
Using mkdir instead of mktemp.
Passing a variable instead of a string for filename or content.