# -*- coding: utf-8 -*-
"""BaseTask._accumulate_counts() 防御层单元测试。

验证需求 1.2：list 类型值转为 len() 后累加。
纯单元测试，不涉及数据库或外部依赖。
"""
from __future__ import annotations

from tasks.base_task import BaseTask


class TestAccumulateCountsListDefense:
    """验证 _accumulate_counts 对 list 类型值的防御处理。"""

    def test_list_value_converted_to_len(self):
        """list 值应转为 len() 后累加。"""
        total = {}
        current = {"errors": [{"table": "dim_a", "error": "boom"}]}
        result = BaseTask._accumulate_counts(total, current)
        assert result["errors"] == 1

    def test_list_value_accumulates_across_calls(self):
        """多次调用时，list 的 len() 应正确累加。"""
        total = {}
        BaseTask._accumulate_counts(total, {"errors": [{"t": "a"}]})
        BaseTask._accumulate_counts(total, {"errors": [{"t": "b"}, {"t": "c"}]})
        assert total["errors"] == 3

    def test_list_and_int_mixed_accumulation(self):
        """先累加 int，再累加 list（或反过来），结果应一致。"""
        total = {}
        BaseTask._accumulate_counts(total, {"errors": 2})
        BaseTask._accumulate_counts(total, {"errors": [{"t": "x"}]})
        assert total["errors"] == 3

    def test_empty_list_adds_zero(self):
        """空 list 应累加 0。"""
        total = {"errors": 5}
        BaseTask._accumulate_counts(total, {"errors": []})
        assert total["errors"] == 5

    def test_int_float_still_work(self):
        """int/float 类型的原有行为不受影响。"""
        total = {}
        BaseTask._accumulate_counts(total, {"inserted": 10, "rate": 0.5})
        BaseTask._accumulate_counts(total, {"inserted": 3, "rate": 0.2})
        assert total["inserted"] == 13
        assert abs(total["rate"] - 0.7) < 1e-9

    def test_non_numeric_non_list_uses_setdefault(self):
        """非数值、非 list 类型使用 setdefault 保留首次值。"""
        total = {}
        BaseTask._accumulate_counts(total, {"status": "ok"})
        BaseTask._accumulate_counts(total, {"status": "fail"})
        assert total["status"] == "ok"

    def test_none_current_is_safe(self):
        """current 为 None 时不报错。"""
        total = {"x": 1}
        result = BaseTask._accumulate_counts(total, None)
        assert result == {"x": 1}

    def test_empty_current_is_safe(self):
        """current 为空字典时不报错。"""
        total = {"x": 1}
        result = BaseTask._accumulate_counts(total, {})
        assert result == {"x": 1}
