File size: 8,709 Bytes
2b395f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
FRED ML Development Testing
Simple testing script for development environment
"""

import os
import sys
import json
import time
from pathlib import Path

def test_streamlit_app():
    """Test Streamlit app functionality"""
    print("🎨 Testing Streamlit app...")
    
    try:
        # Test app imports
        sys.path.append('frontend')
        from app import load_config, init_aws_clients
        
        # Test configuration loading
        config = load_config()
        if config:
            print("βœ… Streamlit app configuration loaded")
        else:
            print("❌ Failed to load Streamlit app configuration")
            return False
        
        # Test AWS client initialization
        try:
            s3_client, lambda_client = init_aws_clients()
            print("βœ… AWS clients initialized")
        except Exception as e:
            print(f"❌ AWS client initialization failed: {str(e)}")
            return False
        
        print("βœ… Streamlit app test passed")
        return True
        
    except Exception as e:
        print(f"❌ Streamlit app test failed: {str(e)}")
        return False

def test_lambda_function():
    """Test Lambda function"""
    print("⚑ Testing Lambda function...")
    
    try:
        import boto3
        lambda_client = boto3.client('lambda')
        
        # Get function info
        function_info = lambda_client.get_function(FunctionName='fred-ml-processor')
        print(f"βœ… Lambda function found: {function_info['Configuration']['FunctionArn']}")
        
        # Test basic invocation
        test_payload = {
            'indicators': ['GDP', 'UNRATE'],
            'start_date': '2023-01-01',
            'end_date': '2023-12-31',
            'test_mode': True
        }
        
        response = lambda_client.invoke(
            FunctionName='fred-ml-processor',
            InvocationType='RequestResponse',
            Payload=json.dumps(test_payload)
        )
        
        if response['StatusCode'] == 200:
            print("βœ… Lambda function invocation successful")
            return True
        else:
            print(f"❌ Lambda invocation failed with status {response['StatusCode']}")
            return False
            
    except Exception as e:
        print(f"❌ Lambda function test failed: {str(e)}")
        return False

def test_s3_access():
    """Test S3 bucket access"""
    print("πŸ“¦ Testing S3 bucket access...")
    
    try:
        import boto3
        s3 = boto3.client('s3')
        
        # Test bucket access
        s3.head_bucket(Bucket='fredmlv1')
        print("βœ… S3 bucket access successful")
        
        # Test upload/download
        test_data = "test content"
        test_key = f"dev-test/test-{int(time.time())}.txt"
        
        # Upload test file
        s3.put_object(
            Bucket='fredmlv1',
            Key=test_key,
            Body=test_data.encode('utf-8')
        )
        print("βœ… S3 upload successful")
        
        # Download and verify
        response = s3.get_object(Bucket='fredmlv1', Key=test_key)
        downloaded_data = response['Body'].read().decode('utf-8')
        
        if downloaded_data == test_data:
            print("βœ… S3 download successful")
        else:
            print("❌ S3 download data mismatch")
            return False
        
        # Clean up test file
        s3.delete_object(Bucket='fredmlv1', Key=test_key)
        print("βœ… S3 cleanup successful")
        
        return True
        
    except Exception as e:
        print(f"❌ S3 access test failed: {str(e)}")
        return False

def test_fred_api():
    """Test FRED API access"""
    print("πŸ“Š Testing FRED API...")
    
    try:
        from fredapi import Fred
        fred = Fred(api_key=os.getenv('FRED_API_KEY'))
        
        # Test basic API access
        test_series = fred.get_series('GDP', limit=5)
        if len(test_series) > 0:
            print(f"βœ… FRED API access successful - retrieved {len(test_series)} data points")
            return True
        else:
            print("❌ FRED API returned no data")
            return False
            
    except Exception as e:
        print(f"❌ FRED API test failed: {str(e)}")
        return False

def test_data_processing():
    """Test data processing capabilities"""
    print("πŸ“ˆ Testing data processing...")
    
    try:
        import pandas as pd
        import numpy as np
        from fredapi import Fred
        
        fred = Fred(api_key=os.getenv('FRED_API_KEY'))
        
        # Get test data
        test_data = {}
        indicators = ['GDP', 'UNRATE', 'CPIAUCSL']
        
        for indicator in indicators:
            try:
                data = fred.get_series(indicator, limit=100)
                test_data[indicator] = data
                print(f"βœ… Retrieved {indicator}: {len(data)} observations")
            except Exception as e:
                print(f"❌ Failed to retrieve {indicator}: {str(e)}")
        
        if not test_data:
            print("❌ No test data retrieved")
            return False
        
        # Test data processing
        df = pd.DataFrame(test_data)
        df = df.dropna()
        
        if len(df) > 0:
            # Test basic statistics
            summary = df.describe()
            correlation = df.corr()
            
            print(f"βœ… Data processing successful - {len(df)} data points processed")
            print(f"   Summary statistics calculated")
            print(f"   Correlation matrix shape: {correlation.shape}")
            return True
        else:
            print("❌ No valid data after processing")
            return False
            
    except Exception as e:
        print(f"❌ Data processing test failed: {str(e)}")
        return False

def test_visualization():
    """Test visualization generation"""
    print("🎨 Testing visualization generation...")
    
    try:
        import matplotlib.pyplot as plt
        import plotly.express as px
        import seaborn as sns
        import pandas as pd
        import numpy as np
        
        # Create test data
        np.random.seed(42)
        dates = pd.date_range('2023-01-01', '2024-01-01', freq='M')
        test_data = pd.DataFrame({
            'GDP': np.random.normal(100, 5, len(dates)),
            'UNRATE': np.random.normal(5, 1, len(dates)),
            'CPIAUCSL': np.random.normal(200, 10, len(dates))
        }, index=dates)
        
        # Test matplotlib
        fig, ax = plt.subplots(figsize=(10, 6))
        test_data.plot(ax=ax)
        plt.title('Test Visualization')
        plt.close()  # Don't display, just test creation
        print("βœ… Matplotlib visualization created")
        
        # Test plotly
        fig = px.line(test_data, title='Test Plotly Visualization')
        fig.update_layout(showlegend=True)
        print("βœ… Plotly visualization created")
        
        # Test seaborn
        plt.figure(figsize=(8, 6))
        sns.heatmap(test_data.corr(), annot=True, cmap='coolwarm')
        plt.title('Test Correlation Heatmap')
        plt.close()
        print("βœ… Seaborn visualization created")
        
        print("βœ… All visualization tests passed")
        return True
        
    except Exception as e:
        print(f"❌ Visualization test failed: {str(e)}")
        return False

def main():
    """Main testing function"""
    print("πŸ§ͺ FRED ML Development Testing")
    print("=" * 50)
    
    tests = [
        ("Streamlit App", test_streamlit_app),
        ("Lambda Function", test_lambda_function),
        ("S3 Bucket Access", test_s3_access),
        ("FRED API", test_fred_api),
        ("Data Processing", test_data_processing),
        ("Visualization", test_visualization)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\nπŸ” Running {test_name} test...")
        if test_func():
            passed += 1
        else:
            print(f"❌ {test_name} test failed")
    
    print(f"\nπŸ“Š Test Summary: {passed}/{total} tests passed")
    
    if passed == total:
        print("βœ… All development tests passed!")
        print("\n🎯 Your development environment is ready!")
        print("You can now:")
        print("1. Run the Streamlit app: streamlit run frontend/app.py")
        print("2. Test the complete system: python scripts/test_complete_system.py")
        return True
    else:
        print("❌ Some tests failed. Please check the issues above.")
        return False

if __name__ == '__main__':
    success = main()
    sys.exit(0 if success else 1)