|
| 1 | +import os |
| 2 | + |
| 3 | +from backtracepython.source_code_handler import SourceCodeHandler |
| 4 | + |
| 5 | + |
| 6 | +def write_file(path, content): |
| 7 | + with open(str(path), "w") as f: |
| 8 | + f.write(content) |
| 9 | + |
| 10 | + |
| 11 | +def make_report(source_paths): |
| 12 | + """Build a minimal report whose main thread stack references the given file paths.""" |
| 13 | + stack = [ |
| 14 | + {"sourceCode": path, "line": 10, "funcName": "test"} for path in source_paths |
| 15 | + ] |
| 16 | + return { |
| 17 | + "mainThread": "main", |
| 18 | + "threads": { |
| 19 | + "main": {"stack": stack}, |
| 20 | + }, |
| 21 | + } |
| 22 | + |
| 23 | + |
| 24 | +def test_collect_removes_unreadable_sources_without_runtime_error(): |
| 25 | + """Reproduces RuntimeError: dictionary changed size during iteration. |
| 26 | +
|
| 27 | + When every source file in the stack is unreadable, collect() used to pop |
| 28 | + entries from the source_code dict while iterating over it. |
| 29 | + """ |
| 30 | + handler = SourceCodeHandler(tab_width=4, context_line_count=3) |
| 31 | + report = make_report( |
| 32 | + [ |
| 33 | + "/nonexistent/path/a.py", |
| 34 | + "/nonexistent/path/b.py", |
| 35 | + ] |
| 36 | + ) |
| 37 | + |
| 38 | + # Before the fix this raised: |
| 39 | + # RuntimeError: dictionary changed size during iteration |
| 40 | + result = handler.collect(report) |
| 41 | + |
| 42 | + assert result["sourceCode"] == {} |
| 43 | + |
| 44 | + |
| 45 | +def test_collect_keeps_readable_sources(tmp_path): |
| 46 | + """Verify that readable source files are collected normally.""" |
| 47 | + source_file = tmp_path / "real.py" |
| 48 | + write_file(source_file, "foobarbaz") |
| 49 | + |
| 50 | + handler = SourceCodeHandler(tab_width=4, context_line_count=1) |
| 51 | + report = make_report([str(source_file)]) |
| 52 | + |
| 53 | + result = handler.collect(report) |
| 54 | + |
| 55 | + assert str(source_file) in result["sourceCode"] |
| 56 | + assert "text" in result["sourceCode"][str(source_file)] |
| 57 | + |
| 58 | + |
| 59 | +def test_collect_mixed_readable_and_unreadable(tmp_path): |
| 60 | + """Mix of existing and missing files""" |
| 61 | + source_file = tmp_path / "exists.py" |
| 62 | + write_file(source_file, "foobarbaz") |
| 63 | + |
| 64 | + handler = SourceCodeHandler(tab_width=4, context_line_count=3) |
| 65 | + report = make_report( |
| 66 | + [ |
| 67 | + "/nonexistent/path/missing.py", |
| 68 | + str(source_file), |
| 69 | + "/another/missing/file.py", |
| 70 | + ] |
| 71 | + ) |
| 72 | + |
| 73 | + result = handler.collect(report) |
| 74 | + |
| 75 | + assert str(source_file) in result["sourceCode"] |
| 76 | + assert "/nonexistent/path/missing.py" not in result["sourceCode"] |
| 77 | + assert "/another/missing/file.py" not in result["sourceCode"] |
0 commit comments