test_string.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import pytest
  2. import numpy as np
  3. from . import util
  4. class TestString(util.F2PyTest):
  5. sources = [util.getpath("tests", "src", "string", "char.f90")]
  6. @pytest.mark.slow
  7. def test_char(self):
  8. strings = np.array(["ab", "cd", "ef"], dtype="c").T
  9. inp, out = self.module.char_test.change_strings(
  10. strings, strings.shape[1])
  11. assert inp == pytest.approx(strings)
  12. expected = strings.copy()
  13. expected[1, :] = "AAA"
  14. assert out == pytest.approx(expected)
  15. class TestDocStringArguments(util.F2PyTest):
  16. sources = [util.getpath("tests", "src", "string", "string.f")]
  17. def test_example(self):
  18. a = np.array(b"123\0\0")
  19. b = np.array(b"123\0\0")
  20. c = np.array(b"123")
  21. d = np.array(b"123")
  22. self.module.foo(a, b, c, d)
  23. assert a.tobytes() == b"123\0\0"
  24. assert b.tobytes() == b"B23\0\0"
  25. assert c.tobytes() == b"123"
  26. assert d.tobytes() == b"D23"
  27. class TestFixedString(util.F2PyTest):
  28. sources = [util.getpath("tests", "src", "string", "fixed_string.f90")]
  29. @staticmethod
  30. def _sint(s, start=0, end=None):
  31. """Return the content of a string buffer as integer value.
  32. For example:
  33. _sint('1234') -> 4321
  34. _sint('123A') -> 17321
  35. """
  36. if isinstance(s, np.ndarray):
  37. s = s.tobytes()
  38. elif isinstance(s, str):
  39. s = s.encode()
  40. assert isinstance(s, bytes)
  41. if end is None:
  42. end = len(s)
  43. i = 0
  44. for j in range(start, min(end, len(s))):
  45. i += s[j] * 10**j
  46. return i
  47. def _get_input(self, intent="in"):
  48. if intent in ["in"]:
  49. yield ""
  50. yield "1"
  51. yield "1234"
  52. yield "12345"
  53. yield b""
  54. yield b"\0"
  55. yield b"1"
  56. yield b"\01"
  57. yield b"1\0"
  58. yield b"1234"
  59. yield b"12345"
  60. yield np.ndarray((), np.bytes_, buffer=b"") # array(b'', dtype='|S0')
  61. yield np.array(b"") # array(b'', dtype='|S1')
  62. yield np.array(b"\0")
  63. yield np.array(b"1")
  64. yield np.array(b"1\0")
  65. yield np.array(b"\01")
  66. yield np.array(b"1234")
  67. yield np.array(b"123\0")
  68. yield np.array(b"12345")
  69. def test_intent_in(self):
  70. for s in self._get_input():
  71. r = self.module.test_in_bytes4(s)
  72. # also checks that s is not changed inplace
  73. expected = self._sint(s, end=4)
  74. assert r == expected, s
  75. def test_intent_inout(self):
  76. for s in self._get_input(intent="inout"):
  77. rest = self._sint(s, start=4)
  78. r = self.module.test_inout_bytes4(s)
  79. expected = self._sint(s, end=4)
  80. assert r == expected
  81. # check that the rest of input string is preserved
  82. assert rest == self._sint(s, start=4)