324 lines
14 KiB
Python
324 lines
14 KiB
Python
"""导数脚本里那几个归一化函数的单元测试。
|
||
|
||
这些函数每一个都是踩过坑才写成现在这样的,改动前请先看注释里的实测数据:
|
||
|
||
* 税率和利润率在老库里是两套口径,混一次就是一次 100 倍误差;
|
||
* ``sys_user.is_deleted`` 是 ``bit(1)``,pymysql 取回来是字节串,
|
||
``bool(b'\\x00')`` 是 True;
|
||
* 采购类别存的是字典 id,不是中文名。
|
||
|
||
都是"跑完不报错、数却悄悄错了"的那类 bug,所以值得钉住。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import importlib.util
|
||
from datetime import date
|
||
from decimal import Decimal
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "migrate_legacy.py"
|
||
|
||
|
||
@pytest.fixture(scope="module")
|
||
def mig():
|
||
spec = importlib.util.spec_from_file_location("migrate_legacy", SCRIPT)
|
||
assert spec and spec.loader
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
return module
|
||
|
||
|
||
@pytest.fixture()
|
||
def report(mig):
|
||
return mig.Report()
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 利润率:老库 *_margin 本来就是百分数
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestMarginRate:
|
||
def test_already_percent_is_left_alone(self, mig, report):
|
||
# 实测 id=7:contract=12990, gross_profit=1578.60, margin=12.15
|
||
assert mig.margin_rate("12.15", report, "gross_profit_margin") == Decimal("12.15")
|
||
assert report.counts == {}
|
||
|
||
def test_small_margin_is_not_multiplied(self, mig, report):
|
||
"""老库真有 0.03 这种利润率,那是 0.03%,不是 3%。
|
||
|
||
旧实现用 -1 < v < 1 一把梭,把 6 条这样的小利润率全放大了 100 倍。
|
||
"""
|
||
for raw, want in [("0.03", "0.03"), ("0.20", "0.20"), ("0.99", "0.99"), ("1", "1")]:
|
||
assert mig.margin_rate(raw, report, "gross_profit_margin") == Decimal(want)
|
||
|
||
def test_negative_and_zero(self, mig, report):
|
||
assert mig.margin_rate("-8.5", report, "m") == Decimal("-8.5")
|
||
assert mig.margin_rate(None, report, "m") == Decimal("0")
|
||
assert mig.margin_rate("", report, "m") == Decimal("0")
|
||
|
||
def test_absurd_rate_is_value_preserved_but_reported(self, mig, report):
|
||
"""P00217 那种脏值照原值导,但要报出来,不能静默。"""
|
||
assert mig.margin_rate("-49504", report, "gross_profit_a_margin") == Decimal("-49504")
|
||
assert any("gross_profit_a_margin" in key for key in report.skips)
|
||
assert report.notes
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 税率:老库 tax_rate 是小数
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestTaxRatePercent:
|
||
def test_fraction_scales_up(self, mig, report):
|
||
assert mig.tax_rate_percent("0.13", report) == Decimal("13")
|
||
assert mig.tax_rate_percent("0", report) == Decimal("0")
|
||
assert mig.tax_rate_percent(None, report) == Decimal("0")
|
||
assert report.counts["换算:税率小数→百分数"] == 1
|
||
|
||
def test_boundary_one_is_full_hundred(self, mig, report):
|
||
assert mig.tax_rate_percent("1", report) == Decimal("100")
|
||
|
||
def test_already_percent_not_double_scaled(self, mig, report):
|
||
"""库里万一有行已经写成 13,落在 (0,1] 之外,不能再乘一次。"""
|
||
assert mig.tax_rate_percent("13", report) == Decimal("13")
|
||
assert mig.tax_rate_percent("6", report) == Decimal("6")
|
||
assert report.counts == {}
|
||
|
||
def test_negative_stays_negative(self, mig, report):
|
||
"""税率不该是负的,但负的也不能被当成小数放大成 -13。"""
|
||
assert mig.tax_rate_percent("-0.13", report) == Decimal("-0.13")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# bit(1):bool(b'\x00') 是 True
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestIsDeleted:
|
||
@pytest.mark.parametrize("value,expected", [
|
||
(b"\x00", False),
|
||
(b"\x01", True),
|
||
(bytearray(b"\x00"), False),
|
||
(bytearray(b"\x01"), True),
|
||
(0, False),
|
||
(1, True),
|
||
(False, False),
|
||
(True, True),
|
||
("0", False),
|
||
("1", True),
|
||
("true", True),
|
||
("Y", True),
|
||
("", False),
|
||
(None, False),
|
||
])
|
||
def test_all_three_legacy_shapes(self, mig, value, expected):
|
||
assert mig.is_deleted(value) is expected
|
||
|
||
def test_naive_bool_would_have_deleted_everyone(self, mig):
|
||
"""这条就是那个 bug 本身:125 个老账号因为 bool(b'\\x00') 全被当成已删除。"""
|
||
assert bool(b"\x00") is True
|
||
assert mig.is_deleted(b"\x00") is False
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 采购类别:存的是 procurement_type 的 id
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestResolveCategory:
|
||
DICTIONARY = {"8": "华智产品", "9": "紫光其他产品", "12": "外购产品",
|
||
"16": "汇智产品", "17": "华三产品", "10": "华智服务"}
|
||
|
||
def test_numeric_id_resolves_through_dictionary(self, mig, report):
|
||
assert mig.resolve_category("8", self.DICTIONARY, report) == ("华智产品", "huazhi")
|
||
assert mig.resolve_category("17", self.DICTIONARY, report) == ("华三产品", "h3c")
|
||
assert report.counts["归一化:采购类别 id → 中文名"] == 2
|
||
|
||
def test_chinese_name_still_accepted(self, mig, report):
|
||
"""少数老行直接存了中文名,两种都得认。"""
|
||
assert mig.resolve_category("华三产品", self.DICTIONARY, report) == ("华三产品", "h3c")
|
||
|
||
def test_service_bucket_folds_into_brand(self, mig, report):
|
||
assert mig.resolve_category("10", self.DICTIONARY, report) == ("华智服务", "huazhi")
|
||
|
||
def test_outside_the_four_buckets_counts_and_leaves_blank(self, mig, report):
|
||
"""不在四个产品归属里:编码留空,但要按类别名计数,否则报告里查不到去向。"""
|
||
mig.UNMAPPED_CATEGORY.clear()
|
||
name, product = mig.resolve_category("12", self.DICTIONARY, report)
|
||
assert (name, product) == ("外购产品", "")
|
||
assert mig.UNMAPPED_CATEGORY == {"外购产品": 1}
|
||
|
||
def test_unmapped_counts_accumulate_instead_of_flooding_the_report(self, mig, report):
|
||
"""老库自由文本几十个只出现一次的类别,一条条 skip 会把报告刷爆。"""
|
||
mig.UNMAPPED_CATEGORY.clear()
|
||
for raw in ("外购产品", "外购产品", "洪彦工程", "网线光纤"):
|
||
mig.resolve_category(raw, self.DICTIONARY, report)
|
||
assert mig.UNMAPPED_CATEGORY == {"外购产品": 2, "洪彦工程": 1, "网线光纤": 1}
|
||
assert report.skips == {}
|
||
|
||
def test_free_text_and_empty(self, mig, report):
|
||
assert mig.resolve_category(None, self.DICTIONARY, report) == ("", "")
|
||
assert mig.resolve_category(" ", self.DICTIONARY, report) == ("", "")
|
||
assert mig.resolve_category("洪彦工程", self.DICTIONARY, report)[:1] == ("洪彦工程",)
|
||
|
||
def test_known_id_beats_same_looking_text(self, mig, report):
|
||
assert mig.resolve_category("16", self.DICTIONARY, report)[0] == "汇智产品"
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 日期:DATE 列不接受空串
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestToDate:
|
||
def test_datetime_and_date_string(self, mig):
|
||
assert mig.to_date("2022-09-07 00:00:00") == date(2022, 9, 7)
|
||
assert mig.to_date("2022-09-07") == date(2022, 9, 7)
|
||
|
||
def test_month_only_fills_first_day(self, mig):
|
||
assert mig.to_date("2022-09") == date(2022, 9, 1)
|
||
|
||
@pytest.mark.parametrize("value", [None, "", " ", "0000-00-00", "abc"])
|
||
def test_emptyish_becomes_null_not_empty_string(self, mig, value):
|
||
"""MySQL 对 DATE 列写 '' 抛 1292,所以这里必须是 None。"""
|
||
assert mig.to_date(value) is None
|
||
|
||
|
||
class TestMonthOf:
|
||
def test_formats(self, mig):
|
||
assert mig.month_of("2022-09-07") == "2022-09"
|
||
assert mig.month_of("2022-09") == "2022-09"
|
||
assert mig.month_of(None) == ""
|
||
assert mig.month_of("2022") == ""
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 列宽:比率列撑不住老数据,就是那次 1264 Out of range
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestRateColumnWidth:
|
||
def test_rate_columns_wide_enough_for_legacy_garbage(self):
|
||
"""project.gross_profit_a_rate 曾经因为 DECIMAL(10,6) 撑不住 -49504 而整批插不进去。"""
|
||
import app.models # noqa: F401
|
||
from app.models.base import Base
|
||
|
||
rate_columns = [
|
||
("project", "gross_profit_a_rate"),
|
||
("project", "gross_profit_rate"),
|
||
("project", "contribution_profit_rate"),
|
||
("project", "advance_interest_rate"),
|
||
("estimate_income_line", "tax_rate"),
|
||
("estimate_cost_line", "tax_rate"),
|
||
("budget_income_line", "tax_rate"),
|
||
("budget_purchase_line", "tax_rate"),
|
||
("budget_fund_month", "interest_rate"),
|
||
]
|
||
for table, column in rate_columns:
|
||
col_type = Base.metadata.tables[table].columns[column].type
|
||
capacity = col_type.precision - col_type.scale
|
||
assert col_type.scale == 6, (table, column)
|
||
assert capacity >= 12, f"{table}.{column} 只装得下 {capacity} 位整数部分"
|
||
# -49504.00 必须能坐下
|
||
assert abs(Decimal("-49504.00")) < Decimal(10) ** capacity
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 超长字符串兜底
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestClipGuard:
|
||
def test_oversize_string_is_clipped_and_counted(self, mig):
|
||
from app.models.finance import BudgetPurchaseLine
|
||
|
||
mig.install_clip_guard()
|
||
mig.CLIPPED.clear()
|
||
line = BudgetPurchaseLine(revision_id=1, project_id=1, purchase_type=1,
|
||
name="x" * 400, pay_way="y" * 300)
|
||
assert len(line.name) == 255 # 列宽从元数据现读
|
||
assert len(line.pay_way) == 255
|
||
assert mig.CLIPPED["budget_purchase_line.name"] == 1
|
||
assert mig.CLIPPED["budget_purchase_line.pay_way"] == 1
|
||
|
||
def test_short_values_untouched(self, mig):
|
||
from app.models.finance import BudgetPurchaseLine
|
||
|
||
mig.install_clip_guard()
|
||
mig.CLIPPED.clear()
|
||
line = BudgetPurchaseLine(revision_id=1, project_id=1, purchase_type=1,
|
||
name="交换机", pay_way="转账")
|
||
assert (line.name, line.pay_way) == ("交换机", "转账")
|
||
assert mig.CLIPPED == {}
|
||
|
||
def test_text_columns_are_never_clipped(self, mig):
|
||
"""TEXT 列装得下,截它才是丢数据。project.value_risk 就是 TEXT。"""
|
||
from app.models.project import Project
|
||
|
||
mig.install_clip_guard()
|
||
mig.CLIPPED.clear()
|
||
long_text = "风险" * 4000
|
||
project = Project(project_no="T1", name="p", creator_id=1, value_risk=long_text)
|
||
assert project.value_risk == long_text
|
||
assert mig.CLIPPED == {}
|
||
|
||
def test_guard_is_idempotent(self, mig):
|
||
"""装两次不能截两遍 / 计两次。"""
|
||
from app.models.finance import BudgetPurchaseLine
|
||
|
||
mig.install_clip_guard()
|
||
mig.install_clip_guard()
|
||
mig.CLIPPED.clear()
|
||
line = BudgetPurchaseLine(revision_id=1, project_id=1, name="x" * 400)
|
||
assert len(line.name) == 255
|
||
assert mig.CLIPPED == {"budget_purchase_line.name": 1}
|
||
|
||
|
||
class TestWideColumnsMatchLegacy:
|
||
"""列宽对不齐老库,导数时就只有两种坏结果:报错或者悄悄截断。"""
|
||
|
||
def test_pay_way_holds_legacy_payment_clause(self):
|
||
from app.models.base import Base
|
||
|
||
# 老 project_budget_cost_detail.pay_way 实测最长 136 字(合同付款条款)
|
||
assert Base.metadata.tables["budget_purchase_line"].columns["pay_way"].type.length >= 255
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# project_visible:type 决定 tid 是"人"还是"角色"
|
||
# ---------------------------------------------------------------------------
|
||
|
||
|
||
class TestVisibleTarget:
|
||
"""老 project_visible 的 type=2 是**按人员**授权,不是按角色。
|
||
|
||
老版本按角色处理,两头都错:tid 撞上 sys_role 的那部分被批成整角色可见,
|
||
真正的人数(15,302 行里 tid>33 的 14,357 行,sys_role 最大 id 才 33)
|
||
整批当"老角色未导入"丢掉。这张表没有报错、只有静默的权限错配,所以钉住。
|
||
"""
|
||
|
||
def test_type_2_is_per_person(self, mig):
|
||
assert mig.visible_target(2) == "member"
|
||
|
||
def test_type_1_is_per_role(self, mig):
|
||
assert mig.visible_target(1) == "role"
|
||
|
||
@pytest.mark.parametrize("value", [0, 3, None, "", "x", 2.5])
|
||
def test_anything_else_is_not_guessed(self, mig, value):
|
||
assert mig.visible_target(value) == ""
|
||
|
||
def test_legacy_tid_range_is_user_range(self, mig):
|
||
"""老库 tid 落在 1~125(sys_user 的 id 区间),角色 id 最大只有 33。"""
|
||
assert mig.LEGACY_VISIBLE_MEMBER == 2
|
||
assert mig.LEGACY_VISIBLE_ROLE == 1
|
||
|
||
def test_member_role_is_viewer_not_participant(self, mig):
|
||
"""按可见性授权的人不该算"我参与的"里的参与人,只能是仅可见。"""
|
||
from app.models.project import ProjectMemberRole
|
||
|
||
assert ProjectMemberRole.VIEWER == "viewer"
|