bpo-30825: guess lineterminator in csv.Sniffer by vmax · Pull Request #2529 · python/cpython · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions Lib/csv.py
15 changes: 15 additions & 0 deletions Lib/test/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import csv
import gc
import pickle
import os
from test import support
from itertools import permutations
from textwrap import dedent
Expand Down Expand Up @@ -1018,6 +1019,20 @@ def test_doublequote(self):
dialect = sniffer.sniff(self.sample9)
self.assertTrue(dialect.doublequote)

def test_guess_lineterminator(self):
sniffer = csv.Sniffer()
dialect = sniffer.sniff(r"Date;Value\r\n2010-01-01;10")
self.assertEqual(dialect.lineterminator, '\r\n')
dialect = sniffer.sniff(r"Date;Value\n2010-01-01;10")
self.assertEqual(dialect.lineterminator, '\n')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assumes that the line terminator for multiline triple-quoted string literals is '\n'. We require that '\r\n' in code files be converted to '\n' before merging, but the test should not assume '\n' for all developer and user systems where the test might be run. So sample8 should be replaced by a literal.

Since the sample strings need not be long, they can all be literals defined here. Make all 3 the same except for the terminator. This will make the test both crystal clear and independent of system and optional local settings.

dialect = sniffer.sniff(r"Date;Value\r2010-01-01;10")
self.assertEqual(dialect.lineterminator, '\r')
dialect = sniffer.sniff(r"Date;Value\v2010-01-01;10")
self.assertEqual(dialect.lineterminator, os.linesep)
dialect = sniffer.sniff(r"Date;Value")
self.assertEqual(dialect.lineterminator, os.linesep)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add tests to cover the last line of _guess_lineterminator: return os.linesep. Add a test with the same literal, but with an oddball terminator, such as '\v' (vertical tab), and another with a single line with no control chars.


class NUL:
def write(s, *args):
pass
Expand Down