"""Bounded tail reads. Both the audit log and an application's captured output are unbounded in M0, and both are read by verbs that must stay cheap. """ from __future__ import annotations from pathlib import Path from hhstreamd.textio import tail_lines def test_the_last_n_lines_are_returned(tmp_path: Path): path = tmp_path / "f.log" path.write_text("".join(f"line {i}\n" for i in range(100))) lines, truncated, size = tail_lines(path, 3) assert lines == ["line 97", "line 98", "line 99"] assert truncated is True # there was more above the window assert size == path.stat().st_size def test_a_short_file_is_returned_whole_and_not_marked_truncated(tmp_path: Path): path = tmp_path / "f.log" path.write_text("a\nb\n") assert tail_lines(path, 10) == (["a", "b"], False, 4) def test_a_large_file_is_never_read_whole(tmp_path: Path): """A gigabyte of Chromium stderr must not become a daemon-sized allocation.""" path = tmp_path / "big.log" path.write_text("".join(f"{i:07d} padding padding padding\n" for i in range(40_000))) assert path.stat().st_size > 1_000_000 lines, truncated, size = tail_lines(path, 5, max_bytes=4096) assert len(lines) == 5 assert lines[-1] == "0039999 padding padding padding" assert truncated is True assert size == path.stat().st_size def test_a_partial_first_line_in_the_window_is_dropped_not_reported_as_whole(tmp_path: Path): path = tmp_path / "f.log" path.write_text("aaaaaaaaaaaaaaaaaaaa\nbbbb\ncccc\n") lines, truncated, _ = tail_lines(path, 10, max_bytes=12) assert "aaaa" not in "".join(lines) assert lines == ["cccc"] or lines == ["bbbb", "cccc"] assert truncated is True def test_a_missing_file_is_empty_rather_than_an_error(tmp_path: Path): assert tail_lines(tmp_path / "absent.log", 10) == ([], False, 0) def test_asking_for_no_lines_still_reports_the_size(tmp_path: Path): path = tmp_path / "f.log" path.write_text("hello\n") assert tail_lines(path, 0) == ([], False, 6) def test_invalid_utf8_is_replaced_not_fatal(tmp_path: Path): path = tmp_path / "f.log" path.write_bytes(b"ok\n\xff\xfe bad\n") lines, _, _ = tail_lines(path, 10) assert lines[0] == "ok" assert "bad" in lines[1]