Initial implementation with unit and integration tests
Reads value1=value2 pairs from a configuration file and replaces every non-overlapping occurrence of value1 with value2 in a text file, printing the resulting lines sorted by the number of symbols replaced. Overlapping patterns resolve to the longest match so the result does not depend on configuration file ordering. Ties keep their original file order.
This commit is contained in:
61
tests/unit/test_replacer.py
Normal file
61
tests/unit/test_replacer.py
Normal file
@@ -0,0 +1,61 @@
|
||||
"""Unit tests for replacer.py"""
|
||||
|
||||
from replacer import prepare_pairs, replace_line
|
||||
|
||||
|
||||
def test_sample_line_from_assignment():
|
||||
"""First sample line from the assignment: 'jgrebbk6hnae'."""
|
||||
pairs = prepare_pairs([("a", "z"), ("bb", "y"), ("c", "x")])
|
||||
result, replaced = replace_line("jgrebbk6hnae", pairs)
|
||||
assert result == "jgreyk6hnze"
|
||||
assert replaced == 3 # "bb" (2) + "a" (1)
|
||||
|
||||
|
||||
def test_no_matches():
|
||||
pairs = prepare_pairs([("a", "z"), ("bb", "y")])
|
||||
result, replaced = replace_line("xyz123", pairs)
|
||||
assert result == "xyz123"
|
||||
assert replaced == 0
|
||||
|
||||
|
||||
def test_empty_line():
|
||||
pairs = prepare_pairs([("a", "z")])
|
||||
result, replaced = replace_line("", pairs)
|
||||
assert result == ""
|
||||
assert replaced == 0
|
||||
|
||||
|
||||
def test_overlapping_prefix_patterns_longest_wins():
|
||||
"""
|
||||
Config has both 'b' and 'bb'. Input 'bbbb' should be read as two
|
||||
'bb' matches (longest-match-first), not four 'b' matches.
|
||||
This is the key edge case the greedy algorithm is designed for.
|
||||
"""
|
||||
pairs = prepare_pairs([("b", "1"), ("bb", "2")])
|
||||
result, replaced = replace_line("bbbb", pairs)
|
||||
assert result == "22"
|
||||
assert replaced == 4 # 2 matches of "bb", 2 symbols each
|
||||
|
||||
|
||||
def test_adjacent_matches_non_overlapping():
|
||||
"""Consecutive matches of the same pattern shouldn't overlap."""
|
||||
pairs = prepare_pairs([("bb", "y")])
|
||||
# Five b's -> "bb", "bb", and a leftover "b".
|
||||
result, replaced = replace_line("bbbbb", pairs)
|
||||
assert result == "yyb"
|
||||
assert replaced == 4
|
||||
|
||||
|
||||
def test_full_line_replacement():
|
||||
pairs = prepare_pairs([("abc", "X")])
|
||||
result, replaced = replace_line("abc", pairs)
|
||||
assert result == "X"
|
||||
assert replaced == 3
|
||||
|
||||
|
||||
def test_single_character_values():
|
||||
# Replacement with an empty string is a valid edge case.
|
||||
pairs = prepare_pairs([("a", "")])
|
||||
result, replaced = replace_line("banana", pairs)
|
||||
assert result == "bnn"
|
||||
assert replaced == 3
|
||||
Reference in New Issue
Block a user