Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions cobbler/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2213,12 +2213,11 @@ def remove_lines_in_file(filepath: str, remove_keywords: List[str]) -> None:

raises OSError: In case the file cannot be read or modified.
"""
tmp_filepath = filepath + ".tmp"
with open(filepath, "r", encoding="UTF-8") as fh, open(
tmp_filepath, "w", encoding="UTF-8"
) as tmp_fh:
for line in fh:
new_content_lines = []
with open(filepath, "r", encoding="UTF-8") as fh:
for line in fh.readlines():
if any(keyword in line for keyword in remove_keywords):
continue
tmp_fh.write(line)
os.replace(tmp_filepath, filepath)
new_content_lines.append(line)
with open(filepath, "w", encoding="UTF-8") as fh:
fh.writelines(new_content_lines)
29 changes: 29 additions & 0 deletions tests/utils_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from threading import Thread
from pathlib import Path
from typing import Any, TYPE_CHECKING
from unittest.mock import MagicMock

import pytest
from netaddr.ip import IPAddress
Expand Down Expand Up @@ -1163,3 +1164,31 @@ def test_create_files_if_not_existing(tmp_path: Path):
# Assert
assert os.path.exists(file1)
assert os.path.exists(file2)


def test_remove_lines_in_file(mocker: "MockerFixture"):
# Arrange
file_content = '''
line1
line2
foobar
line4
deadbeaf
line6
'''
expected = '''
line1
line2
line4
line6
'''

mock_open = mocker.patch("builtins.open", mocker.mock_open(read_data=file_content))
mock_os_replace = mocker.patch("os.replace", MagicMock())

# Act
utils.remove_lines_in_file("randomfile", ["foobar", "deadbeaf"])

# Assert
mock_os_replace.assert_not_called()
assert "".join(mock_open.return_value.writelines.call_args[0][0]) == expected