Loading files
This file is pinned to the selected release. Download the original to open it in your design tool.
"""
Tests for debugger stepping behavior.
Each test evaluates OpenSCAD source with a recording debug hook,
then asserts the expected sequence of debug stops (line, depth,
expr_level, origin).
NOTE (C++ backend): openscad_cpp_evaluator's checkDebug() deliberately
checks at STATEMENT granularity only, not the Python reference's additional
expr_level sub-expression checks (list-comprehension clauses, ternary
branches, individual C-style-for init/condition/incr parts) -- see
Evaluator::checkDebug()'s own doc comment in evaluator.hpp. Tests that
asserted on that finer granularity are adjusted or removed below, with a
comment at each one explaining what changed and why -- not silently dropped.
"""
import tempfile
import time
from pathlib import Path
import pytest
from openscad_cpp_evaluator import Evaluator, EvalError
from belfryscad.window.debugger import _generate_partial_render
def _write(src: str) -> str:
f = tempfile.NamedTemporaryFile(suffix=".scad", mode="w", encoding="utf-8", delete=False)
f.write(src)
f.close()
return f.name
def _make_recorder():
"""Return (hook_fn, stops_list).
The hook records every call as a dict and always returns
("continue", {}) so execution runs to completion.
"""
stops = []
def hook(line, depth, *, forced=False, expr_level=False,
expr_depth=0, origin=None, get_frames=None, generate_partial=None,
get_children_positions=None, set_fast_continue=None):
stops.append({
"line": line,
"depth": depth,
"forced": forced,
"expr_level": expr_level,
"origin": origin,
})
return ("continue", {})
return hook, stops
def _run_with_debug(src: str):
"""Evaluate with a recording debug hook. Returns (bodies, echo_lines, stops)."""
hook, stops = _make_recorder()
echo_lines = []
ev = Evaluator(
echo_fn=lambda msg: echo_lines.append(msg),
debug_hook=hook,
)
bodies, _ = ev.evaluate(_write(src))
return bodies, echo_lines, stops
def _stmt_stops(stops):
"""Filter to statement-level (non-expr_level) stops."""
return [s for s in stops if not s["expr_level"]]
def _lines(stops):
"""Extract just line numbers from a stops list."""
return [s["line"] for s in stops]
# ---------------------------------------------------------------------------
# Basic statement stops
# ---------------------------------------------------------------------------
class TestStatementStops:
def test_sequential_assignments(self):
_, _, stops = _run_with_debug("a = 1;\nb = 2;\nc = 3;\n")
lines = _lines(_stmt_stops(stops))
assert lines == [1, 2, 3]
def test_assignment_depths_are_zero(self):
_, _, stops = _run_with_debug("a = 1;\nb = 2;\n")
for s in _stmt_stops(stops):
assert s["depth"] == 0
def test_echo_is_statement_stop(self):
_, _, stops = _run_with_debug("echo(42);\n")
stmt = _stmt_stops(stops)
assert len(stmt) == 1
assert stmt[0]["line"] == 1
# ---------------------------------------------------------------------------
# Geometry statement stops (ModularCall/modifiers/intersection_for) —
# regression coverage for a bug where _eval_statement's CSG-tree wrapper
# (added in CSG tree Phase 2) intercepts every _TREE_NODE_TYPES node before
# _eval_statement_impl ever runs, but never called _check_debug itself —
# meaning no geometry-producing statement paused the debugger at all, from
# Phase 2 step 1 onward. No existing test caught this since every prior
# test in this file only ever used assignments/control-flow, never a
# geometry statement.
# ---------------------------------------------------------------------------
class TestGeometryStatementStops:
def test_single_primitive_is_statement_stop(self):
_, _, stops = _run_with_debug("cube(1);\n")
stmt = _stmt_stops(stops)
assert len(stmt) == 1
assert stmt[0]["line"] == 1
def test_mixed_assignments_and_geometry_all_stop(self):
# Assignments run before geometry in the same scope (OpenSCAD
# semantics), but every statement should still get its own stop.
_, _, stops = _run_with_debug("a = 1;\ncube(1);\nsphere(1);\nb = 2;\n")
lines = sorted(_lines(_stmt_stops(stops)))
assert lines == [1, 2, 3, 4]
def test_modifier_and_wrapped_child_both_stop(self):
_, _, stops = _run_with_debug("#cube(1);\n")
stmt = _stmt_stops(stops)
assert len(stmt) == 2
assert all(s["line"] == 1 for s in stmt)
def test_boolean_op_and_each_child_stop(self):
_, _, stops = _run_with_debug("union() { cube(1); sphere(1); }\n")
stmt = _stmt_stops(stops)
assert len(stmt) == 3
def test_module_call_stops_at_call_site_and_inside_body(self):
_, _, stops = _run_with_debug("module foo() { cube(1); }\nfoo();\n")
stmt = _stmt_stops(stops)
by_line_depth = sorted((s["line"], s["depth"]) for s in stmt)
assert by_line_depth == [(1, 1), (2, 0)]
# ---------------------------------------------------------------------------
# Ternary conditionals
# ---------------------------------------------------------------------------
class TestTernaryStops:
def test_ternary_has_statement_level_stop(self):
"""Ternary condition should produce a statement-level debug stop."""
_, _, stops = _run_with_debug("a = true ? 1 : 2;\n")
# Line 1: assignment stop + ternary stop (both statement-level)
stmt = _stmt_stops(stops)
stmt_on_line1 = [s for s in stmt if s["line"] == 1]
# At least 2: the assignment itself and the ternary condition
assert len(stmt_on_line1) >= 2
def test_ternary_branch_is_expr_level(self):
"""The chosen ternary branch should be expr_level."""
_, _, stops = _run_with_debug("a = true ? 1 : 2;\n")
expr_stops = [s for s in stops if s["expr_level"] and s["line"] == 1]
assert len(expr_stops) >= 1
# ---------------------------------------------------------------------------
# User-defined function call-site stops
# ---------------------------------------------------------------------------
class TestFunctionCallSiteStops:
def test_function_call_site_stop(self):
"""A call on the SAME line as its enclosing statement produces one
stop, not two.
The call-site stop is real and still fires when the call is on its
own line (see TestListCompStops, which still alternates) -- but on
`a = double(5);` the assignment has already stopped on line 2, and
firing again there made a breakpoint hit twice per execution."""
src = """\
function double(x) = x * 2;
a = double(5);
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
line2_stops = [s for s in stmt if s["line"] == 2]
assert len(line2_stops) == 1 # the assignment only
def test_function_call_increases_depth(self):
"""Inside a user function, depth should be > 0."""
src = """\
function double(x) = x * 2;
a = double(5);
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
all_depths = [s["depth"] for s in stmt]
# Should have depth 0 (assignment, call-site) and depth 1 (function body on line 1)
assert 0 in all_depths
assert 1 in all_depths
def test_no_call_site_stop_for_builtin(self):
"""Built-in functions should NOT produce a call-site debug stop."""
src = "a = len([1,2,3]);\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# Only one statement-level stop: the assignment
assert len(stmt) == 1
assert stmt[0]["line"] == 1
def test_function_call_in_list(self):
"""Function calls inside list literals should get call-site stops."""
src = """\
function f(x) = x + 1;
a = [f(1), f(2), f(3)];
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
line2_stops = [s for s in stmt if s["line"] == 2]
# All three calls sit on the assignment's own line, so all three
# call-site stops collapse into it: one stop, not four.
assert len(line2_stops) == 1
def test_function_literal_call_site_stop(self):
"""Calling a function literal should produce a call-site stop."""
src = """\
f = function(x) x * 2;
a = f(5);
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
line2_stops = [s for s in stmt if s["line"] == 2]
assert len(line2_stops) == 1 # the assignment only
# ---------------------------------------------------------------------------
# Let assignments
# ---------------------------------------------------------------------------
class TestLetStops:
def test_modular_let_stops_at_assignments(self):
"""ModularLet should stop at each assignment, not the let() node."""
src = """\
let(a = 1, b = 2)
echo(a + b);
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
lines = _lines(stmt)
# Should stop at a=1 (line 1), b=2 (line 1), echo (line 2)
assert 2 in lines # echo stop
def test_let_expr_stops_at_assignments(self):
"""let() in expression context should stop at assignments."""
src = """\
a = let(x = 10, y = 20) x + y;
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# Should have assignment stop + let assignment stops
assert len(stmt) >= 2 # at least: a= assignment + x=10 let assignment
# ---------------------------------------------------------------------------
# For loop iteration stops
# ---------------------------------------------------------------------------
class TestForLoopStops:
def test_modular_for_per_iteration_stop(self):
"""ModularFor should fire a debug stop at each iteration."""
src = """\
for(i = [1:3])
echo(i);
"""
_, _, stops = _run_with_debug(src)
# echo fires once per iteration (3 times), so at least 3 statement stops
stmt = _stmt_stops(stops)
echo_stops = [s for s in stmt if s["line"] == 2]
assert len(echo_stops) == 3
def test_modular_for_iteration_stops_are_expr_level(self):
"""ModularFor iteration stops should be expr_level (body statements
already get their own statement-level stops from _eval_statement)."""
src = """\
for(i = [1:3])
echo(i);
"""
_, _, stops = _run_with_debug(src)
expr_stops = [s for s in stops if s["expr_level"]]
assert len(expr_stops) >= 3
# ---------------------------------------------------------------------------
# Modular if/else
# ---------------------------------------------------------------------------
class TestModularIfStops:
def test_if_statement_stop(self):
"""ModularIf should fire a statement-level stop at the if node."""
src = """\
if (true)
echo("yes");
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
lines = _lines(stmt)
assert 1 in lines # if node
assert 2 in lines # echo
def test_if_branch_has_expr_level_stop(self):
"""The chosen branch of an if should have an expr_level stop."""
src = """\
if (true)
echo("yes");
"""
_, _, stops = _run_with_debug(src)
expr_stops = [s for s in stops if s["expr_level"]]
assert len(expr_stops) >= 1
# ---------------------------------------------------------------------------
# List comprehension if stops
# ---------------------------------------------------------------------------
class TestListCompIfStops:
def test_list_comp_if_is_statement_level(self):
"""List comp if() should produce a statement-level debug stop."""
src = """\
a = [
for (i = [0:4])
if (i <= 2)
i * 10
];
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
if_stops = [s for s in stmt if s["line"] == 3]
# 5 iterations, each hitting the if on line 3
assert len(if_stops) == 5
def test_list_comp_if_else_is_statement_level(self):
"""List comp if/else should produce a statement-level debug stop."""
src = """\
a = [
for (i = [0:2])
if (i == 1)
99
else
i
];
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
if_stops = [s for s in stmt if s["line"] == 3]
assert len(if_stops) == 3
# ---------------------------------------------------------------------------
# Expression-level echo and assert stops
# ---------------------------------------------------------------------------
class TestExprEchoAssertStops:
def test_expr_echo_has_statement_level_stop(self):
"""echo() in expression context should produce a statement-level stop."""
src = "a = echo(\"hi\") 42;\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# assignment + echo stop
assert len(stmt) >= 2
def test_expr_assert_has_statement_level_stop(self):
"""assert() in expression context should produce a statement-level stop."""
src = "a = assert(true) 42;\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# assignment + assert stop
assert len(stmt) >= 2
def test_modular_echo_has_statement_level_stop(self):
"""Modular echo() should produce a statement-level stop."""
src = "echo(\"hello\");\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
assert len(stmt) == 1
assert stmt[0]["line"] == 1
def test_modular_assert_has_statement_level_stop(self):
"""Modular assert() should produce a statement-level stop."""
src = "assert(true);\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
assert len(stmt) == 1
assert stmt[0]["line"] == 1
# ---------------------------------------------------------------------------
# List comprehension stops
# ---------------------------------------------------------------------------
class TestListCompStops:
def test_list_comp_for_iterations_are_statement_level(self):
"""List comp for should produce statement-level stops per iteration."""
src = "a = [for(i=[1:3]) i];\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# assignment + 3 iteration stops
assert len(stmt) >= 4
def test_list_comp_for_with_function_call_alternates(self):
"""Step Over through a list comp for with function calls should
alternate between the for line and the call line each iteration."""
src = """\
function fx(x) = x*2;
x = [
for (i = [0:1:4])
fx(i+1)
];
"""
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# After the assignment (line 2), we should see iterations:
# for (line 3) then fx() call-site (line 4), repeated 5 times
after_assign = [s for s in stmt if s["line"] >= 3]
for_stops = [s for s in after_assign if s["line"] == 3]
call_stops = [s for s in after_assign if s["line"] == 4]
assert len(for_stops) == 5
assert len(call_stops) >= 5 # call-site + function body stops
def test_list_comp_let_is_statement_level(self):
"""List comp let assignments should be statement-level stops."""
src = "a = [let(x=1) x];\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# assignment + let assignment
assert len(stmt) >= 2
# ---------------------------------------------------------------------------
# C-style for loop stops
# ---------------------------------------------------------------------------
class TestCStyleForStops:
"""C-style for loop (ListCompCFor) should stop at init assignments,
the condition, body entry, and incr assignments."""
# Source with each CFor part on its own line for line-number assertions:
# line 1 a = [
# line 2 for ( ← CFor node / body-entry stop
# line 3 i = 0; ← init assignment
# line 4 i < 2; ← condition
# line 5 i = i + 1 ← incr assignment
# line 6 ) i ← body expression
# line 7 ];
_SRC = "a = [\n for (\n i = 0;\n i < 2;\n i = i + 1\n ) i\n];\n"
def test_init_assignments_are_statement_stops(self):
"""Each init assignment should produce one statement-level stop before the loop."""
_, _, stops = _run_with_debug(self._SRC)
init_stops = [s for s in _stmt_stops(stops) if s["line"] == 3]
assert len(init_stops) == 1 # fires exactly once, before the loop
def test_condition_is_expr_level(self):
"""Condition should get an expr-level stop each time it is checked,
including the final false-check that terminates the loop."""
_, _, stops = _run_with_debug(self._SRC)
cond_stops = [s for s in stops if s["line"] == 4 and s["expr_level"]]
# 2 iterations → 2 true checks + 1 false check = 3
assert len(cond_stops) == 3
def test_body_entry_fires_per_iteration(self):
"""Each loop body entry should produce a statement-level stop at the for node."""
_, _, stops = _run_with_debug(self._SRC)
body_stops = [s for s in _stmt_stops(stops) if s["line"] == 2]
assert len(body_stops) == 2 # one per iteration
def test_incr_assignments_are_statement_stops(self):
"""Each incr assignment should produce a statement-level stop per iteration."""
_, _, stops = _run_with_debug(self._SRC)
incr_stops = [s for s in _stmt_stops(stops) if s["line"] == 5]
assert len(incr_stops) == 2 # one per iteration
def test_multiple_inits_and_incrs(self):
"""Multiple inits and incrs each get their own stops."""
src = "a = [for (i = 0, j = 0; i < 2; i = i + 1, j = j + 2) i + j];\n"
_, _, stops = _run_with_debug(src)
stmt = _stmt_stops(stops)
# outer assign(1) + 2 inits(2) + 2 body(2) + 2*2 incr(4) = 9 minimum
assert len(stmt) >= 9
def test_stop_order(self):
"""Stops should follow init → (cond → body → incr)* → cond(false) order."""
_, _, stops = _run_with_debug(self._SRC)
# Build a simplified sequence: (line, expr_level)
seq = [(s["line"], s["expr_level"]) for s in stops
if s["line"] in (2, 3, 4, 5)]
assert seq == [
(3, False), # init i=0
(4, True), # condition (true, iter 1)
(2, False), # body entry (iter 1)
(5, False), # incr i=i+1 (iter 1)
(4, True), # condition (true, iter 2)
(2, False), # body entry (iter 2)
(5, False), # incr i=i+1 (iter 2)
(4, True), # condition (false, loop ends)
]
# ---------------------------------------------------------------------------
# Normal for() loop variable-binding stops
# ---------------------------------------------------------------------------
class TestForAssignmentStops:
"""for() loops should stop at each variable binding, in nested order,
before each body evaluation."""
# Listcomp multi-variable source:
# line 1 x = [
# line 2 for( ← ListCompFor node
# line 3 i=[0:2], ← i binding (3 values: 0,1,2)
# line 4 j=[0:1] ← j binding (2 values: 0,1)
# line 5 )
# line 6 i*3+j ← body expression (expr_level stop)
# line 7 ];
_LC_SRC = "x = [\nfor(\ni=[0:2],\nj=[0:1]\n)\ni*3+j\n];\n"
# Modular multi-variable source:
# line 1 for( ← ModularFor node
# line 2 i=[0:2], ← i binding (3 values: 0,1,2)
# line 3 j=[0:1] ← j binding (2 values: 0,1)
# line 4 )
# line 5 echo(i*3+j); ← body first stmt (expr_level body-entry + stmt echo)
_MOD_SRC = "for(\ni=[0:2],\nj=[0:1]\n)\necho(i*3+j);\n"
def test_listcomp_assignment_stops_fire(self):
"""Each variable binding in a listcomp for should produce a statement-level stop."""
_, _, stops = _run_with_debug(self._LC_SRC)
i_stops = [s for s in _stmt_stops(stops) if s["line"] == 3]
j_stops = [s for s in _stmt_stops(stops) if s["line"] == 4]
# i iterates over [0,1,2] → 3 stops; j iterates [0,1] per i value → 6 stops
assert len(i_stops) == 3
assert len(j_stops) == 6
def test_listcomp_assignment_stop_order(self):
"""Outer variable advances only after inner variable exhausts its range."""
_, _, stops = _run_with_debug(self._LC_SRC)
seq = [(s["line"], s["expr_level"]) for s in stops if s["line"] in (3, 4, 6)]
assert seq == [
(3, False), # i=0
(4, False), (6, True), # j=0, body
(4, False), (6, True), # j=1, body
(3, False), # i=1
(4, False), (6, True),
(4, False), (6, True),
(3, False), # i=2
(4, False), (6, True),
(4, False), (6, True),
]
def test_modular_assignment_stops_fire(self):
"""Each variable binding in a modular for should produce a statement-level stop."""
_, _, stops = _run_with_debug(self._MOD_SRC)
i_stops = [s for s in _stmt_stops(stops) if s["line"] == 2]
j_stops = [s for s in _stmt_stops(stops) if s["line"] == 3]
assert len(i_stops) == 3
assert len(j_stops) == 6
def test_modular_assignment_stop_order(self):
"""Outer variable (i) advances only after inner variable (j) exhausts its range."""
_, _, stops = _run_with_debug(self._MOD_SRC)
seq = [(s["line"], s["expr_level"]) for s in stops if s["line"] in (2, 3)]
assert seq == [
(2, False), (3, False), (3, False), # i=0, j=0, j=1
(2, False), (3, False), (3, False), # i=1, j=0, j=1
(2, False), (3, False), (3, False), # i=2, j=0, j=1
]
# ---------------------------------------------------------------------------
# Error break
# ---------------------------------------------------------------------------
class TestErrorBreak:
def test_error_break_fires(self):
"""error_break_fn should be called on evaluation errors."""
breaks = []
def error_break(line, msg, all_frame_locals, call_stack, *, origin=None, generate_partial=None):
breaks.append({
"line": line,
"msg": msg,
"frame_count": len(all_frame_locals),
})
hook, stops = _make_recorder()
ev = Evaluator(
echo_fn=lambda msg: None,
debug_hook=hook,
error_break_fn=error_break,
)
with pytest.raises(EvalError):
ev.evaluate(_write("assert(false);\n"))
assert len(breaks) == 1
assert breaks[0]["line"] == 1
def test_error_break_has_frame_locals(self):
"""Error break should provide frame locals for inspection."""
breaks = []
def error_break(line, msg, all_frame_locals, call_stack, *, origin=None, generate_partial=None):
breaks.append({"locals": all_frame_locals, "stack": call_stack})
hook, _ = _make_recorder()
src = """\
module bad() { assert(false); }
bad();
"""
ev = Evaluator(
echo_fn=lambda msg: None,
debug_hook=hook,
error_break_fn=error_break,
)
with pytest.raises(EvalError):
ev.evaluate(_write(src))
assert len(breaks) == 1
# Should have frame locals and a non-empty call stack
assert len(breaks[0]["locals"]) >= 1
assert len(breaks[0]["stack"]) >= 1
# ---------------------------------------------------------------------------
# Forced stops (breakpoint())
# ---------------------------------------------------------------------------
class TestForcedStops:
def test_breakpoint_is_forced(self):
"""breakpoint() should produce a forced debug stop."""
src = """\
a = 1;
breakpoint();
b = 2;
"""
_, _, stops = _run_with_debug(src)
forced = [s for s in stops if s["forced"]]
assert len(forced) == 1
assert forced[0]["line"] == 2
# ---------------------------------------------------------------------------
# Phase 3 — live partial-tree rendering during debugging.
#
# _generate_partial_render(ev) is the one piece of new logic testable
# without touching DebugSession/Qt at all (no test in this repo instantiates
# DebugSession or any Qt widget — the rest of Phase 3 is thin signal/UI
# plumbing verified manually). It's called from DebugSession's hook and
# _error_break right before every pause, so the viewport can show whatever's
# been resolved so far.
# ---------------------------------------------------------------------------
class TestGeneratePartialRender:
# NOTE: this class was rewritten wholesale for the C++ backend.
# _generate_partial_render() now takes the debug hook's own
# `generate_partial` callable (openscad_cpp_evaluator's
# Evaluator::generatePartialTree(), reading the live in-progress
# treeStack_), not an Evaluator instance with private
# _tree_stack/_eval_statement attributes to poke at directly — those
# don't exist on the C++ facade. See test_python_bindings.py in the
# openscad_cpp_evaluator repo for the same pattern proven at the
# binding level.
def test_success_renders_whatever_is_resolved_so_far(self):
# breakpoint() as the LAST statement: by the time it forces a pause,
# both prior statements have already fully resolved.
seen = {}
def hook(line, depth, *, forced=False, expr_level=False, expr_depth=0, origin=None, get_frames=None,
generate_partial=None, get_children_positions=None, set_fast_continue=None):
if forced:
seen["bodies"], seen["error"] = _generate_partial_render(generate_partial)
return ("continue", {})
ev = Evaluator(debug_hook=hook)
ev.evaluate(_write("cube(1);\nsphere(1);\nbreakpoint();\n"))
assert seen["error"] is None
assert len(seen["bodies"]) == 2
def test_success_on_empty_tree(self):
# The very first pause (breakpoint() as the first statement) happens
# before anything has resolved.
seen = {}
def hook(line, depth, *, forced=False, expr_level=False, expr_depth=0, origin=None, get_frames=None,
generate_partial=None, get_children_positions=None, set_fast_continue=None):
if forced:
seen["bodies"], seen["error"] = _generate_partial_render(generate_partial)
return ("continue", {})
ev = Evaluator(debug_hook=hook)
ev.evaluate(_write("breakpoint();\ncube(1);\n"))
assert seen["error"] is None
assert seen["bodies"] == []
def test_failure_is_caught_and_reported_not_raised(self):
# A generate_partial callable that raises — deterministic way to
# exercise the catch-and-report contract without depending on what
# real generate steps happen to raise on (this backend tolerates
# degenerate input, same as real OpenSCAD, so there's no reliable
# way to force a real failure from a script).
def boom():
raise RuntimeError("boom")
bodies, error = _generate_partial_render(boom)
assert bodies is None
assert error == "boom"
def test_picks_up_leaves_still_nested_in_an_unfinished_parent(self):
# Regression: for a script whose whole geometry is one deeply-nested
# top-level statement (e.g. difference(){union(){cube();sphere();}
# cylinder();}), the top-level csg_tree stays completely empty for
# the entire time spent stepping through cube()/sphere(), since
# difference()'s own CSGNode isn't appended anywhere until every
# child has finished resolving — including union(), which itself
# doesn't finish until cube() *and* sphere() both have.
# generate_partial() must still surface cube() at this point by
# reading every level of the live tree stack, not just the top.
src = "difference() {\n union() {\n cube(10);\n sphere(10);\n }\n cylinder(h=10,d=10);\n}\n"
paused_at_sphere = {}
def hook(line, depth, *, forced=False, expr_level=False, expr_depth=0, origin=None, get_frames=None,
generate_partial=None, get_children_positions=None, set_fast_continue=None):
if line == 4 and not expr_level and not paused_at_sphere:
# Paused right at sphere(10) — cube(10) has resolved (its
# CSGNode sits in union()'s still-in-progress accumulator)
# but neither union() nor difference() has finished yet.
paused_at_sphere["bodies"], paused_at_sphere["error"] = _generate_partial_render(generate_partial)
return ("continue", {})
ev = Evaluator(debug_hook=hook)
ev.evaluate(_write(src))
assert paused_at_sphere["error"] is None
assert len(paused_at_sphere["bodies"]) == 1
# No .volume() on the array-shim body (unlike a real manifold3d
# Manifold) — check the resolved leaf is cube(10) via its bbox size.
verts = paused_at_sphere["bodies"][0].body.to_mesh().vert_properties[:, :3]
size = verts.max(axis=0) - verts.min(axis=0)
assert size == pytest.approx([10.0, 10.0, 10.0])
# ---------------------------------------------------------------------------
# Step to Child — resumes execution until control reaches one of the paused
# call's own children()-forwarded statements, regardless of how much of the
# module's internal logic runs first; falls back to stopping when the call
# returns if it never calls children() at all (same safety net Step Out
# already has, so it can't hang).
#
# This exercises real DebugSession threading (unlike the rest of this file,
# which drives Evaluator's debug_hook directly) because the feature is
# specifically about the interplay between Evaluator._check_debug stashing
# _last_children_positions and DebugSession's hook reading it back at
# resume time — a pure-hook test can't see that half of the mechanism.
# Uses a bare QCoreApplication + a safety-timeout QTimer to pump the event
# loop, since queued cross-thread signals are never delivered without one.
# ---------------------------------------------------------------------------
def _run_debug_session(path: str, on_pause_line, timeout: float = 15.0,
breakpoints: dict | None = None) -> tuple[list[int], int]:
"""Start a real DebugSession on the file at `path`. `on_pause_line(line)`
is called at each pause and must return a resume command string (e.g.
"continue", "step_to_child"). Returns (paused_lines, finished_body_count).
Deliberately avoids a nested QCoreApplication.exec() — a manual
processEvents()-and-sleep poll loop instead, driven by a plain
wall-clock deadline. A prior QTimer-triggered-app.quit() version of this
helper was flaky specifically on Linux CI (never locally, never on the
PR that introduced it, and inconsistently across which of the 4 tests
in this class failed from run to run) — symptomatic of a platform-
specific re-entrant-event-loop quirk rather than a logic bug in the
feature itself. Polling avoids relying on nested QCoreApplication.exec()
semantics at all.
"""
import sys
import time as _time
from PySide6.QtCore import QCoreApplication
from belfryscad.window.debugger import DebugSession
app = QCoreApplication.instance() or QCoreApplication(sys.argv[:1])
session = DebugSession()
paused_lines: list[int] = []
result = {"count": None}
def on_paused(origin, line, frames, stk, pbodies, perr):
paused_lines.append(line)
session.resume(on_pause_line(line))
def on_finished(bodies, id2node):
result["count"] = len(bodies)
def on_errored(msg):
result["count"] = -1
session.paused.connect(on_paused)
session.finished.connect(on_finished)
session.errored.connect(on_errored)
session.start(path, breakpoints=breakpoints or {}, current_file=path)
deadline = _time.monotonic() + timeout
while result["count"] is None and _time.monotonic() < deadline:
app.processEvents()
_time.sleep(0.001)
session.paused.disconnect()
session.finished.disconnect()
session.errored.disconnect()
# If the deadline was hit (session still running/paused), stop it so its
# worker thread doesn't linger blocked into the next test — and either
# way, join so the next test starts with a clean slate rather than
# racing a still-finishing thread for the GIL.
if session.is_running():
session.stop()
if session._thread is not None:
session._thread.join(timeout=5.0)
return paused_lines, result["count"]
class TestLastChildrenPositions:
"""The C++ evaluator stashes the paused ModularCall's own top-level
children's (origin, line) pairs right before calling the debug hook,
exposed via the hook's `get_children_positions` callable (see
openscad_cpp_evaluator's debug_evaluate() binding) — which DebugSession
reads at resume time for Step to Child. Tested directly against
Evaluator here (no DebugSession/Qt needed), matching this file's usual
convention."""
def test_populated_at_a_call_with_children(self):
seen = {}
def hook(line, depth, *, forced=False, expr_level=False,
expr_depth=0, origin=None, get_frames=None, generate_partial=None,
get_children_positions=None, set_fast_continue=None):
if line == 4 and not expr_level:
seen["positions"] = get_children_positions()
return ("continue", {})
src = "module foo(bar) {\n echo(bar);\n}\nfoo(1) {\n cube(42);\n sphere(13);\n}\n"
ev = Evaluator(debug_hook=hook)
ev.evaluate(_write(src))
assert [line for _origin, line in seen["positions"]] == [5, 6]
def test_none_for_a_call_with_no_children(self):
seen = {}
def hook(line, depth, *, forced=False, expr_level=False,
expr_depth=0, origin=None, get_frames=None, generate_partial=None,
get_children_positions=None, set_fast_continue=None):
if line == 1 and not expr_level:
seen["positions"] = get_children_positions()
return ("continue", {})
ev = Evaluator(debug_hook=hook)
ev.evaluate(_write("cube(1);\n"))
assert seen["positions"] is None
class TestStepToChild:
def test_stops_at_child_reached_immediately(self, tmp_path):
src = "module foo(bar) {\n echo(bar);\n children();\n}\nfoo(1) {\n cube(42);\n sphere(13);\n}\necho(\"Done\");\n"
path = tmp_path / "step_to_child_immediate.scad"
path.write_text(src)
def on_pause(line):
return "step_to_child" if line == 5 else "continue"
paused_lines, count = _run_debug_session(str(path), on_pause)
assert 6 in paused_lines # cube(42);
assert count == 2
def test_reaches_child_after_internal_module_logic(self, tmp_path):
# Same as above, but the module does several statements of its own
# bookkeeping before ever calling children() — Step to Child must
# skip past all of it regardless.
src = (
"module foo(bar) {\n"
" a = bar + 1;\n"
" b = a * 2;\n"
" echo(a, b);\n"
" children();\n"
"}\n"
"foo(1) {\n"
" cube(42);\n"
" sphere(13);\n"
"}\n"
"echo(\"Done\");\n"
)
path = tmp_path / "step_to_child_delayed.scad"
path.write_text(src)
def on_pause(line):
return "step_to_child" if line == 7 else "continue"
paused_lines, count = _run_debug_session(str(path), on_pause)
assert 8 in paused_lines # cube(42);
assert count == 2
def test_stops_at_whichever_child_children_call_reaches_first(self, tmp_path):
# children(1) invoked before children(0) — Step to Child should land
# on whichever child actually runs first (sphere), not the one
# written first in the caller's { } block (cube).
src = (
"module reversed(bar) {\n"
" echo(bar);\n"
" children(1);\n"
" children(0);\n"
"}\n"
"reversed(1) {\n"
" cube(42);\n"
" sphere(13);\n"
"}\n"
"echo(\"Done\");\n"
)
path = tmp_path / "step_to_child_reversed.scad"
path.write_text(src)
def on_pause(line):
return "step_to_child" if line == 6 else "continue"
paused_lines, count = _run_debug_session(str(path), on_pause)
assert 8 in paused_lines # sphere(13) — children(1), reached first
assert count == 2
def test_falls_back_to_call_return_when_children_never_invoked(self, tmp_path):
# The module ignores its children entirely. Step to Child must not
# hang — same safety net Step Out already relies on.
src = (
"module ignores_children(bar) {\n"
" echo(bar);\n"
"}\n"
"ignores_children(1) {\n"
" cube(42);\n"
" sphere(13);\n"
"}\n"
"echo(\"Done\");\n"
)
path = tmp_path / "step_to_child_no_children.scad"
path.write_text(src)
def on_pause(line):
return "step_to_child" if line == 4 else "continue"
paused_lines, count = _run_debug_session(str(path), on_pause)
assert count == 0 # neither cube nor sphere ever evaluated
class TestStepOverFastContinue:
"""step_over/step_out never examine anything deeper than the step's own
starting depth, so whatever they step over is safe to run through the
bytecode VM -- same reasoning as plain Continue (see
Evaluator.chunkEligibleNow / DebugSession._apply_fast_continue)."""
def test_step_over_heavy_call_is_fast_and_skips_its_internals(self, tmp_path):
src = (
"function heavy(n) = [for (i=[0:1:n-1]) i*i + i*i*i % 97 - (i % 13)];\n"
"function stepped_over() = let(r = heavy(900000)) len(r);\n"
"a = 1;\n"
"b = stepped_over();\n"
"c = 2;\n"
"cube(10);\n"
)
path = tmp_path / "step_over_fast.scad"
path.write_text(src)
start = time.perf_counter()
paused_lines, count = _run_debug_session(str(path), lambda line: "step_over", timeout=15.0)
elapsed = time.perf_counter() - start
assert paused_lines == [3, 4, 5, 6] # lands past stepped_over()/heavy() without pausing inside
assert count == 1 # cube(10) rendered
assert elapsed < 2.0 # VM fast-continue; interpreted would take several seconds for 900k iterations
def test_step_over_still_honors_a_breakpoint_inside_the_stepped_over_call(self, tmp_path):
src = (
"function heavy(n) = [for (i=[0:1:n-1]) i*i];\n" # line 1 -- breakpoint here
"function stepped_over() = let(r = heavy(3)) len(r);\n"
"a = 1;\n"
"b = stepped_over();\n" # line 4 <- step over this
"c = 2;\n"
"cube(10);\n"
)
path = tmp_path / "step_over_breakpoint.scad"
path.write_text(src)
calls = {"n": 0}
def on_pause(line):
calls["n"] += 1
return "step_over" if calls["n"] <= 2 else "continue"
paused_lines, count = _run_debug_session(
str(path), on_pause, timeout=15.0, breakpoints={str(path): {1}})
assert 1 in paused_lines # breakpoint inside heavy() still hit despite the active step_over
assert count == 1
def test_step_into_is_unaffected_and_still_lands_inside_the_call(self, tmp_path):
src = (
"function heavy(n) = [for (i=[0:1:n-1]) i*i];\n"
"function stepped_into() = let(r = heavy(3)) len(r);\n"
"a = 1;\n"
"b = stepped_into();\n" # line 4 <- step into this
"c = 2;\n"
"cube(10);\n"
)
path = tmp_path / "step_into_sanity.scad"
path.write_text(src)
calls = {"n": 0}
def on_pause(line):
calls["n"] += 1
if calls["n"] == 1:
return "step_over" # trivially steps over line 3 (a = 1;)
if calls["n"] == 2:
return "step_into" # steps into stepped_into(), landing on its own line 2
return "continue"
paused_lines, count = _run_debug_session(str(path), on_pause, timeout=15.0)
assert 2 in paused_lines # inside stepped_into()'s own body, not skipped over
assert count == 1
class TestPauseEventOrdering:
"""Regression test for a lost-wakeup race in DebugSession.hook(): the
worker thread's `paused.emit(...)` only enqueues the cross-thread signal
-- it doesn't block -- so the main thread's queued `on_paused` handler
(which calls `resume()` -> `_pause_event.set()`) can run the instant
`emit()` returns, before the worker thread reaches its own
`_pause_event.clear()`. If `clear()` runs *after* `emit()` instead of
before, that set() gets silently wiped out and `wait()` hangs forever --
this was the actual root cause of TestStepToChild's CI-only flakiness
(never reproduced locally, since the emit()-to-clear() gap is normally a
handful of bytecodes on an idle machine).
Forces the gap open with an injected delay so this test doesn't depend
on incidentally winning the same race that caused the original
flakiness -- it must fail deterministically if the ordering regresses,
not just occasionally on a loaded CI runner.
"""
def test_resume_landing_immediately_after_emit_is_not_lost(self, tmp_path, monkeypatch):
import time
import threading as threading_module
real_clear = threading_module.Event.clear
def delayed_clear(self):
# Widens whatever gap production code leaves between emit() and
# clear() -- harmless (just slower) if clear() already runs
# before emit(), which is what should make this test pass.
time.sleep(0.02)
return real_clear(self)
monkeypatch.setattr(threading_module.Event, "clear", delayed_clear)
src = "module foo(bar) {\n echo(bar);\n children();\n}\nfoo(1) {\n cube(42);\n sphere(13);\n}\n"
path = tmp_path / "pause_event_ordering.scad"
path.write_text(src)
def on_pause(line):
return "step_to_child" if line == 5 else "continue"
paused_lines, count = _run_debug_session(str(path), on_pause, timeout=5.0)
assert 6 in paused_lines # cube(42); -- lost if the resume's set() got clobbered
assert count == 2
class TestFastContinueInterrupt:
"""In hook-skippable mode (a plain Continue with no step pending --
see _apply_fast_continue's own comment in debugger.py), checkDebug()
may skip the Python round-trip entirely for most checkpoints, so a
pause() landing mid-loop has no ordinary checkpoint to be noticed at.
FastContinueSignal.request() is what forces the next checkpoint
through regardless. Without it, pause() during a long hook-skippable
Continue would silently do nothing until the computation finished on
its own."""
def test_pause_interrupts_a_hook_skippable_continue_promptly(self, tmp_path):
import sys
import time as _time
from PySide6.QtCore import QCoreApplication, QTimer
from belfryscad.window.debugger import DebugSession
# Naive recursive fibonacci -- pure function-call computation, no
# geometry. Deliberately NOT a geometry loop: a geometry-heavy
# script's wall time is dominated by Manifold's own (uninterruptible)
# mesh/CSG boolean ops downstream of the last checkDebug() call, so
# pause() there would just be waiting for the render to finish
# regardless of this feature. Function calls each get their own
# checkDebug() checkpoint, spread across the whole ~1.4s of real
# interpreter time -- this is the workload the original bug report
# (BOSL2 NURBS math) actually looked like.
src = "function slow(n) = n <= 1 ? n : slow(n-1) + slow(n-2);\necho(slow(30));\n"
path = tmp_path / "fast_continue_interrupt.scad"
path.write_text(src)
app = QCoreApplication.instance() or QCoreApplication(sys.argv[:1])
session = DebugSession()
pause_times: list[float] = []
continue_issued_at: dict[str, float | None] = {"t": None}
result = {"count": None}
def on_paused(origin, line, frames, stk, pbodies, perr):
pause_times.append(_time.monotonic())
if len(pause_times) == 1:
# break-on-first at line 1. Resume with plain "continue" and
# no breakpoints to engage hook-skippable mode, then request
# a pause() shortly after -- long before the loop would ever
# finish unattended.
continue_issued_at["t"] = _time.monotonic()
QTimer.singleShot(100, session.pause)
session.resume("continue")
def on_finished(bodies, id2node):
result["count"] = len(bodies)
def on_errored(msg):
result["count"] = -1
session.paused.connect(on_paused)
session.finished.connect(on_finished)
session.errored.connect(on_errored)
session.start(str(path), breakpoints={}, current_file=str(path))
deadline = _time.monotonic() + 15.0
while result["count"] is None and len(pause_times) < 2 and _time.monotonic() < deadline:
app.processEvents()
_time.sleep(0.001)
second_pause_delay = (
pause_times[1] - continue_issued_at["t"]
if len(pause_times) >= 2 and continue_issued_at["t"] is not None
else None
)
session.paused.disconnect()
session.finished.disconnect()
session.errored.disconnect()
if session.is_running():
session.stop()
if session._thread is not None:
session._thread.join(timeout=5.0)
assert len(pause_times) >= 2, (
"pause() was never honored during the hook-skippable Continue -- "
"the loop ran to completion instead of being interrupted"
)
# Well under the ~1.4s slow(30) takes to finish unattended -- proves
# the FastContinueSignal interrupt actually cut it short rather than
# the second pause just being the computation's own natural end.
assert second_pause_delay < 1.0
def test_debug_shortcut_labels_match_their_bindings():
"""A button's tooltip must name the key that is actually bound.
They were two hand-written lists and drifted: Step to Child bound Qt's
CTRL (Command on macOS) while the tooltip said Control, and Restart
claimed Command for a Meta binding (#448).
"""
from PySide6.QtGui import QKeySequence
from belfryscad.window.debugger import DEBUG_SHORTCUTS, _key_label
for name, key in DEBUG_SHORTCUTS.items():
expected = QKeySequence(key).toString(
QKeySequence.SequenceFormat.NativeText)
assert expected, f"{name} renders as an empty key name"
assert _key_label(name) == expected
# The pairing that was wrong, stated as the platform sees it.
ctrl = _key_label("step_to_child")
meta = _key_label("restart")
assert ctrl != meta
assert ctrl.endswith("F11") and meta.endswith("F5")
62c9a9e10This file is pinned to the selected release. Download the original to open it in your design tool.