test_quoting.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. """
  2. Tests that quoting specifications are properly handled
  3. during parsing for all of the parsers defined in parsers.py
  4. """
  5. import csv
  6. from io import StringIO
  7. import pytest
  8. from pandas.compat import PY311
  9. from pandas.errors import ParserError
  10. from pandas import DataFrame
  11. import pandas._testing as tm
  12. pytestmark = pytest.mark.usefixtures("pyarrow_skip")
  13. @pytest.mark.parametrize(
  14. "kwargs,msg",
  15. [
  16. ({"quotechar": "foo"}, '"quotechar" must be a(n)? 1-character string'),
  17. (
  18. {"quotechar": None, "quoting": csv.QUOTE_MINIMAL},
  19. "quotechar must be set if quoting enabled",
  20. ),
  21. ({"quotechar": 2}, '"quotechar" must be string( or None)?, not int'),
  22. ],
  23. )
  24. def test_bad_quote_char(all_parsers, kwargs, msg):
  25. data = "1,2,3"
  26. parser = all_parsers
  27. with pytest.raises(TypeError, match=msg):
  28. parser.read_csv(StringIO(data), **kwargs)
  29. @pytest.mark.parametrize(
  30. "quoting,msg",
  31. [
  32. ("foo", '"quoting" must be an integer|Argument'),
  33. (5, 'bad "quoting" value'), # quoting must be in the range [0, 3]
  34. ],
  35. )
  36. def test_bad_quoting(all_parsers, quoting, msg):
  37. data = "1,2,3"
  38. parser = all_parsers
  39. with pytest.raises(TypeError, match=msg):
  40. parser.read_csv(StringIO(data), quoting=quoting)
  41. def test_quote_char_basic(all_parsers):
  42. parser = all_parsers
  43. data = 'a,b,c\n1,2,"cat"'
  44. expected = DataFrame([[1, 2, "cat"]], columns=["a", "b", "c"])
  45. result = parser.read_csv(StringIO(data), quotechar='"')
  46. tm.assert_frame_equal(result, expected)
  47. @pytest.mark.parametrize("quote_char", ["~", "*", "%", "$", "@", "P"])
  48. def test_quote_char_various(all_parsers, quote_char):
  49. parser = all_parsers
  50. expected = DataFrame([[1, 2, "cat"]], columns=["a", "b", "c"])
  51. data = 'a,b,c\n1,2,"cat"'
  52. new_data = data.replace('"', quote_char)
  53. result = parser.read_csv(StringIO(new_data), quotechar=quote_char)
  54. tm.assert_frame_equal(result, expected)
  55. @pytest.mark.parametrize("quoting", [csv.QUOTE_MINIMAL, csv.QUOTE_NONE])
  56. @pytest.mark.parametrize("quote_char", ["", None])
  57. def test_null_quote_char(all_parsers, quoting, quote_char):
  58. kwargs = {"quotechar": quote_char, "quoting": quoting}
  59. data = "a,b,c\n1,2,3"
  60. parser = all_parsers
  61. if quoting != csv.QUOTE_NONE:
  62. # Sanity checking.
  63. msg = (
  64. '"quotechar" must be a 1-character string'
  65. if PY311 and all_parsers.engine == "python" and quote_char == ""
  66. else "quotechar must be set if quoting enabled"
  67. )
  68. with pytest.raises(TypeError, match=msg):
  69. parser.read_csv(StringIO(data), **kwargs)
  70. elif not (PY311 and all_parsers.engine == "python"):
  71. # Python 3.11+ doesn't support null/blank quote chars in their csv parsers
  72. expected = DataFrame([[1, 2, 3]], columns=["a", "b", "c"])
  73. result = parser.read_csv(StringIO(data), **kwargs)
  74. tm.assert_frame_equal(result, expected)
  75. @pytest.mark.parametrize(
  76. "kwargs,exp_data",
  77. [
  78. ({}, [[1, 2, "foo"]]), # Test default.
  79. # QUOTE_MINIMAL only applies to CSV writing, so no effect on reading.
  80. ({"quotechar": '"', "quoting": csv.QUOTE_MINIMAL}, [[1, 2, "foo"]]),
  81. # QUOTE_MINIMAL only applies to CSV writing, so no effect on reading.
  82. ({"quotechar": '"', "quoting": csv.QUOTE_ALL}, [[1, 2, "foo"]]),
  83. # QUOTE_NONE tells the reader to do no special handling
  84. # of quote characters and leave them alone.
  85. ({"quotechar": '"', "quoting": csv.QUOTE_NONE}, [[1, 2, '"foo"']]),
  86. # QUOTE_NONNUMERIC tells the reader to cast
  87. # all non-quoted fields to float
  88. ({"quotechar": '"', "quoting": csv.QUOTE_NONNUMERIC}, [[1.0, 2.0, "foo"]]),
  89. ],
  90. )
  91. def test_quoting_various(all_parsers, kwargs, exp_data):
  92. data = '1,2,"foo"'
  93. parser = all_parsers
  94. columns = ["a", "b", "c"]
  95. result = parser.read_csv(StringIO(data), names=columns, **kwargs)
  96. expected = DataFrame(exp_data, columns=columns)
  97. tm.assert_frame_equal(result, expected)
  98. @pytest.mark.parametrize(
  99. "doublequote,exp_data", [(True, [[3, '4 " 5']]), (False, [[3, '4 " 5"']])]
  100. )
  101. def test_double_quote(all_parsers, doublequote, exp_data):
  102. parser = all_parsers
  103. data = 'a,b\n3,"4 "" 5"'
  104. result = parser.read_csv(StringIO(data), quotechar='"', doublequote=doublequote)
  105. expected = DataFrame(exp_data, columns=["a", "b"])
  106. tm.assert_frame_equal(result, expected)
  107. @pytest.mark.parametrize("quotechar", ['"', "\u0001"])
  108. def test_quotechar_unicode(all_parsers, quotechar):
  109. # see gh-14477
  110. data = "a\n1"
  111. parser = all_parsers
  112. expected = DataFrame({"a": [1]})
  113. result = parser.read_csv(StringIO(data), quotechar=quotechar)
  114. tm.assert_frame_equal(result, expected)
  115. @pytest.mark.parametrize("balanced", [True, False])
  116. def test_unbalanced_quoting(all_parsers, balanced):
  117. # see gh-22789.
  118. parser = all_parsers
  119. data = 'a,b,c\n1,2,"3'
  120. if balanced:
  121. # Re-balance the quoting and read in without errors.
  122. expected = DataFrame([[1, 2, 3]], columns=["a", "b", "c"])
  123. result = parser.read_csv(StringIO(data + '"'))
  124. tm.assert_frame_equal(result, expected)
  125. else:
  126. msg = (
  127. "EOF inside string starting at row 1"
  128. if parser.engine == "c"
  129. else "unexpected end of data"
  130. )
  131. with pytest.raises(ParserError, match=msg):
  132. parser.read_csv(StringIO(data))