Test Overview
This test creates a temporary file using pytest's tmp_path fixture, writes text to it, reads the text back, and verifies the content matches what was written.
Jump into concepts and practice - no test required
This test creates a temporary file using pytest's tmp_path fixture, writes text to it, reads the text back, and verifies the content matches what was written.
import pytest def test_write_and_read_file(tmp_path): # Create a temporary file path file = tmp_path / "testfile.txt" # Write text to the file file.write_text("Hello, pytest!") # Read text from the file content = file.read_text() # Verify the content is correct assert content == "Hello, pytest!"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initializes with tmp_path fixture ready | — | PASS |
| 2 | tmp_path fixture provides a temporary directory path | Temporary directory created in system temp location | — | PASS |
| 3 | Create a file path 'testfile.txt' inside tmp_path | File path object points to a new file in temp directory | — | PASS |
| 4 | Write text 'Hello, pytest!' to the file | File 'testfile.txt' contains the text 'Hello, pytest!' | — | PASS |
| 5 | Read text content from the file | Content read from 'testfile.txt' is 'Hello, pytest!' | — | PASS |
| 6 | Assert that read content equals 'Hello, pytest!' | Comparison between expected and actual content | content == 'Hello, pytest!' | PASS |
| 7 | Test ends successfully | Temporary files cleaned up automatically by pytest | — | PASS |
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.