Skip to content

Commit c16c209

Browse files
kenjitoyamacopybara-github
authored andcommitted
Pass delete_on_close=False to NamedTemporaryFile().
The behavior of [`NamedTemporaryFile()`](https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile) is slightly different on Windows when the file is accessed multiple times in the same context manager. `delete_on_close=False` allows the file to exist until the end of the context manager, which is the behavior we want in all platforms. Unfortunately this argument was only added in Python `3.12`, so we add a switch to support earlier versions. We may remove it in the future once `3.11` is EOL. Please see PR #265 for details (and thanks to @NingLi670 for opening the original PR). PiperOrigin-RevId: 732961399
1 parent b8e0d77 commit c16c209

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

android_env/components/adb_call_parser.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,15 @@ def _install_apk(
280280
['install', '-r', '-t', '-g', fpath], timeout=timeout
281281
)
282282
case 'blob':
283-
with tempfile.NamedTemporaryFile(suffix='.apk') as f:
283+
284+
# `delete_on_close` was only added in Python 3.12 so we add a switch
285+
# here to still support previous Python versions.
286+
if sys.version_info >= (3, 12):
287+
kwargs = {'suffix': '.apk', 'delete_on_close': False}
288+
else:
289+
kwargs = {'suffix': '.apk'}
290+
291+
with tempfile.NamedTemporaryFile(**kwargs) as f:
284292
fpath = f.name
285293
f.write(install_apk.blob.contents)
286294

android_env/components/adb_call_parser_test.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,13 @@ def test_install_apk_from_blob(self, mock_tempfile):
9898
['install', '-r', '-t', '-g', '/my/home/test.apk'], None
9999
)
100100
# pytype: disable=attribute-error
101+
expected_tempfile_kwargs = (
102+
{'suffix': '.apk', 'delete_on_close': False}
103+
if sys.version_info > (3, 12)
104+
else {'suffix': '.apk'}
105+
)
101106
mock_tempfile.assert_has_calls([
102-
mock.call(suffix='.apk'), # Constructor
107+
mock.call(**expected_tempfile_kwargs), # Constructor
103108
mock.call().__enter__(), # Enter context
104109
mock.call().__enter__().write(blob_content), # Call write function
105110
mock.call().__exit__(None, None, None), # Exit context

0 commit comments

Comments
 (0)