test_loadtxt.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. """
  2. Tests specific to `np.loadtxt` added during the move of loadtxt to be backed
  3. by C code.
  4. These tests complement those found in `test_io.py`.
  5. """
  6. import sys
  7. import os
  8. import pytest
  9. from tempfile import NamedTemporaryFile, mkstemp
  10. from io import StringIO
  11. import numpy as np
  12. from numpy.ma.testutils import assert_equal
  13. from numpy.testing import assert_array_equal, HAS_REFCOUNT, IS_PYPY
  14. def test_scientific_notation():
  15. """Test that both 'e' and 'E' are parsed correctly."""
  16. data = StringIO(
  17. "1.0e-1,2.0E1,3.0\n"
  18. "4.0e-2,5.0E-1,6.0\n"
  19. "7.0e-3,8.0E1,9.0\n"
  20. "0.0e-4,1.0E-1,2.0"
  21. )
  22. expected = np.array(
  23. [[0.1, 20., 3.0], [0.04, 0.5, 6], [0.007, 80., 9], [0, 0.1, 2]]
  24. )
  25. assert_array_equal(np.loadtxt(data, delimiter=","), expected)
  26. @pytest.mark.parametrize("comment", ["..", "//", "@-", "this is a comment:"])
  27. def test_comment_multiple_chars(comment):
  28. content = "# IGNORE\n1.5, 2.5# ABC\n3.0,4.0# XXX\n5.5,6.0\n"
  29. txt = StringIO(content.replace("#", comment))
  30. a = np.loadtxt(txt, delimiter=",", comments=comment)
  31. assert_equal(a, [[1.5, 2.5], [3.0, 4.0], [5.5, 6.0]])
  32. @pytest.fixture
  33. def mixed_types_structured():
  34. """
  35. Fixture providing heterogeneous input data with a structured dtype, along
  36. with the associated structured array.
  37. """
  38. data = StringIO(
  39. "1000;2.4;alpha;-34\n"
  40. "2000;3.1;beta;29\n"
  41. "3500;9.9;gamma;120\n"
  42. "4090;8.1;delta;0\n"
  43. "5001;4.4;epsilon;-99\n"
  44. "6543;7.8;omega;-1\n"
  45. )
  46. dtype = np.dtype(
  47. [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
  48. )
  49. expected = np.array(
  50. [
  51. (1000, 2.4, "alpha", -34),
  52. (2000, 3.1, "beta", 29),
  53. (3500, 9.9, "gamma", 120),
  54. (4090, 8.1, "delta", 0),
  55. (5001, 4.4, "epsilon", -99),
  56. (6543, 7.8, "omega", -1)
  57. ],
  58. dtype=dtype
  59. )
  60. return data, dtype, expected
  61. @pytest.mark.parametrize('skiprows', [0, 1, 2, 3])
  62. def test_structured_dtype_and_skiprows_no_empty_lines(
  63. skiprows, mixed_types_structured):
  64. data, dtype, expected = mixed_types_structured
  65. a = np.loadtxt(data, dtype=dtype, delimiter=";", skiprows=skiprows)
  66. assert_array_equal(a, expected[skiprows:])
  67. def test_unpack_structured(mixed_types_structured):
  68. data, dtype, expected = mixed_types_structured
  69. a, b, c, d = np.loadtxt(data, dtype=dtype, delimiter=";", unpack=True)
  70. assert_array_equal(a, expected["f0"])
  71. assert_array_equal(b, expected["f1"])
  72. assert_array_equal(c, expected["f2"])
  73. assert_array_equal(d, expected["f3"])
  74. def test_structured_dtype_with_shape():
  75. dtype = np.dtype([("a", "u1", 2), ("b", "u1", 2)])
  76. data = StringIO("0,1,2,3\n6,7,8,9\n")
  77. expected = np.array([((0, 1), (2, 3)), ((6, 7), (8, 9))], dtype=dtype)
  78. assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dtype), expected)
  79. def test_structured_dtype_with_multi_shape():
  80. dtype = np.dtype([("a", "u1", (2, 2))])
  81. data = StringIO("0 1 2 3\n")
  82. expected = np.array([(((0, 1), (2, 3)),)], dtype=dtype)
  83. assert_array_equal(np.loadtxt(data, dtype=dtype), expected)
  84. def test_nested_structured_subarray():
  85. # Test from gh-16678
  86. point = np.dtype([('x', float), ('y', float)])
  87. dt = np.dtype([('code', int), ('points', point, (2,))])
  88. data = StringIO("100,1,2,3,4\n200,5,6,7,8\n")
  89. expected = np.array(
  90. [
  91. (100, [(1., 2.), (3., 4.)]),
  92. (200, [(5., 6.), (7., 8.)]),
  93. ],
  94. dtype=dt
  95. )
  96. assert_array_equal(np.loadtxt(data, dtype=dt, delimiter=","), expected)
  97. def test_structured_dtype_offsets():
  98. # An aligned structured dtype will have additional padding
  99. dt = np.dtype("i1, i4, i1, i4, i1, i4", align=True)
  100. data = StringIO("1,2,3,4,5,6\n7,8,9,10,11,12\n")
  101. expected = np.array([(1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12)], dtype=dt)
  102. assert_array_equal(np.loadtxt(data, delimiter=",", dtype=dt), expected)
  103. @pytest.mark.parametrize("param", ("skiprows", "max_rows"))
  104. def test_exception_negative_row_limits(param):
  105. """skiprows and max_rows should raise for negative parameters."""
  106. with pytest.raises(ValueError, match="argument must be nonnegative"):
  107. np.loadtxt("foo.bar", **{param: -3})
  108. @pytest.mark.parametrize("param", ("skiprows", "max_rows"))
  109. def test_exception_noninteger_row_limits(param):
  110. with pytest.raises(TypeError, match="argument must be an integer"):
  111. np.loadtxt("foo.bar", **{param: 1.0})
  112. @pytest.mark.parametrize(
  113. "data, shape",
  114. [
  115. ("1 2 3 4 5\n", (1, 5)), # Single row
  116. ("1\n2\n3\n4\n5\n", (5, 1)), # Single column
  117. ]
  118. )
  119. def test_ndmin_single_row_or_col(data, shape):
  120. arr = np.array([1, 2, 3, 4, 5])
  121. arr2d = arr.reshape(shape)
  122. assert_array_equal(np.loadtxt(StringIO(data), dtype=int), arr)
  123. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=0), arr)
  124. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=1), arr)
  125. assert_array_equal(np.loadtxt(StringIO(data), dtype=int, ndmin=2), arr2d)
  126. @pytest.mark.parametrize("badval", [-1, 3, None, "plate of shrimp"])
  127. def test_bad_ndmin(badval):
  128. with pytest.raises(ValueError, match="Illegal value of ndmin keyword"):
  129. np.loadtxt("foo.bar", ndmin=badval)
  130. @pytest.mark.parametrize(
  131. "ws",
  132. (
  133. " ", # space
  134. "\t", # tab
  135. "\u2003", # em
  136. "\u00A0", # non-break
  137. "\u3000", # ideographic space
  138. )
  139. )
  140. def test_blank_lines_spaces_delimit(ws):
  141. txt = StringIO(
  142. f"1 2{ws}30\n\n{ws}\n"
  143. f"4 5 60{ws}\n {ws} \n"
  144. f"7 8 {ws} 90\n # comment\n"
  145. f"3 2 1"
  146. )
  147. # NOTE: It is unclear that the ` # comment` should succeed. Except
  148. # for delimiter=None, which should use any whitespace (and maybe
  149. # should just be implemented closer to Python
  150. expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
  151. assert_equal(
  152. np.loadtxt(txt, dtype=int, delimiter=None, comments="#"), expected
  153. )
  154. def test_blank_lines_normal_delimiter():
  155. txt = StringIO('1,2,30\n\n4,5,60\n\n7,8,90\n# comment\n3,2,1')
  156. expected = np.array([[1, 2, 30], [4, 5, 60], [7, 8, 90], [3, 2, 1]])
  157. assert_equal(
  158. np.loadtxt(txt, dtype=int, delimiter=',', comments="#"), expected
  159. )
  160. @pytest.mark.parametrize("dtype", (float, object))
  161. def test_maxrows_no_blank_lines(dtype):
  162. txt = StringIO("1.5,2.5\n3.0,4.0\n5.5,6.0")
  163. res = np.loadtxt(txt, dtype=dtype, delimiter=",", max_rows=2)
  164. assert_equal(res.dtype, dtype)
  165. assert_equal(res, np.array([["1.5", "2.5"], ["3.0", "4.0"]], dtype=dtype))
  166. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  167. reason="PyPy bug in error formatting")
  168. @pytest.mark.parametrize("dtype", (np.dtype("f8"), np.dtype("i2")))
  169. def test_exception_message_bad_values(dtype):
  170. txt = StringIO("1,2\n3,XXX\n5,6")
  171. msg = f"could not convert string 'XXX' to {dtype} at row 1, column 2"
  172. with pytest.raises(ValueError, match=msg):
  173. np.loadtxt(txt, dtype=dtype, delimiter=",")
  174. def test_converters_negative_indices():
  175. txt = StringIO('1.5,2.5\n3.0,XXX\n5.5,6.0')
  176. conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
  177. expected = np.array([[1.5, 2.5], [3.0, np.nan], [5.5, 6.0]])
  178. res = np.loadtxt(txt, dtype=np.float64, delimiter=",", converters=conv)
  179. assert_equal(res, expected)
  180. def test_converters_negative_indices_with_usecols():
  181. txt = StringIO('1.5,2.5,3.5\n3.0,4.0,XXX\n5.5,6.0,7.5\n')
  182. conv = {-1: lambda s: np.nan if s == 'XXX' else float(s)}
  183. expected = np.array([[1.5, 3.5], [3.0, np.nan], [5.5, 7.5]])
  184. res = np.loadtxt(
  185. txt,
  186. dtype=np.float64,
  187. delimiter=",",
  188. converters=conv,
  189. usecols=[0, -1],
  190. )
  191. assert_equal(res, expected)
  192. # Second test with variable number of rows:
  193. res = np.loadtxt(StringIO('''0,1,2\n0,1,2,3,4'''), delimiter=",",
  194. usecols=[0, -1], converters={-1: (lambda x: -1)})
  195. assert_array_equal(res, [[0, -1], [0, -1]])
  196. def test_ragged_error():
  197. rows = ["1,2,3", "1,2,3", "4,3,2,1"]
  198. with pytest.raises(ValueError,
  199. match="the number of columns changed from 3 to 4 at row 3"):
  200. np.loadtxt(rows, delimiter=",")
  201. def test_ragged_usecols():
  202. # usecols, and negative ones, work even with varying number of columns.
  203. txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
  204. expected = np.array([[0, 0], [0, 0], [0, 0]])
  205. res = np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
  206. assert_equal(res, expected)
  207. txt = StringIO("0,0,XXX\n0\n0,XXX,XXX,0,XXX\n")
  208. with pytest.raises(ValueError,
  209. match="invalid column index -2 at row 2 with 1 columns"):
  210. # There is no -2 column in the second row:
  211. np.loadtxt(txt, dtype=float, delimiter=",", usecols=[0, -2])
  212. def test_empty_usecols():
  213. txt = StringIO("0,0,XXX\n0,XXX,0,XXX\n0,XXX,XXX,0,XXX\n")
  214. res = np.loadtxt(txt, dtype=np.dtype([]), delimiter=",", usecols=[])
  215. assert res.shape == (3,)
  216. assert res.dtype == np.dtype([])
  217. @pytest.mark.parametrize("c1", ["a", "の", "🫕"])
  218. @pytest.mark.parametrize("c2", ["a", "の", "🫕"])
  219. def test_large_unicode_characters(c1, c2):
  220. # c1 and c2 span ascii, 16bit and 32bit range.
  221. txt = StringIO(f"a,{c1},c,1.0\ne,{c2},2.0,g")
  222. res = np.loadtxt(txt, dtype=np.dtype('U12'), delimiter=",")
  223. expected = np.array(
  224. [f"a,{c1},c,1.0".split(","), f"e,{c2},2.0,g".split(",")],
  225. dtype=np.dtype('U12')
  226. )
  227. assert_equal(res, expected)
  228. def test_unicode_with_converter():
  229. txt = StringIO("cat,dog\nαβγ,δεζ\nabc,def\n")
  230. conv = {0: lambda s: s.upper()}
  231. res = np.loadtxt(
  232. txt,
  233. dtype=np.dtype("U12"),
  234. converters=conv,
  235. delimiter=",",
  236. encoding=None
  237. )
  238. expected = np.array([['CAT', 'dog'], ['ΑΒΓ', 'δεζ'], ['ABC', 'def']])
  239. assert_equal(res, expected)
  240. def test_converter_with_structured_dtype():
  241. txt = StringIO('1.5,2.5,Abc\n3.0,4.0,dEf\n5.5,6.0,ghI\n')
  242. dt = np.dtype([('m', np.int32), ('r', np.float32), ('code', 'U8')])
  243. conv = {0: lambda s: int(10*float(s)), -1: lambda s: s.upper()}
  244. res = np.loadtxt(txt, dtype=dt, delimiter=",", converters=conv)
  245. expected = np.array(
  246. [(15, 2.5, 'ABC'), (30, 4.0, 'DEF'), (55, 6.0, 'GHI')], dtype=dt
  247. )
  248. assert_equal(res, expected)
  249. def test_converter_with_unicode_dtype():
  250. """
  251. With the 'bytes' encoding, tokens are encoded prior to being
  252. passed to the converter. This means that the output of the converter may
  253. be bytes instead of unicode as expected by `read_rows`.
  254. This test checks that outputs from the above scenario are properly decoded
  255. prior to parsing by `read_rows`.
  256. """
  257. txt = StringIO('abc,def\nrst,xyz')
  258. conv = bytes.upper
  259. res = np.loadtxt(
  260. txt, dtype=np.dtype("U3"), converters=conv, delimiter=",",
  261. encoding="bytes")
  262. expected = np.array([['ABC', 'DEF'], ['RST', 'XYZ']])
  263. assert_equal(res, expected)
  264. def test_read_huge_row():
  265. row = "1.5, 2.5," * 50000
  266. row = row[:-1] + "\n"
  267. txt = StringIO(row * 2)
  268. res = np.loadtxt(txt, delimiter=",", dtype=float)
  269. assert_equal(res, np.tile([1.5, 2.5], (2, 50000)))
  270. @pytest.mark.parametrize("dtype", "edfgFDG")
  271. def test_huge_float(dtype):
  272. # Covers a non-optimized path that is rarely taken:
  273. field = "0" * 1000 + ".123456789"
  274. dtype = np.dtype(dtype)
  275. value = np.loadtxt([field], dtype=dtype)[()]
  276. assert value == dtype.type("0.123456789")
  277. @pytest.mark.parametrize(
  278. ("given_dtype", "expected_dtype"),
  279. [
  280. ("S", np.dtype("S5")),
  281. ("U", np.dtype("U5")),
  282. ],
  283. )
  284. def test_string_no_length_given(given_dtype, expected_dtype):
  285. """
  286. The given dtype is just 'S' or 'U' with no length. In these cases, the
  287. length of the resulting dtype is determined by the longest string found
  288. in the file.
  289. """
  290. txt = StringIO("AAA,5-1\nBBBBB,0-3\nC,4-9\n")
  291. res = np.loadtxt(txt, dtype=given_dtype, delimiter=",")
  292. expected = np.array(
  293. [['AAA', '5-1'], ['BBBBB', '0-3'], ['C', '4-9']], dtype=expected_dtype
  294. )
  295. assert_equal(res, expected)
  296. assert_equal(res.dtype, expected_dtype)
  297. def test_float_conversion():
  298. """
  299. Some tests that the conversion to float64 works as accurately as the
  300. Python built-in `float` function. In a naive version of the float parser,
  301. these strings resulted in values that were off by an ULP or two.
  302. """
  303. strings = [
  304. '0.9999999999999999',
  305. '9876543210.123456',
  306. '5.43215432154321e+300',
  307. '0.901',
  308. '0.333',
  309. ]
  310. txt = StringIO('\n'.join(strings))
  311. res = np.loadtxt(txt)
  312. expected = np.array([float(s) for s in strings])
  313. assert_equal(res, expected)
  314. def test_bool():
  315. # Simple test for bool via integer
  316. txt = StringIO("1, 0\n10, -1")
  317. res = np.loadtxt(txt, dtype=bool, delimiter=",")
  318. assert res.dtype == bool
  319. assert_array_equal(res, [[True, False], [True, True]])
  320. # Make sure we use only 1 and 0 on the byte level:
  321. assert_array_equal(res.view(np.uint8), [[1, 0], [1, 1]])
  322. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  323. reason="PyPy bug in error formatting")
  324. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  325. @pytest.mark.filterwarnings("error:.*integer via a float.*:DeprecationWarning")
  326. def test_integer_signs(dtype):
  327. dtype = np.dtype(dtype)
  328. assert np.loadtxt(["+2"], dtype=dtype) == 2
  329. if dtype.kind == "u":
  330. with pytest.raises(ValueError):
  331. np.loadtxt(["-1\n"], dtype=dtype)
  332. else:
  333. assert np.loadtxt(["-2\n"], dtype=dtype) == -2
  334. for sign in ["++", "+-", "--", "-+"]:
  335. with pytest.raises(ValueError):
  336. np.loadtxt([f"{sign}2\n"], dtype=dtype)
  337. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  338. reason="PyPy bug in error formatting")
  339. @pytest.mark.parametrize("dtype", np.typecodes["AllInteger"])
  340. @pytest.mark.filterwarnings("error:.*integer via a float.*:DeprecationWarning")
  341. def test_implicit_cast_float_to_int_fails(dtype):
  342. txt = StringIO("1.0, 2.1, 3.7\n4, 5, 6")
  343. with pytest.raises(ValueError):
  344. np.loadtxt(txt, dtype=dtype, delimiter=",")
  345. @pytest.mark.parametrize("dtype", (np.complex64, np.complex128))
  346. @pytest.mark.parametrize("with_parens", (False, True))
  347. def test_complex_parsing(dtype, with_parens):
  348. s = "(1.0-2.5j),3.75,(7+-5.0j)\n(4),(-19e2j),(0)"
  349. if not with_parens:
  350. s = s.replace("(", "").replace(")", "")
  351. res = np.loadtxt(StringIO(s), dtype=dtype, delimiter=",")
  352. expected = np.array(
  353. [[1.0-2.5j, 3.75, 7-5j], [4.0, -1900j, 0]], dtype=dtype
  354. )
  355. assert_equal(res, expected)
  356. def test_read_from_generator():
  357. def gen():
  358. for i in range(4):
  359. yield f"{i},{2*i},{i**2}"
  360. res = np.loadtxt(gen(), dtype=int, delimiter=",")
  361. expected = np.array([[0, 0, 0], [1, 2, 1], [2, 4, 4], [3, 6, 9]])
  362. assert_equal(res, expected)
  363. def test_read_from_generator_multitype():
  364. def gen():
  365. for i in range(3):
  366. yield f"{i} {i / 4}"
  367. res = np.loadtxt(gen(), dtype="i, d", delimiter=" ")
  368. expected = np.array([(0, 0.0), (1, 0.25), (2, 0.5)], dtype="i, d")
  369. assert_equal(res, expected)
  370. def test_read_from_bad_generator():
  371. def gen():
  372. yield from ["1,2", b"3, 5", 12738]
  373. with pytest.raises(
  374. TypeError, match=r"non-string returned while reading data"):
  375. np.loadtxt(gen(), dtype="i, i", delimiter=",")
  376. @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
  377. def test_object_cleanup_on_read_error():
  378. sentinel = object()
  379. already_read = 0
  380. def conv(x):
  381. nonlocal already_read
  382. if already_read > 4999:
  383. raise ValueError("failed half-way through!")
  384. already_read += 1
  385. return sentinel
  386. txt = StringIO("x\n" * 10000)
  387. with pytest.raises(ValueError, match="at row 5000, column 1"):
  388. np.loadtxt(txt, dtype=object, converters={0: conv})
  389. assert sys.getrefcount(sentinel) == 2
  390. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  391. reason="PyPy bug in error formatting")
  392. def test_character_not_bytes_compatible():
  393. """Test exception when a character cannot be encoded as 'S'."""
  394. data = StringIO("–") # == \u2013
  395. with pytest.raises(ValueError):
  396. np.loadtxt(data, dtype="S5")
  397. @pytest.mark.parametrize("conv", (0, [float], ""))
  398. def test_invalid_converter(conv):
  399. msg = (
  400. "converters must be a dictionary mapping columns to converter "
  401. "functions or a single callable."
  402. )
  403. with pytest.raises(TypeError, match=msg):
  404. np.loadtxt(StringIO("1 2\n3 4"), converters=conv)
  405. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  406. reason="PyPy bug in error formatting")
  407. def test_converters_dict_raises_non_integer_key():
  408. with pytest.raises(TypeError, match="keys of the converters dict"):
  409. np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int})
  410. with pytest.raises(TypeError, match="keys of the converters dict"):
  411. np.loadtxt(StringIO("1 2\n3 4"), converters={"a": int}, usecols=0)
  412. @pytest.mark.parametrize("bad_col_ind", (3, -3))
  413. def test_converters_dict_raises_non_col_key(bad_col_ind):
  414. data = StringIO("1 2\n3 4")
  415. with pytest.raises(ValueError, match="converter specified for column"):
  416. np.loadtxt(data, converters={bad_col_ind: int})
  417. def test_converters_dict_raises_val_not_callable():
  418. with pytest.raises(TypeError,
  419. match="values of the converters dictionary must be callable"):
  420. np.loadtxt(StringIO("1 2\n3 4"), converters={0: 1})
  421. @pytest.mark.parametrize("q", ('"', "'", "`"))
  422. def test_quoted_field(q):
  423. txt = StringIO(
  424. f"{q}alpha, x{q}, 2.5\n{q}beta, y{q}, 4.5\n{q}gamma, z{q}, 5.0\n"
  425. )
  426. dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
  427. expected = np.array(
  428. [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
  429. )
  430. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar=q)
  431. assert_array_equal(res, expected)
  432. @pytest.mark.parametrize("q", ('"', "'", "`"))
  433. def test_quoted_field_with_whitepace_delimiter(q):
  434. txt = StringIO(
  435. f"{q}alpha, x{q} 2.5\n{q}beta, y{q} 4.5\n{q}gamma, z{q} 5.0\n"
  436. )
  437. dtype = np.dtype([('f0', 'U8'), ('f1', np.float64)])
  438. expected = np.array(
  439. [("alpha, x", 2.5), ("beta, y", 4.5), ("gamma, z", 5.0)], dtype=dtype
  440. )
  441. res = np.loadtxt(txt, dtype=dtype, delimiter=None, quotechar=q)
  442. assert_array_equal(res, expected)
  443. def test_quote_support_default():
  444. """Support for quoted fields is disabled by default."""
  445. txt = StringIO('"lat,long", 45, 30\n')
  446. dtype = np.dtype([('f0', 'U24'), ('f1', np.float64), ('f2', np.float64)])
  447. with pytest.raises(ValueError,
  448. match="the dtype passed requires 3 columns but 4 were"):
  449. np.loadtxt(txt, dtype=dtype, delimiter=",")
  450. # Enable quoting support with non-None value for quotechar param
  451. txt.seek(0)
  452. expected = np.array([("lat,long", 45., 30.)], dtype=dtype)
  453. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
  454. assert_array_equal(res, expected)
  455. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  456. reason="PyPy bug in error formatting")
  457. def test_quotechar_multichar_error():
  458. txt = StringIO("1,2\n3,4")
  459. msg = r".*must be a single unicode character or None"
  460. with pytest.raises(TypeError, match=msg):
  461. np.loadtxt(txt, delimiter=",", quotechar="''")
  462. def test_comment_multichar_error_with_quote():
  463. txt = StringIO("1,2\n3,4")
  464. msg = (
  465. "when multiple comments or a multi-character comment is given, "
  466. "quotes are not supported."
  467. )
  468. with pytest.raises(ValueError, match=msg):
  469. np.loadtxt(txt, delimiter=",", comments="123", quotechar='"')
  470. with pytest.raises(ValueError, match=msg):
  471. np.loadtxt(txt, delimiter=",", comments=["#", "%"], quotechar='"')
  472. # A single character string in a tuple is unpacked though:
  473. res = np.loadtxt(txt, delimiter=",", comments=("#",), quotechar="'")
  474. assert_equal(res, [[1, 2], [3, 4]])
  475. def test_structured_dtype_with_quotes():
  476. data = StringIO(
  477. "1000;2.4;'alpha';-34\n"
  478. "2000;3.1;'beta';29\n"
  479. "3500;9.9;'gamma';120\n"
  480. "4090;8.1;'delta';0\n"
  481. "5001;4.4;'epsilon';-99\n"
  482. "6543;7.8;'omega';-1\n"
  483. )
  484. dtype = np.dtype(
  485. [('f0', np.uint16), ('f1', np.float64), ('f2', 'S7'), ('f3', np.int8)]
  486. )
  487. expected = np.array(
  488. [
  489. (1000, 2.4, "alpha", -34),
  490. (2000, 3.1, "beta", 29),
  491. (3500, 9.9, "gamma", 120),
  492. (4090, 8.1, "delta", 0),
  493. (5001, 4.4, "epsilon", -99),
  494. (6543, 7.8, "omega", -1)
  495. ],
  496. dtype=dtype
  497. )
  498. res = np.loadtxt(data, dtype=dtype, delimiter=";", quotechar="'")
  499. assert_array_equal(res, expected)
  500. def test_quoted_field_is_not_empty():
  501. txt = StringIO('1\n\n"4"\n""')
  502. expected = np.array(["1", "4", ""], dtype="U1")
  503. res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
  504. assert_equal(res, expected)
  505. def test_quoted_field_is_not_empty_nonstrict():
  506. # Same as test_quoted_field_is_not_empty but check that we are not strict
  507. # about missing closing quote (this is the `csv.reader` default also)
  508. txt = StringIO('1\n\n"4"\n"')
  509. expected = np.array(["1", "4", ""], dtype="U1")
  510. res = np.loadtxt(txt, delimiter=",", dtype="U1", quotechar='"')
  511. assert_equal(res, expected)
  512. def test_consecutive_quotechar_escaped():
  513. txt = StringIO('"Hello, my name is ""Monty""!"')
  514. expected = np.array('Hello, my name is "Monty"!', dtype="U40")
  515. res = np.loadtxt(txt, dtype="U40", delimiter=",", quotechar='"')
  516. assert_equal(res, expected)
  517. @pytest.mark.parametrize("data", ("", "\n\n\n", "# 1 2 3\n# 4 5 6\n"))
  518. @pytest.mark.parametrize("ndmin", (0, 1, 2))
  519. @pytest.mark.parametrize("usecols", [None, (1, 2, 3)])
  520. def test_warn_on_no_data(data, ndmin, usecols):
  521. """Check that a UserWarning is emitted when no data is read from input."""
  522. if usecols is not None:
  523. expected_shape = (0, 3)
  524. elif ndmin == 2:
  525. expected_shape = (0, 1) # guess a single column?!
  526. else:
  527. expected_shape = (0,)
  528. txt = StringIO(data)
  529. with pytest.warns(UserWarning, match="input contained no data"):
  530. res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
  531. assert res.shape == expected_shape
  532. with NamedTemporaryFile(mode="w") as fh:
  533. fh.write(data)
  534. fh.seek(0)
  535. with pytest.warns(UserWarning, match="input contained no data"):
  536. res = np.loadtxt(txt, ndmin=ndmin, usecols=usecols)
  537. assert res.shape == expected_shape
  538. @pytest.mark.parametrize("skiprows", (2, 3))
  539. def test_warn_on_skipped_data(skiprows):
  540. data = "1 2 3\n4 5 6"
  541. txt = StringIO(data)
  542. with pytest.warns(UserWarning, match="input contained no data"):
  543. np.loadtxt(txt, skiprows=skiprows)
  544. @pytest.mark.parametrize(["dtype", "value"], [
  545. ("i2", 0x0001), ("u2", 0x0001),
  546. ("i4", 0x00010203), ("u4", 0x00010203),
  547. ("i8", 0x0001020304050607), ("u8", 0x0001020304050607),
  548. # The following values are constructed to lead to unique bytes:
  549. ("float16", 3.07e-05),
  550. ("float32", 9.2557e-41), ("complex64", 9.2557e-41+2.8622554e-29j),
  551. ("float64", -1.758571353180402e-24),
  552. # Here and below, the repr side-steps a small loss of precision in
  553. # complex `str` in PyPy (which is probably fine, as repr works):
  554. ("complex128", repr(5.406409232372729e-29-1.758571353180402e-24j)),
  555. # Use integer values that fit into double. Everything else leads to
  556. # problems due to longdoubles going via double and decimal strings
  557. # causing rounding errors.
  558. ("longdouble", 0x01020304050607),
  559. ("clongdouble", repr(0x01020304050607 + (0x00121314151617 * 1j))),
  560. ("U2", "\U00010203\U000a0b0c")])
  561. @pytest.mark.parametrize("swap", [True, False])
  562. def test_byteswapping_and_unaligned(dtype, value, swap):
  563. # Try to create "interesting" values within the valid unicode range:
  564. dtype = np.dtype(dtype)
  565. data = [f"x,{value}\n"] # repr as PyPy `str` truncates some
  566. if swap:
  567. dtype = dtype.newbyteorder()
  568. full_dt = np.dtype([("a", "S1"), ("b", dtype)], align=False)
  569. # The above ensures that the interesting "b" field is unaligned:
  570. assert full_dt.fields["b"][1] == 1
  571. res = np.loadtxt(data, dtype=full_dt, delimiter=",",
  572. max_rows=1) # max-rows prevents over-allocation
  573. assert res["b"] == dtype.type(value)
  574. @pytest.mark.parametrize("dtype",
  575. np.typecodes["AllInteger"] + "efdFD" + "?")
  576. def test_unicode_whitespace_stripping(dtype):
  577. # Test that all numeric types (and bool) strip whitespace correctly
  578. # \u202F is a narrow no-break space, `\n` is just a whitespace if quoted.
  579. # Currently, skip float128 as it did not always support this and has no
  580. # "custom" parsing:
  581. txt = StringIO(' 3 ,"\u202F2\n"')
  582. res = np.loadtxt(txt, dtype=dtype, delimiter=",", quotechar='"')
  583. assert_array_equal(res, np.array([3, 2]).astype(dtype))
  584. @pytest.mark.parametrize("dtype", "FD")
  585. def test_unicode_whitespace_stripping_complex(dtype):
  586. # Complex has a few extra cases since it has two components and
  587. # parentheses
  588. line = " 1 , 2+3j , ( 4+5j ), ( 6+-7j ) , 8j , ( 9j ) \n"
  589. data = [line, line.replace(" ", "\u202F")]
  590. res = np.loadtxt(data, dtype=dtype, delimiter=',')
  591. assert_array_equal(res, np.array([[1, 2+3j, 4+5j, 6-7j, 8j, 9j]] * 2))
  592. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  593. reason="PyPy bug in error formatting")
  594. @pytest.mark.parametrize("dtype", "FD")
  595. @pytest.mark.parametrize("field",
  596. ["1 +2j", "1+ 2j", "1+2 j", "1+-+3", "(1j", "(1", "(1+2j", "1+2j)"])
  597. def test_bad_complex(dtype, field):
  598. with pytest.raises(ValueError):
  599. np.loadtxt([field + "\n"], dtype=dtype, delimiter=",")
  600. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  601. reason="PyPy bug in error formatting")
  602. @pytest.mark.parametrize("dtype",
  603. np.typecodes["AllInteger"] + "efgdFDG" + "?")
  604. def test_nul_character_error(dtype):
  605. # Test that a \0 character is correctly recognized as an error even if
  606. # what comes before is valid (not everything gets parsed internally).
  607. if dtype.lower() == "g":
  608. pytest.xfail("longdouble/clongdouble assignment may misbehave.")
  609. with pytest.raises(ValueError):
  610. np.loadtxt(["1\000"], dtype=dtype, delimiter=",", quotechar='"')
  611. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  612. reason="PyPy bug in error formatting")
  613. @pytest.mark.parametrize("dtype",
  614. np.typecodes["AllInteger"] + "efgdFDG" + "?")
  615. def test_no_thousands_support(dtype):
  616. # Mainly to document behaviour, Python supports thousands like 1_1.
  617. # (e and G may end up using different conversion and support it, this is
  618. # a bug but happens...)
  619. if dtype == "e":
  620. pytest.skip("half assignment currently uses Python float converter")
  621. if dtype in "eG":
  622. pytest.xfail("clongdouble assignment is buggy (uses `complex`?).")
  623. assert int("1_1") == float("1_1") == complex("1_1") == 11
  624. with pytest.raises(ValueError):
  625. np.loadtxt(["1_1\n"], dtype=dtype)
  626. @pytest.mark.parametrize("data", [
  627. ["1,2\n", "2\n,3\n"],
  628. ["1,2\n", "2\r,3\n"]])
  629. def test_bad_newline_in_iterator(data):
  630. # In NumPy <=1.22 this was accepted, because newlines were completely
  631. # ignored when the input was an iterable. This could be changed, but right
  632. # now, we raise an error.
  633. msg = "Found an unquoted embedded newline within a single line"
  634. with pytest.raises(ValueError, match=msg):
  635. np.loadtxt(data, delimiter=",")
  636. @pytest.mark.parametrize("data", [
  637. ["1,2\n", "2,3\r\n"], # a universal newline
  638. ["1,2\n", "'2\n',3\n"], # a quoted newline
  639. ["1,2\n", "'2\r',3\n"],
  640. ["1,2\n", "'2\r\n',3\n"],
  641. ])
  642. def test_good_newline_in_iterator(data):
  643. # The quoted newlines will be untransformed here, but are just whitespace.
  644. res = np.loadtxt(data, delimiter=",", quotechar="'")
  645. assert_array_equal(res, [[1., 2.], [2., 3.]])
  646. @pytest.mark.parametrize("newline", ["\n", "\r", "\r\n"])
  647. def test_universal_newlines_quoted(newline):
  648. # Check that universal newline support within the tokenizer is not applied
  649. # to quoted fields. (note that lines must end in newline or quoted
  650. # fields will not include a newline at all)
  651. data = ['1,"2\n"\n', '3,"4\n', '1"\n']
  652. data = [row.replace("\n", newline) for row in data]
  653. res = np.loadtxt(data, dtype=object, delimiter=",", quotechar='"')
  654. assert_array_equal(res, [['1', f'2{newline}'], ['3', f'4{newline}1']])
  655. def test_null_character():
  656. # Basic tests to check that the NUL character is not special:
  657. res = np.loadtxt(["1\0002\0003\n", "4\0005\0006"], delimiter="\000")
  658. assert_array_equal(res, [[1, 2, 3], [4, 5, 6]])
  659. # Also not as part of a field (avoid unicode/arrays as unicode strips \0)
  660. res = np.loadtxt(["1\000,2\000,3\n", "4\000,5\000,6"],
  661. delimiter=",", dtype=object)
  662. assert res.tolist() == [["1\000", "2\000", "3"], ["4\000", "5\000", "6"]]
  663. def test_iterator_fails_getting_next_line():
  664. class BadSequence:
  665. def __len__(self):
  666. return 100
  667. def __getitem__(self, item):
  668. if item == 50:
  669. raise RuntimeError("Bad things happened!")
  670. return f"{item}, {item+1}"
  671. with pytest.raises(RuntimeError, match="Bad things happened!"):
  672. np.loadtxt(BadSequence(), dtype=int, delimiter=",")
  673. class TestCReaderUnitTests:
  674. # These are internal tests for path that should not be possible to hit
  675. # unless things go very very wrong somewhere.
  676. def test_not_an_filelike(self):
  677. with pytest.raises(AttributeError, match=".*read"):
  678. np._core._multiarray_umath._load_from_filelike(
  679. object(), dtype=np.dtype("i"), filelike=True)
  680. def test_filelike_read_fails(self):
  681. # Can only be reached if loadtxt opens the file, so it is hard to do
  682. # via the public interface (although maybe not impossible considering
  683. # the current "DataClass" backing).
  684. class BadFileLike:
  685. counter = 0
  686. def read(self, size):
  687. self.counter += 1
  688. if self.counter > 20:
  689. raise RuntimeError("Bad bad bad!")
  690. return "1,2,3\n"
  691. with pytest.raises(RuntimeError, match="Bad bad bad!"):
  692. np._core._multiarray_umath._load_from_filelike(
  693. BadFileLike(), dtype=np.dtype("i"), filelike=True)
  694. def test_filelike_bad_read(self):
  695. # Can only be reached if loadtxt opens the file, so it is hard to do
  696. # via the public interface (although maybe not impossible considering
  697. # the current "DataClass" backing).
  698. class BadFileLike:
  699. counter = 0
  700. def read(self, size):
  701. return 1234 # not a string!
  702. with pytest.raises(TypeError,
  703. match="non-string returned while reading data"):
  704. np._core._multiarray_umath._load_from_filelike(
  705. BadFileLike(), dtype=np.dtype("i"), filelike=True)
  706. def test_not_an_iter(self):
  707. with pytest.raises(TypeError,
  708. match="error reading from object, expected an iterable"):
  709. np._core._multiarray_umath._load_from_filelike(
  710. object(), dtype=np.dtype("i"), filelike=False)
  711. def test_bad_type(self):
  712. with pytest.raises(TypeError, match="internal error: dtype must"):
  713. np._core._multiarray_umath._load_from_filelike(
  714. object(), dtype="i", filelike=False)
  715. def test_bad_encoding(self):
  716. with pytest.raises(TypeError, match="encoding must be a unicode"):
  717. np._core._multiarray_umath._load_from_filelike(
  718. object(), dtype=np.dtype("i"), filelike=False, encoding=123)
  719. @pytest.mark.parametrize("newline", ["\r", "\n", "\r\n"])
  720. def test_manual_universal_newlines(self, newline):
  721. # This is currently not available to users, because we should always
  722. # open files with universal newlines enabled `newlines=None`.
  723. # (And reading from an iterator uses slightly different code paths.)
  724. # We have no real support for `newline="\r"` or `newline="\n" as the
  725. # user cannot specify those options.
  726. data = StringIO('0\n1\n"2\n"\n3\n4 #\n'.replace("\n", newline),
  727. newline="")
  728. res = np._core._multiarray_umath._load_from_filelike(
  729. data, dtype=np.dtype("U10"), filelike=True,
  730. quote='"', comment="#", skiplines=1)
  731. assert_array_equal(res[:, 0], ["1", f"2{newline}", "3", "4 "])
  732. def test_delimiter_comment_collision_raises():
  733. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  734. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", comments=",")
  735. def test_delimiter_quotechar_collision_raises():
  736. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  737. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", quotechar=",")
  738. def test_comment_quotechar_collision_raises():
  739. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  740. np.loadtxt(StringIO("1 2 3"), comments="#", quotechar="#")
  741. def test_delimiter_and_multiple_comments_collision_raises():
  742. with pytest.raises(
  743. TypeError, match="Comment characters.*cannot include the delimiter"
  744. ):
  745. np.loadtxt(StringIO("1, 2, 3"), delimiter=",", comments=["#", ","])
  746. @pytest.mark.parametrize(
  747. "ws",
  748. (
  749. " ", # space
  750. "\t", # tab
  751. "\u2003", # em
  752. "\u00A0", # non-break
  753. "\u3000", # ideographic space
  754. )
  755. )
  756. def test_collision_with_default_delimiter_raises(ws):
  757. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  758. np.loadtxt(StringIO(f"1{ws}2{ws}3\n4{ws}5{ws}6\n"), comments=ws)
  759. with pytest.raises(TypeError, match=".*control characters.*incompatible"):
  760. np.loadtxt(StringIO(f"1{ws}2{ws}3\n4{ws}5{ws}6\n"), quotechar=ws)
  761. @pytest.mark.parametrize("nl", ("\n", "\r"))
  762. def test_control_character_newline_raises(nl):
  763. txt = StringIO(f"1{nl}2{nl}3{nl}{nl}4{nl}5{nl}6{nl}{nl}")
  764. msg = "control character.*cannot be a newline"
  765. with pytest.raises(TypeError, match=msg):
  766. np.loadtxt(txt, delimiter=nl)
  767. with pytest.raises(TypeError, match=msg):
  768. np.loadtxt(txt, comments=nl)
  769. with pytest.raises(TypeError, match=msg):
  770. np.loadtxt(txt, quotechar=nl)
  771. @pytest.mark.parametrize(
  772. ("generic_data", "long_datum", "unitless_dtype", "expected_dtype"),
  773. [
  774. ("2012-03", "2013-01-15", "M8", "M8[D]"), # Datetimes
  775. ("spam-a-lot", "tis_but_a_scratch", "U", "U17"), # str
  776. ],
  777. )
  778. @pytest.mark.parametrize("nrows", (10, 50000, 60000)) # lt, eq, gt chunksize
  779. def test_parametric_unit_discovery(
  780. generic_data, long_datum, unitless_dtype, expected_dtype, nrows
  781. ):
  782. """Check that the correct unit (e.g. month, day, second) is discovered from
  783. the data when a user specifies a unitless datetime."""
  784. # Unit should be "D" (days) due to last entry
  785. data = [generic_data] * nrows + [long_datum]
  786. expected = np.array(data, dtype=expected_dtype)
  787. assert len(data) == nrows+1
  788. assert len(data) == len(expected)
  789. # file-like path
  790. txt = StringIO("\n".join(data))
  791. a = np.loadtxt(txt, dtype=unitless_dtype)
  792. assert len(a) == len(expected)
  793. assert a.dtype == expected.dtype
  794. assert_equal(a, expected)
  795. # file-obj path
  796. fd, fname = mkstemp()
  797. os.close(fd)
  798. with open(fname, "w") as fh:
  799. fh.write("\n".join(data)+"\n")
  800. # loading the full file...
  801. a = np.loadtxt(fname, dtype=unitless_dtype)
  802. assert len(a) == len(expected)
  803. assert a.dtype == expected.dtype
  804. assert_equal(a, expected)
  805. # loading half of the file...
  806. a = np.loadtxt(fname, dtype=unitless_dtype, max_rows=int(nrows/2))
  807. os.remove(fname)
  808. assert len(a) == int(nrows/2)
  809. assert_equal(a, expected[:int(nrows/2)])
  810. def test_str_dtype_unit_discovery_with_converter():
  811. data = ["spam-a-lot"] * 60000 + ["XXXtis_but_a_scratch"]
  812. expected = np.array(
  813. ["spam-a-lot"] * 60000 + ["tis_but_a_scratch"], dtype="U17"
  814. )
  815. conv = lambda s: s.removeprefix("XXX")
  816. # file-like path
  817. txt = StringIO("\n".join(data))
  818. a = np.loadtxt(txt, dtype="U", converters=conv)
  819. assert a.dtype == expected.dtype
  820. assert_equal(a, expected)
  821. # file-obj path
  822. fd, fname = mkstemp()
  823. os.close(fd)
  824. with open(fname, "w") as fh:
  825. fh.write("\n".join(data))
  826. a = np.loadtxt(fname, dtype="U", converters=conv)
  827. os.remove(fname)
  828. assert a.dtype == expected.dtype
  829. assert_equal(a, expected)
  830. @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
  831. reason="PyPy bug in error formatting")
  832. def test_control_character_empty():
  833. with pytest.raises(TypeError, match="Text reading control character must"):
  834. np.loadtxt(StringIO("1 2 3"), delimiter="")
  835. with pytest.raises(TypeError, match="Text reading control character must"):
  836. np.loadtxt(StringIO("1 2 3"), quotechar="")
  837. with pytest.raises(ValueError, match="comments cannot be an empty string"):
  838. np.loadtxt(StringIO("1 2 3"), comments="")
  839. with pytest.raises(ValueError, match="comments cannot be an empty string"):
  840. np.loadtxt(StringIO("1 2 3"), comments=["#", ""])
  841. def test_control_characters_as_bytes():
  842. """Byte control characters (comments, delimiter) are supported."""
  843. a = np.loadtxt(StringIO("#header\n1,2,3"), comments=b"#", delimiter=b",")
  844. assert_equal(a, [1, 2, 3])
  845. @pytest.mark.filterwarnings('ignore::UserWarning')
  846. def test_field_growing_cases():
  847. # Test empty field appending/growing (each field still takes 1 character)
  848. # to see if the final field appending does not create issues.
  849. res = np.loadtxt([""], delimiter=",", dtype=bytes)
  850. assert len(res) == 0
  851. for i in range(1, 1024):
  852. res = np.loadtxt(["," * i], delimiter=",", dtype=bytes, max_rows=10)
  853. assert len(res) == i+1
  854. @pytest.mark.parametrize("nmax", (10000, 50000, 55000, 60000))
  855. def test_maxrows_exceeding_chunksize(nmax):
  856. # tries to read all of the file,
  857. # or less, equal, greater than _loadtxt_chunksize
  858. file_length = 60000
  859. # file-like path
  860. data = ["a 0.5 1"]*file_length
  861. txt = StringIO("\n".join(data))
  862. res = np.loadtxt(txt, dtype=str, delimiter=" ", max_rows=nmax)
  863. assert len(res) == nmax
  864. # file-obj path
  865. fd, fname = mkstemp()
  866. os.close(fd)
  867. with open(fname, "w") as fh:
  868. fh.write("\n".join(data))
  869. res = np.loadtxt(fname, dtype=str, delimiter=" ", max_rows=nmax)
  870. os.remove(fname)
  871. assert len(res) == nmax
  872. @pytest.mark.parametrize("nskip", (0, 10000, 12345, 50000, 67891, 100000))
  873. def test_skiprow_exceeding_maxrows_exceeding_chunksize(tmpdir, nskip):
  874. # tries to read a file in chunks by skipping a variable amount of lines,
  875. # less, equal, greater than max_rows
  876. file_length = 110000
  877. data = "\n".join(f"{i} a 0.5 1" for i in range(1, file_length + 1))
  878. expected_length = min(60000, file_length - nskip)
  879. expected = np.arange(nskip + 1, nskip + 1 + expected_length).astype(str)
  880. # file-like path
  881. txt = StringIO(data)
  882. res = np.loadtxt(txt, dtype='str', delimiter=" ", skiprows=nskip, max_rows=60000)
  883. assert len(res) == expected_length
  884. # are the right lines read in res?
  885. assert_array_equal(expected, res[:, 0])
  886. # file-obj path
  887. tmp_file = tmpdir / "test_data.txt"
  888. tmp_file.write(data)
  889. fname = str(tmp_file)
  890. res = np.loadtxt(fname, dtype='str', delimiter=" ", skiprows=nskip, max_rows=60000)
  891. assert len(res) == expected_length
  892. # are the right lines read in res?
  893. assert_array_equal(expected, res[:, 0])