Create and verify a file using tmp_path fixture in pytest
Preconditions (2)
✅ Expected Result: The file 'testfile.txt' is created in the temporary directory with the exact content 'Hello, pytest!'
Jump into concepts and practice - no test required
import pytest def test_create_and_read_file(tmp_path): # Create a file path object for 'testfile.txt' file = tmp_path / "testfile.txt" # Write text to the file using context manager with file.open('w', encoding='utf-8') as f: f.write('Hello, pytest!') # Read the content back with file.open('r', encoding='utf-8') as f: content = f.read() # Assert the file exists assert file.exists(), f"File {file} should exist" # Assert the content is correct assert content == 'Hello, pytest!', f"File content should be 'Hello, pytest!' but was '{content}'"
This test uses the tmp_path fixture provided by pytest to get a temporary directory unique to this test run. It creates a file named testfile.txt inside this directory.
Using a context manager (with statement) ensures the file is properly opened and closed when writing and reading.
Assertions check that the file exists and that its content matches the expected string. This ensures the file system operations are working as intended in an isolated environment.
Using tmp_path keeps tests clean and avoids side effects on the real file system.
Now add data-driven testing to create and verify files with three different contents
tmp_path in pytest tests?tmp_path provides a temporary directory unique to each test run.test.txt inside the tmp_path directory in pytest?tmp_path is a pathlib.Path object, so to create a file, you combine paths with / operator.write_text() on the file path: (tmp_path / 'test.txt').write_text('Hello').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?read_text() returns the string 'pytest rocks', which matches the assertion exactly.tmp_path:
def test_file_creation(tmp_path):
file = tmp_path / 'log.txt'
file.write('Log entry')
assert file.read_text() == 'Log entry'
Path objects do not have a write() method; the correct method to write text is write_text().write() will raise an AttributeError because it does not exist on the Path object.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?tmp_path.iterdir() returns an iterator of Path objects for all entries in the directory.f.name and compare as a set to ensure exactly the three expected files exist.