test_string.py 2.9 KB

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