-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestar.py
More file actions
225 lines (177 loc) · 6.57 KB
/
Copy pathtestar.py
File metadata and controls
225 lines (177 loc) · 6.57 KB
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
#!/usr/bin/env python3
"""
Script de Teste - Gerador de Mosaico ODS
Verifica se tudo está funcionando corretamente
"""
import sys
import os
from pathlib import Path
def print_header(text):
"""Imprime cabeçalho formatado"""
print(f"\n{'=' * 50}")
print(f" {text}")
print('=' * 50)
def print_status(check, message):
"""Imprime status de verificação"""
icon = "✅" if check else "❌"
print(f"{icon} {message}")
def test_python_version():
"""Testa versão do Python"""
print_header("Verificando Python")
version = sys.version_info
print(f"Versão do Python: {version.major}.{version.minor}.{version.patch}")
is_valid = version.major >= 3 and version.minor >= 8
print_status(is_valid, "Python 3.8+ requerido" if is_valid else "Python 3.8+ NÃO encontrado")
return is_valid
def test_dependencies():
"""Testa dependências instaladas"""
print_header("Verificando Dependências")
all_ok = True
# Testar Pillow
try:
import PIL
print_status(True, f"Pillow {PIL.__version__} instalado")
except ImportError:
print_status(False, "Pillow NÃO instalado")
all_ok = False
# Testar python-dotenv
try:
import dotenv
print_status(True, "python-dotenv instalado")
except ImportError:
print_status(False, "python-dotenv NÃO instalado")
all_ok = False
# Testar cairosvg (opcional)
try:
import cairosvg
print_status(True, "cairosvg instalado (suporte a SVG)")
except ImportError:
print_status(False, "cairosvg NÃO instalado (apenas PNG disponível)")
return all_ok
def test_files():
"""Testa existência de arquivos necessários"""
print_header("Verificando Arquivos")
all_ok = True
script_dir = Path(__file__).parent
# Arquivos obrigatórios
required_files = {
'gerador_ods.py': 'Script principal',
'.env.example': 'Arquivo de exemplo de configuração',
'requirements.txt': 'Lista de dependências',
'README.md': 'Documentação',
}
for filename, description in required_files.items():
exists = (script_dir / filename).exists()
print_status(exists, f"{description}: {filename}")
if not exists:
all_ok = False
# Verificar arquivo .env
env_exists = (script_dir / '.env').exists()
print_status(env_exists, "Arquivo .env (configuração)")
if not env_exists:
print(" ⚠️ Crie o .env: cp .env.example .env")
return all_ok
def test_image_paths():
"""Testa caminhos das imagens"""
print_header("Verificando Imagens ODS")
script_dir = Path(__file__).parent
images_path = script_dir / '../assets/images/ods'
if not images_path.exists():
print_status(False, f"Diretório de imagens não encontrado: {images_path}")
return False
print_status(True, f"Diretório de imagens encontrado")
# Verificar quantas imagens existem
svg_count = len(list(images_path.glob('*.svg')))
png_count = len(list(images_path.glob('*.png')))
print(f" 📊 Imagens SVG encontradas: {svg_count}")
print(f" 📊 Imagens PNG encontradas: {png_count}")
if svg_count >= 17 or png_count >= 17:
print_status(True, "Imagens suficientes para gerar mosaicos")
return True
else:
print_status(False, "Imagens insuficientes (esperado 17)")
return False
def test_env_config():
"""Testa configuração do .env"""
print_header("Verificando Configuração .env")
script_dir = Path(__file__).parent
env_path = script_dir / '.env'
if not env_path.exists():
print_status(False, "Arquivo .env não encontrado")
return False
# Ler arquivo .env
with open(env_path, 'r', encoding='utf-8') as f:
content = f.read()
# Verificar variáveis essenciais
required_vars = [
'IMAGES_PER_ROW',
'IMAGE_SIZE',
'SPACING',
'BACKGROUND_TYPE',
'OUTPUT_DIR',
]
all_ok = True
for var in required_vars:
exists = var in content
print_status(exists, f"Variável {var}")
if not exists:
all_ok = False
return all_ok
def run_test_generation():
"""Tenta gerar um mosaico de teste"""
print_header("Teste de Geração")
try:
print("Tentando gerar mosaico de teste com 3 imagens...")
# Importar o gerador
from gerador_ods import ODSMosaicGenerator
generator = ODSMosaicGenerator()
# Tentar gerar com 3 imagens
result = generator.generate("1,2,3")
if result and result.exists():
print_status(True, f"Mosaico de teste gerado com sucesso!")
print(f" 📁 Arquivo: {result}")
print(f" 📊 Tamanho: {result.stat().st_size / 1024:.2f} KB")
return True
else:
print_status(False, "Falha ao gerar mosaico de teste")
return False
except Exception as e:
print_status(False, f"Erro ao gerar mosaico de teste: {e}")
return False
def main():
"""Função principal"""
print("\n🔍 Executando Testes do Gerador de Mosaico ODS")
print("=" * 50)
results = {
'Python': test_python_version(),
'Dependências': test_dependencies(),
'Arquivos': test_files(),
'Imagens': test_image_paths(),
}
# Testar .env apenas se tudo anterior passou
if all(results.values()):
results['Configuração'] = test_env_config()
# Tentar gerar mosaico de teste
if results['Configuração']:
results['Geração'] = run_test_generation()
# Sumário final
print_header("Sumário dos Testes")
for test_name, result in results.items():
print_status(result, test_name)
# Resultado final
all_passed = all(results.values())
print("\n" + "=" * 50)
if all_passed:
print("🎉 Todos os testes passaram! Sistema pronto para uso!")
print("\nPróximos passos:")
print(" python gerador_ods.py 1,2,3,4,5,6,7")
else:
print("⚠️ Alguns testes falharam. Verifique os erros acima.")
print("\nSoluções comuns:")
print(" 1. Instalar dependências: pip install -r requirements.txt")
print(" 2. Criar arquivo .env: cp .env.example .env")
print(" 3. Verificar caminho das imagens no .env")
print("=" * 50 + "\n")
return 0 if all_passed else 1
if __name__ == '__main__':
sys.exit(main())