#!/usr/bin/env python3 """ TSNet Phase 2 - Test Directo sin MCP Test directo de funcionalidad TSNet mediante ejecución local """ import subprocess import time import os from datetime import datetime def run_csharp_test(test_name, code): """Ejecutar código C# directamente usando dotnet script""" print(f"\n🧪 Testing: {test_name}") # Crear archivo temporal de test test_file = f"temp_test_{int(time.time())}.csx" full_code = f""" #r "d:\\Proyectos\\VisualStudio\\CtrEditor\\bin\\Debug\\net8.0-windows8.0\\CtrEditor.dll" #r "d:\\Proyectos\\VisualStudio\\CtrEditor\\bin\\Debug\\net8.0-windows8.0\\CommunityToolkit.Mvvm.dll" using System; using CtrEditor.ObjetosSim; using CtrEditor.HydraulicSimulator.TSNet; using CtrEditor.HydraulicSimulator.TSNet.Components; try {{ Console.WriteLine("=== {test_name} ==="); {code} Console.WriteLine("✅ Test PASSED"); }} catch (Exception ex) {{ Console.WriteLine($"❌ Test FAILED: {{ex.Message}}"); Console.WriteLine($"Stack trace: {{ex.StackTrace}}"); }} """ try: with open(test_file, "w", encoding="utf-8") as f: f.write(full_code) # Ejecutar con dotnet script result = subprocess.run( ["dotnet", "script", test_file], capture_output=True, text=True, timeout=30, cwd="d:\\Proyectos\\VisualStudio\\CtrEditor", ) print(f"Exit code: {result.returncode}") if result.stdout: print("Output:", result.stdout) if result.stderr: print("Errors:", result.stderr) return result.returncode == 0 except Exception as e: print(f"❌ Test execution failed: {e}") return False finally: # Limpiar archivo temporal if os.path.exists(test_file): os.remove(test_file) def test_1_basic_object_creation(): """Test 1: Creación básica de objetos hidráulicos""" code = """ // Test creación de objetos hidráulicos básicos var tank = new osHydTank(); Console.WriteLine($"Tank created: {tank != null}"); var pump = new osHydPump(); Console.WriteLine($"Pump created: {pump != null}"); var pipe = new osHydPipe(); Console.WriteLine($"Pipe created: {pipe != null}"); Console.WriteLine("Basic object creation successful"); """ return run_csharp_test("Basic Object Creation", code) def test_2_checkdata_initialization(): """Test 2: Inicialización con CheckData""" code = """ // Test inicialización correcta de IDs var tank = new osHydTank(); Console.WriteLine($"Tank ID before CheckData: {tank.Id?.Value}"); tank.CheckData(); Console.WriteLine($"Tank ID after CheckData: {tank.Id?.Value}"); if (tank.Id?.Value > 0) { Console.WriteLine("CheckData initialization successful"); } else { throw new Exception("CheckData failed to initialize ID"); } """ return run_csharp_test("CheckData Initialization", code) def test_3_adapter_creation_with_valid_id(): """Test 3: Creación de adaptador con ID válido""" code = """ // Test creación de adaptador con ID válido var tank = new osHydTank(); tank.CheckData(); // Asegurar ID válido var adapter = new TSNetTankAdapter(tank); Console.WriteLine($"Adapter created with TankId: {adapter.TankId}"); if (adapter.TankId.StartsWith("TANK_")) { Console.WriteLine("Adapter creation with valid ID successful"); } else { throw new Exception($"Invalid adapter ID format: {adapter.TankId}"); } """ return run_csharp_test("Adapter Creation with Valid ID", code) def test_4_adapter_creation_without_id(): """Test 4: Prevención de NullReference sin ID""" code = """ // Test prevención de NullReference var tank = new osHydTank(); // NO llamar CheckData() intencionalmente try { var adapter = new TSNetTankAdapter(tank); throw new Exception("Should have failed with null ID validation"); } catch (InvalidOperationException ex) { if (ex.Message.Contains("Id válido")) { Console.WriteLine("Proper validation error caught - NullReference prevention working"); } else { throw new Exception($"Wrong exception type: {ex.Message}"); } } catch (Exception ex) { throw new Exception($"Unexpected exception: {ex.GetType().Name}: {ex.Message}"); } """ return run_csharp_test("NullReference Prevention", code) def test_5_configuration_capture(): """Test 5: Captura de configuración""" code = """ // Test captura de configuración var tank = new osHydTank(); tank.CheckData(); tank.MinLevelM = 0.5; tank.MaxLevelM = 3.0; tank.CurrentLevelM = 1.5; var adapter = new TSNetTankAdapter(tank); adapter.CaptureConfigurationForSimulation(); Console.WriteLine($"Configuration captured: {adapter.Configuration != null}"); Console.WriteLine($"MinLevel: {adapter.Configuration?.MinLevelM}"); Console.WriteLine($"MaxLevel: {adapter.Configuration?.MaxLevelM}"); Console.WriteLine($"InitialLevel: {adapter.Configuration?.InitialLevelM}"); if (adapter.Configuration != null && adapter.Configuration.MinLevelM == 0.5 && adapter.Configuration.MaxLevelM == 3.0) { Console.WriteLine("Configuration capture successful"); } else { throw new Exception("Configuration capture failed"); } """ return run_csharp_test("Configuration Capture", code) def test_6_configuration_validation(): """Test 6: Validación de configuración""" code = """ // Test validación con valores inválidos var tank = new osHydTank(); tank.CheckData(); tank.MinLevelM = -1.0; // Valor inválido tank.MaxLevelM = 0.5; // Menor que min (inválido) var adapter = new TSNetTankAdapter(tank); adapter.CaptureConfigurationForSimulation(); var errors = adapter.ValidateConfiguration(); Console.WriteLine($"Validation errors found: {errors.Count}"); foreach (var error in errors) { Console.WriteLine($"Error: {error}"); } if (errors.Count >= 2) { Console.WriteLine("Configuration validation working correctly"); } else { throw new Exception($"Expected at least 2 validation errors, got {errors.Count}"); } """ return run_csharp_test("Configuration Validation", code) def test_7_simulation_manager(): """Test 7: TSNetSimulationManager básico""" code = """ // Test TSNetSimulationManager var manager = new TSNetSimulationManager(); Console.WriteLine($"Simulation manager created: {manager != null}"); // Test reset manager.ResetAllCalculatedValues(); Console.WriteLine("Reset completed successfully"); Console.WriteLine("Simulation manager basic functionality working"); """ return run_csharp_test("Simulation Manager Basic", code) def run_all_tests(): """Ejecutar todos los tests directos""" print("🧪 TSNet Phase 2 - Direct Tests (No MCP Required)") print("=" * 60) print(f"Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") tests = [ test_1_basic_object_creation, test_2_checkdata_initialization, test_3_adapter_creation_with_valid_id, test_4_adapter_creation_without_id, test_5_configuration_capture, test_6_configuration_validation, test_7_simulation_manager, ] results = [] for test_func in tests: try: result = test_func() results.append(result) print(f"Result: {'✅ PASS' if result else '❌ FAIL'}") except Exception as e: print(f"❌ Test execution error: {e}") results.append(False) time.sleep(1) # Resumen print("\n" + "=" * 60) print("📊 DIRECT TESTS SUMMARY") print("=" * 60) passed = sum(results) total = len(results) print(f"Tests Executed: {total}") print(f"Passed: {passed} ✅") print(f"Failed: {total - passed} ❌") print(f"Success Rate: {passed/total*100:.1f}%") if passed == total: print("\n🎉 ALL DIRECT TESTS PASSED!") print("✅ TSNet Phase 2 core functionality is working correctly") print("✅ NullReference issues have been resolved") print("✅ Error handling is robust") elif passed >= total * 0.8: print("\n✅ Most tests passed - TSNet Phase 2 is largely functional") else: print("\n⚠️ Multiple test failures - Review implementation") print(f"\nCompleted at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") return passed == total def main(): # Verificar que dotnet está disponible try: result = subprocess.run(["dotnet", "--version"], capture_output=True, text=True) print(f"Using .NET version: {result.stdout.strip()}") except: print("❌ .NET not found - cannot run direct tests") return False return run_all_tests() if __name__ == "__main__": success = main() exit(0 if success else 1)