From 5203640549e690672c1bea3a1aa9ebe6c4f47121 Mon Sep 17 00:00:00 2001 From: Jonathan Shimwell Date: Thu, 9 Jul 2026 23:55:32 +0200 Subject: [PATCH] Further input validation for plot methods (#4004) --- openmc/model/model.py | 14 +++++++++++++- tests/unit_tests/test_model.py | 21 +++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/openmc/model/model.py b/openmc/model/model.py index 328494288..b166137f2 100644 --- a/openmc/model/model.py +++ b/openmc/model/model.py @@ -21,7 +21,8 @@ import openmc import openmc._xml as xml from openmc.dummy_comm import DummyCommunicator from openmc.executor import _process_CLI_arguments -from openmc.checkvalue import check_type, check_value, PathLike +from openmc.checkvalue import (check_type, check_value, check_greater_than, + check_length, PathLike) from openmc.exceptions import InvalidIDError from openmc.plots import add_plot_params, _BASIS_INDICES, id_map_to_rgb from openmc.utility_funcs import change_directory @@ -1050,6 +1051,13 @@ class Model: pixels: int | Sequence[int], basis: str ): + if isinstance(pixels, int): + check_greater_than('pixels', pixels, 0) + else: + check_length('pixels', pixels, 2) + for p in pixels: + check_greater_than('pixels', p, 0) + x, y, _ = _BASIS_INDICES[basis] bb = self.bounding_box @@ -1301,7 +1309,11 @@ class Model: import matplotlib.pyplot as plt check_type('n_samples', n_samples, int | None) + if n_samples is not None: + check_greater_than('n_samples', n_samples, 0, equality=True) check_type('plane_tolerance', plane_tolerance, Real) + check_greater_than('plane_tolerance', plane_tolerance, 0.0) + if legend_kwargs is None: legend_kwargs = {} legend_kwargs.setdefault('bbox_to_anchor', (1.05, 1)) diff --git a/tests/unit_tests/test_model.py b/tests/unit_tests/test_model.py index 028a83b0b..52ac43117 100644 --- a/tests/unit_tests/test_model.py +++ b/tests/unit_tests/test_model.py @@ -660,6 +660,27 @@ def test_model_plot(): plt.close('all') +def test_model_plot_invalid_inputs(): + surface = openmc.Sphere(r=10.0, boundary_type="vacuum") + cell = openmc.Cell(region=-surface) + model = openmc.Model(openmc.Geometry([cell])) + + with pytest.raises(ValueError): + model.plot(n_samples=-1) + with pytest.raises(TypeError): + model.plot(n_samples=1.5) + with pytest.raises(ValueError): + model.plot(plane_tolerance=0.0) + with pytest.raises(TypeError): + model.plot(plane_tolerance='1') + with pytest.raises(ValueError): + model.plot(pixels=-1) + with pytest.raises(ValueError): + model.plot(pixels=(0, 100)) + with pytest.raises(ValueError): + model.plot(pixels=(100,)) + + def test_model_id_map_initialization(run_in_tmpdir): model = openmc.examples.pwr_assembly() model.init_lib(output=False)