diff --git a/rocketpy/__init__.py b/rocketpy/__init__.py index 27b7c034a..b548f64ad 100644 --- a/rocketpy/__init__.py +++ b/rocketpy/__init__.py @@ -4,6 +4,8 @@ from .exceptions import ( InvalidInertiaError, InvalidParameterError, + StochasticTypeError, + StochasticValueError, UnstableRocketWarning, ) from .mathutils import ( diff --git a/rocketpy/exceptions.py b/rocketpy/exceptions.py index e6bdc4355..f746bf5e4 100644 --- a/rocketpy/exceptions.py +++ b/rocketpy/exceptions.py @@ -19,6 +19,24 @@ class InvalidInertiaError(RocketPyError, ValueError): """Raised when the inertia tuple/list does not have the expected length.""" +class StochasticTypeError(RocketPyError, TypeError, AssertionError): + """Raised when a stochastic input has the wrong type or format (e.g. a + string where a number or tuple is expected). + + Also an ``AssertionError``, which these checks used to raise, so existing + ``except AssertionError`` clauses keep working. + """ + + +class StochasticValueError(RocketPyError, ValueError, AssertionError): + """Raised when a stochastic input has the right type but an invalid value + (e.g. a tuple of the wrong length or an out-of-range ensemble member). + + Also an ``AssertionError``, which these checks used to raise, so existing + ``except AssertionError`` clauses keep working. + """ + + class UnstableRocketWarning(UserWarning): """Issued when the rocket's static margin is negative at motor ignition, indicating an aerodynamically unstable configuration. diff --git a/rocketpy/stochastic/stochastic_aero_surfaces.py b/rocketpy/stochastic/stochastic_aero_surfaces.py index 97017b3bf..ed0a3b78c 100644 --- a/rocketpy/stochastic/stochastic_aero_surfaces.py +++ b/rocketpy/stochastic/stochastic_aero_surfaces.py @@ -6,6 +6,7 @@ import numpy as np +from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.rocket.aero_surface import ( AirBrakes, EllipticalFins, @@ -103,7 +104,7 @@ def _validate_kind(self, kind): isinstance(kind, list) and all(isinstance(member, str) for member in kind) ): - raise AssertionError("`kind` must be a list of strings") + raise StochasticTypeError("`kind` must be a list of strings") def create_object(self): """Creates and returns a NoseCone object from the randomly generated @@ -449,7 +450,7 @@ def _validate_shape_points(self, shape_points): Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ if shape_points is None or isinstance( @@ -475,7 +476,7 @@ def _validate_shape_points(self, shape_points): return [self._validate_outline(shape_points)] return [self._validate_outline(outline) for outline in shape_points] - raise AssertionError( + raise StochasticTypeError( "`shape_points` must be a tuple, list, numpy array, int, or float " "or a custom sampler" ) @@ -501,11 +502,11 @@ def _validate_shape_points_tuple(self, shape_points): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input is not in a valid format. """ if len(shape_points) not in (2, 3): - raise AssertionError("'shape_points': tuple must have length 2 or 3") + raise StochasticValueError("'shape_points': tuple must have length 2 or 3") if isinstance(shape_points[0], (int, float)): # (standard deviation, distribution name), the nominal outline being @@ -513,7 +514,7 @@ def _validate_shape_points_tuple(self, shape_points): # make the first one the nominal value, which for this argument is # an outline rather than a number. if not isinstance(shape_points[1], str): - raise AssertionError( + raise StochasticTypeError( "'shape_points': when the first item of a tuple is a " "standard deviation, the second must be a string naming a " "valid numpy.random distribution function." @@ -526,13 +527,13 @@ def _validate_shape_points_tuple(self, shape_points): # accepts a string there and would read the outline as the deviation. outline = self._validate_outline(shape_points[0]) if not isinstance(shape_points[1], (int, float)): - raise AssertionError( + raise StochasticTypeError( "'shape_points': second item of tuple must be an int or float " "standard deviation." ) if len(shape_points) == 3: if not isinstance(shape_points[2], str): - raise AssertionError( + raise StochasticTypeError( "'shape_points': Third item of tuple must be a string containing " "the name of a valid numpy.random distribution function." ) @@ -552,12 +553,12 @@ def _validate_outline_distribution(cls, distribution_name): Raises ------ - AssertionError + StochasticValueError If the distribution cannot be applied to an outline. """ if distribution_name not in cls._outline_distributions: accepted = ", ".join(repr(name) for name in cls._outline_distributions) - raise AssertionError( + raise StochasticValueError( f"'shape_points': the '{distribution_name}' distribution cannot " f"be applied to an outline. Use one of {accepted}, which take " "the nominal coordinate as the centre of the deviation." @@ -590,17 +591,17 @@ def _validate_outline(outline): Raises ------ - AssertionError + StochasticValueError If the outline is not a sequence of at least three (x, y) numbers. """ if not StochasticFreeFormFins._is_outline(outline): - raise AssertionError( + raise StochasticValueError( "`shape_points` outlines must be sequences of (x, y) numbers, " "i.e. have shape (n, 2)." ) array = np.asarray(outline, dtype=float) if array.shape[0] < 3: - raise AssertionError( + raise StochasticValueError( "`shape_points` outlines must have at least 3 points to " "enclose an area." ) diff --git a/rocketpy/stochastic/stochastic_environment.py b/rocketpy/stochastic/stochastic_environment.py index 15fbe7c83..23ed9209e 100644 --- a/rocketpy/stochastic/stochastic_environment.py +++ b/rocketpy/stochastic/stochastic_environment.py @@ -1,5 +1,7 @@ """Defines the StochasticEnvironment class.""" +from rocketpy.exceptions import StochasticTypeError, StochasticValueError + from .stochastic_model import StochasticModel @@ -119,7 +121,7 @@ def _validate_ensemble(self, ensemble_member, environment): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the environment does not have ensemble members and the ensemble_member input argument is not None. """ @@ -127,7 +129,7 @@ def _validate_ensemble(self, ensemble_member, environment): if environment.atmospheric_model_type not in valid_atmospheric_types: if ensemble_member is not None: - raise AssertionError( + raise StochasticValueError( f"Environment with {environment.atmospheric_model_type} " "does not have ensemble members" ) @@ -135,14 +137,13 @@ def _validate_ensemble(self, ensemble_member, environment): if ensemble_member is not None: if not isinstance(ensemble_member, list): - raise AssertionError("`ensemble_member` must be a list") - if not ( - all( - isinstance(member, int) and member >= 0 - for member in ensemble_member + raise StochasticTypeError("`ensemble_member` must be a list") + if not all(isinstance(member, int) for member in ensemble_member): + raise StochasticTypeError( + "`ensemble_member` must be a list of positive integers" ) - ): - raise AssertionError( + if not all(member >= 0 for member in ensemble_member): + raise StochasticValueError( "`ensemble_member` must be a list of positive integers" ) if not ( @@ -151,7 +152,7 @@ def _validate_ensemble(self, ensemble_member, environment): <= max(ensemble_member) < environment.num_ensemble_members ): - raise AssertionError( + raise StochasticValueError( "`ensemble_member` must be in the range from 0 to " + f"{environment.num_ensemble_members - 1}" ) diff --git a/rocketpy/stochastic/stochastic_flight.py b/rocketpy/stochastic/stochastic_flight.py index 12c505077..feda6c58f 100644 --- a/rocketpy/stochastic/stochastic_flight.py +++ b/rocketpy/stochastic/stochastic_flight.py @@ -5,6 +5,7 @@ import numpy as np +from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.simulation import Flight from .stochastic_model import StochasticModel @@ -89,13 +90,13 @@ def __init__( if terminate_on_apogee is not None and not isinstance( terminate_on_apogee, bool ): - raise AssertionError("`terminate_on_apogee` must be a boolean") + raise StochasticTypeError("`terminate_on_apogee` must be a boolean") if time_overshoot is not None: if not isinstance(time_overshoot, bool): - raise TypeError("`time_overshoot` must be a boolean") + raise StochasticTypeError("`time_overshoot` must be a boolean") if max_time is not None: if not isinstance(max_time, (int, float)): - raise TypeError("`max_time` must be a number") + raise StochasticTypeError("`max_time` must be a number") super().__init__( flight, rail_length=rail_length, @@ -143,7 +144,7 @@ def _validate_initial_solution(self, initial_solution): if initial_solution is not None: if isinstance(initial_solution, (tuple, list)): if not len(initial_solution) == 14: - raise AssertionError( + raise StochasticValueError( "`initial_solution` must be a 14 element tuple, the " "elements are:\n t_initial, x_init, y_init, z_init, " "vx_init, vy_init, vz_init, e0_init, e1_init, e2_init, " @@ -153,11 +154,13 @@ def _validate_initial_solution(self, initial_solution): isinstance(i, Real) and not isinstance(i, (bool, np.bool_)) for i in initial_solution ): - raise AssertionError( + raise StochasticTypeError( "`initial_solution` must be a tuple of numbers" ) else: - raise TypeError("`initial_solution` must be a tuple of numbers") + raise StochasticTypeError( + "`initial_solution` must be a tuple of numbers" + ) def _sample_flight_inputs(self): """Sample rail_length, inclination, and heading in a single draw. diff --git a/rocketpy/stochastic/stochastic_model.py b/rocketpy/stochastic/stochastic_model.py index d9a8f3527..2f89e202d 100644 --- a/rocketpy/stochastic/stochastic_model.py +++ b/rocketpy/stochastic/stochastic_model.py @@ -5,6 +5,7 @@ import numpy as np +from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.mathutils.function import Function from rocketpy.stochastic.custom_sampler import CustomSampler @@ -151,7 +152,7 @@ def __init__(self, obj, seed=None, **kwargs): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input arguments do not conform to the specified formats. """ @@ -275,7 +276,7 @@ def _set_stochastic(self, seed=None): input_name, input_value ) else: - raise AssertionError( + raise StochasticTypeError( f"'{input_name}' must be a tuple, list, int, or float" "or a custom sampler" ) @@ -356,17 +357,17 @@ def _validate_tuple(self, input_name, input_value, getattr=getattr): # pylint: Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input is not in a valid format. """ if len(input_value) not in [ 2, 3, ]: - raise AssertionError(f"'{input_name}': tuple must have length 2 or 3") + raise StochasticValueError(f"'{input_name}': tuple must have length 2 or 3") if not isinstance(input_value[0], (int, float)): if input_name not in self.array_valued_inputs: - raise AssertionError( + raise StochasticTypeError( f"'{input_name}': First item of tuple must be an int or float" ) # An array-valued input carries its whole nominal value here, so the @@ -402,11 +403,11 @@ def _validate_tuple_length_two(self, input_name, input_value, getattr=getattr): Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ if not isinstance(input_value[1], (int, float, str)): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}': second item of tuple must be an int, float, or string." ) @@ -453,16 +454,16 @@ def _validate_tuple_length_three(self, input_name, input_value, getattr=getattr) Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ if not isinstance(input_value[1], (int, float)): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}': Second item of a tuple with length 3 must be an " "int or float." ) if not isinstance(input_value[2], str): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}': Third item of tuple must be a string containing the " "name of a valid numpy.random distribution function." ) @@ -486,11 +487,6 @@ def _validate_list(self, input_name, input_value, getattr=getattr): # pylint: d ------- list Validated list. - - Raises - ------ - AssertionError - If the input is not in a valid format. """ if not input_value: return [self._nominal(input_name, getattr)] @@ -542,7 +538,7 @@ def _validate_factors(self, input_name, input_value): Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ attribute_name = input_name.replace("_factor", "") @@ -555,7 +551,7 @@ def _validate_factors(self, input_name, input_value): elif isinstance(input_value, CustomSampler): return self._validate_custom_sampler(input_name, input_value) else: - raise AssertionError( + raise StochasticTypeError( f"`{input_name}`: must be either a tuple or listor a custom sampler" ) @@ -577,18 +573,18 @@ def _validate_tuple_factor(self, input_name, factor_tuple): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input is not in a valid format. """ if len(factor_tuple) not in [ 2, 3, ]: - raise AssertionError( + raise StochasticValueError( f"'{input_name}`: Factors tuple must have length 2 or 3" ) if not all(isinstance(item, (int, float)) for item in factor_tuple[:2]): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}`: First and second items of Factors tuple must be " "either an int or float" ) @@ -601,7 +597,7 @@ def _validate_tuple_factor(self, input_name, factor_tuple): ) elif len(factor_tuple) == 3: if not isinstance(factor_tuple[2], str): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}`: Third item of tuple must be a string containing " "the name of a valid numpy.random distribution function" ) @@ -628,11 +624,11 @@ def _validate_list_factor(self, input_name, factor_list): Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ if not all(isinstance(item, (int, float)) for item in factor_list): - raise AssertionError( + raise StochasticTypeError( f"'{input_name}`: Items in list must be either ints or floats" ) return factor_list @@ -650,7 +646,7 @@ def _validate_1d_array_like(self, input_name, input_value): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input is not in a valid format. """ if input_value is not None: @@ -660,14 +656,14 @@ def _validate_1d_array_like(self, input_name, input_value): ) if not isinstance(input_value, list): - raise AssertionError(error_msg) + raise StochasticTypeError(error_msg) for member in input_value: if isinstance(member, list): if len(np.shape(member)) != 2 or np.shape(member)[1] != 2: - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) elif not isinstance(member, (str, Function)): - raise AssertionError(error_msg) + raise StochasticTypeError(error_msg) def _validate_positive_int_list(self, input_name, input_value): """ @@ -682,19 +678,20 @@ def _validate_positive_int_list(self, input_name, input_value): Raises ------ - AssertionError - If the input is not in a valid format. + StochasticTypeError + If the input is not a list of integers. + StochasticValueError + If any member is negative. """ if input_value is not None: + error_msg = f"`{input_name}` must be a list of positive integers" if not ( isinstance(input_value, list) - and all( - isinstance(member, int) and member >= 0 for member in input_value - ) + and all(isinstance(member, int) for member in input_value) ): - raise AssertionError( - f"`{input_name}` must be a list of positive integers" - ) + raise StochasticTypeError(error_msg) + if not all(member >= 0 for member in input_value): + raise StochasticValueError(error_msg) def _reset_custom_samplers(self, seed): """Seed each sampler, and each shared generator once. @@ -745,13 +742,12 @@ def _validate_custom_sampler(self, input_name, sampler): Raises ------ - AssertionError + StochasticTypeError If the input is not in a valid format. """ - # Raised, not asserted: `python -O` strips asserts. AssertionError is - # kept so callers that catch it still do. Same as #1103. + # Raised, not asserted: `python -O` strips asserts. if not isinstance(sampler, CustomSampler): - raise AssertionError( + raise StochasticTypeError( f"`{input_name}` must be a CustomSampler, not {type(sampler).__name__}" ) return sampler @@ -767,7 +763,7 @@ def _validate_airfoil(self, airfoil): Raises ------ - AssertionError + StochasticTypeError, StochasticValueError If the input is not in a valid format. """ # TODO: The _validate_airfoil should be defined in a child class. @@ -776,19 +772,21 @@ def _validate_airfoil(self, airfoil): isinstance(airfoil, list) and all(isinstance(member, tuple) for member in airfoil) ): - raise AssertionError("`airfoil` must be a list of tuples") + raise StochasticTypeError("`airfoil` must be a list of tuples") for member in airfoil: if not len(member) == 2: - raise AssertionError("`airfoil` tuples must have length 2") + raise StochasticValueError("`airfoil` tuples must have length 2") if not isinstance(member[1], str): - raise AssertionError( + raise StochasticTypeError( "`airfoil` tuples must have a string as the second item" ) if isinstance(member[0], list): if len(np.shape(member[0])) != 2 and np.shape(member[0])[1] != 2: - raise AssertionError("`airfoil` tuples must have shape (n,2)") + raise StochasticValueError( + "`airfoil` tuples must have shape (n,2)" + ) elif not isinstance(member[0], str) and not callable(member[0]): - raise AssertionError( + raise StochasticTypeError( "`airfoil` tuples must have a string or Function as " "the first item" ) diff --git a/rocketpy/stochastic/stochastic_parachute.py b/rocketpy/stochastic/stochastic_parachute.py index 6ff3775be..ebd6a5432 100644 --- a/rocketpy/stochastic/stochastic_parachute.py +++ b/rocketpy/stochastic/stochastic_parachute.py @@ -1,5 +1,6 @@ """Defines the StochasticParachute class.""" +from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.rocket import Parachute from rocketpy.rocket.parachute import _is_a_height_trigger @@ -165,19 +166,19 @@ def _validate_trigger(self, trigger): if trigger is None: return - valid = ( - isinstance(trigger, list) - and bool(trigger) - and all(_is_a_trigger(member) for member in trigger) + error_msg = ( + "`trigger` must be a non-empty list whose members are " + "callables, the string 'apogee', heights, or ('time', t_deploy)" ) # Raised rather than asserted: `python -O` strips an assert, and this # is the only thing standing between a bad trigger and a Parachute # that either refuses it much later or reads True as a height of 1. - if not valid: - raise AssertionError( - "`trigger` must be a non-empty list whose members are " - "callables, the string 'apogee', heights, or ('time', t_deploy)" - ) + if not isinstance(trigger, list) or not all( + _is_a_trigger(member) for member in trigger + ): + raise StochasticTypeError(error_msg) + if not trigger: + raise StochasticValueError(error_msg) def _validate_noise(self, noise): """Validates the noise input. If the noise input argument is not @@ -189,7 +190,7 @@ def _validate_noise(self, noise): isinstance(noise, list) and all(isinstance(member, tuple) for member in noise) ): - raise AssertionError( + raise StochasticTypeError( "`noise` must be a list of tuples in the form of " "(mean, standard deviation, time-correlation)" ) diff --git a/rocketpy/stochastic/stochastic_rocket.py b/rocketpy/stochastic/stochastic_rocket.py index 67831f49b..0b5128744 100644 --- a/rocketpy/stochastic/stochastic_rocket.py +++ b/rocketpy/stochastic/stochastic_rocket.py @@ -2,8 +2,8 @@ import warnings - from rocketpy.control import _Controller +from rocketpy.exceptions import StochasticTypeError, StochasticValueError from rocketpy.mathutils.vector_matrix import Vector from rocketpy.motors.empty_motor import EmptyMotor from rocketpy.motors.motor import GenericMotor, Motor @@ -265,7 +265,7 @@ def add_motor(self, motor, position=None): # checks if input is a Motor if not isinstance(motor, (Motor, StochasticMotorModel)): - raise TypeError("`motor` must be a StochasticMotor or Motor type") + raise StochasticTypeError("`motor` must be a StochasticMotor or Motor type") if isinstance(motor, Motor): # TODO implement HybridMotor and LiquidMotor stochastic models if isinstance(motor, SolidMotor): @@ -296,7 +296,7 @@ def _add_surfaces(self, surfaces, positions, type_, stochastic_type, error_messa type. """ if not isinstance(surfaces, (type_, stochastic_type)): - raise AssertionError(error_message) + raise StochasticTypeError(error_message) if isinstance(surfaces, type_): # Positionally: the stochastic classes each name this first # parameter after their own surface (`nosecone`, `tail`, ...), so @@ -407,7 +407,7 @@ def add_parachute(self, parachute): """ # checks if input is a StochasticParachute type if not isinstance(parachute, (Parachute, StochasticParachute)): - raise TypeError( + raise StochasticTypeError( "`parachute` must be of Parachute or StochasticParachute type" ) if isinstance(parachute, Parachute): @@ -429,7 +429,7 @@ def set_rail_buttons( The position of the lower button. """ if not isinstance(rail_buttons, (StochasticRailButtons, RailButtons)): - raise AssertionError( + raise StochasticTypeError( "`rail_buttons` must be of RailButtons or StochasticRailButtons type" ) if isinstance(rail_buttons, RailButtons): @@ -450,7 +450,7 @@ def add_air_brakes(self, air_brakes, controller): Deterministic air brake controller. """ if not isinstance(air_brakes, (AirBrakes, StochasticAirBrakes)): - raise TypeError( + raise StochasticTypeError( "`air_brake` must be of AirBrakes or StochasticAirBrakes type" ) if isinstance(air_brakes, AirBrakes): @@ -547,7 +547,7 @@ def _validate_eccentricity(self, eccentricity, position): Raises ------ - ValueError + StochasticTypeError, StochasticValueError If the position argument does not conform to the specified formats. """ if isinstance(position, tuple): @@ -572,7 +572,7 @@ def _validate_eccentricity(self, eccentricity, position): position, ) else: - raise AssertionError("`position` must be a tuple, list, int, or float") + raise StochasticTypeError("`position` must be a tuple, list, int, or float") def _validate_position(self, validated_object, position): """Validate the position argument. @@ -591,7 +591,7 @@ def _validate_position(self, validated_object, position): Raises ------ - ValueError + StochasticTypeError, StochasticValueError If the position argument does not conform to the specified formats. """ if isinstance(position, tuple): @@ -620,7 +620,7 @@ def _validate_position(self, validated_object, position): getattr=self._create_get_position(validated_object), ) else: - raise AssertionError("`position` must be a tuple, list, int, or float") + raise StochasticTypeError("`position` must be a tuple, list, int, or float") def _create_get_position(self, validated_object): """Create a function to get the nominal position from an object. @@ -646,7 +646,7 @@ def _create_get_position(self, validated_object): # special case for motor stochastic model if isinstance(validated_object, (StochasticMotorModel)): if isinstance(self.obj.motor, EmptyMotor): - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) def get_motor_position(self_object, _): return self_object.motor_position @@ -660,12 +660,12 @@ def get_surface_position(self_object, _): validated_object.obj.__class__ ) if len(surfaces) == 0: - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) for surface in surfaces: if surface.component == validated_object.obj: return surface.position else: - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) else: @@ -674,11 +674,11 @@ def get_surface_position(self_object, _): validated_object.obj.__class__ ) if len(surfaces) == 0: - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) for surface in surfaces: if surface.component == validated_object.obj: return surface.position - raise AssertionError(error_msg) + raise StochasticValueError(error_msg) return get_surface_position diff --git a/tests/unit/stochastic/test_stochastic_exceptions.py b/tests/unit/stochastic/test_stochastic_exceptions.py new file mode 100644 index 000000000..b5956a1cc --- /dev/null +++ b/tests/unit/stochastic/test_stochastic_exceptions.py @@ -0,0 +1,212 @@ +"""Invalid stochastic inputs raise RocketPy exceptions that are still +``AssertionError`` for callers written before they existed.""" + +from types import SimpleNamespace + +import pytest + +import rocketpy +from rocketpy.exceptions import ( + RocketPyError, + StochasticTypeError, + StochasticValueError, +) +from rocketpy.stochastic import ( + StochasticEnvironment, + StochasticFlight, + StochasticFreeFormFins, + StochasticParachute, + StochasticRocket, +) +from rocketpy.stochastic.stochastic_model import StochasticModel + +ENSEMBLE_ENVIRONMENT = SimpleNamespace( + atmospheric_model_type="Ensemble", num_ensemble_members=3 +) + + +def _model_with_mass(**inputs): + return StochasticModel(SimpleNamespace(mass=1.0), **inputs) + + +def _free_form_fins(fins, shape_points): + return StochasticFreeFormFins(free_form_fins=fins, shape_points=shape_points) + + +@pytest.mark.parametrize("error", [StochasticTypeError, StochasticValueError]) +def test_stochastic_errors_keep_their_old_and_new_bases(error): + assert issubclass(error, RocketPyError) + assert issubclass(error, AssertionError) + assert getattr(rocketpy, error.__name__) is error + + +def test_stochastic_errors_are_the_matching_builtin(): + assert issubclass(StochasticTypeError, TypeError) + assert issubclass(StochasticValueError, ValueError) + + +@pytest.mark.parametrize( + "build, error", + [ + pytest.param( + lambda: _model_with_mass(mass="heavy"), StochasticTypeError, id="model_str" + ), + pytest.param( + lambda: _model_with_mass(mass=(1.0, 0.1, "normal", "extra")), + StochasticValueError, + id="model_tuple_length", + ), + pytest.param( + lambda: _model_with_mass(mass=("a", 0.1)), + StochasticTypeError, + id="model_tuple_first_item", + ), + pytest.param( + lambda: _model_with_mass(mass=(1.0, 0.1, 5)), + StochasticTypeError, + id="model_tuple_distribution_name", + ), + pytest.param( + lambda: _model_with_mass(mass=(1.0, [0.1])), + StochasticTypeError, + id="model_tuple_second_item", + ), + pytest.param( + lambda: _model_with_mass()._validate_custom_sampler("mass", object()), + StochasticTypeError, + id="custom_sampler", + ), + pytest.param( + lambda: _model_with_mass()._validate_airfoil([("naca", "x", "y")]), + StochasticValueError, + id="airfoil_tuple_length", + ), + pytest.param( + lambda: _model_with_mass()._validate_airfoil("naca"), + StochasticTypeError, + id="airfoil_not_a_list", + ), + pytest.param( + lambda: _model_with_mass()._validate_positive_int_list("m", [-1]), + StochasticValueError, + id="negative_int_list", + ), + pytest.param( + lambda: _model_with_mass()._validate_positive_int_list("m", "abc"), + StochasticTypeError, + id="int_list_not_a_list", + ), + pytest.param( + lambda: _model_with_mass()._validate_positive_int_list("m", [1.5]), + StochasticTypeError, + id="int_list_float_member", + ), + pytest.param( + lambda: _model_with_mass()._validate_1d_array_like("m", "path"), + StochasticTypeError, + id="array_like_not_a_list", + ), + pytest.param( + lambda: StochasticEnvironment._validate_ensemble( + SimpleNamespace(), + [0], + SimpleNamespace(atmospheric_model_type="Forecast"), + ), + StochasticValueError, + id="ensemble_on_environment_without_members", + ), + pytest.param( + lambda: StochasticEnvironment._validate_ensemble( + SimpleNamespace(), 0, ENSEMBLE_ENVIRONMENT + ), + StochasticTypeError, + id="ensemble_member_not_a_list", + ), + pytest.param( + lambda: StochasticEnvironment._validate_ensemble( + SimpleNamespace(), ["a"], ENSEMBLE_ENVIRONMENT + ), + StochasticTypeError, + id="ensemble_member_not_an_int", + ), + pytest.param( + lambda: StochasticEnvironment._validate_ensemble( + SimpleNamespace(), [-1], ENSEMBLE_ENVIRONMENT + ), + StochasticValueError, + id="ensemble_member_negative", + ), + pytest.param( + lambda: StochasticEnvironment._validate_ensemble( + SimpleNamespace(), [3], ENSEMBLE_ENVIRONMENT + ), + StochasticValueError, + id="ensemble_member_out_of_range", + ), + ], +) +def test_stochastic_model_inputs_raise_the_matching_error(build, error): + with pytest.raises(error): + build() + with pytest.raises(AssertionError): + build() + + +def test_wrong_flight_inputs_raise_the_matching_error(flight_calisto_robust): + with pytest.raises(StochasticTypeError): + StochasticFlight(flight=flight_calisto_robust, terminate_on_apogee="yes") + with pytest.raises(StochasticTypeError): + StochasticFlight(flight=flight_calisto_robust, time_overshoot="yes") + with pytest.raises(StochasticTypeError): + StochasticFlight(flight=flight_calisto_robust, max_time="5") + with pytest.raises(StochasticTypeError): + StochasticFlight(flight=flight_calisto_robust, initial_solution=5) + with pytest.raises(StochasticValueError): + StochasticFlight(flight=flight_calisto_robust, initial_solution=(0.0, 1.0)) + with pytest.raises(AssertionError): + StochasticFlight(flight=flight_calisto_robust, initial_solution=(0.0, 1.0)) + + +def test_wrong_parachute_trigger_raises_the_matching_error(calisto_main_chute): + with pytest.raises(StochasticTypeError): + StochasticParachute(calisto_main_chute, trigger="banana") + with pytest.raises(StochasticValueError): + StochasticParachute(calisto_main_chute, trigger=[]) + with pytest.raises(AssertionError): + StochasticParachute(calisto_main_chute, trigger="banana") + + +@pytest.mark.parametrize( + "shape_points, error", + [ + ("outline", StochasticTypeError), + ([(0.0, 0.0), (0.1, 0.0)], StochasticValueError), + ((0.001,), StochasticValueError), + (([(0.0, 0.0), (0.1, 0.0), (0.1, 0.1)], "x"), StochasticTypeError), + ], + ids=["not_an_outline", "too_few_points", "tuple_too_short", "std_is_a_string"], +) +def test_wrong_free_form_fins_shape_raises_the_matching_error( + calisto_free_form_fins, shape_points, error +): + with pytest.raises(error): + _free_form_fins(calisto_free_form_fins, shape_points) + with pytest.raises(AssertionError): + _free_form_fins(calisto_free_form_fins, shape_points) + + +def test_wrong_rocket_components_raise_the_matching_error(calisto_robust, calisto_tail): + stochastic = StochasticRocket(rocket=calisto_robust) + + with pytest.raises(StochasticTypeError): + stochastic.add_free_form_fins(calisto_tail) + with pytest.raises(StochasticTypeError): + stochastic.set_rail_buttons("buttons") + with pytest.raises(StochasticTypeError): + stochastic.add_motor("motor") + with pytest.raises(StochasticTypeError): + stochastic.add_parachute("parachute") + with pytest.raises(StochasticTypeError): + stochastic.add_air_brakes("air_brakes", controller=None) + with pytest.raises(AssertionError): + stochastic.set_rail_buttons("buttons") diff --git a/tests/unit/stochastic/test_stochastic_parachute.py b/tests/unit/stochastic/test_stochastic_parachute.py index 7b6c95be6..d18024c28 100644 --- a/tests/unit/stochastic/test_stochastic_parachute.py +++ b/tests/unit/stochastic/test_stochastic_parachute.py @@ -193,7 +193,7 @@ def test_the_check_is_not_stripped_by_python_dash_o(): later or reads `True` as a height.""" source = inspect.getsource(StochasticParachute._validate_trigger) - assert "raise AssertionError" in source + assert "raise " in source assert not any(line.strip().startswith("assert ") for line in source.splitlines())