File size: 3,656 Bytes
68e9069
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# test_quick.py
import sys
import os
from pathlib import Path

# Agregar el directorio actual al path
sys.path.append(str(Path(__file__).parent))

from backend.converters.converter_engine import convert_file

def test_conversion():
    """Prueba rápida de conversión"""
    print("🚀 Probando conversión CSV → JSON...")
    
    # Usar ruta absoluta para asegurar que encuentra el archivo
    current_dir = Path(__file__).parent
    
    # Buscar cualquier archivo que empiece con 'test.csv'
    csv_files = list(current_dir.glob("test.csv*"))
    
    if not csv_files:
        print("❌ No se encontró test.csv. Creándolo...")
        csv_path = current_dir / "test.csv"
        csv_path.write_text("""id,name,age,city
1,Alice,25,Madrid
2,Bob,30,Barcelona
3,Charlie,35,Valencia
4,Diana,28,Sevilla
5,Eve,32,Bilbao""")
        print("✅ Archivo test.csv creado")
        csv_files = [csv_path]
    else:
        csv_path = csv_files[0]
        print(f"✅ Encontrado archivo: {csv_path.name}")
    
    # Limpiar el nombre del archivo (quitar espacios)
    clean_path = current_dir / "test_clean.csv"
    if " " in csv_path.name:
        # Copiar el archivo con nombre limpio
        clean_path.write_text(csv_path.read_text())
        csv_path = clean_path
        print("✅ Archivo limpiado (sin espacios)")
    
    try:
        # Convertir test.csv a JSON
        json_path = convert_file(str(csv_path), ".json")
        print(f"✅ Conversión exitosa!")
        print(f"📁 Archivo JSON generado: {json_path}")
        
        # Mostrar contenido del JSON
        with open(json_path, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"📊 Contenido (primeros 500 chars):")
            print(content[:500] + "..." if len(content) > 500 else content)
            
        # Limpiar archivo temporal si se creó
        if clean_path.exists():
            clean_path.unlink()
            
    except Exception as e:
        print(f"❌ Error: {e}")
        # Limpiar archivo temporal si existe
        if clean_path.exists():
            clean_path.unlink()

def test_all_conversions():
    """Probar todas las conversiones soportadas"""
    print("\n" + "="*50)
    print("🧪 PROBANDO TODAS LAS CONVERSIONES")
    print("="*50)
    
    current_dir = Path(__file__).parent
    
    # Buscar archivo test.csv
    csv_files = list(current_dir.glob("test.csv*"))
    if not csv_files:
        print("❌ No se encontró test.csv")
        return
    
    csv_path = csv_files[0]
    
    # Limpiar nombre si tiene espacios
    clean_path = current_dir / "test_clean.csv"
    if " " in csv_path.name:
        clean_path.write_text(csv_path.read_text())
        csv_path = clean_path
    
    conversions = [
        ('.json', 'JSON'),
        ('.xlsx', 'Excel'),
        ('.txt', 'Texto')
    ]
    
    for format_ext, format_name in conversions:
        try:
            print(f"\n🔄 Convirtiendo a {format_name}...")
            output_path = convert_file(str(csv_path), format_ext)
            print(f"✅ {format_name}: {output_path}")
            
            # Verificar que el archivo se creó
            if Path(output_path).exists():
                file_size = Path(output_path).stat().st_size
                print(f"   📏 Tamaño: {file_size} bytes")
            else:
                print("   ❌ Archivo no se creó")
                
        except Exception as e:
            print(f"❌ Error en {format_name}: {e}")
    
    # Limpiar archivo temporal
    if clean_path.exists():
        clean_path.unlink()

if __name__ == "__main__":
    test_conversion()
    test_all_conversions()