| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- """精确数值与权重规则的单元测试。"""
- from __future__ import annotations
- from decimal import Decimal
- import pytest
- from toolsvc.customs.engine.numbers import D, StrictSum, growth, index_of, number, ratio, to_text, weights
- def test_number_parsing_accepts_common_formats():
- assert number("1234.50") == D("1234.50")
- assert number("1,234.50") == D("1234.50")
- assert number(" 42 ") == D(42)
- assert number(3.5) == D("3.5")
- assert number(Decimal("1E+3")) == D(1000)
- def test_number_parsing_rejects_blank_and_garbage():
- for raw in [None, "", " ", "-", "--", "/", "NULL", "abc", float("nan")]:
- assert number(raw) is None
- def test_ratio_and_growth_never_substitute_zero():
- assert ratio(D(10), D(4)) == D("2.5")
- assert ratio(D(10), D(0)) is None
- assert ratio(D(10), None) is None
- assert growth(D(120), D(100)) == D("0.2")
- assert growth(D(120), D(0)) is None
- def test_index_uses_1000_base():
- assert index_of(D(150), D(100)) == D(1500)
- assert index_of(D(100), D(100)) == D(1000)
- assert index_of(D(1), D(0)) is None
- def test_strict_sum_propagates_unknown():
- aggregate = StrictSum()
- for value in ["1.5", "2.5"]:
- aggregate.step(value)
- assert aggregate.finalize() == "4.0"
- broken = StrictSum()
- broken.step("1.5")
- broken.step("oops")
- assert broken.finalize() is None
- def test_weights_cap_at_ten_percent_with_reallocation():
- # 一个样本占绝对多数,其余 11 个样本很小:最大值应被封到 10%,剩下的重新分配
- amounts = [D(1000)] + [D(10)] * 11
- result = weights(amounts)
- assert len(result) == 12
- assert result[0] == pytest.approx(D("0.1"), abs=D("1e-20"))
- assert sum(result) == pytest.approx(D(1), abs=D("1e-20"))
- assert max(result) <= D("0.1")
- def test_weights_with_less_than_ten_samples_skip_cap():
- amounts = [D(90), D(5), D(5)]
- result = weights(amounts)
- assert result[0] == D("0.9")
- assert sum(result) == D(1)
- def test_weights_reject_invalid_amounts():
- assert weights([]) == []
- assert weights([D(0), D(1)]) == []
- assert weights([None, D(1)]) == []
- def test_to_text_keeps_precision_without_scientific_notation():
- assert to_text(D("1E+3")) == "1000"
- assert to_text(D("0.100000")) == "0.1"
- assert to_text(None) == ""
|