Model-config web apps: describe the app in configuration instead of writing code. Built on Polars and DuckDB.
test_crud_engine_api.py · 11.7 KB · 354 lines
| 1 | #!/usr/bin/env python3 |
| 2 | """ |
| 3 | Comprehensive API Tests for DBBasic CRUD Engine |
| 4 | |
| 5 | Tests all CRUD operations, configuration loading, error handling, |
| 6 | and integration with AI Service Builder hooks. |
| 7 | """ |
| 8 | |
| 9 | import pytest |
| 10 | import requests |
| 11 | import json |
| 12 | import time |
| 13 | import os |
| 14 | import tempfile |
| 15 | import yaml |
| 16 | from pathlib import Path |
| 17 | |
| 18 | BASE_URL = "http://localhost:8005" |
| 19 | |
| 20 | class TestCRUDEngineAPI: |
| 21 | """Test suite for CRUD Engine API functionality""" |
| 22 | |
| 23 | @classmethod |
| 24 | def setup_class(cls): |
| 25 | """Setup test environment""" |
| 26 | # Wait for CRUD Engine to be ready |
| 27 | max_retries = 30 |
| 28 | for i in range(max_retries): |
| 29 | try: |
| 30 | response = requests.get(f"{BASE_URL}/") |
| 31 | if response.status_code == 200: |
| 32 | print("✅ CRUD Engine is ready") |
| 33 | break |
| 34 | except requests.ConnectionError: |
| 35 | if i == max_retries - 1: |
| 36 | raise Exception("❌ CRUD Engine not accessible after 30 seconds") |
| 37 | time.sleep(1) |
| 38 | |
| 39 | def test_dashboard_loads(self): |
| 40 | """Test that dashboard loads successfully""" |
| 41 | response = requests.get(f"{BASE_URL}/") |
| 42 | assert response.status_code == 200 |
| 43 | assert "DBBasic CRUD Dashboard" in response.text |
| 44 | print("✅ Dashboard loads successfully") |
| 45 | |
| 46 | def test_customers_resource_exists(self): |
| 47 | """Test that customers resource is loaded""" |
| 48 | response = requests.get(f"{BASE_URL}/customers") |
| 49 | assert response.status_code == 200 |
| 50 | assert "Customers Management" in response.text |
| 51 | print("✅ Customers resource interface loads") |
| 52 | |
| 53 | def test_api_list_customers_empty(self): |
| 54 | """Test listing customers when empty""" |
| 55 | response = requests.get(f"{BASE_URL}/api/customers") |
| 56 | assert response.status_code == 200 |
| 57 | data = response.json() |
| 58 | assert "records" in data |
| 59 | assert isinstance(data["records"], list) |
| 60 | print(f"✅ Empty customers list: {len(data['records'])} records") |
| 61 | |
| 62 | def test_api_create_customer_minimal(self): |
| 63 | """Test creating a customer with minimal data""" |
| 64 | customer_data = { |
| 65 | "name": "Test Customer", |
| 66 | "email": "test@example.com" |
| 67 | } |
| 68 | |
| 69 | response = requests.post( |
| 70 | f"{BASE_URL}/api/customers", |
| 71 | json=customer_data, |
| 72 | headers={"Content-Type": "application/json"} |
| 73 | ) |
| 74 | |
| 75 | # Should fail due to hooks, but test the flow |
| 76 | print(f"📊 Create customer response: {response.status_code}") |
| 77 | print(f"📊 Response: {response.text}") |
| 78 | |
| 79 | # Either succeeds (200) or fails due to missing hook service (500) |
| 80 | assert response.status_code in [200, 500] |
| 81 | |
| 82 | if response.status_code == 500: |
| 83 | # Should indicate hook service not found |
| 84 | assert "validate_business_rules" in response.text or "Hook" in response.text |
| 85 | print("✅ Hook system correctly detected missing service") |
| 86 | else: |
| 87 | # Success - verify data |
| 88 | data = response.json() |
| 89 | assert data["name"] == customer_data["name"] |
| 90 | assert data["email"] == customer_data["email"] |
| 91 | print("✅ Customer created successfully") |
| 92 | |
| 93 | def test_api_create_customer_full(self): |
| 94 | """Test creating a customer with full data""" |
| 95 | customer_data = { |
| 96 | "name": "John Doe", |
| 97 | "email": "john.doe@example.com", |
| 98 | "phone": "555-0123", |
| 99 | "credit_limit": 5000, |
| 100 | "status": "active" |
| 101 | } |
| 102 | |
| 103 | response = requests.post( |
| 104 | f"{BASE_URL}/api/customers", |
| 105 | json=customer_data, |
| 106 | headers={"Content-Type": "application/json"} |
| 107 | ) |
| 108 | |
| 109 | print(f"📊 Full customer creation: {response.status_code}") |
| 110 | # Hook system should trigger |
| 111 | assert response.status_code in [200, 500] |
| 112 | print("✅ Full customer creation handled") |
| 113 | |
| 114 | def test_api_validation_errors(self): |
| 115 | """Test validation error handling""" |
| 116 | # Test missing required field |
| 117 | invalid_data = { |
| 118 | "email": "missing-name@example.com" |
| 119 | } |
| 120 | |
| 121 | response = requests.post( |
| 122 | f"{BASE_URL}/api/customers", |
| 123 | json=invalid_data, |
| 124 | headers={"Content-Type": "application/json"} |
| 125 | ) |
| 126 | |
| 127 | # Should fail validation or hook processing |
| 128 | assert response.status_code in [400, 422, 500] |
| 129 | print("✅ Validation errors handled properly") |
| 130 | |
| 131 | def test_api_duplicate_email(self): |
| 132 | """Test duplicate email handling""" |
| 133 | customer_data = { |
| 134 | "name": "Duplicate Test", |
| 135 | "email": "duplicate@example.com" |
| 136 | } |
| 137 | |
| 138 | # Try to create same email twice |
| 139 | response1 = requests.post( |
| 140 | f"{BASE_URL}/api/customers", |
| 141 | json=customer_data, |
| 142 | headers={"Content-Type": "application/json"} |
| 143 | ) |
| 144 | |
| 145 | response2 = requests.post( |
| 146 | f"{BASE_URL}/api/customers", |
| 147 | json=customer_data, |
| 148 | headers={"Content-Type": "application/json"} |
| 149 | ) |
| 150 | |
| 151 | print(f"📊 First creation: {response1.status_code}") |
| 152 | print(f"📊 Duplicate creation: {response2.status_code}") |
| 153 | |
| 154 | # At least one should indicate constraint violation |
| 155 | assert response1.status_code in [200, 500] or response2.status_code in [400, 409, 500] |
| 156 | print("✅ Duplicate email constraint handled") |
| 157 | |
| 158 | class TestCRUDEngineConfig: |
| 159 | """Test configuration loading and hot reload""" |
| 160 | |
| 161 | def create_test_config(self, resource_name="test_products"): |
| 162 | """Create a test configuration file""" |
| 163 | config = { |
| 164 | "resource": resource_name, |
| 165 | "database": f"{resource_name}.db", |
| 166 | "fields": { |
| 167 | "id": {"type": "primary_key"}, |
| 168 | "name": { |
| 169 | "type": "string", |
| 170 | "required": True, |
| 171 | "searchable": True, |
| 172 | "max_length": 100 |
| 173 | }, |
| 174 | "price": { |
| 175 | "type": "decimal", |
| 176 | "min": 0, |
| 177 | "max": 99999.99 |
| 178 | }, |
| 179 | "category": { |
| 180 | "type": "select", |
| 181 | "options": ["electronics", "books", "clothing"], |
| 182 | "default": "electronics" |
| 183 | }, |
| 184 | "created_at": { |
| 185 | "type": "timestamp", |
| 186 | "auto_now_add": True |
| 187 | } |
| 188 | }, |
| 189 | "interface": { |
| 190 | "list_display": ["name", "price", "category", "created_at"], |
| 191 | "search_fields": ["name"], |
| 192 | "filters": ["category", "created_at"], |
| 193 | "per_page": 10 |
| 194 | }, |
| 195 | "permissions": { |
| 196 | "create": "authenticated", |
| 197 | "read": "public", |
| 198 | "update": "authenticated", |
| 199 | "delete": "admin_only" |
| 200 | }, |
| 201 | "api": { |
| 202 | "base_path": f"/api/{resource_name}", |
| 203 | "enable_bulk": True, |
| 204 | "enable_export": True |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | config_file = f"{resource_name}_crud.yaml" |
| 209 | with open(config_file, 'w') as f: |
| 210 | yaml.dump(config, f, default_flow_style=False) |
| 211 | |
| 212 | return config_file |
| 213 | |
| 214 | def test_config_loading(self): |
| 215 | """Test that new config files are loaded""" |
| 216 | config_file = self.create_test_config("test_products") |
| 217 | |
| 218 | try: |
| 219 | # Wait for file watcher to detect new config |
| 220 | time.sleep(3) |
| 221 | |
| 222 | # Test that new resource is available |
| 223 | response = requests.get(f"{BASE_URL}/test_products") |
| 224 | print(f"📊 New resource response: {response.status_code}") |
| 225 | |
| 226 | if response.status_code == 200: |
| 227 | assert "Test Products Management" in response.text or "test_products" in response.text.lower() |
| 228 | print("✅ New config loaded successfully") |
| 229 | else: |
| 230 | print("⚠️ Config hot reload may need manual restart") |
| 231 | |
| 232 | finally: |
| 233 | # Cleanup |
| 234 | if os.path.exists(config_file): |
| 235 | os.remove(config_file) |
| 236 | |
| 237 | def test_config_validation(self): |
| 238 | """Test configuration validation""" |
| 239 | # Create invalid config |
| 240 | invalid_config = { |
| 241 | "resource": "invalid_test", |
| 242 | "fields": { |
| 243 | # Missing required field structure |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | config_file = "invalid_test_crud.yaml" |
| 248 | try: |
| 249 | with open(config_file, 'w') as f: |
| 250 | yaml.dump(invalid_config, f) |
| 251 | |
| 252 | time.sleep(2) |
| 253 | |
| 254 | # Should not create invalid resource |
| 255 | response = requests.get(f"{BASE_URL}/invalid_test") |
| 256 | assert response.status_code == 404 |
| 257 | print("✅ Invalid config rejected") |
| 258 | |
| 259 | finally: |
| 260 | if os.path.exists(config_file): |
| 261 | os.remove(config_file) |
| 262 | |
| 263 | class TestCRUDEngineIntegration: |
| 264 | """Test integration with other services""" |
| 265 | |
| 266 | def test_ai_service_builder_integration(self): |
| 267 | """Test that missing hooks trigger AI service requests""" |
| 268 | # This test validates the hook detection logic |
| 269 | customer_data = { |
| 270 | "name": "Hook Test Customer", |
| 271 | "email": "hooktest@example.com" |
| 272 | } |
| 273 | |
| 274 | response = requests.post( |
| 275 | f"{BASE_URL}/api/customers", |
| 276 | json=customer_data, |
| 277 | headers={"Content-Type": "application/json"} |
| 278 | ) |
| 279 | |
| 280 | # Should detect missing hook service |
| 281 | if response.status_code == 500: |
| 282 | error_text = response.text |
| 283 | if "validate_business_rules" in error_text: |
| 284 | print("✅ AI Service Builder integration: Hook detection working") |
| 285 | else: |
| 286 | print(f"📊 Hook response: {error_text}") |
| 287 | else: |
| 288 | print("📊 No hook errors - may be working with generated services") |
| 289 | |
| 290 | def test_real_time_monitor_integration(self): |
| 291 | """Test that CRUD operations can send events to real-time monitor""" |
| 292 | # Test if real-time monitor is accessible |
| 293 | try: |
| 294 | monitor_response = requests.get("http://localhost:8004") |
| 295 | if monitor_response.status_code == 200: |
| 296 | print("✅ Real-time Monitor accessible for integration") |
| 297 | else: |
| 298 | print("⚠️ Real-time Monitor not accessible") |
| 299 | except requests.ConnectionError: |
| 300 | print("⚠️ Real-time Monitor not running") |
| 301 | |
| 302 | def run_api_tests(): |
| 303 | """Run all API tests""" |
| 304 | print("🚀 Starting CRUD Engine API Tests") |
| 305 | print("=" * 50) |
| 306 | |
| 307 | # Test basic functionality |
| 308 | test_basic = TestCRUDEngineAPI() |
| 309 | test_basic.setup_class() |
| 310 | |
| 311 | try: |
| 312 | test_basic.test_dashboard_loads() |
| 313 | test_basic.test_customers_resource_exists() |
| 314 | test_basic.test_api_list_customers_empty() |
| 315 | test_basic.test_api_create_customer_minimal() |
| 316 | test_basic.test_api_create_customer_full() |
| 317 | test_basic.test_api_validation_errors() |
| 318 | test_basic.test_api_duplicate_email() |
| 319 | |
| 320 | print("\n📋 Basic API Tests: ✅ PASSED") |
| 321 | |
| 322 | except Exception as e: |
| 323 | print(f"\n❌ Basic API Tests FAILED: {e}") |
| 324 | return False |
| 325 | |
| 326 | # Test configuration |
| 327 | test_config = TestCRUDEngineConfig() |
| 328 | try: |
| 329 | test_config.test_config_loading() |
| 330 | test_config.test_config_validation() |
| 331 | |
| 332 | print("📋 Configuration Tests: ✅ PASSED") |
| 333 | |
| 334 | except Exception as e: |
| 335 | print(f"❌ Configuration Tests FAILED: {e}") |
| 336 | |
| 337 | # Test integration |
| 338 | test_integration = TestCRUDEngineIntegration() |
| 339 | try: |
| 340 | test_integration.test_ai_service_builder_integration() |
| 341 | test_integration.test_real_time_monitor_integration() |
| 342 | |
| 343 | print("📋 Integration Tests: ✅ PASSED") |
| 344 | |
| 345 | except Exception as e: |
| 346 | print(f"❌ Integration Tests FAILED: {e}") |
| 347 | |
| 348 | print("\n" + "=" * 50) |
| 349 | print("✅ CRUD Engine API Testing Complete!") |
| 350 | return True |
| 351 | |
| 352 | if __name__ == "__main__": |
| 353 | success = run_api_tests() |
| 354 | exit(0 if success else 1) |