Enhance entry addition process: implement immediate file save after adding an entry and handle save failure by removing the entry for improved reliability.

This commit is contained in:
Philip Henning 2025-08-17 19:26:30 +02:00
parent 6171e0ca0b
commit 77d4a2e955
3 changed files with 84 additions and 9 deletions

View file

@ -634,3 +634,58 @@ class TestHostsManager:
finally:
# Clean up
Path(temp_path).unlink()
def test_add_entry_success(self):
"""Test successfully adding an entry with immediate save."""
manager = HostsManager()
manager.edit_mode = True
# Mock the save operation to succeed
with patch.object(manager, "save_hosts_file") as mock_save:
mock_save.return_value = (True, "File saved successfully")
hosts_file = HostsFile()
test_entry = HostEntry(ip_address="192.168.1.100", hostnames=["testhost"])
success, message = manager.add_entry(hosts_file, test_entry)
assert success
assert "Entry added: testhost" in message
assert len(hosts_file.entries) == 1
assert hosts_file.entries[0] == test_entry
mock_save.assert_called_once_with(hosts_file)
def test_add_entry_save_failure(self):
"""Test adding an entry when save fails."""
manager = HostsManager()
manager.edit_mode = True
# Mock the save operation to fail
with patch.object(manager, "save_hosts_file") as mock_save:
mock_save.return_value = (False, "Permission denied")
hosts_file = HostsFile()
test_entry = HostEntry(ip_address="192.168.1.100", hostnames=["testhost"])
success, message = manager.add_entry(hosts_file, test_entry)
assert not success
assert "Failed to save after adding entry" in message
assert (
len(hosts_file.entries) == 0
) # Entry should be removed on save failure
mock_save.assert_called_once_with(hosts_file)
def test_add_entry_not_in_edit_mode(self):
"""Test adding an entry when not in edit mode."""
manager = HostsManager()
# edit_mode defaults to False
hosts_file = HostsFile()
test_entry = HostEntry(ip_address="192.168.1.100", hostnames=["testhost"])
success, message = manager.add_entry(hosts_file, test_entry)
assert not success
assert "Not in edit mode" in message
assert len(hosts_file.entries) == 0