Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(cli): cfn test broken on Windows - NamedTemporaryFile issue #924

Merged
merged 4 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/rpdk/core/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,14 +77,27 @@ def empty_hook_override():
return {"CREATE_PRE_PROVISION": {}}


# As per Python docs NamedTemporaryFile does NOT work the same in Windows. Setting delete=False as workaround.
#
# Temporary file must be explicitly cleaned up after temporary_ini_file() is called!
#
# "Whether the name can be used to open the file a second time, while the named temporary file is still open,
# varies across platforms (it can be so used on Unix; it cannot on Windows)."
# https://docs.python.org/3.9/library/tempfile.html#tempfile.NamedTemporaryFile
#
# Fix being tracked here https://github.com/python/cpython/issues/58451


@contextmanager
def temporary_ini_file():
with NamedTemporaryFile(
mode="w", encoding="utf-8", prefix="pytest_", suffix=".ini"
mode="w", encoding="utf-8", prefix="pytest_", suffix=".ini", delete=False
) as temp:
LOG.debug("temporary pytest.ini path: %s", temp.name)
path = Path(temp.name).resolve(strict=True)
copy_resource(__name__, "data/pytest-contract.ini", path)
# Close temporary file for other processes to use, needed on Windows
temp.close()
yield str(path)


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

Expand Down
5 changes: 5 additions & 0 deletions tests/test_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,11 @@ def test_temporary_ini_file():

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


def test_get_overrides_no_root():
Expand Down