From 2e5d9853b13779d27b01179eed899d29e4bd7784 Mon Sep 17 00:00:00 2001 From: liamhuber Date: Wed, 10 Jan 2024 11:40:21 -0800 Subject: [PATCH] Extend the delete method so it has an option for safety No change to the default behaviour --- pyiron_workflow/files.py | 5 +++-- tests/unit/test_files.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/pyiron_workflow/files.py b/pyiron_workflow/files.py index 11beb5e8..ea980d35 100644 --- a/pyiron_workflow/files.py +++ b/pyiron_workflow/files.py @@ -43,8 +43,9 @@ def __init__(self, directory): def create(self): self.path.mkdir(parents=True, exist_ok=True) - def delete(self): - delete_files_and_directories_recursively(self.path) + def delete(self, only_if_empty: bool = False): + if self.is_empty or not only_if_empty: + delete_files_and_directories_recursively(self.path) def list_content(self): return categorize_folder_items(self.path) diff --git a/tests/unit/test_files.py b/tests/unit/test_files.py index 329b56ba..d4358418 100644 --- a/tests/unit/test_files.py +++ b/tests/unit/test_files.py @@ -50,6 +50,24 @@ def test_is_empty(self): self.directory.write(file_name="test.txt", content="something") self.assertFalse(self.directory.is_empty) + def test_delete(self): + self.assertTrue( + Path("test").exists() and Path("test").is_dir(), + msg="Sanity check on initial state" + ) + self.directory.write(file_name="test.txt", content="something") + self.directory.delete(only_if_empty=True) + self.assertFalse( + self.directory.is_empty, + msg="Flag argument on delete should have prevented removal" + ) + self.directory.delete() + self.assertFalse( + Path("test").exists(), + msg="Delete should remove the entire directory" + ) + self.directory = DirectoryObject("test") # Rebuild it so the tearDown works + if __name__ == '__main__': unittest.main()