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.