|
| 1 | +# Copyright 2026 BrainX Ecosystem Limited. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +# ============================================================================== |
| 15 | + |
| 16 | +"""Regression tests from the Quantity string-formatting audit. |
| 17 | +
|
| 18 | +Each test below pins one confirmed bug in ``__repr__`` / ``__str__`` / |
| 19 | +``__format__`` / ``_format_value`` (saiunit/_base_quantity.py). The docstrings |
| 20 | +record the wrong behavior observed before the fix. |
| 21 | +""" |
| 22 | + |
| 23 | +import jax |
| 24 | +import jax.numpy as jnp |
| 25 | +import numpy as np |
| 26 | +import pytest |
| 27 | + |
| 28 | +import saiunit as u |
| 29 | +from saiunit import Quantity |
| 30 | + |
| 31 | + |
| 32 | +class TestReprLargePythonInt: |
| 33 | + def test_repr_does_not_crash_on_large_python_int(self): |
| 34 | + """``_format_value`` promotes Python scalars via ``jnp.asarray`` and |
| 35 | + caught only TypeError. A Python int that does not fit int32 raises |
| 36 | + OverflowError, so ``repr``/``str`` crashed for values as small as |
| 37 | + 2**40. |
| 38 | +
|
| 39 | + Before the fix: OverflowError: Python int 1099511627776 too large to |
| 40 | + convert to int32. |
| 41 | + """ |
| 42 | + q = Quantity(2 ** 40, unit=u.mV) |
| 43 | + r = repr(q) |
| 44 | + s = str(q) |
| 45 | + assert "1099511627776" in r |
| 46 | + assert "1099511627776" in s |
| 47 | + |
| 48 | + |
| 49 | +class TestPercentFormatGuard: |
| 50 | + def test_percent_rejected_for_named_dimensionless_unit(self): |
| 51 | + """The '%' guard in ``__format__`` checked ``unit.is_unitless`` while |
| 52 | + display uses ``unit.should_display_unit``. Radian is unitless by |
| 53 | + magnitude but displays 'rad', so the guard let through exactly the |
| 54 | + nonsense it was written to block. |
| 55 | +
|
| 56 | + Before the fix: format(Quantity(0.5, unit=u.radian), '.1%') |
| 57 | + == '50.0% rad'. |
| 58 | + """ |
| 59 | + q = Quantity(0.5, unit=u.radian) |
| 60 | + with pytest.raises(ValueError): |
| 61 | + format(q, ".1%") |
| 62 | + |
| 63 | + def test_percent_as_fill_character_is_not_rejected(self): |
| 64 | + """The guard tested ``'%' in format_spec``, so '%' used as a |
| 65 | + legitimate fill character (e.g. '%>10') was rejected even though the |
| 66 | + format type is not '%'. |
| 67 | +
|
| 68 | + Before the fix: ValueError instead of '%%%%%%%0.5 mV' |
| 69 | + (plain ``format(0.5, '%>10')`` gives '%%%%%%%0.5'). |
| 70 | + """ |
| 71 | + q = Quantity(0.5, unit=u.mV) |
| 72 | + assert format(q, "%>10") == "%%%%%%%0.5 mV" |
| 73 | + |
| 74 | + def test_percent_array_keeps_percent_semantics(self): |
| 75 | + """For non-scalar unitless quantities, '.1%' fell into the |
| 76 | + precision-regex path which treated '%' as a plain rounding spec: no |
| 77 | + x100 scaling and no '%' sign — silently wrong values. Scalars gave |
| 78 | + '50.0%'; arrays gave '[0.5 0.2]'. |
| 79 | +
|
| 80 | + Either honoring percent semantics per element or rejecting the spec |
| 81 | + for arrays is acceptable; silently emitting wrong numbers is not. |
| 82 | + """ |
| 83 | + q = Quantity(np.array([0.5, 0.25])) |
| 84 | + try: |
| 85 | + out = format(q, ".1%") |
| 86 | + except ValueError: |
| 87 | + return # explicit rejection is an acceptable contract |
| 88 | + assert "%" in out, f"percent semantics dropped: {out!r}" |
| 89 | + |
| 90 | + |
| 91 | +class TestFormatSpecArraySemantics: |
| 92 | + def test_scientific_spec_array_uses_scientific_notation(self): |
| 93 | + """The array path extracted only the precision digit from '.1e' and |
| 94 | + applied decimal rounding (np.round(value, 1)), ignoring the 'e' type |
| 95 | + entirely. Scalars honor it ('1.2e+03'); arrays did not. |
| 96 | +
|
| 97 | + Before the fix: format(Quantity([1234.5], mV), '.1e') |
| 98 | + == '[1234.5] mV'. |
| 99 | + """ |
| 100 | + q = Quantity(np.array([1234.5]), unit=u.mV) |
| 101 | + out = format(q, ".1e") |
| 102 | + value_part = out.replace("mV", "") |
| 103 | + assert "e" in value_part, f"scientific notation dropped: {out!r}" |
| 104 | + |
| 105 | + |
| 106 | +class TestFormatSpecUnderJit: |
| 107 | + def test_format_spec_scalar_under_jit_does_not_crash(self): |
| 108 | + """``__format__`` had no tracer guard (unlike ``_format_value``). |
| 109 | + For 0-d quantities it called ``format(self.mantissa, format_spec)`` |
| 110 | + which raises on tracers. |
| 111 | +
|
| 112 | + Before the fix: TypeError: unsupported format string passed to |
| 113 | + DynamicJaxprTracer.__format__. |
| 114 | + """ |
| 115 | + captured = [] |
| 116 | + |
| 117 | + @jax.jit |
| 118 | + def f(x): |
| 119 | + q = Quantity(x, unit=u.mV) |
| 120 | + captured.append(f"{q:.2f}") |
| 121 | + return x |
| 122 | + |
| 123 | + f(jnp.asarray(1.0)) |
| 124 | + assert captured and isinstance(captured[0], str) |
| 125 | + |
| 126 | + def test_format_spec_array_under_jit_does_not_crash(self): |
| 127 | + """For non-scalar quantities ``__format__`` called |
| 128 | + ``np.asarray(self.mantissa)`` which raises |
| 129 | + TracerArrayConversionError on traced arrays. |
| 130 | + """ |
| 131 | + captured = [] |
| 132 | + |
| 133 | + @jax.jit |
| 134 | + def f(x): |
| 135 | + q = Quantity(x, unit=u.mV) |
| 136 | + captured.append(f"{q:.2f}") |
| 137 | + return x |
| 138 | + |
| 139 | + f(jnp.arange(3.0)) |
| 140 | + assert captured and isinstance(captured[0], str) |
| 141 | + |
| 142 | + |
| 143 | +class TestFormatSpecLazyBackends: |
| 144 | + def test_format_spec_dask_does_not_materialize(self): |
| 145 | + """``_format_value`` never materializes dask graphs and |
| 146 | + ``np.asarray(Quantity)`` raises BackendError, but |
| 147 | + ``__format__('.2f')`` called ``np.asarray(self.mantissa)`` directly, |
| 148 | + silently computing the whole graph. |
| 149 | +
|
| 150 | + Either a lazy-safe fallback or BackendError is acceptable; silent |
| 151 | + materialization is not. |
| 152 | + """ |
| 153 | + da = pytest.importorskip("dask.array") |
| 154 | + reads = [] |
| 155 | + |
| 156 | + def spy(block): |
| 157 | + if block.size: # ignore dask's zero-size meta-inference calls |
| 158 | + reads.append(block.size) |
| 159 | + return block |
| 160 | + |
| 161 | + arr = da.from_array(np.array([1.0, 2.0]), chunks=1).map_blocks(spy) |
| 162 | + q = Quantity(arr, unit=u.mV) |
| 163 | + reads.clear() |
| 164 | + try: |
| 165 | + format(q, ".2f") |
| 166 | + except u.BackendError: |
| 167 | + pass # explicit rejection is an acceptable contract |
| 168 | + assert not reads, "format(q, '.2f') materialized the dask graph" |
| 169 | + |
| 170 | + def test_format_spec_ndonnx_no_opaque_crash(self): |
| 171 | + """``__format__('.2f')`` applied ``np.round`` to the ndonnx symbolic |
| 172 | + array, raising an opaque ufunc TypeError. ``repr``/``str`` degrade |
| 173 | + gracefully for the same quantity. |
| 174 | +
|
| 175 | + Before the fix: TypeError: loop of ufunc does not support argument 0 |
| 176 | + of type Array which has no callable rint method. |
| 177 | + """ |
| 178 | + ndx = pytest.importorskip("ndonnx") |
| 179 | + q = Quantity(ndx.asarray(np.array([1.0, 2.0])), unit=u.mV) |
| 180 | + try: |
| 181 | + out = format(q, ".2f") |
| 182 | + except u.BackendError: |
| 183 | + return # explicit rejection is an acceptable contract |
| 184 | + assert isinstance(out, str) |
| 185 | + |
| 186 | + def test_format_spec_torch_requires_grad_does_not_crash(self): |
| 187 | + """``__format__('.2f')`` called ``np.asarray`` on the torch mantissa; |
| 188 | + tensors with ``requires_grad=True`` refuse the conversion. |
| 189 | + ``repr``/``str`` work for the same quantity. |
| 190 | +
|
| 191 | + Before the fix: RuntimeError: Can't call numpy() on Tensor that |
| 192 | + requires grad. |
| 193 | + """ |
| 194 | + torch = pytest.importorskip("torch") |
| 195 | + q = Quantity(torch.tensor([1.5], requires_grad=True), unit=u.mV) |
| 196 | + out = format(q, ".2f") |
| 197 | + assert isinstance(out, str) |
0 commit comments