diff --git a/swh/loader/core/tests/test_utils.py b/swh/loader/core/tests/test_utils.py new file mode 100644 --- /dev/null +++ b/swh/loader/core/tests/test_utils.py @@ -0,0 +1,95 @@ +# Copyright (C) 2019 The Software Heritage developers +# See the AUTHORS file at the top-level directory of this distribution +# License: GNU General Public License version 3, or any later version +# See top-level LICENSE file for more information + +import os + +from unittest.mock import patch + +from swh.loader.core.utils import clean_dangling_folders + + +def test_clean_dangling_folders_0(tmpdir): + """Folder does not exist, do nothing""" + r = clean_dangling_folders('/path/does/not/exist', 'unused-pattern') + assert r is None + + +@patch('swh.loader.core.utils.psutil.pid_exists') +def test_clean_dangling_folders_1(mock_pid_exists, tmpdir): + """Folder which matches pattern with pid dead are cleaned up + + """ + # pid is dead + mock_pid_exists.return_value = False + + dangling = [ + tmpdir / 'something', + tmpdir / 'swh.loader.svn-4321.noisynoise', + ] + for d in dangling: + os.mkdir(d) + + clean_dangling_folders(tmpdir, 'swh.loader.svn') + + expected_dir = os.listdir(tmpdir) + + mock_pid_exists.assert_called_once_with(4321) + + assert expected_dir == ['something'] + + +@patch('swh.loader.core.utils.psutil.pid_exists') +def test_clean_dangling_folders_2(mock_pid_exists, tmpdir): + """Folder which matches pattern with pid alive are skipped + + """ + # pid is live + mock_pid_exists.return_value = True + + dangling = [ + tmpdir / 'something', + tmpdir / 'swh.loader.svn-1234.noisynoise', + ] + for d in dangling: + os.mkdir(d) + + clean_dangling_folders(tmpdir, 'swh.loader.svn') + + expected_dirs = os.listdir(tmpdir) + sorted(expected_dirs) + + mock_pid_exists.assert_called_once_with(1234) + + assert expected_dirs == [ + 'swh.loader.svn-1234.noisynoise', 'something', + ] + + +@patch('swh.loader.core.utils.psutil.pid_exists') +@patch('swh.loader.core.utils.shutil.rmtree') +def test_clean_dangling_folders_3(mock_rmtree, mock_pid_exists, tmpdir): + """Error in trying to clean dangling folders are skipped + + """ + # pid is dead, we can clean up + mock_pid_exists.return_value = False + # for some reason, this fails to remove the dangling folder + mock_rmtree.side_effect = ValueError('Could not remove for reasons') + + path2 = tmpdir / 'swh.loader.git-1468.noisy' + dangling_folders = list(map(str, [tmpdir / 'thingy', path2])) + sorted(dangling_folders) + for d in dangling_folders: + os.makedirs(d) + + clean_dangling_folders(tmpdir, 'swh.loader.git') + + expected_dirs = os.listdir(tmpdir) + sorted(expected_dirs) + + mock_pid_exists.assert_called_once_with(1468) + mock_rmtree.assert_called_once_with(str(path2)) + + assert expected_dirs == ['swh.loader.git-1468.noisy', 'thingy']