diff --git a/src/ert/resources/shell_scripts/careful_copy_file.py b/src/ert/resources/shell_scripts/careful_copy_file.py index 7e15430ba95..3a36c60f654 100755 --- a/src/ert/resources/shell_scripts/careful_copy_file.py +++ b/src/ert/resources/shell_scripts/careful_copy_file.py @@ -5,13 +5,12 @@ def careful_copy_file(src, target=None): + if target is None: + target = os.path.basename(src) if os.path.exists(target): print(f"File: {target} already present - not updated") return if os.path.isfile(src): - if target is None: - target = os.path.basename(src) - if os.path.isdir(target): target_file = os.path.join(target, os.path.basename(src)) shutil.copyfile(src, target_file) diff --git a/tests/ert/unit_tests/resources/test_shell.py b/tests/ert/unit_tests/resources/test_shell.py index 51dad3771f2..74a9cb7989e 100644 --- a/tests/ert/unit_tests/resources/test_shell.py +++ b/tests/ert/unit_tests/resources/test_shell.py @@ -1,6 +1,7 @@ import contextlib import os import os.path +import shutil import sys from contextlib import suppress from pathlib import Path @@ -471,6 +472,22 @@ def test_copy_file3(): assert os.path.isfile("rms/output/file.txt") +@pytest.mark.usefixtures("use_tmpdir") +def test_copy_when_target_is_none(): + Path("somedir").mkdir() + Path("somedir/file.txt").write_text("Hei", encoding="utf-8") + + copy_file("somedir/file.txt", None) + assert Path("file.txt").read_text(encoding="utf-8") == "Hei" + + +@pytest.mark.usefixtures("use_tmpdir") +def test_copy_when_target_is_none_in_same_directory(): + Path("file.txt").write_text("Hei", encoding="utf-8") + with pytest.raises(shutil.SameFileError): + copy_file("file.txt", None) + + @pytest.mark.usefixtures("use_tmpdir") def test_careful_copy_file(): with open("file1", "w", encoding="utf-8") as f: @@ -486,6 +503,31 @@ def test_careful_copy_file(): assert os.path.isfile("file3") +@pytest.mark.usefixtures("use_tmpdir") +def test_careful_copy_file_when_target_is_none(): + Path("somedir").mkdir() + Path("somedir/file.txt").write_text("Hei", encoding="utf-8") + + careful_copy_file("somedir/file.txt", None) + assert Path("file.txt").read_text(encoding="utf-8") == "Hei" + + +@pytest.mark.usefixtures("use_tmpdir") +def test_careful_copy_when_target_is_none_in_same_directory_is_noop(): + Path("file.txt").write_text("Hei", encoding="utf-8") + careful_copy_file("file.txt", None) # File will not be touched + assert Path("file.txt").read_text(encoding="utf-8") == "Hei" + + +@pytest.mark.usefixtures("use_tmpdir") +def test_careful_copy_when_target_is_none_does_not_touch_existing(): + Path("somedir").mkdir() + Path("somedir/file.txt").write_text("Hei", encoding="utf-8") + Path("file.txt").write_text("I will survive", encoding="utf-8") + careful_copy_file("somedir/file.txt", None) + assert Path("file.txt").read_text(encoding="utf-8") == "I will survive" + + @pytest.fixture def minimal_case(tmpdir): with tmpdir.as_cwd():