Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/source/apps.rst
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ Applications

.. autofunction:: download_and_extract

.. autofunction:: create_temp_dir

`Deepgrow`
----------

Expand Down
1 change: 1 addition & 0 deletions monai/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
SUPPORTED_HASH_TYPES,
HashCheckError,
check_hash,
create_temp_dir,
download_and_extract,
download_url,
extractall,
Expand Down
38 changes: 37 additions & 1 deletion monai/apps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from __future__ import annotations

import atexit
import hashlib
import json
import logging
Expand All @@ -29,7 +30,7 @@
from urllib.request import urlopen, urlretrieve

from monai.config.type_definitions import PathLike
from monai.utils import look_up_option, min_version, optional_import
from monai.utils import MONAIEnvVars, look_up_option, min_version, optional_import
from monai.utils.deprecate_utils import warn_deprecated

requests, has_requests = optional_import("requests")
Expand All @@ -46,6 +47,7 @@
__all__ = [
"HashCheckError",
"check_hash",
"create_temp_dir",
"download_url",
"extractall",
"download_and_extract",
Expand Down Expand Up @@ -520,3 +522,37 @@ def download_and_extract(
filename = filepath or Path(tmp_dir, get_filename_from_url(url)).resolve()
download_url(url=url, filepath=filename, hash_val=hash_val, hash_type=hash_type, progress=progress)
extractall(filepath=filename, output_dir=output_dir, file_type=file_type, has_base=has_base)


def create_temp_dir(directory: PathLike | None = None, delete_on_finalise: bool = False) -> str:
"""
Creates or uses an existing temporary directory. If `directory` is given, this is used as the path to a directory
which is created if it doesn't exist already. If `directory` is None, the value of the environment variable
`MONAI_DATA_DIRECTORY` is used instead, if this is not present then a random temporary directory is chosen. If
`delete_on_finalise` is True, or a random temp directory was created, the directory and its contents will be deleted
when the process exits. This will not delete the `MONAI_DATA_DIRECTORY` in any situation.

Args:
directory: path to desired temporary directory, or None to use MONAI_DATA_DIRECTORY or choose a random one.
delete_on_finalise: if True, the given or chosen directory and contents will be deleted when the process exits.

Returns:
The path to the existing or new temporary directory, if `directory` is given this will be returned, otherwise it
will be the value of MONAI_DATA_DIRECTORY if present or the chosen random directory. This directory will exist.

"""
if directory is None:
directory = MONAIEnvVars.data_dir()
delete_on_finalise = directory is None # override argument so MONAI data directory isn't deleted by accident

if directory is None: # choose a temporary directory which will be deleted on exit
directory = tempfile.mkdtemp()
else:
directory = str(directory) # convert Path if given

os.makedirs(directory, exist_ok=True)

if delete_on_finalise:
atexit.register(shutil.rmtree, directory, ignore_errors=True)

return directory
86 changes: 86 additions & 0 deletions tests/apps/test_create_temp_dir.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Copyright (c) MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import os
import shutil
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

from parameterized import parameterized

from monai.apps import create_temp_dir
from monai.utils import MONAIEnvVars

MONAI_DATA_DIRECTORY = "MONAI_DATA_DIRECTORY"


class TestCreateTempDir(unittest.TestCase):
def test_basic_use(self):
Comment thread
ericspod marked this conversation as resolved.
Resolved
"""Test basic usage which should create a new random temporary directory."""

data_dir = os.environ.pop(MONAI_DATA_DIRECTORY, None) # don't let environment variable interfere with testing
test_dir = None
try:
with patch("atexit.register") as mock_reg:
test_dir = create_temp_dir()

self.assertTrue(os.path.isdir(test_dir))

mock_reg.assert_called_once_with(shutil.rmtree, test_dir, ignore_errors=True)
finally:
if data_dir is not None:
os.environ[MONAI_DATA_DIRECTORY] = data_dir
if test_dir is not None:
shutil.rmtree(test_dir, ignore_errors=True)

def test_data_dir(self):
"""Test using a mocked MONAIEnvVars.data_dir(), which should be returned by the function."""
with (
patch("atexit.register") as mock_reg,
patch("monai.utils.MONAIEnvVars.data_dir") as data_dir,
tempfile.TemporaryDirectory() as temp_dir,
):
data_dir.return_value = selected_dir = f"{temp_dir}{os.path.sep}test_inner_dir"

self.assertEqual(selected_dir, MONAIEnvVars.data_dir())

test_dir = create_temp_dir()

mock_reg.assert_not_called()
self.assertTrue(os.path.isdir(test_dir))
self.assertEqual(test_dir, selected_dir)

@parameterized.expand([(False, False), (True, False), (False, True)])
def test_given_dir(self, as_path, delete_on_finalise):
"""
Test giving a directory to the function as string or Path, ensuring it creates the directory. If
`delete_on_finalise` is True, check the call to rmtree was registered, otherwise check atexit was not called.
"""
with patch("atexit.register") as mock_reg, tempfile.TemporaryDirectory() as temp_dir:
selected_dir = f"{temp_dir}{os.path.sep}test_inner_dir"

test_dir = create_temp_dir(Path(selected_dir) if as_path else selected_dir, delete_on_finalise)

self.assertTrue(os.path.isdir(selected_dir))
self.assertEqual(test_dir, selected_dir)

if delete_on_finalise:
mock_reg.assert_called_once_with(shutil.rmtree, selected_dir, ignore_errors=True)
else:
mock_reg.assert_not_called()


if __name__ == "__main__":
unittest.main()
Loading