Bird
Raised Fist0
PyTesttesting~20 mins

File system testing with tmp_path in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
tmp_path Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of pytest tmp_path file creation
What will be the output of this pytest test when run?
def test_create_file(tmp_path):
    file = tmp_path / "test.txt"
    file.write_text("hello")
    content = file.read_text()
    print(content)
    assert content == "hello"
PyTest
def test_create_file(tmp_path):
    file = tmp_path / "test.txt"
    file.write_text("hello")
    content = file.read_text()
    print(content)
    assert content == "hello"
APrints 'hello' but test fails
BPrints 'hello' and test passes
CRaises FileNotFoundError
DPrints empty string and test fails
Attempts:
2 left
💡 Hint
tmp_path creates a temporary directory unique to the test.
assertion
intermediate
2:00remaining
Correct assertion for file existence with tmp_path
Which assertion correctly checks that a file named 'data.csv' exists in the tmp_path directory?
PyTest
def test_file_exists(tmp_path):
    file = tmp_path / "data.csv"
    file.write_text("id,name\n1,Alice")
    # Which assertion is correct here?
Aassert file.read_text() == ''
Bassert file.is_file()
Cassert tmp_path.exists()
Dassert file.exists()
Attempts:
2 left
💡 Hint
Check if the file path exists on the filesystem.
🔧 Debug
advanced
2:00remaining
Debug failing test with tmp_path and file write
This test fails with an error. What is the cause?
def test_write_file(tmp_path):
    file = tmp_path / "output.txt"
    file.write("data")
    assert file.read_text() == "data"
PyTest
def test_write_file(tmp_path):
    file = tmp_path / "output.txt"
    file.write("data")
    assert file.read_text() == "data"
Aread_text() returns bytes, causing assertion failure
BFile path is incorrect, should use str(file)
Cwrite() is not a method on pathlib.Path, should use write_text()
Dtmp_path is read-only, cannot write files
Attempts:
2 left
💡 Hint
Check pathlib.Path methods for writing text.
🧠 Conceptual
advanced
2:00remaining
Why use tmp_path over tmpdir in pytest?
Which reason best explains why pytest recommends using tmp_path instead of tmpdir for file system tests?
Atmp_path provides pathlib.Path objects which are more modern and easier to use
Btmpdir creates files in the system root directory causing permission errors
Ctmp_path runs tests faster by caching files between tests
Dtmpdir does not clean up files after tests finish
Attempts:
2 left
💡 Hint
Consider the type of object returned by each fixture.
framework
expert
2:00remaining
Handling cleanup of nested directories with tmp_path
In a pytest test using tmp_path, you create nested directories and files:
def test_nested(tmp_path):
    nested_dir = tmp_path / "a" / "b" / "c"
    nested_dir.mkdir(parents=True)
    file = nested_dir / "file.txt"
    file.write_text("content")
    # After test finishes, what happens to these files and directories?
AAll files and directories under tmp_path are deleted automatically after the test
BOnly the top-level tmp_path directory is deleted, nested files remain
CFiles remain but directories are deleted, causing orphan files
DNothing is deleted automatically; manual cleanup is required
Attempts:
2 left
💡 Hint
pytest tmp_path fixture manages cleanup automatically.

Practice

(1/5)
1. What is the main purpose of using tmp_path in pytest tests?
easy
A. To mock file system calls without creating real files
B. To permanently store test files for later use
C. To speed up test execution by caching files
D. To create a temporary directory unique to each test for safe file operations

Solution

  1. Step 1: Understand tmp_path functionality

    tmp_path provides a temporary directory unique to each test run.
  2. Step 2: Identify its purpose in tests

    This temporary directory allows safe creation, reading, and deletion of files without affecting the real file system.
  3. Final Answer:

    To create a temporary directory unique to each test for safe file operations -> Option D
  4. Quick Check:

    tmp_path = safe temp folder [OK]
Hint: Remember tmp_path is a safe temp folder for each test [OK]
Common Mistakes:
  • Thinking tmp_path stores files permanently
  • Confusing tmp_path with mocking file calls
  • Assuming tmp_path speeds up tests by caching
2. Which of the following is the correct way to create a new file named test.txt inside the tmp_path directory in pytest?
easy
A. (tmp_path / 'test.txt').write_text('Hello')
B. tmp_path / 'test.txt'.write_text('Hello')
C. tmp_path.write_text('test.txt', 'Hello')
D. tmp_path.write('test.txt', 'Hello')

