test_numbers.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """精确数值与权重规则的单元测试。"""
  2. from __future__ import annotations
  3. from decimal import Decimal
  4. import pytest
  5. from toolsvc.customs.engine.numbers import D, StrictSum, growth, index_of, number, ratio, to_text, weights
  6. def test_number_parsing_accepts_common_formats():
  7. assert number("1234.50") == D("1234.50")
  8. assert number("1,234.50") == D("1234.50")
  9. assert number(" 42 ") == D(42)
  10. assert number(3.5) == D("3.5")
  11. assert number(Decimal("1E+3")) == D(1000)
  12. def test_number_parsing_rejects_blank_and_garbage():
  13. for raw in [None, "", " ", "-", "--", "/", "NULL", "abc", float("nan")]:
  14. assert number(raw) is None
  15. def test_ratio_and_growth_never_substitute_zero():
  16. assert ratio(D(10), D(4)) == D("2.5")
  17. assert ratio(D(10), D(0)) is None
  18. assert ratio(D(10), None) is None
  19. assert growth(D(120), D(100)) == D("0.2")
  20. assert growth(D(120), D(0)) is None
  21. def test_index_uses_1000_base():
  22. assert index_of(D(150), D(100)) == D(1500)
  23. assert index_of(D(100), D(100)) == D(1000)
  24. assert index_of(D(1), D(0)) is None
  25. def test_strict_sum_propagates_unknown():
  26. aggregate = StrictSum()
  27. for value in ["1.5", "2.5"]:
  28. aggregate.step(value)
  29. assert aggregate.finalize() == "4.0"
  30. broken = StrictSum()
  31. broken.step("1.5")
  32. broken.step("oops")
  33. assert broken.finalize() is None
  34. def test_weights_cap_at_ten_percent_with_reallocation():
  35. # 一个样本占绝对多数,其余 11 个样本很小:最大值应被封到 10%,剩下的重新分配
  36. amounts = [D(1000)] + [D(10)] * 11
  37. result = weights(amounts)
  38. assert len(result) == 12
  39. assert result[0] == pytest.approx(D("0.1"), abs=D("1e-20"))
  40. assert sum(result) == pytest.approx(D(1), abs=D("1e-20"))
  41. assert max(result) <= D("0.1")
  42. def test_weights_with_less_than_ten_samples_skip_cap():
  43. amounts = [D(90), D(5), D(5)]
  44. result = weights(amounts)
  45. assert result[0] == D("0.9")
  46. assert sum(result) == D(1)
  47. def test_weights_reject_invalid_amounts():
  48. assert weights([]) == []
  49. assert weights([D(0), D(1)]) == []
  50. assert weights([None, D(1)]) == []
  51. def test_to_text_keeps_precision_without_scientific_notation():
  52. assert to_text(D("1E+3")) == "1000"
  53. assert to_text(D("0.100000")) == "0.1"
  54. assert to_text(None) == ""