Skip to content

Commit d33b360

Browse files
committed
Fix python try except instrumentation
1 parent 7d417f1 commit d33b360

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

openc3-cosmos-script-runner-api/scripts/script_instrumentor.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,9 @@ def track_enter_leave(self, node):
7373
in_try = self.in_try
7474
if not in_try and type(node) in self.try_nodes:
7575
self.in_try = True
76+
7677
# Visit the children of the node
7778
node = self.generic_visit(node)
78-
if not in_try and type(node) in self.try_nodes:
79-
self.in_try = False
8079
# ast.parse returns a module, so we need to extract
8180
# the first element of the body which is the node
8281
pre_line = ast.parse(
@@ -136,9 +135,10 @@ def track_enter_leave(self, node):
136135
# Call the pre_line_instrumentation ONLY and then execute the node
137136
def track_reached(self, node):
138137
# Determine if we're in a try block, this is used by track_enter_leave
139-
in_try = self.in_try
140-
if not in_try and type(node) in self.try_nodes:
138+
if not self.in_try and type(node) in self.try_nodes:
141139
self.in_try = True
140+
else:
141+
self.in_try = False
142142

143143
# Visit the children of the node
144144
node = self.generic_visit(node)

openc3-cosmos-script-runner-api/test/scripts/test_script_instrumentor.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,36 @@ def test_exception_script(mock_running_script):
191191
]
192192

193193

194+
def test_raise_with_try(mock_running_script):
195+
script = """
196+
raise RuntimeError("Error")
197+
try:
198+
pass
199+
except RuntimeError:
200+
pass
201+
raise RuntimeError("Error")
202+
"""
203+
parsed = ast.parse(script)
204+
tree = ScriptInstrumentor("testfile.py").visit(parsed)
205+
compiled = compile(tree, filename="testfile.py", mode="exec")
206+
exec(compiled, {"RunningScript": mock_running_script})
207+
208+
assert mock_running_script.pre_lines == [
209+
("testfile.py", 2),
210+
("testfile.py", 3),
211+
("testfile.py", 4),
212+
("testfile.py", 7),
213+
]
214+
assert mock_running_script.post_lines == [
215+
("testfile.py", 2),
216+
("testfile.py", 7),
217+
]
218+
assert mock_running_script.exceptions == [
219+
("testfile.py", 2),
220+
("testfile.py", 7),
221+
]
222+
223+
194224
def test_import_future_script(mock_running_script):
195225
script = "from __future__ import annotations\nprint('hi')"
196226
parsed = ast.parse(script)

0 commit comments

Comments
 (0)