-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtestrules.py
More file actions
1469 lines (1185 loc) · 49.9 KB
/
Copy pathtestrules.py
File metadata and controls
1469 lines (1185 loc) · 49.9 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
#!/usr/bin/env python3
"""
Lightweight Test Runner
A simple, efficient Python testing framework that provides test discovery at the method level,
code coverage reporting, and basic linting capabilities.
Usage:
python testrules.py [group|test_module1 test_module2 ...|lint|check|unit|integration|e2e|regression]
Examples:
python testrules.py # Run all tests
python testrules.py unit # Run unit tests only
python testrules.py integration # Run integration tests only
python testrules.py e2e # Run end-to-end tests only
python testrules.py regression # Run regression tests only
python testrules.py lint # Run linting only
python testrules.py check # Run both linting and all tests
python testrules.py core # Run tests in 'core' group (if defined in config)
python testrules.py test_module1 test_module2 # Run specific test modules
"""
import sys
import os
import json
import time
import unittest
import importlib
import importlib.util
import glob
from typing import Dict, List, Optional, Any, Tuple
import traceback
try:
import coverage
COVERAGE_AVAILABLE = True
except ImportError:
COVERAGE_AVAILABLE = False
print("Warning: coverage package not available. Install with: pip install coverage")
try:
import flake8.api.legacy as flake8
FLAKE8_AVAILABLE = True
except ImportError:
FLAKE8_AVAILABLE = False
print("Warning: flake8 package not available. Install with: pip install flake8")
class TestMethod:
"""
Represents a test method.
"""
def __init__(self, name, module, class_name=None, file_path=None):
self.name = name
self.module = module
self.class_name = class_name
self.file_path = file_path
self.full_name = f"{module}.{class_name}.{name}" if class_name else f"{module}.{name}"
def __str__(self):
return self.full_name
def __repr__(self):
return f"TestMethod(name='{self.name}', module='{self.module}', class_name='{self.class_name}')"
class MethodResult:
"""
Represents the result of executing a test method.
"""
def __init__(self, method, status, duration, error=None, traceback_str=None):
self.method = method
self.status = status # "pass", "fail", or "error"
self.duration = duration
self.error = error
self.traceback_str = traceback_str
def __str__(self):
return f"{self.method.full_name} ... {self.status.upper()}"
def __repr__(self):
return f"MethodResult(method={self.method.full_name}, status='{self.status}', duration={self.duration})"
class TestResult:
"""
Container for test results.
"""
def __init__(self):
self.total = 0
self.passed = 0
self.failed = 0
self.errors = 0
self.method_results = []
self.duration = 0.0
self.start_time = None
self.end_time = None
def add_result(self, method_result):
"""
Add a method result to the test results.
Args:
method_result: MethodResult object to add
"""
self.method_results.append(method_result)
self.total += 1
if method_result.status == "pass":
self.passed += 1
elif method_result.status == "fail":
self.failed += 1
elif method_result.status == "error":
self.errors += 1
def start_timing(self):
"""Start timing the test run."""
self.start_time = time.time()
def stop_timing(self):
"""Stop timing the test run and calculate duration."""
self.end_time = time.time()
if self.start_time:
self.duration = self.end_time - self.start_time
def get_success_rate(self):
"""
Calculate the success rate as a percentage.
Returns:
Success rate as a float (0.0 to 100.0)
"""
if self.total == 0:
return 0.0
return (self.passed / self.total) * 100.0
def get_failed_results(self):
"""
Get all failed and error method results.
Returns:
List of MethodResult objects with status 'fail' or 'error'
"""
return [result for result in self.method_results if result.status in ['fail', 'error']]
def __str__(self):
return f"TestResult(total={self.total}, passed={self.passed}, failed={self.failed}, errors={self.errors})"
class Config:
"""
Configuration for the test runner.
"""
def __init__(self, data=None):
self.data = data or {}
self.test_patterns = self.data.get("test_patterns", {
"unit": ["test_*.py", "*_test.py"],
"integration": ["integration_test_*.py", "*_integration_test.py"],
"e2e": ["e2e_test_*.py", "*_e2e_test.py"],
"regression": ["regression_test_*.py", "*_regression_test.py"]
})
self.test_groups = self.data.get("test_groups", {"all": []})
self.coverage_enabled = self.data.get("coverage_enabled", True)
self.html_coverage = self.data.get("html_coverage", True)
self.html_coverage_dir = self.data.get("html_coverage_dir", "htmlcov")
def get_test_types(self):
"""
Get all available test types.
Returns:
List of test type names
"""
return list(self.test_patterns.keys())
def get_patterns_for_test_type(self, test_type):
"""
Get file patterns for a specific test type.
Args:
test_type: The test type to get patterns for
Returns:
List of file patterns for the test type, or empty list if not found
"""
return self.test_patterns.get(test_type, [])
def has_test_type(self, test_type):
"""
Check if a test type is configured.
Args:
test_type: The test type to check
Returns:
True if the test type is configured, False otherwise
"""
return test_type in self.test_patterns
def add_custom_test_type(self, test_type, patterns):
"""
Add a custom test type with its patterns.
Args:
test_type: Name of the custom test type
patterns: List of file patterns for the test type
"""
self.test_patterns[test_type] = patterns
def get_all_patterns(self):
"""
Get all file patterns from all test types.
Returns:
List of all file patterns
"""
all_patterns = []
for patterns in self.test_patterns.values():
all_patterns.extend(patterns)
return list(set(all_patterns)) # Remove duplicates
def get_test_files_by_type(test_type, config, search_path="."):
"""
Get test files for a specific test type based on configured patterns.
Args:
test_type: The test type to get files for
config: Config object containing test patterns
search_path: Directory to search in (default: current directory)
Returns:
List of test file paths matching the test type patterns
"""
if not config.has_test_type(test_type):
print(f"⚠️ Unknown test type: {test_type}")
return []
patterns = config.get_patterns_for_test_type(test_type)
test_files = []
for pattern in patterns:
# Search recursively for files matching the pattern
search_pattern = os.path.join(search_path, "**", pattern)
matching_files = glob.glob(search_pattern, recursive=True)
test_files.extend(matching_files)
# Remove duplicates and sort
test_files = sorted(list(set(test_files)))
return test_files
def get_all_test_files(config, search_path="."):
"""
Get all test files based on all configured patterns.
Args:
config: Config object containing test patterns
search_path: Directory to search in (default: current directory)
Returns:
Dictionary mapping test types to their test files
"""
all_test_files = {}
for test_type in config.get_test_types():
test_files = get_test_files_by_type(test_type, config, search_path)
if test_files:
all_test_files[test_type] = test_files
return all_test_files
def discover_files_by_modules(module_names, search_path="."):
"""
Discover test files by explicit module names.
Args:
module_names: List of module names to discover
search_path: Directory to search in (default: current directory)
Returns:
List of test file paths for the specified modules
"""
test_files = []
for module_name in module_names:
# Try different possible file paths for the module
possible_paths = [
f"{module_name}.py",
os.path.join(search_path, f"{module_name}.py"),
os.path.join(search_path, "**", f"{module_name}.py"),
]
found = False
for path in possible_paths:
if "**" in path:
# Use glob for recursive search
matching_files = glob.glob(path, recursive=True)
if matching_files:
test_files.extend(matching_files)
found = True
break
else:
# Direct file check
if os.path.exists(path):
test_files.append(path)
found = True
break
if not found:
print(f"⚠️ Module file not found: {module_name}")
# Remove duplicates and sort
return sorted(list(set(test_files)))
def resolve_test_group(group_name, config):
"""
Resolve a test group to get the list of modules in that group.
Args:
group_name: Name of the test group
config: Config object containing test groups
Returns:
List of module names in the group, or empty list if group not found
"""
if group_name not in config.test_groups:
print(f"⚠️ Test group '{group_name}' not found in configuration")
return []
modules = config.test_groups[group_name]
print(f"📋 Test group '{group_name}' contains {len(modules)} modules: {modules}")
return modules
def discover_tests(test_type=None, modules=None, group=None, config=None, search_path="."):
"""
Discover test files and methods based on various criteria.
Args:
test_type: Type of tests to discover (unit, integration, e2e, regression)
modules: List of specific modules to test
group: Test group name to resolve from configuration
config: Configuration object
search_path: Directory to search in (default: current directory)
Returns:
List of test file paths
"""
if config is None:
config = Config()
test_files = []
# Priority order: explicit modules > test group > test type > all tests
if modules:
print(f"🎯 Discovering tests for explicit modules: {modules}")
test_files = discover_files_by_modules(modules, search_path)
elif group:
print(f"📋 Discovering tests for group: {group}")
group_modules = resolve_test_group(group, config)
if group_modules:
test_files = discover_files_by_modules(group_modules, search_path)
else:
print(f"⚠️ No modules found in group '{group}' or group doesn't exist")
elif test_type:
print(f"🔍 Discovering tests for type: {test_type}")
test_files = get_test_files_by_type(test_type, config, search_path)
else:
print("🔍 Discovering all test files")
all_test_files = get_all_test_files(config, search_path)
for files in all_test_files.values():
test_files.extend(files)
# Remove duplicates
test_files = sorted(list(set(test_files)))
print(f"📁 Found {len(test_files)} test files")
return test_files
def safe_import_module(module_name, file_path=None):
"""
Safely import a module with comprehensive error handling.
Args:
module_name: Name of the module to import
file_path: Optional file path of the module for dynamic loading
Returns:
Tuple of (module, success_flag, error_message)
"""
try:
if file_path and os.path.exists(file_path):
# Dynamic module loading from file path
spec = importlib.util.spec_from_file_location(module_name, file_path)
if spec and spec.loader:
module = importlib.util.module_from_spec(spec)
# Add the module's directory to sys.path temporarily
module_dir = os.path.dirname(os.path.abspath(file_path))
if module_dir not in sys.path:
sys.path.insert(0, module_dir)
path_added = True
else:
path_added = False
try:
spec.loader.exec_module(module)
return module, True, None
finally:
# Remove the added path
if path_added:
sys.path.remove(module_dir)
else:
return None, False, f"Could not create module spec for {module_name} at {file_path}"
else:
# Standard module import
module = importlib.import_module(module_name)
return module, True, None
except ImportError as e:
return None, False, f"ImportError: {e}"
except SyntaxError as e:
return None, False, f"SyntaxError in {module_name}: {e}"
except Exception as e:
return None, False, f"Unexpected error importing {module_name}: {e}"
def inspect_module_for_tests(module_name, file_path=None):
"""
Inspect a module to find test methods using reflection with safe importing.
Args:
module_name: Name of the module to inspect
file_path: Optional file path of the module
Returns:
List of TestMethod objects found in the module
"""
test_methods = []
# Safely import the module
module, success, error_msg = safe_import_module(module_name, file_path)
if not success:
print(f"⚠️ Failed to import module {module_name}: {error_msg}")
return test_methods
try:
# Find all classes in the module
for attr_name in dir(module):
try:
attr = getattr(module, attr_name)
# Check if it's a class and inherits from unittest.TestCase
if (isinstance(attr, type) and
issubclass(attr, unittest.TestCase) and
attr != unittest.TestCase):
class_name = attr_name
# Find all test methods in the class
for method_name in dir(attr):
if method_name.startswith('test'):
try:
method_obj = getattr(attr, method_name)
if callable(method_obj):
test_method = TestMethod(
name=method_name,
module=module_name,
class_name=class_name,
file_path=file_path
)
test_methods.append(test_method)
except Exception as e:
print(f"⚠️ Error accessing method {method_name} in {class_name}: {e}")
continue
except Exception as e:
print(f"⚠️ Error accessing attribute {attr_name} in module {module_name}: {e}")
continue
# Also check for standalone test functions (not in classes)
for attr_name in dir(module):
if attr_name.startswith('test'):
try:
attr = getattr(module, attr_name)
# Make sure it's a function and not a class
if callable(attr) and not isinstance(attr, type):
test_method = TestMethod(
name=attr_name,
module=module_name,
class_name=None,
file_path=file_path
)
test_methods.append(test_method)
except Exception as e:
print(f"⚠️ Error accessing function {attr_name} in module {module_name}: {e}")
continue
except Exception as e:
print(f"⚠️ Error inspecting module {module_name}: {e}")
return test_methods
def discover_test_methods(test_files):
"""
Discover test methods from a list of test files with graceful error handling.
Args:
test_files: List of test file paths
Returns:
Dictionary mapping module names to lists of TestMethod objects
"""
test_methods_by_module = {}
failed_modules = []
for file_path in test_files:
# Convert file path to module name
# Normalize the path and remove leading ./
normalized_path = os.path.normpath(file_path)
if normalized_path.startswith('./'):
normalized_path = normalized_path[2:]
# Convert to module name
module_name = normalized_path.replace('/', '.').replace('\\', '.').replace('.py', '')
# Remove leading dots
while module_name.startswith('.'):
module_name = module_name[1:]
print(f"🔍 Inspecting module: {module_name} ({file_path})")
# Check if file exists
if not os.path.exists(file_path):
print(f"⚠️ File not found: {file_path}")
failed_modules.append(module_name)
continue
# Inspect the module for test methods
test_methods = inspect_module_for_tests(module_name, file_path)
if test_methods:
test_methods_by_module[module_name] = test_methods
print(f" ✅ Found {len(test_methods)} test methods:")
for method in test_methods:
print(f" - {method.full_name}")
else:
print(f" ℹ️ No test methods found in {module_name}")
# Report summary
total_modules = len(test_files)
successful_modules = len(test_methods_by_module)
failed_count = len(failed_modules)
print(f"\n📊 Module Discovery Summary:")
print(f" Total modules processed: {total_modules}")
print(f" Successfully imported: {successful_modules}")
print(f" Failed to import: {failed_count}")
if failed_modules:
print(f" Failed modules: {failed_modules}")
return test_methods_by_module
def run_single_test_method(test_method):
"""
Run a single test method and collect its result.
Args:
test_method: TestMethod object to run
Returns:
MethodResult object containing the test result
"""
start_time = time.time()
try:
# Import the module containing the test
module, success, error_msg = safe_import_module(test_method.module, test_method.file_path)
if not success:
duration = time.time() - start_time
return MethodResult(
method=test_method,
status="error",
duration=duration,
error=f"Failed to import module: {error_msg}",
traceback_str=None
)
# Get the test class and method
if test_method.class_name:
# Test method is in a class
test_class = getattr(module, test_method.class_name)
# Create a test suite with just this method
suite = unittest.TestSuite()
test_instance = test_class(test_method.name)
suite.addTest(test_instance)
else:
# Standalone test function - create a wrapper
test_func = getattr(module, test_method.name)
# Create a test case wrapper for the function
class FunctionTestCase(unittest.TestCase):
def runTest(self):
test_func()
suite = unittest.TestSuite()
suite.addTest(FunctionTestCase())
# Run the test with a custom result collector
result = unittest.TestResult()
suite.run(result)
duration = time.time() - start_time
# Determine the status and extract error information
if result.wasSuccessful():
return MethodResult(
method=test_method,
status="pass",
duration=duration,
error=None,
traceback_str=None
)
elif result.failures:
# Test failed (assertion error)
failure = result.failures[0] # Get first failure
error_msg = str(failure[1])
traceback_str = failure[1]
return MethodResult(
method=test_method,
status="fail",
duration=duration,
error=error_msg,
traceback_str=traceback_str
)
elif result.errors:
# Test had an error (exception)
error = result.errors[0] # Get first error
error_msg = str(error[1])
traceback_str = error[1]
return MethodResult(
method=test_method,
status="error",
duration=duration,
error=error_msg,
traceback_str=traceback_str
)
else:
# Shouldn't happen, but handle gracefully
return MethodResult(
method=test_method,
status="error",
duration=duration,
error="Unknown test result state",
traceback_str=None
)
except Exception as e:
duration = time.time() - start_time
error_msg = str(e)
traceback_str = traceback.format_exc()
return MethodResult(
method=test_method,
status="error",
duration=duration,
error=error_msg,
traceback_str=traceback_str
)
def start_coverage_collection(config):
"""
Initialize and start coverage collection with proper configuration.
Args:
config: Config object containing coverage settings
Returns:
Coverage object if successful, None otherwise
"""
if not COVERAGE_AVAILABLE:
print("⚠️ Coverage package not available. Install with: pip install coverage")
return None
try:
# Initialize coverage with configuration
cov = coverage.Coverage(
branch=True, # Enable branch coverage
source=['.'], # Cover current directory
omit=[
'*/tests/*', # Exclude test files from coverage
'*/test_*', # Exclude test files
'*_test.py', # Exclude test files
'setup.py', # Exclude setup files
'*/venv/*', # Exclude virtual environment
'*/env/*', # Exclude virtual environment
'*/.venv/*', # Exclude virtual environment
]
)
# Start coverage collection
cov.start()
print("📊 Coverage collection started with branch coverage enabled")
return cov
except Exception as e:
print(f"⚠️ Failed to initialize coverage collection: {e}")
return None
def stop_coverage_collection(cov):
"""
Stop coverage collection and save data.
Args:
cov: Coverage object to stop
Returns:
True if successful, False otherwise
"""
if not cov:
return False
try:
cov.stop()
cov.save()
print("📊 Coverage collection completed and data saved")
return True
except Exception as e:
print(f"⚠️ Error stopping coverage collection: {e}")
return False
def generate_coverage_report(cov):
"""
Generate console coverage report with line and branch coverage.
Args:
cov: Coverage object containing coverage data
Returns:
Dictionary containing coverage summary data
"""
if not cov:
print("⚠️ No coverage data available")
return None
try:
# Get coverage data
coverage_data = cov.get_data()
if not coverage_data.measured_files():
print("⚠️ No files were measured for coverage")
return None
# Generate coverage report
print("\n📊 COVERAGE REPORT")
print("=" * 60)
# Print header
print(f"{'Name':<30} {'Stmts':<8} {'Miss':<8} {'Branch':<8} {'BrPart':<8} {'Cover':<8}")
print("-" * 60)
total_statements = 0
total_missing = 0
total_branches = 0
total_partial_branches = 0
# Get coverage analysis for each file
for filename in sorted(coverage_data.measured_files()):
try:
# Get analysis for this file - analysis2 returns a tuple
analysis_result = cov.analysis2(filename)
# analysis2 returns (filename, statements, excluded, missing, missing_formatted)
if len(analysis_result) >= 4:
_, statements_list, _, missing_list = analysis_result[:4]
statements = len(statements_list)
missing = len(missing_list)
else:
# Fallback to basic analysis
statements = 0
missing = 0
missing_list = []
# Get branch coverage if available
try:
branch_stats = cov.branch_stats().get(filename, (0, 0, 0))
branches = branch_stats[0] if len(branch_stats) > 0 else 0
partial_branches = branch_stats[1] if len(branch_stats) > 1 else 0
except:
branches = 0
partial_branches = 0
# Calculate coverage percentage
if statements > 0:
coverage_percent = ((statements - missing) / statements) * 100
else:
coverage_percent = 100.0
# Accumulate totals
total_statements += statements
total_missing += missing
total_branches += branches
total_partial_branches += partial_branches
# Format filename for display
display_name = filename
if len(display_name) > 28:
display_name = "..." + display_name[-25:]
# Print file coverage
print(f"{display_name:<30} {statements:<8} {missing:<8} {branches:<8} {partial_branches:<8} {coverage_percent:>6.1f}%")
# Show missing lines if there are any
if missing > 0 and len(missing_list) <= 10: # Only show if not too many
missing_lines = sorted(missing_list)
missing_ranges = []
if missing_lines:
# Group consecutive lines into ranges
start = missing_lines[0]
end = start
for line in missing_lines[1:]:
if line == end + 1:
end = line
else:
if start == end:
missing_ranges.append(str(start))
else:
missing_ranges.append(f"{start}-{end}")
start = end = line
# Add the last range
if start == end:
missing_ranges.append(str(start))
else:
missing_ranges.append(f"{start}-{end}")
print(f"{'':<30} Missing: {', '.join(missing_ranges)}")
except Exception as e:
print(f"⚠️ Error analyzing coverage for {filename}: {e}")
continue
# Print totals
print("-" * 60)
# Calculate total coverage
if total_statements > 0:
total_coverage = ((total_statements - total_missing) / total_statements) * 100
else:
total_coverage = 100.0
print(f"{'TOTAL':<30} {total_statements:<8} {total_missing:<8} {total_branches:<8} {total_partial_branches:<8} {total_coverage:>6.1f}%")
# Coverage summary
print(f"\n📈 COVERAGE SUMMARY:")
print(f" Lines covered: {total_statements - total_missing}/{total_statements} ({total_coverage:.1f}%)")
if total_branches > 0:
branch_coverage = ((total_branches - total_partial_branches) / total_branches) * 100 if total_branches > 0 else 100.0
print(f" Branches covered: {total_branches - total_partial_branches}/{total_branches} ({branch_coverage:.1f}%)")
# Return summary data
return {
'total_statements': total_statements,
'total_missing': total_missing,
'total_branches': total_branches,
'total_partial_branches': total_partial_branches,
'line_coverage': total_coverage,
'branch_coverage': ((total_branches - total_partial_branches) / total_branches) * 100 if total_branches > 0 else 100.0
}
except Exception as e:
print(f"⚠️ Error generating coverage report: {e}")
return None
def generate_html_coverage_report(cov, config):
"""
Generate HTML coverage report using coverage package.
Args:
cov: Coverage object containing coverage data
config: Config object containing HTML coverage settings
Returns:
True if successful, False otherwise
"""
if not cov:
print("⚠️ No coverage data available for HTML report")
return False
if not config.html_coverage:
print("ℹ️ HTML coverage report generation is disabled in configuration")
return False
try:
# Ensure the HTML coverage directory exists
html_dir = config.html_coverage_dir
if not os.path.exists(html_dir):
os.makedirs(html_dir)
print(f"📁 Created HTML coverage directory: {html_dir}")
# Generate HTML report
print(f"📄 Generating HTML coverage report...")
cov.html_report(directory=html_dir)
# Get the path to the main HTML file
index_path = os.path.join(html_dir, 'index.html')
if os.path.exists(index_path):
# Convert to absolute path for better display
abs_index_path = os.path.abspath(index_path)
print(f"📁 HTML coverage report saved to: {abs_index_path}")
print(f"🌐 Open in browser: file://{abs_index_path}")
return True
else:
print(f"⚠️ HTML report was generated but index.html not found at expected location")
return False
except Exception as e:
print(f"⚠️ Error generating HTML coverage report: {e}")
return False
def run_tests(test_methods_by_module, collect_coverage=True, config=None):
"""
Run tests and collect results.
Args:
test_methods_by_module: Dictionary mapping module names to lists of TestMethod objects
collect_coverage: Whether to collect coverage information
config: Config object containing coverage settings
Returns:
Tuple of (TestResult object, Coverage object or None)
"""
print("🧪 Starting test execution...")
# Initialize test results
test_result = TestResult()
test_result.start_timing()
# Initialize coverage if requested
cov = None
if collect_coverage:
if config is None:
config = Config()
cov = start_coverage_collection(config)
# Count total test methods
total_methods = sum(len(methods) for methods in test_methods_by_module.values())
print(f"🎯 Running {total_methods} test methods across {len(test_methods_by_module)} modules")
current_method = 0
# Run tests for each module
for module_name, test_methods in test_methods_by_module.items():
print(f"\n📦 Running tests in module: {module_name}")
for test_method in test_methods:
current_method += 1
print(f" [{current_method}/{total_methods}] {test_method.full_name} ... ", end="", flush=True)
# Run the test method
method_result = run_single_test_method(test_method)
# Add result to test results
test_result.add_result(method_result)
# Print result with timing
if method_result.status == "pass":
print(f"✅ PASS ({method_result.duration:.3f}s)")
elif method_result.status == "fail":
print(f"❌ FAIL ({method_result.duration:.3f}s)")
elif method_result.status == "error":
print(f"💥 ERROR ({method_result.duration:.3f}s)")
# Stop timing
test_result.stop_timing()
# Stop coverage collection if it was started
stop_coverage_collection(cov)