Solution

  1. Step 1: Understand tmp_path usage

    tmp_path is a pathlib.Path object, so to create a file, you combine paths with / operator.
  2. Step 2: Correct syntax for writing text

    Use parentheses to combine path and then call write_text() on the file path: (tmp_path / 'test.txt').write_text('Hello').
  3. Final Answer:

    (tmp_path / 'test.txt').write_text('Hello') -> Option A
  4. Quick Check:

    Use (tmp_path / filename).write_text() [OK]
Hint: Use parentheses to combine path before write_text() [OK]
Common Mistakes:
  • Calling write_text directly on tmp_path
  • Missing parentheses around path combination
  • Using incorrect method names like write()
3. Given the following pytest test code using tmp_path:
def test_write_and_read(tmp_path):
    file = tmp_path / 'data.txt'
    file.write_text('pytest rocks')
    content = file.read_text()
    assert content == 'pytest rocks'
What will be the result of running this test?
medium
A. Test passes because the file content matches the assertion
B. Test fails because the file is not created
C. Test fails because read_text() returns bytes, not string
D. Test raises a syntax error

Solution

  1. Step 1: Analyze file creation and writing

    The code creates a file named 'data.txt' in tmp_path and writes the string 'pytest rocks' correctly.
  2. Step 2: Analyze reading and assertion

    Reading the file with read_text() returns the string 'pytest rocks', which matches the assertion exactly.
  3. Final Answer:

    Test passes because the file content matches the assertion -> Option A
  4. Quick Check:

    write_text + read_text = matching string [OK]
Hint: write_text and read_text use strings, so assertion matches [OK]
Common Mistakes:
  • Thinking read_text returns bytes instead of string
  • Assuming file is not created automatically
  • Confusing syntax errors with runtime behavior
4. Identify the error in this pytest test using tmp_path:
def test_file_creation(tmp_path):
    file = tmp_path / 'log.txt'
    file.write('Log entry')
    assert file.read_text() == 'Log entry'
medium
A. Missing parentheses around tmp_path / 'log.txt'
B. The assertion compares bytes to string causing failure
C. Using write() instead of write_text() causes an AttributeError
D. The test will pass without errors

Solution

  1. Step 1: Check method used to write file

    Path objects do not have a write() method; the correct method to write text is write_text().
  2. Step 2: Understand error caused

    Calling write() will raise an AttributeError because it does not exist on the Path object.
  3. Final Answer:

    Using write() instead of write_text() causes an AttributeError -> Option C
  4. Quick Check:

    Use write_text() to write strings to files [OK]
Hint: Use write_text() for writing strings to files [OK]
Common Mistakes:
  • Confusing write() with write_text()
  • Ignoring method errors and expecting test pass
  • Assuming parentheses are missing around path
5. You want to test a function that creates multiple files inside a directory using pytest's tmp_path. Which approach correctly verifies that exactly three files named a.txt, b.txt, and c.txt exist in the temporary directory after the function runs?
hard
A. Use assert tmp_path.read_text() == 'a.txtb.txtc.txt'
B. Use assert set(f.name for f in tmp_path.iterdir()) == {'a.txt', 'b.txt', 'c.txt'}
C. Use assert tmp_path.glob('*.txt') == ['a.txt', 'b.txt', 'c.txt']
D. Use assert tmp_path.exists('a.txt') and tmp_path.exists('b.txt') and tmp_path.exists('c.txt')

Solution

  1. Step 1: Understand how to list files in tmp_path

    tmp_path.iterdir() returns an iterator of Path objects for all entries in the directory.
  2. Step 2: Verify file names correctly

    Extract file names with f.name and compare as a set to ensure exactly the three expected files exist.
  3. Final Answer:

    Use assert set(f.name for f in tmp_path.iterdir()) == {'a.txt', 'b.txt', 'c.txt'} -> Option B
  4. Quick Check:

    Use iterdir() and set comparison for exact files [OK]
Hint: Use set of filenames from iterdir() to check exact files [OK]
Common Mistakes:
  • Using glob() without converting to list or set
  • Trying to read tmp_path as a file
  • Using exists() incorrectly on tmp_path object