-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_core.py
More file actions
1343 lines (1061 loc) · 58.4 KB
/
Copy pathtest_core.py
File metadata and controls
1343 lines (1061 loc) · 58.4 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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
DevCenter - Unit Tests
Testet die Kernkomponenten
"""
import unittest
import sys
import os
import tempfile
import shutil
from pathlib import Path
# Pfad für Imports
sys.path.insert(0, str(Path(__file__).parent.parent / 'src'))
class TestProjectManager(unittest.TestCase):
"""Tests für ProjectManager"""
def setUp(self):
"""Erstellt temporäres Verzeichnis"""
self.temp_dir = tempfile.mkdtemp()
from core.project_manager import ProjectManager
self.settings_file = os.path.join(self.temp_dir, "settings.json")
self.pm = ProjectManager(settings_path=self.settings_file)
def tearDown(self):
"""Räumt auf"""
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_create_project(self):
"""Testet Projekt-Erstellung"""
project = self.pm.create_project(
name="TestProject",
path=self.temp_dir
)
self.assertIsNotNone(project)
self.assertEqual(project.name, "TestProject")
self.assertTrue(os.path.exists(os.path.join(self.temp_dir, "devcenter.json")))
def test_open_project(self):
"""Testet Projekt-Öffnen"""
# Erst erstellen
self.pm.create_project("Test", self.temp_dir)
# Dann öffnen
project = self.pm.open_project(self.temp_dir)
self.assertIsNotNone(project)
self.assertEqual(project.name, "Test")
def test_recent_projects(self):
"""Testet Recent-Projects-Liste"""
self.pm.create_project("Test1", self.temp_dir)
recent = self.pm.get_recent_projects()
self.assertTrue(len(recent) >= 1)
def test_create_project_template_files_have_real_newlines(self):
"""_create_template_files darf kein literales \\n in Template-Dateien schreiben."""
project_dir = os.path.join(self.temp_dir, "newline_test")
os.makedirs(project_dir, exist_ok=True)
self.pm.create_project("NewlineTest", project_dir)
init_path = os.path.join(project_dir, "src", "__init__.py")
req_path = os.path.join(project_dir, "requirements.txt")
for path in (init_path, req_path):
with open(path, "r", encoding="utf-8") as f:
content = f.read()
self.assertNotIn("\\n", content,
f"{path} enthält literales \\\\n statt echtem Newline")
def test_save_recent_projects_handles_corrupt_settings_json(self):
"""_save_recent_projects muss json.JSONDecodeError sauber abfangen."""
with open(self.settings_file, "w", encoding="utf-8") as f:
f.write("{ not valid json }")
project_dir = os.path.join(self.temp_dir, "new_project")
os.makedirs(project_dir, exist_ok=True)
result = self.pm.create_project("CorruptSettingsTest", project_dir)
self.assertIsNotNone(result, "create_project muss trotz korrupter settings.json funktionieren")
def test_get_recent_projects_emits_signal_on_stale_cleanup(self):
"""Regression: get_recent_projects() muss recent_projects_changed emittieren wenn
veraltete Einträge entfernt werden — ohne Fix bleibt die UI-Darstellung der Liste veraltet."""
import inspect
from core.project_manager import ProjectManager
source = inspect.getsource(ProjectManager.get_recent_projects)
self.assertIn('recent_projects_changed.emit', source,
"get_recent_projects() muss recent_projects_changed emittieren wenn veraltete Einträge entfernt wurden")
class TestSettingsManager(unittest.TestCase):
"""Tests für SettingsManager"""
def setUp(self):
from core.settings_manager import SettingsManager
self.temp_dir = tempfile.mkdtemp()
self.settings_file = os.path.join(self.temp_dir, "settings.json")
self.sm = SettingsManager(self.settings_file)
def tearDown(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_get_default(self):
"""Testet Default-Wert"""
value = self.sm.get('nonexistent.key', 'default')
self.assertEqual(value, 'default')
def test_set_and_get(self):
"""Testet Setzen und Lesen"""
self.sm.set('test.key', 'test_value')
value = self.sm.get('test.key')
self.assertEqual(value, 'test_value')
def test_nested_keys(self):
"""Testet verschachtelte Schlüssel"""
self.sm.set('level1.level2.level3', 42)
value = self.sm.get('level1.level2.level3')
self.assertEqual(value, 42)
def test_extra_keys_persist(self):
"""Testet Persistenz nicht modellierter Schlüssel"""
from core.settings_manager import SettingsManager
self.sm.set('build.output_dir', 'custom_dist')
self.sm.set('level1.level2.level3', 42)
reloaded = SettingsManager(self.settings_file)
self.assertEqual(reloaded.get('build.output_dir'), 'custom_dist')
self.assertEqual(reloaded.get('level1.level2.level3'), 42)
class TestEventBus(unittest.TestCase):
"""Tests für EventBus"""
def setUp(self):
from core.event_bus import EventBus, EventType
self.eb = EventBus()
self.EventType = EventType
self.received_events = []
def test_subscribe_and_emit(self):
"""Testet Subscribe und Emit"""
def handler(event):
self.received_events.append(event)
self.eb.subscribe(self.EventType.FILE_OPENED, handler)
self.eb.emit(self.EventType.FILE_OPENED, {'path': 'test.py'})
self.assertEqual(len(self.received_events), 1)
self.assertEqual(self.received_events[0].data['path'], 'test.py')
def test_unsubscribe(self):
"""Testet Unsubscribe"""
def handler(event):
self.received_events.append(event)
self.eb.subscribe(self.EventType.FILE_SAVED, handler)
self.eb.unsubscribe(self.EventType.FILE_SAVED, handler)
self.eb.emit(self.EventType.FILE_SAVED, {})
self.assertEqual(len(self.received_events), 0)
class TestMethodAnalyzer(unittest.TestCase):
"""Tests für MethodAnalyzer"""
def setUp(self):
from modules.analyzer import MethodAnalyzer
self.analyzer = MethodAnalyzer()
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_analyze_simple_file(self):
"""Testet Analyse einer einfachen Datei"""
code = '''
def hello():
"""Says hello"""
print("Hello, World!")
class Greeter:
def greet(self, name):
return f"Hello, {name}!"
'''
file_path = os.path.join(self.temp_dir, "test.py")
with open(file_path, 'w') as f:
f.write(code)
result = self.analyzer.analyze_file(file_path)
self.assertEqual(len(result.functions), 1)
self.assertEqual(result.functions[0].name, 'hello')
self.assertEqual(len(result.classes), 1)
self.assertEqual(result.classes[0].name, 'Greeter')
def test_syntax_error_detection(self):
"""Testet Erkennung von Syntax-Fehlern"""
code = '''
def broken(:
pass
'''
file_path = os.path.join(self.temp_dir, "broken.py")
with open(file_path, 'w') as f:
f.write(code)
result = self.analyzer.analyze_file(file_path)
self.assertTrue(len(result.errors) > 0)
self.assertEqual(result.errors[0]['type'], 'SyntaxError')
def test_complexity_calculation(self):
"""Testet Komplexitäts-Berechnung"""
code = '''
def complex_function(x):
if x > 0:
for i in range(x):
if i % 2 == 0:
print(i)
else:
print(-i)
else:
while x < 0:
x += 1
return x
'''
file_path = os.path.join(self.temp_dir, "complex.py")
with open(file_path, 'w') as f:
f.write(code)
result = self.analyzer.analyze_file(file_path)
self.assertTrue(result.functions[0].complexity > 1)
def test_aliased_from_import_not_flagged_as_unused(self):
"""Bug 19: from X import Y as Z darf nicht als ungenutzt gelten wenn Z verwendet wird."""
code = 'from typing import Optional as Opt\ndef f(x: Opt) -> None:\n pass\n'
file_path = os.path.join(self.temp_dir, "aliased.py")
with open(file_path, 'w') as f:
f.write(code)
result = self.analyzer.analyze_file(file_path)
self.assertNotIn('typing.Optional', result.unused_imports,
"Aliasierter From-Import fälschlich als ungenutzt markiert")
class TestKompilator(unittest.TestCase):
"""Tests für Kompilator"""
def test_pyinstaller_check(self):
"""Testet PyInstaller-Verfügbarkeit"""
from modules.builder import Kompilator
kompilator = Kompilator()
# Sollte nicht abstürzen
available = kompilator.check_pyinstaller()
self.assertIsInstance(available, bool)
def test_build_resolves_output_dir_relative_to_script_dir(self):
"""build() muss output_dir relativ zum Skript-Verzeichnis auflösen, nicht Python-CWD."""
import inspect
from modules.builder import Kompilator
source = inspect.getsource(Kompilator.build)
self.assertIn('isabs', source, "build() muss prüfen ob output_dir absolut ist")
self.assertIn('abspath', source, "build() muss den absoluten Skript-Verzeichnis-Pfad verwenden")
def test_clean_build_uses_script_directory(self):
"""_clean_build muss Artefakte relativ zum Skript-Verzeichnis löschen."""
from modules.builder import Kompilator, BuildConfig
kompilator = Kompilator()
temp_dir = tempfile.mkdtemp()
try:
script_path = os.path.join(temp_dir, "myscript.py")
open(script_path, "w").close()
# Fake Build-Artefakte im Skript-Verzeichnis anlegen
build_dir = os.path.join(temp_dir, "build", "myscript")
os.makedirs(build_dir)
spec_file = os.path.join(temp_dir, "myscript.spec")
with open(spec_file, "w") as f:
f.write("# dummy spec")
config = BuildConfig(script_path=script_path, name="myscript")
# Aufruf aus einem anderen Arbeitsverzeichnis simulieren
original_cwd = os.getcwd()
try:
os.chdir(self.temp_dir if hasattr(self, "temp_dir") else tempfile.gettempdir())
kompilator._clean_build(config)
finally:
os.chdir(original_cwd)
self.assertFalse(os.path.exists(build_dir), "build/<name>-Ordner wurde nicht gelöscht")
self.assertFalse(os.path.exists(spec_file), ".spec-Datei wurde nicht gelöscht")
finally:
shutil.rmtree(temp_dir, ignore_errors=True)
class TestSyncManager(unittest.TestCase):
"""Tests für SyncManager"""
def setUp(self):
from modules.filemanager import SyncManager, SyncConfig
self.sm = SyncManager()
self.SyncConfig = SyncConfig
self.source_dir = tempfile.mkdtemp()
self.target_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.source_dir, ignore_errors=True)
shutil.rmtree(self.target_dir, ignore_errors=True)
def test_sync_files(self):
"""Testet Datei-Synchronisation"""
# Dateien erstellen
with open(os.path.join(self.source_dir, "test.txt"), 'w') as f:
f.write("Hello")
config = self.SyncConfig(
source_path=self.source_dir,
target_path=self.target_dir
)
result = self.sm.sync(config)
self.assertTrue(result.success)
self.assertEqual(result.files_copied, 1)
self.assertTrue(os.path.exists(os.path.join(self.target_dir, "test.txt")))
def test_exclude_patterns(self):
"""Testet Ausschluss-Muster"""
# Dateien erstellen
with open(os.path.join(self.source_dir, "include.txt"), 'w') as f:
f.write("Include")
os.makedirs(os.path.join(self.source_dir, "__pycache__"))
with open(os.path.join(self.source_dir, "__pycache__", "cache.pyc"), 'w') as f:
f.write("Cache")
config = self.SyncConfig(
source_path=self.source_dir,
target_path=self.target_dir,
excludes=['__pycache__']
)
result = self.sm.sync(config)
self.assertTrue(result.success)
self.assertFalse(os.path.exists(os.path.join(self.target_dir, "__pycache__")))
def test_cancelled_sync_reports_failure(self):
"""sync() muss nach Abbruch während der Kopierphase success=False melden."""
import inspect
from modules.filemanager.sync_manager import SyncManager
source = inspect.getsource(SyncManager.sync)
self.assertEqual(source.count('Sync abgebrochen'), 2,
"sync() muss 'Sync abgebrochen' sowohl bei frühem als auch spätem Cancel eintragen")
def test_delete_orphans_respects_excludes(self):
"""delete_orphans darf Dateien in ausgeschlossenen Verzeichnissen nicht löschen."""
from modules.filemanager import SyncConfig
# Quelldatei
with open(os.path.join(self.source_dir, "keep.txt"), "w") as f:
f.write("keep")
# Erste Synchronisation
config = SyncConfig(source_path=self.source_dir, target_path=self.target_dir)
self.sm.sync(config)
# Im Ziel ein ausgeschlossenes Verzeichnis anlegen (simuliert .git etc.)
excluded_dir = os.path.join(self.target_dir, "__pycache__")
os.makedirs(excluded_dir)
excluded_file = os.path.join(excluded_dir, "cached.pyc")
with open(excluded_file, "w") as f:
f.write("cache")
# Zweite Sync mit delete_orphans=True
config2 = SyncConfig(
source_path=self.source_dir,
target_path=self.target_dir,
excludes=["__pycache__"],
delete_orphans=True,
)
result = self.sm.sync(config2)
self.assertTrue(result.success)
self.assertTrue(os.path.exists(excluded_file), "Ausgeschlossene Datei wurde fälschlich gelöscht")
def test_delete_orphan_error_includes_exception_detail(self):
"""Regression: Fehlertext beim Löschen einer Waisendatei muss die Exception enthalten.
Ohne Fix: f'Löschen fehlgeschlagen: {rel_path}' — Exception-Grund fehlt komplett."""
from unittest.mock import patch
from modules.filemanager import SyncConfig
# Datei im Ziel anlegen (kein Pendant in der Quelle → Waisendatei)
orphan_path = os.path.join(self.target_dir, "orphan.txt")
with open(orphan_path, "w") as f:
f.write("orphan")
config = SyncConfig(
source_path=self.source_dir,
target_path=self.target_dir,
delete_orphans=True,
)
with patch("os.remove", side_effect=PermissionError("Zugriff verweigert")):
result = self.sm.sync(config)
self.assertTrue(any("Zugriff verweigert" in e for e in result.errors),
f"Fehlermeldung muss Exception-Text enthalten; errors={result.errors}")
class TestEventBusUnsubscribeDuringEmit(unittest.TestCase):
"""EventBus: Callback darf sich während Emission selbst abmelden."""
def test_unsubscribe_during_emit_does_not_skip_next(self):
from core.event_bus import EventBus, EventType
import sys
from PySide6.QtWidgets import QApplication
app = QApplication.instance() or QApplication(sys.argv)
bus = EventBus()
results = []
def cb_a(event):
results.append('A')
bus.unsubscribe(EventType.FILE_OPENED, cb_a)
def cb_b(event):
results.append('B')
bus.subscribe(EventType.FILE_OPENED, cb_a)
bus.subscribe(EventType.FILE_OPENED, cb_b)
bus.emit(EventType.FILE_OPENED)
self.assertIn('B', results, "cb_b darf nicht übersprungen werden wenn cb_a sich abmeldet")
class TestEncodingFixer(unittest.TestCase):
"""Tests für EncodingFixer"""
def setUp(self):
from modules.analyzer import EncodingFixer
self.fixer = EncodingFixer()
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_detect_utf8(self):
"""Testet UTF-8 Erkennung"""
file_path = os.path.join(self.temp_dir, "utf8.txt")
with open(file_path, 'w', encoding='utf-8') as f:
f.write("Hello Wörld! 你好")
encoding, confidence = self.fixer.detect_encoding(file_path)
self.assertIn('utf', encoding.lower())
def test_check_file(self):
"""Testet Datei-Prüfung"""
file_path = os.path.join(self.temp_dir, "test.txt")
with open(file_path, 'w', encoding='utf-8') as f:
f.write("Test content")
result = self.fixer.check_file(file_path)
self.assertTrue(result['is_valid_utf8'])
class TestAIService(unittest.TestCase):
"""Tests für AIService"""
def test_service_without_key(self):
"""Testet Service ohne API-Key"""
from modules.ai_assistant import AIService
service = AIService(api_key="")
self.assertFalse(service.is_available())
def test_model_setting(self):
"""Testet Modell-Einstellung"""
from modules.ai_assistant import AIService, AIModel
service = AIService()
service.set_model(AIModel.CLAUDE_OPUS)
self.assertEqual(service.model, AIModel.CLAUDE_OPUS.value)
def test_ai_worker_loop_cleanup_in_source(self):
"""AIWorker.run() muss event loop in finally schließen, sonst Leak bei Exception."""
import inspect
from gui.panels.ai_panel import AIWorker
source = inspect.getsource(AIWorker.run)
self.assertIn('finally', source, "AIWorker.run() muss finally-Block für loop.close() haben")
self.assertIn('loop.close()', source, "AIWorker.run() muss loop.close() in finally aufrufen")
class TestProfilerBridge(unittest.TestCase):
"""Tests für ProfilerBridge"""
def setUp(self):
from modules.filemanager import ProfilerBridge
self.temp_dir = tempfile.mkdtemp()
db_path = os.path.join(self.temp_dir, "test_index.db")
self.bridge = ProfilerBridge(db_path)
def tearDown(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_index_file(self):
"""Testet Datei-Indizierung"""
file_path = os.path.join(self.temp_dir, "test.py")
with open(file_path, 'w') as f:
f.write("print('Hello')")
success = self.bridge.index_file(file_path)
self.assertTrue(success)
def test_search(self):
"""Testet Suche"""
file_path = os.path.join(self.temp_dir, "searchable.py")
with open(file_path, 'w') as f:
f.write("def unique_function_name():\n pass")
self.bridge.index_file(file_path)
results = self.bridge.search("unique_function_name")
self.assertTrue(len(results) > 0)
def test_index_directory_does_not_exclude_file_with_excluded_word_in_name(self):
"""index_directory darf Dateien wie build_helper.py nicht wegen Substring 'build' ausschließen."""
project_dir = os.path.join(self.temp_dir, "my_project")
os.makedirs(project_dir)
build_helper = os.path.join(project_dir, "build_helper.py")
with open(build_helper, "w") as f:
f.write("# helper")
count = self.bridge.index_directory(project_dir)
self.assertEqual(count, 1, "build_helper.py muss indiziert werden, da es nicht in build/ liegt")
def test_find_duplicates_with_apostrophe_in_project_path(self):
"""find_duplicates darf bei Apostroph im project_path nicht abstürzen."""
project_path = "/Users/O'Brien/MyProject"
# Soll keinen OperationalError werfen
try:
result = self.bridge.find_duplicates(project_path=project_path)
self.assertIsInstance(result, dict)
except Exception as e:
self.fail(f"find_duplicates mit Apostroph-Pfad crashte: {e}")
def test_get_statistics_with_apostrophe_in_project_path(self):
"""get_statistics darf bei Apostroph im project_path nicht abstürzen."""
project_path = "/Users/O'Brien/MyProject"
try:
stats = self.bridge.get_statistics(project_path=project_path)
self.assertEqual(stats['total_files'], 0)
except Exception as e:
self.fail(f"get_statistics mit Apostroph-Pfad crashte: {e}")
def test_fts_search_respects_project_path_filter(self):
"""Bug 20: FTS-Suche darf bei project_path-Filter keine Treffer aus anderen Projekten zurückgeben."""
project_a = os.path.join(self.temp_dir, "proj_a")
project_b = os.path.join(self.temp_dir, "proj_b")
os.makedirs(project_a)
os.makedirs(project_b)
file_a = os.path.join(project_a, "alpha.py")
file_b = os.path.join(project_b, "beta.py")
with open(file_a, 'w') as f:
f.write("def unique_alpha_xyz(): pass")
with open(file_b, 'w') as f:
f.write("def unique_alpha_xyz(): pass")
self.bridge.index_file(file_a, project_path=project_a)
self.bridge.index_file(file_b, project_path=project_b)
results = self.bridge.search("unique_alpha_xyz", project_path=project_a)
for r in results:
self.assertEqual(r.file.path, file_a,
f"FTS lieferte Ergebnis aus falschem Projekt: {r.file.path}")
def test_search_closes_connection_on_exception(self):
"""Bug 40: search() muss conn.close() auch bei DB-Fehler aufrufen (kein Connection-Leak)."""
from unittest.mock import MagicMock, patch
mock_conn = MagicMock()
mock_cursor = MagicMock()
mock_cursor.execute.side_effect = Exception("injected DB error")
mock_conn.cursor.return_value = mock_cursor
with patch("modules.filemanager.profiler_bridge.sqlite3.connect", return_value=mock_conn):
result = self.bridge.search("anything")
mock_conn.close.assert_called_once()
self.assertEqual(result, [])
def test_get_statistics_closes_connection_on_exception(self):
"""Bug 40: get_statistics() muss conn.close() auch bei DB-Fehler aufrufen."""
from unittest.mock import MagicMock, patch
mock_conn = MagicMock()
mock_cursor = MagicMock()
mock_cursor.execute.side_effect = Exception("injected DB error")
mock_conn.cursor.return_value = mock_cursor
with patch("modules.filemanager.profiler_bridge.sqlite3.connect", return_value=mock_conn):
stats = self.bridge.get_statistics()
mock_conn.close.assert_called_once()
self.assertEqual(stats['total_files'], 0)
class TestSettingsDialogPersistence(unittest.TestCase):
"""Statischer Test: SettingsDialog muss alle UI-Felder speichern und laden."""
def test_ai_model_is_saved_and_loaded(self):
"""ai.model-Auswahl muss in _save_settings und _load_settings vorkommen."""
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
save_src = inspect.getsource(SettingsDialog._save_settings)
load_src = inspect.getsource(SettingsDialog._load_settings)
self.assertIn('ai.model', save_src, "_save_settings muss ai.model speichern")
self.assertIn('ai.model', load_src, "_load_settings muss ai.model laden")
def test_backup_interval_is_saved_and_loaded(self):
"""sync.backup_interval_minutes muss in _save_settings und _load_settings vorkommen."""
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
save_src = inspect.getsource(SettingsDialog._save_settings)
load_src = inspect.getsource(SettingsDialog._load_settings)
self.assertIn('backup_interval', save_src, "_save_settings muss backup_interval speichern")
self.assertIn('backup_interval', load_src, "_load_settings muss backup_interval laden")
class TestBuildSettingsKeyNames(unittest.TestCase):
"""SettingsDialog muss die kanonischen BuildSettings-Feldnamen verwenden."""
def test_build_settings_uses_canonical_field_names(self):
"""build.output_dir/console/upx sind keine gültigen Felder — canonical ist
default_output_dir / console_mode / upx_enabled."""
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
src = inspect.getsource(SettingsDialog._load_settings) + \
inspect.getsource(SettingsDialog._save_settings)
self.assertIn('default_output_dir', src,
"_load/_save muss 'build.default_output_dir' verwenden")
self.assertIn('console_mode', src,
"_load/_save muss 'build.console_mode' verwenden")
self.assertIn('upx_enabled', src,
"_load/_save muss 'build.upx_enabled' verwenden")
self.assertNotIn("'build.output_dir'", src,
"_load/_save darf nicht den falschen Key 'build.output_dir' verwenden")
self.assertNotIn("'build.console'", src,
"_load/_save darf nicht den falschen Key 'build.console' verwenden")
self.assertNotIn("'build.upx'", src,
"_load/_save darf nicht den falschen Key 'build.upx' verwenden")
class TestBuildDialogImport(unittest.TestCase):
"""BuildDialog muss den Builder mit absolutem Import laden (nicht mit 3 Punkten)."""
def test_build_dialog_uses_absolute_import_for_builder(self):
"""'from ...modules.builder' scheitert immer — nur absoluter Import funktioniert."""
import inspect
from gui.dialogs.build_dialog import BuildDialog
source = inspect.getsource(BuildDialog._start_build)
self.assertNotIn('from ...modules.builder', source,
"_start_build darf keinen 3-Punkte-Relativ-Import verwenden")
self.assertIn('from modules.builder', source,
"_start_build muss 'from modules.builder' (absolut) verwenden")
class TestNewProjectDialogValidation(unittest.TestCase):
"""Statischer Test: NewProjectDialog muss leere safe_names ablehnen."""
def test_validate_and_accept_rejects_empty_safe_name(self):
"""Namen aus nur Sonderzeichen erzeugen leere safe_name → darf nicht akzeptiert werden."""
import inspect
from gui.dialogs.new_project_dialog import NewProjectDialog
source = inspect.getsource(NewProjectDialog._validate_and_accept)
self.assertIn('not safe_name', source,
"_validate_and_accept muss empty safe_name ablehnen")
class TestAIPanelInlineCodeEscaping(unittest.TestCase):
"""Statischer Test: Inline-Code-Blöcke in _format_code_blocks müssen HTML-escaped werden."""
def test_inline_code_html_escaped(self):
"""Ohne Escaping: `a < b` → <code>a < b</code> → `<b>` wird als HTML-Tag geparst."""
import inspect
from gui.panels.ai_panel import AIAssistantPanel
source = inspect.getsource(AIAssistantPanel._format_code_blocks)
self.assertNotIn(r'r\'<code style="background-color: #1e1e1e; padding: 2px 4px;">\1</code>\'', source,
"_format_code_blocks darf Inline-Code nicht ohne HTML-Escaping einsetzen")
self.assertIn('escape_html', source,
"_format_code_blocks muss _escape_html für Inline-Code verwenden")
class TestNewProjectDialogAPIContract(unittest.TestCase):
"""Statischer Test: main_window ruft get_values(), nicht get_project_info()."""
def test_main_window_calls_get_values_not_get_project_info(self):
"""main_window.py:_new_project rief get_project_info() — Methode existiert nicht → AttributeError."""
main_source = (Path(__file__).parent.parent / 'src' / 'gui' / 'main_window.py').read_text(encoding='utf-8')
self.assertNotIn('get_project_info', main_source,
"main_window.py darf get_project_info() nicht aufrufen — Methode heißt get_values()")
from gui.dialogs.new_project_dialog import NewProjectDialog
self.assertTrue(hasattr(NewProjectDialog, 'get_values'),
"NewProjectDialog muss get_values() definieren")
class TestBuildDialogWorkerCleanup(unittest.TestCase):
"""Statischer Test: BuildDialog muss reject() überschreiben um Worker zu stoppen."""
def test_reject_overrides_to_stop_worker(self):
"""Ohne reject()-Override: Worker läuft nach Dialog-Schließen weiter → Crash."""
import inspect
from gui.dialogs.build_dialog import BuildDialog
source = inspect.getsource(BuildDialog)
self.assertIn('def reject(self)', source, "BuildDialog muss reject() überschreiben")
self.assertIn('_worker.terminate()', source, "reject() muss terminate() aufrufen (quit() hat keinen Effekt ohne Event-Loop)")
class TestMainWindowShortcuts(unittest.TestCase):
"""Statischer Test: keine doppelten Keyboard-Shortcuts in main_window.py"""
def test_no_duplicate_shortcuts(self):
"""Zwei Aktionen mit demselben Shortcut im selben Fenster führen zu Qt-Ambiguität."""
import re
source_path = Path(__file__).parent.parent / 'src' / 'gui' / 'main_window.py'
source = source_path.read_text(encoding='utf-8')
shortcuts = re.findall(r'setShortcut\(QKeySequence\("(.+?)"\)\)', source)
non_empty = [s for s in shortcuts if s]
duplicates = [s for s in set(non_empty) if non_empty.count(s) > 1]
self.assertEqual(duplicates, [], f"Doppelte Shortcuts: {duplicates}")
class TestSettingsManagerGeneralSection(unittest.TestCase):
"""Bug 24: reset_to_defaults() setzte general.open_last_project nicht zurück."""
def setUp(self):
self.temp_dir = tempfile.mkdtemp()
def tearDown(self):
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_general_open_last_project_persists_round_trip(self):
"""general.open_last_project muss save/load-Round-Trip überstehen."""
from core.settings_manager import SettingsManager
path = os.path.join(self.temp_dir, 'settings.json')
sm = SettingsManager(settings_path=path)
sm.set('general.open_last_project', True)
sm2 = SettingsManager(settings_path=path)
self.assertTrue(sm2.get('general.open_last_project', False),
"general.open_last_project muss nach Reload True sein")
def test_reset_to_defaults_clears_open_last_project(self):
"""reset_to_defaults() muss general.open_last_project auf False zurücksetzen."""
from core.settings_manager import SettingsManager
path = os.path.join(self.temp_dir, 'settings.json')
sm = SettingsManager(settings_path=path)
sm.set('general.open_last_project', True, save=False)
sm.reset_to_defaults()
self.assertFalse(sm.get('general.open_last_project', False),
"Nach reset_to_defaults muss open_last_project False sein")
class TestSettingsDialogGeneralTab(unittest.TestCase):
"""Bug 23: general.open_last_project war nicht über UI setzbar."""
def test_settings_dialog_saves_open_last_project(self):
"""settings_dialog.py muss general.open_last_project speichern."""
source = (Path(__file__).parent.parent / 'src' / 'gui' / 'dialogs' / 'settings_dialog.py').read_text(encoding='utf-8')
self.assertIn("general.open_last_project", source,
"SettingsDialog muss general.open_last_project setzen")
def test_settings_dialog_has_open_last_project_attribute(self):
"""SettingsDialog muss open_last_project-Widget besitzen."""
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
self.assertIn('open_last_project', inspect.getsource(SettingsDialog))
class TestSettingsDialogResetConfirmation(unittest.TestCase):
"""Das Zurücksetzen darf bei Enter nicht unbeabsichtigt bestätigt werden."""
def test_reset_confirmation_defaults_to_no(self):
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
source = inspect.getsource(SettingsDialog._reset_settings)
self.assertIn(
'QMessageBox.StandardButton.No,',
source,
"Die Zurücksetzen-Bestätigung muss standardmäßig Nein auswählen.",
)
class TestSettingsDialogLineNumbersKey(unittest.TestCase):
"""Bug 27: settings_dialog verwendete 'editor.line_numbers' statt kanonischem 'editor.show_line_numbers'."""
def test_dialog_uses_canonical_show_line_numbers_key(self):
"""editor.show_line_numbers ist das kanonische Feld; 'editor.line_numbers' landet in extra_settings."""
import inspect
from gui.dialogs.settings_dialog import SettingsDialog
src = inspect.getsource(SettingsDialog._load_settings) + inspect.getsource(SettingsDialog._save_settings)
self.assertIn('editor.show_line_numbers', src,
"Dialog muss 'editor.show_line_numbers' (kanonisch) verwenden")
self.assertNotIn("'editor.line_numbers'", src,
"Dialog darf falschen Key 'editor.line_numbers' nicht mehr verwenden")
def test_main_window_uses_canonical_key_directly(self):
"""_apply_editor_settings muss 'editor.show_line_numbers' direkt lesen, kein Fallback-Shim."""
import inspect
from gui.main_window import MainWindow
src = inspect.getsource(MainWindow._apply_editor_settings)
self.assertNotIn("'editor.line_numbers'", src,
"_apply_editor_settings darf 'editor.line_numbers' nicht mehr als Fallback lesen")
self.assertIn('editor.show_line_numbers', src,
"_apply_editor_settings muss kanonischen Key 'editor.show_line_numbers' verwenden")
class TestCloseTabSavesCorrectEditor(unittest.TestCase):
"""Bug 26: _close_tab() rief _save_file() auf, das den aktiven (falschen) Tab speichert."""
def test_close_tab_does_not_call_save_file_method(self):
"""_close_tab muss widget.save_file() direkt aufrufen, nicht self._save_file()."""
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow._close_tab)
self.assertNotIn('self._save_file()', source,
"_close_tab darf nicht self._save_file() aufrufen — spart aktiven Tab, nicht den zu schließenden")
self.assertIn('widget.save_file', source,
"_close_tab muss widget.save_file() direkt aufrufen")
class TestMainWindowCloseEventNewFiles(unittest.TestCase):
"""Bug 25: closeEvent prüfte nur open_files, neue Dateien ohne Pfad wurden ignoriert."""
def test_close_event_iterates_editor_tabs_not_open_files(self):
"""closeEvent muss editor_tabs iterieren, nicht open_files, damit neue Dateien erkannt werden."""
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow.closeEvent)
self.assertIn('editor_tabs', source,
"closeEvent muss editor_tabs durchlaufen (nicht nur open_files)")
self.assertNotIn('self.open_files.items()', source,
"closeEvent darf nicht mehr über self.open_files.items() iterieren")
class TestAIPanelNonCodeTextEscaped(unittest.TestCase):
"""Bug 35: _format_code_blocks() escapte nur Code-Blöcke, nicht den normalen Text.
Vergleichsoperatoren wie x > 0 außerhalb von Code-Blöcken wurden als rohes HTML interpretiert."""
def _make_panel(self):
import sys
from PySide6.QtWidgets import QApplication
if not QApplication.instance():
QApplication(sys.argv)
from gui.panels.ai_panel import AIAssistantPanel
return AIAssistantPanel()
def test_non_code_text_with_angle_brackets_is_escaped(self):
panel = self._make_panel()
result = panel._format_code_blocks("Use x > 0 and x < 100")
self.assertIn('>', result, "'>'-Zeichen im normalen Text muss HTML-escaped werden")
self.assertIn('<', result, "'<'-Zeichen im normalen Text muss HTML-escaped werden")
self.assertNotIn('<100', result, "Unescaped '<100' darf nicht im Output erscheinen")
def test_code_block_still_formatted(self):
panel = self._make_panel()
result = panel._format_code_blocks("```python\nif x > 0:\n pass\n```")
self.assertIn('<pre', result, "Code-Blöcke müssen als <pre> formatiert werden")
self.assertIn('>', result, "'>'-Zeichen im Code-Block muss escaped werden")
class TestCloseEventNoSaveFileAsCall(unittest.TestCase):
"""Bug 34: closeEvent() rief _save_file_as() für unbenannte Dateien auf.
_save_file_as() holt den Editor via _get_current_editor() (aktiver Tab), nicht den Editor aus der Schleife."""
def test_close_event_does_not_delegate_to_save_file_as(self):
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow.closeEvent)
self.assertNotIn('self._save_file_as()', source,
"closeEvent() darf _save_file_as() nicht aufrufen (würde falschen Editor speichern)")
self.assertIn('QFileDialog', source,
"closeEvent() muss Save-As-Dialog direkt aufrufen")
class TestSaveFileAsRemovesOldPath(unittest.TestCase):
"""Bug 33: _save_file_as() entfernte den alten Pfad nicht aus open_files.
Nach 'Speichern unter' zeigten beide Pfade auf denselben Editor."""
def test_save_file_as_clears_old_open_files_entry(self):
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow._save_file_as)
self.assertIn('old_path', source,
"_save_file_as() muss den alten Pfad vor dem Speichern sichern")
self.assertIn('del self.open_files', source,
"_save_file_as() muss den alten Eintrag aus open_files entfernen")
def test_save_file_as_checks_save_return_value(self):
"""Regression: _save_file_as() muss den Rückgabewert von save_file() prüfen.
Bei Fehler: open_files konsistent halten und Fehler-Dialog zeigen.
Ohne Fix: open_files[new_path] gesetzt, old_path entfernt, obwohl Datei nicht gespeichert."""
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow._save_file_as)
self.assertIn('editor.save_file(path)', source,
"_save_file_as() muss den Rückgabewert von save_file(path) prüfen")
# Der Rückgabewert muss ausgewertet werden — entweder via if oder Zuweisung
self.assertTrue(
'if editor.save_file(path)' in source or 'ok = editor.save_file(path)' in source,
"_save_file_as() muss open_files nur bei erfolgreichem Speichern aktualisieren"
)
def test_save_file_checks_save_return_value(self):
"""Regression: _save_file() muss den Rückgabewert von save_file() prüfen.
Bei Fehler soll ein Fehler-Dialog erscheinen, kein stilles Scheitern."""
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow._save_file)
self.assertIn('editor.save_file()', source,
"_save_file() muss save_file() aufrufen")
self.assertNotIn('editor.save_file()\n', source,
"_save_file() darf den Rückgabewert nicht verwerfen (Zeile ohne Zuweisung/if)")
class TestNewProjectDialogOptionsUsed(unittest.TestCase):
"""Bug 32: _new_project() rief get_options() auf, nutzte das Ergebnis aber nie.
Git-Init- und venv-Checkbox-Wahl des Users wurden still ignoriert."""
def test_new_project_uses_init_git_option(self):
import inspect
from gui.main_window import MainWindow
source = inspect.getsource(MainWindow._new_project)
self.assertIn('init_git', source,
"_new_project() muss die init_git-Option aus get_options() verwenden")
self.assertIn('git', source,
"_new_project() muss git init ausführen wenn init_git=True")
class TestAIServiceTemperaturePassthrough(unittest.TestCase):
"""Bug 31: complete() übergab temperature nie an die API — Einstellung hatte keinen Effekt."""
def test_complete_includes_temperature_in_kwargs(self):
import inspect
from modules.ai_assistant.ai_service import AIService
source = inspect.getsource(AIService.complete)
self.assertIn('temperature', source,
"complete() muss temperature an den API-Aufruf übergeben")
self.assertIn('self.temperature', source,
"complete() muss self.temperature in kwargs aufnehmen")
class TestLicenseGeneratorSubprocessEncoding(unittest.TestCase):
"""Bug 30: subprocess.run(..., text=True) ohne encoding='utf-8' → cp1252 auf Windows."""
def test_get_licenses_subprocess_calls_use_utf8(self):
import inspect
from modules.builder.license_generator import LicenseGenerator
source = inspect.getsource(LicenseGenerator.get_licenses)
# Jeder text=True-Aufruf muss encoding='utf-8' daneben haben
import re
runs = re.findall(r'subprocess\.run\([^)]+\)', source, re.DOTALL)
for call in runs:
if 'text=True' in call:
self.assertIn("encoding='utf-8'", call,
f"subprocess.run mit text=True benötigt encoding='utf-8': {call[:80]}")
class TestBuildDialogLoadDefaultsEncoding(unittest.TestCase):
"""Bug 29: _load_defaults() öffnete requirements.txt ohne encoding='utf-8'.
UnicodeDecodeError wurde nicht abgefangen → Absturz bei UTF-8-Zeichen."""
def test_load_defaults_uses_utf8_and_catches_unicode_error(self):
import inspect
from gui.dialogs.build_dialog import BuildDialog
source = inspect.getsource(BuildDialog._load_defaults)
self.assertIn("encoding='utf-8'", source,
"_load_defaults muss requirements.txt mit encoding='utf-8' öffnen")
self.assertIn('UnicodeDecodeError', source,
"_load_defaults muss UnicodeDecodeError abfangen")
class TestSettingsManagerSavePreservesRecentProjects(unittest.TestCase):
"""Bug 28: SettingsManager._save() überschrieb recent_projects mit veralteter Kopie aus _extra_settings."""