blob: 8b7577b0205cde740c3a70d2b506077f3104f3d3 [file] [log] [blame]
Tim Peters3230d5c2001-07-11 22:21:17 +00001'''
2Tests for fileinput module.
3Nick Mathewson
4'''
Benjamin Petersoneb462882011-03-15 09:50:18 -05005import os
6import sys
7import re
briancurtin906f0c42011-03-15 10:29:41 -04008import fileinput
9import collections
Florent Xiclunaa011e2b2011-11-07 19:43:07 +010010import builtins
Serhiy Storchaka5f48e262018-06-05 12:08:36 +030011import tempfile
Benjamin Petersoneb462882011-03-15 09:50:18 -050012import unittest
13
briancurtinf84f3c32011-03-18 13:03:17 -050014try:
15 import bz2
16except ImportError:
17 bz2 = None
Ezio Melottic3afbb92011-05-14 10:10:53 +030018try:
19 import gzip
20except ImportError:
21 gzip = None
briancurtinf84f3c32011-03-18 13:03:17 -050022
Serhiy Storchaka946cfc32014-05-14 21:08:33 +030023from io import BytesIO, StringIO
Benjamin Petersoneb462882011-03-15 09:50:18 -050024from fileinput import FileInput, hook_encoded
Roy Williams002665a2017-05-22 22:24:17 -070025from pathlib import Path
Benjamin Petersoneb462882011-03-15 09:50:18 -050026
Serhiy Storchaka597d15a2016-04-24 13:45:58 +030027from test.support import verbose, TESTFN, check_warnings
Benjamin Petersoneb462882011-03-15 09:50:18 -050028from test.support import unlink as safe_unlink
Martin Panter7978e102016-01-16 06:26:54 +000029from test import support
Serhiy Storchaka946cfc32014-05-14 21:08:33 +030030from unittest import mock
Benjamin Petersoneb462882011-03-15 09:50:18 -050031
Tim Peters3230d5c2001-07-11 22:21:17 +000032
33# The fileinput module has 2 interfaces: the FileInput class which does
34# all the work, and a few functions (input, etc.) that use a global _state
briancurtin906f0c42011-03-15 10:29:41 -040035# variable.
Tim Peters3230d5c2001-07-11 22:21:17 +000036
Serhiy Storchaka5f48e262018-06-05 12:08:36 +030037class BaseTests:
38 # Write a content (str or bytes) to temp file, and return the
39 # temp file's name.
40 def writeTmp(self, content, *, mode='w'): # opening in text mode is the default
41 fd, name = tempfile.mkstemp()
42 self.addCleanup(support.unlink, name)
43 with open(fd, mode) as f:
44 f.write(content)
45 return name
Tim Peters3230d5c2001-07-11 22:21:17 +000046
Serhiy Storchakacc2dbc52016-03-08 18:28:36 +020047class LineReader:
48
49 def __init__(self):
50 self._linesread = []
51
52 @property
53 def linesread(self):
54 try:
55 return self._linesread[:]
56 finally:
57 self._linesread = []
58
59 def openhook(self, filename, mode):
60 self.it = iter(filename.splitlines(True))
61 return self
62
63 def readline(self, size=None):
64 line = next(self.it, '')
65 self._linesread.append(line)
66 return line
67
68 def readlines(self, hint=-1):
69 lines = []
70 size = 0
71 while True:
72 line = self.readline()
73 if not line:
74 return lines
75 lines.append(line)
76 size += len(line)
77 if size >= hint:
78 return lines
79
80 def close(self):
81 pass
82
Serhiy Storchaka5f48e262018-06-05 12:08:36 +030083class BufferSizesTests(BaseTests, unittest.TestCase):
Guido van Rossumd8faa362007-04-27 19:54:29 +000084 def test_buffer_sizes(self):
85 # First, run the tests with default and teeny buffer size.
86 for round, bs in (0, 0), (1, 30):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +030087 t1 = self.writeTmp(''.join("Line %s of file 1\n" % (i+1) for i in range(15)))
88 t2 = self.writeTmp(''.join("Line %s of file 2\n" % (i+1) for i in range(10)))
89 t3 = self.writeTmp(''.join("Line %s of file 3\n" % (i+1) for i in range(5)))
90 t4 = self.writeTmp(''.join("Line %s of file 4\n" % (i+1) for i in range(1)))
91 if bs:
92 with self.assertWarns(DeprecationWarning):
Serhiy Storchaka674e2d02016-03-08 18:35:19 +020093 self.buffer_size_test(t1, t2, t3, t4, bs, round)
Serhiy Storchaka5f48e262018-06-05 12:08:36 +030094 else:
95 self.buffer_size_test(t1, t2, t3, t4, bs, round)
Tim Peters3230d5c2001-07-11 22:21:17 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
98 pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
Tim Peters3230d5c2001-07-11 22:21:17 +000099
Guido van Rossumd8faa362007-04-27 19:54:29 +0000100 start = 1 + round*6
101 if verbose:
102 print('%s. Simple iteration (bs=%s)' % (start+0, bs))
103 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
Tim Peters3230d5c2001-07-11 22:21:17 +0000104 lines = list(fi)
Tim Peters3230d5c2001-07-11 22:21:17 +0000105 fi.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000106 self.assertEqual(len(lines), 31)
107 self.assertEqual(lines[4], 'Line 5 of file 1\n')
108 self.assertEqual(lines[30], 'Line 1 of file 4\n')
109 self.assertEqual(fi.lineno(), 31)
110 self.assertEqual(fi.filename(), t4)
Tim Peters3230d5c2001-07-11 22:21:17 +0000111
Guido van Rossumd8faa362007-04-27 19:54:29 +0000112 if verbose:
113 print('%s. Status variables (bs=%s)' % (start+1, bs))
114 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
115 s = "x"
116 while s and s != 'Line 6 of file 2\n':
117 s = fi.readline()
118 self.assertEqual(fi.filename(), t2)
119 self.assertEqual(fi.lineno(), 21)
120 self.assertEqual(fi.filelineno(), 6)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000121 self.assertFalse(fi.isfirstline())
122 self.assertFalse(fi.isstdin())
Tim Peters3230d5c2001-07-11 22:21:17 +0000123
Guido van Rossumd8faa362007-04-27 19:54:29 +0000124 if verbose:
125 print('%s. Nextfile (bs=%s)' % (start+2, bs))
126 fi.nextfile()
127 self.assertEqual(fi.readline(), 'Line 1 of file 3\n')
128 self.assertEqual(fi.lineno(), 22)
129 fi.close()
Tim Peters3230d5c2001-07-11 22:21:17 +0000130
Guido van Rossumd8faa362007-04-27 19:54:29 +0000131 if verbose:
132 print('%s. Stdin (bs=%s)' % (start+3, bs))
133 fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
134 savestdin = sys.stdin
135 try:
136 sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n")
137 lines = list(fi)
138 self.assertEqual(len(lines), 33)
139 self.assertEqual(lines[32], 'Line 2 of stdin\n')
140 self.assertEqual(fi.filename(), '<stdin>')
141 fi.nextfile()
142 finally:
143 sys.stdin = savestdin
Tim Peters3230d5c2001-07-11 22:21:17 +0000144
Guido van Rossumd8faa362007-04-27 19:54:29 +0000145 if verbose:
146 print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
147 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
148 self.assertEqual(fi.lineno(), 0)
149 self.assertEqual(fi.filename(), None)
150 fi.nextfile()
151 self.assertEqual(fi.lineno(), 0)
152 self.assertEqual(fi.filename(), None)
Tim Peters3230d5c2001-07-11 22:21:17 +0000153
Guido van Rossumd8faa362007-04-27 19:54:29 +0000154 if verbose:
155 print('%s. Inplace (bs=%s)' % (start+5, bs))
156 savestdout = sys.stdout
157 try:
158 fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
159 for line in fi:
160 line = line[:-1].upper()
161 print(line)
162 fi.close()
163 finally:
164 sys.stdout = savestdout
Tim Peters3230d5c2001-07-11 22:21:17 +0000165
Guido van Rossumd8faa362007-04-27 19:54:29 +0000166 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
167 for line in fi:
168 self.assertEqual(line[-1], '\n')
169 m = pat.match(line[:-1])
170 self.assertNotEqual(m, None)
171 self.assertEqual(int(m.group(1)), fi.filelineno())
172 fi.close()
Georg Brandle4662172006-02-19 09:51:27 +0000173
briancurtin906f0c42011-03-15 10:29:41 -0400174class UnconditionallyRaise:
175 def __init__(self, exception_type):
176 self.exception_type = exception_type
177 self.invoked = False
178 def __call__(self, *args, **kwargs):
179 self.invoked = True
180 raise self.exception_type()
181
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300182class FileInputTests(BaseTests, unittest.TestCase):
briancurtin906f0c42011-03-15 10:29:41 -0400183
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184 def test_zero_byte_files(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300185 t1 = self.writeTmp("")
186 t2 = self.writeTmp("")
187 t3 = self.writeTmp("The only line there is.\n")
188 t4 = self.writeTmp("")
189 fi = FileInput(files=(t1, t2, t3, t4))
Georg Brandl67e9fb92006-02-19 13:56:17 +0000190
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300191 line = fi.readline()
192 self.assertEqual(line, 'The only line there is.\n')
193 self.assertEqual(fi.lineno(), 1)
194 self.assertEqual(fi.filelineno(), 1)
195 self.assertEqual(fi.filename(), t3)
Georg Brandlc029f872006-02-19 14:12:34 +0000196
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300197 line = fi.readline()
198 self.assertFalse(line)
199 self.assertEqual(fi.lineno(), 1)
200 self.assertEqual(fi.filelineno(), 0)
201 self.assertEqual(fi.filename(), t4)
202 fi.close()
Georg Brandlc98eeed2006-02-19 14:57:47 +0000203
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204 def test_files_that_dont_end_with_newline(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300205 t1 = self.writeTmp("A\nB\nC")
206 t2 = self.writeTmp("D\nE\nF")
207 fi = FileInput(files=(t1, t2))
208 lines = list(fi)
209 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
210 self.assertEqual(fi.filelineno(), 3)
211 self.assertEqual(fi.lineno(), 6)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000213## def test_unicode_filenames(self):
214## # XXX A unicode string is always returned by writeTmp.
215## # So is this needed?
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300216## t1 = self.writeTmp("A\nB")
217## encoding = sys.getfilesystemencoding()
218## if encoding is None:
219## encoding = 'ascii'
220## fi = FileInput(files=str(t1, encoding))
221## lines = list(fi)
222## self.assertEqual(lines, ["A\n", "B"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
224 def test_fileno(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300225 t1 = self.writeTmp("A\nB")
226 t2 = self.writeTmp("C\nD")
227 fi = FileInput(files=(t1, t2))
228 self.assertEqual(fi.fileno(), -1)
229 line = next(fi)
230 self.assertNotEqual(fi.fileno(), -1)
231 fi.nextfile()
232 self.assertEqual(fi.fileno(), -1)
233 line = list(fi)
234 self.assertEqual(fi.fileno(), -1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000235
236 def test_opening_mode(self):
237 try:
238 # invalid mode, should raise ValueError
239 fi = FileInput(mode="w")
240 self.fail("FileInput should reject invalid mode argument")
241 except ValueError:
242 pass
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300243 # try opening in universal newline mode
244 t1 = self.writeTmp(b"A\nB\r\nC\rD", mode="wb")
245 with check_warnings(('', DeprecationWarning)):
246 fi = FileInput(files=t1, mode="U")
247 with check_warnings(('', DeprecationWarning)):
248 lines = list(fi)
249 self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
Serhiy Storchaka946cfc32014-05-14 21:08:33 +0300251 def test_stdin_binary_mode(self):
252 with mock.patch('sys.stdin') as m_stdin:
253 m_stdin.buffer = BytesIO(b'spam, bacon, sausage, and spam')
254 fi = FileInput(files=['-'], mode='rb')
255 lines = list(fi)
256 self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
257
R David Murray830207e2016-01-02 15:41:41 -0500258 def test_detached_stdin_binary_mode(self):
259 orig_stdin = sys.stdin
260 try:
261 sys.stdin = BytesIO(b'spam, bacon, sausage, and spam')
262 self.assertFalse(hasattr(sys.stdin, 'buffer'))
263 fi = FileInput(files=['-'], mode='rb')
264 lines = list(fi)
265 self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
266 finally:
267 sys.stdin = orig_stdin
268
Guido van Rossume22905a2007-08-27 23:09:25 +0000269 def test_file_opening_hook(self):
270 try:
271 # cannot use openhook and inplace mode
272 fi = FileInput(inplace=1, openhook=lambda f, m: None)
273 self.fail("FileInput should raise if both inplace "
274 "and openhook arguments are given")
275 except ValueError:
276 pass
277 try:
278 fi = FileInput(openhook=1)
279 self.fail("FileInput should check openhook for being callable")
280 except ValueError:
281 pass
briancurtin906f0c42011-03-15 10:29:41 -0400282
283 class CustomOpenHook:
284 def __init__(self):
285 self.invoked = False
286 def __call__(self, *args):
287 self.invoked = True
288 return open(*args)
289
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300290 t = self.writeTmp("\n")
briancurtin906f0c42011-03-15 10:29:41 -0400291 custom_open_hook = CustomOpenHook()
292 with FileInput([t], openhook=custom_open_hook) as fi:
293 fi.readline()
294 self.assertTrue(custom_open_hook.invoked, "openhook not invoked")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200296 def test_readline(self):
297 with open(TESTFN, 'wb') as f:
298 f.write(b'A\nB\r\nC\r')
299 # Fill TextIOWrapper buffer.
300 f.write(b'123456789\n' * 1000)
301 # Issue #20501: readline() shouldn't read whole file.
302 f.write(b'\x80')
303 self.addCleanup(safe_unlink, TESTFN)
304
305 with FileInput(files=TESTFN,
Serhiy Storchakacc2dbc52016-03-08 18:28:36 +0200306 openhook=hook_encoded('ascii')) as fi:
Serhiy Storchaka682ea5f2014-03-03 21:17:17 +0200307 try:
308 self.assertEqual(fi.readline(), 'A\n')
309 self.assertEqual(fi.readline(), 'B\n')
310 self.assertEqual(fi.readline(), 'C\n')
311 except UnicodeDecodeError:
312 self.fail('Read to end of file')
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200313 with self.assertRaises(UnicodeDecodeError):
314 # Read to the end of file.
315 list(fi)
Serhiy Storchaka314464d2015-11-01 16:43:58 +0200316 self.assertEqual(fi.readline(), '')
317 self.assertEqual(fi.readline(), '')
318
319 def test_readline_binary_mode(self):
320 with open(TESTFN, 'wb') as f:
321 f.write(b'A\nB\r\nC\rD')
322 self.addCleanup(safe_unlink, TESTFN)
323
324 with FileInput(files=TESTFN, mode='rb') as fi:
325 self.assertEqual(fi.readline(), b'A\n')
326 self.assertEqual(fi.readline(), b'B\r\n')
327 self.assertEqual(fi.readline(), b'C\rD')
328 # Read to the end of file.
329 self.assertEqual(fi.readline(), b'')
330 self.assertEqual(fi.readline(), b'')
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200331
Berker Peksagbe6dbfb2019-04-29 17:55:39 +0300332 def test_inplace_binary_write_mode(self):
333 temp_file = self.writeTmp(b'Initial text.', mode='wb')
334 with FileInput(temp_file, mode='rb', inplace=True) as fobj:
335 line = fobj.readline()
336 self.assertEqual(line, b'Initial text.')
337 # print() cannot be used with files opened in binary mode.
338 sys.stdout.write(b'New line.')
339 with open(temp_file, 'rb') as f:
340 self.assertEqual(f.read(), b'New line.')
341
Georg Brandl6cb7b652010-07-31 20:08:15 +0000342 def test_context_manager(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300343 t1 = self.writeTmp("A\nB\nC")
344 t2 = self.writeTmp("D\nE\nF")
345 with FileInput(files=(t1, t2)) as fi:
346 lines = list(fi)
347 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
348 self.assertEqual(fi.filelineno(), 3)
349 self.assertEqual(fi.lineno(), 6)
350 self.assertEqual(fi._files, ())
Georg Brandl6cb7b652010-07-31 20:08:15 +0000351
352 def test_close_on_exception(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300353 t1 = self.writeTmp("")
Georg Brandl6cb7b652010-07-31 20:08:15 +0000354 try:
Georg Brandl6cb7b652010-07-31 20:08:15 +0000355 with FileInput(files=t1) as fi:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200356 raise OSError
357 except OSError:
Georg Brandl6cb7b652010-07-31 20:08:15 +0000358 self.assertEqual(fi._files, ())
Georg Brandl6cb7b652010-07-31 20:08:15 +0000359
briancurtin906f0c42011-03-15 10:29:41 -0400360 def test_empty_files_list_specified_to_constructor(self):
361 with FileInput(files=[]) as fi:
Brett Cannond47af532011-03-15 15:55:12 -0400362 self.assertEqual(fi._files, ('-',))
briancurtin906f0c42011-03-15 10:29:41 -0400363
Berker Peksag84a13fb2018-08-11 09:05:04 +0300364 @support.ignore_warnings(category=DeprecationWarning)
briancurtin906f0c42011-03-15 10:29:41 -0400365 def test__getitem__(self):
366 """Tests invoking FileInput.__getitem__() with the current
367 line number"""
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300368 t = self.writeTmp("line1\nline2\n")
briancurtin906f0c42011-03-15 10:29:41 -0400369 with FileInput(files=[t]) as fi:
370 retval1 = fi[0]
371 self.assertEqual(retval1, "line1\n")
372 retval2 = fi[1]
373 self.assertEqual(retval2, "line2\n")
374
Berker Peksag84a13fb2018-08-11 09:05:04 +0300375 def test__getitem___deprecation(self):
376 t = self.writeTmp("line1\nline2\n")
377 with self.assertWarnsRegex(DeprecationWarning,
378 r'Use iterator protocol instead'):
379 with FileInput(files=[t]) as fi:
380 self.assertEqual(fi[0], "line1\n")
381
382 @support.ignore_warnings(category=DeprecationWarning)
briancurtin906f0c42011-03-15 10:29:41 -0400383 def test__getitem__invalid_key(self):
384 """Tests invoking FileInput.__getitem__() with an index unequal to
385 the line number"""
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300386 t = self.writeTmp("line1\nline2\n")
briancurtin906f0c42011-03-15 10:29:41 -0400387 with FileInput(files=[t]) as fi:
388 with self.assertRaises(RuntimeError) as cm:
389 fi[1]
Brett Cannond47af532011-03-15 15:55:12 -0400390 self.assertEqual(cm.exception.args, ("accessing lines out of order",))
briancurtin906f0c42011-03-15 10:29:41 -0400391
Berker Peksag84a13fb2018-08-11 09:05:04 +0300392 @support.ignore_warnings(category=DeprecationWarning)
briancurtin906f0c42011-03-15 10:29:41 -0400393 def test__getitem__eof(self):
394 """Tests invoking FileInput.__getitem__() with the line number but at
395 end-of-input"""
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300396 t = self.writeTmp('')
briancurtin906f0c42011-03-15 10:29:41 -0400397 with FileInput(files=[t]) as fi:
398 with self.assertRaises(IndexError) as cm:
399 fi[0]
Brett Cannond47af532011-03-15 15:55:12 -0400400 self.assertEqual(cm.exception.args, ("end of input reached",))
briancurtin906f0c42011-03-15 10:29:41 -0400401
402 def test_nextfile_oserror_deleting_backup(self):
403 """Tests invoking FileInput.nextfile() when the attempt to delete
404 the backup file would raise OSError. This error is expected to be
405 silently ignored"""
406
407 os_unlink_orig = os.unlink
408 os_unlink_replacement = UnconditionallyRaise(OSError)
409 try:
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300410 t = self.writeTmp("\n")
411 self.addCleanup(support.unlink, t + '.bak')
briancurtin906f0c42011-03-15 10:29:41 -0400412 with FileInput(files=[t], inplace=True) as fi:
413 next(fi) # make sure the file is opened
414 os.unlink = os_unlink_replacement
415 fi.nextfile()
416 finally:
417 os.unlink = os_unlink_orig
418
419 # sanity check to make sure that our test scenario was actually hit
420 self.assertTrue(os_unlink_replacement.invoked,
421 "os.unlink() was not invoked")
422
423 def test_readline_os_fstat_raises_OSError(self):
424 """Tests invoking FileInput.readline() when os.fstat() raises OSError.
425 This exception should be silently discarded."""
426
427 os_fstat_orig = os.fstat
428 os_fstat_replacement = UnconditionallyRaise(OSError)
429 try:
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300430 t = self.writeTmp("\n")
briancurtin906f0c42011-03-15 10:29:41 -0400431 with FileInput(files=[t], inplace=True) as fi:
432 os.fstat = os_fstat_replacement
433 fi.readline()
434 finally:
435 os.fstat = os_fstat_orig
436
437 # sanity check to make sure that our test scenario was actually hit
438 self.assertTrue(os_fstat_replacement.invoked,
439 "os.fstat() was not invoked")
440
briancurtin906f0c42011-03-15 10:29:41 -0400441 def test_readline_os_chmod_raises_OSError(self):
442 """Tests invoking FileInput.readline() when os.chmod() raises OSError.
443 This exception should be silently discarded."""
444
445 os_chmod_orig = os.chmod
446 os_chmod_replacement = UnconditionallyRaise(OSError)
447 try:
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300448 t = self.writeTmp("\n")
briancurtin906f0c42011-03-15 10:29:41 -0400449 with FileInput(files=[t], inplace=True) as fi:
450 os.chmod = os_chmod_replacement
451 fi.readline()
452 finally:
453 os.chmod = os_chmod_orig
454
455 # sanity check to make sure that our test scenario was actually hit
456 self.assertTrue(os_chmod_replacement.invoked,
457 "os.fstat() was not invoked")
458
459 def test_fileno_when_ValueError_raised(self):
460 class FilenoRaisesValueError(UnconditionallyRaise):
461 def __init__(self):
462 UnconditionallyRaise.__init__(self, ValueError)
463 def fileno(self):
464 self.__call__()
465
466 unconditionally_raise_ValueError = FilenoRaisesValueError()
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300467 t = self.writeTmp("\n")
briancurtin906f0c42011-03-15 10:29:41 -0400468 with FileInput(files=[t]) as fi:
469 file_backup = fi._file
470 try:
471 fi._file = unconditionally_raise_ValueError
472 result = fi.fileno()
473 finally:
474 fi._file = file_backup # make sure the file gets cleaned up
475
476 # sanity check to make sure that our test scenario was actually hit
477 self.assertTrue(unconditionally_raise_ValueError.invoked,
478 "_file.fileno() was not invoked")
479
480 self.assertEqual(result, -1, "fileno() should return -1")
481
Serhiy Storchakacc2dbc52016-03-08 18:28:36 +0200482 def test_readline_buffering(self):
483 src = LineReader()
484 with FileInput(files=['line1\nline2', 'line3\n'],
485 openhook=src.openhook) as fi:
486 self.assertEqual(src.linesread, [])
487 self.assertEqual(fi.readline(), 'line1\n')
488 self.assertEqual(src.linesread, ['line1\n'])
489 self.assertEqual(fi.readline(), 'line2')
490 self.assertEqual(src.linesread, ['line2'])
491 self.assertEqual(fi.readline(), 'line3\n')
492 self.assertEqual(src.linesread, ['', 'line3\n'])
493 self.assertEqual(fi.readline(), '')
494 self.assertEqual(src.linesread, [''])
495 self.assertEqual(fi.readline(), '')
496 self.assertEqual(src.linesread, [])
497
498 def test_iteration_buffering(self):
499 src = LineReader()
500 with FileInput(files=['line1\nline2', 'line3\n'],
501 openhook=src.openhook) as fi:
502 self.assertEqual(src.linesread, [])
503 self.assertEqual(next(fi), 'line1\n')
504 self.assertEqual(src.linesread, ['line1\n'])
505 self.assertEqual(next(fi), 'line2')
506 self.assertEqual(src.linesread, ['line2'])
507 self.assertEqual(next(fi), 'line3\n')
508 self.assertEqual(src.linesread, ['', 'line3\n'])
509 self.assertRaises(StopIteration, next, fi)
510 self.assertEqual(src.linesread, [''])
511 self.assertRaises(StopIteration, next, fi)
512 self.assertEqual(src.linesread, [])
513
Roy Williams002665a2017-05-22 22:24:17 -0700514 def test_pathlib_file(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300515 t1 = Path(self.writeTmp("Pathlib file."))
516 with FileInput(t1) as fi:
517 line = fi.readline()
518 self.assertEqual(line, 'Pathlib file.')
519 self.assertEqual(fi.lineno(), 1)
520 self.assertEqual(fi.filelineno(), 1)
521 self.assertEqual(fi.filename(), os.fspath(t1))
Roy Williams002665a2017-05-22 22:24:17 -0700522
Zhiming Wang06de1ae2017-09-05 01:37:24 +0800523 def test_pathlib_file_inplace(self):
Serhiy Storchaka5f48e262018-06-05 12:08:36 +0300524 t1 = Path(self.writeTmp('Pathlib file.'))
525 with FileInput(t1, inplace=True) as fi:
526 line = fi.readline()
527 self.assertEqual(line, 'Pathlib file.')
528 print('Modified %s' % line)
529 with open(t1) as f:
530 self.assertEqual(f.read(), 'Modified Pathlib file.\n')
Zhiming Wang06de1ae2017-09-05 01:37:24 +0800531
Roy Williams002665a2017-05-22 22:24:17 -0700532
briancurtin906f0c42011-03-15 10:29:41 -0400533class MockFileInput:
534 """A class that mocks out fileinput.FileInput for use during unit tests"""
535
536 def __init__(self, files=None, inplace=False, backup="", bufsize=0,
537 mode="r", openhook=None):
538 self.files = files
539 self.inplace = inplace
540 self.backup = backup
541 self.bufsize = bufsize
542 self.mode = mode
543 self.openhook = openhook
544 self._file = None
545 self.invocation_counts = collections.defaultdict(lambda: 0)
546 self.return_values = {}
547
548 def close(self):
549 self.invocation_counts["close"] += 1
550
551 def nextfile(self):
552 self.invocation_counts["nextfile"] += 1
553 return self.return_values["nextfile"]
554
555 def filename(self):
556 self.invocation_counts["filename"] += 1
557 return self.return_values["filename"]
558
559 def lineno(self):
560 self.invocation_counts["lineno"] += 1
561 return self.return_values["lineno"]
562
563 def filelineno(self):
564 self.invocation_counts["filelineno"] += 1
565 return self.return_values["filelineno"]
566
567 def fileno(self):
568 self.invocation_counts["fileno"] += 1
569 return self.return_values["fileno"]
570
571 def isfirstline(self):
572 self.invocation_counts["isfirstline"] += 1
573 return self.return_values["isfirstline"]
574
575 def isstdin(self):
576 self.invocation_counts["isstdin"] += 1
577 return self.return_values["isstdin"]
578
579class BaseFileInputGlobalMethodsTest(unittest.TestCase):
580 """Base class for unit tests for the global function of
581 the fileinput module."""
582
583 def setUp(self):
584 self._orig_state = fileinput._state
585 self._orig_FileInput = fileinput.FileInput
586 fileinput.FileInput = MockFileInput
587
588 def tearDown(self):
589 fileinput.FileInput = self._orig_FileInput
590 fileinput._state = self._orig_state
591
592 def assertExactlyOneInvocation(self, mock_file_input, method_name):
593 # assert that the method with the given name was invoked once
594 actual_count = mock_file_input.invocation_counts[method_name]
595 self.assertEqual(actual_count, 1, method_name)
596 # assert that no other unexpected methods were invoked
597 actual_total_count = len(mock_file_input.invocation_counts)
598 self.assertEqual(actual_total_count, 1)
599
600class Test_fileinput_input(BaseFileInputGlobalMethodsTest):
601 """Unit tests for fileinput.input()"""
602
603 def test_state_is_not_None_and_state_file_is_not_None(self):
604 """Tests invoking fileinput.input() when fileinput._state is not None
605 and its _file attribute is also not None. Expect RuntimeError to
606 be raised with a meaningful error message and for fileinput._state
607 to *not* be modified."""
608 instance = MockFileInput()
609 instance._file = object()
610 fileinput._state = instance
611 with self.assertRaises(RuntimeError) as cm:
612 fileinput.input()
613 self.assertEqual(("input() already active",), cm.exception.args)
614 self.assertIs(instance, fileinput._state, "fileinput._state")
615
616 def test_state_is_not_None_and_state_file_is_None(self):
617 """Tests invoking fileinput.input() when fileinput._state is not None
618 but its _file attribute *is* None. Expect it to create and return
619 a new fileinput.FileInput object with all method parameters passed
620 explicitly to the __init__() method; also ensure that
621 fileinput._state is set to the returned instance."""
622 instance = MockFileInput()
623 instance._file = None
624 fileinput._state = instance
625 self.do_test_call_input()
626
627 def test_state_is_None(self):
628 """Tests invoking fileinput.input() when fileinput._state is None
629 Expect it to create and return a new fileinput.FileInput object
630 with all method parameters passed explicitly to the __init__()
631 method; also ensure that fileinput._state is set to the returned
632 instance."""
633 fileinput._state = None
634 self.do_test_call_input()
635
636 def do_test_call_input(self):
637 """Tests that fileinput.input() creates a new fileinput.FileInput
638 object, passing the given parameters unmodified to
639 fileinput.FileInput.__init__(). Note that this test depends on the
640 monkey patching of fileinput.FileInput done by setUp()."""
641 files = object()
642 inplace = object()
643 backup = object()
644 bufsize = object()
645 mode = object()
646 openhook = object()
647
648 # call fileinput.input() with different values for each argument
649 result = fileinput.input(files=files, inplace=inplace, backup=backup,
650 bufsize=bufsize,
651 mode=mode, openhook=openhook)
652
653 # ensure fileinput._state was set to the returned object
654 self.assertIs(result, fileinput._state, "fileinput._state")
655
656 # ensure the parameters to fileinput.input() were passed directly
657 # to FileInput.__init__()
658 self.assertIs(files, result.files, "files")
659 self.assertIs(inplace, result.inplace, "inplace")
660 self.assertIs(backup, result.backup, "backup")
661 self.assertIs(bufsize, result.bufsize, "bufsize")
662 self.assertIs(mode, result.mode, "mode")
663 self.assertIs(openhook, result.openhook, "openhook")
664
665class Test_fileinput_close(BaseFileInputGlobalMethodsTest):
666 """Unit tests for fileinput.close()"""
667
668 def test_state_is_None(self):
669 """Tests that fileinput.close() does nothing if fileinput._state
670 is None"""
671 fileinput._state = None
672 fileinput.close()
673 self.assertIsNone(fileinput._state)
674
675 def test_state_is_not_None(self):
676 """Tests that fileinput.close() invokes close() on fileinput._state
677 and sets _state=None"""
678 instance = MockFileInput()
679 fileinput._state = instance
680 fileinput.close()
681 self.assertExactlyOneInvocation(instance, "close")
682 self.assertIsNone(fileinput._state)
683
684class Test_fileinput_nextfile(BaseFileInputGlobalMethodsTest):
685 """Unit tests for fileinput.nextfile()"""
686
687 def test_state_is_None(self):
688 """Tests fileinput.nextfile() when fileinput._state is None.
689 Ensure that it raises RuntimeError with a meaningful error message
690 and does not modify fileinput._state"""
691 fileinput._state = None
692 with self.assertRaises(RuntimeError) as cm:
693 fileinput.nextfile()
694 self.assertEqual(("no active input()",), cm.exception.args)
695 self.assertIsNone(fileinput._state)
696
697 def test_state_is_not_None(self):
698 """Tests fileinput.nextfile() when fileinput._state is not None.
699 Ensure that it invokes fileinput._state.nextfile() exactly once,
700 returns whatever it returns, and does not modify fileinput._state
701 to point to a different object."""
702 nextfile_retval = object()
703 instance = MockFileInput()
704 instance.return_values["nextfile"] = nextfile_retval
705 fileinput._state = instance
706 retval = fileinput.nextfile()
707 self.assertExactlyOneInvocation(instance, "nextfile")
708 self.assertIs(retval, nextfile_retval)
709 self.assertIs(fileinput._state, instance)
710
711class Test_fileinput_filename(BaseFileInputGlobalMethodsTest):
712 """Unit tests for fileinput.filename()"""
713
714 def test_state_is_None(self):
715 """Tests fileinput.filename() when fileinput._state is None.
716 Ensure that it raises RuntimeError with a meaningful error message
717 and does not modify fileinput._state"""
718 fileinput._state = None
719 with self.assertRaises(RuntimeError) as cm:
720 fileinput.filename()
721 self.assertEqual(("no active input()",), cm.exception.args)
722 self.assertIsNone(fileinput._state)
723
724 def test_state_is_not_None(self):
725 """Tests fileinput.filename() when fileinput._state is not None.
726 Ensure that it invokes fileinput._state.filename() exactly once,
727 returns whatever it returns, and does not modify fileinput._state
728 to point to a different object."""
729 filename_retval = object()
730 instance = MockFileInput()
731 instance.return_values["filename"] = filename_retval
732 fileinput._state = instance
733 retval = fileinput.filename()
734 self.assertExactlyOneInvocation(instance, "filename")
735 self.assertIs(retval, filename_retval)
736 self.assertIs(fileinput._state, instance)
737
738class Test_fileinput_lineno(BaseFileInputGlobalMethodsTest):
739 """Unit tests for fileinput.lineno()"""
740
741 def test_state_is_None(self):
742 """Tests fileinput.lineno() when fileinput._state is None.
743 Ensure that it raises RuntimeError with a meaningful error message
744 and does not modify fileinput._state"""
745 fileinput._state = None
746 with self.assertRaises(RuntimeError) as cm:
747 fileinput.lineno()
748 self.assertEqual(("no active input()",), cm.exception.args)
749 self.assertIsNone(fileinput._state)
750
751 def test_state_is_not_None(self):
752 """Tests fileinput.lineno() when fileinput._state is not None.
753 Ensure that it invokes fileinput._state.lineno() exactly once,
754 returns whatever it returns, and does not modify fileinput._state
755 to point to a different object."""
756 lineno_retval = object()
757 instance = MockFileInput()
758 instance.return_values["lineno"] = lineno_retval
759 fileinput._state = instance
760 retval = fileinput.lineno()
761 self.assertExactlyOneInvocation(instance, "lineno")
762 self.assertIs(retval, lineno_retval)
763 self.assertIs(fileinput._state, instance)
764
765class Test_fileinput_filelineno(BaseFileInputGlobalMethodsTest):
766 """Unit tests for fileinput.filelineno()"""
767
768 def test_state_is_None(self):
769 """Tests fileinput.filelineno() when fileinput._state is None.
770 Ensure that it raises RuntimeError with a meaningful error message
771 and does not modify fileinput._state"""
772 fileinput._state = None
773 with self.assertRaises(RuntimeError) as cm:
774 fileinput.filelineno()
775 self.assertEqual(("no active input()",), cm.exception.args)
776 self.assertIsNone(fileinput._state)
777
778 def test_state_is_not_None(self):
779 """Tests fileinput.filelineno() when fileinput._state is not None.
780 Ensure that it invokes fileinput._state.filelineno() exactly once,
781 returns whatever it returns, and does not modify fileinput._state
782 to point to a different object."""
783 filelineno_retval = object()
784 instance = MockFileInput()
785 instance.return_values["filelineno"] = filelineno_retval
786 fileinput._state = instance
787 retval = fileinput.filelineno()
788 self.assertExactlyOneInvocation(instance, "filelineno")
789 self.assertIs(retval, filelineno_retval)
790 self.assertIs(fileinput._state, instance)
791
792class Test_fileinput_fileno(BaseFileInputGlobalMethodsTest):
793 """Unit tests for fileinput.fileno()"""
794
795 def test_state_is_None(self):
796 """Tests fileinput.fileno() when fileinput._state is None.
797 Ensure that it raises RuntimeError with a meaningful error message
798 and does not modify fileinput._state"""
799 fileinput._state = None
800 with self.assertRaises(RuntimeError) as cm:
801 fileinput.fileno()
802 self.assertEqual(("no active input()",), cm.exception.args)
803 self.assertIsNone(fileinput._state)
804
805 def test_state_is_not_None(self):
806 """Tests fileinput.fileno() when fileinput._state is not None.
807 Ensure that it invokes fileinput._state.fileno() exactly once,
808 returns whatever it returns, and does not modify fileinput._state
809 to point to a different object."""
810 fileno_retval = object()
811 instance = MockFileInput()
812 instance.return_values["fileno"] = fileno_retval
813 instance.fileno_retval = fileno_retval
814 fileinput._state = instance
815 retval = fileinput.fileno()
816 self.assertExactlyOneInvocation(instance, "fileno")
817 self.assertIs(retval, fileno_retval)
818 self.assertIs(fileinput._state, instance)
819
820class Test_fileinput_isfirstline(BaseFileInputGlobalMethodsTest):
821 """Unit tests for fileinput.isfirstline()"""
822
823 def test_state_is_None(self):
824 """Tests fileinput.isfirstline() when fileinput._state is None.
825 Ensure that it raises RuntimeError with a meaningful error message
826 and does not modify fileinput._state"""
827 fileinput._state = None
828 with self.assertRaises(RuntimeError) as cm:
829 fileinput.isfirstline()
830 self.assertEqual(("no active input()",), cm.exception.args)
831 self.assertIsNone(fileinput._state)
832
833 def test_state_is_not_None(self):
834 """Tests fileinput.isfirstline() when fileinput._state is not None.
835 Ensure that it invokes fileinput._state.isfirstline() exactly once,
836 returns whatever it returns, and does not modify fileinput._state
837 to point to a different object."""
838 isfirstline_retval = object()
839 instance = MockFileInput()
840 instance.return_values["isfirstline"] = isfirstline_retval
841 fileinput._state = instance
842 retval = fileinput.isfirstline()
843 self.assertExactlyOneInvocation(instance, "isfirstline")
844 self.assertIs(retval, isfirstline_retval)
845 self.assertIs(fileinput._state, instance)
846
847class Test_fileinput_isstdin(BaseFileInputGlobalMethodsTest):
848 """Unit tests for fileinput.isstdin()"""
849
850 def test_state_is_None(self):
851 """Tests fileinput.isstdin() when fileinput._state is None.
852 Ensure that it raises RuntimeError with a meaningful error message
853 and does not modify fileinput._state"""
854 fileinput._state = None
855 with self.assertRaises(RuntimeError) as cm:
856 fileinput.isstdin()
857 self.assertEqual(("no active input()",), cm.exception.args)
858 self.assertIsNone(fileinput._state)
859
860 def test_state_is_not_None(self):
861 """Tests fileinput.isstdin() when fileinput._state is not None.
862 Ensure that it invokes fileinput._state.isstdin() exactly once,
863 returns whatever it returns, and does not modify fileinput._state
864 to point to a different object."""
865 isstdin_retval = object()
866 instance = MockFileInput()
867 instance.return_values["isstdin"] = isstdin_retval
868 fileinput._state = instance
869 retval = fileinput.isstdin()
870 self.assertExactlyOneInvocation(instance, "isstdin")
871 self.assertIs(retval, isstdin_retval)
872 self.assertIs(fileinput._state, instance)
873
874class InvocationRecorder:
875 def __init__(self):
876 self.invocation_count = 0
877 def __call__(self, *args, **kwargs):
878 self.invocation_count += 1
879 self.last_invocation = (args, kwargs)
880
881class Test_hook_compressed(unittest.TestCase):
882 """Unit tests for fileinput.hook_compressed()"""
883
884 def setUp(self):
885 self.fake_open = InvocationRecorder()
886
887 def test_empty_string(self):
888 self.do_test_use_builtin_open("", 1)
889
890 def test_no_ext(self):
891 self.do_test_use_builtin_open("abcd", 2)
892
Ezio Melottic3afbb92011-05-14 10:10:53 +0300893 @unittest.skipUnless(gzip, "Requires gzip and zlib")
briancurtin5eb35912011-03-15 10:59:36 -0400894 def test_gz_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400895 original_open = gzip.open
896 gzip.open = self.fake_open
897 try:
898 result = fileinput.hook_compressed("test.gz", 3)
899 finally:
900 gzip.open = original_open
901
902 self.assertEqual(self.fake_open.invocation_count, 1)
903 self.assertEqual(self.fake_open.last_invocation, (("test.gz", 3), {}))
904
briancurtinf84f3c32011-03-18 13:03:17 -0500905 @unittest.skipUnless(bz2, "Requires bz2")
briancurtin5eb35912011-03-15 10:59:36 -0400906 def test_bz2_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400907 original_open = bz2.BZ2File
908 bz2.BZ2File = self.fake_open
909 try:
910 result = fileinput.hook_compressed("test.bz2", 4)
911 finally:
912 bz2.BZ2File = original_open
913
914 self.assertEqual(self.fake_open.invocation_count, 1)
915 self.assertEqual(self.fake_open.last_invocation, (("test.bz2", 4), {}))
916
917 def test_blah_ext(self):
918 self.do_test_use_builtin_open("abcd.blah", 5)
919
briancurtin5eb35912011-03-15 10:59:36 -0400920 def test_gz_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400921 self.do_test_use_builtin_open("abcd.Gz", 6)
922
briancurtin5eb35912011-03-15 10:59:36 -0400923 def test_bz2_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400924 self.do_test_use_builtin_open("abcd.Bz2", 7)
925
926 def do_test_use_builtin_open(self, filename, mode):
927 original_open = self.replace_builtin_open(self.fake_open)
928 try:
929 result = fileinput.hook_compressed(filename, mode)
930 finally:
931 self.replace_builtin_open(original_open)
932
933 self.assertEqual(self.fake_open.invocation_count, 1)
934 self.assertEqual(self.fake_open.last_invocation,
935 ((filename, mode), {}))
936
937 @staticmethod
938 def replace_builtin_open(new_open_func):
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100939 original_open = builtins.open
940 builtins.open = new_open_func
briancurtin906f0c42011-03-15 10:29:41 -0400941 return original_open
942
943class Test_hook_encoded(unittest.TestCase):
944 """Unit tests for fileinput.hook_encoded()"""
945
946 def test(self):
947 encoding = object()
Serhiy Storchakab2752102016-04-27 23:13:46 +0300948 errors = object()
949 result = fileinput.hook_encoded(encoding, errors=errors)
briancurtin906f0c42011-03-15 10:29:41 -0400950
951 fake_open = InvocationRecorder()
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100952 original_open = builtins.open
953 builtins.open = fake_open
briancurtin906f0c42011-03-15 10:29:41 -0400954 try:
955 filename = object()
956 mode = object()
957 open_result = result(filename, mode)
958 finally:
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100959 builtins.open = original_open
briancurtin906f0c42011-03-15 10:29:41 -0400960
961 self.assertEqual(fake_open.invocation_count, 1)
962
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100963 args, kwargs = fake_open.last_invocation
briancurtin906f0c42011-03-15 10:29:41 -0400964 self.assertIs(args[0], filename)
965 self.assertIs(args[1], mode)
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100966 self.assertIs(kwargs.pop('encoding'), encoding)
Serhiy Storchakab2752102016-04-27 23:13:46 +0300967 self.assertIs(kwargs.pop('errors'), errors)
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100968 self.assertFalse(kwargs)
Georg Brandl6cb7b652010-07-31 20:08:15 +0000969
Serhiy Storchakab2752102016-04-27 23:13:46 +0300970 def test_errors(self):
971 with open(TESTFN, 'wb') as f:
972 f.write(b'\x80abc')
973 self.addCleanup(safe_unlink, TESTFN)
974
975 def check(errors, expected_lines):
976 with FileInput(files=TESTFN, mode='r',
977 openhook=hook_encoded('utf-8', errors=errors)) as fi:
978 lines = list(fi)
979 self.assertEqual(lines, expected_lines)
980
981 check('ignore', ['abc'])
982 with self.assertRaises(UnicodeDecodeError):
983 check('strict', ['abc'])
984 check('replace', ['\ufffdabc'])
985 check('backslashreplace', ['\\x80abc'])
986
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200987 def test_modes(self):
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200988 with open(TESTFN, 'wb') as f:
Serhiy Storchaka682ea5f2014-03-03 21:17:17 +0200989 # UTF-7 is a convenient, seldom used encoding
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200990 f.write(b'A\nB\r\nC\rD+IKw-')
991 self.addCleanup(safe_unlink, TESTFN)
992
993 def check(mode, expected_lines):
994 with FileInput(files=TESTFN, mode=mode,
995 openhook=hook_encoded('utf-7')) as fi:
996 lines = list(fi)
997 self.assertEqual(lines, expected_lines)
998
999 check('r', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka9fff8492014-02-26 21:03:19 +02001000 with self.assertWarns(DeprecationWarning):
1001 check('rU', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
1002 with self.assertWarns(DeprecationWarning):
1003 check('U', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka517b7472014-02-26 20:59:43 +02001004 with self.assertRaises(ValueError):
1005 check('rb', ['A\n', 'B\r\n', 'C\r', 'D\u20ac'])
1006
Guido van Rossumd8faa362007-04-27 19:54:29 +00001007
Martin Panter7978e102016-01-16 06:26:54 +00001008class MiscTest(unittest.TestCase):
1009
1010 def test_all(self):
Serhiy Storchaka674e2d02016-03-08 18:35:19 +02001011 support.check__all__(self, fileinput)
Martin Panter7978e102016-01-16 06:26:54 +00001012
1013
Guido van Rossumd8faa362007-04-27 19:54:29 +00001014if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -04001015 unittest.main()