rust_rule_engine/engine/
coverage.rs

1//! Module đo coverage cho rule engine
2//! Lưu lại thông tin rule đã được test, facts đã test, và sinh báo cáo coverage
3
4use std::collections::{HashMap, HashSet};
5
6#[derive(Debug, Default)]
7pub struct RuleCoverage {
8    /// Tên rule -> số lần được kích hoạt
9    pub rule_hits: HashMap<String, usize>,
10    /// Tên rule -> facts đã test
11    pub rule_facts: HashMap<String, HashSet<String>>,
12    /// Facts đã test toàn bộ
13    pub tested_facts: HashSet<String>,
14}
15
16impl RuleCoverage {
17    pub fn new() -> Self {
18        Self::default()
19    }
20
21    /// Ghi nhận rule được kích hoạt với facts
22    pub fn record_hit(&mut self, rule_name: &str, facts_id: &str) {
23        *self.rule_hits.entry(rule_name.to_string()).or_insert(0) += 1;
24        self.rule_facts.entry(rule_name.to_string())
25            .or_insert_with(HashSet::new)
26            .insert(facts_id.to_string());
27        self.tested_facts.insert(facts_id.to_string());
28    }
29
30    /// Sinh báo cáo coverage, cảnh báo rule chưa được test
31    pub fn report(&self, all_rules: &[String]) -> String {
32        let mut report = String::new();
33        report.push_str("Rule Coverage Report\n====================\n");
34        let mut untested = Vec::new();
35        for rule in all_rules {
36            let hits = self.rule_hits.get(rule).copied().unwrap_or(0);
37            let facts = self.rule_facts.get(rule).map(|f| f.len()).unwrap_or(0);
38            report.push_str(&format!(
39                "Rule: {} | Hits: {} | Facts tested: {}\n",
40                rule, hits, facts
41            ));
42            if hits == 0 {
43                untested.push(rule.clone());
44            }
45        }
46        report.push_str(&format!("Total facts tested: {}\n", self.tested_facts.len()));
47        if !untested.is_empty() {
48            report.push_str("\n⚠️ Cảnh báo: Các rule chưa được test:\n");
49            for rule in untested {
50                report.push_str(&format!("  - {}\n", rule));
51            }
52        }
53        report
54    }
55}
56
57// TODO: Thêm hàm sinh test case cho facts và chạy toàn bộ rule để đo coverage
58
59/// Lấy tất cả điều kiện Single từ ConditionGroup
60
61fn flatten_conditions(group: &crate::engine::rule::ConditionGroup) -> Vec<crate::engine::rule::Condition> {
62    use crate::engine::rule::ConditionGroup;
63    let mut out = Vec::new();
64    match group {
65        ConditionGroup::Single(cond) => out.push(cond.clone()),
66        ConditionGroup::Compound { left, right, .. } => {
67            out.extend(flatten_conditions(left));
68            out.extend(flatten_conditions(right));
69        }
70        ConditionGroup::Not(inner) | ConditionGroup::Exists(inner) | ConditionGroup::Forall(inner) => {
71            out.extend(flatten_conditions(inner));
72        }
73    }
74    out
75}
76
77/// Sinh facts mẫu cho một rule dựa trên nhiều kiểu dữ liệu và kết hợp nhiều điều kiện
78pub fn generate_test_facts_for_rule(rule: &crate::engine::rule::Rule) -> Vec<crate::Facts> {
79    use crate::types::Value;
80    let conds = flatten_conditions(&rule.conditions);
81    let mut test_facts = Vec::new();
82
83    // Sinh facts cho từng điều kiện riêng lẻ
84    for cond in &conds {
85        let mut facts = crate::Facts::new();
86        let field = cond.field.clone();
87        match &cond.value {
88            Value::Integer(i) => {
89                facts.set(&field, Value::Integer(*i));
90                test_facts.push(facts.clone());
91                facts.set(&field, Value::Integer(i + 1));
92                test_facts.push(facts.clone());
93            }
94            Value::Boolean(b) => {
95                facts.set(&field, Value::Boolean(*b));
96                test_facts.push(facts.clone());
97                facts.set(&field, Value::Boolean(!b));
98                test_facts.push(facts.clone());
99            }
100            Value::String(s) => {
101                facts.set(&field, Value::String(s.clone()));
102                test_facts.push(facts.clone());
103                facts.set(&field, Value::String("other_value".to_string()));
104                test_facts.push(facts.clone());
105            }
106            _ => {}
107        }
108    }
109
110    // Sinh facts kết hợp nhiều điều kiện (all true)
111    if !conds.is_empty() {
112        let mut facts = crate::Facts::new();
113        for cond in &conds {
114            let field = cond.field.clone();
115            match &cond.value {
116                Value::Integer(i) => facts.set(&field, Value::Integer(*i)),
117                Value::Boolean(b) => facts.set(&field, Value::Boolean(*b)),
118                Value::String(s) => facts.set(&field, Value::String(s.clone())),
119                _ => {}
120            }
121        }
122        test_facts.push(facts);
123    }
124
125    test_facts
126}