-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_runner.py
More file actions
564 lines (455 loc) · 20.3 KB
/
Copy pathtest_runner.py
File metadata and controls
564 lines (455 loc) · 20.3 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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Test Runner Script
Vergi Hatırlatıcı Bot için interactive test runner
"""
import os
import sys
import subprocess
import argparse
import time
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import json
# Renkli terminal output için
class Colors:
"""Terminal renk kodları"""
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
BLUE = '\033[0;34m'
PURPLE = '\033[0;35m'
CYAN = '\033[0;36m'
WHITE = '\033[0;37m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
NC = '\033[0m' # No Color
class TestRunner:
"""Ana test runner sınıfı"""
def __init__(self):
self.start_time = datetime.now()
self.results = {}
self.total_tests = 0
self.passed_tests = 0
self.failed_tests = 0
self.coverage_threshold = 80
# Test kategorileri
self.test_categories = {
'unit': 'Unit Tests (Hızlı, izole testler)',
'integration': 'Integration Tests (Modüller arası testler)',
'database': 'Database Tests (Veritabanı işlemleri)',
'scraper': 'Scraper Tests (Web scraping testleri)',
'bot': 'Bot Tests (Telegram bot testleri)',
'slow': 'Slow Tests (Uzun süren testler)',
'fast': 'Fast Tests (Hızlı testler)',
'all': 'All Tests (Tüm testler)'
}
def print_header(self):
"""Başlık yazdır"""
print(f"\n{Colors.CYAN}{'='*60}{Colors.NC}")
print(f"{Colors.CYAN}{Colors.BOLD} VERGİ HATIRLATICISI BOT - TEST RUNNER {Colors.NC}")
print(f"{Colors.CYAN}{'='*60}{Colors.NC}")
print(f"{Colors.WHITE}Başlatma zamanı: {self.start_time.strftime('%d.%m.%Y %H:%M:%S')}{Colors.NC}")
print(f"{Colors.WHITE}Python version: {sys.version.split()[0]}{Colors.NC}")
print()
def print_menu(self):
"""Ana menüyü yazdır"""
print(f"{Colors.YELLOW}{Colors.BOLD}TEST KATEGORİLERİ:{Colors.NC}")
print()
for i, (key, description) in enumerate(self.test_categories.items(), 1):
color = Colors.GREEN if key == 'all' else Colors.WHITE
print(f"{color}{i:2d}. {description}{Colors.NC}")
print()
print(f"{Colors.BLUE}{Colors.BOLD}ÖZEL KOMUTLAR:{Colors.NC}")
print(f"{Colors.WHITE}{len(self.test_categories)+1:2d}. Coverage Report (Test kapsamı raporu){Colors.NC}")
print(f"{Colors.WHITE}{len(self.test_categories)+2:2d}. Lint Check (Kod kalitesi kontrolü){Colors.NC}")
print(f"{Colors.WHITE}{len(self.test_categories)+3:2d}. Format Check (Kod formatı kontrolü){Colors.NC}")
print(f"{Colors.WHITE}{len(self.test_categories)+4:2d}. Full CI Pipeline (Tam test pipeline){Colors.NC}")
print(f"{Colors.WHITE}{len(self.test_categories)+5:2d}. Clean Up (Temizlik){Colors.NC}")
print()
print(f"{Colors.RED}{len(self.test_categories)+6:2d}. Çıkış{Colors.NC}")
print()
def check_environment(self) -> bool:
"""Ortam kontrolü"""
print(f"{Colors.BLUE}Ortam kontrolleri yapılıyor...{Colors.NC}")
checks = []
# Python kontrolü
python_version = sys.version_info
if python_version >= (3, 8):
checks.append(("Python", True, f"{python_version.major}.{python_version.minor}.{python_version.micro}"))
else:
checks.append(("Python", False, f"Minimum Python 3.8 gerekli, mevcut: {python_version.major}.{python_version.minor}"))
# Pytest kontrolü
try:
result = subprocess.run(['pytest', '--version'], capture_output=True, text=True)
if result.returncode == 0:
version = result.stdout.strip().split()[1]
checks.append(("Pytest", True, version))
else:
checks.append(("Pytest", False, "Yüklü değil"))
except FileNotFoundError:
checks.append(("Pytest", False, "Bulunamadı"))
# Coverage kontrolü
try:
result = subprocess.run(['coverage', '--version'], capture_output=True, text=True)
if result.returncode == 0:
version = result.stdout.strip().split()[1].rstrip(',')
checks.append(("Coverage", True, version))
else:
checks.append(("Coverage", False, "Yüklü değil"))
except FileNotFoundError:
checks.append(("Coverage", False, "Bulunamadı"))
# Test dosyaları kontrolü
test_files = [
'tests/test_database.py',
'tests/test_scraper.py',
'tests/test_bot.py',
'tests/conftest.py'
]
missing_files = []
for test_file in test_files:
if os.path.exists(test_file):
checks.append((f"Test File: {os.path.basename(test_file)}", True, "Mevcut"))
else:
missing_files.append(test_file)
checks.append((f"Test File: {os.path.basename(test_file)}", False, "Eksik"))
# Sonuçları yazdır
print()
for check_name, status, info in checks:
status_color = Colors.GREEN if status else Colors.RED
status_text = "✓" if status else "✗"
print(f"{status_color}{status_text} {check_name:<25} {info}{Colors.NC}")
all_passed = all(status for _, status, _ in checks)
print()
if all_passed:
print(f"{Colors.GREEN}✓ Tüm ortam kontrolleri başarılı!{Colors.NC}")
else:
print(f"{Colors.RED}✗ Bazı kontroller başarısız! Eksiklikleri giderin.{Colors.NC}")
if missing_files:
print(f"{Colors.YELLOW}Eksik dosyalar:{Colors.NC}")
for file in missing_files:
print(f" - {file}")
print()
return all_passed
def run_command(self, command: List[str], description: str) -> Tuple[bool, str]:
"""Komut çalıştır ve sonucu döndür"""
print(f"{Colors.BLUE}Çalıştırılıyor: {description}{Colors.NC}")
print(f"{Colors.WHITE}Komut: {' '.join(command)}{Colors.NC}")
print()
start_time = time.time()
try:
result = subprocess.run(
command,
capture_output=False, # Output'u terminal'de göster
text=True,
cwd=os.getcwd()
)
end_time = time.time()
duration = end_time - start_time
success = result.returncode == 0
if success:
print(f"\n{Colors.GREEN}✓ {description} başarılı! ({duration:.2f}s){Colors.NC}\n")
else:
print(f"\n{Colors.RED}✗ {description} başarısız! ({duration:.2f}s){Colors.NC}\n")
return success, f"Duration: {duration:.2f}s"
except Exception as e:
print(f"\n{Colors.RED}✗ Komut çalıştırılırken hata: {str(e)}{Colors.NC}\n")
return False, f"Error: {str(e)}"
def run_tests(self, category: str) -> bool:
"""Belirtilen kategoride testleri çalıştır"""
commands = {
'unit': ['pytest', 'tests/', '-m', 'unit', '-v'],
'integration': ['pytest', 'tests/', '-m', 'integration', '-v'],
'database': ['pytest', 'tests/', '-m', 'database', '-v'],
'scraper': ['pytest', 'tests/', '-m', 'scraper', '-v'],
'bot': ['pytest', 'tests/', '-m', 'bot', '-v'],
'slow': ['pytest', 'tests/', '-m', 'slow', '-v', '--timeout=60'],
'fast': ['pytest', 'tests/', '-m', 'not slow', '-v'],
'all': ['pytest', 'tests/', '-v']
}
if category not in commands:
print(f"{Colors.RED}Geçersiz test kategorisi: {category}{Colors.NC}")
return False
command = commands[category]
description = f"{self.test_categories[category]}"
success, duration = self.run_command(command, description)
self.results[category] = {
'success': success,
'duration': duration,
'timestamp': datetime.now().isoformat()
}
return success
def run_coverage(self) -> bool:
"""Coverage raporu çalıştır"""
command = [
'pytest', 'tests/',
'--cov=.',
'--cov-report=term-missing',
'--cov-report=html',
'--cov-report=xml',
f'--cov-fail-under={self.coverage_threshold}'
]
success, duration = self.run_command(command, "Coverage Analysis")
if success:
print(f"{Colors.CYAN}📊 Coverage raporu: htmlcov/index.html{Colors.NC}")
self.results['coverage'] = {
'success': success,
'duration': duration,
'threshold': self.coverage_threshold,
'timestamp': datetime.now().isoformat()
}
return success
def run_lint(self) -> bool:
"""Linting kontrolü"""
command = [
'flake8',
'bot.py', 'database.py', 'scraper.py', 'main.py', 'bot_handlers.py'
]
success, duration = self.run_command(command, "Code Linting (Flake8)")
self.results['lint'] = {
'success': success,
'duration': duration,
'timestamp': datetime.now().isoformat()
}
return success
def run_format_check(self) -> bool:
"""Format kontrolü"""
print(f"{Colors.BLUE}Format kontrolü yapılıyor...{Colors.NC}")
# Black kontrolü
black_command = [
'black', '--check', '--diff',
'bot.py', 'database.py', 'scraper.py', 'main.py', 'bot_handlers.py'
]
success1, _ = self.run_command(black_command, "Black Format Check")
# isort kontrolü
isort_command = [
'isort', '--check-only', '--diff',
'bot.py', 'database.py', 'scraper.py', 'main.py', 'bot_handlers.py'
]
success2, duration = self.run_command(isort_command, "Import Sort Check")
success = success1 and success2
self.results['format'] = {
'success': success,
'duration': duration,
'timestamp': datetime.now().isoformat()
}
return success
def run_full_pipeline(self) -> bool:
"""Tam CI pipeline çalıştır"""
print(f"{Colors.PURPLE}{Colors.BOLD}🚀 Tam CI Pipeline başlatılıyor...{Colors.NC}\n")
steps = [
("Environment Check", self.check_environment),
("Code Linting", self.run_lint),
("Format Check", self.run_format_check),
("Unit Tests", lambda: self.run_tests('unit')),
("Integration Tests", lambda: self.run_tests('integration')),
("Database Tests", lambda: self.run_tests('database')),
("Scraper Tests", lambda: self.run_tests('scraper')),
("Bot Tests", lambda: self.run_tests('bot')),
("Coverage Analysis", self.run_coverage)
]
all_success = True
pipeline_results = []
for step_name, step_func in steps:
print(f"{Colors.YELLOW}📋 Pipeline Step: {step_name}{Colors.NC}")
success = step_func()
pipeline_results.append({
'step': step_name,
'success': success,
'timestamp': datetime.now().isoformat()
})
if not success:
all_success = False
print(f"{Colors.RED}❌ Pipeline durdu: {step_name} başarısız{Colors.NC}")
break
else:
print(f"{Colors.GREEN}✅ {step_name} tamamlandı{Colors.NC}\n")
# Pipeline özeti
print(f"\n{Colors.PURPLE}{'='*50}{Colors.NC}")
print(f"{Colors.PURPLE}{Colors.BOLD}CI PIPELINE ÖZET{Colors.NC}")
print(f"{Colors.PURPLE}{'='*50}{Colors.NC}")
for result in pipeline_results:
status = "✅ BAŞARILI" if result['success'] else "❌ BAŞARISIZ"
color = Colors.GREEN if result['success'] else Colors.RED
print(f"{color}{result['step']:<25} {status}{Colors.NC}")
print()
if all_success:
print(f"{Colors.GREEN}{Colors.BOLD}🎉 TÜM PIPELINE BAŞARILI!{Colors.NC}")
else:
print(f"{Colors.RED}{Colors.BOLD}💥 PIPELINE BAŞARISIZ!{Colors.NC}")
self.results['pipeline'] = {
'success': all_success,
'steps': pipeline_results,
'timestamp': datetime.now().isoformat()
}
return all_success
def clean_up(self) -> bool:
"""Temizlik işlemleri"""
print(f"{Colors.BLUE}Temizlik işlemleri yapılıyor...{Colors.NC}")
cleanup_items = [
'htmlcov/',
'.coverage',
'coverage.xml',
'.pytest_cache/',
'__pycache__/',
'.tox/'
]
removed_items = []
for item in cleanup_items:
try:
if os.path.exists(item):
if os.path.isdir(item):
import shutil
shutil.rmtree(item)
else:
os.remove(item)
removed_items.append(item)
print(f"{Colors.GREEN}✓ Silindi: {item}{Colors.NC}")
except Exception as e:
print(f"{Colors.RED}✗ Silinirken hata ({item}): {str(e)}{Colors.NC}")
# .pyc dosyalarını temizle
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith('.pyc'):
try:
os.remove(os.path.join(root, file))
except:
pass
print(f"\n{Colors.GREEN}🧹 Temizlik tamamlandı! {len(removed_items)} öğe silindi.{Colors.NC}")
return True
def show_results_summary(self):
"""Test sonuçlarının özetini göster"""
if not self.results:
return
print(f"\n{Colors.CYAN}{'='*50}{Colors.NC}")
print(f"{Colors.CYAN}{Colors.BOLD}TEST SONUÇLARI ÖZETİ{Colors.NC}")
print(f"{Colors.CYAN}{'='*50}{Colors.NC}")
total_time = (datetime.now() - self.start_time).total_seconds()
print(f"{Colors.WHITE}Toplam süre: {total_time:.2f} saniye{Colors.NC}")
print()
for test_name, result in self.results.items():
status = "✅ BAŞARILI" if result['success'] else "❌ BAŞARISIZ"
color = Colors.GREEN if result['success'] else Colors.RED
print(f"{color}{test_name.upper():<15} {status}{Colors.NC}")
# Sonuçları JSON dosyasına kaydet
try:
results_file = f"test_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(results_file, 'w') as f:
json.dump({
'timestamp': self.start_time.isoformat(),
'total_duration': total_time,
'results': self.results
}, f, indent=2, ensure_ascii=False)
print(f"\n{Colors.CYAN}📄 Sonuçlar kaydedildi: {results_file}{Colors.NC}")
except Exception as e:
print(f"{Colors.YELLOW}⚠️ Sonuçlar kaydedilemedi: {str(e)}{Colors.NC}")
def interactive_mode(self):
"""Interactive menü modu"""
self.print_header()
# Ortam kontrolü
if not self.check_environment():
print(f"{Colors.YELLOW}⚠️ Ortam sorunları tespit edildi ama devam ediliyor...{Colors.NC}")
input("Devam etmek için Enter'a basın...")
while True:
self.print_menu()
try:
choice = input(f"{Colors.BOLD}Seçiminiz (1-{len(self.test_categories)+6}): {Colors.NC}").strip()
if not choice.isdigit():
print(f"{Colors.RED}Lütfen geçerli bir sayı girin!{Colors.NC}\n")
continue
choice_num = int(choice)
if choice_num <= len(self.test_categories):
# Test kategorisi seçildi
category = list(self.test_categories.keys())[choice_num - 1]
self.run_tests(category)
elif choice_num == len(self.test_categories) + 1:
# Coverage report
self.run_coverage()
elif choice_num == len(self.test_categories) + 2:
# Lint check
self.run_lint()
elif choice_num == len(self.test_categories) + 3:
# Format check
self.run_format_check()
elif choice_num == len(self.test_categories) + 4:
# Full CI pipeline
self.run_full_pipeline()
elif choice_num == len(self.test_categories) + 5:
# Clean up
self.clean_up()
elif choice_num == len(self.test_categories) + 6:
# Çıkış
break
else:
print(f"{Colors.RED}Geçersiz seçim! Lütfen 1-{len(self.test_categories)+6} arasında bir sayı girin.{Colors.NC}\n")
continue
input(f"\n{Colors.YELLOW}Devam etmek için Enter'a basın...{Colors.NC}")
print("\n" + "="*60)
except KeyboardInterrupt:
print(f"\n\n{Colors.YELLOW}Test runner kapatılıyor...{Colors.NC}")
break
except Exception as e:
print(f"\n{Colors.RED}Hata oluştu: {str(e)}{Colors.NC}")
input("Devam etmek için Enter'a basın...")
self.show_results_summary()
print(f"\n{Colors.GREEN}Görüşmek üzere! 👋{Colors.NC}\n")
def main():
"""Ana fonksiyon"""
parser = argparse.ArgumentParser(
description="Vergi Hatırlatıcı Bot Test Runner",
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
'--category', '-c',
choices=['unit', 'integration', 'database', 'scraper', 'bot', 'slow', 'fast', 'all'],
help='Test kategorisi seç'
)
parser.add_argument(
'--coverage',
action='store_true',
help='Coverage raporu çalıştır'
)
parser.add_argument(
'--lint',
action='store_true',
help='Lint kontrolü çalıştır'
)
parser.add_argument(
'--format-check',
action='store_true',
help='Format kontrolü çalıştır'
)
parser.add_argument(
'--pipeline',
action='store_true',
help='Tam CI pipeline çalıştır'
)
parser.add_argument(
'--clean',
action='store_true',
help='Temizlik işlemleri yap'
)
args = parser.parse_args()
runner = TestRunner()
# Command line arguments varsa onları çalıştır
if any(vars(args).values()):
runner.print_header()
if args.category:
runner.run_tests(args.category)
if args.coverage:
runner.run_coverage()
if args.lint:
runner.run_lint()
if args.format_check:
runner.run_format_check()
if args.pipeline:
runner.run_full_pipeline()
if args.clean:
runner.clean_up()
runner.show_results_summary()
else:
# Interactive mode
runner.interactive_mode()
if __name__ == "__main__":
main()