blob: 1e70641150dc09b671493c97860fc37f5660d47f [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
25from test.support import verbose, TESTFN, run_unittest
26from 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")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000227 fi = FileInput(files=t1, mode="U")
228 lines = list(fi)
229 self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"])
230 finally:
231 remove_tempfiles(t1)
232
Guido van Rossume22905a2007-08-27 23:09:25 +0000233 def test_file_opening_hook(self):
234 try:
235 # cannot use openhook and inplace mode
236 fi = FileInput(inplace=1, openhook=lambda f, m: None)
237 self.fail("FileInput should raise if both inplace "
238 "and openhook arguments are given")
239 except ValueError:
240 pass
241 try:
242 fi = FileInput(openhook=1)
243 self.fail("FileInput should check openhook for being callable")
244 except ValueError:
245 pass
briancurtin906f0c42011-03-15 10:29:41 -0400246
247 class CustomOpenHook:
248 def __init__(self):
249 self.invoked = False
250 def __call__(self, *args):
251 self.invoked = True
252 return open(*args)
253
254 t = writeTmp(1, ["\n"])
255 self.addCleanup(remove_tempfiles, t)
256 custom_open_hook = CustomOpenHook()
257 with FileInput([t], openhook=custom_open_hook) as fi:
258 fi.readline()
259 self.assertTrue(custom_open_hook.invoked, "openhook not invoked")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000260
Georg Brandl6cb7b652010-07-31 20:08:15 +0000261 def test_context_manager(self):
262 try:
263 t1 = writeTmp(1, ["A\nB\nC"])
264 t2 = writeTmp(2, ["D\nE\nF"])
265 with FileInput(files=(t1, t2)) as fi:
266 lines = list(fi)
267 self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"])
268 self.assertEqual(fi.filelineno(), 3)
269 self.assertEqual(fi.lineno(), 6)
270 self.assertEqual(fi._files, ())
271 finally:
272 remove_tempfiles(t1, t2)
273
274 def test_close_on_exception(self):
275 try:
276 t1 = writeTmp(1, [""])
277 with FileInput(files=t1) as fi:
278 raise IOError
279 except IOError:
280 self.assertEqual(fi._files, ())
281 finally:
282 remove_tempfiles(t1)
283
briancurtin906f0c42011-03-15 10:29:41 -0400284 def test_empty_files_list_specified_to_constructor(self):
285 with FileInput(files=[]) as fi:
Brett Cannond47af532011-03-15 15:55:12 -0400286 self.assertEqual(fi._files, ('-',))
briancurtin906f0c42011-03-15 10:29:41 -0400287
288 def test__getitem__(self):
289 """Tests invoking FileInput.__getitem__() with the current
290 line number"""
291 t = writeTmp(1, ["line1\n", "line2\n"])
292 self.addCleanup(remove_tempfiles, t)
293 with FileInput(files=[t]) as fi:
294 retval1 = fi[0]
295 self.assertEqual(retval1, "line1\n")
296 retval2 = fi[1]
297 self.assertEqual(retval2, "line2\n")
298
299 def test__getitem__invalid_key(self):
300 """Tests invoking FileInput.__getitem__() with an index unequal to
301 the line number"""
302 t = writeTmp(1, ["line1\n", "line2\n"])
303 self.addCleanup(remove_tempfiles, t)
304 with FileInput(files=[t]) as fi:
305 with self.assertRaises(RuntimeError) as cm:
306 fi[1]
Brett Cannond47af532011-03-15 15:55:12 -0400307 self.assertEqual(cm.exception.args, ("accessing lines out of order",))
briancurtin906f0c42011-03-15 10:29:41 -0400308
309 def test__getitem__eof(self):
310 """Tests invoking FileInput.__getitem__() with the line number but at
311 end-of-input"""
312 t = writeTmp(1, [])
313 self.addCleanup(remove_tempfiles, t)
314 with FileInput(files=[t]) as fi:
315 with self.assertRaises(IndexError) as cm:
316 fi[0]
Brett Cannond47af532011-03-15 15:55:12 -0400317 self.assertEqual(cm.exception.args, ("end of input reached",))
briancurtin906f0c42011-03-15 10:29:41 -0400318
319 def test_nextfile_oserror_deleting_backup(self):
320 """Tests invoking FileInput.nextfile() when the attempt to delete
321 the backup file would raise OSError. This error is expected to be
322 silently ignored"""
323
324 os_unlink_orig = os.unlink
325 os_unlink_replacement = UnconditionallyRaise(OSError)
326 try:
327 t = writeTmp(1, ["\n"])
328 self.addCleanup(remove_tempfiles, t)
329 with FileInput(files=[t], inplace=True) as fi:
330 next(fi) # make sure the file is opened
331 os.unlink = os_unlink_replacement
332 fi.nextfile()
333 finally:
334 os.unlink = os_unlink_orig
335
336 # sanity check to make sure that our test scenario was actually hit
337 self.assertTrue(os_unlink_replacement.invoked,
338 "os.unlink() was not invoked")
339
340 def test_readline_os_fstat_raises_OSError(self):
341 """Tests invoking FileInput.readline() when os.fstat() raises OSError.
342 This exception should be silently discarded."""
343
344 os_fstat_orig = os.fstat
345 os_fstat_replacement = UnconditionallyRaise(OSError)
346 try:
347 t = writeTmp(1, ["\n"])
348 self.addCleanup(remove_tempfiles, t)
349 with FileInput(files=[t], inplace=True) as fi:
350 os.fstat = os_fstat_replacement
351 fi.readline()
352 finally:
353 os.fstat = os_fstat_orig
354
355 # sanity check to make sure that our test scenario was actually hit
356 self.assertTrue(os_fstat_replacement.invoked,
357 "os.fstat() was not invoked")
358
359 @unittest.skipIf(not hasattr(os, "chmod"), "os.chmod does not exist")
360 def test_readline_os_chmod_raises_OSError(self):
361 """Tests invoking FileInput.readline() when os.chmod() raises OSError.
362 This exception should be silently discarded."""
363
364 os_chmod_orig = os.chmod
365 os_chmod_replacement = UnconditionallyRaise(OSError)
366 try:
367 t = writeTmp(1, ["\n"])
368 self.addCleanup(remove_tempfiles, t)
369 with FileInput(files=[t], inplace=True) as fi:
370 os.chmod = os_chmod_replacement
371 fi.readline()
372 finally:
373 os.chmod = os_chmod_orig
374
375 # sanity check to make sure that our test scenario was actually hit
376 self.assertTrue(os_chmod_replacement.invoked,
377 "os.fstat() was not invoked")
378
379 def test_fileno_when_ValueError_raised(self):
380 class FilenoRaisesValueError(UnconditionallyRaise):
381 def __init__(self):
382 UnconditionallyRaise.__init__(self, ValueError)
383 def fileno(self):
384 self.__call__()
385
386 unconditionally_raise_ValueError = FilenoRaisesValueError()
387 t = writeTmp(1, ["\n"])
388 self.addCleanup(remove_tempfiles, t)
389 with FileInput(files=[t]) as fi:
390 file_backup = fi._file
391 try:
392 fi._file = unconditionally_raise_ValueError
393 result = fi.fileno()
394 finally:
395 fi._file = file_backup # make sure the file gets cleaned up
396
397 # sanity check to make sure that our test scenario was actually hit
398 self.assertTrue(unconditionally_raise_ValueError.invoked,
399 "_file.fileno() was not invoked")
400
401 self.assertEqual(result, -1, "fileno() should return -1")
402
403class MockFileInput:
404 """A class that mocks out fileinput.FileInput for use during unit tests"""
405
406 def __init__(self, files=None, inplace=False, backup="", bufsize=0,
407 mode="r", openhook=None):
408 self.files = files
409 self.inplace = inplace
410 self.backup = backup
411 self.bufsize = bufsize
412 self.mode = mode
413 self.openhook = openhook
414 self._file = None
415 self.invocation_counts = collections.defaultdict(lambda: 0)
416 self.return_values = {}
417
418 def close(self):
419 self.invocation_counts["close"] += 1
420
421 def nextfile(self):
422 self.invocation_counts["nextfile"] += 1
423 return self.return_values["nextfile"]
424
425 def filename(self):
426 self.invocation_counts["filename"] += 1
427 return self.return_values["filename"]
428
429 def lineno(self):
430 self.invocation_counts["lineno"] += 1
431 return self.return_values["lineno"]
432
433 def filelineno(self):
434 self.invocation_counts["filelineno"] += 1
435 return self.return_values["filelineno"]
436
437 def fileno(self):
438 self.invocation_counts["fileno"] += 1
439 return self.return_values["fileno"]
440
441 def isfirstline(self):
442 self.invocation_counts["isfirstline"] += 1
443 return self.return_values["isfirstline"]
444
445 def isstdin(self):
446 self.invocation_counts["isstdin"] += 1
447 return self.return_values["isstdin"]
448
449class BaseFileInputGlobalMethodsTest(unittest.TestCase):
450 """Base class for unit tests for the global function of
451 the fileinput module."""
452
453 def setUp(self):
454 self._orig_state = fileinput._state
455 self._orig_FileInput = fileinput.FileInput
456 fileinput.FileInput = MockFileInput
457
458 def tearDown(self):
459 fileinput.FileInput = self._orig_FileInput
460 fileinput._state = self._orig_state
461
462 def assertExactlyOneInvocation(self, mock_file_input, method_name):
463 # assert that the method with the given name was invoked once
464 actual_count = mock_file_input.invocation_counts[method_name]
465 self.assertEqual(actual_count, 1, method_name)
466 # assert that no other unexpected methods were invoked
467 actual_total_count = len(mock_file_input.invocation_counts)
468 self.assertEqual(actual_total_count, 1)
469
470class Test_fileinput_input(BaseFileInputGlobalMethodsTest):
471 """Unit tests for fileinput.input()"""
472
473 def test_state_is_not_None_and_state_file_is_not_None(self):
474 """Tests invoking fileinput.input() when fileinput._state is not None
475 and its _file attribute is also not None. Expect RuntimeError to
476 be raised with a meaningful error message and for fileinput._state
477 to *not* be modified."""
478 instance = MockFileInput()
479 instance._file = object()
480 fileinput._state = instance
481 with self.assertRaises(RuntimeError) as cm:
482 fileinput.input()
483 self.assertEqual(("input() already active",), cm.exception.args)
484 self.assertIs(instance, fileinput._state, "fileinput._state")
485
486 def test_state_is_not_None_and_state_file_is_None(self):
487 """Tests invoking fileinput.input() when fileinput._state is not None
488 but its _file attribute *is* None. Expect it to create and return
489 a new fileinput.FileInput object with all method parameters passed
490 explicitly to the __init__() method; also ensure that
491 fileinput._state is set to the returned instance."""
492 instance = MockFileInput()
493 instance._file = None
494 fileinput._state = instance
495 self.do_test_call_input()
496
497 def test_state_is_None(self):
498 """Tests invoking fileinput.input() when fileinput._state is None
499 Expect it to create and return a new fileinput.FileInput object
500 with all method parameters passed explicitly to the __init__()
501 method; also ensure that fileinput._state is set to the returned
502 instance."""
503 fileinput._state = None
504 self.do_test_call_input()
505
506 def do_test_call_input(self):
507 """Tests that fileinput.input() creates a new fileinput.FileInput
508 object, passing the given parameters unmodified to
509 fileinput.FileInput.__init__(). Note that this test depends on the
510 monkey patching of fileinput.FileInput done by setUp()."""
511 files = object()
512 inplace = object()
513 backup = object()
514 bufsize = object()
515 mode = object()
516 openhook = object()
517
518 # call fileinput.input() with different values for each argument
519 result = fileinput.input(files=files, inplace=inplace, backup=backup,
520 bufsize=bufsize,
521 mode=mode, openhook=openhook)
522
523 # ensure fileinput._state was set to the returned object
524 self.assertIs(result, fileinput._state, "fileinput._state")
525
526 # ensure the parameters to fileinput.input() were passed directly
527 # to FileInput.__init__()
528 self.assertIs(files, result.files, "files")
529 self.assertIs(inplace, result.inplace, "inplace")
530 self.assertIs(backup, result.backup, "backup")
531 self.assertIs(bufsize, result.bufsize, "bufsize")
532 self.assertIs(mode, result.mode, "mode")
533 self.assertIs(openhook, result.openhook, "openhook")
534
535class Test_fileinput_close(BaseFileInputGlobalMethodsTest):
536 """Unit tests for fileinput.close()"""
537
538 def test_state_is_None(self):
539 """Tests that fileinput.close() does nothing if fileinput._state
540 is None"""
541 fileinput._state = None
542 fileinput.close()
543 self.assertIsNone(fileinput._state)
544
545 def test_state_is_not_None(self):
546 """Tests that fileinput.close() invokes close() on fileinput._state
547 and sets _state=None"""
548 instance = MockFileInput()
549 fileinput._state = instance
550 fileinput.close()
551 self.assertExactlyOneInvocation(instance, "close")
552 self.assertIsNone(fileinput._state)
553
554class Test_fileinput_nextfile(BaseFileInputGlobalMethodsTest):
555 """Unit tests for fileinput.nextfile()"""
556
557 def test_state_is_None(self):
558 """Tests fileinput.nextfile() when fileinput._state is None.
559 Ensure that it raises RuntimeError with a meaningful error message
560 and does not modify fileinput._state"""
561 fileinput._state = None
562 with self.assertRaises(RuntimeError) as cm:
563 fileinput.nextfile()
564 self.assertEqual(("no active input()",), cm.exception.args)
565 self.assertIsNone(fileinput._state)
566
567 def test_state_is_not_None(self):
568 """Tests fileinput.nextfile() when fileinput._state is not None.
569 Ensure that it invokes fileinput._state.nextfile() exactly once,
570 returns whatever it returns, and does not modify fileinput._state
571 to point to a different object."""
572 nextfile_retval = object()
573 instance = MockFileInput()
574 instance.return_values["nextfile"] = nextfile_retval
575 fileinput._state = instance
576 retval = fileinput.nextfile()
577 self.assertExactlyOneInvocation(instance, "nextfile")
578 self.assertIs(retval, nextfile_retval)
579 self.assertIs(fileinput._state, instance)
580
581class Test_fileinput_filename(BaseFileInputGlobalMethodsTest):
582 """Unit tests for fileinput.filename()"""
583
584 def test_state_is_None(self):
585 """Tests fileinput.filename() when fileinput._state is None.
586 Ensure that it raises RuntimeError with a meaningful error message
587 and does not modify fileinput._state"""
588 fileinput._state = None
589 with self.assertRaises(RuntimeError) as cm:
590 fileinput.filename()
591 self.assertEqual(("no active input()",), cm.exception.args)
592 self.assertIsNone(fileinput._state)
593
594 def test_state_is_not_None(self):
595 """Tests fileinput.filename() when fileinput._state is not None.
596 Ensure that it invokes fileinput._state.filename() exactly once,
597 returns whatever it returns, and does not modify fileinput._state
598 to point to a different object."""
599 filename_retval = object()
600 instance = MockFileInput()
601 instance.return_values["filename"] = filename_retval
602 fileinput._state = instance
603 retval = fileinput.filename()
604 self.assertExactlyOneInvocation(instance, "filename")
605 self.assertIs(retval, filename_retval)
606 self.assertIs(fileinput._state, instance)
607
608class Test_fileinput_lineno(BaseFileInputGlobalMethodsTest):
609 """Unit tests for fileinput.lineno()"""
610
611 def test_state_is_None(self):
612 """Tests fileinput.lineno() when fileinput._state is None.
613 Ensure that it raises RuntimeError with a meaningful error message
614 and does not modify fileinput._state"""
615 fileinput._state = None
616 with self.assertRaises(RuntimeError) as cm:
617 fileinput.lineno()
618 self.assertEqual(("no active input()",), cm.exception.args)
619 self.assertIsNone(fileinput._state)
620
621 def test_state_is_not_None(self):
622 """Tests fileinput.lineno() when fileinput._state is not None.
623 Ensure that it invokes fileinput._state.lineno() exactly once,
624 returns whatever it returns, and does not modify fileinput._state
625 to point to a different object."""
626 lineno_retval = object()
627 instance = MockFileInput()
628 instance.return_values["lineno"] = lineno_retval
629 fileinput._state = instance
630 retval = fileinput.lineno()
631 self.assertExactlyOneInvocation(instance, "lineno")
632 self.assertIs(retval, lineno_retval)
633 self.assertIs(fileinput._state, instance)
634
635class Test_fileinput_filelineno(BaseFileInputGlobalMethodsTest):
636 """Unit tests for fileinput.filelineno()"""
637
638 def test_state_is_None(self):
639 """Tests fileinput.filelineno() when fileinput._state is None.
640 Ensure that it raises RuntimeError with a meaningful error message
641 and does not modify fileinput._state"""
642 fileinput._state = None
643 with self.assertRaises(RuntimeError) as cm:
644 fileinput.filelineno()
645 self.assertEqual(("no active input()",), cm.exception.args)
646 self.assertIsNone(fileinput._state)
647
648 def test_state_is_not_None(self):
649 """Tests fileinput.filelineno() when fileinput._state is not None.
650 Ensure that it invokes fileinput._state.filelineno() exactly once,
651 returns whatever it returns, and does not modify fileinput._state
652 to point to a different object."""
653 filelineno_retval = object()
654 instance = MockFileInput()
655 instance.return_values["filelineno"] = filelineno_retval
656 fileinput._state = instance
657 retval = fileinput.filelineno()
658 self.assertExactlyOneInvocation(instance, "filelineno")
659 self.assertIs(retval, filelineno_retval)
660 self.assertIs(fileinput._state, instance)
661
662class Test_fileinput_fileno(BaseFileInputGlobalMethodsTest):
663 """Unit tests for fileinput.fileno()"""
664
665 def test_state_is_None(self):
666 """Tests fileinput.fileno() when fileinput._state is None.
667 Ensure that it raises RuntimeError with a meaningful error message
668 and does not modify fileinput._state"""
669 fileinput._state = None
670 with self.assertRaises(RuntimeError) as cm:
671 fileinput.fileno()
672 self.assertEqual(("no active input()",), cm.exception.args)
673 self.assertIsNone(fileinput._state)
674
675 def test_state_is_not_None(self):
676 """Tests fileinput.fileno() when fileinput._state is not None.
677 Ensure that it invokes fileinput._state.fileno() exactly once,
678 returns whatever it returns, and does not modify fileinput._state
679 to point to a different object."""
680 fileno_retval = object()
681 instance = MockFileInput()
682 instance.return_values["fileno"] = fileno_retval
683 instance.fileno_retval = fileno_retval
684 fileinput._state = instance
685 retval = fileinput.fileno()
686 self.assertExactlyOneInvocation(instance, "fileno")
687 self.assertIs(retval, fileno_retval)
688 self.assertIs(fileinput._state, instance)
689
690class Test_fileinput_isfirstline(BaseFileInputGlobalMethodsTest):
691 """Unit tests for fileinput.isfirstline()"""
692
693 def test_state_is_None(self):
694 """Tests fileinput.isfirstline() when fileinput._state is None.
695 Ensure that it raises RuntimeError with a meaningful error message
696 and does not modify fileinput._state"""
697 fileinput._state = None
698 with self.assertRaises(RuntimeError) as cm:
699 fileinput.isfirstline()
700 self.assertEqual(("no active input()",), cm.exception.args)
701 self.assertIsNone(fileinput._state)
702
703 def test_state_is_not_None(self):
704 """Tests fileinput.isfirstline() when fileinput._state is not None.
705 Ensure that it invokes fileinput._state.isfirstline() exactly once,
706 returns whatever it returns, and does not modify fileinput._state
707 to point to a different object."""
708 isfirstline_retval = object()
709 instance = MockFileInput()
710 instance.return_values["isfirstline"] = isfirstline_retval
711 fileinput._state = instance
712 retval = fileinput.isfirstline()
713 self.assertExactlyOneInvocation(instance, "isfirstline")
714 self.assertIs(retval, isfirstline_retval)
715 self.assertIs(fileinput._state, instance)
716
717class Test_fileinput_isstdin(BaseFileInputGlobalMethodsTest):
718 """Unit tests for fileinput.isstdin()"""
719
720 def test_state_is_None(self):
721 """Tests fileinput.isstdin() when fileinput._state is None.
722 Ensure that it raises RuntimeError with a meaningful error message
723 and does not modify fileinput._state"""
724 fileinput._state = None
725 with self.assertRaises(RuntimeError) as cm:
726 fileinput.isstdin()
727 self.assertEqual(("no active input()",), cm.exception.args)
728 self.assertIsNone(fileinput._state)
729
730 def test_state_is_not_None(self):
731 """Tests fileinput.isstdin() when fileinput._state is not None.
732 Ensure that it invokes fileinput._state.isstdin() exactly once,
733 returns whatever it returns, and does not modify fileinput._state
734 to point to a different object."""
735 isstdin_retval = object()
736 instance = MockFileInput()
737 instance.return_values["isstdin"] = isstdin_retval
738 fileinput._state = instance
739 retval = fileinput.isstdin()
740 self.assertExactlyOneInvocation(instance, "isstdin")
741 self.assertIs(retval, isstdin_retval)
742 self.assertIs(fileinput._state, instance)
743
744class InvocationRecorder:
745 def __init__(self):
746 self.invocation_count = 0
747 def __call__(self, *args, **kwargs):
748 self.invocation_count += 1
749 self.last_invocation = (args, kwargs)
750
751class Test_hook_compressed(unittest.TestCase):
752 """Unit tests for fileinput.hook_compressed()"""
753
754 def setUp(self):
755 self.fake_open = InvocationRecorder()
756
757 def test_empty_string(self):
758 self.do_test_use_builtin_open("", 1)
759
760 def test_no_ext(self):
761 self.do_test_use_builtin_open("abcd", 2)
762
Ezio Melottic3afbb92011-05-14 10:10:53 +0300763 @unittest.skipUnless(gzip, "Requires gzip and zlib")
briancurtin5eb35912011-03-15 10:59:36 -0400764 def test_gz_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400765 original_open = gzip.open
766 gzip.open = self.fake_open
767 try:
768 result = fileinput.hook_compressed("test.gz", 3)
769 finally:
770 gzip.open = original_open
771
772 self.assertEqual(self.fake_open.invocation_count, 1)
773 self.assertEqual(self.fake_open.last_invocation, (("test.gz", 3), {}))
774
briancurtinf84f3c32011-03-18 13:03:17 -0500775 @unittest.skipUnless(bz2, "Requires bz2")
briancurtin5eb35912011-03-15 10:59:36 -0400776 def test_bz2_ext_fake(self):
briancurtin906f0c42011-03-15 10:29:41 -0400777 original_open = bz2.BZ2File
778 bz2.BZ2File = self.fake_open
779 try:
780 result = fileinput.hook_compressed("test.bz2", 4)
781 finally:
782 bz2.BZ2File = original_open
783
784 self.assertEqual(self.fake_open.invocation_count, 1)
785 self.assertEqual(self.fake_open.last_invocation, (("test.bz2", 4), {}))
786
787 def test_blah_ext(self):
788 self.do_test_use_builtin_open("abcd.blah", 5)
789
briancurtin5eb35912011-03-15 10:59:36 -0400790 def test_gz_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400791 self.do_test_use_builtin_open("abcd.Gz", 6)
792
briancurtin5eb35912011-03-15 10:59:36 -0400793 def test_bz2_ext_builtin(self):
briancurtin906f0c42011-03-15 10:29:41 -0400794 self.do_test_use_builtin_open("abcd.Bz2", 7)
795
796 def do_test_use_builtin_open(self, filename, mode):
797 original_open = self.replace_builtin_open(self.fake_open)
798 try:
799 result = fileinput.hook_compressed(filename, mode)
800 finally:
801 self.replace_builtin_open(original_open)
802
803 self.assertEqual(self.fake_open.invocation_count, 1)
804 self.assertEqual(self.fake_open.last_invocation,
805 ((filename, mode), {}))
806
807 @staticmethod
808 def replace_builtin_open(new_open_func):
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100809 original_open = builtins.open
810 builtins.open = new_open_func
briancurtin906f0c42011-03-15 10:29:41 -0400811 return original_open
812
813class Test_hook_encoded(unittest.TestCase):
814 """Unit tests for fileinput.hook_encoded()"""
815
816 def test(self):
817 encoding = object()
818 result = fileinput.hook_encoded(encoding)
819
820 fake_open = InvocationRecorder()
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100821 original_open = builtins.open
822 builtins.open = fake_open
briancurtin906f0c42011-03-15 10:29:41 -0400823 try:
824 filename = object()
825 mode = object()
826 open_result = result(filename, mode)
827 finally:
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100828 builtins.open = original_open
briancurtin906f0c42011-03-15 10:29:41 -0400829
830 self.assertEqual(fake_open.invocation_count, 1)
831
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100832 args, kwargs = fake_open.last_invocation
briancurtin906f0c42011-03-15 10:29:41 -0400833 self.assertIs(args[0], filename)
834 self.assertIs(args[1], mode)
Florent Xiclunaa011e2b2011-11-07 19:43:07 +0100835 self.assertIs(kwargs.pop('encoding'), encoding)
836 self.assertFalse(kwargs)
Georg Brandl6cb7b652010-07-31 20:08:15 +0000837
Guido van Rossumd8faa362007-04-27 19:54:29 +0000838def test_main():
briancurtin906f0c42011-03-15 10:29:41 -0400839 run_unittest(
840 BufferSizesTests,
841 FileInputTests,
842 Test_fileinput_input,
843 Test_fileinput_close,
844 Test_fileinput_nextfile,
845 Test_fileinput_filename,
846 Test_fileinput_lineno,
847 Test_fileinput_filelineno,
848 Test_fileinput_fileno,
849 Test_fileinput_isfirstline,
850 Test_fileinput_isstdin,
851 Test_hook_compressed,
852 Test_hook_encoded,
853 )
Guido van Rossumd8faa362007-04-27 19:54:29 +0000854
855if __name__ == "__main__":
856 test_main()