Verify temporary directory creation and cleanup using pytest tmp_path fixture
Preconditions (2)
✅ Expected Result: The file 'testfile.txt' is created with correct content during the test, and the temporary directory is removed after test completion
import pytest def test_temporary_directory(tmp_path): # Create a file path in the temporary directory file_path = tmp_path / "testfile.txt" # Write text to the file file_path.write_text("Hello, pytest!") # Read the text back content = file_path.read_text() # Assert the file exists assert file_path.exists(), f"File {file_path} should exist" # Assert the content is correct assert content == "Hello, pytest!", f"File content should be 'Hello, pytest!' but was '{content}'" # Note: pytest automatically cleans up tmp_path after test execution
This test uses the tmp_path fixture provided by pytest to create a temporary directory unique to the test run.
We create a file testfile.txt inside this directory and write the string 'Hello, pytest!' to it.
Then, we read the file content and assert that the file exists and the content matches what we wrote.
We rely on pytest to automatically delete the temporary directory and its contents after the test finishes, so no manual cleanup is needed.
This approach keeps tests isolated and avoids side effects on the real file system.
Now add data-driven testing to create multiple files with different names and contents using pytest parametrize
tmp_path fixture in pytest?tmp_path in pytesttmp_path fixture provides a temporary directory unique to each test run.tmp_path fixture in a pytest test function?tmp_path as a function argument automatically.tmp_path / 'filename' creates a Path object; write_text() writes content correctly.def test_write_read(tmp_path):
file = tmp_path / 'data.txt'
file.write_text('pytest')
content = file.read_text()
assert content == 'pytest'tmp_path:def test_error(tmp_path):
file = tmp_path + '/file.txt'
file.write_text('error')tmp_path is a Path object; using + with string causes TypeError.tmp_path / 'file.txt' to join paths properly.tmp_path and write a file in the deepest folder. Which code snippet correctly does this in pytest?mkdir(parents=True) is needed to create all missing parents./ operator joins paths correctly; writing text to file is valid.parents=True, so mkdir fails if parents missing. def test_nested(tmp_path):\n nested_dir = tmp_path / 'a' / 'b' / 'c'\n file = nested_dir / 'file.txt'\n file.write_text('nested') does not create directories before writing file. def test_nested(tmp_path):\n nested_dir = tmp_path + '/a/b/c'\n nested_dir.mkdir(parents=True)\n file = nested_dir / 'file.txt'\n file.write_text('nested') uses + operator incorrectly for paths.Pass the test and this pattern moves unknown