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:
0
tests/__init__.py
Normal file
0
tests/__init__.py
Normal file
0
tests/integration/__init__.py
Normal file
0
tests/integration/__init__.py
Normal file
139
tests/integration/test_cli.py
Normal file
139
tests/integration/test_cli.py
Normal file
@@ -0,0 +1,139 @@
|
||||
"""
|
||||
End-to-end tests that invoke main.py as a real subprocess.
|
||||
|
||||
These cover what unit tests cannot: argument handling, exit status,
|
||||
stderr messages, and the final sort order as actually printed.
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
MAIN = PROJECT_ROOT / "main.py"
|
||||
|
||||
|
||||
def run_cli(*args: str) -> subprocess.CompletedProcess:
|
||||
"""Invoke main.py with the given arguments."""
|
||||
return subprocess.run(
|
||||
[sys.executable, str(MAIN), *args],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=PROJECT_ROOT,
|
||||
)
|
||||
|
||||
|
||||
def assert_clean_error(result: subprocess.CompletedProcess) -> None:
|
||||
"""A failure must be a user-facing message, never a stack trace.
|
||||
|
||||
Asserted explicitly because an escaping exception also exits with
|
||||
status 1 and prints the same text as part of its traceback, which
|
||||
would otherwise satisfy the message assertions on its own.
|
||||
"""
|
||||
assert result.returncode == 1
|
||||
assert result.stdout == ""
|
||||
assert "Traceback" not in result.stderr
|
||||
assert result.stderr.strip().startswith("error:")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample(tmp_path):
|
||||
"""The configuration and text files from the assignment."""
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z\nbb=y\nc=x\n", encoding="utf-8")
|
||||
|
||||
text_file = tmp_path / "input.txt"
|
||||
text_file.write_text(
|
||||
"jgrebbk6hnae\n"
|
||||
"cnhjrfyjvth3nxr\n"
|
||||
"b#sjcf_ansbbbbbvo!\n"
|
||||
"dajf#aemfaocfna%\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return config_file, text_file
|
||||
|
||||
|
||||
def test_assignment_example_end_to_end(sample):
|
||||
"""The full worked example, sorted most-changed first."""
|
||||
config_file, text_file = sample
|
||||
|
||||
result = run_cli(str(config_file), str(text_file))
|
||||
|
||||
assert result.returncode == 0
|
||||
assert result.stderr == ""
|
||||
assert result.stdout.splitlines() == [
|
||||
"b#sjxf_znsyybvo!", # 6 symbols replaced
|
||||
"dzjf#zemfzoxfnz%", # 5
|
||||
"jgreyk6hnze", # 3
|
||||
"xnhjrfyjvth3nxr", # 1
|
||||
]
|
||||
|
||||
|
||||
def test_equal_counts_keep_original_file_order(tmp_path):
|
||||
"""The sort is stable and keys only on the count, so lines with the
|
||||
same number of replacements must stay in their original order."""
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z\n", encoding="utf-8")
|
||||
|
||||
text_file = tmp_path / "input.txt"
|
||||
text_file.write_text("first a\nsecond a\nthird a\n", encoding="utf-8")
|
||||
|
||||
result = run_cli(str(config_file), str(text_file))
|
||||
|
||||
assert result.returncode == 0
|
||||
assert result.stdout.splitlines() == ["first z", "second z", "third z"]
|
||||
|
||||
|
||||
def test_missing_config_file(tmp_path, sample):
|
||||
_, text_file = sample
|
||||
missing = tmp_path / "does_not_exist.txt"
|
||||
|
||||
result = run_cli(str(missing), str(text_file))
|
||||
|
||||
assert_clean_error(result)
|
||||
assert "No such file or directory" in result.stderr
|
||||
assert str(missing) in result.stderr
|
||||
|
||||
|
||||
def test_missing_text_file(tmp_path, sample):
|
||||
config_file, _ = sample
|
||||
missing = tmp_path / "does_not_exist.txt"
|
||||
|
||||
result = run_cli(str(config_file), str(missing))
|
||||
|
||||
assert_clean_error(result)
|
||||
assert "No such file or directory" in result.stderr
|
||||
|
||||
|
||||
def test_malformed_config_reports_line_number(tmp_path, sample):
|
||||
_, text_file = sample
|
||||
config_file = tmp_path / "bad.txt"
|
||||
config_file.write_text("a=z\nnoequalsign\n", encoding="utf-8")
|
||||
|
||||
result = run_cli(str(config_file), str(text_file))
|
||||
|
||||
assert_clean_error(result)
|
||||
assert "line 2" in result.stderr
|
||||
|
||||
|
||||
def test_non_utf8_text_file(tmp_path, sample):
|
||||
"""A decoding failure must be reported, not raised as a traceback."""
|
||||
config_file, _ = sample
|
||||
text_file = tmp_path / "latin1.txt"
|
||||
text_file.write_bytes(b"caf\xe9 abc\n")
|
||||
|
||||
result = run_cli(str(config_file), str(text_file))
|
||||
|
||||
assert_clean_error(result)
|
||||
assert "codec can't decode" in result.stderr
|
||||
|
||||
|
||||
def test_missing_arguments_is_a_usage_error():
|
||||
"""argparse reserves exit status 2 for command line misuse."""
|
||||
result = run_cli()
|
||||
|
||||
assert result.returncode == 2
|
||||
assert "usage:" in result.stderr
|
||||
0
tests/unit/__init__.py
Normal file
0
tests/unit/__init__.py
Normal file
58
tests/unit/test_config_loader.py
Normal file
58
tests/unit/test_config_loader.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""Unit tests for config_loader.py"""
|
||||
|
||||
import pytest
|
||||
from config_loader import load_config
|
||||
|
||||
|
||||
def test_valid_config(tmp_path):
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z\nbb=y\nc=x\n")
|
||||
pairs = load_config(str(config_file))
|
||||
assert pairs == [("a", "z"), ("bb", "y"), ("c", "x")]
|
||||
|
||||
|
||||
def test_skips_blank_lines(tmp_path):
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z\n\nbb=y\n")
|
||||
pairs = load_config(str(config_file))
|
||||
assert pairs == [("a", "z"), ("bb", "y")]
|
||||
|
||||
|
||||
def test_invalid_line_raises_value_error(tmp_path):
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z\nnoequalsign\n")
|
||||
with pytest.raises(ValueError):
|
||||
load_config(str(config_file))
|
||||
|
||||
|
||||
def test_value_can_contain_equals_sign(tmp_path):
|
||||
"""split('=', 1) should only split on the FIRST '=', so value2
|
||||
is allowed to contain additional '=' characters."""
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=x=y\n")
|
||||
pairs = load_config(str(config_file))
|
||||
assert pairs == [("a", "x=y")]
|
||||
|
||||
|
||||
def test_trailing_whitespace_in_value_is_preserved(tmp_path):
|
||||
"""Whitespace inside value2 is significant and deliberately kept.
|
||||
|
||||
The configuration format has no quoting or escaping, so stripping
|
||||
would make a replacement value ending in a space impossible to
|
||||
express. Guarding against accidental trailing spaces is therefore
|
||||
left to the caller.
|
||||
"""
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("a=z \n") # trailing space before newline
|
||||
|
||||
pairs = load_config(str(config_file))
|
||||
|
||||
assert pairs == [("a", "z ")]
|
||||
|
||||
|
||||
def test_empty_config_file(tmp_path):
|
||||
"""An empty configuration is valid and simply replaces nothing."""
|
||||
config_file = tmp_path / "config.txt"
|
||||
config_file.write_text("", encoding="utf-8")
|
||||
|
||||
assert load_config(str(config_file)) == []
|
||||
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
|
||||
29
tests/unit/test_sample_data.py
Normal file
29
tests/unit/test_sample_data.py
Normal file
@@ -0,0 +1,29 @@
|
||||
"""
|
||||
Verifies the worked example from instructions.md line by line.
|
||||
|
||||
The end-to-end behaviour of that same example, including the sort order
|
||||
and the printed output, is covered by tests/integration/test_cli.py.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from replacer import prepare_pairs, replace_line
|
||||
|
||||
SAMPLE_PAIRS = prepare_pairs([("a", "z"), ("bb", "y"), ("c", "x")])
|
||||
|
||||
# Each sample line mapped to its expected result and replacement count.
|
||||
EXPECTED_RESULTS = {
|
||||
"jgrebbk6hnae": ("jgreyk6hnze", 3),
|
||||
"cnhjrfyjvth3nxr": ("xnhjrfyjvth3nxr", 1),
|
||||
"b#sjcf_ansbbbbbvo!": ("b#sjxf_znsyybvo!", 6),
|
||||
"dajf#aemfaocfna%": ("dzjf#zemfzoxfnz%", 5),
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line", list(EXPECTED_RESULTS))
|
||||
def test_each_sample_line(line):
|
||||
expected_result, expected_replaced = EXPECTED_RESULTS[line]
|
||||
|
||||
result, replaced = replace_line(line, SAMPLE_PAIRS)
|
||||
|
||||
assert result == expected_result
|
||||
assert replaced == expected_replaced
|
||||
Reference in New Issue
Block a user