Spaces:
				
			
			
	
			
			
		Paused
		
	
	
	
			
			
	
	
	
	
		
		
		Paused
		
	File size: 8,834 Bytes
			
			| c636ebf | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | #!/usr/bin/env python3
"""
Basic Analytics Test Suite
=========================
Simple test suite for core analytics functionality without heavy dependencies.
"""
from app.services.cache_service import cache_service
from app.services.database_service import DatabaseManager
import asyncio
import sys
import os
import json
from datetime import datetime, timedelta
from typing import Dict, List, Any
# Add the app directory to the path
sys.path.append(os.path.join(os.path.dirname(__file__), 'app'))
class BasicAnalyticsTester:
    """Basic tester for core analytics features"""
    def __init__(self):
        self.db_manager = DatabaseManager()
        self.test_results = {
            "total_tests": 0,
            "passed": 0,
            "failed": 0,
            "errors": []
        }
    async def run_all_tests(self):
        """Run all basic analytics tests"""
        print("π Basic Analytics Test Suite")
        print("=" * 50)
        try:
            # Test database connectivity
            await self.test_database_connectivity()
            # Test cache functionality
            await self.test_cache_functionality()
            # Test basic metrics calculation
            await self.test_basic_metrics()
            # Test document operations
            await self.test_document_operations()
            # Generate test report
            self.generate_test_report()
        except Exception as e:
            print(f"β Test suite failed: {e}")
            import traceback
            traceback.print_exc()
    async def test_database_connectivity(self):
        """Test database connectivity and basic operations"""
        print("\nποΈ Testing Database Connectivity...")
        try:
            # Test database connection
            is_connected = self.db_manager.is_connected()
            assert is_connected, "Database should be connected"
            # Test basic statistics
            stats = self.db_manager.get_document_statistics()
            assert isinstance(stats, dict), "Statistics should be a dictionary"
            print(f"β
 Database connectivity test passed")
            print(f"   - Connected: {is_connected}")
            print(f"   - Statistics keys: {list(stats.keys())}")
            self.test_results["passed"] += 1
        except Exception as e:
            print(f"β Database connectivity test failed: {e}")
            self.test_results["failed"] += 1
            self.test_results["errors"].append(f"Database connectivity: {e}")
        self.test_results["total_tests"] += 1
    async def test_cache_functionality(self):
        """Test cache functionality"""
        print("\nβ‘ Testing Cache Functionality...")
        try:
            # Test cache operations
            test_key = "test_analytics_key"
            test_data = {"test": "data",
                         "timestamp": datetime.now().isoformat()}
            # Set cache data
            await cache_service.set(test_key, test_data, expire=60)
            # Get cache data
            cached_data = await cache_service.get(test_key)
            assert cached_data == test_data, "Cached data should match original data"
            # Test cache stats
            cache_stats = await cache_service.get_stats()
            assert isinstance(
                cache_stats, dict), "Cache stats should be a dictionary"
            print(f"β
 Cache functionality test passed")
            print(
                f"   - Cache hit rate: {cache_stats.get('hit_rate', 0):.1f}%")
            self.test_results["passed"] += 1
        except Exception as e:
            print(f"β Cache functionality test failed: {e}")
            self.test_results["failed"] += 1
            self.test_results["errors"].append(f"Cache functionality: {e}")
        self.test_results["total_tests"] += 1
    async def test_basic_metrics(self):
        """Test basic metrics calculation"""
        print("\nπ Testing Basic Metrics...")
        try:
            # Get document statistics
            stats = self.db_manager.get_document_statistics()
            # Test basic metric calculations
            total_docs = stats.get('total_documents', 0)
            assert isinstance(
                total_docs, int), "Total documents should be an integer"
            assert total_docs >= 0, "Total documents should be non-negative"
            # Test quality metrics
            quality_metrics = stats.get('quality_metrics', {})
            assert isinstance(
                quality_metrics, dict), "Quality metrics should be a dictionary"
            # Test category distribution
            category_dist = stats.get('category_distribution', {})
            assert isinstance(
                category_dist, dict), "Category distribution should be a dictionary"
            print(f"β
 Basic metrics test passed")
            print(f"   - Total documents: {total_docs}")
            print(f"   - Quality metrics: {len(quality_metrics)}")
            print(f"   - Categories: {len(category_dist)}")
            self.test_results["passed"] += 1
        except Exception as e:
            print(f"β Basic metrics test failed: {e}")
            self.test_results["failed"] += 1
            self.test_results["errors"].append(f"Basic metrics: {e}")
        self.test_results["total_tests"] += 1
    async def test_document_operations(self):
        """Test document operations"""
        print("\nπ Testing Document Operations...")
        try:
            # Test getting all documents
            all_docs = self.db_manager.get_all_documents()
            assert isinstance(all_docs, list), "All documents should be a list"
            # Test getting documents by date
            today = datetime.now().date()
            today_docs = self.db_manager.get_documents_by_date(today)
            assert isinstance(
                today_docs, list), "Today's documents should be a list"
            # Test getting processing times
            processing_times = self.db_manager.get_processing_times()
            assert isinstance(processing_times,
                              list), "Processing times should be a list"
            print(f"β
 Document operations test passed")
            print(f"   - Total documents: {len(all_docs)}")
            print(f"   - Today's documents: {len(today_docs)}")
            print(f"   - Processing times: {len(processing_times)}")
            self.test_results["passed"] += 1
        except Exception as e:
            print(f"β Document operations test failed: {e}")
            self.test_results["failed"] += 1
            self.test_results["errors"].append(f"Document operations: {e}")
        self.test_results["total_tests"] += 1
    def generate_test_report(self):
        """Generate comprehensive test report"""
        print("\n" + "=" * 50)
        print("π Basic Analytics Test Report")
        print("=" * 50)
        success_rate = (self.test_results["passed"] / self.test_results["total_tests"] * 100) \
            if self.test_results["total_tests"] > 0 else 0
        print(f"π Test Summary:")
        print(f"   - Total tests: {self.test_results['total_tests']}")
        print(f"   - Passed: {self.test_results['passed']}")
        print(f"   - Failed: {self.test_results['failed']}")
        print(f"   - Success rate: {success_rate:.1f}%")
        if self.test_results["errors"]:
            print(f"\nβ Errors encountered:")
            for error in self.test_results["errors"]:
                print(f"   - {error}")
        # Save test results
        test_report = {
            "timestamp": datetime.now().isoformat(),
            "test_results": self.test_results,
            "success_rate": success_rate
        }
        with open("basic_analytics_test_report.json", "w", encoding="utf-8") as f:
            json.dump(test_report, f, indent=2, ensure_ascii=False)
        print(f"\nπ Test report saved to: basic_analytics_test_report.json")
        if success_rate >= 90:
            print("π All tests passed! Basic analytics system is working correctly.")
        elif success_rate >= 70:
            print("β οΈ Most tests passed. Some issues need attention.")
        else:
            print("β Multiple test failures detected. System needs fixes.")
        return success_rate >= 90
async def main():
    """Main test runner"""
    tester = BasicAnalyticsTester()
    success = await tester.run_all_tests()
    return 0 if success else 1
if __name__ == "__main__":
    exit_code = asyncio.run(main())
    sys.exit(exit_code)
 |