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