Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1 | # Copyright (C) 2001,2002 Python Software Foundation |
| 2 | # csv package unit tests |
| 3 | |
Serhiy Storchaka | f81be8a | 2015-12-25 21:04:29 +0200 | [diff] [blame] | 4 | import copy |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 5 | import io |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 6 | import sys |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 7 | import os |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 8 | import unittest |
R. David Murray | 8b7d4aa | 2009-04-04 01:38:38 +0000 | [diff] [blame] | 9 | from io import StringIO |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 10 | from tempfile import TemporaryFile |
Skip Montanaro | 594adac | 2003-04-10 17:16:15 +0000 | [diff] [blame] | 11 | import csv |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 12 | import gc |
Serhiy Storchaka | f81be8a | 2015-12-25 21:04:29 +0200 | [diff] [blame] | 13 | import pickle |
Benjamin Peterson | ee8712c | 2008-05-20 21:35:26 +0000 | [diff] [blame] | 14 | from test import support |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 15 | |
| 16 | class Test_Csv(unittest.TestCase): |
| 17 | """ |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 18 | Test the underlying C csv parser in ways that are not appropriate |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 19 | from the high level interface. Further tests of this nature are done |
| 20 | in TestDialectRegistry. |
| 21 | """ |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 22 | def _test_arg_valid(self, ctor, arg): |
| 23 | self.assertRaises(TypeError, ctor) |
| 24 | self.assertRaises(TypeError, ctor, None) |
| 25 | self.assertRaises(TypeError, ctor, arg, bad_attr = 0) |
| 26 | self.assertRaises(TypeError, ctor, arg, delimiter = 0) |
| 27 | self.assertRaises(TypeError, ctor, arg, delimiter = 'XX') |
| 28 | self.assertRaises(csv.Error, ctor, arg, 'foo') |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 29 | self.assertRaises(TypeError, ctor, arg, delimiter=None) |
| 30 | self.assertRaises(TypeError, ctor, arg, delimiter=1) |
| 31 | self.assertRaises(TypeError, ctor, arg, quotechar=1) |
| 32 | self.assertRaises(TypeError, ctor, arg, lineterminator=None) |
| 33 | self.assertRaises(TypeError, ctor, arg, lineterminator=1) |
| 34 | self.assertRaises(TypeError, ctor, arg, quoting=None) |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 35 | self.assertRaises(TypeError, ctor, arg, |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 36 | quoting=csv.QUOTE_ALL, quotechar='') |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 37 | self.assertRaises(TypeError, ctor, arg, |
Andrew McNamara | 5d45a8d | 2005-01-12 08:16:17 +0000 | [diff] [blame] | 38 | quoting=csv.QUOTE_ALL, quotechar=None) |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 39 | |
| 40 | def test_reader_arg_valid(self): |
| 41 | self._test_arg_valid(csv.reader, []) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 42 | |
| 43 | def test_writer_arg_valid(self): |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 44 | self._test_arg_valid(csv.writer, StringIO()) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 45 | |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 46 | def _test_default_attrs(self, ctor, *args): |
| 47 | obj = ctor(*args) |
| 48 | # Check defaults |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 49 | self.assertEqual(obj.dialect.delimiter, ',') |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 50 | self.assertEqual(obj.dialect.doublequote, True) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 51 | self.assertEqual(obj.dialect.escapechar, None) |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 52 | self.assertEqual(obj.dialect.lineterminator, "\r\n") |
| 53 | self.assertEqual(obj.dialect.quotechar, '"') |
| 54 | self.assertEqual(obj.dialect.quoting, csv.QUOTE_MINIMAL) |
| 55 | self.assertEqual(obj.dialect.skipinitialspace, False) |
| 56 | self.assertEqual(obj.dialect.strict, False) |
| 57 | # Try deleting or changing attributes (they are read-only) |
Collin Winter | 42dae6a | 2007-03-28 21:44:53 +0000 | [diff] [blame] | 58 | self.assertRaises(AttributeError, delattr, obj.dialect, 'delimiter') |
| 59 | self.assertRaises(AttributeError, setattr, obj.dialect, 'delimiter', ':') |
Barry Warsaw | b180c06 | 2005-04-20 19:41:36 +0000 | [diff] [blame] | 60 | self.assertRaises(AttributeError, delattr, obj.dialect, 'quoting') |
| 61 | self.assertRaises(AttributeError, setattr, obj.dialect, |
| 62 | 'quoting', None) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 63 | |
| 64 | def test_reader_attrs(self): |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 65 | self._test_default_attrs(csv.reader, []) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 66 | |
| 67 | def test_writer_attrs(self): |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 68 | self._test_default_attrs(csv.writer, StringIO()) |
| 69 | |
| 70 | def _test_kw_attrs(self, ctor, *args): |
| 71 | # Now try with alternate options |
| 72 | kwargs = dict(delimiter=':', doublequote=False, escapechar='\\', |
| 73 | lineterminator='\r', quotechar='*', |
| 74 | quoting=csv.QUOTE_NONE, skipinitialspace=True, |
| 75 | strict=True) |
| 76 | obj = ctor(*args, **kwargs) |
| 77 | self.assertEqual(obj.dialect.delimiter, ':') |
| 78 | self.assertEqual(obj.dialect.doublequote, False) |
| 79 | self.assertEqual(obj.dialect.escapechar, '\\') |
| 80 | self.assertEqual(obj.dialect.lineterminator, "\r") |
| 81 | self.assertEqual(obj.dialect.quotechar, '*') |
| 82 | self.assertEqual(obj.dialect.quoting, csv.QUOTE_NONE) |
| 83 | self.assertEqual(obj.dialect.skipinitialspace, True) |
| 84 | self.assertEqual(obj.dialect.strict, True) |
| 85 | |
| 86 | def test_reader_kw_attrs(self): |
| 87 | self._test_kw_attrs(csv.reader, []) |
| 88 | |
| 89 | def test_writer_kw_attrs(self): |
| 90 | self._test_kw_attrs(csv.writer, StringIO()) |
| 91 | |
| 92 | def _test_dialect_attrs(self, ctor, *args): |
| 93 | # Now try with dialect-derived options |
| 94 | class dialect: |
| 95 | delimiter='-' |
| 96 | doublequote=False |
| 97 | escapechar='^' |
| 98 | lineterminator='$' |
| 99 | quotechar='#' |
| 100 | quoting=csv.QUOTE_ALL |
| 101 | skipinitialspace=True |
| 102 | strict=False |
| 103 | args = args + (dialect,) |
| 104 | obj = ctor(*args) |
| 105 | self.assertEqual(obj.dialect.delimiter, '-') |
| 106 | self.assertEqual(obj.dialect.doublequote, False) |
| 107 | self.assertEqual(obj.dialect.escapechar, '^') |
| 108 | self.assertEqual(obj.dialect.lineterminator, "$") |
| 109 | self.assertEqual(obj.dialect.quotechar, '#') |
| 110 | self.assertEqual(obj.dialect.quoting, csv.QUOTE_ALL) |
| 111 | self.assertEqual(obj.dialect.skipinitialspace, True) |
| 112 | self.assertEqual(obj.dialect.strict, False) |
| 113 | |
| 114 | def test_reader_dialect_attrs(self): |
| 115 | self._test_dialect_attrs(csv.reader, []) |
| 116 | |
| 117 | def test_writer_dialect_attrs(self): |
| 118 | self._test_dialect_attrs(csv.writer, StringIO()) |
| 119 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 120 | |
| 121 | def _write_test(self, fields, expect, **kwargs): |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 122 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 123 | writer = csv.writer(fileobj, **kwargs) |
| 124 | writer.writerow(fields) |
| 125 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 126 | self.assertEqual(fileobj.read(), |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 127 | expect + writer.dialect.lineterminator) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 128 | |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 129 | def _write_error_test(self, exc, fields, **kwargs): |
| 130 | with TemporaryFile("w+", newline='') as fileobj: |
| 131 | writer = csv.writer(fileobj, **kwargs) |
| 132 | with self.assertRaises(exc): |
| 133 | writer.writerow(fields) |
| 134 | fileobj.seek(0) |
| 135 | self.assertEqual(fileobj.read(), '') |
| 136 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 137 | def test_write_arg_valid(self): |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 138 | self._write_error_test(csv.Error, None) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 139 | self._write_test((), '') |
| 140 | self._write_test([None], '""') |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 141 | self._write_error_test(csv.Error, [None], quoting = csv.QUOTE_NONE) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 142 | # Check that exceptions are passed up the chain |
| 143 | class BadList: |
| 144 | def __len__(self): |
| 145 | return 10; |
| 146 | def __getitem__(self, i): |
| 147 | if i > 2: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 148 | raise OSError |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 149 | self._write_error_test(OSError, BadList()) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 150 | class BadItem: |
| 151 | def __str__(self): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 152 | raise OSError |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 153 | self._write_error_test(OSError, [BadItem()]) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 154 | |
| 155 | def test_write_bigfield(self): |
| 156 | # This exercises the buffer realloc functionality |
| 157 | bigstring = 'X' * 50000 |
| 158 | self._write_test([bigstring,bigstring], '%s,%s' % \ |
| 159 | (bigstring, bigstring)) |
| 160 | |
| 161 | def test_write_quoting(self): |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 162 | self._write_test(['a',1,'p,q'], 'a,1,"p,q"') |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 163 | self._write_error_test(csv.Error, ['a',1,'p,q'], |
| 164 | quoting = csv.QUOTE_NONE) |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 165 | self._write_test(['a',1,'p,q'], 'a,1,"p,q"', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 166 | quoting = csv.QUOTE_MINIMAL) |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 167 | self._write_test(['a',1,'p,q'], '"a",1,"p,q"', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 168 | quoting = csv.QUOTE_NONNUMERIC) |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 169 | self._write_test(['a',1,'p,q'], '"a","1","p,q"', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 170 | quoting = csv.QUOTE_ALL) |
R. David Murray | cde68cf | 2009-04-01 22:37:58 +0000 | [diff] [blame] | 171 | self._write_test(['a\nb',1], '"a\nb","1"', |
| 172 | quoting = csv.QUOTE_ALL) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 173 | |
| 174 | def test_write_escape(self): |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 175 | self._write_test(['a',1,'p,q'], 'a,1,"p,q"', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 176 | escapechar='\\') |
Serhiy Storchaka | 0b4e355 | 2015-03-25 19:16:15 +0200 | [diff] [blame] | 177 | self._write_error_test(csv.Error, ['a',1,'p,"q"'], |
| 178 | escapechar=None, doublequote=False) |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 179 | self._write_test(['a',1,'p,"q"'], 'a,1,"p,\\"q\\""', |
| 180 | escapechar='\\', doublequote = False) |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 181 | self._write_test(['"'], '""""', |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 182 | escapechar='\\', quoting = csv.QUOTE_MINIMAL) |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 183 | self._write_test(['"'], '\\"', |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 184 | escapechar='\\', quoting = csv.QUOTE_MINIMAL, |
| 185 | doublequote = False) |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 186 | self._write_test(['"'], '\\"', |
Andrew McNamara | c89f284 | 2005-01-12 07:44:42 +0000 | [diff] [blame] | 187 | escapechar='\\', quoting = csv.QUOTE_NONE) |
| 188 | self._write_test(['a',1,'p,q'], 'a,1,p\\,q', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 189 | escapechar='\\', quoting = csv.QUOTE_NONE) |
| 190 | |
Serhiy Storchaka | 7901b48 | 2015-03-30 09:09:54 +0300 | [diff] [blame] | 191 | def test_write_iterable(self): |
| 192 | self._write_test(iter(['a', 1, 'p,q']), 'a,1,"p,q"') |
| 193 | self._write_test(iter(['a', 1, None]), 'a,1,') |
| 194 | self._write_test(iter([]), '') |
| 195 | self._write_test(iter([None]), '""') |
| 196 | self._write_error_test(csv.Error, iter([None]), quoting=csv.QUOTE_NONE) |
| 197 | self._write_test(iter([None, None]), ',') |
| 198 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 199 | def test_writerows(self): |
| 200 | class BrokenFile: |
| 201 | def write(self, buf): |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 202 | raise OSError |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 203 | writer = csv.writer(BrokenFile()) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 204 | self.assertRaises(OSError, writer.writerows, [['a']]) |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 205 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 206 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 207 | writer = csv.writer(fileobj) |
| 208 | self.assertRaises(TypeError, writer.writerows, None) |
| 209 | writer.writerows([['a','b'],['c','d']]) |
| 210 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 211 | self.assertEqual(fileobj.read(), "a,b\r\nc,d\r\n") |
Tim Peters | 27f8836 | 2004-07-08 04:22:35 +0000 | [diff] [blame] | 212 | |
Stefan Krah | e6996ed | 2012-11-02 14:44:20 +0100 | [diff] [blame] | 213 | @support.cpython_only |
| 214 | def test_writerows_legacy_strings(self): |
| 215 | import _testcapi |
| 216 | |
| 217 | c = _testcapi.unicode_legacy_string('a') |
| 218 | with TemporaryFile("w+", newline='') as fileobj: |
| 219 | writer = csv.writer(fileobj) |
| 220 | writer.writerows([[c]]) |
| 221 | fileobj.seek(0) |
| 222 | self.assertEqual(fileobj.read(), "a\r\n") |
| 223 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 224 | def _read_test(self, input, expect, **kwargs): |
| 225 | reader = csv.reader(input, **kwargs) |
| 226 | result = list(reader) |
| 227 | self.assertEqual(result, expect) |
| 228 | |
| 229 | def test_read_oddinputs(self): |
| 230 | self._read_test([], []) |
| 231 | self._read_test([''], [[]]) |
| 232 | self.assertRaises(csv.Error, self._read_test, |
| 233 | ['"ab"c'], None, strict = 1) |
| 234 | # cannot handle null bytes for the moment |
| 235 | self.assertRaises(csv.Error, self._read_test, |
| 236 | ['ab\0c'], None, strict = 1) |
| 237 | self._read_test(['"ab"c'], [['abc']], doublequote = 0) |
| 238 | |
Amaury Forgeot d'Arc | 10c476d | 2007-11-19 21:20:21 +0000 | [diff] [blame] | 239 | self.assertRaises(csv.Error, self._read_test, |
| 240 | [b'ab\0c'], None) |
| 241 | |
| 242 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 243 | def test_read_eol(self): |
| 244 | self._read_test(['a,b'], [['a','b']]) |
| 245 | self._read_test(['a,b\n'], [['a','b']]) |
| 246 | self._read_test(['a,b\r\n'], [['a','b']]) |
| 247 | self._read_test(['a,b\r'], [['a','b']]) |
| 248 | self.assertRaises(csv.Error, self._read_test, ['a,b\rc,d'], []) |
| 249 | self.assertRaises(csv.Error, self._read_test, ['a,b\nc,d'], []) |
| 250 | self.assertRaises(csv.Error, self._read_test, ['a,b\r\nc,d'], []) |
| 251 | |
Senthil Kumaran | 67b7b98 | 2012-09-25 02:30:27 -0700 | [diff] [blame] | 252 | def test_read_eof(self): |
| 253 | self._read_test(['a,"'], [['a', '']]) |
| 254 | self._read_test(['"a'], [['a']]) |
| 255 | self._read_test(['^'], [['\n']], escapechar='^') |
| 256 | self.assertRaises(csv.Error, self._read_test, ['a,"'], [], strict=True) |
| 257 | self.assertRaises(csv.Error, self._read_test, ['"a'], [], strict=True) |
| 258 | self.assertRaises(csv.Error, self._read_test, |
| 259 | ['^'], [], escapechar='^', strict=True) |
| 260 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 261 | def test_read_escape(self): |
Andrew McNamara | 36a7691 | 2005-01-10 01:04:40 +0000 | [diff] [blame] | 262 | self._read_test(['a,\\b,c'], [['a', 'b', 'c']], escapechar='\\') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 263 | self._read_test(['a,b\\,c'], [['a', 'b,c']], escapechar='\\') |
| 264 | self._read_test(['a,"b\\,c"'], [['a', 'b,c']], escapechar='\\') |
Andrew McNamara | 36a7691 | 2005-01-10 01:04:40 +0000 | [diff] [blame] | 265 | self._read_test(['a,"b,\\c"'], [['a', 'b,c']], escapechar='\\') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 266 | self._read_test(['a,"b,c\\""'], [['a', 'b,c"']], escapechar='\\') |
| 267 | self._read_test(['a,"b,c"\\'], [['a', 'b,c\\']], escapechar='\\') |
| 268 | |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 269 | def test_read_quoting(self): |
| 270 | self._read_test(['1,",3,",5'], [['1', ',3,', '5']]) |
| 271 | self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']], |
| 272 | quotechar=None, escapechar='\\') |
| 273 | self._read_test(['1,",3,",5'], [['1', '"', '3', '"', '5']], |
| 274 | quoting=csv.QUOTE_NONE, escapechar='\\') |
Andrew McNamara | 0f0599d | 2005-01-12 09:45:18 +0000 | [diff] [blame] | 275 | # will this fail where locale uses comma for decimals? |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 276 | self._read_test([',3,"5",7.3, 9'], [['', 3, '5', 7.3, 9]], |
Andrew McNamara | 0f0599d | 2005-01-12 09:45:18 +0000 | [diff] [blame] | 277 | quoting=csv.QUOTE_NONNUMERIC) |
R. David Murray | cde68cf | 2009-04-01 22:37:58 +0000 | [diff] [blame] | 278 | self._read_test(['"a\nb", 7'], [['a\nb', ' 7']]) |
Tim Peters | 608c2ff | 2005-01-13 17:37:38 +0000 | [diff] [blame] | 279 | self.assertRaises(ValueError, self._read_test, |
Andrew McNamara | 0f0599d | 2005-01-12 09:45:18 +0000 | [diff] [blame] | 280 | ['abc,3'], [[]], |
| 281 | quoting=csv.QUOTE_NONNUMERIC) |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 282 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 283 | def test_read_bigfield(self): |
Andrew McNamara | e4d05c4 | 2005-01-11 07:32:02 +0000 | [diff] [blame] | 284 | # This exercises the buffer realloc functionality and field size |
| 285 | # limits. |
Andrew McNamara | 31d8896 | 2005-01-12 03:45:10 +0000 | [diff] [blame] | 286 | limit = csv.field_size_limit() |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 287 | try: |
| 288 | size = 50000 |
| 289 | bigstring = 'X' * size |
| 290 | bigline = '%s,%s' % (bigstring, bigstring) |
| 291 | self._read_test([bigline], [[bigstring, bigstring]]) |
Andrew McNamara | 31d8896 | 2005-01-12 03:45:10 +0000 | [diff] [blame] | 292 | csv.field_size_limit(size) |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 293 | self._read_test([bigline], [[bigstring, bigstring]]) |
Andrew McNamara | 31d8896 | 2005-01-12 03:45:10 +0000 | [diff] [blame] | 294 | self.assertEqual(csv.field_size_limit(), size) |
| 295 | csv.field_size_limit(size-1) |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 296 | self.assertRaises(csv.Error, self._read_test, [bigline], []) |
Andrew McNamara | 31d8896 | 2005-01-12 03:45:10 +0000 | [diff] [blame] | 297 | self.assertRaises(TypeError, csv.field_size_limit, None) |
| 298 | self.assertRaises(TypeError, csv.field_size_limit, 1, None) |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 299 | finally: |
Andrew McNamara | 31d8896 | 2005-01-12 03:45:10 +0000 | [diff] [blame] | 300 | csv.field_size_limit(limit) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 301 | |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 302 | def test_read_linenum(self): |
| 303 | r = csv.reader(['line,1', 'line,2', 'line,3']) |
| 304 | self.assertEqual(r.line_num, 0) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 305 | next(r) |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 306 | self.assertEqual(r.line_num, 1) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 307 | next(r) |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 308 | self.assertEqual(r.line_num, 2) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 309 | next(r) |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 310 | self.assertEqual(r.line_num, 3) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 311 | self.assertRaises(StopIteration, next, r) |
Andrew McNamara | 7f2053e | 2005-01-12 11:17:16 +0000 | [diff] [blame] | 312 | self.assertEqual(r.line_num, 3) |
| 313 | |
R. David Murray | cde68cf | 2009-04-01 22:37:58 +0000 | [diff] [blame] | 314 | def test_roundtrip_quoteed_newlines(self): |
| 315 | with TemporaryFile("w+", newline='') as fileobj: |
| 316 | writer = csv.writer(fileobj) |
| 317 | self.assertRaises(TypeError, writer.writerows, None) |
| 318 | rows = [['a\nb','b'],['c','x\r\nd']] |
| 319 | writer.writerows(rows) |
| 320 | fileobj.seek(0) |
| 321 | for i, row in enumerate(csv.reader(fileobj)): |
| 322 | self.assertEqual(row, rows[i]) |
| 323 | |
R David Murray | c7c42ef | 2013-03-19 22:41:47 -0400 | [diff] [blame] | 324 | def test_roundtrip_escaped_unquoted_newlines(self): |
| 325 | with TemporaryFile("w+", newline='') as fileobj: |
| 326 | writer = csv.writer(fileobj,quoting=csv.QUOTE_NONE,escapechar="\\") |
| 327 | rows = [['a\nb','b'],['c','x\r\nd']] |
| 328 | writer.writerows(rows) |
| 329 | fileobj.seek(0) |
| 330 | for i, row in enumerate(csv.reader(fileobj,quoting=csv.QUOTE_NONE,escapechar="\\")): |
| 331 | self.assertEqual(row,rows[i]) |
| 332 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 333 | class TestDialectRegistry(unittest.TestCase): |
| 334 | def test_registry_badargs(self): |
| 335 | self.assertRaises(TypeError, csv.list_dialects, None) |
| 336 | self.assertRaises(TypeError, csv.get_dialect) |
| 337 | self.assertRaises(csv.Error, csv.get_dialect, None) |
| 338 | self.assertRaises(csv.Error, csv.get_dialect, "nonesuch") |
| 339 | self.assertRaises(TypeError, csv.unregister_dialect) |
| 340 | self.assertRaises(csv.Error, csv.unregister_dialect, None) |
| 341 | self.assertRaises(csv.Error, csv.unregister_dialect, "nonesuch") |
| 342 | self.assertRaises(TypeError, csv.register_dialect, None) |
| 343 | self.assertRaises(TypeError, csv.register_dialect, None, None) |
Andrew McNamara | af1e312 | 2005-01-12 01:55:21 +0000 | [diff] [blame] | 344 | self.assertRaises(TypeError, csv.register_dialect, "nonesuch", 0, 0) |
| 345 | self.assertRaises(TypeError, csv.register_dialect, "nonesuch", |
| 346 | badargument=None) |
| 347 | self.assertRaises(TypeError, csv.register_dialect, "nonesuch", |
| 348 | quoting=None) |
| 349 | self.assertRaises(TypeError, csv.register_dialect, []) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 350 | |
| 351 | def test_registry(self): |
| 352 | class myexceltsv(csv.excel): |
| 353 | delimiter = "\t" |
| 354 | name = "myexceltsv" |
| 355 | expected_dialects = csv.list_dialects() + [name] |
| 356 | expected_dialects.sort() |
| 357 | csv.register_dialect(name, myexceltsv) |
Éric Araujo | 5137d64 | 2010-12-02 22:16:19 +0000 | [diff] [blame] | 358 | self.addCleanup(csv.unregister_dialect, name) |
| 359 | self.assertEqual(csv.get_dialect(name).delimiter, '\t') |
| 360 | got_dialects = sorted(csv.list_dialects()) |
| 361 | self.assertEqual(expected_dialects, got_dialects) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 362 | |
Andrew McNamara | 8662597 | 2005-01-11 01:28:33 +0000 | [diff] [blame] | 363 | def test_register_kwargs(self): |
| 364 | name = 'fedcba' |
| 365 | csv.register_dialect(name, delimiter=';') |
Éric Araujo | 5137d64 | 2010-12-02 22:16:19 +0000 | [diff] [blame] | 366 | self.addCleanup(csv.unregister_dialect, name) |
| 367 | self.assertEqual(csv.get_dialect(name).delimiter, ';') |
| 368 | self.assertEqual([['X', 'Y', 'Z']], list(csv.reader(['X;Y;Z'], name))) |
Andrew McNamara | 8662597 | 2005-01-11 01:28:33 +0000 | [diff] [blame] | 369 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 370 | def test_incomplete_dialect(self): |
| 371 | class myexceltsv(csv.Dialect): |
| 372 | delimiter = "\t" |
| 373 | self.assertRaises(csv.Error, myexceltsv) |
| 374 | |
| 375 | def test_space_dialect(self): |
| 376 | class space(csv.excel): |
| 377 | delimiter = " " |
| 378 | quoting = csv.QUOTE_NONE |
| 379 | escapechar = "\\" |
| 380 | |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 381 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 382 | fileobj.write("abc def\nc1ccccc1 benzene\n") |
| 383 | fileobj.seek(0) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 384 | reader = csv.reader(fileobj, dialect=space()) |
| 385 | self.assertEqual(next(reader), ["abc", "def"]) |
| 386 | self.assertEqual(next(reader), ["c1ccccc1", "benzene"]) |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 387 | |
| 388 | def compare_dialect_123(self, expected, *writeargs, **kwwriteargs): |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 389 | |
| 390 | with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj: |
| 391 | |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 392 | writer = csv.writer(fileobj, *writeargs, **kwwriteargs) |
| 393 | writer.writerow([1,2,3]) |
| 394 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 395 | self.assertEqual(fileobj.read(), expected) |
Tim Peters | 27f8836 | 2004-07-08 04:22:35 +0000 | [diff] [blame] | 396 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 397 | def test_dialect_apply(self): |
| 398 | class testA(csv.excel): |
| 399 | delimiter = "\t" |
| 400 | class testB(csv.excel): |
| 401 | delimiter = ":" |
| 402 | class testC(csv.excel): |
| 403 | delimiter = "|" |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 404 | class testUni(csv.excel): |
| 405 | delimiter = "\u039B" |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 406 | |
| 407 | csv.register_dialect('testC', testC) |
| 408 | try: |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 409 | self.compare_dialect_123("1,2,3\r\n") |
| 410 | self.compare_dialect_123("1\t2\t3\r\n", testA) |
| 411 | self.compare_dialect_123("1:2:3\r\n", dialect=testB()) |
| 412 | self.compare_dialect_123("1|2|3\r\n", dialect='testC') |
| 413 | self.compare_dialect_123("1;2;3\r\n", dialect=testA, |
| 414 | delimiter=';') |
| 415 | self.compare_dialect_123("1\u039B2\u039B3\r\n", |
| 416 | dialect=testUni) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 417 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 418 | finally: |
| 419 | csv.unregister_dialect('testC') |
| 420 | |
| 421 | def test_bad_dialect(self): |
| 422 | # Unknown parameter |
Andrew McNamara | 1196cf1 | 2005-01-07 04:42:45 +0000 | [diff] [blame] | 423 | self.assertRaises(TypeError, csv.reader, [], bad_attr = 0) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 424 | # Bad values |
| 425 | self.assertRaises(TypeError, csv.reader, [], delimiter = None) |
| 426 | self.assertRaises(TypeError, csv.reader, [], quoting = -1) |
| 427 | self.assertRaises(TypeError, csv.reader, [], quoting = 100) |
| 428 | |
Barry Warsaw | 09880c8 | 2016-01-11 15:14:53 -0500 | [diff] [blame] | 429 | # See issue #22995 |
| 430 | ## def test_copy(self): |
| 431 | ## for name in csv.list_dialects(): |
| 432 | ## dialect = csv.get_dialect(name) |
| 433 | ## self.assertRaises(TypeError, copy.copy, dialect) |
Serhiy Storchaka | f81be8a | 2015-12-25 21:04:29 +0200 | [diff] [blame] | 434 | |
Barry Warsaw | 09880c8 | 2016-01-11 15:14:53 -0500 | [diff] [blame] | 435 | ## def test_pickle(self): |
| 436 | ## for name in csv.list_dialects(): |
| 437 | ## dialect = csv.get_dialect(name) |
| 438 | ## for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 439 | ## self.assertRaises(TypeError, pickle.dumps, dialect, proto) |
Serhiy Storchaka | f81be8a | 2015-12-25 21:04:29 +0200 | [diff] [blame] | 440 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 441 | class TestCsvBase(unittest.TestCase): |
| 442 | def readerAssertEqual(self, input, expected_result): |
Amaury Forgeot d'Arc | 10c476d | 2007-11-19 21:20:21 +0000 | [diff] [blame] | 443 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 444 | fileobj.write(input) |
| 445 | fileobj.seek(0) |
| 446 | reader = csv.reader(fileobj, dialect = self.dialect) |
| 447 | fields = list(reader) |
| 448 | self.assertEqual(fields, expected_result) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 449 | |
| 450 | def writerAssertEqual(self, input, expected_result): |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 451 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 452 | writer = csv.writer(fileobj, dialect = self.dialect) |
| 453 | writer.writerows(input) |
| 454 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 455 | self.assertEqual(fileobj.read(), expected_result) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 456 | |
| 457 | class TestDialectExcel(TestCsvBase): |
| 458 | dialect = 'excel' |
| 459 | |
| 460 | def test_single(self): |
| 461 | self.readerAssertEqual('abc', [['abc']]) |
| 462 | |
| 463 | def test_simple(self): |
| 464 | self.readerAssertEqual('1,2,3,4,5', [['1','2','3','4','5']]) |
| 465 | |
| 466 | def test_blankline(self): |
| 467 | self.readerAssertEqual('', []) |
| 468 | |
| 469 | def test_empty_fields(self): |
| 470 | self.readerAssertEqual(',', [['', '']]) |
| 471 | |
| 472 | def test_singlequoted(self): |
| 473 | self.readerAssertEqual('""', [['']]) |
| 474 | |
| 475 | def test_singlequoted_left_empty(self): |
| 476 | self.readerAssertEqual('"",', [['','']]) |
| 477 | |
| 478 | def test_singlequoted_right_empty(self): |
| 479 | self.readerAssertEqual(',""', [['','']]) |
| 480 | |
| 481 | def test_single_quoted_quote(self): |
| 482 | self.readerAssertEqual('""""', [['"']]) |
| 483 | |
| 484 | def test_quoted_quotes(self): |
| 485 | self.readerAssertEqual('""""""', [['""']]) |
| 486 | |
| 487 | def test_inline_quote(self): |
| 488 | self.readerAssertEqual('a""b', [['a""b']]) |
| 489 | |
| 490 | def test_inline_quotes(self): |
| 491 | self.readerAssertEqual('a"b"c', [['a"b"c']]) |
| 492 | |
| 493 | def test_quotes_and_more(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 494 | # Excel would never write a field containing '"a"b', but when |
| 495 | # reading one, it will return 'ab'. |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 496 | self.readerAssertEqual('"a"b', [['ab']]) |
| 497 | |
| 498 | def test_lone_quote(self): |
| 499 | self.readerAssertEqual('a"b', [['a"b']]) |
| 500 | |
| 501 | def test_quote_and_quote(self): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 502 | # Excel would never write a field containing '"a" "b"', but when |
| 503 | # reading one, it will return 'a "b"'. |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 504 | self.readerAssertEqual('"a" "b"', [['a "b"']]) |
| 505 | |
| 506 | def test_space_and_quote(self): |
| 507 | self.readerAssertEqual(' "a"', [[' "a"']]) |
| 508 | |
| 509 | def test_quoted(self): |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 510 | self.readerAssertEqual('1,2,3,"I think, therefore I am",5,6', |
| 511 | [['1', '2', '3', |
| 512 | 'I think, therefore I am', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 513 | '5', '6']]) |
| 514 | |
| 515 | def test_quoted_quote(self): |
| 516 | self.readerAssertEqual('1,2,3,"""I see,"" said the blind man","as he picked up his hammer and saw"', |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 517 | [['1', '2', '3', |
| 518 | '"I see," said the blind man', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 519 | 'as he picked up his hammer and saw']]) |
| 520 | |
| 521 | def test_quoted_nl(self): |
| 522 | input = '''\ |
| 523 | 1,2,3,"""I see,"" |
| 524 | said the blind man","as he picked up his |
| 525 | hammer and saw" |
| 526 | 9,8,7,6''' |
| 527 | self.readerAssertEqual(input, |
Tim Peters | 0eadaac | 2003-04-24 16:02:54 +0000 | [diff] [blame] | 528 | [['1', '2', '3', |
| 529 | '"I see,"\nsaid the blind man', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 530 | 'as he picked up his\nhammer and saw'], |
| 531 | ['9','8','7','6']]) |
| 532 | |
| 533 | def test_dubious_quote(self): |
| 534 | self.readerAssertEqual('12,12,1",', [['12', '12', '1"', '']]) |
| 535 | |
| 536 | def test_null(self): |
| 537 | self.writerAssertEqual([], '') |
| 538 | |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 539 | def test_single_writer(self): |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 540 | self.writerAssertEqual([['abc']], 'abc\r\n') |
| 541 | |
Georg Brandl | 89fad14 | 2010-03-14 10:23:39 +0000 | [diff] [blame] | 542 | def test_simple_writer(self): |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 543 | self.writerAssertEqual([[1, 2, 'abc', 3, 4]], '1,2,abc,3,4\r\n') |
| 544 | |
| 545 | def test_quotes(self): |
| 546 | self.writerAssertEqual([[1, 2, 'a"bc"', 3, 4]], '1,2,"a""bc""",3,4\r\n') |
| 547 | |
| 548 | def test_quote_fieldsep(self): |
| 549 | self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') |
| 550 | |
| 551 | def test_newlines(self): |
| 552 | self.writerAssertEqual([[1, 2, 'a\nbc', 3, 4]], '1,2,"a\nbc",3,4\r\n') |
| 553 | |
| 554 | class EscapedExcel(csv.excel): |
| 555 | quoting = csv.QUOTE_NONE |
| 556 | escapechar = '\\' |
| 557 | |
| 558 | class TestEscapedExcel(TestCsvBase): |
| 559 | dialect = EscapedExcel() |
| 560 | |
| 561 | def test_escape_fieldsep(self): |
| 562 | self.writerAssertEqual([['abc,def']], 'abc\\,def\r\n') |
| 563 | |
| 564 | def test_read_escape_fieldsep(self): |
| 565 | self.readerAssertEqual('abc\\,def\r\n', [['abc,def']]) |
| 566 | |
Georg Brandl | 7424dd3 | 2010-10-27 07:27:06 +0000 | [diff] [blame] | 567 | class TestDialectUnix(TestCsvBase): |
| 568 | dialect = 'unix' |
| 569 | |
| 570 | def test_simple_writer(self): |
| 571 | self.writerAssertEqual([[1, 'abc def', 'abc']], '"1","abc def","abc"\n') |
| 572 | |
| 573 | def test_simple_reader(self): |
| 574 | self.readerAssertEqual('"1","abc def","abc"\n', [['1', 'abc def', 'abc']]) |
| 575 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 576 | class QuotedEscapedExcel(csv.excel): |
| 577 | quoting = csv.QUOTE_NONNUMERIC |
| 578 | escapechar = '\\' |
| 579 | |
| 580 | class TestQuotedEscapedExcel(TestCsvBase): |
| 581 | dialect = QuotedEscapedExcel() |
| 582 | |
| 583 | def test_write_escape_fieldsep(self): |
| 584 | self.writerAssertEqual([['abc,def']], '"abc,def"\r\n') |
| 585 | |
| 586 | def test_read_escape_fieldsep(self): |
| 587 | self.readerAssertEqual('"abc\\,def"\r\n', [['abc,def']]) |
| 588 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 589 | class TestDictFields(unittest.TestCase): |
| 590 | ### "long" means the row is longer than the number of fieldnames |
| 591 | ### "short" means there are fewer elements in the row than fieldnames |
| 592 | def test_write_simple_dict(self): |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 593 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 594 | writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"]) |
R. David Murray | be0698b | 2010-02-23 22:57:58 +0000 | [diff] [blame] | 595 | writer.writeheader() |
| 596 | fileobj.seek(0) |
| 597 | self.assertEqual(fileobj.readline(), "f1,f2,f3\r\n") |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 598 | writer.writerow({"f1": 10, "f3": "abc"}) |
| 599 | fileobj.seek(0) |
R. David Murray | be0698b | 2010-02-23 22:57:58 +0000 | [diff] [blame] | 600 | fileobj.readline() # header |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 601 | self.assertEqual(fileobj.read(), "10,,abc\r\n") |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 602 | |
Antoine Pitrou | 05da1ef | 2014-04-29 01:58:06 +0200 | [diff] [blame] | 603 | def test_write_multiple_dict_rows(self): |
| 604 | fileobj = StringIO() |
| 605 | writer = csv.DictWriter(fileobj, fieldnames=["f1", "f2", "f3"]) |
| 606 | writer.writeheader() |
| 607 | self.assertEqual(fileobj.getvalue(), "f1,f2,f3\r\n") |
| 608 | writer.writerows([{"f1": 1, "f2": "abc", "f3": "f"}, |
| 609 | {"f1": 2, "f2": 5, "f3": "xyz"}]) |
| 610 | self.assertEqual(fileobj.getvalue(), |
| 611 | "f1,f2,f3\r\n1,abc,f\r\n2,5,xyz\r\n") |
| 612 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 613 | def test_write_no_fields(self): |
| 614 | fileobj = StringIO() |
| 615 | self.assertRaises(TypeError, csv.DictWriter, fileobj) |
| 616 | |
R David Murray | fb099c9 | 2013-11-19 13:16:20 -0500 | [diff] [blame] | 617 | def test_write_fields_not_in_fieldnames(self): |
| 618 | with TemporaryFile("w+", newline='') as fileobj: |
| 619 | writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"]) |
| 620 | # Of special note is the non-string key (issue 19449) |
| 621 | with self.assertRaises(ValueError) as cx: |
| 622 | writer.writerow({"f4": 10, "f2": "spam", 1: "abc"}) |
| 623 | exception = str(cx.exception) |
| 624 | self.assertIn("fieldnames", exception) |
| 625 | self.assertIn("'f4'", exception) |
| 626 | self.assertNotIn("'f2'", exception) |
| 627 | self.assertIn("1", exception) |
| 628 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 629 | def test_read_dict_fields(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 630 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 631 | fileobj.write("1,2,abc\r\n") |
| 632 | fileobj.seek(0) |
| 633 | reader = csv.DictReader(fileobj, |
| 634 | fieldnames=["f1", "f2", "f3"]) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 635 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'}) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 636 | |
Skip Montanaro | dffeed3 | 2003-10-03 14:03:01 +0000 | [diff] [blame] | 637 | def test_read_dict_no_fieldnames(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 638 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 639 | fileobj.write("f1,f2,f3\r\n1,2,abc\r\n") |
| 640 | fileobj.seek(0) |
| 641 | reader = csv.DictReader(fileobj) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 642 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'}) |
Skip Montanaro | af8fcfa | 2008-08-09 19:44:22 +0000 | [diff] [blame] | 643 | self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"]) |
| 644 | |
| 645 | # Two test cases to make sure existing ways of implicitly setting |
| 646 | # fieldnames continue to work. Both arise from discussion in issue3436. |
| 647 | def test_read_dict_fieldnames_from_file(self): |
| 648 | with TemporaryFile("w+") as fileobj: |
| 649 | fileobj.write("f1,f2,f3\r\n1,2,abc\r\n") |
| 650 | fileobj.seek(0) |
| 651 | reader = csv.DictReader(fileobj, |
| 652 | fieldnames=next(csv.reader(fileobj))) |
| 653 | self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"]) |
| 654 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', "f3": 'abc'}) |
| 655 | |
| 656 | def test_read_dict_fieldnames_chain(self): |
| 657 | import itertools |
| 658 | with TemporaryFile("w+") as fileobj: |
| 659 | fileobj.write("f1,f2,f3\r\n1,2,abc\r\n") |
| 660 | fileobj.seek(0) |
| 661 | reader = csv.DictReader(fileobj) |
| 662 | first = next(reader) |
| 663 | for row in itertools.chain([first], reader): |
| 664 | self.assertEqual(reader.fieldnames, ["f1", "f2", "f3"]) |
| 665 | self.assertEqual(row, {"f1": '1', "f2": '2', "f3": 'abc'}) |
Skip Montanaro | dffeed3 | 2003-10-03 14:03:01 +0000 | [diff] [blame] | 666 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 667 | def test_read_long(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 668 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 669 | fileobj.write("1,2,abc,4,5,6\r\n") |
| 670 | fileobj.seek(0) |
| 671 | reader = csv.DictReader(fileobj, |
| 672 | fieldnames=["f1", "f2"]) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 673 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 674 | None: ["abc", "4", "5", "6"]}) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 675 | |
| 676 | def test_read_long_with_rest(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 677 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 678 | fileobj.write("1,2,abc,4,5,6\r\n") |
| 679 | fileobj.seek(0) |
| 680 | reader = csv.DictReader(fileobj, |
| 681 | fieldnames=["f1", "f2"], restkey="_rest") |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 682 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 683 | "_rest": ["abc", "4", "5", "6"]}) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 684 | |
Skip Montanaro | dffeed3 | 2003-10-03 14:03:01 +0000 | [diff] [blame] | 685 | def test_read_long_with_rest_no_fieldnames(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 686 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 687 | fileobj.write("f1,f2\r\n1,2,abc,4,5,6\r\n") |
| 688 | fileobj.seek(0) |
| 689 | reader = csv.DictReader(fileobj, restkey="_rest") |
Skip Montanaro | af8fcfa | 2008-08-09 19:44:22 +0000 | [diff] [blame] | 690 | self.assertEqual(reader.fieldnames, ["f1", "f2"]) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 691 | self.assertEqual(next(reader), {"f1": '1', "f2": '2', |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 692 | "_rest": ["abc", "4", "5", "6"]}) |
Skip Montanaro | dffeed3 | 2003-10-03 14:03:01 +0000 | [diff] [blame] | 693 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 694 | def test_read_short(self): |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 695 | with TemporaryFile("w+") as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 696 | fileobj.write("1,2,abc,4,5,6\r\n1,2,abc\r\n") |
| 697 | fileobj.seek(0) |
| 698 | reader = csv.DictReader(fileobj, |
| 699 | fieldnames="1 2 3 4 5 6".split(), |
| 700 | restval="DEFAULT") |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 701 | self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 702 | "4": '4', "5": '5', "6": '6'}) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 703 | self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 704 | "4": 'DEFAULT', "5": 'DEFAULT', |
| 705 | "6": 'DEFAULT'}) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 706 | |
Skip Montanaro | 1546bc4 | 2003-06-12 02:40:22 +0000 | [diff] [blame] | 707 | def test_read_multi(self): |
| 708 | sample = [ |
| 709 | '2147483648,43.0e12,17,abc,def\r\n', |
| 710 | '147483648,43.0e2,17,abc,def\r\n', |
| 711 | '47483648,43.0,170,abc,def\r\n' |
| 712 | ] |
| 713 | |
| 714 | reader = csv.DictReader(sample, |
| 715 | fieldnames="i1 float i2 s1 s2".split()) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 716 | self.assertEqual(next(reader), {"i1": '2147483648', |
Skip Montanaro | 1546bc4 | 2003-06-12 02:40:22 +0000 | [diff] [blame] | 717 | "float": '43.0e12', |
| 718 | "i2": '17', |
| 719 | "s1": 'abc', |
| 720 | "s2": 'def'}) |
| 721 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 722 | def test_read_with_blanks(self): |
| 723 | reader = csv.DictReader(["1,2,abc,4,5,6\r\n","\r\n", |
| 724 | "1,2,abc,4,5,6\r\n"], |
| 725 | fieldnames="1 2 3 4 5 6".split()) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 726 | self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 727 | "4": '4', "5": '5', "6": '6'}) |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 728 | self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 729 | "4": '4', "5": '5', "6": '6'}) |
| 730 | |
Skip Montanaro | 3f7a948 | 2003-09-06 19:52:12 +0000 | [diff] [blame] | 731 | def test_read_semi_sep(self): |
| 732 | reader = csv.DictReader(["1;2;abc;4;5;6\r\n"], |
| 733 | fieldnames="1 2 3 4 5 6".split(), |
| 734 | delimiter=';') |
Georg Brandl | a18af4e | 2007-04-21 15:47:16 +0000 | [diff] [blame] | 735 | self.assertEqual(next(reader), {"1": '1', "2": '2', "3": 'abc', |
Skip Montanaro | 3f7a948 | 2003-09-06 19:52:12 +0000 | [diff] [blame] | 736 | "4": '4', "5": '5', "6": '6'}) |
| 737 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 738 | class TestArrayWrites(unittest.TestCase): |
| 739 | def test_int_write(self): |
| 740 | import array |
| 741 | contents = [(20-i) for i in range(20)] |
| 742 | a = array.array('i', contents) |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 743 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 744 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 745 | writer = csv.writer(fileobj, dialect="excel") |
| 746 | writer.writerow(a) |
| 747 | expected = ",".join([str(i) for i in a])+"\r\n" |
| 748 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 749 | self.assertEqual(fileobj.read(), expected) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 750 | |
| 751 | def test_double_write(self): |
| 752 | import array |
| 753 | contents = [(20-i)*0.1 for i in range(20)] |
| 754 | a = array.array('d', contents) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 755 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 756 | writer = csv.writer(fileobj, dialect="excel") |
| 757 | writer.writerow(a) |
| 758 | expected = ",".join([str(i) for i in a])+"\r\n" |
| 759 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 760 | self.assertEqual(fileobj.read(), expected) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 761 | |
| 762 | def test_float_write(self): |
| 763 | import array |
| 764 | contents = [(20-i)*0.1 for i in range(20)] |
| 765 | a = array.array('f', contents) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 766 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 767 | writer = csv.writer(fileobj, dialect="excel") |
| 768 | writer.writerow(a) |
| 769 | expected = ",".join([str(i) for i in a])+"\r\n" |
| 770 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 771 | self.assertEqual(fileobj.read(), expected) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 772 | |
| 773 | def test_char_write(self): |
| 774 | import array, string |
Martin v. Löwis | 967f1e3 | 2007-08-14 09:23:10 +0000 | [diff] [blame] | 775 | a = array.array('u', string.ascii_letters) |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 776 | |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 777 | with TemporaryFile("w+", newline='') as fileobj: |
Skip Montanaro | 58fc5d08 | 2004-06-05 17:03:20 +0000 | [diff] [blame] | 778 | writer = csv.writer(fileobj, dialect="excel") |
| 779 | writer.writerow(a) |
| 780 | expected = ",".join(a)+"\r\n" |
| 781 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 782 | self.assertEqual(fileobj.read(), expected) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 783 | |
| 784 | class TestDialectValidity(unittest.TestCase): |
| 785 | def test_quoting(self): |
| 786 | class mydialect(csv.Dialect): |
| 787 | delimiter = ";" |
| 788 | escapechar = '\\' |
| 789 | doublequote = False |
| 790 | skipinitialspace = True |
| 791 | lineterminator = '\r\n' |
| 792 | quoting = csv.QUOTE_NONE |
| 793 | d = mydialect() |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 794 | self.assertEqual(d.quoting, csv.QUOTE_NONE) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 795 | |
| 796 | mydialect.quoting = None |
| 797 | self.assertRaises(csv.Error, mydialect) |
| 798 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 799 | mydialect.doublequote = True |
| 800 | mydialect.quoting = csv.QUOTE_ALL |
| 801 | mydialect.quotechar = '"' |
| 802 | d = mydialect() |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 803 | self.assertEqual(d.quoting, csv.QUOTE_ALL) |
| 804 | self.assertEqual(d.quotechar, '"') |
| 805 | self.assertTrue(d.doublequote) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 806 | |
| 807 | mydialect.quotechar = "''" |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 808 | with self.assertRaises(csv.Error) as cm: |
| 809 | mydialect() |
| 810 | self.assertEqual(str(cm.exception), |
Berker Peksag | 0f41acb | 2014-07-27 23:22:34 +0300 | [diff] [blame] | 811 | '"quotechar" must be a 1-character string') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 812 | |
| 813 | mydialect.quotechar = 4 |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 814 | with self.assertRaises(csv.Error) as cm: |
| 815 | mydialect() |
| 816 | self.assertEqual(str(cm.exception), |
| 817 | '"quotechar" must be string, not int') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 818 | |
| 819 | def test_delimiter(self): |
| 820 | class mydialect(csv.Dialect): |
| 821 | delimiter = ";" |
| 822 | escapechar = '\\' |
| 823 | doublequote = False |
| 824 | skipinitialspace = True |
| 825 | lineterminator = '\r\n' |
| 826 | quoting = csv.QUOTE_NONE |
| 827 | d = mydialect() |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 828 | self.assertEqual(d.delimiter, ";") |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 829 | |
| 830 | mydialect.delimiter = ":::" |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 831 | with self.assertRaises(csv.Error) as cm: |
| 832 | mydialect() |
| 833 | self.assertEqual(str(cm.exception), |
Berker Peksag | 0f41acb | 2014-07-27 23:22:34 +0300 | [diff] [blame] | 834 | '"delimiter" must be a 1-character string') |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 835 | |
| 836 | mydialect.delimiter = "" |
| 837 | with self.assertRaises(csv.Error) as cm: |
| 838 | mydialect() |
| 839 | self.assertEqual(str(cm.exception), |
Berker Peksag | 0f41acb | 2014-07-27 23:22:34 +0300 | [diff] [blame] | 840 | '"delimiter" must be a 1-character string') |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 841 | |
| 842 | mydialect.delimiter = b"," |
| 843 | with self.assertRaises(csv.Error) as cm: |
| 844 | mydialect() |
| 845 | self.assertEqual(str(cm.exception), |
| 846 | '"delimiter" must be string, not bytes') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 847 | |
| 848 | mydialect.delimiter = 4 |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 849 | with self.assertRaises(csv.Error) as cm: |
| 850 | mydialect() |
| 851 | self.assertEqual(str(cm.exception), |
| 852 | '"delimiter" must be string, not int') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 853 | |
| 854 | def test_lineterminator(self): |
| 855 | class mydialect(csv.Dialect): |
| 856 | delimiter = ";" |
| 857 | escapechar = '\\' |
| 858 | doublequote = False |
| 859 | skipinitialspace = True |
| 860 | lineterminator = '\r\n' |
| 861 | quoting = csv.QUOTE_NONE |
| 862 | d = mydialect() |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 863 | self.assertEqual(d.lineterminator, '\r\n') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 864 | |
| 865 | mydialect.lineterminator = ":::" |
| 866 | d = mydialect() |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 867 | self.assertEqual(d.lineterminator, ":::") |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 868 | |
| 869 | mydialect.lineterminator = 4 |
Serhiy Storchaka | cac23a5 | 2013-12-19 16:27:18 +0200 | [diff] [blame] | 870 | with self.assertRaises(csv.Error) as cm: |
| 871 | mydialect() |
| 872 | self.assertEqual(str(cm.exception), |
| 873 | '"lineterminator" must be a string') |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 874 | |
Victor Stinner | 6a31b0f | 2014-01-02 12:53:13 +0100 | [diff] [blame] | 875 | def test_invalid_chars(self): |
| 876 | def create_invalid(field_name, value): |
| 877 | class mydialect(csv.Dialect): |
| 878 | pass |
| 879 | setattr(mydialect, field_name, value) |
| 880 | d = mydialect() |
| 881 | |
| 882 | for field_name in ("delimiter", "escapechar", "quotechar"): |
Victor Stinner | 009771e | 2014-01-02 12:53:50 +0100 | [diff] [blame] | 883 | with self.subTest(field_name=field_name): |
| 884 | self.assertRaises(csv.Error, create_invalid, field_name, "") |
| 885 | self.assertRaises(csv.Error, create_invalid, field_name, "abc") |
| 886 | self.assertRaises(csv.Error, create_invalid, field_name, b'x') |
| 887 | self.assertRaises(csv.Error, create_invalid, field_name, 5) |
Victor Stinner | 6a31b0f | 2014-01-02 12:53:13 +0100 | [diff] [blame] | 888 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 889 | |
Skip Montanaro | 48816c6 | 2003-04-25 14:43:14 +0000 | [diff] [blame] | 890 | class TestSniffer(unittest.TestCase): |
| 891 | sample1 = """\ |
| 892 | Harry's, Arlington Heights, IL, 2/1/03, Kimi Hayes |
| 893 | Shark City, Glendale Heights, IL, 12/28/02, Prezence |
| 894 | Tommy's Place, Blue Island, IL, 12/28/02, Blue Sunday/White Crow |
| 895 | Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back |
| 896 | """ |
| 897 | sample2 = """\ |
| 898 | 'Harry''s':'Arlington Heights':'IL':'2/1/03':'Kimi Hayes' |
| 899 | 'Shark City':'Glendale Heights':'IL':'12/28/02':'Prezence' |
| 900 | 'Tommy''s Place':'Blue Island':'IL':'12/28/02':'Blue Sunday/White Crow' |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 901 | 'Stonecutters ''Seafood'' and Chop House':'Lemont':'IL':'12/19/02':'Week Back' |
Skip Montanaro | 48816c6 | 2003-04-25 14:43:14 +0000 | [diff] [blame] | 902 | """ |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 903 | header1 = '''\ |
Skip Montanaro | 48816c6 | 2003-04-25 14:43:14 +0000 | [diff] [blame] | 904 | "venue","city","state","date","performers" |
| 905 | ''' |
Skip Montanaro | 7789237 | 2003-05-19 15:33:36 +0000 | [diff] [blame] | 906 | sample3 = '''\ |
| 907 | 05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 |
| 908 | 05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 |
| 909 | 05/05/03?05/05/03?05/05/03?05/05/03?05/05/03?05/05/03 |
| 910 | ''' |
| 911 | |
Skip Montanaro | 1546bc4 | 2003-06-12 02:40:22 +0000 | [diff] [blame] | 912 | sample4 = '''\ |
| 913 | 2147483648;43.0e12;17;abc;def |
| 914 | 147483648;43.0e2;17;abc;def |
| 915 | 47483648;43.0;170;abc;def |
| 916 | ''' |
| 917 | |
Skip Montanaro | 91bb70c | 2005-12-28 15:37:25 +0000 | [diff] [blame] | 918 | sample5 = "aaa\tbbb\r\nAAA\t\r\nBBB\t\r\n" |
Skip Montanaro | 39b29be | 2005-12-30 05:09:48 +0000 | [diff] [blame] | 919 | sample6 = "a|b|c\r\nd|e|f\r\n" |
| 920 | sample7 = "'a'|'b'|'c'\r\n'd'|e|f\r\n" |
Skip Montanaro | 91bb70c | 2005-12-28 15:37:25 +0000 | [diff] [blame] | 921 | |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 922 | # Issue 18155: Use a delimiter that is a special char to regex: |
| 923 | |
| 924 | header2 = '''\ |
| 925 | "venue"+"city"+"state"+"date"+"performers" |
| 926 | ''' |
| 927 | sample8 = """\ |
| 928 | Harry's+ Arlington Heights+ IL+ 2/1/03+ Kimi Hayes |
| 929 | Shark City+ Glendale Heights+ IL+ 12/28/02+ Prezence |
| 930 | Tommy's Place+ Blue Island+ IL+ 12/28/02+ Blue Sunday/White Crow |
| 931 | Stonecutters Seafood and Chop House+ Lemont+ IL+ 12/19/02+ Week Back |
| 932 | """ |
| 933 | sample9 = """\ |
| 934 | 'Harry''s'+ Arlington Heights'+ 'IL'+ '2/1/03'+ 'Kimi Hayes' |
| 935 | 'Shark City'+ Glendale Heights'+' IL'+ '12/28/02'+ 'Prezence' |
| 936 | 'Tommy''s Place'+ Blue Island'+ 'IL'+ '12/28/02'+ 'Blue Sunday/White Crow' |
| 937 | 'Stonecutters ''Seafood'' and Chop House'+ 'Lemont'+ 'IL'+ '12/19/02'+ 'Week Back' |
| 938 | """ |
| 939 | |
Skip Montanaro | 48816c6 | 2003-04-25 14:43:14 +0000 | [diff] [blame] | 940 | def test_has_header(self): |
| 941 | sniffer = csv.Sniffer() |
| 942 | self.assertEqual(sniffer.has_header(self.sample1), False) |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 943 | self.assertEqual(sniffer.has_header(self.header1 + self.sample1), |
| 944 | True) |
| 945 | |
| 946 | def test_has_header_regex_special_delimiter(self): |
| 947 | sniffer = csv.Sniffer() |
| 948 | self.assertEqual(sniffer.has_header(self.sample8), False) |
| 949 | self.assertEqual(sniffer.has_header(self.header2 + self.sample8), |
| 950 | True) |
Skip Montanaro | 48816c6 | 2003-04-25 14:43:14 +0000 | [diff] [blame] | 951 | |
| 952 | def test_sniff(self): |
| 953 | sniffer = csv.Sniffer() |
| 954 | dialect = sniffer.sniff(self.sample1) |
| 955 | self.assertEqual(dialect.delimiter, ",") |
| 956 | self.assertEqual(dialect.quotechar, '"') |
| 957 | self.assertEqual(dialect.skipinitialspace, True) |
| 958 | |
| 959 | dialect = sniffer.sniff(self.sample2) |
| 960 | self.assertEqual(dialect.delimiter, ":") |
| 961 | self.assertEqual(dialect.quotechar, "'") |
| 962 | self.assertEqual(dialect.skipinitialspace, False) |
| 963 | |
Skip Montanaro | 7789237 | 2003-05-19 15:33:36 +0000 | [diff] [blame] | 964 | def test_delimiters(self): |
| 965 | sniffer = csv.Sniffer() |
| 966 | dialect = sniffer.sniff(self.sample3) |
Thomas Wouters | 4d70c3d | 2006-06-08 14:42:34 +0000 | [diff] [blame] | 967 | # given that all three lines in sample3 are equal, |
| 968 | # I think that any character could have been 'guessed' as the |
| 969 | # delimiter, depending on dictionary order |
Benjamin Peterson | 577473f | 2010-01-19 00:09:57 +0000 | [diff] [blame] | 970 | self.assertIn(dialect.delimiter, self.sample3) |
Skip Montanaro | 7789237 | 2003-05-19 15:33:36 +0000 | [diff] [blame] | 971 | dialect = sniffer.sniff(self.sample3, delimiters="?,") |
| 972 | self.assertEqual(dialect.delimiter, "?") |
| 973 | dialect = sniffer.sniff(self.sample3, delimiters="/,") |
| 974 | self.assertEqual(dialect.delimiter, "/") |
Skip Montanaro | 1546bc4 | 2003-06-12 02:40:22 +0000 | [diff] [blame] | 975 | dialect = sniffer.sniff(self.sample4) |
| 976 | self.assertEqual(dialect.delimiter, ";") |
Skip Montanaro | 91bb70c | 2005-12-28 15:37:25 +0000 | [diff] [blame] | 977 | dialect = sniffer.sniff(self.sample5) |
| 978 | self.assertEqual(dialect.delimiter, "\t") |
Skip Montanaro | 39b29be | 2005-12-30 05:09:48 +0000 | [diff] [blame] | 979 | dialect = sniffer.sniff(self.sample6) |
| 980 | self.assertEqual(dialect.delimiter, "|") |
| 981 | dialect = sniffer.sniff(self.sample7) |
| 982 | self.assertEqual(dialect.delimiter, "|") |
| 983 | self.assertEqual(dialect.quotechar, "'") |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 984 | dialect = sniffer.sniff(self.sample8) |
| 985 | self.assertEqual(dialect.delimiter, '+') |
| 986 | dialect = sniffer.sniff(self.sample9) |
| 987 | self.assertEqual(dialect.delimiter, '+') |
| 988 | self.assertEqual(dialect.quotechar, "'") |
Skip Montanaro | 7789237 | 2003-05-19 15:33:36 +0000 | [diff] [blame] | 989 | |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 990 | def test_doublequote(self): |
| 991 | sniffer = csv.Sniffer() |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 992 | dialect = sniffer.sniff(self.header1) |
| 993 | self.assertFalse(dialect.doublequote) |
| 994 | dialect = sniffer.sniff(self.header2) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 995 | self.assertFalse(dialect.doublequote) |
| 996 | dialect = sniffer.sniff(self.sample2) |
| 997 | self.assertTrue(dialect.doublequote) |
R David Murray | 925a322 | 2013-06-29 18:40:53 -0400 | [diff] [blame] | 998 | dialect = sniffer.sniff(self.sample8) |
| 999 | self.assertFalse(dialect.doublequote) |
| 1000 | dialect = sniffer.sniff(self.sample9) |
| 1001 | self.assertTrue(dialect.doublequote) |
Benjamin Peterson | 4ac9ce4 | 2009-10-04 14:49:41 +0000 | [diff] [blame] | 1002 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1003 | class NUL: |
| 1004 | def write(s, *args): |
| 1005 | pass |
| 1006 | writelines = write |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1007 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1008 | @unittest.skipUnless(hasattr(sys, "gettotalrefcount"), |
| 1009 | 'requires sys.gettotalrefcount()') |
| 1010 | class TestLeaks(unittest.TestCase): |
| 1011 | def test_create_read(self): |
| 1012 | delta = 0 |
| 1013 | lastrc = sys.gettotalrefcount() |
| 1014 | for i in range(20): |
| 1015 | gc.collect() |
| 1016 | self.assertEqual(gc.garbage, []) |
| 1017 | rc = sys.gettotalrefcount() |
| 1018 | csv.reader(["a,b,c\r\n"]) |
| 1019 | csv.reader(["a,b,c\r\n"]) |
| 1020 | csv.reader(["a,b,c\r\n"]) |
| 1021 | delta = rc-lastrc |
| 1022 | lastrc = rc |
| 1023 | # if csv.reader() leaks, last delta should be 3 or more |
| 1024 | self.assertEqual(delta < 3, True) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1025 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1026 | def test_create_write(self): |
| 1027 | delta = 0 |
| 1028 | lastrc = sys.gettotalrefcount() |
| 1029 | s = NUL() |
| 1030 | for i in range(20): |
| 1031 | gc.collect() |
| 1032 | self.assertEqual(gc.garbage, []) |
| 1033 | rc = sys.gettotalrefcount() |
| 1034 | csv.writer(s) |
| 1035 | csv.writer(s) |
| 1036 | csv.writer(s) |
| 1037 | delta = rc-lastrc |
| 1038 | lastrc = rc |
| 1039 | # if csv.writer() leaks, last delta should be 3 or more |
| 1040 | self.assertEqual(delta < 3, True) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1041 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1042 | def test_read(self): |
| 1043 | delta = 0 |
| 1044 | rows = ["a,b,c\r\n"]*5 |
| 1045 | lastrc = sys.gettotalrefcount() |
| 1046 | for i in range(20): |
| 1047 | gc.collect() |
| 1048 | self.assertEqual(gc.garbage, []) |
| 1049 | rc = sys.gettotalrefcount() |
| 1050 | rdr = csv.reader(rows) |
| 1051 | for row in rdr: |
| 1052 | pass |
| 1053 | delta = rc-lastrc |
| 1054 | lastrc = rc |
| 1055 | # if reader leaks during read, delta should be 5 or more |
| 1056 | self.assertEqual(delta < 5, True) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1057 | |
Serhiy Storchaka | 4376763 | 2013-11-03 21:31:38 +0200 | [diff] [blame] | 1058 | def test_write(self): |
| 1059 | delta = 0 |
| 1060 | rows = [[1,2,3]]*5 |
| 1061 | s = NUL() |
| 1062 | lastrc = sys.gettotalrefcount() |
| 1063 | for i in range(20): |
| 1064 | gc.collect() |
| 1065 | self.assertEqual(gc.garbage, []) |
| 1066 | rc = sys.gettotalrefcount() |
| 1067 | writer = csv.writer(s) |
| 1068 | for row in rows: |
| 1069 | writer.writerow(row) |
| 1070 | delta = rc-lastrc |
| 1071 | lastrc = rc |
| 1072 | # if writer leaks during write, last delta should be 5 or more |
| 1073 | self.assertEqual(delta < 5, True) |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1074 | |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 1075 | class TestUnicode(unittest.TestCase): |
| 1076 | |
| 1077 | names = ["Martin von Löwis", |
| 1078 | "Marc André Lemburg", |
| 1079 | "Guido van Rossum", |
| 1080 | "François Pinard"] |
| 1081 | |
| 1082 | def test_unicode_read(self): |
| 1083 | import io |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 1084 | with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj: |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 1085 | fileobj.write(",".join(self.names) + "\r\n") |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 1086 | fileobj.seek(0) |
| 1087 | reader = csv.reader(fileobj) |
| 1088 | self.assertEqual(list(reader), [self.names]) |
| 1089 | |
| 1090 | |
| 1091 | def test_unicode_write(self): |
| 1092 | import io |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 1093 | with TemporaryFile("w+", newline='', encoding="utf-8") as fileobj: |
| 1094 | writer = csv.writer(fileobj) |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 1095 | writer.writerow(self.names) |
| 1096 | expected = ",".join(self.names)+"\r\n" |
| 1097 | fileobj.seek(0) |
Guido van Rossum | f0c7416 | 2007-08-28 03:29:45 +0000 | [diff] [blame] | 1098 | self.assertEqual(fileobj.read(), expected) |
Guido van Rossum | 4626458 | 2007-08-06 19:32:18 +0000 | [diff] [blame] | 1099 | |
| 1100 | |
Skip Montanaro | b4a0417 | 2003-03-20 23:29:12 +0000 | [diff] [blame] | 1101 | if __name__ == '__main__': |
Zachary Ware | 38c707e | 2015-04-13 15:00:43 -0500 | [diff] [blame] | 1102 | unittest.main() |