Spaces:
Runtime error

File size: 10,844 Bytes
ce06eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
"""
Test cases for P1 tests:
1. BIDesignAgent (Mock Mode)
2. Edge Cases
3. Mock Data Validation
"""

import sys
from pathlib import Path
import json
import os

# Add project root to path
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))

from models.indicator import Indicator
from models.indicator_set import IndicatorSet
from agents.bi_design_agent import BIDesignAgent


class TestBIDesignAgent:
    """Test cases for BIDesignAgent (Mock Mode)"""
    
    def setup_method(self):
        """Setup for each test"""
        self.agent = BIDesignAgent(mock_mode=True)
    
    def test_create_agent_success(self):
        """Test creating BIDesignAgent in mock mode"""
        assert self.agent.mock_mode == True
        assert "BIDesignAgent" in str(type(self.agent))
        
        print("✓ P1 Test 1.1: Create BIDesignAgent (Mock Mode) - PASSED")
    
    def test_run_with_indicator_set(self):
        """Test run() with IndicatorSet input"""
        ind = Indicator(
            indicator_id="ind_001",
            indicator_name="GMV",
            business_meaning="商品交易总额",
            calculation_logic="SUM(order_amount)"
        )
        
        indicator_set = IndicatorSet(
            set_id="test_001",
            set_name="测试指标集",
            business_domain="电商",
            indicators=[ind]
        )
        
        result = self.agent.run({
            "indicator_set": indicator_set
        })
        
        assert result["status"] == "success"
        assert "data" in result
        assert "bi_design" in result["data"]
        
        bi_design = result["data"]["bi_design"]
        assert "charts" in bi_design
        assert "dashboard_layout" in bi_design
        assert "markdown" in bi_design
        
        print("✓ P1 Test 1.2: Run with IndicatorSet - PASSED")
    
    def test_run_with_schemes(self):
        """Test run() with schemes (from ModelingAgent)"""
        ind = Indicator(
            indicator_id="ind_001",
            indicator_name="GMV",
            business_meaning="商品交易总额",
            calculation_logic="SUM(order_amount)"
        )
        
        indicator_set = IndicatorSet(
            set_id="test_002",
            set_name="测试指标集",
            business_domain="电商",
            indicators=[ind]
        )
        
        schemes = [{
            "indicator_id": "ind_001",
            "indicator_name": "GMV",
            "sql": "SELECT SUM(amount) FROM orders",
            "markdown": "# GMV\n\nThis is a test.",
            "table_structure": {"columns": []}
        }]
        
        result = self.agent.run({
            "indicator_set": indicator_set,
            "schemes": schemes
        })
        
        assert result["status"] == "success"
        
        print("✓ P1 Test 1.3: Run with schemes - PASSED")
    
    def test_run_missing_indicator_set(self):
        """Test run() with missing indicator_set (should return error)"""
        result = self.agent.run({})
        
        assert result["status"] == "error"
        
        print("✓ P1 Test 1.4: Run with missing indicator_set - PASSED")
    
    def test_mock_charts_structure(self):
        """Test that mock mode returns valid charts structure"""
        ind = Indicator(
            indicator_id="ind_001",
            indicator_name="GMV",
            business_meaning="商品交易总额",
            calculation_logic="SUM(order_amount)"
        )
        
        indicator_set = IndicatorSet(
            set_id="test_003",
            set_name="测试指标集",
            business_domain="电商",
            indicators=[ind]
        )
        
        result = self.agent.run({
            "indicator_set": indicator_set
        })
        
        assert result["status"] == "success"
        bi_design = result["data"]["bi_design"]
        charts = bi_design["charts"]
        
        assert isinstance(charts, list)
        if len(charts) > 0:
            chart = charts[0]
            assert "chart_type" in chart
            assert "title" in chart
        
        print("✓ P1 Test 1.5: Mock charts structure - PASSED")


