diff --git a/lib/csv.rb b/lib/csv.rb
index 8258eef9..094cd19d 100644
--- a/lib/csv.rb
+++ b/lib/csv.rb
@@ -851,6 +851,9 @@
class CSV
# The error thrown when the parser encounters illegal CSV formatting.
+ #
+ # After a CSV::InvalidEncodingError, parsing stops. After any other of
+ # these errors, CSV#shift continues reading at the next line.
class MalformedCSVError < RuntimeError
attr_reader :line_number
alias_method :lineno, :line_number
@@ -860,12 +863,22 @@ def initialize(message, line_number)
end
end
- # The error thrown when the parser encounters invalid encoding in CSV.
+ # The error thrown when the parser encounters invalid encoding in CSV,
+ # or when the input File or IO can't convert the data to the internal
+ # encoding. In the second case, the original Encoding error is #cause.
+ # Parsing stops at this error; see CSV#shift. With String input, a
+ # conversion error is raised by CSV.new as the Encoding error itself.
+ #
+ # #encoding is the encoding the data was read in. +message+ replaces
+ # the default "Invalid byte sequence in ..." text, for example for
+ # data that is valid but can't be converted.
class InvalidEncodingError < MalformedCSVError
attr_reader :encoding
- def initialize(encoding, line_number)
+ def initialize(encoding,
+ line_number,
+ message: "Invalid byte sequence in #{encoding}")
@encoding = encoding
- super("Invalid byte sequence in #{encoding}", line_number)
+ super(message, line_number)
end
end
@@ -2429,6 +2442,10 @@ def to_io
@io.respond_to?(:to_io) ? @io.to_io : @io
end
+ # Returns +true+ when all of the input has been read, and +false+
+ # before the first row is read. It also returns +true+ after a
+ # CSV::InvalidEncodingError, which stops parsing, even though the
+ # input has unread data. See #shift.
def eof?
parser.eof?
end
@@ -2783,6 +2800,24 @@ def header_row?
# csv.close
# # Raises IOError (not opened for reading)
# csv.shift
+ #
+ # Raises CSV::InvalidEncodingError if the data has an invalid byte
+ # sequence, or if the IO can't convert it to the internal encoding.
+ # Parsing stops at that error: later calls return +nil+, #eof? returns
+ # +true+, and the rest of the input isn't read. So a loop that rescues
+ # CSV::MalformedCSVError and continues ends at the first such error,
+ # and #eof? doesn't show whether all the input was read.
+ #
+ # The rows before the error are returned, except with String input,
+ # and except when the error is in the data read from the start of a
+ # File or IO to detect the row separator (with the default
+ # row_sep: :auto).
+ #
+ # To read past invalid data, replace it before parsing. String#scrub
+ # does this for a String; for a large IO, scrub each line as it is
+ # read. When the IO converts to a different internal encoding,
+ # invalid: :replace and undef: :replace, which
+ # CSV.open passes to File.open, also replace it.
def shift
parser.parse do |row|
return row
diff --git a/lib/csv/parser.rb b/lib/csv/parser.rb
index f14be3af..d33df4a3 100644
--- a/lib/csv/parser.rb
+++ b/lib/csv/parser.rb
@@ -35,6 +35,10 @@ def eof?(input)
class InvalidEncoding < StandardError
end
+ # Raised when the input IO can't transcode its data.
+ class InvalidTranscoding < InvalidEncoding
+ end
+
# Raised when unexpected case is happen.
class UnexpectedError < StandardError
end
@@ -92,6 +96,9 @@ def keep_drop
# CSV::InputsScanner.scan() tries to match with pattern at the current position.
# If there's a match, the scanner advances the "scan pointer" and returns the matched string.
# Otherwise, the scanner returns nil.
+ # If reading the next chunk after a match fails with InvalidEncoding,
+ # scan() still returns the match, and the error is raised when the
+ # scanner next reads from the input that failed.
#
# CSV::InputsScanner.rest() returns the "rest" of the string (i.e. everything after the scan pointer).
# If there is no more data (eos? = true), it returns "".
@@ -104,6 +111,8 @@ def initialize(inputs, encoding, row_separator, chunk_size: 8192)
@chunk_size = chunk_size
@last_scanner = @inputs.empty?
@keeps = []
+ @pending_invalid_encoding = nil
+ @pending_invalid_encoding_input = nil
read_chunk
end
@@ -155,23 +164,35 @@ def each_line(row_separator)
def scan(pattern)
# trace(__method__, pattern, :start)
+ read_chunk if @pending_invalid_encoding and @scanner.eos?
value = @scanner.scan(pattern)
# trace(__method__, pattern, :done, :last, value) if @last_scanner
return value if @last_scanner
- read_chunk if value and @scanner.eos?
+ if value and @scanner.eos?
+ begin
+ read_chunk
+ rescue InvalidEncoding => error
+ # scan() never extends a match into the next chunk, so the
+ # error can wait for the next read.
+ defer_invalid_encoding(error)
+ end
+ end
# trace(__method__, pattern, :done, value)
value
end
def scan_all(pattern)
# trace(__method__, pattern, :start)
+ read_chunk if @pending_invalid_encoding and @scanner.eos?
value = @scanner.scan(pattern)
# trace(__method__, pattern, :done, :last, value) if @last_scanner
return value if @last_scanner
# trace(__method__, pattern, :done, :nil) if value.nil?
return nil if value.nil?
+ # The value may continue in the next chunk, so a failed read here
+ # raises at once instead of being deferred like in scan().
while @scanner.eos? and read_chunk and (sub_value = @scanner.scan(pattern))
# trace(__method__, pattern, :sub, sub_value)
value << sub_value
@@ -304,26 +325,80 @@ def adjust_last_keep
# trace(__method__, :done)
end
+ def defer_invalid_encoding(error)
+ @pending_invalid_encoding = error
+ @pending_invalid_encoding_input = @inputs.first
+ end
+
+ # Raises the deferred error once the next read would come from the
+ # input that failed. Data that keep_back pushed back in front of it
+ # is read first.
+ def raise_pending_invalid_encoding
+ error = @pending_invalid_encoding
+ return if error.nil?
+ return unless @inputs.first.equal?(@pending_invalid_encoding_input)
+ @pending_invalid_encoding = nil
+ @pending_invalid_encoding_input = nil
+ raise error
+ end
+
+ # When the previous chunk ends with the start of the row separator
+ # and +chunk+ starts with the remainder, returns that remainder;
+ # otherwise nil.
+ def row_separator_rest(chunk)
+ # There is no previous chunk while the first chunk is read.
+ return nil if @scanner.nil?
+ return nil if @row_separator.size < 2
+ previous = @scanner.string
+ (1...@row_separator.size).each do |n|
+ next unless previous.end_with?(@row_separator[0, n])
+ rest = @row_separator[n..-1]
+ return rest if chunk.byteslice(0, rest.bytesize).b == rest.b
+ end
+ nil
+ end
+
def read_chunk
+ raise_pending_invalid_encoding
return false if @last_scanner
- adjust_last_keep
-
+ # Call adjust_last_keep only just before replacing @scanner: it
+ # copies the kept part of @scanner into the keep's buffer, so if
+ # @scanner stays (a failed read), keep_end returns that part twice.
input = @inputs.first
case input
when StringIO
string = input.read
raise InvalidEncoding unless string.valid_encoding?
# trace(__method__, :stringio, string)
+ adjust_last_keep
@scanner = StringScanner.new(string)
@inputs.shift
@last_scanner = @inputs.empty?
true
else
- chunk = input.gets(@row_separator, @chunk_size)
+ begin
+ chunk = input.gets(@row_separator, @chunk_size)
+ rescue Encoding::InvalidByteSequenceError,
+ Encoding::UndefinedConversionError => error
+ # IO#gets discards the data it read before the error, so when
+ # the previous chunk ended in the middle of the row separator,
+ # the rest of it is lost with the previous row.
+ raise InvalidTranscoding, cause: error
+ end
if chunk
- raise InvalidEncoding unless chunk.valid_encoding?
+ unless chunk.valid_encoding?
+ rest = row_separator_rest(chunk)
+ raise InvalidEncoding unless rest
+ # Scan the rest of the row separator first so the previous
+ # row can end, and raise the error on the next read.
+ adjust_last_keep
+ @scanner = StringScanner.new(rest)
+ defer_invalid_encoding(InvalidEncoding.new)
+ return true
+ end
# trace(__method__, :chunk, chunk)
+ adjust_last_keep
@scanner = StringScanner.new(chunk)
if Parser.eof?(input)
@inputs.shift
@@ -332,6 +407,7 @@ def read_chunk
true
else
# trace(__method__, :no_chunk)
+ adjust_last_keep
@scanner = StringScanner.new("".encode(@encoding))
@inputs.shift
@last_scanner = @inputs.empty?
@@ -349,6 +425,8 @@ def initialize(input, options)
@input = input
@options = options
@samples = []
+ @samples_transcoding_error = nil
+ @invalid_encoding_after_broken_line = nil
prepare
end
@@ -421,16 +499,33 @@ def parse(&block)
end
begin
- @scanner ||= build_scanner
- __send__(@parse_method, &block)
- rescue InvalidEncoding
- if @scanner
- ignore_broken_line
- lineno = @lineno
- else
- lineno = @lineno + 1
+ unless @scanner
+ if @samples_transcoding_error
+ raise InvalidTranscoding, cause: @samples_transcoding_error
+ end
+ begin
+ @scanner = build_scanner
+ rescue InvalidEncodingError
+ # build_scanner raises InvalidEncodingError itself when the
+ # whole input is one string.
+ finish_scanner
+ raise
+ end
+ end
+ if @invalid_encoding_after_broken_line
+ error = @invalid_encoding_after_broken_line
+ @invalid_encoding_after_broken_line = nil
+ raise error
end
- raise InvalidEncodingError.new(@encoding, lineno)
+ __send__(@parse_method, &block)
+ rescue InvalidEncoding => error
+ # The error is in the line after the last row. For a transcoding
+ # error in the samples, IO#gets discards the data it read before
+ # the error, so that line isn't known and line 1 is reported.
+ @lineno += 1
+ finish_scanner
+ cause = error.is_a?(InvalidTranscoding) ? error.cause : error
+ raise invalid_encoding_error(error, @lineno), cause: cause
rescue UnexpectedError => error
if @scanner
ignore_broken_line
@@ -723,6 +818,12 @@ def resolve_row_separator(separator)
end
rescue IOError
# do nothing: ensure will set default
+ rescue Encoding::InvalidByteSequenceError,
+ Encoding::UndefinedConversionError => error
+ # #parse raises this as InvalidEncodingError. Raising it here
+ # would fail the parser's construction, and CSV would build a
+ # new parser, reading on from the IO, on every call.
+ @samples_transcoding_error = error
end
end
separator = InputRecordSeparator.value if separator == :auto
@@ -1254,6 +1355,42 @@ def ignore_broken_line
@scanner.scan_all(@not_line_end)
@scanner.scan_all(@line_end)
@lineno += 1
+ rescue InvalidEncoding => error
+ # The line end can reach an invalid next chunk. Raise the error on
+ # the next #parse call, so the error for the broken line comes
+ # first.
+ @lineno += 1
+ @invalid_encoding_after_broken_line = error
+ end
+
+ # Replaces the scanner with an empty one, so later #parse calls
+ # yield no data rows, #eof? returns true and #line returns "".
+ def finish_scanner
+ @scanner = Scanner.new("".encode(@encoding))
+ @scanner.keep_start
+ @last_line = nil
+ end
+
+ def invalid_encoding_error(error, lineno)
+ cause = error.cause if error.is_a?(InvalidTranscoding)
+ return InvalidEncodingError.new(@encoding, lineno) if cause.nil?
+
+ # Use the IO's encodings: the cause names the step that failed,
+ # which can be an intermediate encoding such as UTF-8.
+ source = io_encoding(:external_encoding) || cause.source_encoding
+ if cause.is_a?(Encoding::UndefinedConversionError)
+ destination =
+ io_encoding(:internal_encoding) || cause.destination_encoding
+ message = "Undefined conversion from #{source} to #{destination}"
+ InvalidEncodingError.new(source, lineno, message: message)
+ else
+ InvalidEncodingError.new(source, lineno)
+ end
+ end
+
+ def io_encoding(name)
+ return nil unless @input.respond_to?(name)
+ @input.public_send(name)
end
def start_row
diff --git a/test/csv/parse/test_inputs_scanner.rb b/test/csv/parse/test_inputs_scanner.rb
index b82bb6c3..2c3c5c40 100644
--- a/test/csv/parse/test_inputs_scanner.rb
+++ b/test/csv/parse/test_inputs_scanner.rb
@@ -74,4 +74,111 @@ def test_each_line_keep_over_chunks_fit_chunk_size
assert_equal("a", each_line.next)
scanner.keep_back
end
+
+ def test_scan_invalid_next_chunk
+ input = CSV::Parser::UnoptimizedStringIO.new("ab\n\xFF\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\n",
+ chunk_size: 3)
+ assert_equal("ab\n", scanner.scan(/ab\n/))
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan_all(/[^\n]+/)
+ end
+ assert_nil(scanner.scan_all(/[^\n]+/))
+ end
+
+ def test_scan_invalid_next_chunk_keep_back
+ input = CSV::Parser::UnoptimizedStringIO.new("ab\n\xFF\ncd\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\n",
+ chunk_size: 3)
+ scanner.keep_start
+ assert_equal("ab\n", scanner.scan(/ab\n/))
+ scanner.keep_back
+ assert_equal("ab\n", scanner.scan(/ab\n/))
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan_all(/[^\n]+/)
+ end
+ end
+
+ def test_scan_invalid_next_chunk_keep_back_buffer
+ input = CSV::Parser::UnoptimizedStringIO.new("abc\n\xFF\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\n",
+ chunk_size: 2)
+ scanner.keep_start
+ assert_equal("abc", scanner.scan_all(/[a-c]+/))
+ assert_equal("\n", scanner.scan(/\n/))
+ scanner.keep_back
+ assert_equal(["abc", "\n"],
+ [scanner.scan_all(/[a-c]+/), scanner.scan(/\n/)])
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan_all(/[^\n]+/)
+ end
+ end
+
+ def test_scan_invalid_next_chunk_split_row_separator
+ input = CSV::Parser::UnoptimizedStringIO.new("ab\r\n\xFF\r\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\r\n",
+ chunk_size: 3)
+ scanner.keep_start
+ assert_equal(["ab", "\r", "\n"],
+ [scanner.scan(/ab/), scanner.scan(/\r/), scanner.scan(/\n/)])
+ assert_equal("ab\r\n", scanner.keep_end)
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan_all(/[^\r]+/)
+ end
+ end
+
+ def test_scan_after_invalid_next_chunk
+ input = CSV::Parser::UnoptimizedStringIO.new("ab\n\xFF\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\n",
+ chunk_size: 3)
+ assert_equal("ab\n", scanner.scan(/ab\n/))
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan(/\n/)
+ end
+ end
+
+ def test_invalid_first_chunk_with_multi_character_row_separator
+ input = CSV::Parser::UnoptimizedStringIO.new("\xFFb\r\n".b.force_encoding("UTF-8"))
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\r\n",
+ chunk_size: 3)
+ end
+ end
+
+ def test_scan_invalid_next_chunk_not_starting_with_row_separator_rest
+ input = CSV::Parser::UnoptimizedStringIO.new("ab\rc\xFF\r\n".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "\r\n",
+ chunk_size: 3)
+ assert_equal(["ab", "\r"], [scanner.scan(/ab/), scanner.scan(/\r/)])
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan(/\n/)
+ end
+ end
+
+ def test_scan_invalid_next_chunk_split_long_row_separator
+ input = CSV::Parser::UnoptimizedStringIO.new("ab<|>\xFF<|>".b.force_encoding("UTF-8"))
+ scanner = CSV::Parser::InputsScanner.new([input],
+ Encoding::UTF_8,
+ "<|>",
+ chunk_size: 4)
+ assert_equal(["ab", "<|", ">"],
+ [scanner.scan(/ab/), scanner.scan(/<\|/), scanner.scan(/>/)])
+ assert_raise(CSV::Parser::InvalidEncoding) do
+ scanner.scan_all(/[^<]+/)
+ end
+ end
end
diff --git a/test/csv/test_encodings.rb b/test/csv/test_encodings.rb
index 55a7a60f..131be120 100644
--- a/test/csv/test_encodings.rb
+++ b/test/csv/test_encodings.rb
@@ -288,6 +288,360 @@ def test_invalid_encoding_row_error
[error.encoding, error.message])
end
+ def test_invalid_encoding_file_in_sample
+ File.binwrite(@temp_csv_path, "id,name\n1,bob\xFF\n2,carol\n")
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 2]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ if CSV::Parser::SCANNER_TEST
+ # With CSV_PARSER_SCANNER_TEST, the scanner reads the sample in
+ # small chunks, so the rows before the invalid byte are returned.
+ expected_rows = [["id", "name"]]
+ else
+ expected_rows = []
+ end
+ assert_equal([expected_rows, [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_large_file_in_sample
+ data = numbered_rows(6000)
+ data[line_offset(data, 2)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ if CSV::Parser::SCANNER_TEST
+ expected_rows = numbered_fields(1..1)
+ expected_line = 2
+ else
+ expected_rows = []
+ # The invalid byte is in line 2, but line 1 is reported:
+ # https://github.com/ruby/csv/issues/385
+ expected_line = 1
+ end
+ assert_equal([[CSV::InvalidEncodingError, expected_line]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([expected_rows, [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_later_chunk
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([numbered_fields(1..3999), ["3999,user3999,ok\n"], [""]],
+ [result[:rows], result[:row_lines].last(1), result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_first_chunk_with_row_sep
+ data = numbered_rows(6000)
+ data[line_offset(data, 1)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8", row_sep: "\n") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 1]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([[], [""]], [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_first_chunk_with_crlf_row_sep
+ # The invalid first line opens a quoted field with line breaks. The
+ # rows after it must not be parsed from the middle of that field.
+ data = "1,\"junk\xFF\r\n9999,admin,true\r\nX\",ok\r\n2,b,ok\r\n".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8", row_sep: "\r\n") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 1]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([[], [""]], [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_later_chunk_robust_parser
+ # The escaped quotes switch the parser to parse_quotable_robust.
+ data = quoted_numbered_rows(6000)
+ data[line_offset(data, 4000)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal(quoted_numbered_fields(1..3999), result[:rows])
+ assert_equal(["3999,\"user \"\"3999\"\"\",ok\n", ""],
+ [result[:row_lines].last, result[:error_lines][0]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_later_chunk_no_quote
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8", quote_char: nil) do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([numbered_fields(1..3999), [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_later_chunk_quoted_line_break
+ # The invalid chunk starts a quoted field with a line break. The rows
+ # after it must not be parsed from the middle of that field.
+ data = numbered_rows(6000)
+ offset = line_offset(data, 4000)
+ data[offset, line_offset(data, 4001) - offset] =
+ "4000,\"junk\xFF\n9999,admin,true\nX\",ok\n".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([numbered_fields(1..3999), [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_in_later_chunk_crlf_robust_parser
+ data = quoted_numbered_rows(6000).gsub("\n", "\r\n")
+ data[line_offset(data, 4000)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal([quoted_numbered_fields(1..3999), [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_after_split_crlf
+ [{}, {quote_char: nil}, {strip: true}].each do |options|
+ data, long_line = split_crlf_rows
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8", **options) do |csv|
+ result = shift_all_rescuing(csv)
+ n_rows = result[:rows].size
+ assert_equal([[CSV::InvalidEncodingError, n_rows + 1]],
+ result[:errors].collect {|error| [error.class, error.line_number]},
+ options.inspect)
+ assert_equal([long_line.chomp("\r\n").split(","), long_line],
+ [result[:rows].last, result[:row_lines].last],
+ options.inspect)
+ assert_equal([nil, true], [csv.shift, csv.eof?], options.inspect)
+ end
+ end
+ end
+
+ def test_invalid_encoding_file_after_long_line_with_skip_lines
+ # skip_lines keeps a line longer than a chunk, so the data after the
+ # chunk is pushed back while the invalid chunk's error is pending.
+ data = (1..60).collect {|i| "#{i},#{"y" * 9000},ok\n"}.join.b
+ data[line_offset(data, 31)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path,
+ encoding: "UTF-8",
+ skip_lines: /\A#/,
+ strip: true) do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 31]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal((1..30).collect {|i| [i.to_s, "y" * 9000, "ok"]},
+ result[:rows])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_transcode_through_utf8
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000) + 5, 1] = "\x80".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "Windows-1252:Shift_JIS") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::Windows_1252,
+ "Undefined conversion from Windows-1252 to Shift_JIS " +
+ "in line 4000."],
+ [result[:errors].size, error.encoding, error.message])
+ assert_equal(Encoding::UndefinedConversionError, error.cause.class)
+ assert_equal(3999, result[:rows].size)
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_transcode_undefined_in_external_encoding
+ # 0x81 has no mapping in Windows-1252, so the conversion to UTF-8, a
+ # step before Shift_JIS, fails.
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000) + 5, 1] = "\x81".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "Windows-1252:Shift_JIS") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::Windows_1252,
+ "Undefined conversion from Windows-1252 to Shift_JIS " +
+ "in line 4000."],
+ [result[:errors].size, error.encoding, error.message])
+ assert_equal(Encoding::UndefinedConversionError, error.cause.class)
+ assert_equal(3999, result[:rows].size)
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_transcode_after_split_crlf
+ omit_if(CSV::Parser::SCANNER_TEST,
+ "CSV_PARSER_SCANNER_TEST doesn't use 8192-byte chunks")
+ # IO#gets discards the data it read before a conversion error,
+ # including the "\n" that ends the long line, so that row is lost and
+ # the error names its line.
+ data, long_line = split_crlf_rows
+ long_line_number = data.byteslice(0, data.index(long_line.b)).count("\n") + 1
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:UTF-16LE") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, long_line_number]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal(long_line_number - 1, result[:rows].size)
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_after_broken_line
+ # Scanning past the broken line reads the invalid chunk after it.
+ data = quoted_numbered_rows(6000)
+ offset = line_offset(data, 3999)
+ data[offset, line_offset(data, 4000) - offset] = "3999,\"user\" x,ok\n".b
+ data[line_offset(data, 4000)] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8") do |csv|
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::MalformedCSVError, 3999],
+ [CSV::InvalidEncodingError, 4000]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ assert_equal(quoted_numbered_fields(1..3998), result[:rows])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_string
+ csv = CSV.new("id,name\n1,bob\xFF\n2,carol\n")
+ result = shift_all_rescuing(csv)
+ assert_equal([[CSV::InvalidEncodingError, 2]],
+ result[:errors].collect {|error| [error.class, error.line_number]})
+ if CSV::Parser::SCANNER_TEST
+ # CSV_PARSER_SCANNER_TEST reads the String in small chunks.
+ expected_rows = [["id", "name"]]
+ else
+ expected_rows = []
+ end
+ assert_equal([expected_rows, [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true, ""], [csv.shift, csv.eof?, csv.line])
+ end
+
+ def test_invalid_encoding_file_transcode_in_later_chunk
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000) + 2] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:UTF-16LE") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::UTF_8,
+ "Invalid byte sequence in UTF-8 in line 4000."],
+ [result[:errors].size, error.encoding, error.message])
+ assert_equal(Encoding::InvalidByteSequenceError, error.cause.class)
+ assert_equal([numbered_fields(1..3999), [""]],
+ [encode_ary(result[:rows], "UTF-8"), result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_transcode_in_later_chunk_robust_parser
+ data = quoted_numbered_rows(6000)
+ data[line_offset(data, 4000) + 2] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:UTF-16LE") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::UTF_8,
+ "Invalid byte sequence in UTF-8 in line 4000."],
+ [result[:errors].size, error.encoding, error.message])
+ assert_equal(Encoding::InvalidByteSequenceError, error.cause.class)
+ assert_equal(quoted_numbered_fields(1..3999),
+ encode_ary(result[:rows], "UTF-8"))
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_transcode_in_sample
+ data = numbered_rows(6000)
+ data[line_offset(data, 10) + 2] = "\xFF".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:UTF-16LE") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ # IO#gets discards the data before the error, so the line isn't
+ # known and line 1 is reported.
+ assert_equal([1, Encoding::UTF_8, 1, []],
+ [result[:errors].size, error.encoding, error.line_number,
+ result[:rows]])
+ assert_equal(Encoding::InvalidByteSequenceError, error.cause.class)
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_undefined_conversion_in_later_chunk
+ data = numbered_rows(6000)
+ data[line_offset(data, 4000), 1] = "\u3042".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:ISO-8859-1") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::UTF_8,
+ "Undefined conversion from UTF-8 to ISO-8859-1 in line 4000."],
+ [result[:errors].size, error.encoding, error.message])
+ assert_equal(Encoding::UndefinedConversionError, error.cause.class)
+ assert_equal([numbered_fields(1..3999), [""]],
+ [result[:rows], result[:error_lines]])
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
+ def test_invalid_encoding_file_undefined_conversion_in_sample
+ data = numbered_rows(6000)
+ data[line_offset(data, 10), 1] = "\u3042".b
+ File.binwrite(@temp_csv_path, data)
+ CSV.open(@temp_csv_path, encoding: "UTF-8:ISO-8859-1") do |csv|
+ result = shift_all_rescuing(csv)
+ error = result[:errors][0]
+ assert_equal([1, Encoding::UTF_8,
+ "Undefined conversion from UTF-8 to ISO-8859-1 in line 1.",
+ []],
+ [result[:errors].size, error.encoding, error.message,
+ result[:rows]])
+ assert_equal(Encoding::UndefinedConversionError, error.cause.class)
+ assert_equal([nil, true], [csv.shift, csv.eof?])
+ end
+ end
+
def test_string_input_transcode
# U+3042 HIRAGANA LETTER A
# U+3044 HIRAGANA LETTER I
@@ -321,6 +675,71 @@ def test_string_input_set_encoding_encoding
private
+ # Reads every row the way an importer that skips bad rows does, and
+ # stops after max_errors errors so that a parser that never advances
+ # can't hang the test.
+ def shift_all_rescuing(csv, max_errors: 10)
+ result = {rows: [], row_lines: [], errors: [], error_lines: []}
+ while result[:errors].size < max_errors
+ begin
+ row = csv.shift
+ break if row.nil?
+ result[:rows] << row
+ result[:row_lines] << csv.line
+ rescue CSV::MalformedCSVError => error
+ result[:errors] << error
+ result[:error_lines] << csv.line
+ end
+ end
+ result
+ end
+
+ def numbered_rows(n)
+ (1..n).collect {|i| "#{i},user#{i},ok\n"}.join.b
+ end
+
+ # Rows whose first 32 KiB, the sample read for row separator detection,
+ # end at a row end, followed by a line whose "\r" is the 8192nd byte of
+ # the next chunk and an invalid line. Returns the data and the long line.
+ def split_crlf_rows
+ sample_size = 32 * 1024
+ rows = +""
+ i = 0
+ while rows.bytesize < sample_size - 64
+ i += 1
+ rows << "#{i},a,ok\r\n"
+ end
+ i += 1
+ padding = sample_size - rows.bytesize - "#{i},,ok\r\n".bytesize
+ rows << "#{i},#{"a" * padding},ok\r\n"
+ i += 1
+ prefix = "#{i},"
+ long_line = "#{prefix}#{"x" * (8192 - 1 - prefix.bytesize)}\r\n"
+ i += 1
+ data = rows + long_line + "#{i},\xFF,ok\r\n#{i + 1},a,ok\r\n"
+ [data.b, long_line]
+ end
+
+ def numbered_fields(range)
+ range.collect {|i| [i.to_s, "user#{i}", "ok"]}
+ end
+
+ def quoted_numbered_rows(n)
+ (1..n).collect {|i| "#{i},\"user \"\"#{i}\"\"\",ok\n"}.join.b
+ end
+
+ def quoted_numbered_fields(range)
+ range.collect {|i| [i.to_s, "user \"#{i}\"", "ok"]}
+ end
+
+ def line_offset(data, line)
+ offset = 0
+ (line - 1).times do
+ offset = data.index("\n", offset) + 1
+ end
+ offset
+ end
+
def assert_parses(fields, encoding, **options)
encoding = Encoding.find(encoding) unless encoding.is_a? Encoding
orig_fields = fields