Skip to content

Commit e06a619

Browse files
committed
tests: remove the temporary directory make_nifti_image creates
make_nifti_image creates a mkdtemp directory to hold the image but returns only the file path, so the directory outlives every call. The four callers that delete the file still leave the directory behind; running tests/data/test_nifti_rw.py alone left 65 of them in the system temp dir. Register the directory for removal at interpreter exit when the helper created it, and leave caller-supplied directories alone. Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
1 parent ed76cd5 commit e06a619

2 files changed

Lines changed: 27 additions & 2 deletions

File tree

tests/data/test_make_nifti.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@
1111

1212
from __future__ import annotations
1313

14+
import atexit
1415
import os
16+
import shutil
17+
import subprocess
18+
import sys
1519
import tempfile
1620
import unittest
1721

@@ -26,8 +30,10 @@
2630
_, has_nib = optional_import("nibabel")
2731

2832
TESTS = []
33+
caller_owned_dir = tempfile.mkdtemp()
34+
atexit.register(shutil.rmtree, caller_owned_dir, ignore_errors=True)
2935
for affine in (None, np.eye(4), torch.eye(4)):
30-
for dir in (None, tempfile.mkdtemp()):
36+
for dir in (None, caller_owned_dir):
3137
for fname in (None, "fname"):
3238
TESTS.append([{"affine": affine, "dir": dir, "fname": fname}])
3339

@@ -40,6 +46,21 @@ def test_make_nifti(self, params):
4046
created_file = make_nifti_image(im, verbose=True, **params)
4147
self.assertTrue(os.path.isfile(created_file))
4248

49+
def test_temp_dir_removed_at_exit(self):
50+
script = (
51+
"from monai.data.synthetic import create_test_image_2d;"
52+
"from tests.test_utils import make_nifti_image;"
53+
"print(make_nifti_image(create_test_image_2d(100, 88)[0]))"
54+
)
55+
created_file = subprocess.check_output([sys.executable, "-c", script], text=True).strip()
56+
self.assertFalse(os.path.exists(os.path.dirname(created_file)))
57+
58+
def test_caller_owned_dir_kept(self):
59+
im, _ = create_test_image_2d(100, 88)
60+
with tempfile.TemporaryDirectory() as caller_dir:
61+
make_nifti_image(im, dir=caller_dir)
62+
self.assertTrue(os.path.isdir(caller_dir))
63+
4364

4465
if __name__ == "__main__":
4566
unittest.main()

tests/test_utils.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from __future__ import annotations
1313

1414
import argparse
15+
import atexit
1516
import copy
1617
import datetime
1718
import functools
@@ -20,6 +21,7 @@
2021
import operator
2122
import os
2223
import queue
24+
import shutil
2325
import ssl
2426
import subprocess
2527
import sys
@@ -391,7 +393,8 @@ def make_nifti_image(
391393
):
392394
"""
393395
Create a temporary nifti image on the disk and return the image name.
394-
User is responsible for deleting the temporary file when done with it.
396+
If `dir` is not given, a temporary directory is created to hold the image and removed at
397+
interpreter exit. If `dir` is given, the caller owns it.
395398
"""
396399
if isinstance(array, torch.Tensor):
397400
array, *_ = convert_data_type(array, np.ndarray)
@@ -404,6 +407,7 @@ def make_nifti_image(
404407
# if dir not given, create random. Else, make sure it exists.
405408
if dir is None:
406409
dir = tempfile.mkdtemp()
410+
atexit.register(shutil.rmtree, dir, ignore_errors=True)
407411
else:
408412
os.makedirs(dir, exist_ok=True)
409413

0 commit comments

Comments
 (0)