Test Overview
This test uses pytest's tmp_path fixture to create a temporary directory. It verifies that a file can be created and read inside this temporary directory.
This test uses pytest's tmp_path fixture to create a temporary directory. It verifies that a file can be created and read inside this temporary directory.
import pytest def test_create_and_read_file(tmp_path): # Create a file path inside 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 content is as expected assert content == "Hello, pytest!"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | pytest provides tmp_path fixture as a temporary directory | A new empty temporary directory is created for the test | — | PASS |
| 3 | Create a file path 'testfile.txt' inside tmp_path | Temporary directory is empty, file path is prepared | — | PASS |
| 4 | Write text 'Hello, pytest!' to the file | File 'testfile.txt' now exists with content 'Hello, pytest!' | — | PASS |
| 5 | Read text content from the file | File content read as 'Hello, pytest!' | — | PASS |
| 6 | Assert that the read content equals 'Hello, pytest!' | Content matches expected string | assert content == 'Hello, pytest!' | PASS |
| 7 | Test ends and temporary directory is cleaned up | Temporary directory and files removed | — | PASS |
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