temp_file helper now uses and returns pathlib.Path

This commit is contained in:
Pedro Algarvio 2020-12-04 04:52:03 +00:00
parent 19c72464df
commit 8cbc51737a

View file

@ -15,7 +15,6 @@ import warnings
from contextlib import contextmanager
import pytest
import salt.utils.files
from tests.support.pytest.loader import LoaderModuleMock
from tests.support.runtests import RUNTIME_VARS
@ -106,18 +105,20 @@ def temp_file(name=None, contents=None, directory=None, strip_first_newline=True
try:
if directory is None:
directory = RUNTIME_VARS.TMP
elif isinstance(directory, pathlib.Path):
directory = str(directory)
if not isinstance(directory, pathlib.Path):
directory = pathlib.Path(str(directory))
if name is not None:
file_path = os.path.join(directory, name)
file_path = directory / name
else:
handle, file_path = tempfile.mkstemp(dir=directory)
handle, file_path = tempfile.mkstemp(dir=str(directory))
os.close(handle)
file_path = pathlib.Path(file_path)
file_directory = os.path.dirname(file_path)
if not os.path.isdir(file_directory):
os.makedirs(file_directory)
file_directory = file_path.parent
if not file_directory.is_dir():
file_directory.mkdir(parents=True)
if contents is not None:
if contents:
@ -127,10 +128,9 @@ def temp_file(name=None, contents=None, directory=None, strip_first_newline=True
else:
file_contents = contents
with salt.utils.files.fopen(file_path, "w") as wfh:
wfh.write(file_contents)
log_contents = "{0} Contents {0}\n{1}\n{2} Contents {2}".format(
">" * 15, file_contents, "<" * 15
file_path.write_text(file_contents)
log_contents = "{0} Contents of {1}\n{2}\n{3} Contents of {1}".format(
">" * 6, file_path, file_contents, "<" * 6
)
log.debug("Created temp file: %s\n%s", file_path, log_contents)
else:
@ -139,12 +139,9 @@ def temp_file(name=None, contents=None, directory=None, strip_first_newline=True
yield file_path
finally:
try:
os.unlink(file_path)
if file_path.exists():
file_path.unlink()
log.debug("Deleted temp file: %s", file_path)
except OSError:
# Already deleted
pass
@pytest.helpers.register