Skip to content

Commit 3491f7a

Browse files
authored
fix(cli): cfn test broken on Windows - NamedTemporaryFile issue (#924)
* Work around to temporary_ini_file to work on Windows * Fix formating and unit tests * Explicitly close file in temporary_ini_file and catch FileNotFoundError exceptions
1 parent 03d369c commit 3491f7a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/rpdk/core/test.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,27 @@ def empty_hook_override():
7777
return {"CREATE_PRE_PROVISION": {}}
7878

7979

80+
# As per Python docs NamedTemporaryFile does NOT work the same in Windows. Setting delete=False as workaround.
81+
#
82+
# Temporary file must be explicitly cleaned up after temporary_ini_file() is called!
83+
#
84+
# "Whether the name can be used to open the file a second time, while the named temporary file is still open,
85+
# varies across platforms (it can be so used on Unix; it cannot on Windows)."
86+
# https://docs.python.org/3.9/library/tempfile.html#tempfile.NamedTemporaryFile
87+
#
88+
# Fix being tracked here https://github.com/python/cpython/issues/58451
89+
90+
8091
@contextmanager
8192
def temporary_ini_file():
8293
with NamedTemporaryFile(
83-
mode="w", encoding="utf-8", prefix="pytest_", suffix=".ini"
94+
mode="w", encoding="utf-8", prefix="pytest_", suffix=".ini", delete=False
8495
) as temp:
8596
LOG.debug("temporary pytest.ini path: %s", temp.name)
8697
path = Path(temp.name).resolve(strict=True)
8798
copy_resource(__name__, "data/pytest-contract.ini", path)
99+
# Close temporary file for other processes to use, needed on Windows
100+
temp.close()
88101
yield str(path)
89102

90103

@@ -394,6 +407,11 @@ def invoke_test(args, project, overrides, inputs):
394407
pytest_args.extend(args.passed_to_pytest)
395408
LOG.debug("pytest args: %s", pytest_args)
396409
ret = pytest.main(pytest_args, plugins=[plugin])
410+
# Manually clean up temporary file before exiting - issue with NamedTemporaryFile method on Windows
411+
try:
412+
os.unlink(path)
413+
except FileNotFoundError:
414+
pass
397415
if ret:
398416
raise SysExitRecommendedError("One or more contract tests failed")
399417

tests/test_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,11 @@ def test_temporary_ini_file():
337337

338338
with path.open("r", encoding="utf-8") as f:
339339
assert "[pytest]" in f.read()
340+
# Manually clean up temporary file before exiting - issue with NamedTemporaryFile method on Windows
341+
try:
342+
os.unlink(path_str)
343+
except FileNotFoundError:
344+
pass
340345

341346

342347
def test_get_overrides_no_root():

0 commit comments

Comments
 (0)