|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import pytest |
| 5 | + |
| 6 | +from arraybridge import ArrayGeometry, ArrayPayload |
| 7 | + |
| 8 | + |
| 9 | +class DeviceArray: |
| 10 | + """Array-shaped value that rejects implicit host conversion.""" |
| 11 | + |
| 12 | + shape = (2, 3, 4) |
| 13 | + |
| 14 | + def __array__(self, dtype=None): |
| 15 | + del dtype |
| 16 | + raise TypeError("implicit host conversion is forbidden") |
| 17 | + |
| 18 | + |
| 19 | +class DevicePayload(ArrayPayload): |
| 20 | + def __init__(self, data): |
| 21 | + self.data = data |
| 22 | + |
| 23 | + def array_payload_data(self): |
| 24 | + return self.data |
| 25 | + |
| 26 | + def with_data(self, data): |
| 27 | + return type(self)(data) |
| 28 | + |
| 29 | + |
| 30 | +def test_array_geometry_reads_declared_device_shape_without_host_conversion() -> None: |
| 31 | + assert ArrayGeometry.from_value(DeviceArray()) == ArrayGeometry((2, 3, 4)) |
| 32 | + |
| 33 | + |
| 34 | +def test_array_geometry_unwraps_nominal_array_payload() -> None: |
| 35 | + assert ArrayGeometry.from_value(DevicePayload(DeviceArray())) == ArrayGeometry((2, 3, 4)) |
| 36 | + |
| 37 | + |
| 38 | +def test_array_geometry_falls_back_for_python_array_inputs() -> None: |
| 39 | + assert ArrayGeometry.from_value([[1, 2], [3, 4]]) == ArrayGeometry((2, 2)) |
| 40 | + assert ArrayGeometry.from_value(np.zeros((4, 5))) == ArrayGeometry((4, 5)) |
| 41 | + |
| 42 | + |
| 43 | +def test_array_geometry_requires_concrete_shape() -> None: |
| 44 | + class UnshapedValue: |
| 45 | + def __array__(self, dtype=None): |
| 46 | + del dtype |
| 47 | + raise TypeError("not an array") |
| 48 | + |
| 49 | + with pytest.raises(TypeError, match="Runtime output requires concrete array geometry"): |
| 50 | + ArrayGeometry.require_from_value( |
| 51 | + UnshapedValue(), |
| 52 | + value_name="Runtime output", |
| 53 | + ) |
0 commit comments