test_taxonomy.py 3.97 KB
"""业务标签层:声明式打标 + 可插拔维度。

取代了原先的 test_metadata_contract.py——那套断言针对硬编码在 metadata.py 里的词表,
现在词表已外置到 resources/taxonomy.yaml,代码不再认识任何具体维度名。
"""
import textwrap
import unittest

from src.rag.ingestion.taxonomy import extract_labels, load_taxonomy


class TaxonomyLoadTest(unittest.TestCase):
    def test_declared_dimensions_drive_filterable_and_display(self):
        taxonomy = load_taxonomy()

        names = [d.name for d in taxonomy.dimensions]
        self.assertIn("brand", names)
        self.assertIn("page_type", names)
        # also_emit_as 声明的键也要进 filterable,否则 payload 和索引会漏掉它
        self.assertIn("intent_type", taxonomy.filterable_names())
        self.assertTrue(taxonomy.display_map())

    def test_boostable_only_returns_dimensions_with_boost(self):
        taxonomy = load_taxonomy()

        boostable = {d.name for d in taxonomy.boostable()}
        self.assertIn("brand", boostable)
        # brand_series 是派生维度,没声明 boost,不该参与查询侧加权
        self.assertNotIn("brand_series", boostable)
        for dim in taxonomy.boostable():
            self.assertGreater(dim.boost, 0)


class ExtractLabelsTest(unittest.TestCase):
    def test_page_type_uses_plural_canonical_values(self):
        labels = extract_labels("问界整车延保价格与保障范围")

        self.assertEqual(labels["page_type"], "products")
        self.assertEqual(labels["intent_type"], labels["page_type"])

    def test_priority_decides_when_multiple_page_types_hit(self):
        # 同时命中 troubleshooting(报错/无法)与 procedures(入单)
        labels = extract_labels("小鹏系统报错,无法入单")

        self.assertEqual(labels["page_type"], "troubleshooting")
        self.assertEqual(labels["page_types"], ["troubleshooting", "procedures"])

    def test_derived_dimension_maps_brand_to_series(self):
        self.assertEqual(extract_labels("问界延保")["brand_series"], "鸿蒙智行")
        self.assertEqual(extract_labels("岚图延保")["brand_series"], "通用品牌")

    def test_no_hit_returns_empty_labels(self):
        self.assertEqual(extract_labels("今天天气不错"), {})


class PluggableTaxonomyTest(unittest.TestCase):
    """加一个维度只该改 YAML——代码、表结构、payload 构造都不用动。"""

    def test_new_dimension_from_yaml_needs_no_code_change(self):
        import pathlib
        import tempfile

        yaml_text = textwrap.dedent(
            """
            version: test
            dimensions:
              severity:
                kind: scalar
                filterable: true
                display: 严重度
                boost: 0.2
                values:
                  P0: [宕机, 全线不可用]
                  P1: [报错, 失败]
            """
        )
        with tempfile.TemporaryDirectory() as tmp:
            path = pathlib.Path(tmp) / "custom.yaml"
            path.write_text(yaml_text, encoding="utf-8")
            taxonomy = load_taxonomy(str(path))

            self.assertEqual([d.name for d in taxonomy.dimensions], ["severity"])
            self.assertIn("severity", taxonomy.filterable_names())
            self.assertEqual(taxonomy.display_map()["severity"], "严重度")
            self.assertEqual(
                extract_labels("服务全线不可用", taxonomy=taxonomy)["severity"], "P0"
            )

    def test_empty_taxonomy_disables_business_labels(self):
        import pathlib
        import tempfile

        with tempfile.TemporaryDirectory() as tmp:
            path = pathlib.Path(tmp) / "empty.yaml"
            path.write_text("version: none\ndimensions: {}\n", encoding="utf-8")
            taxonomy = load_taxonomy(str(path))

            self.assertEqual(taxonomy.dimensions, ())
            self.assertEqual(extract_labels("问界延保", taxonomy=taxonomy), {})


if __name__ == "__main__":
    unittest.main()