39 lines
1.3 KiB
Python
39 lines
1.3 KiB
Python
import os
|
|
import tempfile
|
|
import pytest
|
|
|
|
import pathlib
|
|
|
|
from lib.main import write_content_to_file
|
|
|
|
|
|
@pytest.mark.parametrize("test_input", ["Expected content", "Incorrect content"])
|
|
def test(test_input, temp_file_path, cleanups):
|
|
|
|
write_content_to_file(test_input, temp_file_path)
|
|
|
|
def in_test_print_out_on_test_failure():
|
|
print(f'(In-test cleanup) Test using tempfile {temp_file_path} failed')
|
|
cleanups.add_failure(in_test_print_out_on_test_failure)
|
|
|
|
assert temp_file_path.read_text() == "Expected content"
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
def temp_file_path(cleanups) -> pathlib.Path:
|
|
# In real production use, you'd be more likely to use methods from the `tempfile` library
|
|
# (https://docs.python.org/3/library/tempfile.html) directly - but I'm implementing this fixture by-hand to
|
|
# demonstrate that the `cleanups` object can handle cleanup-methods being attached from within a fixture.
|
|
f = tempfile.NamedTemporaryFile(delete=False, dir='.')
|
|
path = pathlib.Path(f.name)
|
|
|
|
def delete_temp_file_on_test_success():
|
|
path.unlink()
|
|
cleanups.add_success(delete_temp_file_on_test_success)
|
|
|
|
def print_out_temp_file_path_on_test_failure():
|
|
print(f'Test failed involving tempfile {path}')
|
|
cleanups.add_failure(print_out_temp_file_path_on_test_failure)
|
|
|
|
return path |