blob: 8ca1e62c4ae0200414d066a209ee5063f6d52de1 [file] [log] [blame]
Skip Montanarob4a04172003-03-20 23:29:12 +00001# Copyright (C) 2001,2002 Python Software Foundation
2# csv package unit tests
3
Guido van Rossumf0c74162007-08-28 03:29:45 +00004import io
Skip Montanarob4a04172003-03-20 23:29:12 +00005import sys
Skip Montanaro58fc5d082004-06-05 17:03:20 +00006import os
Skip Montanarob4a04172003-03-20 23:29:12 +00007import unittest
R. David Murray8b7d4aa2009-04-04 01:38:38 +00008from io import StringIO
Guido van Rossum46264582007-08-06 19:32:18 +00009from tempfile import TemporaryFile
Skip Montanaro594adac2003-04-10 17:16:15 +000010import csv
Skip Montanarob4a04172003-03-20 23:29:12 +000011import gc
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Skip Montanarob4a04172003-03-20 23:29:12 +000013
14class Test_Csv(unittest.TestCase):
15 """
Tim Peters0eadaac2003-04-24 16:02:54 +000016 Test the underlying C csv parser in ways that are not appropriate
Skip Montanarob4a04172003-03-20 23:29:12 +000017 from the high level interface. Further tests of this nature are done
18 in TestDialectRegistry.
19 """
Andrew McNamara1196cf12005-01-07 04:42:45 +000020 def _test_arg_valid(self, ctor, arg):
21 self.assertRaises(TypeError, ctor)
22 self.assertRaises(TypeError, ctor, None)
23 self.assertRaises(TypeError, ctor, arg, bad_attr = 0)
24 self.assertRaises(TypeError, ctor, arg, delimiter = 0)
25 self.assertRaises(TypeError, ctor, arg, delimiter = 'XX')
26 self.assertRaises(csv.Error, ctor, arg, 'foo')
Andrew McNamara1196cf12005-01-07 04:42:45 +000027 self.assertRaises(TypeError, ctor, arg, delimiter=None)
28 self.assertRaises(TypeError, ctor, arg, delimiter=1)
29 self.assertRaises(TypeError, ctor, arg, quotechar=1)
30 self.assertRaises(TypeError, ctor, arg, lineterminator=None)
31 self.assertRaises(TypeError, ctor, arg, lineterminator=1)
32 self.assertRaises(TypeError, ctor, arg, quoting=None)
Tim Peters608c2ff2005-01-13 17:37:38 +000033 self.assertRaises(TypeError, ctor, arg,
Andrew McNamaraaf1e3122005-01-12 01:55:21 +000034 quoting=csv.QUOTE_ALL, quotechar='')
Tim Peters608c2ff2005-01-13 17:37:38 +000035 self.assertRaises(TypeError, ctor, arg,
Andrew McNamara5d45a8d2005-01-12 08:16:17 +000036 quoting=csv.QUOTE_ALL, quotechar=None)
Andrew McNamara1196cf12005-01-07 04:42:45 +000037
38 def test_reader_arg_valid(self):
39 self._test_arg_valid(csv.reader, [])
Skip Montanarob4a04172003-03-20 23:29:12 +000040
41 def test_writer_arg_valid(self):
Andrew McNamara1196cf12005-01-07 04:42:45 +000042 self._test_arg_valid(csv.writer, StringIO())
Skip Montanarob4a04172003-03-20 23:29:12 +000043
Andrew McNamara1196cf12005-01-07 04:42:45 +000044 def _test_default_attrs(self, ctor, *args):
45 obj = ctor(*args)
46 # Check defaults
Skip Montanarob4a04172003-03-20 23:29:12 +000047 self.assertEqual(obj.dialect.delimiter, ',')
Andrew McNamara1196cf12005-01-07 04:42:45 +000048 self.assertEqual(obj.dialect.doublequote, True)
Skip Montanarob4a04172003-03-20 23:29:12 +000049 self.assertEqual(obj.dialect.escapechar, None)
Andrew McNamara1196cf12005-01-07 04:42:45 +000050 self.assertEqual(obj.dialect.lineterminator, "\r\n")
51 self.assertEqual(obj.dialect.quotechar, '"')
52 self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL)
53 self.assertEqual(obj.dialect.skipinitialspace, False)
54 self.assertEqual(obj.dialect.strict, False)
55 # Try deleting or changing attributes (they are read-only)
Collin Winter42dae6a2007-03-28 21:44:53 +000056 self.assertRaises(AttributeError, delattr, obj.dialect, 'delimiter')
57 self.assertRaises(AttributeError, setattr, obj.dialect, 'delimiter', ':')
Barry Warsawb180c062005-04-20 19:41:36 +000058 self.assertRaises(AttributeError, delattr, obj.dialect, 'quoting')
59 self.assertRaises(AttributeError, setattr, obj.dialect,
60 'quoting', None)
Skip Montanarob4a04172003-03-20 23:29:12 +000061
62 def test_reader_attrs(self):
Andrew McNamara1196cf12005-01-07 04:42:45 +000063 self._test_default_attrs(csv.reader, [])
Skip Montanarob4a04172003-03-20 23:29:12 +000064
65 def test_writer_attrs(self):
Andrew McNamara1196cf12005-01-07 04:42:45 +000066 self._test_default_attrs(csv.writer, StringIO())
67
68 def _test_kw_attrs(self, ctor, *args):
69 # Now try with alternate options
70 kwargs = dict(delimiter=':', doublequote=False, escapechar='\\',
71 lineterminator='\r', quotechar='*',
72 quoting=csv.QUOTE_NONE, skipinitialspace=True,
73 strict=True)
74 obj = ctor(*args, **kwargs)
75 self.assertEqual(obj.dialect.delimiter, ':')
76 self.assertEqual(obj.dialect.doublequote, False)
77 self.assertEqual(obj.dialect.escapechar, '\\')
78 self.assertEqual(obj.dialect.lineterminator, "\r")
79 self.assertEqual(obj.dialect.quotechar, '*')
80 self.assertEqual(obj.dialect.quoting, csv.QUOTE_NONE)
81 self.assertEqual(obj.dialect.skipinitialspace, True)
82 self.assertEqual(obj.dialect.strict, True)
83
84 def test_reader_kw_attrs(self):
85 self._test_kw_attrs(csv.reader, [])
86
87 def test_writer_kw_attrs(self):
88 self._test_kw_attrs(csv.writer, StringIO())
89
90 def _test_dialect_attrs(self, ctor, *args):
91 # Now try with dialect-derived options
92 class dialect:
93 delimiter='-'
94 doublequote=False
95 escapechar='^'
96 lineterminator='$'
97 quotechar='#'
98 quoting=csv.QUOTE_ALL
99 skipinitialspace=True
100 strict=False
101 args = args + (dialect,)
102 obj = ctor(*args)
103 self.assertEqual(obj.dialect.delimiter, '-')
104 self.assertEqual(obj.dialect.doublequote, False)
105 self.assertEqual(obj.dialect.escapechar, '^')
106 self.assertEqual(obj.dialect.lineterminator, "$")
107 self.assertEqual(obj.dialect.quotechar, '#')
108 self.assertEqual(obj.dialect.quoting, csv.QUOTE_ALL)
109 self.assertEqual(obj.dialect.skipinitialspace, True)
110 self.assertEqual(obj.dialect.strict, False)
111
112 def test_reader_dialect_attrs(self):
113 self._test_dialect_attrs(csv.reader, [])
114
115 def test_writer_dialect_attrs(self):
116 self._test_dialect_attrs(csv.writer, StringIO())
117
Skip Montanarob4a04172003-03-20 23:29:12 +0000118
119 def _write_test(self, fields, expect, **kwargs):
Guido van Rossumf0c74162007-08-28 03:29:45 +0000120 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000121 writer = csv.writer(fileobj, **kwargs)
122 writer.writerow(fields)
123 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000124 self.assertEqual(fileobj.read(),
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000125 expect + writer.dialect.lineterminator)
Skip Montanarob4a04172003-03-20 23:29:12 +0000126
127 def test_write_arg_valid(self):
128 self.assertRaises(csv.Error, self._write_test, None, '')
129 self._write_test((), '')
130 self._write_test([None], '""')
Tim Peters0eadaac2003-04-24 16:02:54 +0000131 self.assertRaises(csv.Error, self._write_test,
Skip Montanarob4a04172003-03-20 23:29:12 +0000132 [None], None, quoting = csv.QUOTE_NONE)
133 # Check that exceptions are passed up the chain
134 class BadList:
135 def __len__(self):
136 return 10;
137 def __getitem__(self, i):
138 if i > 2:
139 raise IOError
140 self.assertRaises(IOError, self._write_test, BadList(), '')
141 class BadItem:
142 def __str__(self):
143 raise IOError
144 self.assertRaises(IOError, self._write_test, [BadItem()], '')
145
146 def test_write_bigfield(self):
147 # This exercises the buffer realloc functionality
148 bigstring = 'X' * 50000
149 self._write_test([bigstring,bigstring], '%s,%s' % \
150 (bigstring, bigstring))
151
152 def test_write_quoting(self):
Andrew McNamarac89f2842005-01-12 07:44:42 +0000153 self._write_test(['a',1,'p,q'], 'a,1,"p,q"')
Tim Peters0eadaac2003-04-24 16:02:54 +0000154 self.assertRaises(csv.Error,
Skip Montanarob4a04172003-03-20 23:29:12 +0000155 self._write_test,
Andrew McNamarac89f2842005-01-12 07:44:42 +0000156 ['a',1,'p,q'], 'a,1,p,q',
Skip Montanarob4a04172003-03-20 23:29:12 +0000157 quoting = csv.QUOTE_NONE)
Andrew McNamarac89f2842005-01-12 07:44:42 +0000158 self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
Skip Montanarob4a04172003-03-20 23:29:12 +0000159 quoting = csv.QUOTE_MINIMAL)
Andrew McNamarac89f2842005-01-12 07:44:42 +0000160 self._write_test(['a',1,'p,q'], '"a",1,"p,q"',
Skip Montanarob4a04172003-03-20 23:29:12 +0000161 quoting = csv.QUOTE_NONNUMERIC)
Andrew McNamarac89f2842005-01-12 07:44:42 +0000162 self._write_test(['a',1,'p,q'], '"a","1","p,q"',
Skip Montanarob4a04172003-03-20 23:29:12 +0000163 quoting = csv.QUOTE_ALL)
R. David Murraycde68cf2009-04-01 22:37:58 +0000164 self._write_test(['a\nb',1], '"a\nb","1"',
165 quoting = csv.QUOTE_ALL)
Skip Montanarob4a04172003-03-20 23:29:12 +0000166
167 def test_write_escape(self):
Andrew McNamarac89f2842005-01-12 07:44:42 +0000168 self._write_test(['a',1,'p,q'], 'a,1,"p,q"',
Skip Montanarob4a04172003-03-20 23:29:12 +0000169 escapechar='\\')
Andrew McNamarac89f2842005-01-12 07:44:42 +0000170 self.assertRaises(csv.Error,
171 self._write_test,
172 ['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
Tim Peters608c2ff2005-01-13 17:37:38 +0000173 escapechar=None, doublequote=False)
Andrew McNamarac89f2842005-01-12 07:44:42 +0000174 self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""',
175 escapechar='\\', doublequote = False)
Tim Peters608c2ff2005-01-13 17:37:38 +0000176 self._write_test(['"'], '""""',
Andrew McNamarac89f2842005-01-12 07:44:42 +0000177 escapechar='\\', quoting = csv.QUOTE_MINIMAL)
Tim Peters608c2ff2005-01-13 17:37:38 +0000178 self._write_test(['"'], '\\"',
Andrew McNamarac89f2842005-01-12 07:44:42 +0000179 escapechar='\\', quoting = csv.QUOTE_MINIMAL,
180 doublequote = False)
Tim Peters608c2ff2005-01-13 17:37:38 +0000181 self._write_test(['"'], '\\"',
Andrew McNamarac89f2842005-01-12 07:44:42 +0000182 escapechar='\\', quoting = csv.QUOTE_NONE)
183 self._write_test(['a',1,'p,q'], 'a,1,p\\,q',
Skip Montanarob4a04172003-03-20 23:29:12 +0000184 escapechar='\\', quoting = csv.QUOTE_NONE)
185
186 def test_writerows(self):
187 class BrokenFile:
188 def write(self, buf):
189 raise IOError
190 writer = csv.writer(BrokenFile())
191 self.assertRaises(IOError, writer.writerows, [['a']])
Guido van Rossum46264582007-08-06 19:32:18 +0000192
Guido van Rossumf0c74162007-08-28 03:29:45 +0000193 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000194 writer = csv.writer(fileobj)
195 self.assertRaises(TypeError, writer.writerows, None)
196 writer.writerows([['a','b'],['c','d']])
197 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000198 self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n")
Tim Peters27f88362004-07-08 04:22:35 +0000199
Skip Montanarob4a04172003-03-20 23:29:12 +0000200 def _read_test(self, input, expect, **kwargs):
201 reader = csv.reader(input, **kwargs)
202 result = list(reader)
203 self.assertEqual(result, expect)
204
205 def test_read_oddinputs(self):
206 self._read_test([], [])
207 self._read_test([''], [[]])
208 self.assertRaises(csv.Error, self._read_test,
209 ['"ab"c'], None, strict = 1)
210 # cannot handle null bytes for the moment
211 self.assertRaises(csv.Error, self._read_test,
212 ['ab\0c'], None, strict = 1)
213 self._read_test(['"ab"c'], [['abc']], doublequote = 0)
214
Amaury Forgeot d'Arc10c476d2007-11-19 21:20:21 +0000215 self.assertRaises(csv.Error, self._read_test,
216 [b'ab\0c'], None)
217
218
Skip Montanarob4a04172003-03-20 23:29:12 +0000219 def test_read_eol(self):
220 self._read_test(['a,b'], [['a','b']])
221 self._read_test(['a,b\n'], [['a','b']])
222 self._read_test(['a,b\r\n'], [['a','b']])
223 self._read_test(['a,b\r'], [['a','b']])
224 self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], [])
225 self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], [])
226 self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], [])
227
228 def test_read_escape(self):
Andrew McNamara36a76912005-01-10 01:04:40 +0000229 self._read_test(['a,\\b,c'], [['a', 'b', 'c']], escapechar='\\')
Skip Montanarob4a04172003-03-20 23:29:12 +0000230 self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\')
231 self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\')
Andrew McNamara36a76912005-01-10 01:04:40 +0000232 self._read_test(['a,"b,\\c"'], [['a', 'b,c']], escapechar='\\')
Skip Montanarob4a04172003-03-20 23:29:12 +0000233 self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\')
234 self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\')
235
Andrew McNamara1196cf12005-01-07 04:42:45 +0000236 def test_read_quoting(self):
237 self._read_test(['1,",3,",5'], [['1', ',3,', '5']])
238 self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']],
239 quotechar=None, escapechar='\\')
240 self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']],
241 quoting=csv.QUOTE_NONE, escapechar='\\')
Andrew McNamara0f0599d2005-01-12 09:45:18 +0000242 # will this fail where locale uses comma for decimals?
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000243 self._read_test([',3,"5",7.3, 9'], [['', 3, '5', 7.3, 9]],
Andrew McNamara0f0599d2005-01-12 09:45:18 +0000244 quoting=csv.QUOTE_NONNUMERIC)
R. David Murraycde68cf2009-04-01 22:37:58 +0000245 self._read_test(['"a\nb", 7'], [['a\nb', ' 7']])
Tim Peters608c2ff2005-01-13 17:37:38 +0000246 self.assertRaises(ValueError, self._read_test,
Andrew McNamara0f0599d2005-01-12 09:45:18 +0000247 ['abc,3'], [[]],
248 quoting=csv.QUOTE_NONNUMERIC)
Andrew McNamara1196cf12005-01-07 04:42:45 +0000249
Skip Montanarob4a04172003-03-20 23:29:12 +0000250 def test_read_bigfield(self):
Andrew McNamarae4d05c42005-01-11 07:32:02 +0000251 # This exercises the buffer realloc functionality and field size
252 # limits.
Andrew McNamara31d88962005-01-12 03:45:10 +0000253 limit = csv.field_size_limit()
Andrew McNamaraaf1e3122005-01-12 01:55:21 +0000254 try:
255 size = 50000
256 bigstring = 'X' * size
257 bigline = '%s,%s' % (bigstring, bigstring)
258 self._read_test([bigline], [[bigstring, bigstring]])
Andrew McNamara31d88962005-01-12 03:45:10 +0000259 csv.field_size_limit(size)
Andrew McNamaraaf1e3122005-01-12 01:55:21 +0000260 self._read_test([bigline], [[bigstring, bigstring]])
Andrew McNamara31d88962005-01-12 03:45:10 +0000261 self.assertEqual(csv.field_size_limit(), size)
262 csv.field_size_limit(size-1)
Andrew McNamaraaf1e3122005-01-12 01:55:21 +0000263 self.assertRaises(csv.Error, self._read_test, [bigline], [])
Andrew McNamara31d88962005-01-12 03:45:10 +0000264 self.assertRaises(TypeError, csv.field_size_limit, None)
265 self.assertRaises(TypeError, csv.field_size_limit, 1, None)
Andrew McNamaraaf1e3122005-01-12 01:55:21 +0000266 finally:
Andrew McNamara31d88962005-01-12 03:45:10 +0000267 csv.field_size_limit(limit)
Skip Montanarob4a04172003-03-20 23:29:12 +0000268
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000269 def test_read_linenum(self):
270 r = csv.reader(['line,1', 'line,2', 'line,3'])
271 self.assertEqual(r.line_num, 0)
Georg Brandla18af4e2007-04-21 15:47:16 +0000272 next(r)
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000273 self.assertEqual(r.line_num, 1)
Georg Brandla18af4e2007-04-21 15:47:16 +0000274 next(r)
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000275 self.assertEqual(r.line_num, 2)
Georg Brandla18af4e2007-04-21 15:47:16 +0000276 next(r)
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000277 self.assertEqual(r.line_num, 3)
Georg Brandla18af4e2007-04-21 15:47:16 +0000278 self.assertRaises(StopIteration, next, r)
Andrew McNamara7f2053e2005-01-12 11:17:16 +0000279 self.assertEqual(r.line_num, 3)
280
R. David Murraycde68cf2009-04-01 22:37:58 +0000281 def test_roundtrip_quoteed_newlines(self):
282 with TemporaryFile("w+", newline='') as fileobj:
283 writer = csv.writer(fileobj)
284 self.assertRaises(TypeError, writer.writerows, None)
285 rows = [['a\nb','b'],['c','x\r\nd']]
286 writer.writerows(rows)
287 fileobj.seek(0)
288 for i, row in enumerate(csv.reader(fileobj)):
289 self.assertEqual(row, rows[i])
290
Skip Montanarob4a04172003-03-20 23:29:12 +0000291class TestDialectRegistry(unittest.TestCase):
292 def test_registry_badargs(self):
293 self.assertRaises(TypeError, csv.list_dialects, None)
294 self.assertRaises(TypeError, csv.get_dialect)
295 self.assertRaises(csv.Error, csv.get_dialect, None)
296 self.assertRaises(csv.Error, csv.get_dialect, "nonesuch")
297 self.assertRaises(TypeError, csv.unregister_dialect)
298 self.assertRaises(csv.Error, csv.unregister_dialect, None)
299 self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch")
300 self.assertRaises(TypeError, csv.register_dialect, None)
301 self.assertRaises(TypeError, csv.register_dialect, None, None)
Andrew McNamaraaf1e3122005-01-12 01:55:21 +0000302 self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0)
303 self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
304 badargument=None)
305 self.assertRaises(TypeError, csv.register_dialect, "nonesuch",
306 quoting=None)
307 self.assertRaises(TypeError, csv.register_dialect, [])
Skip Montanarob4a04172003-03-20 23:29:12 +0000308
309 def test_registry(self):
310 class myexceltsv(csv.excel):
311 delimiter = "\t"
312 name = "myexceltsv"
313 expected_dialects = csv.list_dialects() + [name]
314 expected_dialects.sort()
315 csv.register_dialect(name, myexceltsv)
Éric Araujo5137d642010-12-02 22:16:19 +0000316 self.addCleanup(csv.unregister_dialect, name)
317 self.assertEqual(csv.get_dialect(name).delimiter, '\t')
318 got_dialects = sorted(csv.list_dialects())
319 self.assertEqual(expected_dialects, got_dialects)
Skip Montanarob4a04172003-03-20 23:29:12 +0000320
Andrew McNamara86625972005-01-11 01:28:33 +0000321 def test_register_kwargs(self):
322 name = 'fedcba'
323 csv.register_dialect(name, delimiter=';')
Éric Araujo5137d642010-12-02 22:16:19 +0000324 self.addCleanup(csv.unregister_dialect, name)
325 self.assertEqual(csv.get_dialect(name).delimiter, ';')
326 self.assertEqual([['X', 'Y', 'Z']], list(csv.reader(['X;Y;Z'], name)))
Andrew McNamara86625972005-01-11 01:28:33 +0000327
Skip Montanarob4a04172003-03-20 23:29:12 +0000328 def test_incomplete_dialect(self):
329 class myexceltsv(csv.Dialect):
330 delimiter = "\t"
331 self.assertRaises(csv.Error, myexceltsv)
332
333 def test_space_dialect(self):
334 class space(csv.excel):
335 delimiter = " "
336 quoting = csv.QUOTE_NONE
337 escapechar = "\\"
338
Guido van Rossum46264582007-08-06 19:32:18 +0000339 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000340 fileobj.write("abc def\nc1ccccc1 benzene\n")
341 fileobj.seek(0)
Georg Brandla18af4e2007-04-21 15:47:16 +0000342 reader = csv.reader(fileobj, dialect=space())
343 self.assertEqual(next(reader), ["abc", "def"])
344 self.assertEqual(next(reader), ["c1ccccc1", "benzene"])
Guido van Rossum46264582007-08-06 19:32:18 +0000345
346 def compare_dialect_123(self, expected, *writeargs, **kwwriteargs):
Guido van Rossumf0c74162007-08-28 03:29:45 +0000347
348 with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
349
Guido van Rossum46264582007-08-06 19:32:18 +0000350 writer = csv.writer(fileobj, *writeargs, **kwwriteargs)
351 writer.writerow([1,2,3])
352 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000353 self.assertEqual(fileobj.read(), expected)
Tim Peters27f88362004-07-08 04:22:35 +0000354
Skip Montanarob4a04172003-03-20 23:29:12 +0000355 def test_dialect_apply(self):
356 class testA(csv.excel):
357 delimiter = "\t"
358 class testB(csv.excel):
359 delimiter = ":"
360 class testC(csv.excel):
361 delimiter = "|"
Guido van Rossum46264582007-08-06 19:32:18 +0000362 class testUni(csv.excel):
363 delimiter = "\u039B"
Skip Montanarob4a04172003-03-20 23:29:12 +0000364
365 csv.register_dialect('testC', testC)
366 try:
Guido van Rossum46264582007-08-06 19:32:18 +0000367 self.compare_dialect_123("1,2,3\r\n")
368 self.compare_dialect_123("1\t2\t3\r\n", testA)
369 self.compare_dialect_123("1:2:3\r\n", dialect=testB())
370 self.compare_dialect_123("1|2|3\r\n", dialect='testC')
371 self.compare_dialect_123("1;2;3\r\n", dialect=testA,
372 delimiter=';')
373 self.compare_dialect_123("1\u039B2\u039B3\r\n",
374 dialect=testUni)
Skip Montanarob4a04172003-03-20 23:29:12 +0000375
Skip Montanarob4a04172003-03-20 23:29:12 +0000376 finally:
377 csv.unregister_dialect('testC')
378
379 def test_bad_dialect(self):
380 # Unknown parameter
Andrew McNamara1196cf12005-01-07 04:42:45 +0000381 self.assertRaises(TypeError, csv.reader, [], bad_attr = 0)
Skip Montanarob4a04172003-03-20 23:29:12 +0000382 # Bad values
383 self.assertRaises(TypeError, csv.reader, [], delimiter = None)
384 self.assertRaises(TypeError, csv.reader, [], quoting = -1)
385 self.assertRaises(TypeError, csv.reader, [], quoting = 100)
386
387class TestCsvBase(unittest.TestCase):
388 def readerAssertEqual(self, input, expected_result):
Amaury Forgeot d'Arc10c476d2007-11-19 21:20:21 +0000389 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000390 fileobj.write(input)
391 fileobj.seek(0)
392 reader = csv.reader(fileobj, dialect = self.dialect)
393 fields = list(reader)
394 self.assertEqual(fields, expected_result)
Skip Montanarob4a04172003-03-20 23:29:12 +0000395
396 def writerAssertEqual(self, input, expected_result):
Guido van Rossumf0c74162007-08-28 03:29:45 +0000397 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000398 writer = csv.writer(fileobj, dialect = self.dialect)
399 writer.writerows(input)
400 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000401 self.assertEqual(fileobj.read(), expected_result)
Skip Montanarob4a04172003-03-20 23:29:12 +0000402
403class TestDialectExcel(TestCsvBase):
404 dialect = 'excel'
405
406 def test_single(self):
407 self.readerAssertEqual('abc', [['abc']])
408
409 def test_simple(self):
410 self.readerAssertEqual('1,2,3,4,5', [['1','2','3','4','5']])
411
412 def test_blankline(self):
413 self.readerAssertEqual('', [])
414
415 def test_empty_fields(self):
416 self.readerAssertEqual(',', [['', '']])
417
418 def test_singlequoted(self):
419 self.readerAssertEqual('""', [['']])
420
421 def test_singlequoted_left_empty(self):
422 self.readerAssertEqual('"",', [['','']])
423
424 def test_singlequoted_right_empty(self):
425 self.readerAssertEqual(',""', [['','']])
426
427 def test_single_quoted_quote(self):
428 self.readerAssertEqual('""""', [['"']])
429
430 def test_quoted_quotes(self):
431 self.readerAssertEqual('""""""', [['""']])
432
433 def test_inline_quote(self):
434 self.readerAssertEqual('a""b', [['a""b']])
435
436 def test_inline_quotes(self):
437 self.readerAssertEqual('a"b"c', [['a"b"c']])
438
439 def test_quotes_and_more(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000440 # Excel would never write a field containing '"a"b', but when
441 # reading one, it will return 'ab'.
Skip Montanarob4a04172003-03-20 23:29:12 +0000442 self.readerAssertEqual('"a"b', [['ab']])
443
444 def test_lone_quote(self):
445 self.readerAssertEqual('a"b', [['a"b']])
446
447 def test_quote_and_quote(self):
Guido van Rossumd8faa362007-04-27 19:54:29 +0000448 # Excel would never write a field containing '"a" "b"', but when
449 # reading one, it will return 'a "b"'.
Skip Montanarob4a04172003-03-20 23:29:12 +0000450 self.readerAssertEqual('"a" "b"', [['a "b"']])
451
452 def test_space_and_quote(self):
453 self.readerAssertEqual(' "a"', [[' "a"']])
454
455 def test_quoted(self):
Tim Peters0eadaac2003-04-24 16:02:54 +0000456 self.readerAssertEqual('1,2,3,"I think, therefore I am",5,6',
457 [['1', '2', '3',
458 'I think, therefore I am',
Skip Montanarob4a04172003-03-20 23:29:12 +0000459 '5', '6']])
460
461 def test_quoted_quote(self):
Georg Brandlcd9f1202011-07-06 07:31:38 +0200462 self.readerAssertEqual('1,2,3,"""I see,"" said the blind man","as he picked up his hammer and saw"',
Tim Peters0eadaac2003-04-24 16:02:54 +0000463 [['1', '2', '3',
Georg Brandlcd9f1202011-07-06 07:31:38 +0200464 '"I see," said the blind man',
Skip Montanarob4a04172003-03-20 23:29:12 +0000465 'as he picked up his hammer and saw']])
466
467 def test_quoted_nl(self):
468 input = '''\
4691,2,3,"""I see,""
Georg Brandlcd9f1202011-07-06 07:31:38 +0200470said the blind man","as he picked up his
Skip Montanarob4a04172003-03-20 23:29:12 +0000471hammer and saw"
4729,8,7,6'''
473 self.readerAssertEqual(input,
Tim Peters0eadaac2003-04-24 16:02:54 +0000474 [['1', '2', '3',
Georg Brandlcd9f1202011-07-06 07:31:38 +0200475 '"I see,"\nsaid the blind man',
Skip Montanarob4a04172003-03-20 23:29:12 +0000476 'as he picked up his\nhammer and saw'],
477 ['9','8','7','6']])
478
479 def test_dubious_quote(self):
480 self.readerAssertEqual('12,12,1",', [['12', '12', '1"', '']])
481
482 def test_null(self):
483 self.writerAssertEqual([], '')
484
Georg Brandl89fad142010-03-14 10:23:39 +0000485 def test_single_writer(self):
Skip Montanarob4a04172003-03-20 23:29:12 +0000486 self.writerAssertEqual([['abc']], 'abc\r\n')
487
Georg Brandl89fad142010-03-14 10:23:39 +0000488 def test_simple_writer(self):
Skip Montanarob4a04172003-03-20 23:29:12 +0000489 self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n')
490
491 def test_quotes(self):
492 self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n')
493
494 def test_quote_fieldsep(self):
495 self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
496
497 def test_newlines(self):
498 self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n')
499
500class EscapedExcel(csv.excel):
501 quoting = csv.QUOTE_NONE
502 escapechar = '\\'
503
504class TestEscapedExcel(TestCsvBase):
505 dialect = EscapedExcel()
506
507 def test_escape_fieldsep(self):
508 self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n')
509
510 def test_read_escape_fieldsep(self):
511 self.readerAssertEqual('abc\\,def\r\n', [['abc,def']])
512
Georg Brandl7424dd32010-10-27 07:27:06 +0000513class TestDialectUnix(TestCsvBase):
514 dialect = 'unix'
515
516 def test_simple_writer(self):
517 self.writerAssertEqual([[1, 'abc def', 'abc']], '"1","abc def","abc"\n')
518
519 def test_simple_reader(self):
520 self.readerAssertEqual('"1","abc def","abc"\n', [['1', 'abc def', 'abc']])
521
Skip Montanarob4a04172003-03-20 23:29:12 +0000522class QuotedEscapedExcel(csv.excel):
523 quoting = csv.QUOTE_NONNUMERIC
524 escapechar = '\\'
525
526class TestQuotedEscapedExcel(TestCsvBase):
527 dialect = QuotedEscapedExcel()
528
529 def test_write_escape_fieldsep(self):
530 self.writerAssertEqual([['abc,def']], '"abc,def"\r\n')
531
532 def test_read_escape_fieldsep(self):
533 self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']])
534
Skip Montanarob4a04172003-03-20 23:29:12 +0000535class TestDictFields(unittest.TestCase):
536 ### "long" means the row is longer than the number of fieldnames
537 ### "short" means there are fewer elements in the row than fieldnames
538 def test_write_simple_dict(self):
Guido van Rossumf0c74162007-08-28 03:29:45 +0000539 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000540 writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
R. David Murraybe0698b2010-02-23 22:57:58 +0000541 writer.writeheader()
542 fileobj.seek(0)
543 self.assertEqual(fileobj.readline(), "f1,f2,f3\r\n")
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000544 writer.writerow({"f1": 10, "f3": "abc"})
545 fileobj.seek(0)
R. David Murraybe0698b2010-02-23 22:57:58 +0000546 fileobj.readline() # header
Guido van Rossumf0c74162007-08-28 03:29:45 +0000547 self.assertEqual(fileobj.read(), "10,,abc\r\n")
Skip Montanarob4a04172003-03-20 23:29:12 +0000548
549 def test_write_no_fields(self):
550 fileobj = StringIO()
551 self.assertRaises(TypeError, csv.DictWriter, fileobj)
552
553 def test_read_dict_fields(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000554 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000555 fileobj.write("1,2,abc\r\n")
556 fileobj.seek(0)
557 reader = csv.DictReader(fileobj,
558 fieldnames=["f1", "f2", "f3"])
Georg Brandla18af4e2007-04-21 15:47:16 +0000559 self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
Skip Montanarob4a04172003-03-20 23:29:12 +0000560
Skip Montanarodffeed32003-10-03 14:03:01 +0000561 def test_read_dict_no_fieldnames(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000562 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000563 fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
564 fileobj.seek(0)
565 reader = csv.DictReader(fileobj)
Georg Brandla18af4e2007-04-21 15:47:16 +0000566 self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
Skip Montanaroaf8fcfa2008-08-09 19:44:22 +0000567 self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
568
569 # Two test cases to make sure existing ways of implicitly setting
570 # fieldnames continue to work. Both arise from discussion in issue3436.
571 def test_read_dict_fieldnames_from_file(self):
572 with TemporaryFile("w+") as fileobj:
573 fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
574 fileobj.seek(0)
575 reader = csv.DictReader(fileobj,
576 fieldnames=next(csv.reader(fileobj)))
577 self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
578 self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'})
579
580 def test_read_dict_fieldnames_chain(self):
581 import itertools
582 with TemporaryFile("w+") as fileobj:
583 fileobj.write("f1,f2,f3\r\n1,2,abc\r\n")
584 fileobj.seek(0)
585 reader = csv.DictReader(fileobj)
586 first = next(reader)
587 for row in itertools.chain([first], reader):
588 self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"])
589 self.assertEqual(row, {"f1": '1', "f2": '2', "f3": 'abc'})
Skip Montanarodffeed32003-10-03 14:03:01 +0000590
Skip Montanarob4a04172003-03-20 23:29:12 +0000591 def test_read_long(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000592 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000593 fileobj.write("1,2,abc,4,5,6\r\n")
594 fileobj.seek(0)
595 reader = csv.DictReader(fileobj,
596 fieldnames=["f1", "f2"])
Georg Brandla18af4e2007-04-21 15:47:16 +0000597 self.assertEqual(next(reader), {"f1": '1', "f2": '2',
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000598 None: ["abc", "4", "5", "6"]})
Skip Montanarob4a04172003-03-20 23:29:12 +0000599
600 def test_read_long_with_rest(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000601 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000602 fileobj.write("1,2,abc,4,5,6\r\n")
603 fileobj.seek(0)
604 reader = csv.DictReader(fileobj,
605 fieldnames=["f1", "f2"], restkey="_rest")
Georg Brandla18af4e2007-04-21 15:47:16 +0000606 self.assertEqual(next(reader), {"f1": '1', "f2": '2',
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000607 "_rest": ["abc", "4", "5", "6"]})
Skip Montanarob4a04172003-03-20 23:29:12 +0000608
Skip Montanarodffeed32003-10-03 14:03:01 +0000609 def test_read_long_with_rest_no_fieldnames(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000610 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000611 fileobj.write("f1,f2\r\n1,2,abc,4,5,6\r\n")
612 fileobj.seek(0)
613 reader = csv.DictReader(fileobj, restkey="_rest")
Skip Montanaroaf8fcfa2008-08-09 19:44:22 +0000614 self.assertEqual(reader.fieldnames, ["f1", "f2"])
Georg Brandla18af4e2007-04-21 15:47:16 +0000615 self.assertEqual(next(reader), {"f1": '1', "f2": '2',
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000616 "_rest": ["abc", "4", "5", "6"]})
Skip Montanarodffeed32003-10-03 14:03:01 +0000617
Skip Montanarob4a04172003-03-20 23:29:12 +0000618 def test_read_short(self):
Guido van Rossum46264582007-08-06 19:32:18 +0000619 with TemporaryFile("w+") as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000620 fileobj.write("1,2,abc,4,5,6\r\n1,2,abc\r\n")
621 fileobj.seek(0)
622 reader = csv.DictReader(fileobj,
623 fieldnames="1 2 3 4 5 6".split(),
624 restval="DEFAULT")
Georg Brandla18af4e2007-04-21 15:47:16 +0000625 self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000626 "4": '4', "5": '5', "6": '6'})
Georg Brandla18af4e2007-04-21 15:47:16 +0000627 self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000628 "4": 'DEFAULT', "5": 'DEFAULT',
629 "6": 'DEFAULT'})
Skip Montanarob4a04172003-03-20 23:29:12 +0000630
Skip Montanaro1546bc42003-06-12 02:40:22 +0000631 def test_read_multi(self):
632 sample = [
633 '2147483648,43.0e12,17,abc,def\r\n',
634 '147483648,43.0e2,17,abc,def\r\n',
635 '47483648,43.0,170,abc,def\r\n'
636 ]
637
638 reader = csv.DictReader(sample,
639 fieldnames="i1 float i2 s1 s2".split())
Georg Brandla18af4e2007-04-21 15:47:16 +0000640 self.assertEqual(next(reader), {"i1": '2147483648',
Skip Montanaro1546bc42003-06-12 02:40:22 +0000641 "float": '43.0e12',
642 "i2": '17',
643 "s1": 'abc',
644 "s2": 'def'})
645
Skip Montanarob4a04172003-03-20 23:29:12 +0000646 def test_read_with_blanks(self):
647 reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n",
648 "1,2,abc,4,5,6\r\n"],
649 fieldnames="1 2 3 4 5 6".split())
Georg Brandla18af4e2007-04-21 15:47:16 +0000650 self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
Skip Montanarob4a04172003-03-20 23:29:12 +0000651 "4": '4', "5": '5', "6": '6'})
Georg Brandla18af4e2007-04-21 15:47:16 +0000652 self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
Skip Montanarob4a04172003-03-20 23:29:12 +0000653 "4": '4', "5": '5', "6": '6'})
654
Skip Montanaro3f7a9482003-09-06 19:52:12 +0000655 def test_read_semi_sep(self):
656 reader = csv.DictReader(["1;2;abc;4;5;6\r\n"],
657 fieldnames="1 2 3 4 5 6".split(),
658 delimiter=';')
Georg Brandla18af4e2007-04-21 15:47:16 +0000659 self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc',
Skip Montanaro3f7a9482003-09-06 19:52:12 +0000660 "4": '4', "5": '5', "6": '6'})
661
Skip Montanarob4a04172003-03-20 23:29:12 +0000662class TestArrayWrites(unittest.TestCase):
663 def test_int_write(self):
664 import array
665 contents = [(20-i) for i in range(20)]
666 a = array.array('i', contents)
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000667
Guido van Rossumf0c74162007-08-28 03:29:45 +0000668 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000669 writer = csv.writer(fileobj, dialect="excel")
670 writer.writerow(a)
671 expected = ",".join([str(i) for i in a])+"\r\n"
672 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000673 self.assertEqual(fileobj.read(), expected)
Skip Montanarob4a04172003-03-20 23:29:12 +0000674
675 def test_double_write(self):
676 import array
677 contents = [(20-i)*0.1 for i in range(20)]
678 a = array.array('d', contents)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000679 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000680 writer = csv.writer(fileobj, dialect="excel")
681 writer.writerow(a)
682 expected = ",".join([str(i) for i in a])+"\r\n"
683 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000684 self.assertEqual(fileobj.read(), expected)
Skip Montanarob4a04172003-03-20 23:29:12 +0000685
686 def test_float_write(self):
687 import array
688 contents = [(20-i)*0.1 for i in range(20)]
689 a = array.array('f', contents)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000690 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000691 writer = csv.writer(fileobj, dialect="excel")
692 writer.writerow(a)
693 expected = ",".join([str(i) for i in a])+"\r\n"
694 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000695 self.assertEqual(fileobj.read(), expected)
Skip Montanarob4a04172003-03-20 23:29:12 +0000696
697 def test_char_write(self):
698 import array, string
Martin v. Löwis967f1e32007-08-14 09:23:10 +0000699 a = array.array('u', string.ascii_letters)
Guido van Rossum46264582007-08-06 19:32:18 +0000700
Guido van Rossumf0c74162007-08-28 03:29:45 +0000701 with TemporaryFile("w+", newline='') as fileobj:
Skip Montanaro58fc5d082004-06-05 17:03:20 +0000702 writer = csv.writer(fileobj, dialect="excel")
703 writer.writerow(a)
704 expected = ",".join(a)+"\r\n"
705 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000706 self.assertEqual(fileobj.read(), expected)
Skip Montanarob4a04172003-03-20 23:29:12 +0000707
708class TestDialectValidity(unittest.TestCase):
709 def test_quoting(self):
710 class mydialect(csv.Dialect):
711 delimiter = ";"
712 escapechar = '\\'
713 doublequote = False
714 skipinitialspace = True
715 lineterminator = '\r\n'
716 quoting = csv.QUOTE_NONE
717 d = mydialect()
718
719 mydialect.quoting = None
720 self.assertRaises(csv.Error, mydialect)
721
Skip Montanarob4a04172003-03-20 23:29:12 +0000722 mydialect.doublequote = True
723 mydialect.quoting = csv.QUOTE_ALL
724 mydialect.quotechar = '"'
725 d = mydialect()
726
727 mydialect.quotechar = "''"
728 self.assertRaises(csv.Error, mydialect)
729
730 mydialect.quotechar = 4
731 self.assertRaises(csv.Error, mydialect)
732
733 def test_delimiter(self):
734 class mydialect(csv.Dialect):
735 delimiter = ";"
736 escapechar = '\\'
737 doublequote = False
738 skipinitialspace = True
739 lineterminator = '\r\n'
740 quoting = csv.QUOTE_NONE
741 d = mydialect()
742
743 mydialect.delimiter = ":::"
744 self.assertRaises(csv.Error, mydialect)
745
746 mydialect.delimiter = 4
747 self.assertRaises(csv.Error, mydialect)
748
749 def test_lineterminator(self):
750 class mydialect(csv.Dialect):
751 delimiter = ";"
752 escapechar = '\\'
753 doublequote = False
754 skipinitialspace = True
755 lineterminator = '\r\n'
756 quoting = csv.QUOTE_NONE
757 d = mydialect()
758
759 mydialect.lineterminator = ":::"
760 d = mydialect()
761
762 mydialect.lineterminator = 4
763 self.assertRaises(csv.Error, mydialect)
764
765
Skip Montanaro48816c62003-04-25 14:43:14 +0000766class TestSniffer(unittest.TestCase):
767 sample1 = """\
768Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes
769Shark City, Glendale Heights, IL, 12/28/02, Prezence
770Tommy's Place, Blue Island, IL, 12/28/02, Blue Sunday/White Crow
771Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
772"""
773 sample2 = """\
774'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes'
775'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence'
776'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow'
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000777'Stonecutters ''Seafood'' and Chop House':'Lemont':'IL':'12/19/02':'Week Back'
Skip Montanaro48816c62003-04-25 14:43:14 +0000778"""
Skip Montanaro48816c62003-04-25 14:43:14 +0000779 header = '''\
780"venue","city","state","date","performers"
781'''
Skip Montanaro77892372003-05-19 15:33:36 +0000782 sample3 = '''\
78305/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
78405/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
78505/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03
786'''
787
Skip Montanaro1546bc42003-06-12 02:40:22 +0000788 sample4 = '''\
7892147483648;43.0e12;17;abc;def
790147483648;43.0e2;17;abc;def
79147483648;43.0;170;abc;def
792'''
793
Skip Montanaro91bb70c2005-12-28 15:37:25 +0000794 sample5 = "aaa\tbbb\r\nAAA\t\r\nBBB\t\r\n"
Skip Montanaro39b29be2005-12-30 05:09:48 +0000795 sample6 = "a|b|c\r\nd|e|f\r\n"
796 sample7 = "'a'|'b'|'c'\r\n'd'|e|f\r\n"
Skip Montanaro91bb70c2005-12-28 15:37:25 +0000797
Skip Montanaro48816c62003-04-25 14:43:14 +0000798 def test_has_header(self):
799 sniffer = csv.Sniffer()
800 self.assertEqual(sniffer.has_header(self.sample1), False)
801 self.assertEqual(sniffer.has_header(self.header+self.sample1), True)
802
803 def test_sniff(self):
804 sniffer = csv.Sniffer()
805 dialect = sniffer.sniff(self.sample1)
806 self.assertEqual(dialect.delimiter, ",")
807 self.assertEqual(dialect.quotechar, '"')
808 self.assertEqual(dialect.skipinitialspace, True)
809
810 dialect = sniffer.sniff(self.sample2)
811 self.assertEqual(dialect.delimiter, ":")
812 self.assertEqual(dialect.quotechar, "'")
813 self.assertEqual(dialect.skipinitialspace, False)
814
Skip Montanaro77892372003-05-19 15:33:36 +0000815 def test_delimiters(self):
816 sniffer = csv.Sniffer()
817 dialect = sniffer.sniff(self.sample3)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000818 # given that all three lines in sample3 are equal,
819 # I think that any character could have been 'guessed' as the
820 # delimiter, depending on dictionary order
Benjamin Peterson577473f2010-01-19 00:09:57 +0000821 self.assertIn(dialect.delimiter, self.sample3)
Skip Montanaro77892372003-05-19 15:33:36 +0000822 dialect = sniffer.sniff(self.sample3, delimiters="?,")
823 self.assertEqual(dialect.delimiter, "?")
824 dialect = sniffer.sniff(self.sample3, delimiters="/,")
825 self.assertEqual(dialect.delimiter, "/")
Skip Montanaro1546bc42003-06-12 02:40:22 +0000826 dialect = sniffer.sniff(self.sample4)
827 self.assertEqual(dialect.delimiter, ";")
Skip Montanaro91bb70c2005-12-28 15:37:25 +0000828 dialect = sniffer.sniff(self.sample5)
829 self.assertEqual(dialect.delimiter, "\t")
Skip Montanaro39b29be2005-12-30 05:09:48 +0000830 dialect = sniffer.sniff(self.sample6)
831 self.assertEqual(dialect.delimiter, "|")
832 dialect = sniffer.sniff(self.sample7)
833 self.assertEqual(dialect.delimiter, "|")
834 self.assertEqual(dialect.quotechar, "'")
Skip Montanaro77892372003-05-19 15:33:36 +0000835
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +0000836 def test_doublequote(self):
837 sniffer = csv.Sniffer()
838 dialect = sniffer.sniff(self.header)
839 self.assertFalse(dialect.doublequote)
840 dialect = sniffer.sniff(self.sample2)
841 self.assertTrue(dialect.doublequote)
842
Skip Montanarob4a04172003-03-20 23:29:12 +0000843if not hasattr(sys, "gettotalrefcount"):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000844 if support.verbose: print("*** skipping leakage tests ***")
Skip Montanarob4a04172003-03-20 23:29:12 +0000845else:
846 class NUL:
847 def write(s, *args):
848 pass
849 writelines = write
850
851 class TestLeaks(unittest.TestCase):
852 def test_create_read(self):
853 delta = 0
854 lastrc = sys.gettotalrefcount()
Guido van Rossum805365e2007-05-07 22:24:25 +0000855 for i in range(20):
Skip Montanarob4a04172003-03-20 23:29:12 +0000856 gc.collect()
857 self.assertEqual(gc.garbage, [])
858 rc = sys.gettotalrefcount()
859 csv.reader(["a,b,c\r\n"])
860 csv.reader(["a,b,c\r\n"])
861 csv.reader(["a,b,c\r\n"])
862 delta = rc-lastrc
863 lastrc = rc
864 # if csv.reader() leaks, last delta should be 3 or more
865 self.assertEqual(delta < 3, True)
866
867 def test_create_write(self):
868 delta = 0
869 lastrc = sys.gettotalrefcount()
870 s = NUL()
Guido van Rossum805365e2007-05-07 22:24:25 +0000871 for i in range(20):
Skip Montanarob4a04172003-03-20 23:29:12 +0000872 gc.collect()
873 self.assertEqual(gc.garbage, [])
874 rc = sys.gettotalrefcount()
875 csv.writer(s)
876 csv.writer(s)
877 csv.writer(s)
878 delta = rc-lastrc
879 lastrc = rc
880 # if csv.writer() leaks, last delta should be 3 or more
881 self.assertEqual(delta < 3, True)
882
883 def test_read(self):
884 delta = 0
885 rows = ["a,b,c\r\n"]*5
886 lastrc = sys.gettotalrefcount()
Guido van Rossum805365e2007-05-07 22:24:25 +0000887 for i in range(20):
Skip Montanarob4a04172003-03-20 23:29:12 +0000888 gc.collect()
889 self.assertEqual(gc.garbage, [])
890 rc = sys.gettotalrefcount()
891 rdr = csv.reader(rows)
892 for row in rdr:
893 pass
894 delta = rc-lastrc
895 lastrc = rc
896 # if reader leaks during read, delta should be 5 or more
897 self.assertEqual(delta < 5, True)
898
899 def test_write(self):
900 delta = 0
901 rows = [[1,2,3]]*5
902 s = NUL()
903 lastrc = sys.gettotalrefcount()
Guido van Rossum805365e2007-05-07 22:24:25 +0000904 for i in range(20):
Skip Montanarob4a04172003-03-20 23:29:12 +0000905 gc.collect()
906 self.assertEqual(gc.garbage, [])
907 rc = sys.gettotalrefcount()
908 writer = csv.writer(s)
909 for row in rows:
910 writer.writerow(row)
911 delta = rc-lastrc
912 lastrc = rc
913 # if writer leaks during write, last delta should be 5 or more
914 self.assertEqual(delta < 5, True)
915
Guido van Rossum46264582007-08-06 19:32:18 +0000916class TestUnicode(unittest.TestCase):
917
918 names = ["Martin von Löwis",
919 "Marc André Lemburg",
920 "Guido van Rossum",
921 "François Pinard"]
922
923 def test_unicode_read(self):
924 import io
Guido van Rossumf0c74162007-08-28 03:29:45 +0000925 with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
Guido van Rossum46264582007-08-06 19:32:18 +0000926 fileobj.write(",".join(self.names) + "\r\n")
Guido van Rossum46264582007-08-06 19:32:18 +0000927 fileobj.seek(0)
928 reader = csv.reader(fileobj)
929 self.assertEqual(list(reader), [self.names])
930
931
932 def test_unicode_write(self):
933 import io
Guido van Rossumf0c74162007-08-28 03:29:45 +0000934 with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj:
935 writer = csv.writer(fileobj)
Guido van Rossum46264582007-08-06 19:32:18 +0000936 writer.writerow(self.names)
937 expected = ",".join(self.names)+"\r\n"
938 fileobj.seek(0)
Guido van Rossumf0c74162007-08-28 03:29:45 +0000939 self.assertEqual(fileobj.read(), expected)
Guido van Rossum46264582007-08-06 19:32:18 +0000940
941
Skip Montanaro1a566652003-05-06 15:56:05 +0000942
Walter Dörwald21d3a322003-05-01 17:45:56 +0000943def test_main():
Skip Montanarob4a04172003-03-20 23:29:12 +0000944 mod = sys.modules[__name__]
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000945 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000946 *[getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
947 )
Skip Montanarob4a04172003-03-20 23:29:12 +0000948
949if __name__ == '__main__':
Walter Dörwald21d3a322003-05-01 17:45:56 +0000950 test_main()