test_byteswap.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from hypothesis import (
  2. assume,
  3. example,
  4. given,
  5. strategies as st,
  6. )
  7. import numpy as np
  8. import pytest
  9. import pandas._testing as tm
  10. from pandas.io.sas._byteswap import (
  11. read_double_with_byteswap,
  12. read_float_with_byteswap,
  13. read_uint16_with_byteswap,
  14. read_uint32_with_byteswap,
  15. read_uint64_with_byteswap,
  16. )
  17. @given(read_offset=st.integers(0, 11), number=st.integers(min_value=0))
  18. @example(number=2**16, read_offset=0)
  19. @example(number=2**32, read_offset=0)
  20. @example(number=2**64, read_offset=0)
  21. @pytest.mark.parametrize("int_type", [np.uint16, np.uint32, np.uint64])
  22. @pytest.mark.parametrize("should_byteswap", [True, False])
  23. def test_int_byteswap(read_offset, number, int_type, should_byteswap):
  24. assume(number < 2 ** (8 * int_type(0).itemsize))
  25. _test(number, int_type, read_offset, should_byteswap)
  26. @pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning")
  27. @given(read_offset=st.integers(0, 11), number=st.floats())
  28. @pytest.mark.parametrize("float_type", [np.float32, np.float64])
  29. @pytest.mark.parametrize("should_byteswap", [True, False])
  30. def test_float_byteswap(read_offset, number, float_type, should_byteswap):
  31. _test(number, float_type, read_offset, should_byteswap)
  32. def _test(number, number_type, read_offset, should_byteswap):
  33. number = number_type(number)
  34. data = np.random.default_rng().integers(0, 256, size=20, dtype="uint8")
  35. data[read_offset : read_offset + number.itemsize] = number[None].view("uint8")
  36. swap_func = {
  37. np.float32: read_float_with_byteswap,
  38. np.float64: read_double_with_byteswap,
  39. np.uint16: read_uint16_with_byteswap,
  40. np.uint32: read_uint32_with_byteswap,
  41. np.uint64: read_uint64_with_byteswap,
  42. }[type(number)]
  43. output_number = number_type(swap_func(bytes(data), read_offset, should_byteswap))
  44. if should_byteswap:
  45. tm.assert_equal(output_number, number.byteswap())
  46. else:
  47. tm.assert_equal(output_number, number)