diff --git a/openhtf/core/measurements.py b/openhtf/core/measurements.py index 6c66cf3f..39e98458 100644 --- a/openhtf/core/measurements.py +++ b/openhtf/core/measurements.py @@ -146,6 +146,10 @@ def with_args(self, **kwargs: Any) -> '_ConditionalValidator': return self +def _round_value(value: Any, ndigits: int) -> Any: + return round(value, ndigits=ndigits) if value is not None else None + + def _coordinates_len(coordinates: Any) -> int: """Returns count of measurement coordinates. @@ -397,7 +401,9 @@ def with_precision(self, precision: int) -> 'Measurement': if not isinstance(precision, int): raise TypeError('Precision must be specified as an int, not %s' % type(precision)) - return self.with_transform(functools.partial(round, ndigits=precision)) + return self.with_transform( + functools.partial(_round_value, ndigits=precision) + ) def with_transform(self, transform_fn: Callable[[Any], Any]) -> 'Measurement': """Set the transform function.""" diff --git a/test/core/measurements_test.py b/test/core/measurements_test.py index 068b9bbf..cd9c1168 100644 --- a/test/core/measurements_test.py +++ b/test/core/measurements_test.py @@ -123,6 +123,30 @@ def test_precision(self): m.measured_value[42] = 1.2346 self.assertAlmostEqual(m.measured_value[42], 1.235) + def test_precision_handles_none(self): + """Check that with_precision handles None values gracefully.""" + m = htf.Measurement('meas_with_precision').with_precision(3) + m.measured_value.set(None) + self.assertIsNone(m.measured_value.value) + + m_dim = htf.Measurement('meas_with_precision_and_dims').with_precision( + 3 + ).with_dimensions('x') + m_dim.measured_value[42] = None + self.assertIsNone(m_dim.measured_value[42]) + + def test_precision_with_validator_none(self): + """Check that with_precision with InRange validator handles None without crashing.""" + m = ( + htf.Measurement('meas_with_precision_and_range') + .with_precision(2) + .in_range(1.0, 5.0) + ) + m.measured_value.set(None) + m.notify_value_set() + self.assertEqual(m.outcome, measurements.Outcome.FAIL) + self.assertIsNone(m.measured_value.value) + def test_cache_same_object(self): m = htf.Measurement('measurement') basetypes0 = m.as_base_types()