From 0b41d056d3a68bfdf7beb9ae715c2706b57ea903 Mon Sep 17 00:00:00 2001
From: Jan-Philipp Benecke <jan-philipp@bnck.me>
Date: Tue, 11 Mar 2025 20:05:02 +0100
Subject: [PATCH] Only do WebDAV path migration when path differs (#140402)

---
 homeassistant/components/webdav/helpers.py |  3 ++-
 tests/components/webdav/test_init.py       | 24 ++++++++++++++++++----
 2 files changed, 22 insertions(+), 5 deletions(-)

diff --git a/homeassistant/components/webdav/helpers.py b/homeassistant/components/webdav/helpers.py
index 5db15bba0f7..442f69b4d3c 100644
--- a/homeassistant/components/webdav/helpers.py
+++ b/homeassistant/components/webdav/helpers.py
@@ -49,7 +49,8 @@ async def async_ensure_path_exists(client: Client, path: str) -> bool:
 async def async_migrate_wrong_folder_path(client: Client, path: str) -> None:
     """Migrate the wrong encoded folder path to the correct one."""
     wrong_path = path.replace(" ", "%20")
-    if await client.check(wrong_path):
+    # migrate folder when the old folder exists
+    if wrong_path != path and await client.check(wrong_path):
         try:
             await client.move(wrong_path, path)
         except WebDavError as err:
diff --git a/tests/components/webdav/test_init.py b/tests/components/webdav/test_init.py
index c267f7c3251..124a644fa93 100644
--- a/tests/components/webdav/test_init.py
+++ b/tests/components/webdav/test_init.py
@@ -39,14 +39,30 @@ async def test_migrate_wrong_path(
     webdav_client.move.assert_called_once_with("/wrong%20path", "/wrong path")
 
 
+@pytest.mark.parametrize(
+    ("expected_path", "remote_path_check"),
+    [
+        (
+            "/correct path",
+            False,
+        ),  # remote_path_check is False as /correct%20path is not there
+        ("/", True),
+        ("/folder_with_underscores", True),
+    ],
+)
 async def test_migrate_non_wrong_path(
-    hass: HomeAssistant, webdav_client: AsyncMock
+    hass: HomeAssistant,
+    webdav_client: AsyncMock,
+    expected_path: str,
+    remote_path_check: bool,
 ) -> None:
     """Test no migration of correct folder path."""
     webdav_client.list_with_properties.return_value = [
-        {"/correct path": []},
+        {expected_path: []},
     ]
-    webdav_client.check.side_effect = lambda path: path == "/correct path"
+    # first return is used to check the connectivity
+    # second is used in the migration to determine if wrong quoted path is there
+    webdav_client.check.side_effect = [True, remote_path_check]
 
     config_entry = MockConfigEntry(
         title="user@webdav.demo",
@@ -55,7 +71,7 @@ async def test_migrate_non_wrong_path(
             CONF_URL: "https://webdav.demo",
             CONF_USERNAME: "user",
             CONF_PASSWORD: "supersecretpassword",
-            CONF_BACKUP_PATH: "/correct path",
+            CONF_BACKUP_PATH: expected_path,
         },
         entry_id="01JKXV07ASC62D620DGYNG2R8H",
     )
-- 
GitLab