1212from __future__ import annotations
1313
1414import os
15+ import shutil
1516import tempfile
1617import unittest
18+ from pathlib import Path
1719from unittest .mock import patch
1820
1921from monai .apps import create_temp_dir
2527class TestCreateTempDir (unittest .TestCase ):
2628 def test_basic_use (self ):
2729 """Test basic usage which should create a new random temporary directory."""
28- try :
29- data_dir = os .environ .pop (MONAI_DATA_DIRECTORY , None ) # ignore the environment variable if present
3030
31- test_dir = create_temp_dir ()
31+ data_dir = os .environ .pop (MONAI_DATA_DIRECTORY , None ) # ignore the environment variable if present
32+ try :
33+ with patch ("atexit.register" ) as mock_reg :
34+ test_dir = create_temp_dir ()
3235
33- self .assertTrue (os .path .isdir (test_dir ))
36+ self .assertTrue (os .path .isdir (test_dir ))
3437
38+ mock_reg .assert_called_once_with (shutil .rmtree , test_dir , ignore_errors = True )
3539 finally :
3640 if data_dir is not None :
3741 os .environ [MONAI_DATA_DIRECTORY ] = data_dir
@@ -51,21 +55,33 @@ def test_data_dir(self):
5155 def test_given_dir (self ):
5256 """Test giving a directory to the function, ensuring it creates the directory."""
5357 with tempfile .TemporaryDirectory () as temp_dir :
54- selected_dir = f"{ temp_dir } /test_inner_dir"
58+ selected_dir = f"{ temp_dir } { os .path .sep } test_inner_dir"
59+
5560 test_dir = create_temp_dir (selected_dir )
5661
5762 self .assertTrue (os .path .isdir (selected_dir ))
5863 self .assertEqual (test_dir , selected_dir )
64+ self .assertEqual (test_dir , selected_dir )
65+
66+ def test_given_dir_path (self ):
67+ """Test giving a directory as a Path object to the function, ensuring it creates the directory."""
68+ with tempfile .TemporaryDirectory () as temp_dir :
69+ selected_dir = f"{ temp_dir } { os .path .sep } test_inner_dir"
70+
71+ test_dir = create_temp_dir (Path (selected_dir ))
72+
73+ self .assertTrue (os .path .isdir (selected_dir ))
74+ self .assertEqual (test_dir , selected_dir )
5975
6076 def test_finalisation (self ):
61- """Test the temporary directory is deleted by finalisation using a subprocess ."""
77+ """Test the temporary directory is deleted by finalisation."""
6278 self .finaliser = None
6379
6480 def _register (func , / , * args , ** kwargs ):
6581 self .finaliser = (func , args , kwargs )
6682
6783 with patch ("atexit.register" , new = _register ), tempfile .TemporaryDirectory () as temp_dir :
68- selected_dir = f"{ temp_dir } / test_inner_dir"
84+ selected_dir = f"{ temp_dir } { os . path . sep } test_inner_dir"
6985 test_dir = create_temp_dir (selected_dir , True )
7086
7187 self .assertTrue (os .path .isdir (selected_dir ))
0 commit comments