Ndg07 commited on
Commit
2d23194
·
1 Parent(s): 9128d37

Added images to Readme.md

Browse files
README.md CHANGED
@@ -10,23 +10,24 @@ A comprehensive AI-powered system for detecting misinformation in Indian media u
10
 
11
  ## 📸 Screenshots & Demo
12
 
 
 
 
 
 
 
13
  ### Main Dashboard
14
  > Real-time misinformation detection dashboard with live statistics
15
 
16
- ![Dashboard Preview](docs/images/dashboard.png)
17
  *Coming Soon: Add your dashboard screenshot here*
18
 
19
  ### Interactive India Heatmap
20
  > Geographic visualization of misinformation distribution across Indian states
21
 
22
- ![Heatmap Preview](docs/images/heatmap.png)
23
  *Coming Soon: Add your heatmap screenshot here*
24
 
25
- ### News Analysis Interface
26
- > Detailed article analysis with multi-component scoring
27
-
28
- ![Analysis Preview](docs/images/analysis.png)
29
- *Coming Soon: Add your analysis interface screenshot here*
30
 
31
  ### 🎥 Video Demo
32
  > Full system walkthrough and feature demonstration
 
10
 
11
  ## 📸 Screenshots & Demo
12
 
13
+ ### Main Homepage
14
+ > Overview of the whole website
15
+
16
+ ![Analysis Preview](docs/media-assets/Home.png)
17
+ *Coming Soon: Add your analysis interface screenshot here*
18
+
19
  ### Main Dashboard
20
  > Real-time misinformation detection dashboard with live statistics
21
 
22
+ ![Dashboard Preview](docs/media-assets/Dashboard.png)
23
  *Coming Soon: Add your dashboard screenshot here*
24
 
25
  ### Interactive India Heatmap
26
  > Geographic visualization of misinformation distribution across Indian states
27
 
28
+ ![Heatmap Preview](docs/media-assets/Map.png)
29
  *Coming Soon: Add your heatmap screenshot here*
30
 
 
 
 
 
 
31
 
32
  ### 🎥 Video Demo
33
  > Full system walkthrough and feature demonstration
docs/media-assets/dashboard.png ADDED

Git LFS Details

  • SHA256: e93ac5e27f2c7576bff0e9110500ed007206a9aef945a6e682824af5ea915d85
  • Pointer size: 131 Bytes
  • Size of remote file: 513 kB
docs/media-assets/home.png ADDED

Git LFS Details

  • SHA256: de6495bd1e686fa1d7c3f8a7f4357a0667327376eec1f4d5ff859a4469a7ac58
  • Pointer size: 131 Bytes
  • Size of remote file: 284 kB
docs/media-assets/map.png ADDED

Git LFS Details

  • SHA256: fbbe2abeb93ef08bfd5fbd3a145ae52a6d61da1601634409fd661a43e81817e5
  • Pointer size: 131 Bytes
  • Size of remote file: 666 kB
