Skip to content

Commit 6224be7

Browse files
authored
BUG: accept the callable parachute triggers the docstring promises (#1103)
* BUG: accept the callable parachute triggers the docstring promises The `or` sat inside the isinstance call rather than beside it: isinstance(member, (str, int, float) or callable(member)) A non-empty type tuple is truthy, so the expression short-circuited to the tuple and callable(member) was never evaluated. The check reduced to isinstance(member, (str, int, float)), and a callable is none of those. Parachute takes a callable trigger and Flight calls it, and the docstring three lines above says "a list of callables, string 'apogee' or ints/floats". Only the stochastic wrapper refused one. The two non-callable forms passed throughout, which is why the tests never caught it. Left as an assert to match the other fourteen in these two modules, and because raising a different type would break anyone catching AssertionError. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> * BUG: refuse the trigger forms Parachute cannot use Moving the `or` let callables through, but left four things the check should never have accepted. `["banana"]` passed here and then `Parachute` raised ValueError, so the wrapper only moved the failure to create time. `[True]` is worse: bool is an int, so it went through as a height of one metre. `[]` passed because `all([])` is True. And `numbers.Real` replaces `(int, float)`, which took numpy.float64 because it subclasses float and refused numpy.int64 because it subclasses neither. The check is raised rather than asserted. `python -O` strips an assert outright, and this is the only thing between those triggers and a Parachute that either refuses them later or misreads them. Still an AssertionError, so nothing that catches it has to change. The docstring claimed a tuple form that was never implemented; it now describes what the code does. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> * BUG: do not accept numpy integers the Parachute will refuse Widening the height check to numbers.Real was the same mistake as accepting "banana": Parachute checks isinstance(trigger, (int, float)), so numpy.float64 passes because it subclasses float and numpy.int64 raises ValueError because it subclasses neither. Letting them through here only moved the failure to create_object. Back to (int, float), matching that check rather than improving on it, and the test that asserted numpy.int64 was accepted now asserts both ends refuse it. The asymmetry is Parachute's rather than this wrapper's and is worth fixing there, where widening the check would not strand anything downstream. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> * TST: use the state length Flight actually passes The trigger tests built a 14-element state. Flight passes 13: x y z vx vy vz e0 e1 e2 e3 wx wy wz. Only y[5] is read, so both worked, but the test is there to document the contract and was documenting it wrongly. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> * DOC: add the changelog entry for this branch By hand, because the automation cannot run on a pull request from a fork (#1101). No documented API breaks, but the observable behaviour does: an invalid string, an empty list or a boolean trigger now fails during StochasticParachute validation rather than later in Parachute construction, or silently becoming a one-metre height trigger. Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com> --------- Signed-off-by: thc1006 <84045975+thc1006@users.noreply.github.com>
1 parent 4b187cd commit 6224be7

3 files changed

Lines changed: 150 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Attention: The newest changes should be on top -->
4343

4444
### Fixed
4545

46+
- BUG: Accept the callable parachute triggers `StochasticParachute` documents, and reject the ones it cannot mean. An invalid string, an empty list or a boolean now fails during validation instead of reaching `Parachute` or becoming a one-metre height trigger. [#1103](https://github.com/RocketPy-Team/RocketPy/pull/1103)
4647
- BUG: rocket with a late-starting thrust curve never leaves the rail [#1085](https://github.com/RocketPy-Team/RocketPy/pull/1085)
4748

4849
## [v1.13.0] - 2026-07-21

‎rocketpy/stochastic/stochastic_parachute.py‎

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,21 @@
55
from .stochastic_model import StochasticModel
66

77

8+
def _is_a_trigger(member):
9+
"""One of the three forms ``Parachute`` accepts, and no more.
10+
11+
``(int, float)`` deliberately, matching ``Parachute``'s own check rather
12+
than ``numbers.Real``: that would take ``numpy.int64``, which ``Parachute``
13+
refuses, so widening here only moves the failure to create time. ``bool``
14+
is excluded because it is an ``int``, and would arrive as a height of one.
15+
"""
16+
if callable(member):
17+
return True
18+
if isinstance(member, str):
19+
return member.lower() == "apogee"
20+
return isinstance(member, (int, float)) and not isinstance(member, bool)
21+
22+
823
class StochasticParachute(StochasticModel):
924
"""A Stochastic Parachute class that inherits from StochasticModel.
1025
@@ -114,16 +129,26 @@ def __init__(
114129
)
115130

116131
def _validate_trigger(self, trigger):
117-
"""Validates the trigger input. If the trigger input argument is not
118-
None, it must be:
119-
- a list of callables, string "apogee" or ints/floats
120-
- a tuple that will be further validated in the StochasticModel class
132+
"""Validates the trigger input. If not None, it must be a non-empty
133+
list whose members are each a callable, the string "apogee", or a
134+
height. One of those is chosen per simulation.
121135
"""
122-
if trigger is not None:
123-
assert isinstance(trigger, list) and all(
124-
isinstance(member, (str, int, float) or callable(member))
125-
for member in trigger
126-
), "`trigger` must be a list of callables, string 'apogee' or ints/floats"
136+
if trigger is None:
137+
return
138+
139+
valid = (
140+
isinstance(trigger, list)
141+
and bool(trigger)
142+
and all(_is_a_trigger(member) for member in trigger)
143+
)
144+
# Raised rather than asserted: `python -O` strips an assert, and this
145+
# is the only thing standing between a bad trigger and a Parachute
146+
# that either refuses it much later or reads True as a height of 1.
147+
if not valid:
148+
raise AssertionError(
149+
"`trigger` must be a non-empty list whose members are "
150+
"callables, the string 'apogee', or heights"
151+
)
127152

128153
def _validate_noise(self, noise):
129154
"""Validates the noise input. If the noise input argument is not

‎tests/unit/stochastic/test_stochastic_parachute.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import inspect
2+
3+
import numpy as np
4+
import pytest
5+
6+
from rocketpy.stochastic import StochasticParachute
17
from rocketpy.rocket.parachute import Parachute
28

39

@@ -19,3 +25,112 @@ class creates a StochasticParachute object from the randomly generated
1925
"""
2026
obj = stochastic_main_parachute.create_object()
2127
assert isinstance(obj, Parachute)
28+
29+
30+
def _at_apogee(pressure, height, state): # pylint: disable=unused-argument
31+
"""A trigger of the kind `Parachute` and `Flight` already accept.
32+
33+
Keeps the full signature rather than underscoring the unused two, since the
34+
signature is the contract being tested."""
35+
return state[5] < 0
36+
37+
38+
@pytest.mark.parametrize(
39+
"trigger",
40+
[[_at_apogee], ["apogee"], [800], [_at_apogee, "apogee", 800]],
41+
ids=["callable", "apogee", "height", "mixed"],
42+
)
43+
def test_every_documented_trigger_form_is_accepted(calisto_main_chute, trigger):
44+
"""The docstring promises callables, "apogee" and numbers. The check read
45+
`isinstance(member, (str, int, float) or callable(member))`, and a non-empty
46+
type tuple is truthy, so the `or` short-circuited and callables were
47+
refused. The two non-callable forms passed throughout, which is why it went
48+
unnoticed."""
49+
StochasticParachute(calisto_main_chute, trigger=trigger)
50+
51+
52+
@pytest.mark.parametrize(
53+
"trigger",
54+
[
55+
_at_apogee,
56+
"apogee",
57+
800,
58+
(800,),
59+
[],
60+
[None],
61+
[{}],
62+
["banana"],
63+
[True],
64+
[_at_apogee, None],
65+
],
66+
ids=str,
67+
)
68+
def test_a_trigger_that_is_not_a_list_of_those_is_refused(calisto_main_chute, trigger):
69+
"""The control, and four that the check used to wave through.
70+
71+
`Parachute` refuses "banana" with a ValueError, so accepting it here only
72+
moved the failure to create time. `True` is worse: it is an `int`, so it
73+
was taken as a height of one metre. An empty list passed because `all([])`
74+
is True. And the docstring's tuple form was never implemented.
75+
"""
76+
with pytest.raises(AssertionError, match="must be a non-empty list"):
77+
StochasticParachute(calisto_main_chute, trigger=trigger)
78+
79+
80+
@pytest.mark.parametrize(
81+
"member",
82+
[_at_apogee, "apogee", "APOGEE", 800, 800.0, np.float64(800)],
83+
ids=str,
84+
)
85+
def test_what_this_accepts_is_what_a_parachute_accepts(calisto_main_chute, member):
86+
"""The property, rather than a list of types. Anything this lets through
87+
has to survive `Parachute`, or the check has only moved the failure."""
88+
StochasticParachute(calisto_main_chute, trigger=[member])
89+
90+
Parachute("probe", 10.0, member, 105, 1.5)
91+
92+
93+
@pytest.mark.parametrize("member", [np.int64(800), np.int32(800)], ids=str)
94+
def test_a_numpy_integer_is_refused_here_because_parachute_refuses_it(
95+
calisto_main_chute, member
96+
):
97+
"""`Parachute` checks `isinstance(trigger, (int, float))`. `numpy.float64`
98+
subclasses `float` and passes; `numpy.int64` subclasses neither and raises.
99+
100+
So this check matches that one rather than `numbers.Real`, which would be
101+
the wider and more natural spelling but would let these through to fail at
102+
create time. The asymmetry is `Parachute`'s and is worth fixing there.
103+
"""
104+
with pytest.raises(ValueError, match="Unable to set the trigger"):
105+
Parachute("probe", 10.0, member, 105, 1.5)
106+
107+
with pytest.raises(AssertionError, match="must be a non-empty list"):
108+
StochasticParachute(calisto_main_chute, trigger=[member])
109+
110+
111+
def test_the_check_is_not_stripped_by_python_dash_o():
112+
"""`python -O` removes an `assert` outright, and this check is the only
113+
thing between a bad trigger and a `Parachute` that either refuses it much
114+
later or reads `True` as a height."""
115+
source = inspect.getsource(StochasticParachute._validate_trigger)
116+
117+
assert "raise AssertionError" in source
118+
assert not any(line.strip().startswith("assert ") for line in source.splitlines())
119+
120+
121+
def test_a_callable_trigger_reaches_the_parachute_and_gets_called(
122+
calisto_main_chute,
123+
):
124+
"""Constructing the wrapper is not the property that matters. The callable
125+
has to survive `create_object` and be what `Flight` ends up calling."""
126+
stochastic = StochasticParachute(calisto_main_chute, trigger=[_at_apogee])
127+
stochastic._set_stochastic(42)
128+
129+
built = stochastic.create_object()
130+
131+
assert built.trigger is _at_apogee
132+
# 13, matching the state Flight passes: x y z vx vy vz e0 e1 e2 e3 wx wy wz
133+
descending = [0.0] * 5 + [-5.0] + [0.0] * 7
134+
ascending = [0.0] * 5 + [5.0] + [0.0] * 7
135+
assert built.triggerfunc(0.0, 100.0, descending, [], [])
136+
assert not built.triggerfunc(0.0, 100.0, ascending, [], [])

0 commit comments

Comments
 (0)