blob: 4765a056f6a4ffb029a66e3ea65fc30a89145d47 [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
Benjamin Petersoneb462882011-03-15 09:50:18 -050011import unittest
12
briancurtinf84f3c32011-03-18 13:03:17 -050013try:
14 import bz2
15except ImportError:
16 bz2 = None
Ezio Melottic3afbb92011-05-14 10:10:53 +030017try:
18 import gzip
19except ImportError:
20 gzip = None
briancurtinf84f3c32011-03-18 13:03:17 -050021
Serhiy Storchaka946cfc32014-05-14 21:08:33 +030022from io import BytesIO, StringIO
Benjamin Petersoneb462882011-03-15 09:50:18 -050023from fileinput import FileInput, hook_encoded
24
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +020025from test.support import verbose, TESTFN, run_unittest, check_warnings
Benjamin Petersoneb462882011-03-15 09:50:18 -050026from test.support import unlink as safe_unlink
Serhiy Storchaka946cfc32014-05-14 21:08:33 +030027from unittest import mock
Benjamin Petersoneb462882011-03-15 09:50:18 -050028
Tim Peters3230d5c2001-07-11 22:21:17 +000029
30# The fileinput module has 2 interfaces: the FileInput class which does
31# all the work, and a few functions (input, etc.) that use a global _state
briancurtin906f0c42011-03-15 10:29:41 -040032# variable.
Tim Peters3230d5c2001-07-11 22:21:17 +000033
34# Write lines (a list of lines) to temp file number i, and return the
35# temp file's name.
Tim Peters4d7cad12006-02-19 21:22:10 +000036def writeTmp(i, lines, mode='w'): # opening in text mode is the default
Tim Peters3230d5c2001-07-11 22:21:17 +000037 name = TESTFN + str(i)
Tim Peters4d7cad12006-02-19 21:22:10 +000038 f = open(name, mode)
Guido van Rossumc43e79f2007-06-18 18:26:36 +000039 for line in lines:
40 f.write(line)
Tim Peters3230d5c2001-07-11 22:21:17 +000041 f.close()
42 return name
43
Tim Peters3230d5c2001-07-11 22:21:17 +000044def remove_tempfiles(*names):
45 for name in names:
Guido van Rossume22905a2007-08-27 23:09:25 +000046 if name:
47 safe_unlink(name)
Tim Peters3230d5c2001-07-11 22:21:17 +000048
Guido van Rossumd8faa362007-04-27 19:54:29 +000049class BufferSizesTests(unittest.TestCase):
50 def test_buffer_sizes(self):
51 # First, run the tests with default and teeny buffer size.
52 for round, bs in (0, 0), (1, 30):
Neal Norwitz2595e762008-03-24 06:10:13 +000053 t1 = t2 = t3 = t4 = None
Guido van Rossumd8faa362007-04-27 19:54:29 +000054 try:
55 t1 = writeTmp(1, ["Line %s of file 1\n" % (i+1) for i in range(15)])
56 t2 = writeTmp(2, ["Line %s of file 2\n" % (i+1) for i in range(10)])
57 t3 = writeTmp(3, ["Line %s of file 3\n" % (i+1) for i in range(5)])
58 t4 = writeTmp(4, ["Line %s of file 4\n" % (i+1) for i in range(1)])
59 self.buffer_size_test(t1, t2, t3, t4, bs, round)
60 finally:
61 remove_tempfiles(t1, t2, t3, t4)
Tim Peters3230d5c2001-07-11 22:21:17 +000062
Guido van Rossumd8faa362007-04-27 19:54:29 +000063 def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
64 pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
Tim Peters3230d5c2001-07-11 22:21:17 +000065
Guido van Rossumd8faa362007-04-27 19:54:29 +000066 start = 1 + round*6
67 if verbose:
68 print('%s. Simple iteration (bs=%s)' % (start+0, bs))
69 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
Tim Peters3230d5c2001-07-11 22:21:17 +000070 lines = list(fi)
Tim Peters3230d5c2001-07-11 22:21:17 +000071 fi.close()
Guido van Rossumd8faa362007-04-27 19:54:29 +000072 self.assertEqual(len(lines), 31)
73 self.assertEqual(lines[4], 'Line 5 of file 1\n')
74 self.assertEqual(lines[30], 'Line 1 of file 4\n')
75 self.assertEqual(fi.lineno(), 31)
76 self.assertEqual(fi.filename(), t4)
Tim Peters3230d5c2001-07-11 22:21:17 +000077
Guido van Rossumd8faa362007-04-27 19:54:29 +000078 if verbose:
79 print('%s. Status variables (bs=%s)' % (start+1, bs))
80 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
81 s = "x"
82 while s and s != 'Line 6 of file 2\n':
83 s = fi.readline()
84 self.assertEqual(fi.filename(), t2)
85 self.assertEqual(fi.lineno(), 21)
86 self.assertEqual(fi.filelineno(), 6)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000087 self.assertFalse(fi.isfirstline())
88 self.assertFalse(fi.isstdin())
Tim Peters3230d5c2001-07-11 22:21:17 +000089
Guido van Rossumd8faa362007-04-27 19:54:29 +000090 if verbose:
91 print('%s. Nextfile (bs=%s)' % (start+2, bs))
92 fi.nextfile()
93 self.assertEqual(fi.readline(), 'Line 1 of file 3\n')
94 self.assertEqual(fi.lineno(), 22)
95 fi.close()
Tim Peters3230d5c2001-07-11 22:21:17 +000096
Guido van Rossumd8faa362007-04-27 19:54:29 +000097 if verbose:
98 print('%s. Stdin (bs=%s)' % (start+3, bs))
99 fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs)
100 savestdin = sys.stdin
101 try:
102 sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n")
103 lines = list(fi)
104 self.assertEqual(len(lines), 33)
105 self.assertEqual(lines[32], 'Line 2 of stdin\n')
106 self.assertEqual(fi.filename(), '<stdin>')
107 fi.nextfile()
108 finally:
109 sys.stdin = savestdin
Tim Peters3230d5c2001-07-11 22:21:17 +0000110
Guido van Rossumd8faa362007-04-27 19:54:29 +0000111 if verbose:
112 print('%s. Boundary conditions (bs=%s)' % (start+4, bs))
113 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
114 self.assertEqual(fi.lineno(), 0)
115 self.assertEqual(fi.filename(), None)
116 fi.nextfile()
117 self.assertEqual(fi.lineno(), 0)
118 self.assertEqual(fi.filename(), None)
Tim Peters3230d5c2001-07-11 22:21:17 +0000119
Guido van Rossumd8faa362007-04-27 19:54:29 +0000120 if verbose:
121 print('%s. Inplace (bs=%s)' % (start+5, bs))
122 savestdout = sys.stdout
123 try:
124 fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs)
125 for line in fi:
126 line = line[:-1].upper()
127 print(line)
128 fi.close()
129 finally:
130 sys.stdout = savestdout
Tim Peters3230d5c2001-07-11 22:21:17 +0000131
Guido van Rossumd8faa362007-04-27 19:54:29 +0000132 fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs)
133 for line in fi:
134 self.assertEqual(line[-1], '\n')
135 m = pat.match(line[:-1])
136 self.assertNotEqual(m, None)
137 self.assertEqual(int(m.group(1)), fi.filelineno())
138 fi.close()
Georg Brandle4662172006-02-19 09:51:27 +0000139
briancurtin906f0c42011-03-15 10:29:41 -0400140class UnconditionallyRaise:
141 def __init__(self, exception_type):
142 self.exception_type = exception_type
143 self.invoked = False
144 def __call__(self, *args, **kwargs):
145 self.invoked = True
146 raise self.exception_type()
147
Guido van Rossumd8faa362007-04-27 19:54:29 +0000148class FileInputTests(unittest.TestCase):
briancurtin906f0c42011-03-15 10:29:41 -0400149
Guido van Rossumd8faa362007-04-27 19:54:29 +0000150 def test_zero_byte_files(self):
Neal Norwitz2595e762008-03-24 06:10:13 +0000151 t1 = t2 = t3 = t4 = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000152 try:
153 t1 = writeTmp(1, [""])
154 t2 = writeTmp(2, [""])
155 t3 = writeTmp(3, ["The only line there is.\n"])
156 t4 = writeTmp(4, [""])
157 fi = FileInput(files=(t1, t2, t3, t4))
Georg Brandl67e9fb92006-02-19 13:56:17 +0000158
Guido van Rossumd8faa362007-04-27 19:54:29 +0000159 line = fi.readline()
160 self.assertEqual(line, 'The only line there is.\n')
161 self.assertEqual(fi.lineno(), 1)
162 self.assertEqual(fi.filelineno(), 1)
163 self.assertEqual(fi.filename(), t3)
Georg Brandlc029f872006-02-19 14:12:34 +0000164
Guido van Rossumd8faa362007-04-27 19:54:29 +0000165 line = fi.readline()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000166 self.assertFalse(line)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000167 self.assertEqual(fi.lineno(), 1)
168 self.assertEqual(fi.filelineno(), 0)
169 self.assertEqual(fi.filename(), t4)
170 fi.close()
171 finally:
172 remove_tempfiles(t1, t2, t3, t4)
Georg Brandlc98eeed2006-02-19 14:57:47 +0000173
Guido van Rossumd8faa362007-04-27 19:54:29 +0000174 def test_files_that_dont_end_with_newline(self):
Neal Norwitz2595e762008-03-24 06:10:13 +0000175 t1 = t2 = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000176 try:
177 t1 = writeTmp(1, ["A\nB\nC"])
178 t2 = writeTmp(2, ["D\nE\nF"])
179 fi = FileInput(files=(t1, t2))
180 lines = list(fi)
181 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
182 self.assertEqual(fi.filelineno(), 3)
183 self.assertEqual(fi.lineno(), 6)
184 finally:
185 remove_tempfiles(t1, t2)
186
Guido van Rossumc43e79f2007-06-18 18:26:36 +0000187## def test_unicode_filenames(self):
188## # XXX A unicode string is always returned by writeTmp.
189## # So is this needed?
190## try:
191## t1 = writeTmp(1, ["A\nB"])
192## encoding = sys.getfilesystemencoding()
193## if encoding is None:
194## encoding = 'ascii'
195## fi = FileInput(files=str(t1, encoding))
196## lines = list(fi)
197## self.assertEqual(lines, ["A\n", "B"])
198## finally:
199## remove_tempfiles(t1)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200
201 def test_fileno(self):
Neal Norwitz2595e762008-03-24 06:10:13 +0000202 t1 = t2 = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 try:
204 t1 = writeTmp(1, ["A\nB"])
205 t2 = writeTmp(2, ["C\nD"])
206 fi = FileInput(files=(t1, t2))
207 self.assertEqual(fi.fileno(), -1)
208 line =next( fi)
209 self.assertNotEqual(fi.fileno(), -1)
210 fi.nextfile()
211 self.assertEqual(fi.fileno(), -1)
212 line = list(fi)
213 self.assertEqual(fi.fileno(), -1)
214 finally:
215 remove_tempfiles(t1, t2)
216
217 def test_opening_mode(self):
218 try:
219 # invalid mode, should raise ValueError
220 fi = FileInput(mode="w")
221 self.fail("FileInput should reject invalid mode argument")
222 except ValueError:
223 pass
Guido van Rossume22905a2007-08-27 23:09:25 +0000224 t1 = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000225 try:
226 # try opening in universal newline mode
Guido van Rossume22905a2007-08-27 23:09:25 +0000227 t1 = writeTmp(1, [b"A\nB\r\nC\rD"], mode="wb")
Serhiy Storchaka2480c2e2013-11-24 23:13:26 +0200228 with check_warnings(('', DeprecationWarning)):
229 fi = FileInput(files=t1, mode="U")
230 with check_warnings(('', DeprecationWarning)):
231 lines = list(fi)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232 self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
233 finally:
234 remove_tempfiles(t1)
235
Serhiy Storchaka946cfc32014-05-14 21:08:33 +0300236 def test_stdin_binary_mode(self):
237 with mock.patch('sys.stdin') as m_stdin:
238 m_stdin.buffer = BytesIO(b'spam, bacon, sausage, and spam')
239 fi = FileInput(files=['-'], mode='rb')
240 lines = list(fi)
241 self.assertEqual(lines, [b'spam, bacon, sausage, and spam'])
242
Guido van Rossume22905a2007-08-27 23:09:25 +0000243 def test_file_opening_hook(self):
244 try:
245 # cannot use openhook and inplace mode
246 fi = FileInput(inplace=1, openhook=lambda f, m: None)
247 self.fail("FileInput should raise if both inplace "
248 "and openhook arguments are given")
249 except ValueError:
250 pass
251 try:
252 fi = FileInput(openhook=1)
253 self.fail("FileInput should check openhook for being callable")
254 except ValueError:
255 pass
briancurtin906f0c42011-03-15 10:29:41 -0400256
257 class CustomOpenHook:
258 def __init__(self):
259 self.invoked = False
260 def __call__(self, *args):
261 self.invoked = True
262 return open(*args)
263
264 t = writeTmp(1, ["\n"])
265 self.addCleanup(remove_tempfiles, t)
266 custom_open_hook = CustomOpenHook()
267 with FileInput([t], openhook=custom_open_hook) as fi:
268 fi.readline()
269 self.assertTrue(custom_open_hook.invoked, "openhook not invoked")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000270
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200271 def test_readline(self):
272 with open(TESTFN, 'wb') as f:
273 f.write(b'A\nB\r\nC\r')
274 # Fill TextIOWrapper buffer.
275 f.write(b'123456789\n' * 1000)
276 # Issue #20501: readline() shouldn't read whole file.
277 f.write(b'\x80')
278 self.addCleanup(safe_unlink, TESTFN)
279
280 with FileInput(files=TESTFN,
281 openhook=hook_encoded('ascii'), bufsize=8) as fi:
Serhiy Storchaka682ea5f2014-03-03 21:17:17 +0200282 try:
283 self.assertEqual(fi.readline(), 'A\n')
284 self.assertEqual(fi.readline(), 'B\n')
285 self.assertEqual(fi.readline(), 'C\n')
286 except UnicodeDecodeError:
287 self.fail('Read to end of file')
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200288 with self.assertRaises(UnicodeDecodeError):
289 # Read to the end of file.
290 list(fi)
Serhiy Storchaka314464d2015-11-01 16:43:58 +0200291 self.assertEqual(fi.readline(), '')
292 self.assertEqual(fi.readline(), '')
293
294 def test_readline_binary_mode(self):
295 with open(TESTFN, 'wb') as f:
296 f.write(b'A\nB\r\nC\rD')
297 self.addCleanup(safe_unlink, TESTFN)
298
299 with FileInput(files=TESTFN, mode='rb') as fi:
300 self.assertEqual(fi.readline(), b'A\n')
301 self.assertEqual(fi.readline(), b'B\r\n')
302 self.assertEqual(fi.readline(), b'C\rD')
303 # Read to the end of file.
304 self.assertEqual(fi.readline(), b'')
305 self.assertEqual(fi.readline(), b'')
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200306
Georg Brandl6cb7b652010-07-31 20:08:15 +0000307 def test_context_manager(self):
308 try:
309 t1 = writeTmp(1, ["A\nB\nC"])
310 t2 = writeTmp(2, ["D\nE\nF"])
311 with FileInput(files=(t1, t2)) as fi:
312 lines = list(fi)
313 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
314 self.assertEqual(fi.filelineno(), 3)
315 self.assertEqual(fi.lineno(), 6)
316 self.assertEqual(fi._files, ())
317 finally:
318 remove_tempfiles(t1, t2)
319
320 def test_close_on_exception(self):
321 try:
322 t1 = writeTmp(1, [""])
323 with FileInput(files=t1) as fi:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200324 raise OSError
325 except OSError:
Georg Brandl6cb7b652010-07-31 20:08:15 +0000326 self.assertEqual(fi._files, ())
327 finally:
328 remove_tempfiles(t1)
329
briancurtin906f0c42011-03-15 10:29:41 -0400330 def test_empty_files_list_specified_to_constructor(self):
331 with FileInput(files=[]) as fi:
Brett Cannond47af532011-03-15 15:55:12 -0400332 self.assertEqual(fi._files, ('-',))
briancurtin906f0c42011-03-15 10:29:41 -0400333
334 def test__getitem__(self):
335 """Tests invoking FileInput.__getitem__() with the current
336 line number"""
337 t = writeTmp(1, ["line1\n", "line2\n"])
338 self.addCleanup(remove_tempfiles, t)
339 with FileInput(files=[t]) as fi:
340 retval1 = fi[0]
341 self.assertEqual(retval1, "line1\n")
342 retval2 = fi[1]
343 self.assertEqual(retval2, "line2\n")
344
345 def test__getitem__invalid_key(self):
346 """Tests invoking FileInput.__getitem__() with an index unequal to
347 the line number"""
348 t = writeTmp(1, ["line1\n", "line2\n"])
349 self.addCleanup(remove_tempfiles, t)
350 with FileInput(files=[t]) as fi:
351 with self.assertRaises(RuntimeError) as cm:
352 fi[1]
Brett Cannond47af532011-03-15 15:55:12 -0400353 self.assertEqual(cm.exception.args, ("accessing lines out of order",))
briancurtin906f0c42011-03-15 10:29:41 -0400354
355 def test__getitem__eof(self):
356 """Tests invoking FileInput.__getitem__() with the line number but at
357 end-of-input"""
358 t = writeTmp(1, [])
359 self.addCleanup(remove_tempfiles, t)
360 with FileInput(files=[t]) as fi:
361 with self.assertRaises(IndexError) as cm:
362 fi[0]
Brett Cannond47af532011-03-15 15:55:12 -0400363 self.assertEqual(cm.exception.args, ("end of input reached",))
briancurtin906f0c42011-03-15 10:29:41 -0400364
365 def test_nextfile_oserror_deleting_backup(self):
366 """Tests invoking FileInput.nextfile() when the attempt to delete
367 the backup file would raise OSError. This error is expected to be
368 silently ignored"""
369
370 os_unlink_orig = os.unlink
371 os_unlink_replacement = UnconditionallyRaise(OSError)
372 try:
373 t = writeTmp(1, ["\n"])
374 self.addCleanup(remove_tempfiles, t)
375 with FileInput(files=[t], inplace=True) as fi:
376 next(fi) # make sure the file is opened
377 os.unlink = os_unlink_replacement
378 fi.nextfile()
379 finally:
380 os.unlink = os_unlink_orig
381
382 # sanity check to make sure that our test scenario was actually hit
383 self.assertTrue(os_unlink_replacement.invoked,
384 "os.unlink() was not invoked")
385
386 def test_readline_os_fstat_raises_OSError(self):
387 """Tests invoking FileInput.readline() when os.fstat() raises OSError.
388 This exception should be silently discarded."""
389
390 os_fstat_orig = os.fstat
391 os_fstat_replacement = UnconditionallyRaise(OSError)
392 try:
393 t = writeTmp(1, ["\n"])
394 self.addCleanup(remove_tempfiles, t)
395 with FileInput(files=[t], inplace=True) as fi:
396 os.fstat = os_fstat_replacement
397 fi.readline()
398 finally:
399 os.fstat = os_fstat_orig
400
401 # sanity check to make sure that our test scenario was actually hit
402 self.assertTrue(os_fstat_replacement.invoked,
403 "os.fstat() was not invoked")
404
405 @unittest.skipIf(not hasattr(os, "chmod"), "os.chmod does not exist")
406 def test_readline_os_chmod_raises_OSError(self):
407 """Tests invoking FileInput.readline() when os.chmod() raises OSError.
408 This exception should be silently discarded."""
409
410 os_chmod_orig = os.chmod
411 os_chmod_replacement = UnconditionallyRaise(OSError)
412 try:
413 t = writeTmp(1, ["\n"])
414 self.addCleanup(remove_tempfiles, t)
415 with FileInput(files=[t], inplace=True) as fi:
416 os.chmod = os_chmod_replacement
417 fi.readline()
418 finally:
419 os.chmod = os_chmod_orig
420
421 # sanity check to make sure that our test scenario was actually hit
422 self.assertTrue(os_chmod_replacement.invoked,
423 "os.fstat() was not invoked")
424
425 def test_fileno_when_ValueError_raised(self):
426 class FilenoRaisesValueError(UnconditionallyRaise):
427 def __init__(self):
428 UnconditionallyRaise.__init__(self, ValueError)
429 def fileno(self):
430 self.__call__()
431
432 unconditionally_raise_ValueError = FilenoRaisesValueError()
433 t = writeTmp(1, ["\n"])
434 self.addCleanup(remove_tempfiles, t)
435 with FileInput(files=[t]) as fi:
436 file_backup = fi._file
437 try:
438 fi._file = unconditionally_raise_ValueError
439 result = fi.fileno()
440 finally:
441 fi._file = file_backup # make sure the file gets cleaned up
442
443 # sanity check to make sure that our test scenario was actually hit
444 self.assertTrue(unconditionally_raise_ValueError.invoked,
445 "_file.fileno() was not invoked")
446
447 self.assertEqual(result, -1, "fileno() should return -1")
448
449class MockFileInput:
450 """A class that mocks out fileinput.FileInput for use during unit tests"""
451
452 def __init__(self, files=None, inplace=False, backup="", bufsize=0,
453 mode="r", openhook=None):
454 self.files = files
455 self.inplace = inplace
456 self.backup = backup
457 self.bufsize = bufsize
458 self.mode = mode
459 self.openhook = openhook
460 self._file = None
461 self.invocation_counts = collections.defaultdict(lambda: 0)
462 self.return_values = {}
463
464 def close(self):
465 self.invocation_counts["close"] += 1
466
467 def nextfile(self):
468 self.invocation_counts["nextfile"] += 1
469 return self.return_values["nextfile"]
470
471 def filename(self):
472 self.invocation_counts["filename"] += 1
473 return self.return_values["filename"]
474
475 def lineno(self):
476 self.invocation_counts["lineno"] += 1
477 return self.return_values["lineno"]
478
479 def filelineno(self):
480 self.invocation_counts["filelineno"] += 1
481 return self.return_values["filelineno"]
482
483 def fileno(self):
484 self.invocation_counts["fileno"] += 1
485 return self.return_values["fileno"]
486
487 def isfirstline(self):
488 self.invocation_counts["isfirstline"] += 1
489 return self.return_values["isfirstline"]
490
491 def isstdin(self):
492 self.invocation_counts["isstdin"] += 1
493 return self.return_values["isstdin"]
494
495class BaseFileInputGlobalMethodsTest(unittest.TestCase):
496 """Base class for unit tests for the global function of
497 the fileinput module."""
498
499 def setUp(self):
500 self._orig_state = fileinput._state
501 self._orig_FileInput = fileinput.FileInput
502 fileinput.FileInput = MockFileInput
503
504 def tearDown(self):
505 fileinput.FileInput = self._orig_FileInput
506 fileinput._state = self._orig_state
507
508 def assertExactlyOneInvocation(self, mock_file_input, method_name):
509 # assert that the method with the given name was invoked once
510 actual_count = mock_file_input.invocation_counts[method_name]
511 self.assertEqual(actual_count, 1, method_name)
512 # assert that no other unexpected methods were invoked
513 actual_total_count = len(mock_file_input.invocation_counts)
514 self.assertEqual(actual_total_count, 1)
515
516class Test_fileinput_input(BaseFileInputGlobalMethodsTest):
517 """Unit tests for fileinput.input()"""
518
519 def test_state_is_not_None_and_state_file_is_not_None(self):
520 """Tests invoking fileinput.input() when fileinput._state is not None
521 and its _file attribute is also not None. Expect RuntimeError to
522 be raised with a meaningful error message and for fileinput._state
523 to *not* be modified."""
524 instance = MockFileInput()
525 instance._file = object()
526 fileinput._state = instance
527 with self.assertRaises(RuntimeError) as cm:
528 fileinput.input()
529 self.assertEqual(("input() already active",), cm.exception.args)
530 self.assertIs(instance, fileinput._state, "fileinput._state")
531
532 def test_state_is_not_None_and_state_file_is_None(self):
533 """Tests invoking fileinput.input() when fileinput._state is not None
534 but its _file attribute *is* None. Expect it to create and return
535 a new fileinput.FileInput object with all method parameters passed
536 explicitly to the __init__() method; also ensure that
537 fileinput._state is set to the returned instance."""
538 instance = MockFileInput()
539 instance._file = None
540 fileinput._state = instance
541 self.do_test_call_input()
542
543 def test_state_is_None(self):
544 """Tests invoking fileinput.input() when fileinput._state is None
545 Expect it to create and return a new fileinput.FileInput object
546 with all method parameters passed explicitly to the __init__()
547 method; also ensure that fileinput._state is set to the returned
548 instance."""
549 fileinput._state = None
550 self.do_test_call_input()
551
552 def do_test_call_input(self):
553 """Tests that fileinput.input() creates a new fileinput.FileInput
554 object, passing the given parameters unmodified to
555 fileinput.FileInput.__init__(). Note that this test depends on the
556 monkey patching of fileinput.FileInput done by setUp()."""
557 files = object()
558 inplace = object()
559 backup = object()
560 bufsize = object()
561 mode = object()
562 openhook = object()
563
564 # call fileinput.input() with different values for each argument
565 result = fileinput.input(files=files, inplace=inplace, backup=backup,
566 bufsize=bufsize,
567 mode=mode, openhook=openhook)
568
569 # ensure fileinput._state was set to the returned object
570 self.assertIs(result, fileinput._state, "fileinput._state")
571
572 # ensure the parameters to fileinput.input() were passed directly
573 # to FileInput.__init__()
574 self.assertIs(files, result.files, "files")
575 self.assertIs(inplace, result.inplace, "inplace")
576 self.assertIs(backup, result.backup, "backup")
577 self.assertIs(bufsize, result.bufsize, "bufsize")
578 self.assertIs(mode, result.mode, "mode")
579 self.assertIs(openhook, result.openhook, "openhook")
580
581class Test_fileinput_close(BaseFileInputGlobalMethodsTest):
582 """Unit tests for fileinput.close()"""
583
584 def test_state_is_None(self):
585 """Tests that fileinput.close() does nothing if fileinput._state
586 is None"""
587 fileinput._state = None
588 fileinput.close()
589 self.assertIsNone(fileinput._state)
590
591 def test_state_is_not_None(self):
592 """Tests that fileinput.close() invokes close() on fileinput._state
593 and sets _state=None"""
594 instance = MockFileInput()
595 fileinput._state = instance
596 fileinput.close()
597 self.assertExactlyOneInvocation(instance, "close")
598 self.assertIsNone(fileinput._state)
599
600class Test_fileinput_nextfile(BaseFileInputGlobalMethodsTest):
601 """Unit tests for fileinput.nextfile()"""
602
603 def test_state_is_None(self):
604 """Tests fileinput.nextfile() when fileinput._state is None.
605 Ensure that it raises RuntimeError with a meaningful error message
606 and does not modify fileinput._state"""
607 fileinput._state = None
608 with self.assertRaises(RuntimeError) as cm:
609 fileinput.nextfile()
610 self.assertEqual(("no active input()",), cm.exception.args)
611 self.assertIsNone(fileinput._state)
612
613 def test_state_is_not_None(self):
614 """Tests fileinput.nextfile() when fileinput._state is not None.
615 Ensure that it invokes fileinput._state.nextfile() exactly once,
616 returns whatever it returns, and does not modify fileinput._state
617 to point to a different object."""
618 nextfile_retval = object()
619 instance = MockFileInput()
620 instance.return_values["nextfile"] = nextfile_retval
621 fileinput._state = instance
622 retval = fileinput.nextfile()
623 self.assertExactlyOneInvocation(instance, "nextfile")
624 self.assertIs(retval, nextfile_retval)
625 self.assertIs(fileinput._state, instance)
626
627class Test_fileinput_filename(BaseFileInputGlobalMethodsTest):
628 """Unit tests for fileinput.filename()"""
629
630 def test_state_is_None(self):
631 """Tests fileinput.filename() when fileinput._state is None.
632 Ensure that it raises RuntimeError with a meaningful error message
633 and does not modify fileinput._state"""
634 fileinput._state = None
635 with self.assertRaises(RuntimeError) as cm:
636 fileinput.filename()
637 self.assertEqual(("no active input()",), cm.exception.args)
638 self.assertIsNone(fileinput._state)
639
640 def test_state_is_not_None(self):
641 """Tests fileinput.filename() when fileinput._state is not None.
642 Ensure that it invokes fileinput._state.filename() exactly once,
643 returns whatever it returns, and does not modify fileinput._state
644 to point to a different object."""
645 filename_retval = object()
646 instance = MockFileInput()
647 instance.return_values["filename"] = filename_retval
648 fileinput._state = instance
649 retval = fileinput.filename()
650 self.assertExactlyOneInvocation(instance, "filename")
651 self.assertIs(retval, filename_retval)
652 self.assertIs(fileinput._state, instance)
653
654class Test_fileinput_lineno(BaseFileInputGlobalMethodsTest):
655 """Unit tests for fileinput.lineno()"""
656
657 def test_state_is_None(self):
658 """Tests fileinput.lineno() when fileinput._state is None.
659 Ensure that it raises RuntimeError with a meaningful error message
660 and does not modify fileinput._state"""
661 fileinput._state = None
662 with self.assertRaises(RuntimeError) as cm:
663 fileinput.lineno()
664 self.assertEqual(("no active input()",), cm.exception.args)
665 self.assertIsNone(fileinput._state)
666
667 def test_state_is_not_None(self):
668 """Tests fileinput.lineno() when fileinput._state is not None.
669 Ensure that it invokes fileinput._state.lineno() exactly once,
670 returns whatever it returns, and does not modify fileinput._state
671 to point to a different object."""
672 lineno_retval = object()
673 instance = MockFileInput()
674 instance.return_values["lineno"] = lineno_retval
675 fileinput._state = instance
676 retval = fileinput.lineno()
677 self.assertExactlyOneInvocation(instance, "lineno")
678 self.assertIs(retval, lineno_retval)
679 self.assertIs(fileinput._state, instance)
680
681class Test_fileinput_filelineno(BaseFileInputGlobalMethodsTest):
682 """Unit tests for fileinput.filelineno()"""
683
684 def test_state_is_None(self):
685 """Tests fileinput.filelineno() when fileinput._state is None.
686 Ensure that it raises RuntimeError with a meaningful error message
687 and does not modify fileinput._state"""
688 fileinput._state = None
689 with self.assertRaises(RuntimeError) as cm:
690 fileinput.filelineno()
691 self.assertEqual(("no active input()",), cm.exception.args)
692 self.assertIsNone(fileinput._state)
693
694 def test_state_is_not_None(self):
695 """Tests fileinput.filelineno() when fileinput._state is not None.
696 Ensure that it invokes fileinput._state.filelineno() exactly once,
697 returns whatever it returns, and does not modify fileinput._state
698 to point to a different object."""
699 filelineno_retval = object()
700 instance = MockFileInput()
701 instance.return_values["filelineno"] = filelineno_retval
702 fileinput._state = instance
703 retval = fileinput.filelineno()
704 self.assertExactlyOneInvocation(instance, "filelineno")
705 self.assertIs(retval, filelineno_retval)
706 self.assertIs(fileinput._state, instance)
707
708class Test_fileinput_fileno(BaseFileInputGlobalMethodsTest):
709 """Unit tests for fileinput.fileno()"""
710
711 def test_state_is_None(self):
712 """Tests fileinput.fileno() when fileinput._state is None.
713 Ensure that it raises RuntimeError with a meaningful error message
714 and does not modify fileinput._state"""
715 fileinput._state = None
716 with self.assertRaises(RuntimeError) as cm:
717 fileinput.fileno()
718 self.assertEqual(("no active input()",), cm.exception.args)
719 self.assertIsNone(fileinput._state)
720
721 def test_state_is_not_None(self):
722 """Tests fileinput.fileno() when fileinput._state is not None.
723 Ensure that it invokes fileinput._state.fileno() exactly once,
724 returns whatever it returns, and does not modify fileinput._state
725 to point to a different object."""
726 fileno_retval = object()
727 instance = MockFileInput()
728 instance.return_values["fileno"] = fileno_retval
729 instance.fileno_retval = fileno_retval
730 fileinput._state = instance
731 retval = fileinput.fileno()
732 self.assertExactlyOneInvocation(instance, "fileno")
733 self.assertIs(retval, fileno_retval)
734 self.assertIs(fileinput._state, instance)
735
736class Test_fileinput_isfirstline(BaseFileInputGlobalMethodsTest):
737 """Unit tests for fileinput.isfirstline()"""
738
739 def test_state_is_None(self):
740 """Tests fileinput.isfirstline() when fileinput._state is None.
741 Ensure that it raises RuntimeError with a meaningful error message
742 and does not modify fileinput._state"""
743 fileinput._state = None
744 with self.assertRaises(RuntimeError) as cm:
745 fileinput.isfirstline()
746 self.assertEqual(("no active input()",), cm.exception.args)
747 self.assertIsNone(fileinput._state)
748
749 def test_state_is_not_None(self):
750 """Tests fileinput.isfirstline() when fileinput._state is not None.
751 Ensure that it invokes fileinput._state.isfirstline() exactly once,
752 returns whatever it returns, and does not modify fileinput._state
753 to point to a different object."""
754 isfirstline_retval = object()
755 instance = MockFileInput()
756 instance.return_values["isfirstline"] = isfirstline_retval
757 fileinput._state = instance
758 retval = fileinput.isfirstline()
759 self.assertExactlyOneInvocation(instance, "isfirstline")
760 self.assertIs(retval, isfirstline_retval)
761 self.assertIs(fileinput._state, instance)
762
763class Test_fileinput_isstdin(BaseFileInputGlobalMethodsTest):
764 """Unit tests for fileinput.isstdin()"""
765
766 def test_state_is_None(self):
767 """Tests fileinput.isstdin() when fileinput._state is None.
768 Ensure that it raises RuntimeError with a meaningful error message
769 and does not modify fileinput._state"""
770 fileinput._state = None
771 with self.assertRaises(RuntimeError) as cm:
772 fileinput.isstdin()
773 self.assertEqual(("no active input()",), cm.exception.args)
774 self.assertIsNone(fileinput._state)
775
776 def test_state_is_not_None(self):
777 """Tests fileinput.isstdin() when fileinput._state is not None.
778 Ensure that it invokes fileinput._state.isstdin() exactly once,
779 returns whatever it returns, and does not modify fileinput._state
780 to point to a different object."""
781 isstdin_retval = object()
782 instance = MockFileInput()
783 instance.return_values["isstdin"] = isstdin_retval
784 fileinput._state = instance
785 retval = fileinput.isstdin()
786 self.assertExactlyOneInvocation(instance, "isstdin")
787 self.assertIs(retval, isstdin_retval)
788 self.assertIs(fileinput._state, instance)
789
790class InvocationRecorder:
791 def __init__(self):
792 self.invocation_count = 0
793 def __call__(self, *args, **kwargs):
794 self.invocation_count += 1
795 self.last_invocation = (args, kwargs)
796
797class Test_hook_compressed(unittest.TestCase):
798 """Unit tests for fileinput.hook_compressed()"""
799
800 def setUp(self):
801 self.fake_open = InvocationRecorder()
802
803 def test_empty_string(self):
804 self.do_test_use_builtin_open("", 1)
805
806 def test_no_ext(self):
807 self.do_test_use_builtin_open("abcd", 2)
808
Ezio Melottic3afbb92011-05-14 10:10:53 +0300809 @unittest.skipUnless(gzip, "Requires gzip and zlib")
briancurtin5eb35912011-03-15 10:59:36 -0400810 def test_gz_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400811 original_open = gzip.open
812 gzip.open = self.fake_open
813 try:
814 result = fileinput.hook_compressed("test.gz", 3)
815 finally:
816 gzip.open = original_open
817
818 self.assertEqual(self.fake_open.invocation_count, 1)
819 self.assertEqual(self.fake_open.last_invocation, (("test.gz", 3), {}))
820
briancurtinf84f3c32011-03-18 13:03:17 -0500821 @unittest.skipUnless(bz2, "Requires bz2")
briancurtin5eb35912011-03-15 10:59:36 -0400822 def test_bz2_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400823 original_open = bz2.BZ2File
824 bz2.BZ2File = self.fake_open
825 try:
826 result = fileinput.hook_compressed("test.bz2", 4)
827 finally:
828 bz2.BZ2File = original_open
829
830 self.assertEqual(self.fake_open.invocation_count, 1)
831 self.assertEqual(self.fake_open.last_invocation, (("test.bz2", 4), {}))
832
833 def test_blah_ext(self):
834 self.do_test_use_builtin_open("abcd.blah", 5)
835
briancurtin5eb35912011-03-15 10:59:36 -0400836 def test_gz_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400837 self.do_test_use_builtin_open("abcd.Gz", 6)
838
briancurtin5eb35912011-03-15 10:59:36 -0400839 def test_bz2_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400840 self.do_test_use_builtin_open("abcd.Bz2", 7)
841
842 def do_test_use_builtin_open(self, filename, mode):
843 original_open = self.replace_builtin_open(self.fake_open)
844 try:
845 result = fileinput.hook_compressed(filename, mode)
846 finally:
847 self.replace_builtin_open(original_open)
848
849 self.assertEqual(self.fake_open.invocation_count, 1)
850 self.assertEqual(self.fake_open.last_invocation,
851 ((filename, mode), {}))
852
853 @staticmethod
854 def replace_builtin_open(new_open_func):
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100855 original_open = builtins.open
856 builtins.open = new_open_func
briancurtin906f0c42011-03-15 10:29:41 -0400857 return original_open
858
859class Test_hook_encoded(unittest.TestCase):
860 """Unit tests for fileinput.hook_encoded()"""
861
862 def test(self):
863 encoding = object()
864 result = fileinput.hook_encoded(encoding)
865
866 fake_open = InvocationRecorder()
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100867 original_open = builtins.open
868 builtins.open = fake_open
briancurtin906f0c42011-03-15 10:29:41 -0400869 try:
870 filename = object()
871 mode = object()
872 open_result = result(filename, mode)
873 finally:
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100874 builtins.open = original_open
briancurtin906f0c42011-03-15 10:29:41 -0400875
876 self.assertEqual(fake_open.invocation_count, 1)
877
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100878 args, kwargs = fake_open.last_invocation
briancurtin906f0c42011-03-15 10:29:41 -0400879 self.assertIs(args[0], filename)
880 self.assertIs(args[1], mode)
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100881 self.assertIs(kwargs.pop('encoding'), encoding)
882 self.assertFalse(kwargs)
Georg Brandl6cb7b652010-07-31 20:08:15 +0000883
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200884 def test_modes(self):
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200885 with open(TESTFN, 'wb') as f:
Serhiy Storchaka682ea5f2014-03-03 21:17:17 +0200886 # UTF-7 is a convenient, seldom used encoding
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200887 f.write(b'A\nB\r\nC\rD+IKw-')
888 self.addCleanup(safe_unlink, TESTFN)
889
890 def check(mode, expected_lines):
891 with FileInput(files=TESTFN, mode=mode,
892 openhook=hook_encoded('utf-7')) as fi:
893 lines = list(fi)
894 self.assertEqual(lines, expected_lines)
895
896 check('r', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka9fff8492014-02-26 21:03:19 +0200897 with self.assertWarns(DeprecationWarning):
898 check('rU', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
899 with self.assertWarns(DeprecationWarning):
900 check('U', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200901 with self.assertRaises(ValueError):
902 check('rb', ['A\n', 'B\r\n', 'C\r', 'D\u20ac'])
903
Guido van Rossumd8faa362007-04-27 19:54:29 +0000904
905if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400906 unittest.main()