78 lines
2.1 KiB
Python
78 lines
2.1 KiB
Python
"""Tests for core numeric analysis."""
|
|
|
|
from pathlib import Path
|
|
import pytest
|
|
|
|
from numstats.core import analyze_numbers, read_numbers
|
|
|
|
|
|
def test_read_numbers_basic(tmp_path: Path) -> None:
|
|
f = tmp_path / "data.txt"
|
|
f.write_text("1\n2.5\n3\n")
|
|
nums = read_numbers(f)
|
|
assert nums == [1.0, 2.5, 3.0]
|
|
|
|
|
|
def test_read_numbers_skips_non_numeric(tmp_path: Path) -> None:
|
|
f = tmp_path / "bad.txt"
|
|
f.write_text("1\na\n2\n")
|
|
nums = read_numbers(f)
|
|
assert nums == [1.0, 2.0]
|
|
|
|
|
|
def test_read_numbers_min_filter(tmp_path: Path) -> None:
|
|
f = tmp_path / "filter.txt"
|
|
f.write_text("1\n5\n10\n")
|
|
nums = read_numbers(f, min_value=5)
|
|
assert nums == [5.0, 10.0]
|
|
|
|
|
|
def test_read_numbers_file_not_found() -> None:
|
|
with pytest.raises(FileNotFoundError):
|
|
read_numbers(Path("nonexistent.txt"))
|
|
|
|
|
|
def test_analyze_numbers_empty(tmp_path: Path) -> None:
|
|
f = tmp_path / "empty.txt"
|
|
f.write_text("")
|
|
res = analyze_numbers(f)
|
|
assert res["count"] == 0
|
|
assert res["mean"] == 0.0
|
|
assert res["min"] is None
|
|
assert res["max"] is None
|
|
assert res["top"] == []
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"content, top_n, min_len, expected_count, expected_sum, expected_mean, expected_top",
|
|
[
|
|
("1\n2\n3\n", 2, 0, 3, 6.0, 2.0, [3.0, 2.0]),
|
|
("-5\n0\n10\n", 1, 0, 3, 5.0, 5.0/3, [10.0]),
|
|
("1\n2\n3\n4\n", 3, 2, 3, 9.0, 3.0, [4.0, 3.0, 2.0]),
|
|
("", 5, 0, 0, 0.0, 0.0, []),
|
|
],
|
|
)
|
|
def test_analyze_numbers_parametrized(
|
|
tmp_path: Path,
|
|
content: str,
|
|
top_n: int,
|
|
min_len: int,
|
|
expected_count: int,
|
|
expected_sum: float,
|
|
expected_mean: float,
|
|
expected_top: list,
|
|
) -> None:
|
|
f = tmp_path / "param.txt"
|
|
f.write_text(content)
|
|
res = analyze_numbers(f, top_n=top_n, min_len=min_len)
|
|
assert res["count"] == expected_count
|
|
assert abs(res["sum"] - expected_sum) < 1e-9
|
|
assert abs(res["mean"] - expected_mean) < 1e-9
|
|
assert res["top"] == expected_top
|
|
|
|
|
|
def test_analyze_numbers_encoding(tmp_path: Path) -> None:
|
|
f = tmp_path / "utf16.txt"
|
|
f.write_text("1\n2\n3\n", encoding="utf-16")
|
|
res = analyze_numbers(f, encoding="utf-16")
|
|
assert res["count"] == 3 |