Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TST: increase test coverage #756

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@
"rtol",
"rtype",
"rucsoundings",
"runslow",
"rwork",
"savetxt",
"savgol",
Expand Down
23 changes: 11 additions & 12 deletions rocketpy/environment/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,7 @@ def __initialize_utm_coordinates(self):
flattening=self.ellipsoid.flattening,
semi_major_axis=self.ellipsoid.semi_major_axis,
)
else:
# pragma: no cover
else: # pragma: no cover
warnings.warn(
"UTM coordinates are not available for latitudes "
"above 84 or below -80 degrees. The UTM conversions will fail."
Expand Down Expand Up @@ -715,8 +714,8 @@ def set_location(self, latitude, longitude):

if not isinstance(latitude, NUMERICAL_TYPES) and isinstance(
longitude, NUMERICAL_TYPES
):
# pragma: no cover
): # pragma: no cover

raise TypeError("Latitude and Longitude must be numbers!")

# Store latitude and longitude
Expand Down Expand Up @@ -812,8 +811,8 @@ def max_expected_height(self):

@max_expected_height.setter
def max_expected_height(self, value):
if value < self.elevation:
raise ValueError( # pragma: no cover
if value < self.elevation: # pragma: no cover
raise ValueError(
"Max expected height cannot be lower than the surface elevation"
)
self._max_expected_height = value
Expand Down Expand Up @@ -952,8 +951,8 @@ def get_elevation_from_topographic_profile(self, lat, lon):
Elevation provided by the topographic data, in meters.
"""
# TODO: refactor this method. pylint: disable=too-many-statements
if self.topographic_profile_activated is False:
raise ValueError( # pragma: no cover
if self.topographic_profile_activated is False: # pragma: no cover
raise ValueError(
"You must define a Topographic profile first, please use the "
"Environment.set_topographic_profile() method first."
)
Expand Down Expand Up @@ -1285,8 +1284,8 @@ def set_atmospheric_model( # pylint: disable=too-many-statements
self.process_forecast_reanalysis(dataset, dictionary)
else:
self.process_ensemble(dataset, dictionary)
else:
raise ValueError(f"Unknown model type '{type}'.") # pragma: no cover
else: # pragma: no cover
raise ValueError(f"Unknown model type '{type}'.")

if type not in ["ensemble"]:
# Ensemble already computed these values
Expand Down Expand Up @@ -2578,7 +2577,7 @@ def set_earth_geometry(self, datum):
}
try:
return ellipsoid[datum]
except KeyError as e:
except KeyError as e: # pragma: no cover
available_datums = ', '.join(ellipsoid.keys())
raise AttributeError(
f"The reference system '{datum}' is not recognized. Please use one of "
Expand Down Expand Up @@ -2845,7 +2844,7 @@ def from_dict(cls, data): # pylint: disable=too-many-statements
return env


if __name__ == "__main__":
if __name__ == "__main__": # pragma: no cover
import doctest

results = doctest.testmod()
Expand Down
10 changes: 5 additions & 5 deletions rocketpy/environment/fetchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ def fetch_atmospheric_data_from_windy(lat, lon, model):

try:
response = requests.get(url).json()
if "data" not in response.keys():
if "data" not in response.keys(): # pragma: no cover
raise ValueError(
f"Could not get a valid response for '{model}' from Windy. "
"Check if the coordinates are set inside the model's domain."
)
except requests.exceptions.RequestException as e:
except requests.exceptions.RequestException as e: # pragma: no cover
if model == "iconEu":
raise ValueError(
"Could not get a valid response for Icon-EU from Windy. "
Expand Down Expand Up @@ -315,8 +315,8 @@ def fetch_wyoming_sounding(file):
If the response indicates the output format is invalid.
"""
response = requests.get(file)
if response.status_code != 200:
raise ImportError(f"Unable to load {file}.") # pragma: no cover
if response.status_code != 200: # pragma: no cover
raise ImportError(f"Unable to load {file}.")
if len(re.findall("Can't get .+ Observations at", response.text)):
raise ValueError(
re.findall("Can't get .+ Observations at .+", response.text)[0]
Expand All @@ -330,7 +330,7 @@ def fetch_wyoming_sounding(file):


@exponential_backoff(max_attempts=5, base_delay=2, max_delay=60)
def fetch_noaaruc_sounding(file):
def fetch_noaaruc_sounding(file): # pragma: no cover
"""Fetches sounding data from a specified file using the NOAA RUC soundings.

Parameters
Expand Down
2 changes: 1 addition & 1 deletion rocketpy/environment/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -590,7 +590,7 @@ def utm_to_geodesic( # pylint: disable=too-many-locals,too-many-statements
return lat, lon


if __name__ == "__main__":
if __name__ == "__main__": # pragma: no cover
import doctest

results = doctest.testmod()
Expand Down
18 changes: 10 additions & 8 deletions rocketpy/mathutils/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -1481,7 +1481,7 @@ def plot(self, *args, **kwargs):
else:
print("Error: Only functions with 1D or 2D domains can be plotted.")

def plot1D(self, *args, **kwargs):
def plot1D(self, *args, **kwargs): # pragma: no cover
"""Deprecated method, use Function.plot_1d instead."""
warnings.warn(
"The `Function.plot1D` method is set to be deprecated and fully "
Expand Down Expand Up @@ -1581,7 +1581,7 @@ def plot_1d( # pylint: disable=too-many-statements
if return_object:
return fig, ax

def plot2D(self, *args, **kwargs):
def plot2D(self, *args, **kwargs): # pragma: no cover
"""Deprecated method, use Function.plot_2d instead."""
warnings.warn(
"The `Function.plot2D` method is set to be deprecated and fully "
Expand Down Expand Up @@ -2772,7 +2772,7 @@ def differentiate_complex_step(self, x, dx=1e-200, order=1):
"""
if order == 1:
return float(self.get_value_opt(x + dx * 1j).imag / dx)
else:
else: # pragma: no cover
raise NotImplementedError(
"Only 1st order derivatives are supported yet. Set order=1."
)
Expand Down Expand Up @@ -3119,12 +3119,12 @@ def compose(self, func, extrapolate=False):
The result of inputting the function into the function.
"""
# Check if the input is a function
if not isinstance(func, Function):
if not isinstance(func, Function): # pragma: no cover
raise TypeError("Input must be a Function object.")

if isinstance(self.source, np.ndarray) and isinstance(func.source, np.ndarray):
# Perform bounds check for composition
if not extrapolate:
if not extrapolate: # pragma: no cover
if func.min < self.x_initial or func.max > self.x_final:
raise ValueError(
f"Input Function image {func.min, func.max} must be within "
Expand Down Expand Up @@ -3197,7 +3197,7 @@ def savetxt(

# create the datapoints
if callable(self.source):
if lower is None or upper is None or samples is None:
if lower is None or upper is None or samples is None: # pragma: no cover
raise ValueError(
"If the source is a callable, lower, upper and samples"
+ " must be provided."
Expand Down Expand Up @@ -3264,7 +3264,7 @@ def __validate_source(self, source): # pylint: disable=too-many-statements
self.__inputs__ = header[:-1]
if self.__outputs__ is None:
self.__outputs__ = [header[-1]]
except Exception as e:
except Exception as e: # pragma: no cover
raise ValueError(
"Could not read the csv or txt file to create Function source."
) from e
Expand Down Expand Up @@ -3323,6 +3323,7 @@ def __validate_inputs(self, inputs):
if isinstance(inputs, (list, tuple)):
if len(inputs) == 1:
return inputs
# pragma: no cover
raise ValueError(
"Inputs must be a string or a list of strings with "
"the length of the domain dimension."
Expand All @@ -3335,6 +3336,7 @@ def __validate_inputs(self, inputs):
isinstance(i, str) for i in inputs
):
return inputs
# pragma: no cover
raise ValueError(
"Inputs must be a list of strings with "
"the length of the domain dimension."
Expand Down Expand Up @@ -3611,7 +3613,7 @@ def reset_funcified_methods(instance):
instance.__dict__.pop(key)


if __name__ == "__main__":
if __name__ == "__main__": # pragma: no cover
import doctest

results = doctest.testmod()
Expand Down
2 changes: 1 addition & 1 deletion rocketpy/mathutils/vector_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -1103,7 +1103,7 @@ def from_dict(cls, data):
return cls(data)


if __name__ == "__main__":
if __name__ == "__main__": # pragma: no cover
import doctest

results = doctest.testmod()
Expand Down
4 changes: 2 additions & 2 deletions rocketpy/motors/fluid.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ def __post_init__(self):
If the density is not a positive number.
"""

if not isinstance(self.name, str):
if not isinstance(self.name, str): # pragma: no cover
raise ValueError("The name must be a string.")
if self.density < 0:
if self.density < 0: # pragma: no cover
raise ValueError("The density must be a positive number.")

# Initialize plots and prints object
Expand Down
4 changes: 2 additions & 2 deletions rocketpy/motors/motor.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ class Function. Thrust units are Newtons.
self._csys = 1
elif coordinate_system_orientation == "combustion_chamber_to_nozzle":
self._csys = -1
else:
else: # pragma: no cover
raise ValueError(
"Invalid coordinate system orientation. Options are "
"'nozzle_to_combustion_chamber' and 'combustion_chamber_to_nozzle'."
Expand Down Expand Up @@ -346,7 +346,7 @@ def burn_time(self, burn_time):
else:
if not callable(self.thrust.source):
self._burn_time = (self.thrust.x_array[0], self.thrust.x_array[-1])
else:
else: # pragma: no cover
raise ValueError(
"When using a float or callable as thrust source, a burn_time"
" argument must be specified."
Expand Down
4 changes: 2 additions & 2 deletions rocketpy/plots/rocket_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ def _draw_generic_surface(
x_pos = position[2]
# y position of the surface is the y position in the plot
y_pos = position[1]
else:
else: # pragma: no cover
raise ValueError("Plane must be 'xz' or 'yz'.")

ax.scatter(
Expand Down Expand Up @@ -633,7 +633,7 @@ def _draw_sensors(self, ax, sensors, plane):
# y position of the sensor is the y position in the plot
y_pos = pos[1]
normal_y = sensor.normal_vector.y
else:
else: # pragma: no cover
raise ValueError("Plane must be 'xz' or 'yz'.")

# line length is 2/5 of the rocket radius
Expand Down
2 changes: 1 addition & 1 deletion rocketpy/prints/compare_prints.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
class _ComparePrints:
class _ComparePrints: # pragma: no cover
def __init__(self) -> None:
pass
15 changes: 7 additions & 8 deletions rocketpy/rocket/aero_surface/nose_cone.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def __init__( # pylint: disable=too-many-statements
self._base_radius = base_radius
self._length = length
if bluffness is not None:
if bluffness > 1 or bluffness < 0:
if bluffness > 1 or bluffness < 0: # pragma: no cover
raise ValueError(
f"Bluffness ratio of {bluffness} is out of range. "
"It must be between 0 and 1."
Expand Down Expand Up @@ -286,7 +286,7 @@ def theta(x):
self.y_nosecone = Function(
lambda x: self.base_radius * np.power(x / self.length, self.power)
)
else:
else: # pragma: no cover
raise ValueError(
f"Nose Cone kind '{self.kind}' not found, "
+ "please use one of the following Nose Cone kinds:"
Expand Down Expand Up @@ -317,12 +317,11 @@ def bluffness(self, value):
raise ValueError(
"Parameter 'bluffness' must be None or 0 when using a nose cone kind 'powerseries'."
)
if value is not None:
if value > 1 or value < 0:
raise ValueError(
f"Bluffness ratio of {value} is out of range. "
"It must be between 0 and 1."
)
if value is not None and not 0 <= value <= 1: # pragma: no cover
raise ValueError(
f"Bluffness ratio of {value} is out of range. "
"It must be between 0 and 1."
)
self._bluffness = value
self.evaluate_nose_shape()

Expand Down
4 changes: 2 additions & 2 deletions rocketpy/rocket/rocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def __init__( # pylint: disable=too-many-statements
self._csys = 1
elif coordinate_system_orientation == "nose_to_tail":
self._csys = -1
else:
else: # pragma: no cover
raise TypeError(
"Invalid coordinate system orientation. Please choose between "
+ '"tail_to_nose" and "nose_to_tail".'
Expand Down Expand Up @@ -1173,7 +1173,7 @@ def add_nose(
self.add_surfaces(nose, position)
return nose

def add_fins(self, *args, **kwargs):
def add_fins(self, *args, **kwargs): # pragma: no cover
"""See Rocket.add_trapezoidal_fins for documentation.
This method is set to be deprecated in version 1.0.0 and fully removed
by version 2.0.0. Use Rocket.add_trapezoidal_fins instead. It keeps the
Expand Down
8 changes: 2 additions & 6 deletions rocketpy/sensitivity/sensitivity_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,6 @@ def set_target_variables_nominal(self, target_variables_nominal_value):
self.target_variables_info[target_variable]["nominal_value"] = (
target_variables_nominal_value[i]
)
for i, target_variable in enumerate(self.target_variables_names):
self.target_variables_info[target_variable]["nominal_value"] = (
target_variables_nominal_value[i]
)

self._nominal_target_passed = True

Expand Down Expand Up @@ -356,12 +352,12 @@ def __check_requirements(self):
version = ">=0" if not version else version
try:
check_requirement_version(module_name, version)
except (ValueError, ImportError) as e:
except (ValueError, ImportError) as e: # pragma: no cover
has_error = True
print(
f"The following error occurred while importing {module_name}: {e}"
)
if has_error:
if has_error: # pragma: no cover
print(
"Given the above errors, some methods may not work. Please run "
+ "'pip install rocketpy[sensitivity]' to install extra requirements."
Expand Down
Loading
Loading