class TestEdgeCases:
    """Test cases for edge cases"""
    
    def test_empty_user_input(self):
        """Test RequirementAgent with empty user input"""
        from agents.requirement_agent import RequirementAgent
        
        agent = RequirementAgent(mock_mode=True)
        result = agent.run({"user_input": ""})
        
        assert result["status"] == "error"
        
        print("✓ P1 Test 2.1: Empty user input - PASSED")
    
    def test_no_indicators_selected(self):
        """Test ModelingAgent with no indicators selected"""
        from agents.modeling_agent import ModelingAgent
        
        ind = Indicator(
            indicator_id="ind_001",
            indicator_name="GMV",
            business_meaning="商品交易总额",
            calculation_logic="SUM(order_amount)"
        )
        
        indicator_set = IndicatorSet(
            set_id="test_004",
            set_name="测试指标集",
            business_domain="电商",
            indicators=[ind]
        )
        
        agent = ModelingAgent(mock_mode=True)
        result = agent.run({
            "indicator_set": indicator_set,
            "selected_indicators": []  # Empty list
        })
        
        assert result["status"] == "error"
        
        print("✓ P1 Test 2.2: No indicators selected - PASSED")
    
    def test_invalid_indicator_id(self):
        """Test ModelingAgent with invalid indicator ID"""
        from agents.modeling_agent import ModelingAgent
        
        ind = Indicator(
            indicator_id="ind_001",
            indicator_name="GMV",
            business_meaning="商品交易总额",
            calculation_logic="SUM(order_amount)"
        )
        
        indicator_set = IndicatorSet(
            set_id="test_005",
            set_name="测试指标集",
            business_domain="电商",
            indicators=[ind]
        )
        
        agent = ModelingAgent(mock_mode=True)
        result = agent.run({
            "indicator_set": indicator_set,
            "selected_indicators": ["non_existing_id"]
        })
        
        # Should return success but with 0 schemes (skipped invalid ID)
        assert result["status"] == "success"
        assert len(result["data"]["schemes"]) == 0
        
        print("✓ P1 Test 2.3: Invalid indicator ID - PASSED")
    
    def test_empty_indicator_set(self):
        """Test RecommendationAgent with empty indicators list"""
        from agents.recommendation_agent import RecommendationAgent
        
        indicator_set = IndicatorSet(
            set_id="test_006",
            set_name="空指标集",
            business_domain="通用",
            indicators=[]  # Empty indicators
        )
        
        agent = RecommendationAgent(vector_store=None, mock_mode=True)
        result = agent.run({
            "indicator_set": indicator_set
        })
        
        # Should handle empty indicators gracefully
        assert result["status"] == "success"
        
        print("⚠ P1 Test 2.4: Empty indicator set - Check if handled gracefully")


class TestMockData:
    """Test cases for mock data files"""
    
    def test_mock_data_files_exist(self):
        """Test that all mock data files exist"""
        mock_dir = PROJECT_ROOT / "data" / "mock"
        
        expected_files = [
            "ecommerce_indicators.json",
            "finance_indicators.json",
            "public_resource_indicators.json",
            "retail_indicators.json",
            "toc_standard_indicators.json",
            "design_patterns.json"
        ]
        
        for filename in expected_files:
            file_path = mock_dir / filename
            assert file_path.exists(), f"Mock file not found: {filename}"
        
        print("✓ P1 Test 3.1: Mock data files exist - PASSED")
    
    def test_mock_data_valid_json(self):
        """Test that mock data files are valid JSON"""
        mock_dir = PROJECT_ROOT / "data" / "mock"
        
        for filename in os.listdir(mock_dir):
            if filename.endswith(".json"):
                file_path = mock_dir / filename
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        data = json.load(f)
                    # Should be dict or list
                    assert isinstance(data, (dict, list)), f"Expected dict or list, got {type(data)}"
                except json.JSONDecodeError as e:
                    assert False, f"Invalid JSON in {filename}: {e}"
        
        print("✓ P1 Test 3.2: Mock data is valid JSON - PASSED")
    
    def test_mock_data_structure(self):
        """Test that mock data has expected structure"""
        mock_dir = PROJECT_ROOT / "data" / "mock"
        
        # Test ecommerce_indicators.json
        ec_file = mock_dir / "ecommerce_indicators.json"
        if ec_file.exists():
            with open(ec_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
            
            # Should have 'indicators' key
            assert "indicators" in data, "Missing 'indicators' key"
            assert isinstance(data["indicators"], list)
            
            # Each indicator should have required fields
            if len(data["indicators"]) > 0:
                ind = data["indicators"][0]
                assert "indicator_id" in ind
                assert "indicator_name" in ind
        
        print("✓ P1 Test 3.3: Mock data structure is valid - PASSED")


def run_all_tests():
    """Run all P1 tests"""
    print("\n" + "="*60)
    print("Running P1 Tests: BIDesignAgent, Edge Cases, Mock Data")
    print("="*60 + "\n")
    
    # Test BIDesignAgent
    print("--- Test BIDesignAgent (Mock Mode) ---")
    test_bi = TestBIDesignAgent()
    test_bi.setup_method()
    test_bi.test_create_agent_success()
    test_bi.test_run_with_indicator_set()
    test_bi.test_run_with_schemes()
    test_bi.test_run_missing_indicator_set()
    test_bi.test_mock_charts_structure()
    
    # Test Edge Cases
    print("\n--- Test Edge Cases ---")
    test_edge = TestEdgeCases()
    test_edge.test_empty_user_input()
    test_edge.test_no_indicators_selected()
    test_edge.test_invalid_indicator_id()
    test_edge.test_empty_indicator_set()
    
    # Test Mock Data
    print("\n--- Test Mock Data ---")
    test_mock = TestMockData()
    test_mock.test_mock_data_files_exist()
    test_mock.test_mock_data_valid_json()
    test_mock.test_mock_data_structure()
    
    print("\n" + "="*60)
    print("✅ All P1 Tests Completed!")
    print("="*60 + "\n")


if __name__ == "__main__":
    run_all_tests()