Please write a function, with tests, inside a single python file.
The objective of the function is to take a list of lines that represents a file, and replace lines in that file with another list of lines.
Assistant
To achieve the objective, we'll create a function that takes three arguments: the original list of lines, the list of lines to replace with, and the starting index from where the replacement should begin. We'll also include some basic tests to ensure the function works as expected.
python
def replace_lines_in_file(original_lines, replacement_lines, start_index):
"""
Replace lines in a list (simulating a file) with another list of lines.
Parameters:
- original_lines: List[str]
The original list of lines.
- replacement_lines: List[str]
The list of lines to replace with.
- start_index: int
The index from where the replacement should start.
Returns:
- List[str]
The modified list of lines.
"""
# Ensure the start_index is valid
if start_index < 0 or start_index + len(replacement_lines) > len(original_lines):
raise ValueError("Invalid start_index or replacement_lines length.")
# Create a new list to avoid modifying the original list
new_lines = original_lines[:]
# Replace the lines
for i, line in enumerate(replacement_lines):
new_lines[start_index + i] = line
return new_lines
# Test cases
def test_replace_lines_in_file():
# Test 1: Simple replacement
original = ["line1", "line2", "line3", "line4"]
replacement = ["new2", "new3"]
start = 1
expected = ["line1", "new2", "new3", "line4"]
assert replace_lines_in_file(original, replacement, start) == expected
# Test 2: Replacing with empty lines
original = ["line1", "line2", "line3", "line4"]
replacement = [""]
start = 2
expected = ["line1", "line2", "", "line4"]
assert replace_lines_in_file(original, replacement, start) == expected
# Test 3: Replacing all lines
original = ["line1", "line2", "line3", "line4"]
replacement = ["new1", "new2", "new3", "new4"]
start = 0
expected = ["new1", "new2", "new3", "new4"]
assert replace_lines_in_file(original, replacement, start) == expected
# Test 4: Invalid start_index
try:
replace_lines_in_file(original, replacement, 10)
assert False # This should not be reached
except ValueError:
pass # Expected exception
if __name__ == "__main__":
test_replace_lines_in_file()
print("All tests passed.")
This script defines the replace_lines_in_file function and includes a test_replace_lines_in_file function that runs several test cases to ensure the function behaves correctly. The tests cover various scenarios including simple replacement, replacing with empty lines, replacing all lines, and attempting to replace with an invalid start index, which should raise a ValueError.
To run the tests, simply execute the Python script. If all tests pass, it will print "All tests passed.". If any test fails, it will raise an AssertionError.