|
| 1 | +import struct |
| 2 | +from typing import Union |
| 3 | + |
1 | 4 | import pytest
|
2 | 5 | from hypothesis import given
|
| 6 | +from hypothesis import strategies as st |
3 | 7 |
|
4 | 8 | from . import _array_module as xp
|
5 | 9 | from . import dtype_helpers as dh
|
6 | 10 | from . import hypothesis_helpers as hh
|
7 | 11 | from . import pytest_helpers as ph
|
| 12 | +from . import xps |
8 | 13 | from .typing import DataType
|
9 | 14 |
|
10 | 15 |
|
| 16 | +def float32(n: Union[int, float]) -> float: |
| 17 | + return struct.unpack("!f", struct.pack("!f", float(n)))[0] |
| 18 | + |
| 19 | + |
| 20 | +@given( |
| 21 | + x_dtype=xps.scalar_dtypes(), |
| 22 | + dtype=xps.scalar_dtypes(), |
| 23 | + kw=hh.kwargs(copy=st.booleans()), |
| 24 | + data=st.data(), |
| 25 | +) |
| 26 | +def test_astype(x_dtype, dtype, kw, data): |
| 27 | + if xp.bool in (x_dtype, dtype): |
| 28 | + elements_strat = xps.from_dtype(x_dtype) |
| 29 | + else: |
| 30 | + m1, M1 = dh.dtype_ranges[x_dtype] |
| 31 | + m2, M2 = dh.dtype_ranges[dtype] |
| 32 | + if dh.is_int_dtype(x_dtype): |
| 33 | + cast = int |
| 34 | + elif x_dtype == xp.float32: |
| 35 | + cast = float32 |
| 36 | + else: |
| 37 | + cast = float |
| 38 | + min_value = cast(max(m1, m2)) |
| 39 | + max_value = cast(min(M1, M2)) |
| 40 | + elements_strat = xps.from_dtype( |
| 41 | + x_dtype, |
| 42 | + min_value=min_value, |
| 43 | + max_value=max_value, |
| 44 | + allow_nan=False, |
| 45 | + allow_infinity=False, |
| 46 | + ) |
| 47 | + x = data.draw( |
| 48 | + xps.arrays(dtype=x_dtype, shape=hh.shapes(), elements=elements_strat), label="x" |
| 49 | + ) |
| 50 | + |
| 51 | + out = xp.astype(x, dtype, **kw) |
| 52 | + |
| 53 | + ph.assert_kw_dtype("astype", dtype, out.dtype) |
| 54 | + ph.assert_shape("astype", out.shape, x.shape) |
| 55 | + # TODO: test values |
| 56 | + # TODO: test copy |
| 57 | + |
| 58 | + |
11 | 59 | def make_dtype_id(dtype: DataType) -> str:
|
12 | 60 | return dh.dtype_to_name[dtype]
|
13 | 61 |
|
|
0 commit comments