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.
58 lines
1.8 KiB
Python
58 lines
1.8 KiB
Python
"""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)) == [] |