File size: 6,278 Bytes
d14edbf
 
 
 
 
 
 
 
 
 
 
9594324
d14edbf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Script di test per l'API di traduzione locale.
Questo script testa tutti gli endpoint principali del servizio.
"""

import requests
import json
import time

# Configurazione
BASE_URL = "http://localhost:7860"

def test_health_check():
    """Testa l'endpoint di health check."""
    print("πŸ₯ Test Health Check...")
    try:
        response = requests.get(f"{BASE_URL}/")
        print(f"Status: {response.status_code}")
        print(f"Response: {response.json()}")
        print("βœ… Health check OK\n")
        return True
    except Exception as e:
        print(f"❌ Health check failed: {e}\n")
        return False

def test_get_languages():
    """Testa l'endpoint per ottenere le lingue supportate."""
    print("🌍 Test Lingue Supportate...")
    try:
        response = requests.get(f"{BASE_URL}/languages")
        data = response.json()
        languages = data["supported_languages"]
        print(f"Status: {response.status_code}")
        print(f"Lingue supportate ({len(languages)}): {languages[:10]}...")
        print("βœ… Lingue supportate OK\n")
        return True
    except Exception as e:
        print(f"❌ Test lingue failed: {e}\n")
        return False

def test_translate_single():
    """Testa la traduzione di un singolo testo."""
    print("πŸ“ Test Traduzione Singola...")
    try:
        params = {
            "text": "Ciao mondo! Come stai oggi?",
            "target_language": "en"
        }
        response = requests.post(f"{BASE_URL}/translate-single", params=params)
        data = response.json()
        print(f"Status: {response.status_code}")
        print(f"Testo originale: {data['original_text']}")
        print(f"Testo tradotto: {data['translated_text']}")
        print("βœ… Traduzione singola OK\n")
        return True
    except Exception as e:
        print(f"❌ Test traduzione singola failed: {e}\n")
        return False

def test_translate_locales():
    """Testa la traduzione di oggetti locale complessi."""
    print("🌐 Test Traduzione Locales...")
    try:
        locale_data = {
            "locales": {
                "welcome_message": "Benvenuto nella nostra applicazione!",
                "button_save": "Salva documento",
                "error_required": "Questo campo Γ¨ obbligatorio",
                "html_content": "<p>Clicca <a href='#'>qui</a> per continuare</p>",
                "template_message": "Ciao {name}, hai {count} nuovi messaggi",
                "complex_html": "<div class='alert'><strong>Attenzione:</strong> Operazione completata con successo!</div>"
            }
        }
        
        params = {"target_language": "en"}
        response = requests.post(
            f"{BASE_URL}/translate", 
            json=locale_data, 
            params=params
        )
        
        data = response.json()
        print(f"Status: {response.status_code}")
        print("Traduzioni:")
        for key, value in data["translated_locales"].items():
            original = locale_data["locales"][key]
            print(f"  {key}:")
            print(f"    IT: {original}")
            print(f"    EN: {value}")
        
        print("βœ… Traduzione locales OK\n")
        return True
    except Exception as e:
        print(f"❌ Test traduzione locales failed: {e}\n")
        return False

def test_multiple_languages():
    """Testa la traduzione verso lingue diverse."""
    print("πŸ—£οΈ  Test Lingue Multiple...")
    try:
        locale_data = {
            "locales": {
                "greeting": "Buongiorno!",
                "goodbye": "Arrivederci!"
            }
        }
        
        languages_to_test = ["en", "fr", "de", "es"]
        
        for lang in languages_to_test:
            params = {"target_language": lang}
            response = requests.post(
                f"{BASE_URL}/translate", 
                json=locale_data, 
                params=params
            )
            
            data = response.json()
            print(f"Traduzione in {lang}:")
            for key, value in data["translated_locales"].items():
                print(f"  {key}: {value}")
        
        print("βœ… Test lingue multiple OK\n")
        return True
    except Exception as e:
        print(f"❌ Test lingue multiple failed: {e}\n")
        return False

def test_error_handling():
    """Testa la gestione degli errori."""
    print("⚠️  Test Gestione Errori...")
    try:
        # Test lingua non supportata
        locale_data = {"locales": {"test": "Ciao"}}
        params = {"target_language": "xx"}  # Lingua inesistente
        
        response = requests.post(
            f"{BASE_URL}/translate", 
            json=locale_data, 
            params=params
        )
        
        print(f"Status per lingua inesistente: {response.status_code}")
        if response.status_code == 400:
            print("βœ… Gestione errore lingua inesistente OK")
        
        # Test body malformato
        response = requests.post(
            f"{BASE_URL}/translate", 
            json={"wrong_field": "test"},
            params={"target_language": "en"}
        )
        
        print(f"Status per body malformato: {response.status_code}")
        print("βœ… Test gestione errori OK\n")
        return True
    except Exception as e:
        print(f"❌ Test gestione errori failed: {e}\n")
        return False

def main():
    """Esegue tutti i test."""
    print("πŸš€ Avvio test del Local Translation Server\n")
    print("=" * 50)
    
    tests = [
        test_health_check,
        test_get_languages,
        test_translate_single,
        test_translate_locales,
        test_multiple_languages,
        test_error_handling
    ]
    
    passed = 0
    total = len(tests)
    
    for test in tests:
        try:
            if test():
                passed += 1
            time.sleep(1)  # Pausa tra i test
        except Exception as e:
            print(f"❌ Test failed with exception: {e}\n")
    
    print("=" * 50)
    print(f"πŸ“Š Risultati: {passed}/{total} test passati")
    
    if passed == total:
        print("πŸŽ‰ Tutti i test sono passati!")
    else:
        print("⚠️  Alcuni test sono falliti. Controlla i log sopra.")

if __name__ == "__main__":
    main()