313 lines
14 KiB
Python
313 lines
14 KiB
Python
"""计算内核单元测试。
|
||
|
||
用例编号直接引用《系统重构-计算逻辑详细设计》里的规则号,业务确认口径时可以逐条对。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from decimal import Decimal
|
||
|
||
import pytest
|
||
|
||
from app.service.calc import fund_plan, profit, rules, tax, validate
|
||
from app.service.calc.money import money_str, ratio, round_money, to_dec
|
||
|
||
D = Decimal
|
||
|
||
|
||
class TestMoney:
|
||
@pytest.mark.parametrize("value,expected", [
|
||
("0.005", "0.01"), ("0.004", "0.00"), ("113", "113.00"), ("-0.005", "-0.01"),
|
||
])
|
||
def test_round_half_up(self, value, expected):
|
||
assert str(round_money(value)) == expected
|
||
|
||
def test_money_is_string_in_json(self):
|
||
assert money_str(D("1234.5")) == "1234.50"
|
||
|
||
def test_none_is_zero(self):
|
||
assert to_dec(None) == 0 and to_dec("abc") == 0
|
||
|
||
|
||
class TestTax:
|
||
"""TAX-001 / TAX-002。"""
|
||
|
||
@pytest.mark.parametrize("include,rate,exclude,tax_amount", [
|
||
("113", "13", "100", "13"), # TAX-01
|
||
("106", "6", "100", "6"), # TAX-02
|
||
("100", "0", "100", "0"), # TAX-03
|
||
])
|
||
def test_split(self, include, rate, exclude, tax_amount):
|
||
result = tax.split(D(include), D(rate))
|
||
assert result.exclude == D(exclude)
|
||
assert result.tax == D(tax_amount)
|
||
|
||
def test_rate_null_means_no_tax(self):
|
||
"""TAX-04"""
|
||
result = tax.split(D("100"), None)
|
||
assert (result.exclude, result.tax) == (D("100"), D("0"))
|
||
|
||
def test_manual_total_wins_over_product(self):
|
||
"""TAX-05:人工含税总额优先于 数量×单价。"""
|
||
result = tax.line(D("999"), D("2"), D("500"), D("13"))
|
||
assert result.include == D("999") and result.source == "manual"
|
||
|
||
def test_missing_quantity_does_not_crash(self):
|
||
"""TAX-06:老代码这里会 NPE,现在按 0 处理并交给校验器。"""
|
||
result = tax.line(None, None, D("500"), D("13"))
|
||
assert result.include == D("0")
|
||
|
||
@pytest.mark.parametrize("stored_include", [None, "", "0", "0.00", D("0.00")])
|
||
def test_blank_amount_falls_back_to_qty_times_price(self, stored_include):
|
||
"""明细表 NOT NULL 列把"没填"存成 0.00,不能当成人工 0。
|
||
|
||
之前这里会把整行抹成 0,概算合计直接少掉一条明细。
|
||
"""
|
||
result = tax.line(stored_include, D("2"), D("1090000"), D("9"))
|
||
assert result.include == D("2180000.00") and result.source == "product"
|
||
assert result.exclude == D("2000000.00")
|
||
|
||
def test_explicit_zero_without_price_stays_zero(self):
|
||
"""既没金额也没单价时才是真 0,来源记 manual,校验器据此报必填。"""
|
||
result = tax.line("0.00", D("2"), None, D("9"))
|
||
assert result.include == D("0.00") and result.source == "manual"
|
||
|
||
def test_include_equals_exclude_plus_tax(self):
|
||
"""价内税必须可加:含税 = 不含税 + 税额,一分不差。"""
|
||
for include, rate in [("113", "13"), ("1130", "13"), ("9999.99", "9"), ("1", "13")]:
|
||
result = tax.split(D(include), D(rate))
|
||
assert result.include == result.exclude + result.tax
|
||
|
||
def test_browser_bug_is_gone(self):
|
||
"""RISK-TAX-002:老前端对 113/13% 会算出 14.69。"""
|
||
assert tax.split(D("113"), D("13")).tax != D("14.69")
|
||
|
||
|
||
class TestProfit:
|
||
def test_ladder(self):
|
||
result = profit.calculate(profit.ProfitInput(
|
||
income_device=D("1000"), income_engineering=D("130"),
|
||
purchase_device=D("600"), purchase_construction=D("100"),
|
||
purchase_service=D("50"), purchase_other=D("10"),
|
||
project_manage=D("30"), other_cost=D("5"), finance_cost=D("2"),
|
||
))
|
||
assert result.income_total == D("1130")
|
||
assert result.purchase_total == D("760")
|
||
assert result.gross_a == D("370")
|
||
# 推荐口径:项目毛利 = 采购毛利 - 项目管理 - 其他成本 - 财务费用
|
||
assert result.gross_b == D("333")
|
||
# 公司管理费用按 2.8% 派生
|
||
assert result.company_manage_source == "derived"
|
||
assert result.contribution == result.gross_b - result.company_manage
|
||
|
||
def test_manual_company_manage_beats_rate(self):
|
||
"""RISK-BUD-CM-001:人工填的值必须生效。"""
|
||
result = profit.calculate(profit.ProfitInput(
|
||
income_device=D("1000"), company_manage=D("1"),
|
||
))
|
||
assert result.company_manage == D("1") and result.company_manage_source == "manual"
|
||
|
||
def test_zero_income_rate_is_undefined(self):
|
||
"""PROFIT-02/03:零收入时利润率"未定义",不是 0。"""
|
||
result = profit.calculate(profit.ProfitInput(purchase_device=D("100")))
|
||
assert not result.gross_a_rate.defined
|
||
assert result.gross_a_rate.reason == "zero_denominator"
|
||
assert result.gross_a_rate.to_dict()["value"] is None
|
||
|
||
def test_other_cost_can_be_excluded_for_reconciliation(self):
|
||
"""关掉开关就能复现老后端口径(没扣其他成本)。"""
|
||
args = dict(income_device=D("1000"), other_cost=D("50"))
|
||
strict = profit.calculate(profit.ProfitInput(**args)).gross_b
|
||
with rules.override(profit_other_cost_in_gross=False):
|
||
legacy = profit.calculate(profit.ProfitInput(**args)).gross_b
|
||
assert legacy == strict + D("50")
|
||
|
||
|
||
class TestRatio:
|
||
def test_zero_denominator_undefined(self):
|
||
assert not ratio(D("1"), D("0")).defined
|
||
|
||
def test_zero_denominator_zero_mode(self):
|
||
with rules.override(zero_denominator="zero"):
|
||
assert ratio(D("1"), D("0")).value == 0
|
||
|
||
def test_zero_denominator_mode_is_a_front_end_switch(self):
|
||
"""零分母行为改完立刻生效,不用重启:口径存在库里,不在配置文件里。"""
|
||
rules.apply({"calc.zero_denominator": "zero"})
|
||
try:
|
||
assert ratio(D("1"), D("0")).value == 0
|
||
finally:
|
||
rules.reset_to_defaults()
|
||
assert not ratio(D("1"), D("0")).defined
|
||
|
||
|
||
class TestFundPlan:
|
||
def test_plan_001_balance_chain(self):
|
||
"""PLAN-001:余额 = 收入 - 支出 + 上月余额;垫资还款不重复计入余额。"""
|
||
result = fund_plan.calculate([
|
||
fund_plan.FundMonthInput("2026-01", device_cost=D("100"), interest_rate=D("6")),
|
||
fund_plan.FundMonthInput("2026-02", sale_income=D("80"), interest_rate=D("6")),
|
||
fund_plan.FundMonthInput("2026-03", sale_income=D("200"), interest_rate=D("6")),
|
||
])
|
||
assert [m.balance for m in result.months] == [D("-100.00"), D("-20.00"), D("180.00")]
|
||
assert result.months[0].underwritten_plan == D("100.00")
|
||
assert [m.repayment_plan for m in result.months[1:]] == [D("80.00"), D("20.00")]
|
||
|
||
def test_plan_int_001_interest(self):
|
||
"""PLAN-INT-001:月息 = max(0, -余额 × 年利率/100/12)。"""
|
||
assert fund_plan.capital_interest(D("-100"), D("6")) == D("0.50")
|
||
assert fund_plan.capital_interest(D("500"), D("6")) == D("0")
|
||
assert fund_plan.capital_interest(D("-100"), D("0")) == D("0")
|
||
|
||
def test_repayment_never_overpays(self):
|
||
"""PLAN-REPAY-001:还款最多把历史负余额补到 0。"""
|
||
assert fund_plan.repayment_plan(D("1000"), D("0"), D("-50")) == D("50")
|
||
assert fund_plan.repayment_plan(D("1000"), D("0"), D("50")) == D("0")
|
||
|
||
def test_peak_is_real_peak(self):
|
||
"""RISK-PLAN-STAT-001:峰值是单月最大值,不是各月之和。"""
|
||
result = fund_plan.calculate([
|
||
fund_plan.FundMonthInput("2026-01", device_cost=D("100")),
|
||
fund_plan.FundMonthInput("2026-02", device_cost=D("300")),
|
||
fund_plan.FundMonthInput("2026-03", device_cost=D("50")),
|
||
])
|
||
assert result.peak_month == "2026-02"
|
||
assert result.peak_value == D("300.00")
|
||
assert result.underwritten_total == D("450.00")
|
||
|
||
|
||
class TestValidate:
|
||
def test_bud_val_001_travel_limit(self):
|
||
report = validate.ValidationReport()
|
||
validate.check_travel_limit(report, D("370"), D("30"), D("100"))
|
||
assert not report.passed
|
||
assert report.errors[0].rule_id == "BUD-VAL-001"
|
||
|
||
def test_bud_val_001_within_limit_passes(self):
|
||
report = validate.ValidationReport()
|
||
validate.check_travel_limit(report, D("370"), D("30"), D("10"))
|
||
assert report.passed
|
||
|
||
def test_plan_val_001_pay_plan_reconciles(self):
|
||
report = validate.ValidationReport()
|
||
validate.check_pay_plan_reconciles(report, {1: D("100")}, {1: D("120")})
|
||
assert report.errors[0].rule_id == "PLAN-VAL-001"
|
||
|
||
def test_plan_val_003_missing_boundary_month(self):
|
||
report = validate.ValidationReport()
|
||
validate.check_fund_months(report, ["2026-01", "2026-01"], "2026-01", "2026-06")
|
||
rules = {issue.rule_id for issue in report.errors}
|
||
assert rules == {"PLAN-VAL-003"}
|
||
|
||
def test_tax_range_error(self):
|
||
report = validate.ValidationReport()
|
||
validate.check_tax_inputs(report, [{"tax_rate": "130"}], label="收入")
|
||
assert report.errors[0].rule_id == "INPUT-TAX-RANGE"
|
||
|
||
|
||
class TestCalcRules:
|
||
"""口径参数搬进系统参数表之后的读取口(app/service/calc/rules.py)。"""
|
||
|
||
def test_config_file_no_longer_carries_calc_rules(self):
|
||
"""配置文件里不该再有任何计算规则:口径改了要重启,等于没人敢改。"""
|
||
import tomllib
|
||
from pathlib import Path
|
||
|
||
from app.config import BASE_DIR
|
||
|
||
for name in ("config.toml", "config.dev.toml", "config.prod.toml"):
|
||
path = Path(BASE_DIR) / name
|
||
if not path.is_file():
|
||
continue
|
||
with path.open("rb") as handle:
|
||
data = tomllib.load(handle)
|
||
assert "calc" not in data, f"{name} 里还留着 [calc] 段"
|
||
|
||
def test_every_rule_is_seeded_under_the_calc_group(self):
|
||
"""种进 system_config 的行与内核读的字段一一对应,编码不多也不少。"""
|
||
rows = rules.seed_rows()
|
||
assert [row[0] for row in rows] == list(rules.RULE_CODES)
|
||
assert all(row[4] == "calc" for row in rows)
|
||
# 每行都能被自己校验通过,且折出来就是默认值——否则页面一打开就是"已改"
|
||
for code, _name, value, _type, _group, _remark in rows:
|
||
spec = rules.spec_for(code)
|
||
assert rules.normalize(spec, value) == spec.default_text
|
||
assert rules.parse(spec, rules.normalize(spec, value)) == spec.default
|
||
|
||
def test_apply_reads_the_stored_strings(self):
|
||
rules.apply({"calc.money_scale": "3", "calc.rounding": "half_even",
|
||
"calc.tax_rate_pre_round": "true", "calc.company_manage_fee_rate": "3.5"})
|
||
try:
|
||
# 位数与进位方式都换了:1.0005 在 3 位 + HALF_EVEN 下落到偶数 1.000
|
||
assert round_money("1.0005") == D("1.000")
|
||
assert rules.RULES.rounding == "HALF_EVEN"
|
||
assert rules.RULES.tax_rate_pre_round is True
|
||
assert rules.RULES.company_manage_fee_rate == 3.5
|
||
finally:
|
||
rules.reset_to_defaults()
|
||
|
||
def test_garbage_value_falls_back_instead_of_breaking_the_calc(self):
|
||
"""库里被手写坏了一条:退回默认,别的条照常生效,试算不能停。"""
|
||
rules.apply({"calc.money_scale": "两", "calc.rate_scale": "6"})
|
||
try:
|
||
assert rules.RULES.money_scale == 2
|
||
assert rules.RULES.rate_scale == 6
|
||
finally:
|
||
rules.reset_to_defaults()
|
||
|
||
@pytest.mark.parametrize("key,value,message", [
|
||
("rounding", "HALF_CENTIMETER", "只能是"),
|
||
("zero_denominator", "nan", "只能是"),
|
||
("contribution_rate_action", "block-it", "只能是"),
|
||
("money_scale", "2.5", "必须是整数"),
|
||
("money_scale", "99", "不能大于"),
|
||
("company_manage_fee_rate", "-1", "不能小于"),
|
||
("travel_business_limit_rate", "abc", "必须是数字"),
|
||
("tax_from_complement", "maybe", "是"),
|
||
("version", " ", "不能为空"),
|
||
])
|
||
def test_bad_values_are_rejected_with_a_readable_reason(self, key, value, message):
|
||
spec = rules.SPECS_BY_ATTR[key]
|
||
with pytest.raises(ValueError) as excinfo:
|
||
rules.normalize(spec, value)
|
||
assert message in str(excinfo.value)
|
||
|
||
def test_override_restores_everything_it_touched(self):
|
||
before = rules.as_dict()
|
||
with rules.override(money_scale=4, version="2027.01"):
|
||
assert rules.RULES.money_scale == 4
|
||
assert money_str(D("1.005")) == "1.0050"
|
||
assert rules.as_dict() == before
|
||
|
||
def test_unknown_override_key_is_a_programming_error(self):
|
||
with pytest.raises(KeyError):
|
||
with rules.override(money_scales=3):
|
||
pass
|
||
|
||
def test_view_shape_matches_the_front_end_contract(self):
|
||
"""页面靠这份渲染控件:段落、控件类型、取值范围、默认值,一样都不能少。"""
|
||
class FakeSession:
|
||
def execute(self, _statement):
|
||
return self
|
||
|
||
def scalars(self):
|
||
return self
|
||
|
||
def all(self):
|
||
return []
|
||
|
||
view = rules.view(FakeSession())
|
||
assert view["changed"] == 0
|
||
assert [section["key"] for section in view["sections"]] == [
|
||
key for key, _title, _hint in rules.RULE_SECTIONS if any(
|
||
spec.section == key and spec.attr != "version" for spec in rules.RULE_SPECS
|
||
)
|
||
]
|
||
for section in view["sections"]:
|
||
for item in section["rules"]:
|
||
assert item["code"].startswith("calc.")
|
||
assert item["kind"] in ("int", "decimal", "bool", "enum", "string")
|
||
assert item["configured"] is False
|
||
if item["kind"] == "enum":
|
||
assert item["choices"], f"{item['code']} 是枚举但没有候选值"
|