tests/e2e/requirements.txt DELETED
@@ -1,12 +0,0 @@
1
- # End-to-end testing requirements
2
- pytest>=7.0.0
3
- pytest-asyncio>=0.21.0
4
- selenium>=4.15.0
5
- aiohttp>=3.8.0
6
- requests>=2.28.0
7
- webdriver-manager>=4.0.0
8
-
9
- # Optional: for enhanced reporting
10
- pytest-html>=3.1.0
11
- pytest-cov>=4.0.0
12
- allure-pytest>=2.12.0
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/e2e/run_e2e_tests.ps1 DELETED
@@ -1,442 +0,0 @@
1
- # End-to-End Test Runner Script (PowerShell)
2
- # Runs comprehensive end-to-end tests for the misinformation heatmap system
3
-
4
- param(
5
- [string]$Mode = "local",
6
- [string]$OutputFile = "",
7
- [switch]$Verbose = $false,
8
- [switch]$NoCleanup = $false,
9
- [switch]$NoHeadless = $false,
10
- [int]$Timeout = 300,
11
- [switch]$Help = $false
12
- )
13
-
14
- # Colors for output
15
- $Red = "Red"
16
- $Green = "Green"
17
- $Yellow = "Yellow"
18
- $Blue = "Blue"
19
- $Magenta = "Magenta"
20
-
21
- function Write-Header {
22
- param([string]$Message)
23
- Write-Host "================================" -ForegroundColor $Magenta
24
- Write-Host $Message -ForegroundColor $Magenta
25
- Write-Host "================================" -ForegroundColor $Magenta
26
- }
27
-
28
- function Write-Status {
29
- param([string]$Message)
30
- Write-Host "[INFO] $Message" -ForegroundColor $Blue
31
- }
32
-
33
- function Write-Success {
34
- param([string]$Message)
35
- Write-Host "[SUCCESS] $Message" -ForegroundColor $Green
36
- }
37
-
38
- function Write-Warning {
39
- param([string]$Message)
40
- Write-Host "[WARNING] $Message" -ForegroundColor $Yellow
41
- }
42
-
43
- function Write-Error {
44
- param([string]$Message)
45
- Write-Host "[ERROR] $Message" -ForegroundColor $Red
46
- }
47
-
48
- function Show-Usage {
49
- Write-Host "Usage: .\run_e2e_tests.ps1 [OPTIONS]"
50
- Write-Host ""
51
- Write-Host "Options:"
52
- Write-Host " -Mode MODE Testing mode: local or cloud (default: local)"
53
- Write-Host " -OutputFile FILE Output file for test results (JSON)"
54
- Write-Host " -Verbose Enable verbose output"
55
- Write-Host " -NoCleanup Don't cleanup test data after tests"
56
- Write-Host " -NoHeadless Run browser tests in visible mode"
57
- Write-Host " -Timeout SECONDS Test timeout in seconds (default: 300)"
58
- Write-Host " -Help Show this help message"
59
- Write-Host ""
60
- Write-Host "Examples:"
61
- Write-Host " .\run_e2e_tests.ps1 -Mode local -Verbose"
62
- Write-Host " .\run_e2e_tests.ps1 -Mode cloud -OutputFile results.json"
63
- Write-Host " .\run_e2e_tests.ps1 -NoHeadless -Timeout 600"
64
- }
65
-
66
- function Test-Prerequisites {
67
- Write-Status "Checking prerequisites..."
68
-
69
- # Check Python
70
- try {
71
- $pythonVersion = python --version 2>&1
72
- if ($LASTEXITCODE -ne 0) {
73
- Write-Error "Python is not installed or not in PATH."
74
- exit 1
75
- }
76
- Write-Status "Python found: $pythonVersion"
77
- }
78
- catch {
79
- Write-Error "Python is not installed."
80
- exit 1
81
- }
82
-
83
- # Check if we're in the right directory
84
- if (-not (Test-Path "..\..\backend\api.py")) {
85
- Write-Error "Please run this script from the tests\e2e directory."
86
- exit 1
87
- }
88
-
89
- # Install Python dependencies
90
- Write-Status "Installing Python dependencies..."
91
- try {
92
- pip install -r requirements.txt | Out-Null
93
- if ($LASTEXITCODE -ne 0) {
94
- Write-Error "Failed to install Python dependencies."
95
- exit 1
96
- }
97
- }
98
- catch {
99
- Write-Error "Failed to install Python dependencies."
100
- exit 1
101
- }
102
-
103
- # Check Chrome for Selenium
104
- $chromeFound = $false
105
- $chromePaths = @(
106
- "${env:ProgramFiles}\Google\Chrome\Application\chrome.exe",
107
- "${env:ProgramFiles(x86)}\Google\Chrome\Application\chrome.exe",
108
- "${env:LOCALAPPDATA}\Google\Chrome\Application\chrome.exe"
109
- )
110
-
111
- foreach ($path in $chromePaths) {
112
- if (Test-Path $path) {
113
- Write-Status "Chrome found at: $path"
114
- $chromeFound = $true
115
- break
116
- }
117
- }
118
-
119
- if (-not $chromeFound) {
120
- Write-Warning "Chrome not found. Browser tests may be skipped."
121
- }
122
-
123
- Write-Success "Prerequisites check completed"
124
- }
125
-
126
- function Initialize-TestEnvironment {
127
- Write-Status "Setting up test environment..."
128
-
129
- # Set environment variables
130
- $env:MODE = $Mode
131
- $env:PYTHONPATH = "..\..\backend;$env:PYTHONPATH"
132
-
133
- if ($NoHeadless) {
134
- $env:SELENIUM_HEADLESS = "false"
135
- } else {
136
- $env:SELENIUM_HEADLESS = "true"
137
- }
138
-
139
- # Create test directories
140
- if (-not (Test-Path "test_data")) {
141
- New-Item -ItemType Directory -Path "test_data" | Out-Null
142
- }
143
- if (-not (Test-Path "test_results")) {
144
- New-Item -ItemType Directory -Path "test_results" | Out-Null
145
- }
146
-
147
- Write-Success "Test environment setup completed"
148
- }
149
-
150
- function Start-Services {
151
- Write-Status "Starting services for testing..."
152
-
153
- if ($Mode -eq "local") {
154
- Write-Status "Starting local backend service..."
155
-
156
- # Start backend in background
157
- $backendProcess = Start-Process -FilePath "python" -ArgumentList "..\..\backend\api.py" -PassThru -WindowStyle Hidden
158
- $script:BackendPID = $backendProcess.Id
159
-
160
- # Start frontend in background
161
- Push-Location "..\..\frontend"
162
- $frontendProcess = Start-Process -FilePath "python" -ArgumentList "-m", "http.server", "3000" -PassThru -WindowStyle Hidden
163
- $script:FrontendPID = $frontendProcess.Id
164
- Pop-Location
165
-
166
- # Wait for services to start
167
- Write-Status "Waiting for services to start..."
168
- Start-Sleep -Seconds 10
169
-
170
- # Check if services are running
171
- try {
172
- $response = Invoke-WebRequest -Uri "http://localhost:8000/health" -TimeoutSec 5 -UseBasicParsing
173
- if ($response.StatusCode -ne 200) {
174
- Write-Error "Backend service failed to start"
175
- Stop-Services
176
- exit 1
177
- }
178
- }
179
- catch {
180
- Write-Error "Backend service failed to start"
181
- Stop-Services
182
- exit 1
183
- }
184
-
185
- try {
186
- $response = Invoke-WebRequest -Uri "http://localhost:3000" -TimeoutSec 5 -UseBasicParsing
187
- if ($response.StatusCode -ne 200) {
188
- Write-Error "Frontend service failed to start"
189
- Stop-Services
190
- exit 1
191
- }
192
- }
193
- catch {
194
- Write-Error "Frontend service failed to start"
195
- Stop-Services
196
- exit 1
197
- }
198
-
199
- Write-Success "Local services started successfully"
200
- }
201
- else {
202
- Write-Status "Using cloud services (assuming they are already running)"
203
- }
204
- }
205
-
206
- function Stop-Services {
207
- if ($Mode -eq "local") {
208
- Write-Status "Cleaning up local services..."
209
-
210
- if ($script:BackendPID) {
211
- try {
212
- Stop-Process -Id $script:BackendPID -Force -ErrorAction SilentlyContinue
213
- }
214
- catch {
215
- # Process may have already stopped
216
- }
217
- }
218
-
219
- if ($script:FrontendPID) {
220
- try {
221
- Stop-Process -Id $script:FrontendPID -Force -ErrorAction SilentlyContinue
222
- }
223
- catch {
224
- # Process may have already stopped
225
- }
226
- }
227
-
228
- # Kill any remaining processes
229
- Get-Process | Where-Object { $_.ProcessName -eq "python" -and $_.CommandLine -like "*api.py*" } | Stop-Process -Force -ErrorAction SilentlyContinue
230
- Get-Process | Where-Object { $_.ProcessName -eq "python" -and $_.CommandLine -like "*http.server*" } | Stop-Process -Force -ErrorAction SilentlyContinue
231
-
232
- Write-Success "Services cleanup completed"
233
- }
234
- }
235
-
236
- function Invoke-Tests {
237
- Write-Status "Running end-to-end tests..."
238
-
239
- # Prepare test command
240
- $testArgs = @("test_end_to_end.py", "--mode", $Mode)
241
-
242
- if ($Verbose) {
243
- $testArgs += "--verbose"
244
- }
245
-
246
- if ($OutputFile) {
247
- $testArgs += @("--output", "test_results\$OutputFile")
248
- }
249
-
250
- Write-Status "Executing: python $($testArgs -join ' ')"
251
-
252
- # Run tests with timeout
253
- try {
254
- $job = Start-Job -ScriptBlock {
255
- param($args)
256
- Set-Location $using:PWD
257
- $env:MODE = $using:Mode
258
- $env:PYTHONPATH = $using:env:PYTHONPATH
259
- $env:SELENIUM_HEADLESS = $using:env:SELENIUM_HEADLESS
260
- & python @args
261
- } -ArgumentList $testArgs
262
-
263
- $completed = Wait-Job -Job $job -Timeout $Timeout
264
-
265
- if ($completed) {
266
- $result = Receive-Job -Job $job
267
- $exitCode = $job.State -eq "Completed" ? 0 : 1
268
- Remove-Job -Job $job
269
-
270
- if ($exitCode -eq 0) {
271
- Write-Success "All tests completed successfully"
272
- return 0
273
- }
274
- else {
275
- Write-Error "Tests failed"
276
- return 1
277
- }
278
- }
279
- else {
280
- Stop-Job -Job $job
281
- Remove-Job -Job $job
282
- Write-Error "Tests timed out after $Timeout seconds"
283
- return 124
284
- }
285
- }
286
- catch {
287
- Write-Error "Failed to run tests: $_"
288
- return 1
289
- }
290
- }
291
-
292
- function Remove-TestData {
293
- if (-not $NoCleanup) {
294
- Write-Status "Cleaning up test data..."
295
-
296
- # Remove test database if it exists
297
- if (Test-Path "..\..\data\test_heatmap.db") {
298
- Remove-Item "..\..\data\test_heatmap.db" -Force
299
- }
300
-
301
- # Clean up any temporary files
302
- Get-ChildItem -Path "test_data" -Filter "temp_*" -Recurse | Remove-Item -Force -Recurse
303
-
304
- Write-Success "Test data cleanup completed"
305
- }
306
- else {
307
- Write-Status "Skipping test data cleanup (-NoCleanup specified)"
308
- }
309
- }
310
-
311
- function New-Report {
312
- Write-Status "Generating test report..."
313
-
314
- if ($OutputFile -and (Test-Path "test_results\$OutputFile")) {
315
- # Generate HTML report from JSON results
316
- $pythonScript = @"
317
- import json
318
- import sys
319
- from datetime import datetime
320
-
321
- try:
322
- with open('test_results/$OutputFile', 'r') as f:
323
- results = json.load(f)
324
-
325
- html_report = '''
326
- <!DOCTYPE html>
327
- <html>
328
- <head>
329
- <title>E2E Test Results</title>
330
- <style>
331
- body { font-family: Arial, sans-serif; margin: 20px; }
332
- .header { background: #f8f9fa; padding: 20px; border-radius: 5px; }
333
- .summary { display: flex; gap: 20px; margin: 20px 0; }
334
- .metric { background: #e9ecef; padding: 15px; border-radius: 5px; text-align: center; }
335
- .test { margin: 10px 0; padding: 15px; border-radius: 5px; }
336
- .passed { background: #d4edda; border-left: 5px solid #28a745; }
337
- .failed { background: #f8d7da; border-left: 5px solid #dc3545; }
338
- .skipped { background: #fff3cd; border-left: 5px solid #ffc107; }
339
- </style>
340
- </head>
341
- <body>
342
- <div class="header">
343
- <h1>End-to-End Test Results</h1>
344
- <p>Mode: {mode} | Generated: {timestamp}</p>
345
- </div>
346
-
347
- <div class="summary">
348
- <div class="metric">
349
- <h3>{total}</h3>
350
- <p>Total Tests</p>
351
- </div>
352
- <div class="metric">
353
- <h3>{passed}</h3>
354
- <p>Passed</p>
355
- </div>
356
- <div class="metric">
357
- <h3>{failed}</h3>
358
- <p>Failed</p>
359
- </div>
360
- <div class="metric">
361
- <h3>{success_rate:.1f}%</h3>
362
- <p>Success Rate</p>
363
- </div>
364
- </div>
365
-
366
- <h2>Test Details</h2>
367
- '''.format(
368
- mode=results['mode'].upper(),
369
- timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
370
- total=results['summary']['total'],
371
- passed=results['summary']['passed'],
372
- failed=results['summary']['failed'],
373
- success_rate=results['success_rate']
374
- )
375
-
376
- for test in results['tests']:
377
- status_class = test['status']
378
- html_report += f'''
379
- <div class="test {status_class}">
380
- <h3>{test['name']} - {test['status'].upper()}</h3>
381
- <p>{test['message']}</p>
382
- <small>Duration: {test['duration']:.2f}s | Time: {test['timestamp']}</small>
383
- </div>
384
- '''
385
-
386
- html_report += '''
387
- </body>
388
- </html>
389
- '''
390
-
391
- with open('test_results/report.html', 'w') as f:
392
- f.write(html_report)
393
-
394
- print('HTML report generated: test_results/report.html')
395
-
396
- except Exception as e:
397
- print(f'Failed to generate HTML report: {e}')
398
- "@
399
-
400
- python -c $pythonScript
401
- Write-Success "Test report generated: test_results\report.html"
402
- }
403
- }
404
-
405
- # Main execution
406
- function Main {
407
- if ($Help) {
408
- Show-Usage
409
- exit 0
410
- }
411
-
412
- Write-Header "End-to-End Test Runner - Misinformation Heatmap"
413
-
414
- Test-Prerequisites
415
- Initialize-TestEnvironment
416
-
417
- try {
418
- Start-Services
419
-
420
- $testExitCode = Invoke-Tests
421
-
422
- if ($testExitCode -eq 0) {
423
- Write-Success "All tests passed!"
424
- }
425
- else {
426
- Write-Error "Some tests failed!"
427
- }
428
-
429
- Remove-TestData
430
- New-Report
431
-
432
- Write-Header "Test Run Complete"
433
-
434
- exit $testExitCode
435
- }
436
- finally {
437
- Stop-Services
438
- }
439
- }
440
-
441
- # Run main function
442
- Main
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/e2e/run_e2e_tests.sh DELETED
@@ -1,388 +0,0 @@
1
- #!/bin/bash
2
-
3
- # End-to-End Test Runner Script
4
- # Runs comprehensive end-to-end tests for the misinformation heatmap system
5
-
6
- set -e
7
-
8
- # Colors for output
9
- RED='\033[0;31m'
10
- GREEN='\033[0;32m'
11
- YELLOW='\033[1;33m'
12
- BLUE='\033[0;34m'
13
- PURPLE='\033[0;35m'
14
- NC='\033[0m' # No Color
15
-
16
- print_header() {
17
- echo -e "${PURPLE}================================${NC}"
18
- echo -e "${PURPLE}$1${NC}"
19
- echo -e "${PURPLE}================================${NC}"
20
- }
21
-
22
- print_status() {
23
- echo -e "${BLUE}[INFO]${NC} $1"
24
- }
25
-
26
- print_success() {
27
- echo -e "${GREEN}[SUCCESS]${NC} $1"
28
- }
29
-
30
- print_warning() {
31
- echo -e "${YELLOW}[WARNING]${NC} $1"
32
- }
33
-
34
- print_error() {
35
- echo -e "${RED}[ERROR]${NC} $1"
36
- }
37
-
38
- # Configuration
39
- MODE="local"
40
- VERBOSE=false
41
- OUTPUT_FILE=""
42
- CLEANUP=true
43
- HEADLESS=true
44
- TIMEOUT=300
45
-
46
- show_usage() {
47
- echo "Usage: $0 [OPTIONS]"
48
- echo ""
49
- echo "Options:"
50
- echo " -h, --help Show this help message"
51
- echo " -m, --mode MODE Testing mode: local or cloud (default: local)"
52
- echo " -o, --output FILE Output file for test results (JSON)"
53
- echo " -v, --verbose Enable verbose output"
54
- echo " --no-cleanup Don't cleanup test data after tests"
55
- echo " --no-headless Run browser tests in visible mode"
56
- echo " --timeout SECONDS Test timeout in seconds (default: 300)"
57
- echo ""
58
- echo "Examples:"
59
- echo " $0 --mode local --verbose"
60
- echo " $0 --mode cloud --output results.json"
61
- echo " $0 --no-headless --timeout 600"
62
- }
63
-
64
- parse_args() {
65
- while [[ $# -gt 0 ]]; do
66
- case $1 in
67
- -h|--help)
68
- show_usage
69
- exit 0
70
- ;;
71
- -m|--mode)
72
- MODE="$2"
73
- shift 2
74
- ;;
75
- -o|--output)
76
- OUTPUT_FILE="$2"
77
- shift 2
78
- ;;
79
- -v|--verbose)
80
- VERBOSE=true
81
- shift
82
- ;;
83
- --no-cleanup)
84
- CLEANUP=false
85
- shift
86
- ;;
87
- --no-headless)
88
- HEADLESS=false
89
- shift
90
- ;;
91
- --timeout)
92
- TIMEOUT="$2"
93
- shift 2
94
- ;;
95
- *)
96
- print_error "Unknown option: $1"
97
- show_usage
98
- exit 1
99
- ;;
100
- esac
101
- done
102
- }
103
-
104
- check_prerequisites() {
105
- print_status "Checking prerequisites..."
106
-
107
- # Check Python
108
- if ! command -v python3 &> /dev/null; then
109
- print_error "Python 3 is not installed."
110
- exit 1
111
- fi
112
-
113
- # Check if we're in the right directory
114
- if [[ ! -f "../../backend/api.py" ]]; then
115
- print_error "Please run this script from the tests/e2e directory."
116
- exit 1
117
- fi
118
-
119
- # Install Python dependencies
120
- print_status "Installing Python dependencies..."
121
- pip3 install -r requirements.txt > /dev/null 2>&1 || {
122
- print_error "Failed to install Python dependencies."
123
- exit 1
124
- }
125
-
126
- # Check Chrome/Chromium for Selenium
127
- if command -v google-chrome &> /dev/null || command -v chromium-browser &> /dev/null; then
128
- print_status "Chrome/Chromium found for browser testing"
129
- else
130
- print_warning "Chrome/Chromium not found. Browser tests will be skipped."
131
- fi
132
-
133
- print_success "Prerequisites check completed"
134
- }
135
-
136
- setup_test_environment() {
137
- print_status "Setting up test environment..."
138
-
139
- # Set environment variables
140
- export MODE="$MODE"
141
- export PYTHONPATH="../../backend:$PYTHONPATH"
142
-
143
- if [[ "$HEADLESS" == "false" ]]; then
144
- export SELENIUM_HEADLESS="false"
145
- else
146
- export SELENIUM_HEADLESS="true"
147
- fi
148
-
149
- # Create test data directory
150
- mkdir -p test_data
151
- mkdir -p test_results
152
-
153
- print_success "Test environment setup completed"
154
- }
155
-
156
- start_services() {
157
- print_status "Starting services for testing..."
158
-
159
- if [[ "$MODE" == "local" ]]; then
160
- # Start local services
161
- print_status "Starting local backend service..."
162
-
163
- cd ../../
164
-
165
- # Start backend in background
166
- python3 backend/api.py &
167
- BACKEND_PID=$!
168
-
169
- # Start frontend in background
170
- cd frontend
171
- python3 -m http.server 3000 &
172
- FRONTEND_PID=$!
173
-
174
- cd ../tests/e2e
175
-
176
- # Wait for services to start
177
- print_status "Waiting for services to start..."
178
- sleep 10
179
-
180
- # Check if services are running
181
- if ! curl -s http://localhost:8000/health > /dev/null; then
182
- print_error "Backend service failed to start"
183
- cleanup_services
184
- exit 1
185
- fi
186
-
187
- if ! curl -s http://localhost:3000 > /dev/null; then
188
- print_error "Frontend service failed to start"
189
- cleanup_services
190
- exit 1
191
- fi
192
-
193
- print_success "Local services started successfully"
194
-
195
- else
196
- print_status "Using cloud services (assuming they are already running)"
197
- fi
198
- }
199
-
200
- cleanup_services() {
201
- if [[ "$MODE" == "local" ]]; then
202
- print_status "Cleaning up local services..."
203
-
204
- if [[ -n "$BACKEND_PID" ]]; then
205
- kill $BACKEND_PID 2>/dev/null || true
206
- fi
207
-
208
- if [[ -n "$FRONTEND_PID" ]]; then
209
- kill $FRONTEND_PID 2>/dev/null || true
210
- fi
211
-
212
- # Kill any remaining processes
213
- pkill -f "python3 backend/api.py" 2>/dev/null || true
214
- pkill -f "python3 -m http.server 3000" 2>/dev/null || true
215
-
216
- print_success "Services cleanup completed"
217
- fi
218
- }
219
-
220
- run_tests() {
221
- print_status "Running end-to-end tests..."
222
-
223
- # Prepare test command
224
- TEST_CMD="python3 test_end_to_end.py --mode $MODE"
225
-
226
- if [[ "$VERBOSE" == "true" ]]; then
227
- TEST_CMD="$TEST_CMD --verbose"
228
- fi
229
-
230
- if [[ -n "$OUTPUT_FILE" ]]; then
231
- TEST_CMD="$TEST_CMD --output test_results/$OUTPUT_FILE"
232
- fi
233
-
234
- # Run tests with timeout
235
- print_status "Executing: $TEST_CMD"
236
-
237
- if timeout $TIMEOUT $TEST_CMD; then
238
- print_success "All tests completed successfully"
239
- return 0
240
- else
241
- EXIT_CODE=$?
242
- if [[ $EXIT_CODE -eq 124 ]]; then
243
- print_error "Tests timed out after $TIMEOUT seconds"
244
- else
245
- print_error "Tests failed with exit code $EXIT_CODE"
246
- fi
247
- return $EXIT_CODE
248
- fi
249
- }
250
-
251
- cleanup_test_data() {
252
- if [[ "$CLEANUP" == "true" ]]; then
253
- print_status "Cleaning up test data..."
254
-
255
- # Remove test database if it exists
256
- rm -f ../../data/test_heatmap.db
257
-
258
- # Clean up any temporary files
259
- rm -rf test_data/temp_*
260
-
261
- print_success "Test data cleanup completed"
262
- else
263
- print_status "Skipping test data cleanup (--no-cleanup specified)"
264
- fi
265
- }
266
-
267
- generate_report() {
268
- print_status "Generating test report..."
269
-
270
- if [[ -n "$OUTPUT_FILE" && -f "test_results/$OUTPUT_FILE" ]]; then
271
- # Generate HTML report from JSON results
272
- python3 -c "
273
- import json
274
- import sys
275
- from datetime import datetime
276
-
277
- try:
278
- with open('test_results/$OUTPUT_FILE', 'r') as f:
279
- results = json.load(f)
280
-
281
- html_report = '''
282
- <!DOCTYPE html>
283
- <html>
284
- <head>
285
- <title>E2E Test Results</title>
286
- <style>
287
- body { font-family: Arial, sans-serif; margin: 20px; }
288
- .header { background: #f8f9fa; padding: 20px; border-radius: 5px; }
289
- .summary { display: flex; gap: 20px; margin: 20px 0; }
290
- .metric { background: #e9ecef; padding: 15px; border-radius: 5px; text-align: center; }
291
- .test { margin: 10px 0; padding: 15px; border-radius: 5px; }
292
- .passed { background: #d4edda; border-left: 5px solid #28a745; }
293
- .failed { background: #f8d7da; border-left: 5px solid #dc3545; }
294
- .skipped { background: #fff3cd; border-left: 5px solid #ffc107; }
295
- </style>
296
- </head>
297
- <body>
298
- <div class=\"header\">
299
- <h1>End-to-End Test Results</h1>
300
- <p>Mode: {mode} | Generated: {timestamp}</p>
301
- </div>
302
-
303
- <div class=\"summary\">
304
- <div class=\"metric\">
305
- <h3>{total}</h3>
306
- <p>Total Tests</p>
307
- </div>
308
- <div class=\"metric\">
309
- <h3>{passed}</h3>
310
- <p>Passed</p>
311
- </div>
312
- <div class=\"metric\">
313
- <h3>{failed}</h3>
314
- <p>Failed</p>
315
- </div>
316
- <div class=\"metric\">
317
- <h3>{success_rate:.1f}%</h3>
318
- <p>Success Rate</p>
319
- </div>
320
- </div>
321
-
322
- <h2>Test Details</h2>
323
- '''.format(
324
- mode=results['mode'].upper(),
325
- timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
326
- total=results['summary']['total'],
327
- passed=results['summary']['passed'],
328
- failed=results['summary']['failed'],
329
- success_rate=results['success_rate']
330
- )
331
-
332
- for test in results['tests']:
333
- status_class = test['status']
334
- html_report += f'''
335
- <div class=\"test {status_class}\">
336
- <h3>{test['name']} - {test['status'].upper()}</h3>
337
- <p>{test['message']}</p>
338
- <small>Duration: {test['duration']:.2f}s | Time: {test['timestamp']}</small>
339
- </div>
340
- '''
341
-
342
- html_report += '''
343
- </body>
344
- </html>
345
- '''
346
-
347
- with open('test_results/report.html', 'w') as f:
348
- f.write(html_report)
349
-
350
- print('HTML report generated: test_results/report.html')
351
-
352
- except Exception as e:
353
- print(f'Failed to generate HTML report: {e}')
354
- "
355
-
356
- print_success "Test report generated: test_results/report.html"
357
- fi
358
- }
359
-
360
- main() {
361
- print_header "End-to-End Test Runner - Misinformation Heatmap"
362
-
363
- parse_args "$@"
364
- check_prerequisites
365
- setup_test_environment
366
-
367
- # Trap to ensure cleanup on exit
368
- trap cleanup_services EXIT
369
-
370
- start_services
371
-
372
- if run_tests; then
373
- print_success "All tests passed!"
374
- TEST_EXIT_CODE=0
375
- else
376
- print_error "Some tests failed!"
377
- TEST_EXIT_CODE=1
378
- fi
379
-
380
- cleanup_test_data
381
- generate_report
382
-
383
- print_header "Test Run Complete"
384
-
385
- exit $TEST_EXIT_CODE
386
- }
387
-
388
- main "$@"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/e2e/test_end_to_end.py DELETED
@@ -1,720 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- End-to-end testing pipeline for the Real-Time Misinformation Heatmap system.
4
- Tests the complete flow from data ingestion to visualization.
5
- """
6
-
7
- import asyncio
8
- import json
9
- import logging
10
- import os
11
- import sys
12
- import time
13
- import unittest
14
- from datetime import datetime, timedelta
15
- from typing import Dict, List, Optional, Tuple
16
- from unittest.mock import patch
17
-
18
- import aiohttp
19
- import pytest
20
- import requests
21
- from selenium import webdriver
22
- from selenium.webdriver.chrome.options import Options
23
- from selenium.webdriver.common.by import By
24
- from selenium.webdriver.support import expected_conditions as EC
25
- from selenium.webdriver.support.ui import WebDriverWait
26
-
27
- # Add backend to path for imports
28
- sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..', 'backend'))
29
-
30
- from api import app
31
- from config import Config
32
- from database import Database
33
- from nlp_analyzer import NLPAnalyzer
34
- from satellite_client import SatelliteClient
35
-
36
- # Configure logging
37
- logging.basicConfig(
38
- level=logging.INFO,
39
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
40
- )
41
- logger = logging.getLogger(__name__)
42
-
43
-
44
- class EndToEndTestSuite:
45
- """Comprehensive end-to-end test suite for the misinformation heatmap system."""
46
-
47
- def __init__(self, mode: str = 'local'):
48
- """Initialize the test suite.
49
-
50
- Args:
51
- mode: Testing mode ('local' or 'cloud')
52
- """
53
- self.mode = mode
54
- self.config = Config(mode=mode)
55
- self.base_url = f"http://localhost:{self.config.api_port}"
56
- self.frontend_url = f"http://localhost:3000"
57
- self.driver = None
58
- self.test_results = []
59
-
60
- # Test data
61
- self.test_events = [
62
- {
63
- "text": "Breaking: Major infrastructure collapse reported in Maharashtra with satellite imagery showing significant damage",
64
- "source": "test_news",
65
- "location": "Maharashtra",
66
- "category": "infrastructure"
67
- },
68
- {
69
- "text": "Fake news alert: False claims about Karnataka government policies spreading on social media",
70
- "source": "test_social",
71
- "location": "Karnataka",
72
- "category": "politics"
73
- },
74
- {
75
- "text": "Health misinformation: Unverified medical claims circulating in Tamil Nadu communities",
76
- "source": "test_health",
77
- "location": "Tamil Nadu",
78
- "category": "health"
79
- }
80
- ]
81
-
82
- def setup_webdriver(self) -> None:
83
- """Setup Selenium WebDriver for frontend testing."""
84
- try:
85
- chrome_options = Options()
86
- chrome_options.add_argument('--headless')
87
- chrome_options.add_argument('--no-sandbox')
88
- chrome_options.add_argument('--disable-dev-shm-usage')
89
- chrome_options.add_argument('--disable-gpu')
90
- chrome_options.add_argument('--window-size=1920,1080')
91
-
92
- self.driver = webdriver.Chrome(options=chrome_options)
93
- self.driver.implicitly_wait(10)
94
- logger.info("WebDriver setup completed")
95
- except Exception as e:
96
- logger.error(f"Failed to setup WebDriver: {e}")
97
- raise
98
-
99
- def teardown_webdriver(self) -> None:
100
- """Cleanup WebDriver."""
101
- if self.driver:
102
- self.driver.quit()
103
- logger.info("WebDriver cleanup completed")
104
-
105
- def wait_for_service(self, url: str, timeout: int = 60) -> bool:
106
- """Wait for a service to become available.
107
-
108
- Args:
109
- url: Service URL to check
110
- timeout: Maximum wait time in seconds
111
-
112
- Returns:
113
- True if service is available, False otherwise
114
- """
115
- start_time = time.time()
116
- while time.time() - start_time < timeout:
117
- try:
118
- response = requests.get(f"{url}/health", timeout=5)
119
- if response.status_code == 200:
120
- logger.info(f"Service at {url} is ready")
121
- return True
122
- except requests.exceptions.RequestException:
123
- pass
124
- time.sleep(2)
125
-
126
- logger.error(f"Service at {url} not ready after {timeout} seconds")
127
- return False
128
-
129
- def test_api_health(self) -> Tuple[bool, str]:
130
- """Test API health endpoint."""
131
- try:
132
- response = requests.get(f"{self.base_url}/health", timeout=10)
133
-
134
- if response.status_code != 200:
135
- return False, f"Health check failed with status {response.status_code}"
136
-
137
- health_data = response.json()
138
- required_fields = ['status', 'timestamp', 'dependencies']
139
-
140
- for field in required_fields:
141
- if field not in health_data:
142
- return False, f"Missing required field: {field}"
143
-
144
- if health_data['status'] != 'healthy':
145
- return False, f"Service status is {health_data['status']}"
146
-
147
- logger.info("API health check passed")
148
- return True, "API health check successful"
149
-
150
- except Exception as e:
151
- return False, f"API health check failed: {str(e)}"
152
-
153
- def test_data_ingestion(self) -> Tuple[bool, str]:
154
- """Test data ingestion pipeline."""
155
- try:
156
- ingested_events = []
157
-
158
- for event_data in self.test_events:
159
- response = requests.post(
160
- f"{self.base_url}/ingest/test",
161
- json=event_data,
162
- timeout=30
163
- )
164
-
165
- if response.status_code != 201:
166
- return False, f"Ingestion failed for event: {event_data['text'][:50]}..."
167
-
168
- result = response.json()
169
- required_fields = ['event_id', 'status', 'processing_results']
170
-
171
- for field in required_fields:
172
- if field not in result:
173
- return False, f"Missing field in ingestion response: {field}"
174
-
175
- if result['status'] != 'processed':
176
- return False, f"Event processing failed: {result.get('status')}"
177
-
178
- ingested_events.append(result)
179
- logger.info(f"Successfully ingested event: {result['event_id']}")
180
-
181
- # Wait for processing to complete
182
- time.sleep(5)
183
-
184
- logger.info(f"Data ingestion test passed: {len(ingested_events)} events processed")
185
- return True, f"Successfully ingested {len(ingested_events)} test events"
186
-
187
- except Exception as e:
188
- return False, f"Data ingestion test failed: {str(e)}"
189
-
190
- def test_nlp_processing(self) -> Tuple[bool, str]:
191
- """Test NLP processing pipeline."""
192
- try:
193
- # Test with a sample event
194
- test_text = "Breaking news about infrastructure development in Karnataka with satellite validation"
195
-
196
- response = requests.post(
197
- f"{self.base_url}/ingest/test",
198
- json={
199
- "text": test_text,
200
- "source": "test_nlp",
201
- "location": "Karnataka",
202
- "category": "infrastructure"
203
- },
204
- timeout=30
205
- )
206
-
207
- if response.status_code != 201:
208
- return False, f"NLP test ingestion failed with status {response.status_code}"
209
-
210
- result = response.json()
211
- processing_results = result.get('processing_results', {})
212
-
213
- # Check NLP processing results
214
- required_nlp_fields = [
215
- 'language_detected',
216
- 'region_extracted',
217
- 'entities_found',
218
- 'claims_extracted',
219
- 'virality_score',
220
- 'reality_score'
221
- ]
222
-
223
- for field in required_nlp_fields:
224
- if field not in processing_results:
225
- return False, f"Missing NLP processing field: {field}"
226
-
227
- # Validate processing results
228
- if processing_results['language_detected'] not in ['en', 'hi', 'bn', 'te', 'ta', 'mr', 'gu']:
229
- return False, f"Invalid language detected: {processing_results['language_detected']}"
230
-
231
- if processing_results['region_extracted'] != 'Karnataka':
232
- return False, f"Incorrect region extracted: {processing_results['region_extracted']}"
233
-
234
- if not (0 <= processing_results['virality_score'] <= 1):
235
- return False, f"Invalid virality score: {processing_results['virality_score']}"
236
-
237
- if not (0 <= processing_results['reality_score'] <= 1):
238
- return False, f"Invalid reality score: {processing_results['reality_score']}"
239
-
240
- logger.info("NLP processing test passed")
241
- return True, "NLP processing pipeline working correctly"
242
-
243
- except Exception as e:
244
- return False, f"NLP processing test failed: {str(e)}"
245
-
246
- def test_satellite_validation(self) -> Tuple[bool, str]:
247
- """Test satellite validation system."""
248
- try:
249
- # Test with an event that should trigger satellite validation
250
- test_text = "Satellite imagery shows major changes in infrastructure development in Gujarat region"
251
-
252
- response = requests.post(
253
- f"{self.base_url}/ingest/test",
254
- json={
255
- "text": test_text,
256
- "source": "test_satellite",
257
- "location": "Gujarat",
258
- "category": "infrastructure"
259
- },
260
- timeout=30
261
- )
262
-
263
- if response.status_code != 201:
264
- return False, f"Satellite test ingestion failed with status {response.status_code}"
265
-
266
- result = response.json()
267
- processing_results = result.get('processing_results', {})
268
-
269
- # Check if satellite validation was performed
270
- if 'satellite_validated' not in processing_results:
271
- return False, "Satellite validation field missing from results"
272
-
273
- if not isinstance(processing_results['satellite_validated'], bool):
274
- return False, f"Invalid satellite validation result: {processing_results['satellite_validated']}"
275
-
276
- logger.info("Satellite validation test passed")
277
- return True, "Satellite validation system working correctly"
278
-
279
- except Exception as e:
280
- return False, f"Satellite validation test failed: {str(e)}"
281
-
282
- def test_heatmap_api(self) -> Tuple[bool, str]:
283
- """Test heatmap data API."""
284
- try:
285
- # Wait for data to be processed
286
- time.sleep(3)
287
-
288
- response = requests.get(f"{self.base_url}/heatmap?hours_back=24", timeout=15)
289
-
290
- if response.status_code != 200:
291
- return False, f"Heatmap API failed with status {response.status_code}"
292
-
293
- heatmap_data = response.json()
294
- required_fields = ['states', 'total_events', 'last_updated', 'metadata']
295
-
296
- for field in required_fields:
297
- if field not in heatmap_data:
298
- return False, f"Missing heatmap field: {field}"
299
-
300
- # Check if we have state data
301
- states = heatmap_data['states']
302
- if not isinstance(states, dict):
303
- return False, "States data should be a dictionary"
304
-
305
- # Validate state data structure
306
- for state_name, state_data in states.items():
307
- required_state_fields = [
308
- 'event_count', 'intensity', 'avg_virality_score',
309
- 'avg_reality_score', 'misinformation_risk', 'last_updated'
310
- ]
311
-
312
- for field in required_state_fields:
313
- if field not in state_data:
314
- return False, f"Missing state field {field} for {state_name}"
315
-
316
- # Validate numeric ranges
317
- if not (0 <= state_data['intensity'] <= 1):
318
- return False, f"Invalid intensity for {state_name}: {state_data['intensity']}"
319
-
320
- if not (0 <= state_data['misinformation_risk'] <= 1):
321
- return False, f"Invalid risk for {state_name}: {state_data['misinformation_risk']}"
322
-
323
- logger.info(f"Heatmap API test passed: {len(states)} states with data")
324
- return True, f"Heatmap API working correctly with {len(states)} states"
325
-
326
- except Exception as e:
327
- return False, f"Heatmap API test failed: {str(e)}"
328
-
329
- def test_region_api(self) -> Tuple[bool, str]:
330
- """Test region details API."""
331
- try:
332
- # Test with Maharashtra (should have data from our test events)
333
- response = requests.get(
334
- f"{self.base_url}/region/Maharashtra?hours_back=24&limit=10",
335
- timeout=15
336
- )
337
-
338
- if response.status_code != 200:
339
- return False, f"Region API failed with status {response.status_code}"
340
-
341
- region_data = response.json()
342
- required_fields = ['state_name', 'summary', 'events', 'last_updated']
343
-
344
- for field in required_fields:
345
- if field not in region_data:
346
- return False, f"Missing region field: {field}"
347
-
348
- if region_data['state_name'] != 'Maharashtra':
349
- return False, f"Incorrect state name: {region_data['state_name']}"
350
-
351
- # Check summary data
352
- summary = region_data['summary']
353
- required_summary_fields = [
354
- 'event_count', 'misinformation_risk', 'avg_virality_score', 'avg_reality_score'
355
- ]
356
-
357
- for field in required_summary_fields:
358
- if field not in summary:
359
- return False, f"Missing summary field: {field}"
360
-
361
- # Check events structure
362
- events = region_data['events']
363
- if not isinstance(events, list):
364
- return False, "Events should be a list"
365
-
366
- logger.info(f"Region API test passed: {summary['event_count']} events for Maharashtra")
367
- return True, f"Region API working correctly with {summary['event_count']} events"
368
-
369
- except Exception as e:
370
- return False, f"Region API test failed: {str(e)}"
371
-
372
- def test_frontend_loading(self) -> Tuple[bool, str]:
373
- """Test frontend application loading."""
374
- try:
375
- if not self.driver:
376
- return False, "WebDriver not initialized"
377
-
378
- self.driver.get(self.frontend_url)
379
-
380
- # Wait for page to load
381
- WebDriverWait(self.driver, 20).until(
382
- EC.presence_of_element_located((By.TAG_NAME, "body"))
383
- )
384
-
385
- # Check for essential elements
386
- title_element = WebDriverWait(self.driver, 10).until(
387
- EC.presence_of_element_located((By.CLASS_NAME, "title-main"))
388
- )
389
-
390
- if "Misinformation Heatmap" not in title_element.text:
391
- return False, f"Incorrect page title: {title_element.text}"
392
-
393
- # Check for map container
394
- map_container = WebDriverWait(self.driver, 10).until(
395
- EC.presence_of_element_located((By.CLASS_NAME, "map-container"))
396
- )
397
-
398
- if not map_container.is_displayed():
399
- return False, "Map container not visible"
400
-
401
- # Check for control panel
402
- control_panel = WebDriverWait(self.driver, 10).until(
403
- EC.presence_of_element_located((By.CLASS_NAME, "control-panel"))
404
- )
405
-
406
- if not control_panel.is_displayed():
407
- return False, "Control panel not visible"
408
-
409
- logger.info("Frontend loading test passed")
410
- return True, "Frontend application loaded successfully"
411
-
412
- except Exception as e:
413
- return False, f"Frontend loading test failed: {str(e)}"
414
-
415
- def test_map_interaction(self) -> Tuple[bool, str]:
416
- """Test map interaction functionality."""
417
- try:
418
- if not self.driver:
419
- return False, "WebDriver not initialized"
420
-
421
- # Wait for map to initialize
422
- time.sleep(5)
423
-
424
- # Check for Leaflet map
425
- map_element = WebDriverWait(self.driver, 15).until(
426
- EC.presence_of_element_located((By.CLASS_NAME, "leaflet-container"))
427
- )
428
-
429
- if not map_element.is_displayed():
430
- return False, "Leaflet map not visible"
431
-
432
- # Check for zoom controls
433
- zoom_controls = self.driver.find_elements(By.CLASS_NAME, "leaflet-control-zoom")
434
- if not zoom_controls:
435
- return False, "Zoom controls not found"
436
-
437
- # Check for attribution
438
- attribution = self.driver.find_elements(By.CLASS_NAME, "leaflet-control-attribution")
439
- if not attribution:
440
- return False, "Map attribution not found"
441
-
442
- # Try to find state layers (they should be loaded)
443
- time.sleep(3)
444
- svg_elements = self.driver.find_elements(By.TAG_NAME, "svg")
445
- if not svg_elements:
446
- return False, "No SVG elements found (state boundaries may not be loaded)"
447
-
448
- logger.info("Map interaction test passed")
449
- return True, "Map interaction functionality working correctly"
450
-
451
- except Exception as e:
452
- return False, f"Map interaction test failed: {str(e)}"
453
-
454
- def test_real_time_updates(self) -> Tuple[bool, str]:
455
- """Test real-time data updates."""
456
- try:
457
- if not self.driver:
458
- return False, "WebDriver not initialized"
459
-
460
- # Get initial status
461
- status_element = WebDriverWait(self.driver, 10).until(
462
- EC.presence_of_element_located((By.CLASS_NAME, "status-indicator"))
463
- )
464
-
465
- initial_text = status_element.text
466
-
467
- # Inject a new test event
468
- new_event = {
469
- "text": "Real-time test: New misinformation event detected in Rajasthan",
470
- "source": "test_realtime",
471
- "location": "Rajasthan",
472
- "category": "test"
473
- }
474
-
475
- response = requests.post(
476
- f"{self.base_url}/ingest/test",
477
- json=new_event,
478
- timeout=15
479
- )
480
-
481
- if response.status_code != 201:
482
- return False, f"Real-time test event ingestion failed: {response.status_code}"
483
-
484
- # Wait for potential UI update (the frontend polls every 30 seconds)
485
- # We'll wait a shorter time and check if the status changed
486
- time.sleep(10)
487
-
488
- # Check if status indicator shows activity
489
- current_status = status_element.text
490
-
491
- # The test passes if the system is responsive (even if UI hasn't updated yet)
492
- logger.info("Real-time updates test passed")
493
- return True, "Real-time update system is responsive"
494
-
495
- except Exception as e:
496
- return False, f"Real-time updates test failed: {str(e)}"
497
-
498
- def test_error_handling(self) -> Tuple[bool, str]:
499
- """Test error handling and recovery."""
500
- try:
501
- # Test invalid API endpoint
502
- response = requests.get(f"{self.base_url}/invalid-endpoint", timeout=10)
503
- if response.status_code != 404:
504
- return False, f"Expected 404 for invalid endpoint, got {response.status_code}"
505
-
506
- # Test invalid data ingestion
507
- response = requests.post(
508
- f"{self.base_url}/ingest/test",
509
- json={"invalid": "data"},
510
- timeout=10
511
- )
512
- if response.status_code not in [400, 422]:
513
- return False, f"Expected 400/422 for invalid data, got {response.status_code}"
514
-
515
- # Test invalid region
516
- response = requests.get(f"{self.base_url}/region/InvalidState", timeout=10)
517
- if response.status_code != 404:
518
- return False, f"Expected 404 for invalid state, got {response.status_code}"
519
-
520
- logger.info("Error handling test passed")
521
- return True, "Error handling working correctly"
522
-
523
- except Exception as e:
524
- return False, f"Error handling test failed: {str(e)}"
525
-
526
- def test_performance(self) -> Tuple[bool, str]:
527
- """Test system performance under load."""
528
- try:
529
- # Test API response times
530
- start_time = time.time()
531
- response = requests.get(f"{self.base_url}/heatmap", timeout=10)
532
- heatmap_time = time.time() - start_time
533
-
534
- if response.status_code != 200:
535
- return False, f"Heatmap request failed: {response.status_code}"
536
-
537
- if heatmap_time > 5.0:
538
- return False, f"Heatmap response too slow: {heatmap_time:.2f}s"
539
-
540
- # Test multiple concurrent requests
541
- import concurrent.futures
542
-
543
- def make_request():
544
- return requests.get(f"{self.base_url}/health", timeout=5)
545
-
546
- start_time = time.time()
547
- with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
548
- futures = [executor.submit(make_request) for _ in range(10)]
549
- results = [future.result() for future in concurrent.futures.as_completed(futures)]
550
-
551
- concurrent_time = time.time() - start_time
552
-
553
- # Check all requests succeeded
554
- for result in results:
555
- if result.status_code != 200:
556
- return False, f"Concurrent request failed: {result.status_code}"
557
-
558
- if concurrent_time > 10.0:
559
- return False, f"Concurrent requests too slow: {concurrent_time:.2f}s"
560
-
561
- logger.info(f"Performance test passed: heatmap={heatmap_time:.2f}s, concurrent={concurrent_time:.2f}s")
562
- return True, f"Performance acceptable (heatmap: {heatmap_time:.2f}s, concurrent: {concurrent_time:.2f}s)"
563
-
564
- except Exception as e:
565
- return False, f"Performance test failed: {str(e)}"
566
-
567
- def run_all_tests(self) -> Dict:
568
- """Run all end-to-end tests."""
569
- logger.info(f"Starting end-to-end test suite in {self.mode} mode")
570
-
571
- # Test definitions
572
- tests = [
573
- ("API Health Check", self.test_api_health),
574
- ("Data Ingestion Pipeline", self.test_data_ingestion),
575
- ("NLP Processing", self.test_nlp_processing),
576
- ("Satellite Validation", self.test_satellite_validation),
577
- ("Heatmap API", self.test_heatmap_api),
578
- ("Region API", self.test_region_api),
579
- ("Frontend Loading", self.test_frontend_loading),
580
- ("Map Interaction", self.test_map_interaction),
581
- ("Real-time Updates", self.test_real_time_updates),
582
- ("Error Handling", self.test_error_handling),
583
- ("Performance", self.test_performance)
584
- ]
585
-
586
- results = {
587
- 'mode': self.mode,
588
- 'start_time': datetime.now().isoformat(),
589
- 'tests': [],
590
- 'summary': {
591
- 'total': len(tests),
592
- 'passed': 0,
593
- 'failed': 0,
594
- 'skipped': 0
595
- }
596
- }
597
-
598
- try:
599
- # Wait for services to be ready
600
- if not self.wait_for_service(self.base_url):
601
- logger.error("Backend API not ready, aborting tests")
602
- return results
603
-
604
- # Setup WebDriver for frontend tests
605
- try:
606
- self.setup_webdriver()
607
- webdriver_available = True
608
- except Exception as e:
609
- logger.warning(f"WebDriver setup failed: {e}. Skipping frontend tests.")
610
- webdriver_available = False
611
-
612
- # Run tests
613
- for test_name, test_func in tests:
614
- logger.info(f"Running test: {test_name}")
615
-
616
- # Skip frontend tests if WebDriver not available
617
- if not webdriver_available and test_name in ["Frontend Loading", "Map Interaction", "Real-time Updates"]:
618
- test_result = {
619
- 'name': test_name,
620
- 'status': 'skipped',
621
- 'message': 'WebDriver not available',
622
- 'duration': 0,
623
- 'timestamp': datetime.now().isoformat()
624
- }
625
- results['summary']['skipped'] += 1
626
- else:
627
- start_time = time.time()
628
- try:
629
- success, message = test_func()
630
- duration = time.time() - start_time
631
-
632
- test_result = {
633
- 'name': test_name,
634
- 'status': 'passed' if success else 'failed',
635
- 'message': message,
636
- 'duration': duration,
637
- 'timestamp': datetime.now().isoformat()
638
- }
639
-
640
- if success:
641
- results['summary']['passed'] += 1
642
- logger.info(f"✓ {test_name}: {message}")
643
- else:
644
- results['summary']['failed'] += 1
645
- logger.error(f"✗ {test_name}: {message}")
646
-
647
- except Exception as e:
648
- duration = time.time() - start_time
649
- test_result = {
650
- 'name': test_name,
651
- 'status': 'failed',
652
- 'message': f"Test execution error: {str(e)}",
653
- 'duration': duration,
654
- 'timestamp': datetime.now().isoformat()
655
- }
656
- results['summary']['failed'] += 1
657
- logger.error(f"✗ {test_name}: Test execution error: {str(e)}")
658
-
659
- results['tests'].append(test_result)
660
-
661
- finally:
662
- # Cleanup
663
- self.teardown_webdriver()
664
-
665
- results['end_time'] = datetime.now().isoformat()
666
- results['success_rate'] = (results['summary']['passed'] / results['summary']['total']) * 100
667
-
668
- logger.info(f"Test suite completed: {results['summary']['passed']}/{results['summary']['total']} passed")
669
- return results
670
-
671
-
672
- def main():
673
- """Main function to run the end-to-end test suite."""
674
- import argparse
675
-
676
- parser = argparse.ArgumentParser(description='Run end-to-end tests for misinformation heatmap')
677
- parser.add_argument('--mode', choices=['local', 'cloud'], default='local',
678
- help='Testing mode (default: local)')
679
- parser.add_argument('--output', type=str, help='Output file for test results (JSON)')
680
- parser.add_argument('--verbose', action='store_true', help='Enable verbose logging')
681
-
682
- args = parser.parse_args()
683
-
684
- if args.verbose:
685
- logging.getLogger().setLevel(logging.DEBUG)
686
-
687
- # Run tests
688
- test_suite = EndToEndTestSuite(mode=args.mode)
689
- results = test_suite.run_all_tests()
690
-
691
- # Output results
692
- if args.output:
693
- with open(args.output, 'w') as f:
694
- json.dump(results, f, indent=2)
695
- print(f"Test results saved to {args.output}")
696
-
697
- # Print summary
698
- print(f"\n{'='*60}")
699
- print(f"END-TO-END TEST RESULTS ({args.mode.upper()} MODE)")
700
- print(f"{'='*60}")
701
- print(f"Total Tests: {results['summary']['total']}")
702
- print(f"Passed: {results['summary']['passed']}")
703
- print(f"Failed: {results['summary']['failed']}")
704
- print(f"Skipped: {results['summary']['skipped']}")
705
- print(f"Success Rate: {results['success_rate']:.1f}%")
706
- print(f"{'='*60}")
707
-
708
- # Print failed tests
709
- failed_tests = [test for test in results['tests'] if test['status'] == 'failed']
710
- if failed_tests:
711
- print(f"\nFAILED TESTS:")
712
- for test in failed_tests:
713
- print(f" ✗ {test['name']}: {test['message']}")
714
-
715
- # Exit with appropriate code
716
- sys.exit(0 if results['summary']['failed'] == 0 else 1)
717
-
718
-
719
- if __name__ == '__main__':
720
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/final_system_test.py DELETED
@@ -1,151 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Final System Test - Show the complete enhanced system working
4
- """
5
-
6
- import sqlite3
7
- import requests
8
- import time
9
-
10
- def test_complete_system():
11
- """Test the complete enhanced system"""
12
- print("🚀 FINAL SYSTEM TEST - ENHANCED REAL-TIME MISINFORMATION DETECTION")
13
- print("=" * 80)
14
-
15
- # Wait for system to process some data
16
- print("⏳ Waiting for system to process data...")
17
- time.sleep(5)
18
-
19
- try:
20
- conn = sqlite3.connect('enhanced_realtime.db')
21
- cursor = conn.cursor()
22
-
23
- # Get latest statistics
24
- cursor.execute("SELECT COUNT(*) FROM events")
25
- total_events = cursor.fetchone()[0]
26
-
27
- cursor.execute("SELECT COUNT(DISTINCT state) FROM events")
28
- active_states = cursor.fetchone()[0]
29
-
30
- cursor.execute("SELECT COUNT(DISTINCT source) FROM events")
31
- active_sources = cursor.fetchone()[0]
32
-
33
- # Risk distribution with REAL ML scores
34
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score > 0.7")
35
- high_risk = cursor.fetchone()[0]
36
-
37
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score BETWEEN 0.4 AND 0.7")
38
- medium_risk = cursor.fetchone()[0]
39
-
40
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score < 0.4")
41
- low_risk = cursor.fetchone()[0]
42
-
43
- # Score statistics
44
- cursor.execute("SELECT MIN(misinformation_score), MAX(misinformation_score), AVG(misinformation_score) FROM events")
45
- min_score, max_score, avg_score = cursor.fetchone()
46
-
47
- # Get examples of each risk level
48
- cursor.execute("""
49
- SELECT title, state, misinformation_score, source, category
50
- FROM events
51
- WHERE misinformation_score > 0.7
52
- ORDER BY misinformation_score DESC
53
- LIMIT 3
54
- """)
55
- high_risk_examples = cursor.fetchall()
56
-
57
- cursor.execute("""
58
- SELECT title, state, misinformation_score, source, category
59
- FROM events
60
- WHERE misinformation_score < 0.4
61
- ORDER BY misinformation_score ASC
62
- LIMIT 3
63
- """)
64
- low_risk_examples = cursor.fetchall()
65
-
66
- conn.close()
67
-
68
- print("📊 SYSTEM PERFORMANCE SUMMARY")
69
- print("=" * 50)
70
- print(f"🎯 Total Events: {total_events}")
71
- print(f"🗺️ Active States: {active_states}/29 ({(active_states/29*100):.1f}%)")
72
- print(f"📰 Active Sources: {active_sources}/32 ({(active_sources/32*100):.1f}%)")
73
- print(f"⚡ Processing Speed: Real-time (2-minute cycles)")
74
-
75
- print("\n🧠 ADVANCED ML CLASSIFICATION RESULTS")
76
- print("=" * 50)
77
- print(f"🔴 High Risk (>0.7): {high_risk} events ({(high_risk/total_events*100):.1f}%)")
78
- print(f"🟡 Medium Risk (0.4-0.7): {medium_risk} events ({(medium_risk/total_events*100):.1f}%)")
79
- print(f"🟢 Low Risk (<0.4): {low_risk} events ({(low_risk/total_events*100):.1f}%)")
80
-
81
- print(f"\n📈 SCORE DISTRIBUTION")
82
- print("=" * 50)
83
- print(f"📊 Range: {min_score:.3f} - {max_score:.3f}")
84
- print(f"📊 Average: {avg_score:.3f}")
85
- print(f"📊 Variance: {max_score - min_score:.3f} (EXCELLENT - not static!)")
86
-
87
- if high_risk_examples:
88
- print(f"\n🔴 HIGH RISK EVENTS (ML Detected)")
89
- print("=" * 50)
90
- for i, (title, state, score, source, category) in enumerate(high_risk_examples, 1):
91
- print(f"{i}. {title[:60]}...")
92
- print(f" 📍 {state} | 🎯 {score:.3f} | 📰 {source} | 📂 {category}")
93
-
94
- if low_risk_examples:
95
- print(f"\n🟢 LOW RISK EVENTS (ML Verified)")
96
- print("=" * 50)
97
- for i, (title, state, score, source, category) in enumerate(low_risk_examples, 1):
98
- print(f"{i}. {title[:60]}...")
99
- print(f" 📍 {state} | 🎯 {score:.3f} | 📰 {source} | 📂 {category}")
100
-
101
- # Test API endpoints
102
- print(f"\n🌐 API ENDPOINT TESTS")
103
- print("=" * 50)
104
-
105
- try:
106
- response = requests.get("http://localhost:8080/api/v1/analytics/summary", timeout=5)
107
- if response.status_code == 200:
108
- data = response.json()
109
- print(f"✅ Analytics API: {data['total_events']} events, {data['active_states']} states")
110
- print(f" ML Status: {data['ml_status']}")
111
- print(f" Processing: {data['processing_status']}")
112
- else:
113
- print(f"❌ Analytics API failed: {response.status_code}")
114
- except:
115
- print("❌ Analytics API: Connection failed")
116
-
117
- try:
118
- response = requests.get("http://localhost:8080/api/v1/heatmap/data", timeout=5)
119
- if response.status_code == 200:
120
- data = response.json()
121
- print(f"✅ Heatmap API: {data['total_states']} states with data")
122
- else:
123
- print(f"❌ Heatmap API failed: {response.status_code}")
124
- except:
125
- print("❌ Heatmap API: Connection failed")
126
-
127
- print(f"\n🎉 SYSTEM ACHIEVEMENTS")
128
- print("=" * 50)
129
- print("✅ MASSIVE DATA VOLUME: 120+ events per cycle (vs 4 before)")
130
- print("✅ REAL ML CLASSIFICATION: 95.8% accuracy ensemble classifier")
131
- print("✅ COMPREHENSIVE COVERAGE: All 29 Indian states active")
132
- print("✅ VARIED RISK SCORES: 0.1-0.9 range (not static 50%)")
133
- print("✅ HIGH-VOLUME PROCESSING: 32 RSS sources monitored")
134
- print("✅ REAL-TIME UPDATES: 2-minute processing cycles")
135
- print("✅ ADVANCED FEATURES: Sentiment, linguistic, source analysis")
136
- print("✅ WEB INTERFACE: Interactive heatmap and dashboard")
137
-
138
- print(f"\n🌐 ACCESS THE ENHANCED SYSTEM")
139
- print("=" * 50)
140
- print("📊 Dashboard: http://localhost:8080")
141
- print("🗺️ Heatmap: http://localhost:8080/heatmap")
142
- print("📖 API Docs: http://localhost:8080/docs")
143
-
144
- return True
145
-
146
- except Exception as e:
147
- print(f"❌ Test failed: {e}")
148
- return False
149
-
150
- if __name__ == "__main__":
151
- test_complete_system()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/infrastructure/test_deployment.py DELETED
@@ -1,1087 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Infrastructure and deployment tests for the misinformation heatmap application.
4
- Tests local setup, cloud deployment, and environment switching.
5
- """
6
-
7
- import json
8
- import os
9
- import subprocess
10
- import sys
11
- import tempfile
12
- import time
13
- import unittest
14
- from pathlib import Path
15
- from unittest.mock import Mock, patch
16
-
17
- import requests
18
-
19
-
20
- class DeploymentTestCase(unittest.TestCase):
21
- """Base test case for deployment tests."""
22
-
23
- def setUp(self):
24
- self.project_root = Path(__file__).parent.parent.parent
25
- self.scripts_dir = self.project_root / "scripts"
26
- self.backend_dir = self.project_root / "backend"
27
-
28
- def run_script(self, script_path, args=None, timeout=60):
29
- """Run a script and return the result."""
30
- script_path = Path(script_path)
31
-
32
- # Handle different script types based on extension
33
- if script_path.suffix == '.py':
34
- cmd = [sys.executable, str(script_path)]
35
- elif script_path.suffix == '.sh':
36
- # On Windows, try to run with bash if available, otherwise skip
37
- if os.name == 'nt':
38
- # Try Git Bash or WSL bash
39
- bash_paths = [
40
- r"C:\Program Files\Git\bin\bash.exe",
41
- r"C:\Windows\System32\bash.exe"
42
- ]
43
- bash_exe = None
44
- for bash_path in bash_paths:
45
- if Path(bash_path).exists():
46
- bash_exe = bash_path
47
- break
48
-
49
- if bash_exe:
50
- cmd = [bash_exe, str(script_path)]
51
- else:
52
- # Skip bash scripts on Windows without bash
53
- return Mock(returncode=0, stdout="Skipped on Windows", stderr="")
54
- else:
55
- cmd = ['bash', str(script_path)]
56
- elif script_path.suffix == '.ps1':
57
- if os.name == 'nt':
58
- cmd = ['powershell', '-ExecutionPolicy', 'Bypass', '-File', str(script_path)]
59
- else:
60
- # Skip PowerShell scripts on non-Windows
61
- return Mock(returncode=0, stdout="Skipped on non-Windows", stderr="")
62
- else:
63
- cmd = [str(script_path)]
64
-
65
- if args:
66
- cmd.extend(args)
67
-
68
- try:
69
- result = subprocess.run(
70
- cmd,
71
- capture_output=True,
72
- text=True,
73
- timeout=timeout,
74
- cwd=self.project_root
75
- )
76
- return result
77
- except subprocess.TimeoutExpired:
78
- self.fail(f"Script {script_path} timed out after {timeout}s")
79
- except FileNotFoundError:
80
- # Return a mock result for missing executables
81
- return Mock(returncode=1, stdout="", stderr=f"Executable not found for {script_path}")
82
-
83
-
84
- class LocalSetupTests(DeploymentTestCase):
85
- """Tests for local development setup scripts."""
86
-
87
- def test_run_local_script_exists(self):
88
- """Test that local setup scripts exist and are executable."""
89
- bash_script = self.scripts_dir / "run_local.sh"
90
- ps_script = self.scripts_dir / "run_local.ps1"
91
-
92
- self.assertTrue(bash_script.exists(), "run_local.sh script not found")
93
- self.assertTrue(ps_script.exists(), "run_local.ps1 script not found")
94
-
95
- def test_run_local_help(self):
96
- """Test that local setup script shows help correctly."""
97
- script = self.scripts_dir / "run_local.sh"
98
- result = self.run_script(script, ["--help"])
99
-
100
- self.assertEqual(result.returncode, 0)
101
- self.assertIn("Usage:", result.stdout)
102
- self.assertIn("Options:", result.stdout)
103
-
104
- def test_environment_validation_script(self):
105
- """Test environment validation script."""
106
- script = self.scripts_dir / "validate_environment.py"
107
- self.assertTrue(script.exists(), "validate_environment.py not found")
108
-
109
- # Test help
110
- result = self.run_script(script, ["--help"])
111
- self.assertEqual(result.returncode, 0)
112
-
113
- # Test validation (may fail due to missing dependencies, but should not crash)
114
- result = self.run_script(script, ["--mode", "local"])
115
- self.assertIn(result.returncode, [0, 1]) # Either pass or fail, but not crash
116
-
117
- def test_database_initialization_script(self):
118
- """Test database initialization script."""
119
- script = self.backend_dir / "init_db.py"
120
- self.assertTrue(script.exists(), "init_db.py not found")
121
-
122
- # Test help
123
- result = self.run_script(script, ["--help"])
124
- self.assertEqual(result.returncode, 0)
125
- self.assertIn("Initialize database", result.stdout)
126
-
127
- def test_health_check_script(self):
128
- """Test health check script."""
129
- script = self.scripts_dir / "health_check.py"
130
- self.assertTrue(script.exists(), "health_check.py not found")
131
-
132
- # Test help
133
- result = self.run_script(script, ["--help"])
134
- self.assertEqual(result.returncode, 0)
135
- self.assertIn("Health check", result.stdout)
136
-
137
-
138
- class CloudDeploymentTests(DeploymentTestCase):
139
- """Tests for cloud deployment scripts."""
140
-
141
- def test_cloud_deployment_scripts_exist(self):
142
- """Test that cloud deployment scripts exist."""
143
- scripts = [
144
- "deploy_cloudrun.sh",
145
- "pubsub_setup.sh",
146
- "setup_bigquery.sh",
147
- "cloud_env_template.sh"
148
- ]
149
-
150
- for script_name in scripts:
151
- script_path = self.scripts_dir / script_name
152
- self.assertTrue(script_path.exists(), f"{script_name} not found")
153
-
154
- def test_deploy_cloudrun_help(self):
155
- """Test Cloud Run deployment script help."""
156
- script = self.scripts_dir / "deploy_cloudrun.sh"
157
- result = self.run_script(script, ["--help"])
158
-
159
- self.assertEqual(result.returncode, 0)
160
- self.assertIn("Cloud Run Deployment", result.stdout)
161
- self.assertIn("--project", result.stdout)
162
-
163
- def test_pubsub_setup_help(self):
164
- """Test Pub/Sub setup script help."""
165
- script = self.scripts_dir / "pubsub_setup.sh"
166
- result = self.run_script(script, ["--help"])
167
-
168
- self.assertEqual(result.returncode, 0)
169
- self.assertIn("Pub/Sub Setup", result.stdout)
170
- self.assertIn("--project", result.stdout)
171
-
172
- def test_bigquery_setup_help(self):
173
- """Test BigQuery setup script help."""
174
- script = self.scripts_dir / "setup_bigquery.sh"
175
- result = self.run_script(script, ["--help"])
176
-
177
- self.assertEqual(result.returncode, 0)
178
- self.assertIn("BigQuery Setup", result.stdout)
179
- self.assertIn("--project", result.stdout)
180
-
181
- def test_bigquery_schema_file(self):
182
- """Test BigQuery schema SQL file."""
183
- schema_file = self.scripts_dir / "bigquery_schema.sql"
184
- self.assertTrue(schema_file.exists(), "bigquery_schema.sql not found")
185
-
186
- # Check that schema contains expected elements
187
- content = schema_file.read_text()
188
- self.assertIn("CREATE SCHEMA", content)
189
- self.assertIn("misinformation_heatmap", content)
190
- self.assertIn("events", content)
191
- self.assertIn("state_aggregations", content)
192
-
193
- def test_cloud_env_template(self):
194
- """Test cloud environment template."""
195
- template = self.scripts_dir / "cloud_env_template.sh"
196
- self.assertTrue(template.exists(), "cloud_env_template.sh not found")
197
-
198
- content = template.read_text()
199
- self.assertIn("GOOGLE_CLOUD_PROJECT", content)
200
- self.assertIn("BIGQUERY_DATASET", content)
201
- self.assertIn("PUBSUB_", content)
202
-
203
-
204
- class EnvironmentSwitchingTests(DeploymentTestCase):
205
- """Tests for switching between local and cloud environments."""
206
-
207
- def test_config_mode_switching(self):
208
- """Test configuration mode switching."""
209
- # Import Config class to test mode switching
210
- sys.path.append(str(self.backend_dir))
211
-
212
- try:
213
- from config import Config
214
-
215
- # Test local mode
216
- with patch.dict(os.environ, {'MODE': 'local'}):
217
- config = Config()
218
- self.assertTrue(config.is_local_mode())
219
- self.assertFalse(config.is_cloud_mode())
220
- self.assertEqual(config.mode, 'local')
221
-
222
- # Test cloud mode
223
- with patch.dict(os.environ, {
224
- 'MODE': 'cloud',
225
- 'GCP_PROJECT_ID': 'test-project',
226
- 'WATSON_API_KEY': 'test-key',
227
- 'GEE_SERVICE_ACCOUNT': '/path/to/service-account.json'
228
- }):
229
- config = Config()
230
- self.assertTrue(config.is_cloud_mode())
231
- self.assertFalse(config.is_local_mode())
232
- self.assertEqual(config.mode, 'cloud')
233
-
234
- except ImportError:
235
- self.skipTest("Config module not available")
236
-
237
- def test_database_configuration_switching(self):
238
- """Test database configuration for different modes."""
239
- sys.path.append(str(self.backend_dir))
240
-
241
- try:
242
- from config import Config
243
-
244
- # Test local mode database config
245
- with patch.dict(os.environ, {'MODE': 'local'}):
246
- config = Config()
247
- db_config = config.get_database_config()
248
- self.assertEqual(db_config.type, 'sqlite')
249
- self.assertIn('sqlite:///', db_config.url)
250
-
251
- # Test cloud mode database config
252
- with patch.dict(os.environ, {
253
- 'MODE': 'cloud',
254
- 'GCP_PROJECT_ID': 'test-project'
255
- }):
256
- config = Config()
257
- db_config = config.get_database_config()
258
- self.assertEqual(db_config.type, 'bigquery')
259
- self.assertEqual(db_config.project_id, 'test-project')
260
-
261
- except ImportError:
262
- self.skipTest("Config module not available")
263
-
264
- def test_pubsub_configuration_switching(self):
265
- """Test Pub/Sub configuration for different modes."""
266
- sys.path.append(str(self.backend_dir))
267
-
268
- try:
269
- from config import Config
270
-
271
- # Test local mode Pub/Sub config
272
- with patch.dict(os.environ, {'MODE': 'local'}):
273
- config = Config()
274
- pubsub_config = config.get_pubsub_config()
275
- self.assertTrue(pubsub_config.use_emulator)
276
- self.assertEqual(pubsub_config.emulator_host, 'localhost:8085')
277
-
278
- # Test cloud mode Pub/Sub config
279
- with patch.dict(os.environ, {
280
- 'MODE': 'cloud',
281
- 'GCP_PROJECT_ID': 'test-project'
282
- }):
283
- config = Config()
284
- pubsub_config = config.get_pubsub_config()
285
- self.assertFalse(pubsub_config.use_emulator)
286
- self.assertEqual(pubsub_config.project_id, 'test-project')
287
-
288
- except ImportError:
289
- self.skipTest("Config module not available")
290
-
291
- def test_satellite_configuration_switching(self):
292
- """Test satellite validation configuration for different modes."""
293
- sys.path.append(str(self.backend_dir))
294
-
295
- try:
296
- from config import Config
297
-
298
- # Test local mode satellite config
299
- with patch.dict(os.environ, {'MODE': 'local'}):
300
- config = Config()
301
- satellite_config = config.get_satellite_config()
302
- self.assertTrue(satellite_config.use_stub)
303
-
304
- # Test cloud mode satellite config
305
- with patch.dict(os.environ, {
306
- 'MODE': 'cloud',
307
- 'GEE_SERVICE_ACCOUNT': '/path/to/service-account.json'
308
- }):
309
- config = Config()
310
- satellite_config = config.get_satellite_config()
311
- self.assertFalse(satellite_config.use_stub)
312
- self.assertEqual(satellite_config.gee_service_account_path, '/path/to/service-account.json')
313
-
314
- except ImportError:
315
- self.skipTest("Config module not available")
316
-
317
- def test_environment_variable_validation(self):
318
- """Test environment variable validation for different modes."""
319
- sys.path.append(str(self.backend_dir))
320
-
321
- try:
322
- from config import Config
323
-
324
- # Test cloud mode missing required variables
325
- with patch.dict(os.environ, {'MODE': 'cloud'}, clear=True):
326
- with self.assertRaises(ValueError):
327
- config = Config()
328
- config.get_database_config() # Should fail without GCP_PROJECT_ID
329
-
330
- # Test cloud mode with required variables
331
- with patch.dict(os.environ, {
332
- 'MODE': 'cloud',
333
- 'GCP_PROJECT_ID': 'test-project',
334
- 'WATSON_API_KEY': 'test-key',
335
- 'GEE_SERVICE_ACCOUNT': '/path/to/service-account.json'
336
- }):
337
- config = Config()
338
- # Should not raise exceptions
339
- db_config = config.get_database_config()
340
- watson_config = config.get_watson_config()
341
- satellite_config = config.get_satellite_config()
342
-
343
- self.assertEqual(db_config.project_id, 'test-project')
344
- self.assertTrue(watson_config['enabled'])
345
- self.assertFalse(satellite_config.use_stub)
346
-
347
- except ImportError:
348
- self.skipTest("Config module not available")
349
-
350
-
351
- class IntegrationTests(DeploymentTestCase):
352
- """Integration tests for deployment components."""
353
-
354
- def test_script_dependencies(self):
355
- """Test that all scripts have their dependencies available."""
356
- # Test Python scripts
357
- python_scripts = [
358
- "validate_environment.py",
359
- "health_check.py",
360
- "performance_benchmark.py"
361
- ]
362
-
363
- for script_name in python_scripts:
364
- script_path = self.scripts_dir / script_name
365
- if script_path.exists():
366
- # Test that script can be imported (basic syntax check)
367
- result = subprocess.run([
368
- sys.executable, "-m", "py_compile", str(script_path)
369
- ], capture_output=True)
370
-
371
- self.assertEqual(result.returncode, 0,
372
- f"Python script {script_name} has syntax errors: {result.stderr.decode()}")
373
-
374
- def test_deployment_script_execution(self):
375
- """Test deployment scripts can be executed with help flags."""
376
- bash_scripts = [
377
- ("run_local.sh", ["--help"]),
378
- ("deploy_cloudrun.sh", ["--help"]),
379
- ("pubsub_setup.sh", ["--help"]),
380
- ("setup_bigquery.sh", ["--help"])
381
- ]
382
-
383
- for script_name, args in bash_scripts:
384
- script_path = self.scripts_dir / script_name
385
- if script_path.exists():
386
- try:
387
- result = self.run_script(script_path, args, timeout=30)
388
- self.assertEqual(result.returncode, 0,
389
- f"Script {script_name} help failed: {result.stderr}")
390
- self.assertIn("Usage:", result.stdout,
391
- f"Script {script_name} missing usage information")
392
- except subprocess.TimeoutExpired:
393
- self.fail(f"Script {script_name} timed out")
394
-
395
- def test_environment_validation_integration(self):
396
- """Test environment validation script integration."""
397
- script = self.scripts_dir / "validate_environment.py"
398
- if script.exists():
399
- # Test local mode validation
400
- result = self.run_script(script, ["--mode", "local"], timeout=60)
401
- self.assertIn(result.returncode, [0, 1]) # Either pass or fail gracefully
402
-
403
- # Test that it produces output
404
- self.assertTrue(result.stdout or result.stderr,
405
- "Environment validation script produced no output")
406
-
407
- def test_health_check_integration(self):
408
- """Test health check script integration."""
409
- script = self.scripts_dir / "health_check.py"
410
- if script.exists():
411
- # Test help
412
- result = self.run_script(script, ["--help"])
413
- self.assertEqual(result.returncode, 0)
414
- self.assertIn("Health check", result.stdout)
415
-
416
- # Test JSON format
417
- result = self.run_script(script, ["--format", "json"], timeout=30)
418
- self.assertIn(result.returncode, [0, 1]) # May fail if services not running
419
-
420
- def test_test_data_integrity(self):
421
- """Test that test data files are valid."""
422
- test_data_file = self.project_root / "data" / "fact_checks.csv"
423
-
424
- if test_data_file.exists():
425
- content = test_data_file.read_text()
426
- lines = content.strip().split('\n')
427
-
428
- # Should have header + data rows
429
- self.assertGreater(len(lines), 1, "Test data file is empty")
430
-
431
- # Check header
432
- header = lines[0]
433
- expected_columns = [
434
- 'event_id', 'source', 'original_text', 'lang',
435
- 'region_hint', 'lat', 'lon', 'category'
436
- ]
437
-
438
- for column in expected_columns:
439
- self.assertIn(column, header, f"Missing column: {column}")
440
-
441
- def test_geojson_data_integrity(self):
442
- """Test that GeoJSON data is valid."""
443
- geojson_files = [
444
- self.project_root / "data" / "india_states_geojson.json",
445
- self.project_root / "frontend" / "data" / "india-states.geojson"
446
- ]
447
-
448
- for geojson_file in geojson_files:
449
- if geojson_file.exists():
450
- try:
451
- content = geojson_file.read_text()
452
- data = json.loads(content)
453
-
454
- # Basic GeoJSON structure validation
455
- self.assertEqual(data.get("type"), "FeatureCollection")
456
- self.assertIn("features", data)
457
- self.assertIsInstance(data["features"], list)
458
-
459
- # Check if features exist (may be empty in test data)
460
- if len(data["features"]) > 0:
461
- # Check first feature structure
462
- feature = data["features"][0]
463
- self.assertEqual(feature.get("type"), "Feature")
464
- self.assertIn("properties", feature)
465
- self.assertIn("geometry", feature)
466
-
467
- # Validate Indian state properties
468
- properties = feature.get("properties", {})
469
- self.assertTrue(
470
- "NAME" in properties or "name" in properties or "ST_NM" in properties,
471
- "GeoJSON feature missing state name property"
472
- )
473
- else:
474
- # Empty features array is acceptable for test data
475
- print(f"Warning: {geojson_file} has empty features array")
476
-
477
- except json.JSONDecodeError as e:
478
- self.fail(f"Invalid GeoJSON format in {geojson_file}: {e}")
479
-
480
- def test_docker_configuration(self):
481
- """Test Docker configuration files if they exist."""
482
- dockerfile_paths = [
483
- self.backend_dir / "Dockerfile",
484
- self.project_root / "Dockerfile"
485
- ]
486
-
487
- for dockerfile in dockerfile_paths:
488
- if dockerfile.exists():
489
- content = dockerfile.read_text()
490
-
491
- # Basic Dockerfile validation
492
- self.assertIn("FROM", content, "Dockerfile missing FROM instruction")
493
- self.assertIn("WORKDIR", content, "Dockerfile missing WORKDIR instruction")
494
- self.assertIn("COPY", content, "Dockerfile missing COPY instruction")
495
-
496
- # Check for Python-specific instructions
497
- if "python" in content.lower():
498
- self.assertIn("pip install", content, "Python Dockerfile missing pip install")
499
-
500
- def test_cloud_configuration_templates(self):
501
- """Test cloud configuration templates."""
502
- cloud_templates = [
503
- self.scripts_dir / "cloud_env_template.sh",
504
- self.scripts_dir / "bigquery_schema.sql"
505
- ]
506
-
507
- for template in cloud_templates:
508
- if template.exists():
509
- content = template.read_text()
510
- self.assertGreater(len(content.strip()), 0,
511
- f"Template {template.name} is empty")
512
-
513
- if template.name.endswith('.sql'):
514
- # Basic SQL validation
515
- self.assertIn("CREATE", content.upper(),
516
- "SQL template missing CREATE statements")
517
- elif template.name.endswith('.sh'):
518
- # Basic shell script validation
519
- self.assertTrue(content.startswith('#!/bin/bash') or
520
- content.startswith('#!/bin/sh'),
521
- "Shell script missing shebang")
522
-
523
-
524
- class DeploymentScriptTests(DeploymentTestCase):
525
- """Tests for deployment script functionality and error handling."""
526
-
527
- def test_local_setup_script_error_handling(self):
528
- """Test local setup script error handling."""
529
- script = self.scripts_dir / "run_local.sh"
530
- if not script.exists():
531
- self.skipTest("run_local.sh not found")
532
-
533
- # Test invalid mode
534
- result = self.run_script(script, ["--mode", "invalid"])
535
- self.assertNotEqual(result.returncode, 0, "Script should fail with invalid mode")
536
-
537
- # Test help output
538
- result = self.run_script(script, ["--help"])
539
- self.assertEqual(result.returncode, 0)
540
- self.assertIn("Usage:", result.stdout)
541
- self.assertIn("--mode", result.stdout)
542
-
543
- def test_cloud_deployment_script_validation(self):
544
- """Test cloud deployment script validation."""
545
- script = self.scripts_dir / "deploy_cloudrun.sh"
546
- if not script.exists():
547
- self.skipTest("deploy_cloudrun.sh not found")
548
-
549
- # Test missing project ID
550
- result = self.run_script(script, ["--build-only"])
551
- self.assertNotEqual(result.returncode, 0, "Script should fail without project ID")
552
- self.assertIn("Project ID", result.stderr)
553
-
554
- # Test help output
555
- result = self.run_script(script, ["--help"])
556
- self.assertEqual(result.returncode, 0)
557
- self.assertIn("--project", result.stdout)
558
-
559
- def test_pubsub_setup_script_validation(self):
560
- """Test Pub/Sub setup script validation."""
561
- script = self.scripts_dir / "pubsub_setup.sh"
562
- if not script.exists():
563
- self.skipTest("pubsub_setup.sh not found")
564
-
565
- # Test dry run mode
566
- result = self.run_script(script, ["--project", "test-project", "--dry-run"])
567
- self.assertEqual(result.returncode, 0, "Dry run should succeed")
568
- self.assertIn("DRY RUN", result.stdout)
569
-
570
- # Test list functionality (should work without project)
571
- result = self.run_script(script, ["--list"])
572
- # May fail if not authenticated, but should not crash
573
- self.assertIn(result.returncode, [0, 1])
574
-
575
- def test_bigquery_setup_script_validation(self):
576
- """Test BigQuery setup script validation."""
577
- script = self.scripts_dir / "setup_bigquery.sh"
578
- if not script.exists():
579
- self.skipTest("setup_bigquery.sh not found")
580
-
581
- # Test missing project ID
582
- result = self.run_script(script, ["--dry-run"])
583
- self.assertNotEqual(result.returncode, 0, "Script should fail without project ID")
584
-
585
- # Test with project ID in dry run
586
- result = self.run_script(script, ["--project", "test-project", "--dry-run"])
587
- # May fail due to missing gcloud/bq, but should handle gracefully
588
- self.assertIn(result.returncode, [0, 1])
589
-
590
- def test_script_permissions(self):
591
- """Test that deployment scripts have correct permissions."""
592
- bash_scripts = [
593
- "run_local.sh",
594
- "deploy_cloudrun.sh",
595
- "pubsub_setup.sh",
596
- "setup_bigquery.sh"
597
- ]
598
-
599
- for script_name in bash_scripts:
600
- script_path = self.scripts_dir / script_name
601
- if script_path.exists():
602
- # On Windows, just check that file exists and is readable
603
- if os.name == 'nt':
604
- self.assertTrue(script_path.is_file(), f"Script {script_name} is not a file")
605
- # Check if file is readable
606
- try:
607
- with open(script_path, 'r') as f:
608
- f.read(1)
609
- readable = True
610
- except:
611
- readable = False
612
- self.assertTrue(readable, f"Script {script_name} is not readable")
613
- else:
614
- # On Unix-like systems, check executable permissions
615
- stat_info = script_path.stat()
616
- is_executable = bool(stat_info.st_mode & 0o111)
617
- self.assertTrue(is_executable, f"Script {script_name} is not executable")
618
-
619
- def test_powershell_script_functionality(self):
620
- """Test PowerShell script functionality on Windows."""
621
- ps_script = self.scripts_dir / "run_local.ps1"
622
- if not ps_script.exists():
623
- self.skipTest("run_local.ps1 not found")
624
-
625
- # Test help functionality
626
- try:
627
- result = subprocess.run([
628
- "powershell", "-ExecutionPolicy", "Bypass",
629
- "-File", str(ps_script), "-Help"
630
- ], capture_output=True, text=True, timeout=30)
631
-
632
- # Should work on Windows, may fail on other platforms
633
- if result.returncode == 0:
634
- self.assertIn("Usage:", result.stdout)
635
- else:
636
- # If PowerShell not available, just check file exists and has content
637
- content = ps_script.read_text()
638
- self.assertIn("param(", content)
639
- self.assertIn("function", content.lower())
640
-
641
- except (subprocess.TimeoutExpired, FileNotFoundError):
642
- # PowerShell not available, just validate file structure
643
- content = ps_script.read_text()
644
- self.assertIn("param(", content)
645
- self.assertGreater(len(content), 1000, "PowerShell script seems too short")
646
-
647
-
648
- class ErrorHandlingTests(DeploymentTestCase):
649
- """Tests for error handling in deployment scenarios."""
650
-
651
- def test_missing_dependencies_handling(self):
652
- """Test handling of missing dependencies."""
653
- # Test environment validation with missing dependencies
654
- script = self.scripts_dir / "validate_environment.py"
655
- if script.exists():
656
- # Test with minimal environment
657
- minimal_env = {
658
- 'PATH': os.environ.get('PATH', ''),
659
- 'PYTHONPATH': os.environ.get('PYTHONPATH', ''),
660
- 'HOME': os.environ.get('HOME', ''),
661
- 'MODE': 'local'
662
- }
663
-
664
- result = subprocess.run([
665
- sys.executable, str(script), "--mode", "local"
666
- ], env=minimal_env, capture_output=True, text=True, timeout=60)
667
-
668
- # Should handle missing dependencies gracefully
669
- self.assertIn(result.returncode, [0, 1])
670
- self.assertTrue(result.stdout or result.stderr)
671
-
672
- def test_network_failure_handling(self):
673
- """Test handling of network failures."""
674
- # Test health check with unreachable services
675
- script = self.scripts_dir / "health_check.py"
676
- if script.exists():
677
- # Test with unreachable URL and very short timeout
678
- try:
679
- result = self.run_script(script, [
680
- "--url", "http://localhost:9999",
681
- "--timeout", "1",
682
- "--format", "json"
683
- ], timeout=10)
684
-
685
- # Should fail gracefully
686
- self.assertEqual(result.returncode, 1)
687
-
688
- # Should produce some output (may not be valid JSON if connection fails quickly)
689
- self.assertTrue(result.stdout or result.stderr,
690
- "Health check should produce some output even on failure")
691
-
692
- # Try to parse JSON if stdout exists
693
- if result.stdout.strip():
694
- try:
695
- output = json.loads(result.stdout)
696
- self.assertIn("overall_healthy", output)
697
- self.assertFalse(output["overall_healthy"])
698
- except json.JSONDecodeError:
699
- # JSON parsing may fail if connection fails immediately
700
- pass
701
-
702
- except AssertionError as e:
703
- if "timed out" in str(e):
704
- # If script times out, that's also a valid test result
705
- # (shows the script doesn't handle timeouts well)
706
- pass
707
- else:
708
- raise
709
-
710
- def test_configuration_validation_errors(self):
711
- """Test configuration validation error handling."""
712
- sys.path.append(str(self.backend_dir))
713
-
714
- try:
715
- from config import Config
716
-
717
- # Test invalid mode
718
- with patch.dict(os.environ, {'MODE': 'invalid'}):
719
- with self.assertRaises(ValueError):
720
- Config()
721
-
722
- # Test cloud mode with missing required variables
723
- with patch.dict(os.environ, {'MODE': 'cloud'}, clear=True):
724
- config = Config()
725
-
726
- with self.assertRaises(ValueError):
727
- config.get_database_config()
728
-
729
- with self.assertRaises(ValueError):
730
- config.get_watson_config()
731
-
732
- except ImportError:
733
- self.skipTest("Config module not available")
734
-
735
- def test_file_permission_errors(self):
736
- """Test handling of file permission errors."""
737
- # Create a temporary directory with restricted permissions
738
- with tempfile.TemporaryDirectory() as temp_dir:
739
- restricted_dir = Path(temp_dir) / "restricted"
740
- restricted_dir.mkdir()
741
-
742
- # Try to make it read-only (may not work on all systems)
743
- try:
744
- restricted_dir.chmod(0o444)
745
-
746
- # Test database initialization with restricted directory
747
- script = self.backend_dir / "init_db.py"
748
- if script.exists():
749
- result = subprocess.run([
750
- sys.executable, str(script),
751
- "--database-url", f"sqlite:///{restricted_dir}/test.db"
752
- ], capture_output=True, text=True, timeout=30)
753
-
754
- # Should handle permission error gracefully
755
- self.assertNotEqual(result.returncode, 0)
756
- self.assertTrue(result.stderr)
757
-
758
- except OSError:
759
- # Permission changes not supported on this system
760
- self.skipTest("Cannot test file permissions on this system")
761
-
762
-
763
- class PerformanceTests(DeploymentTestCase):
764
- """Performance and load tests."""
765
-
766
- def test_performance_benchmark_script(self):
767
- """Test performance benchmark script."""
768
- script = self.scripts_dir / "performance_benchmark.py"
769
- self.assertTrue(script.exists(), "performance_benchmark.py not found")
770
-
771
- # Test help
772
- result = self.run_script(script, ["--help"])
773
- self.assertEqual(result.returncode, 0)
774
- self.assertIn("Performance benchmark", result.stdout)
775
-
776
- def test_script_execution_performance(self):
777
- """Test deployment script execution performance."""
778
- # Test that help commands execute quickly
779
- scripts_to_test = [
780
- ("validate_environment.py", ["--help"]),
781
- ("health_check.py", ["--help"]),
782
- ("run_local.sh", ["--help"])
783
- ]
784
-
785
- for script_name, args in scripts_to_test:
786
- script_path = self.scripts_dir / script_name
787
- if script_path.exists():
788
- start_time = time.time()
789
- result = self.run_script(script_path, args, timeout=10)
790
- execution_time = time.time() - start_time
791
-
792
- # Help commands should execute quickly
793
- self.assertLess(execution_time, 5.0,
794
- f"Script {script_name} help took too long: {execution_time}s")
795
- self.assertEqual(result.returncode, 0)
796
-
797
- @unittest.skipUnless(
798
- subprocess.run(["curl", "-s", "http://localhost:8000/health"],
799
- capture_output=True).returncode == 0,
800
- "API server not running"
801
- )
802
- def test_api_response_times(self):
803
- """Test API response times meet requirements."""
804
- endpoints = [
805
- "/health",
806
- "/heatmap",
807
- "/api/info"
808
- ]
809
-
810
- for endpoint in endpoints:
811
- start_time = time.time()
812
-
813
- try:
814
- response = requests.get(f"http://localhost:8000{endpoint}", timeout=5)
815
- end_time = time.time()
816
-
817
- response_time = (end_time - start_time) * 1000 # Convert to ms
818
-
819
- # API should respond within 1 second for basic endpoints
820
- self.assertLess(response_time, 1000,
821
- f"Endpoint {endpoint} response time too high: {response_time}ms")
822
-
823
- if response.status_code < 400:
824
- self.assertLess(response_time, 500,
825
- f"Successful endpoint {endpoint} should respond faster: {response_time}ms")
826
-
827
- except requests.exceptions.RequestException as e:
828
- self.fail(f"Request to {endpoint} failed: {e}")
829
-
830
- def test_concurrent_health_checks(self):
831
- """Test concurrent health check execution."""
832
- script = self.scripts_dir / "health_check.py"
833
- if not script.exists():
834
- self.skipTest("health_check.py not found")
835
-
836
- import threading
837
- import queue
838
-
839
- results_queue = queue.Queue()
840
-
841
- def run_health_check():
842
- try:
843
- result = self.run_script(script, ["--format", "json"], timeout=30)
844
- results_queue.put(("success", result.returncode))
845
- except Exception as e:
846
- results_queue.put(("error", str(e)))
847
-
848
- # Run 3 concurrent health checks
849
- threads = []
850
- for _ in range(3):
851
- thread = threading.Thread(target=run_health_check)
852
- threads.append(thread)
853
- thread.start()
854
-
855
- # Wait for all threads to complete
856
- for thread in threads:
857
- thread.join(timeout=60)
858
-
859
- # Check results
860
- success_count = 0
861
- while not results_queue.empty():
862
- status, result = results_queue.get()
863
- if status == "success":
864
- success_count += 1
865
-
866
- # At least some health checks should succeed
867
- self.assertGreater(success_count, 0, "No concurrent health checks succeeded")
868
-
869
-
870
- class ComprehensiveDeploymentTests(DeploymentTestCase):
871
- """Comprehensive end-to-end deployment validation tests."""
872
-
873
- def test_full_local_deployment_simulation(self):
874
- """Test full local deployment simulation."""
875
- # Test that all required components for local deployment exist
876
- required_components = [
877
- # Scripts
878
- self.scripts_dir / "run_local.sh",
879
- self.scripts_dir / "validate_environment.py",
880
- self.scripts_dir / "health_check.py",
881
-
882
- # Backend components
883
- self.backend_dir / "api.py",
884
- self.backend_dir / "config.py",
885
- self.backend_dir / "database.py",
886
- self.backend_dir / "requirements.txt",
887
-
888
- # Frontend components
889
- self.project_root / "frontend" / "index.html",
890
- self.project_root / "frontend" / "app.js",
891
-
892
- # Data components
893
- self.project_root / "data"
894
- ]
895
-
896
- missing_components = []
897
- for component in required_components:
898
- if not component.exists():
899
- missing_components.append(str(component))
900
-
901
- if missing_components:
902
- self.fail(f"Missing components for local deployment: {missing_components}")
903
-
904
- def test_cloud_deployment_readiness(self):
905
- """Test cloud deployment readiness."""
906
- # Test that all required components for cloud deployment exist
907
- cloud_components = [
908
- # Cloud deployment scripts
909
- self.scripts_dir / "deploy_cloudrun.sh",
910
- self.scripts_dir / "pubsub_setup.sh",
911
- self.scripts_dir / "setup_bigquery.sh",
912
- self.scripts_dir / "bigquery_schema.sql",
913
-
914
- # Cloud configuration
915
- self.scripts_dir / "cloud_env_template.sh"
916
- ]
917
-
918
- missing_components = []
919
- for component in cloud_components:
920
- if not component.exists():
921
- missing_components.append(str(component))
922
-
923
- if missing_components:
924
- self.fail(f"Missing components for cloud deployment: {missing_components}")
925
-
926
- def test_deployment_documentation(self):
927
- """Test that deployment documentation exists and is comprehensive."""
928
- readme_files = [
929
- self.project_root / "README.md",
930
- self.project_root / "DEPLOYMENT.md",
931
- self.scripts_dir / "README.md"
932
- ]
933
-
934
- # At least one documentation file should exist
935
- docs_exist = any(readme.exists() for readme in readme_files)
936
-
937
- if not docs_exist:
938
- self.skipTest("No deployment documentation found")
939
-
940
- # Check for key deployment topics in existing docs
941
- for readme in readme_files:
942
- if readme.exists():
943
- content = readme.read_text().lower()
944
-
945
- # Should mention both deployment modes
946
- if "local" in content and "cloud" in content:
947
- self.assertIn("setup", content, "Documentation missing setup instructions")
948
- break
949
-
950
- def test_environment_switching_integration(self):
951
- """Test complete environment switching integration."""
952
- sys.path.append(str(self.backend_dir))
953
-
954
- try:
955
- from config import Config
956
-
957
- # Test switching between modes with proper validation
958
- test_scenarios = [
959
- {
960
- 'mode': 'local',
961
- 'env_vars': {'MODE': 'local'},
962
- 'expected_db_type': 'sqlite',
963
- 'expected_pubsub_emulator': True
964
- },
965
- {
966
- 'mode': 'cloud',
967
- 'env_vars': {
968
- 'MODE': 'cloud',
969
- 'GCP_PROJECT_ID': 'test-project',
970
- 'WATSON_API_KEY': 'test-key',
971
- 'GEE_SERVICE_ACCOUNT': '/path/to/service-account.json'
972
- },
973
- 'expected_db_type': 'bigquery',
974
- 'expected_pubsub_emulator': False
975
- }
976
- ]
977
-
978
- for scenario in test_scenarios:
979
- with patch.dict(os.environ, scenario['env_vars'], clear=True):
980
- config = Config()
981
-
982
- # Test database configuration
983
- db_config = config.get_database_config()
984
- self.assertEqual(db_config.type, scenario['expected_db_type'])
985
-
986
- # Test Pub/Sub configuration
987
- pubsub_config = config.get_pubsub_config()
988
- self.assertEqual(pubsub_config.use_emulator, scenario['expected_pubsub_emulator'])
989
-
990
- # Test satellite configuration
991
- satellite_config = config.get_satellite_config()
992
- expected_stub = scenario['mode'] == 'local'
993
- self.assertEqual(satellite_config.use_stub, expected_stub)
994
-
995
- except ImportError:
996
- self.skipTest("Config module not available for integration testing")
997
-
998
- def test_deployment_rollback_capability(self):
999
- """Test deployment rollback and cleanup capabilities."""
1000
- # Test that cleanup scripts exist and work
1001
- cleanup_scripts = [
1002
- ("run_local.sh", ["--stop"]),
1003
- ("pubsub_setup.sh", ["--cleanup"]),
1004
- ("setup_bigquery.sh", ["--cleanup"])
1005
- ]
1006
-
1007
- for script_name, args in cleanup_scripts:
1008
- script_path = self.scripts_dir / script_name
1009
- if script_path.exists():
1010
- # Test help for cleanup commands
1011
- result = self.run_script(script_path, ["--help"])
1012
- self.assertEqual(result.returncode, 0)
1013
-
1014
- # Check that cleanup options are documented
1015
- help_text = result.stdout.lower()
1016
- cleanup_mentioned = any(word in help_text for word in ['stop', 'cleanup', 'delete'])
1017
- self.assertTrue(cleanup_mentioned,
1018
- f"Script {script_name} missing cleanup documentation")
1019
-
1020
- def test_monitoring_and_observability(self):
1021
- """Test monitoring and observability setup."""
1022
- # Test health check capabilities
1023
- script = self.scripts_dir / "health_check.py"
1024
- if script.exists():
1025
- # Test different output formats
1026
- formats = ["human", "json"]
1027
- for fmt in formats:
1028
- result = self.run_script(script, ["--format", fmt], timeout=30)
1029
- self.assertIn(result.returncode, [0, 1]) # May fail if services not running
1030
-
1031
- if fmt == "json" and result.stdout:
1032
- try:
1033
- data = json.loads(result.stdout)
1034
- self.assertIn("overall_healthy", data)
1035
- self.assertIn("checks", data)
1036
- except json.JSONDecodeError:
1037
- pass # May not be valid JSON if services not running
1038
-
1039
- def test_security_configuration(self):
1040
- """Test security configuration and best practices."""
1041
- # Check for security-related configuration
1042
- config_files = [
1043
- self.project_root / ".env.sample",
1044
- self.scripts_dir / "cloud_env_template.sh"
1045
- ]
1046
-
1047
- for config_file in config_files:
1048
- if config_file.exists():
1049
- content = config_file.read_text()
1050
-
1051
- # Should not contain actual secrets
1052
- sensitive_patterns = [
1053
- r'password\s*=\s*[^<\s]+',
1054
- r'key\s*=\s*[A-Za-z0-9]{20,}',
1055
- r'token\s*=\s*[A-Za-z0-9]{20,}'
1056
- ]
1057
-
1058
- for pattern in sensitive_patterns:
1059
- import re
1060
- matches = re.findall(pattern, content, re.IGNORECASE)
1061
- self.assertEqual(len(matches), 0,
1062
- f"Potential hardcoded secret in {config_file}: {matches}")
1063
-
1064
- # Should have placeholder values
1065
- placeholder_patterns = ['<', 'YOUR_', 'REPLACE_', 'TODO']
1066
- has_placeholders = any(pattern in content for pattern in placeholder_patterns)
1067
-
1068
- if not has_placeholders:
1069
- # At least warn about potential security issue
1070
- print(f"Warning: {config_file} may not have proper placeholder values")
1071
-
1072
-
1073
- if __name__ == "__main__":
1074
- # Create test results directory
1075
- test_results_dir = Path("test-results")
1076
- test_results_dir.mkdir(exist_ok=True)
1077
-
1078
- # Run tests with detailed output
1079
- try:
1080
- import xmlrunner
1081
-
1082
- with open(test_results_dir / "infrastructure-tests.xml", "wb") as output:
1083
- runner = xmlrunner.XMLTestRunner(output=output, verbosity=2)
1084
- unittest.main(testRunner=runner, exit=False)
1085
- except ImportError:
1086
- # Fall back to standard test runner if xmlrunner not available
1087
- unittest.main(verbosity=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_api_basic.py DELETED
@@ -1,80 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Basic test for API functionality
4
- """
5
-
6
- import sys
7
- import os
8
- sys.path.append('backend')
9
-
10
- # Set environment for local mode
11
- os.environ["MODE"] = "local"
12
-
13
- from fastapi.testclient import TestClient
14
- from backend.api import app
15
-
16
- def test_api_basic():
17
- """Test basic API functionality"""
18
- print("Testing API basic functionality...")
19
-
20
- client = TestClient(app)
21
-
22
- # Test root endpoint
23
- response = client.get("/")
24
- assert response.status_code == 200
25
- data = response.json()
26
- assert "message" in data
27
- print("✅ Root endpoint working")
28
-
29
- # Test health check
30
- response = client.get("/health")
31
- assert response.status_code == 200
32
- data = response.json()
33
- assert "status" in data
34
- assert "timestamp" in data
35
- print("✅ Health check endpoint working")
36
-
37
- # Test OpenAPI schema
38
- response = client.get("/openapi.json")
39
- assert response.status_code == 200
40
- schema = response.json()
41
- assert "openapi" in schema
42
- assert "info" in schema
43
- assert schema["info"]["title"] == "Real-time Misinformation Heatmap API"
44
- print("✅ OpenAPI schema generation working")
45
-
46
- # Test docs endpoint
47
- response = client.get("/docs")
48
- assert response.status_code == 200
49
- assert "text/html" in response.headers["content-type"]
50
- print("✅ Swagger docs endpoint working")
51
-
52
- # Test parameter validation
53
- response = client.get("/heatmap?hours_back=0")
54
- assert response.status_code == 422 # Validation error
55
- print("✅ Parameter validation working")
56
-
57
- response = client.get("/heatmap?hours_back=200")
58
- assert response.status_code == 422 # Validation error
59
- print("✅ Parameter range validation working")
60
-
61
- # Test invalid state
62
- response = client.get("/region/California")
63
- assert response.status_code in [400, 422] # Should be validation error
64
- print("✅ State validation working")
65
-
66
- # Test invalid JSON for POST
67
- response = client.post("/ingest/test", json={})
68
- assert response.status_code == 422 # Missing required field
69
- print("✅ POST validation working")
70
-
71
- print("\n🎉 All basic API tests passed!")
72
-
73
- if __name__ == "__main__":
74
- try:
75
- test_api_basic()
76
- except Exception as e:
77
- print(f"❌ API test failed: {e}")
78
- import traceback
79
- traceback.print_exc()
80
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_data_sources_integration.py DELETED
@@ -1,273 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Integration test for the new data sources system.
4
- Tests the complete flow from configuration to data ingestion.
5
- """
6
-
7
- import asyncio
8
- import logging
9
- import sys
10
- import os
11
- from pathlib import Path
12
-
13
- # Add backend to path
14
- sys.path.insert(0, str(Path(__file__).parent.parent / 'backend'))
15
-
16
- from data_sources.config_manager import ConfigManager
17
- from data_sources.registry import DataSourceRegistry
18
- from data_sources.coordinator import IngestionCoordinator
19
- from data_sources.base.data_validator import DataValidator
20
-
21
- logging.basicConfig(level=logging.INFO)
22
- logger = logging.getLogger(__name__)
23
-
24
-
25
- async def test_configuration_loading():
26
- """Test configuration loading and parsing."""
27
- logger.info("Testing configuration loading...")
28
-
29
- try:
30
- # Load configuration
31
- config_manager = ConfigManager("config/data_sources.yaml")
32
-
33
- # Get statistics
34
- stats = config_manager.get_config_stats()
35
- logger.info(f"Loaded {stats['total_sources']} sources ({stats['enabled_sources']} enabled)")
36
-
37
- # Test source retrieval
38
- rss_sources = config_manager.get_sources_by_type('rss')
39
- logger.info(f"Found {len(rss_sources)} RSS sources")
40
-
41
- fact_check_sources = config_manager.get_sources_by_category('fact_check')
42
- logger.info(f"Found {len(fact_check_sources)} fact-checking sources")
43
-
44
- high_priority_sources = config_manager.get_sources_by_priority('critical')
45
- logger.info(f"Found {len(high_priority_sources)} critical priority sources")
46
-
47
- return True
48
-
49
- except Exception as e:
50
- logger.error(f"Configuration loading failed: {e}")
51
- return False
52
-
53
-
54
- async def test_registry_integration():
55
- """Test data source registry integration."""
56
- logger.info("Testing registry integration...")
57
-
58
- try:
59
- # Load configuration
60
- config_manager = ConfigManager("config/data_sources.yaml")
61
-
62
- # Create registry and register sources
63
- registry = DataSourceRegistry()
64
- source_configs = config_manager.export_for_registry()
65
-
66
- connectors = registry.register_sources_from_config(source_configs)
67
- logger.info(f"Registered {len(connectors)} connectors")
68
-
69
- # Test connector retrieval
70
- enabled_connectors = registry.get_enabled_connectors()
71
- logger.info(f"Found {len(enabled_connectors)} enabled connectors")
72
-
73
- # Test specific connector
74
- times_of_india = registry.get_connector('times_of_india')
75
- if times_of_india:
76
- logger.info(f"Times of India connector: {times_of_india}")
77
-
78
- # Test health check
79
- health = await times_of_india.get_health_status()
80
- logger.info(f"Times of India health: {health['status']}")
81
-
82
- return True
83
-
84
- except Exception as e:
85
- logger.error(f"Registry integration failed: {e}")
86
- return False
87
-
88
-
89
- async def test_data_validation():
90
- """Test data validation system."""
91
- logger.info("Testing data validation...")
92
-
93
- try:
94
- from data_sources.base.base_connector import RawEvent
95
- from datetime import datetime, timezone
96
-
97
- validator = DataValidator()
98
-
99
- # Test valid event
100
- valid_event = RawEvent(
101
- source_id="test_source",
102
- source_type="test",
103
- content="This is a test news article about infrastructure development in Maharashtra, India. The government has announced new projects.",
104
- timestamp=datetime.now(timezone.utc),
105
- url="https://example.com/test",
106
- title="Test News Article",
107
- language="en",
108
- location_hint="Maharashtra"
109
- )
110
-
111
- is_valid, reason = validator.validate_event(valid_event)
112
- logger.info(f"Valid event validation: {is_valid} ({reason})")
113
-
114
- # Test invalid event (too short)
115
- invalid_event = RawEvent(
116
- source_id="test_source",
117
- source_type="test",
118
- content="Short",
119
- timestamp=datetime.now(timezone.utc)
120
- )
121
-
122
- is_valid, reason = validator.validate_event(invalid_event)
123
- logger.info(f"Invalid event validation: {is_valid} ({reason})")
124
-
125
- # Get validation stats
126
- stats = validator.get_stats()
127
- logger.info(f"Validation stats: {stats}")
128
-
129
- return True
130
-
131
- except Exception as e:
132
- logger.error(f"Data validation test failed: {e}")
133
- return False
134
-
135
-
136
- async def test_single_source_fetch():
137
- """Test fetching from a single source."""
138
- logger.info("Testing single source fetch...")
139
-
140
- try:
141
- # Load configuration and create registry
142
- config_manager = ConfigManager("config/data_sources.yaml")
143
- registry = DataSourceRegistry()
144
- source_configs = config_manager.export_for_registry()
145
- registry.register_sources_from_config(source_configs)
146
-
147
- # Get a reliable source (PIB)
148
- pib_connector = registry.get_connector('pib_national')
149
- if not pib_connector:
150
- logger.warning("PIB connector not found, trying Times of India")
151
- pib_connector = registry.get_connector('times_of_india')
152
-
153
- if pib_connector:
154
- logger.info(f"Testing fetch from: {pib_connector.source_id}")
155
-
156
- # Fetch events (limit to avoid overwhelming)
157
- events = await pib_connector.fetch_events()
158
- logger.info(f"Fetched {len(events)} events from {pib_connector.source_id}")
159
-
160
- if events:
161
- sample_event = events[0]
162
- logger.info(f"Sample event: {sample_event.title[:100]}...")
163
- logger.info(f"Content length: {len(sample_event.content)}")
164
- logger.info(f"Language: {sample_event.language}")
165
- logger.info(f"Location hint: {sample_event.location_hint}")
166
-
167
- return True
168
-
169
- except Exception as e:
170
- logger.error(f"Single source fetch failed: {e}")
171
- return False
172
-
173
-
174
- async def test_coordinator_integration():
175
- """Test ingestion coordinator."""
176
- logger.info("Testing coordinator integration...")
177
-
178
- try:
179
- # Setup components
180
- config_manager = ConfigManager("config/data_sources.yaml")
181
- registry = DataSourceRegistry()
182
- validator = DataValidator()
183
-
184
- # Register only a few sources for testing
185
- test_sources = {
186
- 'pib_national': config_manager.get_source_config('pib_national'),
187
- 'alt_news': config_manager.get_source_config('alt_news')
188
- }
189
-
190
- # Filter out None values
191
- test_sources = {k: v for k, v in test_sources.items() if v is not None}
192
-
193
- if test_sources:
194
- # Convert to registry format
195
- registry_configs = {}
196
- for source_id, config in test_sources.items():
197
- if config:
198
- registry_configs[source_id] = config.to_dict()
199
-
200
- registry.register_sources_from_config(registry_configs)
201
-
202
- # Create coordinator
203
- coordinator = IngestionCoordinator(registry, validator)
204
-
205
- # Test manual fetch
206
- results = await coordinator.fetch_from_all_sources(max_concurrent=2)
207
-
208
- total_events = sum(len(events) for events in results.values())
209
- logger.info(f"Coordinator fetched {total_events} total events from {len(results)} sources")
210
-
211
- # Get coordinator stats
212
- stats = coordinator.get_ingestion_stats()
213
- logger.info(f"Coordinator stats: {stats['total_events']} events, {stats['total_validated']} validated")
214
-
215
- return True
216
-
217
- except Exception as e:
218
- logger.error(f"Coordinator integration failed: {e}")
219
- return False
220
-
221
-
222
- async def main():
223
- """Run all integration tests."""
224
- logger.info("Starting data sources integration tests...")
225
-
226
- tests = [
227
- ("Configuration Loading", test_configuration_loading),
228
- ("Registry Integration", test_registry_integration),
229
- ("Data Validation", test_data_validation),
230
- ("Single Source Fetch", test_single_source_fetch),
231
- ("Coordinator Integration", test_coordinator_integration)
232
- ]
233
-
234
- results = {}
235
-
236
- for test_name, test_func in tests:
237
- logger.info(f"\n{'='*50}")
238
- logger.info(f"Running: {test_name}")
239
- logger.info(f"{'='*50}")
240
-
241
- try:
242
- result = await test_func()
243
- results[test_name] = result
244
- status = "PASSED" if result else "FAILED"
245
- logger.info(f"{test_name}: {status}")
246
- except Exception as e:
247
- logger.error(f"{test_name}: FAILED - {e}")
248
- results[test_name] = False
249
-
250
- # Summary
251
- logger.info(f"\n{'='*50}")
252
- logger.info("TEST SUMMARY")
253
- logger.info(f"{'='*50}")
254
-
255
- passed = sum(1 for result in results.values() if result)
256
- total = len(results)
257
-
258
- for test_name, result in results.items():
259
- status = "✓ PASSED" if result else "✗ FAILED"
260
- logger.info(f"{status}: {test_name}")
261
-
262
- logger.info(f"\nOverall: {passed}/{total} tests passed")
263
-
264
- if passed == total:
265
- logger.info("🎉 All integration tests passed!")
266
- return 0
267
- else:
268
- logger.error(f"❌ {total - passed} tests failed")
269
- return 1
270
-
271
-
272
- if __name__ == "__main__":
273
- exit_code = asyncio.run(main())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_enhanced_production.py DELETED
@@ -1,173 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Test Enhanced Production System - Show the massive improvements
4
- """
5
-
6
- import sqlite3
7
- import json
8
- from datetime import datetime
9
- import requests
10
-
11
- def test_production_system():
12
- """Test the enhanced production system"""
13
- print("🚀 Enhanced Production System - Performance Test")
14
- print("=" * 70)
15
-
16
- try:
17
- conn = sqlite3.connect('enhanced_realtime.db')
18
- cursor = conn.cursor()
19
-
20
- # Overall statistics
21
- cursor.execute("SELECT COUNT(*) FROM events")
22
- total_events = cursor.fetchone()[0]
23
-
24
- cursor.execute("SELECT COUNT(DISTINCT state) FROM events")
25
- active_states = cursor.fetchone()[0]
26
-
27
- cursor.execute("SELECT COUNT(DISTINCT source) FROM events")
28
- active_sources = cursor.fetchone()[0]
29
-
30
- # Risk distribution
31
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score > 0.7")
32
- high_risk = cursor.fetchone()[0]
33
-
34
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score BETWEEN 0.4 AND 0.7")
35
- medium_risk = cursor.fetchone()[0]
36
-
37
- cursor.execute("SELECT COUNT(*) FROM events WHERE misinformation_score < 0.4")
38
- low_risk = cursor.fetchone()[0]
39
-
40
- # Score statistics
41
- cursor.execute("SELECT MIN(misinformation_score), MAX(misinformation_score), AVG(misinformation_score) FROM events")
42
- min_score, max_score, avg_score = cursor.fetchone()
43
-
44
- # Recent events by state
45
- cursor.execute("""
46
- SELECT state, COUNT(*) as count, AVG(misinformation_score) as avg_score
47
- FROM events
48
- GROUP BY state
49
- ORDER BY count DESC
50
- LIMIT 10
51
- """)
52
- top_states = cursor.fetchall()
53
-
54
- # Category distribution
55
- cursor.execute("""
56
- SELECT category, COUNT(*) as count, AVG(misinformation_score) as avg_score
57
- FROM events
58
- GROUP BY category
59
- ORDER BY count DESC
60
- LIMIT 8
61
- """)
62
- categories = cursor.fetchall()
63
-
64
- # Sample events with varied scores
65
- cursor.execute("""
66
- SELECT title, state, misinformation_score, source, category
67
- FROM events
68
- ORDER BY misinformation_score DESC
69
- LIMIT 5
70
- """)
71
- high_risk_samples = cursor.fetchall()
72
-
73
- cursor.execute("""
74
- SELECT title, state, misinformation_score, source, category
75
- FROM events
76
- ORDER BY misinformation_score ASC
77
- LIMIT 5
78
- """)
79
- low_risk_samples = cursor.fetchall()
80
-
81
- conn.close()
82
-
83
- print("📊 SYSTEM PERFORMANCE METRICS")
84
- print("=" * 50)
85
- print(f"🎯 Total Events Processed: {total_events}")
86
- print(f"🗺️ Active States: {active_states}/29 ({(active_states/29*100):.1f}%)")
87
- print(f"📰 Active Sources: {active_sources}/32 ({(active_sources/32*100):.1f}%)")
88
- print(f"⏱️ Processing Speed: ~{total_events/18:.1f} events/second")
89
-
90
- print("\n🎯 RISK DISTRIBUTION (REAL ML CLASSIFICATION)")
91
- print("=" * 50)
92
- print(f"🔴 High Risk (>0.7): {high_risk} events ({(high_risk/total_events*100):.1f}%)")
93
- print(f"🟡 Medium Risk (0.4-0.7): {medium_risk} events ({(medium_risk/total_events*100):.1f}%)")
94
- print(f"🟢 Low Risk (<0.4): {low_risk} events ({(low_risk/total_events*100):.1f}%)")
95
-
96
- print(f"\n📈 SCORE STATISTICS")
97
- print("=" * 50)
98
- print(f"📊 Score Range: {min_score:.3f} - {max_score:.3f}")
99
- print(f"📊 Average Score: {avg_score:.3f}")
100
- print(f"📊 Score Variance: {max_score - min_score:.3f} (GOOD - not static!)")
101
-
102
- print(f"\n🗺️ TOP ACTIVE STATES")
103
- print("=" * 50)
104
- for state, count, avg_score in top_states:
105
- risk_emoji = "🔴" if avg_score > 0.7 else "🟡" if avg_score > 0.4 else "🟢"
106
- print(f"{risk_emoji} {state}: {count} events (avg: {avg_score:.3f})")
107
-
108
- print(f"\n📂 CONTENT CATEGORIES")
109
- print("=" * 50)
110
- for category, count, avg_score in categories:
111
- risk_emoji = "🔴" if avg_score > 0.7 else "🟡" if avg_score > 0.4 else "🟢"
112
- print(f"{risk_emoji} {category}: {count} events (avg: {avg_score:.3f})")
113
-
114
- print(f"\n🔴 HIGHEST RISK EVENTS")
115
- print("=" * 50)
116
- for i, (title, state, score, source, category) in enumerate(high_risk_samples, 1):
117
- print(f"{i}. {title[:60]}...")
118
- print(f" 📍 {state} | 🎯 {score:.3f} | 📰 {source} | 📂 {category}")
119
-
120
- print(f"\n🟢 LOWEST RISK EVENTS")
121
- print("=" * 50)
122
- for i, (title, state, score, source, category) in enumerate(low_risk_samples, 1):
123
- print(f"{i}. {title[:60]}...")
124
- print(f" 📍 {state} | 🎯 {score:.3f} | 📰 {source} | 📂 {category}")
125
-
126
- # Test API endpoints
127
- print(f"\n🌐 API ENDPOINT TESTS")
128
- print("=" * 50)
129
-
130
- try:
131
- # Test analytics API
132
- response = requests.get("http://localhost:8080/api/v1/analytics/summary", timeout=5)
133
- if response.status_code == 200:
134
- data = response.json()
135
- print(f"✅ Analytics API: {data['total_events']} events, {data['active_states']} states")
136
- else:
137
- print(f"❌ Analytics API failed: {response.status_code}")
138
- except:
139
- print("❌ Analytics API: Connection failed")
140
-
141
- try:
142
- # Test heatmap API
143
- response = requests.get("http://localhost:8080/api/v1/heatmap/data", timeout=5)
144
- if response.status_code == 200:
145
- data = response.json()
146
- print(f"✅ Heatmap API: {data['total_states']} states with data")
147
- else:
148
- print(f"❌ Heatmap API failed: {response.status_code}")
149
- except:
150
- print("❌ Heatmap API: Connection failed")
151
-
152
- print(f"\n🎉 SYSTEM STATUS: FULLY OPERATIONAL")
153
- print("=" * 50)
154
- print("✅ High-volume RSS ingestion working")
155
- print("✅ Advanced ML classification active")
156
- print("✅ Real-time state mapping functional")
157
- print("✅ Comprehensive Indian coverage achieved")
158
- print("✅ Web interface responding")
159
- print("✅ Database aggregations updating")
160
-
161
- print(f"\n🌐 ACCESS THE SYSTEM:")
162
- print("📊 Dashboard: http://localhost:8080")
163
- print("🗺️ Heatmap: http://localhost:8080/heatmap")
164
- print("📖 API Docs: http://localhost:8080/docs")
165
-
166
- return True
167
-
168
- except Exception as e:
169
- print(f"❌ Test failed: {e}")
170
- return False
171
-
172
- if __name__ == "__main__":
173
- test_production_system()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_enhanced_system.py DELETED
@@ -1,186 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Test script for Enhanced Real-Time Misinformation Heatmap
4
- """
5
-
6
- import sqlite3
7
- import json
8
- from datetime import datetime
9
-
10
- def test_database():
11
- """Test if the database is working and has data"""
12
- try:
13
- conn = sqlite3.connect('enhanced_heatmap.db')
14
- cursor = conn.cursor()
15
-
16
- # Check events table
17
- cursor.execute("SELECT COUNT(*) FROM events")
18
- event_count = cursor.fetchone()[0]
19
-
20
- # Check state content table
21
- cursor.execute("SELECT COUNT(*) FROM state_content WHERE total_events > 0")
22
- active_states = cursor.fetchone()[0]
23
-
24
- # Get sample events
25
- cursor.execute("SELECT title, state, misinformation_score, source FROM events LIMIT 5")
26
- sample_events = cursor.fetchall()
27
-
28
- conn.close()
29
-
30
- print("🔍 Enhanced System Database Test Results")
31
- print("=" * 50)
32
- print(f"📊 Total Events Processed: {event_count}")
33
- print(f"🗺️ Active States: {active_states}")
34
- print(f"📈 Sample Events:")
35
-
36
- for i, (title, state, score, source) in enumerate(sample_events, 1):
37
- risk_level = "🔴 High" if score > 0.7 else "🟡 Medium" if score > 0.4 else "🟢 Low"
38
- print(f" {i}. {title[:60]}...")
39
- print(f" State: {state} | Risk: {risk_level} ({score:.2f}) | Source: {source}")
40
-
41
- return True
42
-
43
- except Exception as e:
44
- print(f"❌ Database test failed: {e}")
45
- return False
46
-
47
- def test_rss_ingestion():
48
- """Test RSS ingestion functionality"""
49
- try:
50
- conn = sqlite3.connect('enhanced_heatmap.db')
51
- cursor = conn.cursor()
52
-
53
- # Check recent events (last hour)
54
- cursor.execute("""
55
- SELECT COUNT(*) FROM events
56
- WHERE timestamp >= datetime('now', '-1 hour')
57
- """)
58
- recent_events = cursor.fetchone()[0]
59
-
60
- # Check source diversity
61
- cursor.execute("SELECT DISTINCT source FROM events")
62
- sources = [row[0] for row in cursor.fetchall()]
63
-
64
- conn.close()
65
-
66
- print("\n📡 RSS Ingestion Test Results")
67
- print("=" * 50)
68
- print(f"🕐 Recent Events (last hour): {recent_events}")
69
- print(f"📰 Active Sources: {len(sources)}")
70
- print(" Sources:", ", ".join(sources))
71
-
72
- return recent_events > 0
73
-
74
- except Exception as e:
75
- print(f"❌ RSS ingestion test failed: {e}")
76
- return False
77
-
78
- def test_ai_analysis():
79
- """Test AI analysis functionality"""
80
- try:
81
- conn = sqlite3.connect('enhanced_heatmap.db')
82
- cursor = conn.cursor()
83
-
84
- # Check analysis completeness
85
- cursor.execute("""
86
- SELECT
87
- AVG(misinformation_score) as avg_score,
88
- COUNT(*) as total,
89
- SUM(CASE WHEN misinformation_score > 0.7 THEN 1 ELSE 0 END) as high_risk
90
- FROM events
91
- """)
92
-
93
- avg_score, total, high_risk = cursor.fetchone()
94
-
95
- # Check sentiment analysis
96
- cursor.execute("SELECT DISTINCT sentiment FROM events WHERE sentiment IS NOT NULL")
97
- sentiments = [row[0] for row in cursor.fetchall()]
98
-
99
- conn.close()
100
-
101
- print("\n🧠 AI Analysis Test Results")
102
- print("=" * 50)
103
- print(f"📊 Average Misinformation Score: {avg_score:.3f}")
104
- print(f"🔴 High Risk Events: {high_risk}/{total} ({(high_risk/total*100):.1f}%)")
105
- print(f"😊 Sentiment Analysis: {', '.join(sentiments) if sentiments else 'Fallback mode'}")
106
-
107
- return True
108
-
109
- except Exception as e:
110
- print(f"❌ AI analysis test failed: {e}")
111
- return False
112
-
113
- def test_state_content():
114
- """Test state-specific content functionality"""
115
- try:
116
- conn = sqlite3.connect('enhanced_heatmap.db')
117
- cursor = conn.cursor()
118
-
119
- # Get top states by activity
120
- cursor.execute("""
121
- SELECT state, total_events, high_risk_events, avg_misinformation_score
122
- FROM state_content
123
- WHERE total_events > 0
124
- ORDER BY total_events DESC
125
- LIMIT 5
126
- """)
127
-
128
- top_states = cursor.fetchall()
129
-
130
- conn.close()
131
-
132
- print("\n🗺️ State Content Test Results")
133
- print("=" * 50)
134
- print("📍 Top Active States:")
135
-
136
- for state, total, high_risk, avg_score in top_states:
137
- risk_level = "🔴 High" if avg_score > 0.7 else "🟡 Medium" if avg_score > 0.4 else "🟢 Low"
138
- print(f" • {state}: {total} events ({high_risk} high-risk) - {risk_level}")
139
-
140
- return len(top_states) > 0
141
-
142
- except Exception as e:
143
- print(f"❌ State content test failed: {e}")
144
- return False
145
-
146
- def main():
147
- """Run all tests"""
148
- print("🚀 Enhanced Real-Time Misinformation Heatmap - System Test")
149
- print("=" * 70)
150
-
151
- tests = [
152
- ("Database Functionality", test_database),
153
- ("RSS Ingestion", test_rss_ingestion),
154
- ("AI Analysis", test_ai_analysis),
155
- ("State Content", test_state_content)
156
- ]
157
-
158
- results = []
159
- for test_name, test_func in tests:
160
- try:
161
- result = test_func()
162
- results.append(result)
163
- except Exception as e:
164
- print(f"❌ {test_name} test crashed: {e}")
165
- results.append(False)
166
-
167
- print("\n" + "=" * 70)
168
- print("📋 Test Summary")
169
- print("=" * 70)
170
-
171
- for i, (test_name, _) in enumerate(tests):
172
- status = "✅ PASS" if results[i] else "❌ FAIL"
173
- print(f"{status} {test_name}")
174
-
175
- overall = "✅ ALL TESTS PASSED" if all(results) else "⚠️ SOME TESTS FAILED"
176
- print(f"\n🎯 Overall Status: {overall}")
177
-
178
- if all(results):
179
- print("\n🎉 Enhanced system is working perfectly!")
180
- print("🌐 Access the dashboard at: http://localhost:8080")
181
- print("🗺️ View the heatmap at: http://localhost:8080/heatmap")
182
- else:
183
- print("\n🔧 Some components need attention. Check the logs above.")
184
-
185
- if __name__ == "__main__":
186
- main()