From 8a4142d4bc33de089220b1e26282500c6ce2d02b Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Mon, 7 Aug 2017 13:37:46 -0400 Subject: [PATCH] [Python] Raise exception when setting composition with empty array --- interfaces/cython/cantera/test/test_thermo.py | 8 ++++++++ interfaces/cython/cantera/thermo.pyx | 9 +++++---- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/interfaces/cython/cantera/test/test_thermo.py b/interfaces/cython/cantera/test/test_thermo.py index c27d04811..de4323b05 100644 --- a/interfaces/cython/cantera/test/test_thermo.py +++ b/interfaces/cython/cantera/test/test_thermo.py @@ -217,8 +217,16 @@ class TestThermoPhase(utilities.CanteraTest): self.assertEqual(gas.Y[0], 1.0) def test_setCompositionSlice_bad(self): + X0 = self.phase.X with self.assertRaises(ValueError): self.phase['H2','O2'].Y = [0.1, 0.2, 0.3] + self.assertArrayNear(self.phase.X, X0) + + def test_setCompositionEmpty_bad(self): + X0 = self.phase.X + with self.assertRaises(ValueError): + self.phase.Y = np.array([]) + self.assertArrayNear(self.phase.X, X0) def test_set_equivalence_ratio_stoichiometric(self): gas = ct.Solution('gri30.xml') diff --git a/interfaces/cython/cantera/thermo.pyx b/interfaces/cython/cantera/thermo.pyx index c95e43552..8700487fb 100644 --- a/interfaces/cython/cantera/thermo.pyx +++ b/interfaces/cython/cantera/thermo.pyx @@ -497,14 +497,15 @@ cdef class ThermoPhase(_SolutionBase): if len(values) == self.n_species: data = np.ascontiguousarray(values, dtype=np.double) - elif len(values) == len(self._selected_species): + elif len(values) == len(self._selected_species) != 0: data = np.zeros(self.n_species, dtype=np.double) for i,k in enumerate(self._selected_species): data[k] = values[i] else: - raise ValueError("Array has incorrect length." - " Got {}. Expected {} or {}.".format( - len(values), self.n_species, len(self._selected_species))) + msg = "Got {}. Expected {}".format(len(values), self.n_species) + if len(self._selected_species): + msg += ' or {}'.format(len(self._selected_species)) + raise ValueError('Array has incorrect length. ' + msg + '.') method(self.thermo, &data[0]) property molecular_weights: