File size: 11,087 Bytes
81e3673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""
Flaky Test Detection Script for Atom Test Suite

This script identifies flaky tests by running tests multiple times with different
random seeds and recording which tests fail intermittently.

Flaky tests are those that:
  - Fail in some runs but pass in others (inconsistent behavior)
  - Often indicate race conditions, timing issues, or shared state problems

Usage:
    python detect_flaky_tests.py --runs 3 --update-json
    python detect_flaky_tests.py --help

Exit Codes:
    0: No flaky tests detected
    1: Flaky tests found
    2: Error in execution
"""

import argparse
import json
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Set, Tuple


def run_tests_with_seed(seed: int, test_path: str = "tests/", verbose: bool = False) -> Set[str]:
    """
    Run pytest with a specific random seed and return failed test names.

    Args:
        seed: Random seed for test order randomization
        test_path: Path to tests directory
        verbose: Enable verbose output

    Returns:
        Set of failed test names
    """
    cmd = [
        "python3", "-m", "pytest",
        test_path,
        "-q",
        "--random-order-seed", str(seed),
        "--tb=no",
        "--no-header"
    ]

    if verbose:
        print(f"\nRunning: {' '.join(cmd)}")

    result = subprocess.run(
        cmd,
        capture_output=True,
        text=True,
        cwd=Path(__file__).parent.parent.parent
    )

    # Parse failed tests from output
    failed_tests = set()

    # pytest output format: "FAILED tests/test_module.py::test_function"
    for line in result.stdout.split('\n'):
        if line.startswith('FAILED '):
            test_name = line.split(' ', 1)[1].strip()
            failed_tests.add(test_name)

    if verbose:
        print(f"Failed tests (seed={seed}): {len(failed_tests)}")
        for test in failed_tests:
            print(f"  - {test}")

    return failed_tests


def parse_test_results(output: str) -> Set[str]:
    """
    Parse pytest output to extract failed test names.

    Args:
        output: Pytest stdout/stderr combined output

    Returns:
        Set of failed test names
    """
    failed_tests = set()

    for line in output.split('\n'):
        if line.startswith('FAILED '):
            test_name = line.split(' ', 1)[1].strip()
            failed_tests.add(test_name)

    return failed_tests


def compare_results(results_list: List[Set[str]]) -> Dict[str, int]:
    """
    Compare test results across multiple runs to count failures.

    Args:
        results_list: List of failed test sets from each run

    Returns:
        Dictionary mapping test name to failure count
    """
    failure_counts = {}

    for failed_set in results_list:
        for test_name in failed_set:
            if test_name not in failure_counts:
                failure_counts[test_name] = 0
            failure_counts[test_name] += 1

    return failure_counts


def identify_flaky(failure_counts: Dict[str, int], total_runs: int) -> Dict[str, float]:
    """
    Identify flaky tests from failure counts.

    Flaky tests fail in at least one run but not all runs.
    They exhibit inconsistent behavior across multiple runs.

    Args:
        failure_counts: Dictionary of test -> failure count
        total_runs: Total number of test runs

    Returns:
        Dictionary mapping flaky test to failure frequency (0-1)
    """
    flaky_tests = {}

    for test_name, failures in failure_counts.items():
        # Flaky: fails in some runs but not all (0 < failures < total_runs)
        if 0 < failures < total_runs:
            frequency = failures / total_runs
            flaky_tests[test_name] = frequency

    return flaky_tests


def update_health_json(flaky_tests: Dict[str, float], phase: str = "090", plan: str = "02") -> None:
    """
    Update test_health.json with flaky test entries.

    Args:
        flaky_tests: Dictionary of flaky test -> failure frequency
        phase: Current phase number
        plan: Current plan number
    """
    health_file = Path(__file__).parent.parent / "coverage_reports" / "metrics" / "test_health.json"

    # Load existing health data or create new structure
    if health_file.exists():
        try:
            with open(health_file, 'r') as f:
                health_data = json.load(f)
        except (json.JSONDecodeError, IOError):
            health_data = {}
    else:
        health_data = {}

    # Ensure structure exists
    if "flaky_tests" not in health_data:
        health_data["flaky_tests"] = []
    if "metadata" not in health_data:
        health_data["metadata"] = {}

    # Add current flaky test detection results
    timestamp = datetime.now().isoformat()
    for test_name, frequency in flaky_tests.items():
        entry = {
            "test_name": test_name,
            "failure_frequency": round(frequency, 2),
            "detected_date": timestamp,
            "phase": phase,
            "plan": plan
        }
        health_data["flaky_tests"].append(entry)

    # Update metadata
    health_data["metadata"]["format_version"] = 1
    health_data["metadata"]["last_flaky_scan"] = timestamp

    # Write back to file
    health_file.parent.mkdir(parents=True, exist_ok=True)
    with open(health_file, 'w') as f:
        json.dump(health_data, f, indent=2)


def print_summary(
    flaky_tests: Dict[str, float],
    total_runs: int,
    failure_counts: Dict[str, int],
    verbose: bool = False
) -> None:
    """
    Print formatted summary of flaky test detection.

    Args:
        flaky_tests: Dictionary of flaky test -> failure frequency
        total_runs: Total number of test runs
        failure_counts: All failure counts (including stable failures)
        verbose: Enable verbose output
    """
    print("\n" + "="*70)
    print("FLAKY TEST DETECTION")
    print("="*70)

    print(f"\nTest Runs: {total_runs}")
    print(f"Total Failed Tests (across all runs): {len(failure_counts)}")
    print(f"Flaky Tests (inconsistent failures): {len(flaky_tests)}")

    if flaky_tests:
        print("\n" + "-"*70)
        print("FLAKY TESTS DETECTED:")
        print("-"*70)

        # Sort by failure frequency (most frequent first)
        sorted_tests = sorted(
            flaky_tests.items(),
            key=lambda x: x[1],
            reverse=True
        )

        for test_name, frequency in sorted_tests:
            failure_pct = frequency * 100
            failure_count = int(frequency * total_runs)
            print(f"\n  {test_name}")
            print(f"    Failed {failure_count}/{total_runs} times ({failure_pct:.0f}%)")

        print("\n" + "="*70)
        print("STATUS: FLAKY TESTS FOUND ✗")
        print("="*70)
        print("\nRECOMMENDED ACTIONS:")
        print("  1. Investigate race conditions or timing dependencies")
        print("  2. Check for shared state between tests")
        print("  3. Add proper mocks for external dependencies")
        print("  4. Use unique_resource_name fixture for parallel isolation")
        print("  5. Mark with @pytest.mark.flaky as TEMPORARY workaround")
        print("="*70 + "\n")
    else:
        if failure_counts:
            print("\n" + "-"*70)
            print("STABLE FAILURES (not flaky):")
            print("-"*70)
            for test_name in failure_counts.keys():
                print(f"  - {test_name}")
            print("-"*70)

        print("\n" + "="*70)
        print("STATUS: NO FLAKY TESTS ✓")
        print("="*70 + "\n")

    if verbose and failure_counts:
        print("\nVerbose Output:")
        print("All Test Failures by Frequency:")
        for test_name, count in sorted(failure_counts.items(), key=lambda x: x[1], reverse=True):
            print(f"  {test_name}: {count}/{total_runs} failures")
        print()


def main():
    """Main entry point for flaky test detection."""
    parser = argparse.ArgumentParser(
        description="Detect flaky tests by running multiple times with random seeds",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python detect_flaky_tests.py --runs 3
  python detect_flaky_tests.py --runs 2 --update-json --verbose
  python detect_flaky_tests.py --runs 3 --test-path tests/unit/

Exit Codes:
  0: No flaky tests detected
  1: Flaky tests found
  2: Error in execution

How it works:
  1. Runs the test suite N times with different random seeds
  2. Records which tests fail in each run
  3. Identifies tests that fail inconsistently (not 0 or N failures)
  4. Updates test_health.json with flaky test entries

Flaky tests indicate:
  - Race conditions in parallel execution
  - Timing dependencies without proper mocking
  - Shared state between tests
  - Non-deterministic test data
        """
    )

    parser.add_argument(
        "--runs",
        type=int,
        default=3,
        help="Number of test runs (default: 3)"
    )

    parser.add_argument(
        "--test-path",
        type=str,
        default="tests/",
        help="Path to tests directory (default: tests/)"
    )

    parser.add_argument(
        "--update-json",
        action="store_true",
        help="Update test_health.json with flaky test entries"
    )

    parser.add_argument(
        "--verbose",
        action="store_true",
        help="Enable verbose output"
    )

    parser.add_argument(
        "--phase",
        type=str,
        default="090",
        help="Current phase number for health tracking (default: 090)"
    )

    parser.add_argument(
        "--plan",
        type=str,
        default="02",
        help="Current plan number for health tracking (default: 02)"
    )

    args = parser.parse_args()

    if args.runs < 2:
        print("ERROR: --runs must be at least 2 for flaky test detection")
        sys.exit(2)

    print("="*70)
    print(f"FLAKY TEST DETECTION: {args.runs} runs with random seeds")
    print("="*70)

    # Run tests multiple times with different seeds
    results_list = []
    for i in range(args.runs):
        seed = i * 1000  # Use different seeds: 0, 1000, 2000, ...
        print(f"\nRun {i+1}/{args.runs} (seed={seed})...", end=" ")

        failed_tests = run_tests_with_seed(seed, args.test_path, args.verbose)
        results_list.append(failed_tests)

        print(f"{len(failed_tests)} failed")

    # Compare results across runs
    failure_counts = compare_results(results_list)

    # Identify flaky tests (inconsistent failures)
    flaky_tests = identify_flaky(failure_counts, args.runs)

    # Print summary
    print_summary(flaky_tests, args.runs, failure_counts, args.verbose)

    # Update health JSON if requested
    if args.update_json and flaky_tests:
        update_health_json(flaky_tests, phase=args.phase, plan=args.plan)
        if args.verbose:
            print(f"Updated test_health.json with {len(flaky_tests)} flaky tests\n")

    # Return exit code
    if flaky_tests:
        sys.exit(1)
    else:
        sys.exit(0)


if __name__ == "__main__":
    main()