blob: 1d089f52b8a78b794c445452961b17e4087c1799 [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)
291
Georg Brandl6cb7b652010-07-31 20:08:15 +0000292 def test_context_manager(self):
293 try:
294 t1 = writeTmp(1, ["A\nB\nC"])
295 t2 = writeTmp(2, ["D\nE\nF"])
296 with FileInput(files=(t1, t2)) as fi:
297 lines = list(fi)
298 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
299 self.assertEqual(fi.filelineno(), 3)
300 self.assertEqual(fi.lineno(), 6)
301 self.assertEqual(fi._files, ())
302 finally:
303 remove_tempfiles(t1, t2)
304
305 def test_close_on_exception(self):
306 try:
307 t1 = writeTmp(1, [""])
308 with FileInput(files=t1) as fi:
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200309 raise OSError
310 except OSError:
Georg Brandl6cb7b652010-07-31 20:08:15 +0000311 self.assertEqual(fi._files, ())
312 finally:
313 remove_tempfiles(t1)
314
briancurtin906f0c42011-03-15 10:29:41 -0400315 def test_empty_files_list_specified_to_constructor(self):
316 with FileInput(files=[]) as fi:
Brett Cannond47af532011-03-15 15:55:12 -0400317 self.assertEqual(fi._files, ('-',))
briancurtin906f0c42011-03-15 10:29:41 -0400318
319 def test__getitem__(self):
320 """Tests invoking FileInput.__getitem__() with the current
321 line number"""
322 t = writeTmp(1, ["line1\n", "line2\n"])
323 self.addCleanup(remove_tempfiles, t)
324 with FileInput(files=[t]) as fi:
325 retval1 = fi[0]
326 self.assertEqual(retval1, "line1\n")
327 retval2 = fi[1]
328 self.assertEqual(retval2, "line2\n")
329
330 def test__getitem__invalid_key(self):
331 """Tests invoking FileInput.__getitem__() with an index unequal to
332 the line number"""
333 t = writeTmp(1, ["line1\n", "line2\n"])
334 self.addCleanup(remove_tempfiles, t)
335 with FileInput(files=[t]) as fi:
336 with self.assertRaises(RuntimeError) as cm:
337 fi[1]
Brett Cannond47af532011-03-15 15:55:12 -0400338 self.assertEqual(cm.exception.args, ("accessing lines out of order",))
briancurtin906f0c42011-03-15 10:29:41 -0400339
340 def test__getitem__eof(self):
341 """Tests invoking FileInput.__getitem__() with the line number but at
342 end-of-input"""
343 t = writeTmp(1, [])
344 self.addCleanup(remove_tempfiles, t)
345 with FileInput(files=[t]) as fi:
346 with self.assertRaises(IndexError) as cm:
347 fi[0]
Brett Cannond47af532011-03-15 15:55:12 -0400348 self.assertEqual(cm.exception.args, ("end of input reached",))
briancurtin906f0c42011-03-15 10:29:41 -0400349
350 def test_nextfile_oserror_deleting_backup(self):
351 """Tests invoking FileInput.nextfile() when the attempt to delete
352 the backup file would raise OSError. This error is expected to be
353 silently ignored"""
354
355 os_unlink_orig = os.unlink
356 os_unlink_replacement = UnconditionallyRaise(OSError)
357 try:
358 t = writeTmp(1, ["\n"])
359 self.addCleanup(remove_tempfiles, t)
360 with FileInput(files=[t], inplace=True) as fi:
361 next(fi) # make sure the file is opened
362 os.unlink = os_unlink_replacement
363 fi.nextfile()
364 finally:
365 os.unlink = os_unlink_orig
366
367 # sanity check to make sure that our test scenario was actually hit
368 self.assertTrue(os_unlink_replacement.invoked,
369 "os.unlink() was not invoked")
370
371 def test_readline_os_fstat_raises_OSError(self):
372 """Tests invoking FileInput.readline() when os.fstat() raises OSError.
373 This exception should be silently discarded."""
374
375 os_fstat_orig = os.fstat
376 os_fstat_replacement = UnconditionallyRaise(OSError)
377 try:
378 t = writeTmp(1, ["\n"])
379 self.addCleanup(remove_tempfiles, t)
380 with FileInput(files=[t], inplace=True) as fi:
381 os.fstat = os_fstat_replacement
382 fi.readline()
383 finally:
384 os.fstat = os_fstat_orig
385
386 # sanity check to make sure that our test scenario was actually hit
387 self.assertTrue(os_fstat_replacement.invoked,
388 "os.fstat() was not invoked")
389
390 @unittest.skipIf(not hasattr(os, "chmod"), "os.chmod does not exist")
391 def test_readline_os_chmod_raises_OSError(self):
392 """Tests invoking FileInput.readline() when os.chmod() raises OSError.
393 This exception should be silently discarded."""
394
395 os_chmod_orig = os.chmod
396 os_chmod_replacement = UnconditionallyRaise(OSError)
397 try:
398 t = writeTmp(1, ["\n"])
399 self.addCleanup(remove_tempfiles, t)
400 with FileInput(files=[t], inplace=True) as fi:
401 os.chmod = os_chmod_replacement
402 fi.readline()
403 finally:
404 os.chmod = os_chmod_orig
405
406 # sanity check to make sure that our test scenario was actually hit
407 self.assertTrue(os_chmod_replacement.invoked,
408 "os.fstat() was not invoked")
409
410 def test_fileno_when_ValueError_raised(self):
411 class FilenoRaisesValueError(UnconditionallyRaise):
412 def __init__(self):
413 UnconditionallyRaise.__init__(self, ValueError)
414 def fileno(self):
415 self.__call__()
416
417 unconditionally_raise_ValueError = FilenoRaisesValueError()
418 t = writeTmp(1, ["\n"])
419 self.addCleanup(remove_tempfiles, t)
420 with FileInput(files=[t]) as fi:
421 file_backup = fi._file
422 try:
423 fi._file = unconditionally_raise_ValueError
424 result = fi.fileno()
425 finally:
426 fi._file = file_backup # make sure the file gets cleaned up
427
428 # sanity check to make sure that our test scenario was actually hit
429 self.assertTrue(unconditionally_raise_ValueError.invoked,
430 "_file.fileno() was not invoked")
431
432 self.assertEqual(result, -1, "fileno() should return -1")
433
434class MockFileInput:
435 """A class that mocks out fileinput.FileInput for use during unit tests"""
436
437 def __init__(self, files=None, inplace=False, backup="", bufsize=0,
438 mode="r", openhook=None):
439 self.files = files
440 self.inplace = inplace
441 self.backup = backup
442 self.bufsize = bufsize
443 self.mode = mode
444 self.openhook = openhook
445 self._file = None
446 self.invocation_counts = collections.defaultdict(lambda: 0)
447 self.return_values = {}
448
449 def close(self):
450 self.invocation_counts["close"] += 1
451
452 def nextfile(self):
453 self.invocation_counts["nextfile"] += 1
454 return self.return_values["nextfile"]
455
456 def filename(self):
457 self.invocation_counts["filename"] += 1
458 return self.return_values["filename"]
459
460 def lineno(self):
461 self.invocation_counts["lineno"] += 1
462 return self.return_values["lineno"]
463
464 def filelineno(self):
465 self.invocation_counts["filelineno"] += 1
466 return self.return_values["filelineno"]
467
468 def fileno(self):
469 self.invocation_counts["fileno"] += 1
470 return self.return_values["fileno"]
471
472 def isfirstline(self):
473 self.invocation_counts["isfirstline"] += 1
474 return self.return_values["isfirstline"]
475
476 def isstdin(self):
477 self.invocation_counts["isstdin"] += 1
478 return self.return_values["isstdin"]
479
480class BaseFileInputGlobalMethodsTest(unittest.TestCase):
481 """Base class for unit tests for the global function of
482 the fileinput module."""
483
484 def setUp(self):
485 self._orig_state = fileinput._state
486 self._orig_FileInput = fileinput.FileInput
487 fileinput.FileInput = MockFileInput
488
489 def tearDown(self):
490 fileinput.FileInput = self._orig_FileInput
491 fileinput._state = self._orig_state
492
493 def assertExactlyOneInvocation(self, mock_file_input, method_name):
494 # assert that the method with the given name was invoked once
495 actual_count = mock_file_input.invocation_counts[method_name]
496 self.assertEqual(actual_count, 1, method_name)
497 # assert that no other unexpected methods were invoked
498 actual_total_count = len(mock_file_input.invocation_counts)
499 self.assertEqual(actual_total_count, 1)
500
501class Test_fileinput_input(BaseFileInputGlobalMethodsTest):
502 """Unit tests for fileinput.input()"""
503
504 def test_state_is_not_None_and_state_file_is_not_None(self):
505 """Tests invoking fileinput.input() when fileinput._state is not None
506 and its _file attribute is also not None. Expect RuntimeError to
507 be raised with a meaningful error message and for fileinput._state
508 to *not* be modified."""
509 instance = MockFileInput()
510 instance._file = object()
511 fileinput._state = instance
512 with self.assertRaises(RuntimeError) as cm:
513 fileinput.input()
514 self.assertEqual(("input() already active",), cm.exception.args)
515 self.assertIs(instance, fileinput._state, "fileinput._state")
516
517 def test_state_is_not_None_and_state_file_is_None(self):
518 """Tests invoking fileinput.input() when fileinput._state is not None
519 but its _file attribute *is* None. Expect it to create and return
520 a new fileinput.FileInput object with all method parameters passed
521 explicitly to the __init__() method; also ensure that
522 fileinput._state is set to the returned instance."""
523 instance = MockFileInput()
524 instance._file = None
525 fileinput._state = instance
526 self.do_test_call_input()
527
528 def test_state_is_None(self):
529 """Tests invoking fileinput.input() when fileinput._state is None
530 Expect it to create and return a new fileinput.FileInput object
531 with all method parameters passed explicitly to the __init__()
532 method; also ensure that fileinput._state is set to the returned
533 instance."""
534 fileinput._state = None
535 self.do_test_call_input()
536
537 def do_test_call_input(self):
538 """Tests that fileinput.input() creates a new fileinput.FileInput
539 object, passing the given parameters unmodified to
540 fileinput.FileInput.__init__(). Note that this test depends on the
541 monkey patching of fileinput.FileInput done by setUp()."""
542 files = object()
543 inplace = object()
544 backup = object()
545 bufsize = object()
546 mode = object()
547 openhook = object()
548
549 # call fileinput.input() with different values for each argument
550 result = fileinput.input(files=files, inplace=inplace, backup=backup,
551 bufsize=bufsize,
552 mode=mode, openhook=openhook)
553
554 # ensure fileinput._state was set to the returned object
555 self.assertIs(result, fileinput._state, "fileinput._state")
556
557 # ensure the parameters to fileinput.input() were passed directly
558 # to FileInput.__init__()
559 self.assertIs(files, result.files, "files")
560 self.assertIs(inplace, result.inplace, "inplace")
561 self.assertIs(backup, result.backup, "backup")
562 self.assertIs(bufsize, result.bufsize, "bufsize")
563 self.assertIs(mode, result.mode, "mode")
564 self.assertIs(openhook, result.openhook, "openhook")
565
566class Test_fileinput_close(BaseFileInputGlobalMethodsTest):
567 """Unit tests for fileinput.close()"""
568
569 def test_state_is_None(self):
570 """Tests that fileinput.close() does nothing if fileinput._state
571 is None"""
572 fileinput._state = None
573 fileinput.close()
574 self.assertIsNone(fileinput._state)
575
576 def test_state_is_not_None(self):
577 """Tests that fileinput.close() invokes close() on fileinput._state
578 and sets _state=None"""
579 instance = MockFileInput()
580 fileinput._state = instance
581 fileinput.close()
582 self.assertExactlyOneInvocation(instance, "close")
583 self.assertIsNone(fileinput._state)
584
585class Test_fileinput_nextfile(BaseFileInputGlobalMethodsTest):
586 """Unit tests for fileinput.nextfile()"""
587
588 def test_state_is_None(self):
589 """Tests fileinput.nextfile() when fileinput._state is None.
590 Ensure that it raises RuntimeError with a meaningful error message
591 and does not modify fileinput._state"""
592 fileinput._state = None
593 with self.assertRaises(RuntimeError) as cm:
594 fileinput.nextfile()
595 self.assertEqual(("no active input()",), cm.exception.args)
596 self.assertIsNone(fileinput._state)
597
598 def test_state_is_not_None(self):
599 """Tests fileinput.nextfile() when fileinput._state is not None.
600 Ensure that it invokes fileinput._state.nextfile() exactly once,
601 returns whatever it returns, and does not modify fileinput._state
602 to point to a different object."""
603 nextfile_retval = object()
604 instance = MockFileInput()
605 instance.return_values["nextfile"] = nextfile_retval
606 fileinput._state = instance
607 retval = fileinput.nextfile()
608 self.assertExactlyOneInvocation(instance, "nextfile")
609 self.assertIs(retval, nextfile_retval)
610 self.assertIs(fileinput._state, instance)
611
612class Test_fileinput_filename(BaseFileInputGlobalMethodsTest):
613 """Unit tests for fileinput.filename()"""
614
615 def test_state_is_None(self):
616 """Tests fileinput.filename() when fileinput._state is None.
617 Ensure that it raises RuntimeError with a meaningful error message
618 and does not modify fileinput._state"""
619 fileinput._state = None
620 with self.assertRaises(RuntimeError) as cm:
621 fileinput.filename()
622 self.assertEqual(("no active input()",), cm.exception.args)
623 self.assertIsNone(fileinput._state)
624
625 def test_state_is_not_None(self):
626 """Tests fileinput.filename() when fileinput._state is not None.
627 Ensure that it invokes fileinput._state.filename() exactly once,
628 returns whatever it returns, and does not modify fileinput._state
629 to point to a different object."""
630 filename_retval = object()
631 instance = MockFileInput()
632 instance.return_values["filename"] = filename_retval
633 fileinput._state = instance
634 retval = fileinput.filename()
635 self.assertExactlyOneInvocation(instance, "filename")
636 self.assertIs(retval, filename_retval)
637 self.assertIs(fileinput._state, instance)
638
639class Test_fileinput_lineno(BaseFileInputGlobalMethodsTest):
640 """Unit tests for fileinput.lineno()"""
641
642 def test_state_is_None(self):
643 """Tests fileinput.lineno() when fileinput._state is None.
644 Ensure that it raises RuntimeError with a meaningful error message
645 and does not modify fileinput._state"""
646 fileinput._state = None
647 with self.assertRaises(RuntimeError) as cm:
648 fileinput.lineno()
649 self.assertEqual(("no active input()",), cm.exception.args)
650 self.assertIsNone(fileinput._state)
651
652 def test_state_is_not_None(self):
653 """Tests fileinput.lineno() when fileinput._state is not None.
654 Ensure that it invokes fileinput._state.lineno() exactly once,
655 returns whatever it returns, and does not modify fileinput._state
656 to point to a different object."""
657 lineno_retval = object()
658 instance = MockFileInput()
659 instance.return_values["lineno"] = lineno_retval
660 fileinput._state = instance
661 retval = fileinput.lineno()
662 self.assertExactlyOneInvocation(instance, "lineno")
663 self.assertIs(retval, lineno_retval)
664 self.assertIs(fileinput._state, instance)
665
666class Test_fileinput_filelineno(BaseFileInputGlobalMethodsTest):
667 """Unit tests for fileinput.filelineno()"""
668
669 def test_state_is_None(self):
670 """Tests fileinput.filelineno() when fileinput._state is None.
671 Ensure that it raises RuntimeError with a meaningful error message
672 and does not modify fileinput._state"""
673 fileinput._state = None
674 with self.assertRaises(RuntimeError) as cm:
675 fileinput.filelineno()
676 self.assertEqual(("no active input()",), cm.exception.args)
677 self.assertIsNone(fileinput._state)
678
679 def test_state_is_not_None(self):
680 """Tests fileinput.filelineno() when fileinput._state is not None.
681 Ensure that it invokes fileinput._state.filelineno() exactly once,
682 returns whatever it returns, and does not modify fileinput._state
683 to point to a different object."""
684 filelineno_retval = object()
685 instance = MockFileInput()
686 instance.return_values["filelineno"] = filelineno_retval
687 fileinput._state = instance
688 retval = fileinput.filelineno()
689 self.assertExactlyOneInvocation(instance, "filelineno")
690 self.assertIs(retval, filelineno_retval)
691 self.assertIs(fileinput._state, instance)
692
693class Test_fileinput_fileno(BaseFileInputGlobalMethodsTest):
694 """Unit tests for fileinput.fileno()"""
695
696 def test_state_is_None(self):
697 """Tests fileinput.fileno() when fileinput._state is None.
698 Ensure that it raises RuntimeError with a meaningful error message
699 and does not modify fileinput._state"""
700 fileinput._state = None
701 with self.assertRaises(RuntimeError) as cm:
702 fileinput.fileno()
703 self.assertEqual(("no active input()",), cm.exception.args)
704 self.assertIsNone(fileinput._state)
705
706 def test_state_is_not_None(self):
707 """Tests fileinput.fileno() when fileinput._state is not None.
708 Ensure that it invokes fileinput._state.fileno() exactly once,
709 returns whatever it returns, and does not modify fileinput._state
710 to point to a different object."""
711 fileno_retval = object()
712 instance = MockFileInput()
713 instance.return_values["fileno"] = fileno_retval
714 instance.fileno_retval = fileno_retval
715 fileinput._state = instance
716 retval = fileinput.fileno()
717 self.assertExactlyOneInvocation(instance, "fileno")
718 self.assertIs(retval, fileno_retval)
719 self.assertIs(fileinput._state, instance)
720
721class Test_fileinput_isfirstline(BaseFileInputGlobalMethodsTest):
722 """Unit tests for fileinput.isfirstline()"""
723
724 def test_state_is_None(self):
725 """Tests fileinput.isfirstline() when fileinput._state is None.
726 Ensure that it raises RuntimeError with a meaningful error message
727 and does not modify fileinput._state"""
728 fileinput._state = None
729 with self.assertRaises(RuntimeError) as cm:
730 fileinput.isfirstline()
731 self.assertEqual(("no active input()",), cm.exception.args)
732 self.assertIsNone(fileinput._state)
733
734 def test_state_is_not_None(self):
735 """Tests fileinput.isfirstline() when fileinput._state is not None.
736 Ensure that it invokes fileinput._state.isfirstline() exactly once,
737 returns whatever it returns, and does not modify fileinput._state
738 to point to a different object."""
739 isfirstline_retval = object()
740 instance = MockFileInput()
741 instance.return_values["isfirstline"] = isfirstline_retval
742 fileinput._state = instance
743 retval = fileinput.isfirstline()
744 self.assertExactlyOneInvocation(instance, "isfirstline")
745 self.assertIs(retval, isfirstline_retval)
746 self.assertIs(fileinput._state, instance)
747
748class Test_fileinput_isstdin(BaseFileInputGlobalMethodsTest):
749 """Unit tests for fileinput.isstdin()"""
750
751 def test_state_is_None(self):
752 """Tests fileinput.isstdin() when fileinput._state is None.
753 Ensure that it raises RuntimeError with a meaningful error message
754 and does not modify fileinput._state"""
755 fileinput._state = None
756 with self.assertRaises(RuntimeError) as cm:
757 fileinput.isstdin()
758 self.assertEqual(("no active input()",), cm.exception.args)
759 self.assertIsNone(fileinput._state)
760
761 def test_state_is_not_None(self):
762 """Tests fileinput.isstdin() when fileinput._state is not None.
763 Ensure that it invokes fileinput._state.isstdin() exactly once,
764 returns whatever it returns, and does not modify fileinput._state
765 to point to a different object."""
766 isstdin_retval = object()
767 instance = MockFileInput()
768 instance.return_values["isstdin"] = isstdin_retval
769 fileinput._state = instance
770 retval = fileinput.isstdin()
771 self.assertExactlyOneInvocation(instance, "isstdin")
772 self.assertIs(retval, isstdin_retval)
773 self.assertIs(fileinput._state, instance)
774
775class InvocationRecorder:
776 def __init__(self):
777 self.invocation_count = 0
778 def __call__(self, *args, **kwargs):
779 self.invocation_count += 1
780 self.last_invocation = (args, kwargs)
781
782class Test_hook_compressed(unittest.TestCase):
783 """Unit tests for fileinput.hook_compressed()"""
784
785 def setUp(self):
786 self.fake_open = InvocationRecorder()
787
788 def test_empty_string(self):
789 self.do_test_use_builtin_open("", 1)
790
791 def test_no_ext(self):
792 self.do_test_use_builtin_open("abcd", 2)
793
Ezio Melottic3afbb92011-05-14 10:10:53 +0300794 @unittest.skipUnless(gzip, "Requires gzip and zlib")
briancurtin5eb35912011-03-15 10:59:36 -0400795 def test_gz_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400796 original_open = gzip.open
797 gzip.open = self.fake_open
798 try:
799 result = fileinput.hook_compressed("test.gz", 3)
800 finally:
801 gzip.open = original_open
802
803 self.assertEqual(self.fake_open.invocation_count, 1)
804 self.assertEqual(self.fake_open.last_invocation, (("test.gz", 3), {}))
805
briancurtinf84f3c32011-03-18 13:03:17 -0500806 @unittest.skipUnless(bz2, "Requires bz2")
briancurtin5eb35912011-03-15 10:59:36 -0400807 def test_bz2_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400808 original_open = bz2.BZ2File
809 bz2.BZ2File = self.fake_open
810 try:
811 result = fileinput.hook_compressed("test.bz2", 4)
812 finally:
813 bz2.BZ2File = original_open
814
815 self.assertEqual(self.fake_open.invocation_count, 1)
816 self.assertEqual(self.fake_open.last_invocation, (("test.bz2", 4), {}))
817
818 def test_blah_ext(self):
819 self.do_test_use_builtin_open("abcd.blah", 5)
820
briancurtin5eb35912011-03-15 10:59:36 -0400821 def test_gz_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400822 self.do_test_use_builtin_open("abcd.Gz", 6)
823
briancurtin5eb35912011-03-15 10:59:36 -0400824 def test_bz2_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400825 self.do_test_use_builtin_open("abcd.Bz2", 7)
826
827 def do_test_use_builtin_open(self, filename, mode):
828 original_open = self.replace_builtin_open(self.fake_open)
829 try:
830 result = fileinput.hook_compressed(filename, mode)
831 finally:
832 self.replace_builtin_open(original_open)
833
834 self.assertEqual(self.fake_open.invocation_count, 1)
835 self.assertEqual(self.fake_open.last_invocation,
836 ((filename, mode), {}))
837
838 @staticmethod
839 def replace_builtin_open(new_open_func):
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100840 original_open = builtins.open
841 builtins.open = new_open_func
briancurtin906f0c42011-03-15 10:29:41 -0400842 return original_open
843
844class Test_hook_encoded(unittest.TestCase):
845 """Unit tests for fileinput.hook_encoded()"""
846
847 def test(self):
848 encoding = object()
849 result = fileinput.hook_encoded(encoding)
850
851 fake_open = InvocationRecorder()
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100852 original_open = builtins.open
853 builtins.open = fake_open
briancurtin906f0c42011-03-15 10:29:41 -0400854 try:
855 filename = object()
856 mode = object()
857 open_result = result(filename, mode)
858 finally:
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100859 builtins.open = original_open
briancurtin906f0c42011-03-15 10:29:41 -0400860
861 self.assertEqual(fake_open.invocation_count, 1)
862
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100863 args, kwargs = fake_open.last_invocation
briancurtin906f0c42011-03-15 10:29:41 -0400864 self.assertIs(args[0], filename)
865 self.assertIs(args[1], mode)
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100866 self.assertIs(kwargs.pop('encoding'), encoding)
867 self.assertFalse(kwargs)
Georg Brandl6cb7b652010-07-31 20:08:15 +0000868
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200869 def test_modes(self):
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200870 with open(TESTFN, 'wb') as f:
Serhiy Storchaka682ea5f2014-03-03 21:17:17 +0200871 # UTF-7 is a convenient, seldom used encoding
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200872 f.write(b'A\nB\r\nC\rD+IKw-')
873 self.addCleanup(safe_unlink, TESTFN)
874
875 def check(mode, expected_lines):
876 with FileInput(files=TESTFN, mode=mode,
877 openhook=hook_encoded('utf-7')) as fi:
878 lines = list(fi)
879 self.assertEqual(lines, expected_lines)
880
881 check('r', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka9fff8492014-02-26 21:03:19 +0200882 with self.assertWarns(DeprecationWarning):
883 check('rU', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
884 with self.assertWarns(DeprecationWarning):
885 check('U', ['A\n', 'B\n', 'C\n', 'D\u20ac'])
Serhiy Storchaka517b7472014-02-26 20:59:43 +0200886 with self.assertRaises(ValueError):
887 check('rb', ['A\n', 'B\r\n', 'C\r', 'D\u20ac'])
888
Guido van Rossumd8faa362007-04-27 19:54:29 +0000889
890if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400891 unittest.main()