Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 1 | ''' |
| 2 | Tests for fileinput module. |
| 3 | Nick Mathewson |
| 4 | ''' |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 5 | import os |
| 6 | import sys |
| 7 | import re |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 8 | import fileinput |
| 9 | import collections |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 10 | import builtins |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 11 | import tempfile |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 12 | import unittest |
| 13 | |
briancurtin | f84f3c3 | 2011-03-18 13:03:17 -0500 | [diff] [blame] | 14 | try: |
| 15 | import bz2 |
| 16 | except ImportError: |
| 17 | bz2 = None |
Ezio Melotti | c3afbb9 | 2011-05-14 10:10:53 +0300 | [diff] [blame] | 18 | try: |
| 19 | import gzip |
| 20 | except ImportError: |
| 21 | gzip = None |
briancurtin | f84f3c3 | 2011-03-18 13:03:17 -0500 | [diff] [blame] | 22 | |
Serhiy Storchaka | 946cfc3 | 2014-05-14 21:08:33 +0300 | [diff] [blame] | 23 | from io import BytesIO, StringIO |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 24 | from fileinput import FileInput, hook_encoded |
Roy Williams | 002665a | 2017-05-22 22:24:17 -0700 | [diff] [blame] | 25 | from pathlib import Path |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 26 | |
Serhiy Storchaka | 597d15a | 2016-04-24 13:45:58 +0300 | [diff] [blame] | 27 | from test.support import verbose, TESTFN, check_warnings |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 28 | from test.support import unlink as safe_unlink |
Martin Panter | 7978e10 | 2016-01-16 06:26:54 +0000 | [diff] [blame] | 29 | from test import support |
Serhiy Storchaka | 946cfc3 | 2014-05-14 21:08:33 +0300 | [diff] [blame] | 30 | from unittest import mock |
Benjamin Peterson | eb46288 | 2011-03-15 09:50:18 -0500 | [diff] [blame] | 31 | |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 32 | |
| 33 | # The fileinput module has 2 interfaces: the FileInput class which does |
| 34 | # all the work, and a few functions (input, etc.) that use a global _state |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 35 | # variable. |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 36 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 37 | class BaseTests: |
| 38 | # Write a content (str or bytes) to temp file, and return the |
| 39 | # temp file's name. |
| 40 | def writeTmp(self, content, *, mode='w'): # opening in text mode is the default |
| 41 | fd, name = tempfile.mkstemp() |
| 42 | self.addCleanup(support.unlink, name) |
| 43 | with open(fd, mode) as f: |
| 44 | f.write(content) |
| 45 | return name |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 46 | |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 47 | class LineReader: |
| 48 | |
| 49 | def __init__(self): |
| 50 | self._linesread = [] |
| 51 | |
| 52 | @property |
| 53 | def linesread(self): |
| 54 | try: |
| 55 | return self._linesread[:] |
| 56 | finally: |
| 57 | self._linesread = [] |
| 58 | |
| 59 | def openhook(self, filename, mode): |
| 60 | self.it = iter(filename.splitlines(True)) |
| 61 | return self |
| 62 | |
| 63 | def readline(self, size=None): |
| 64 | line = next(self.it, '') |
| 65 | self._linesread.append(line) |
| 66 | return line |
| 67 | |
| 68 | def readlines(self, hint=-1): |
| 69 | lines = [] |
| 70 | size = 0 |
| 71 | while True: |
| 72 | line = self.readline() |
| 73 | if not line: |
| 74 | return lines |
| 75 | lines.append(line) |
| 76 | size += len(line) |
| 77 | if size >= hint: |
| 78 | return lines |
| 79 | |
| 80 | def close(self): |
| 81 | pass |
| 82 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 83 | class BufferSizesTests(BaseTests, unittest.TestCase): |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 84 | def test_buffer_sizes(self): |
| 85 | # First, run the tests with default and teeny buffer size. |
| 86 | for round, bs in (0, 0), (1, 30): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 87 | t1 = self.writeTmp(''.join("Line %s of file 1\n" % (i+1) for i in range(15))) |
| 88 | t2 = self.writeTmp(''.join("Line %s of file 2\n" % (i+1) for i in range(10))) |
| 89 | t3 = self.writeTmp(''.join("Line %s of file 3\n" % (i+1) for i in range(5))) |
| 90 | t4 = self.writeTmp(''.join("Line %s of file 4\n" % (i+1) for i in range(1))) |
| 91 | if bs: |
| 92 | with self.assertWarns(DeprecationWarning): |
Serhiy Storchaka | 674e2d0 | 2016-03-08 18:35:19 +0200 | [diff] [blame] | 93 | self.buffer_size_test(t1, t2, t3, t4, bs, round) |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 94 | else: |
| 95 | self.buffer_size_test(t1, t2, t3, t4, bs, round) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 96 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 97 | def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0): |
| 98 | pat = re.compile(r'LINE (\d+) OF FILE (\d+)') |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 99 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 100 | start = 1 + round*6 |
| 101 | if verbose: |
| 102 | print('%s. Simple iteration (bs=%s)' % (start+0, bs)) |
| 103 | fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 104 | lines = list(fi) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 105 | fi.close() |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 106 | self.assertEqual(len(lines), 31) |
| 107 | self.assertEqual(lines[4], 'Line 5 of file 1\n') |
| 108 | self.assertEqual(lines[30], 'Line 1 of file 4\n') |
| 109 | self.assertEqual(fi.lineno(), 31) |
| 110 | self.assertEqual(fi.filename(), t4) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 111 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 112 | if verbose: |
| 113 | print('%s. Status variables (bs=%s)' % (start+1, bs)) |
| 114 | fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) |
| 115 | s = "x" |
| 116 | while s and s != 'Line 6 of file 2\n': |
| 117 | s = fi.readline() |
| 118 | self.assertEqual(fi.filename(), t2) |
| 119 | self.assertEqual(fi.lineno(), 21) |
| 120 | self.assertEqual(fi.filelineno(), 6) |
Benjamin Peterson | c9c0f20 | 2009-06-30 23:06:06 +0000 | [diff] [blame] | 121 | self.assertFalse(fi.isfirstline()) |
| 122 | self.assertFalse(fi.isstdin()) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 123 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 124 | if verbose: |
| 125 | print('%s. Nextfile (bs=%s)' % (start+2, bs)) |
| 126 | fi.nextfile() |
| 127 | self.assertEqual(fi.readline(), 'Line 1 of file 3\n') |
| 128 | self.assertEqual(fi.lineno(), 22) |
| 129 | fi.close() |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 130 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 131 | if verbose: |
| 132 | print('%s. Stdin (bs=%s)' % (start+3, bs)) |
| 133 | fi = FileInput(files=(t1, t2, t3, t4, '-'), bufsize=bs) |
| 134 | savestdin = sys.stdin |
| 135 | try: |
| 136 | sys.stdin = StringIO("Line 1 of stdin\nLine 2 of stdin\n") |
| 137 | lines = list(fi) |
| 138 | self.assertEqual(len(lines), 33) |
| 139 | self.assertEqual(lines[32], 'Line 2 of stdin\n') |
| 140 | self.assertEqual(fi.filename(), '<stdin>') |
| 141 | fi.nextfile() |
| 142 | finally: |
| 143 | sys.stdin = savestdin |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 144 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 145 | if verbose: |
| 146 | print('%s. Boundary conditions (bs=%s)' % (start+4, bs)) |
| 147 | fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) |
| 148 | self.assertEqual(fi.lineno(), 0) |
| 149 | self.assertEqual(fi.filename(), None) |
| 150 | fi.nextfile() |
| 151 | self.assertEqual(fi.lineno(), 0) |
| 152 | self.assertEqual(fi.filename(), None) |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 153 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 154 | if verbose: |
| 155 | print('%s. Inplace (bs=%s)' % (start+5, bs)) |
| 156 | savestdout = sys.stdout |
| 157 | try: |
| 158 | fi = FileInput(files=(t1, t2, t3, t4), inplace=1, bufsize=bs) |
| 159 | for line in fi: |
| 160 | line = line[:-1].upper() |
| 161 | print(line) |
| 162 | fi.close() |
| 163 | finally: |
| 164 | sys.stdout = savestdout |
Tim Peters | 3230d5c | 2001-07-11 22:21:17 +0000 | [diff] [blame] | 165 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 166 | fi = FileInput(files=(t1, t2, t3, t4), bufsize=bs) |
| 167 | for line in fi: |
| 168 | self.assertEqual(line[-1], '\n') |
| 169 | m = pat.match(line[:-1]) |
| 170 | self.assertNotEqual(m, None) |
| 171 | self.assertEqual(int(m.group(1)), fi.filelineno()) |
| 172 | fi.close() |
Georg Brandl | e466217 | 2006-02-19 09:51:27 +0000 | [diff] [blame] | 173 | |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 174 | class UnconditionallyRaise: |
| 175 | def __init__(self, exception_type): |
| 176 | self.exception_type = exception_type |
| 177 | self.invoked = False |
| 178 | def __call__(self, *args, **kwargs): |
| 179 | self.invoked = True |
| 180 | raise self.exception_type() |
| 181 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 182 | class FileInputTests(BaseTests, unittest.TestCase): |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 183 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 184 | def test_zero_byte_files(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 185 | t1 = self.writeTmp("") |
| 186 | t2 = self.writeTmp("") |
| 187 | t3 = self.writeTmp("The only line there is.\n") |
| 188 | t4 = self.writeTmp("") |
| 189 | fi = FileInput(files=(t1, t2, t3, t4)) |
Georg Brandl | 67e9fb9 | 2006-02-19 13:56:17 +0000 | [diff] [blame] | 190 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 191 | line = fi.readline() |
| 192 | self.assertEqual(line, 'The only line there is.\n') |
| 193 | self.assertEqual(fi.lineno(), 1) |
| 194 | self.assertEqual(fi.filelineno(), 1) |
| 195 | self.assertEqual(fi.filename(), t3) |
Georg Brandl | c029f87 | 2006-02-19 14:12:34 +0000 | [diff] [blame] | 196 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 197 | line = fi.readline() |
| 198 | self.assertFalse(line) |
| 199 | self.assertEqual(fi.lineno(), 1) |
| 200 | self.assertEqual(fi.filelineno(), 0) |
| 201 | self.assertEqual(fi.filename(), t4) |
| 202 | fi.close() |
Georg Brandl | c98eeed | 2006-02-19 14:57:47 +0000 | [diff] [blame] | 203 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 204 | def test_files_that_dont_end_with_newline(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 205 | t1 = self.writeTmp("A\nB\nC") |
| 206 | t2 = self.writeTmp("D\nE\nF") |
| 207 | fi = FileInput(files=(t1, t2)) |
| 208 | lines = list(fi) |
| 209 | self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"]) |
| 210 | self.assertEqual(fi.filelineno(), 3) |
| 211 | self.assertEqual(fi.lineno(), 6) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 212 | |
Guido van Rossum | c43e79f | 2007-06-18 18:26:36 +0000 | [diff] [blame] | 213 | ## def test_unicode_filenames(self): |
| 214 | ## # XXX A unicode string is always returned by writeTmp. |
| 215 | ## # So is this needed? |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 216 | ## t1 = self.writeTmp("A\nB") |
| 217 | ## encoding = sys.getfilesystemencoding() |
| 218 | ## if encoding is None: |
| 219 | ## encoding = 'ascii' |
| 220 | ## fi = FileInput(files=str(t1, encoding)) |
| 221 | ## lines = list(fi) |
| 222 | ## self.assertEqual(lines, ["A\n", "B"]) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 223 | |
| 224 | def test_fileno(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 225 | t1 = self.writeTmp("A\nB") |
| 226 | t2 = self.writeTmp("C\nD") |
| 227 | fi = FileInput(files=(t1, t2)) |
| 228 | self.assertEqual(fi.fileno(), -1) |
| 229 | line = next(fi) |
| 230 | self.assertNotEqual(fi.fileno(), -1) |
| 231 | fi.nextfile() |
| 232 | self.assertEqual(fi.fileno(), -1) |
| 233 | line = list(fi) |
| 234 | self.assertEqual(fi.fileno(), -1) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 235 | |
| 236 | def test_opening_mode(self): |
| 237 | try: |
| 238 | # invalid mode, should raise ValueError |
| 239 | fi = FileInput(mode="w") |
| 240 | self.fail("FileInput should reject invalid mode argument") |
| 241 | except ValueError: |
| 242 | pass |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 243 | # try opening in universal newline mode |
| 244 | t1 = self.writeTmp(b"A\nB\r\nC\rD", mode="wb") |
| 245 | with check_warnings(('', DeprecationWarning)): |
| 246 | fi = FileInput(files=t1, mode="U") |
| 247 | with check_warnings(('', DeprecationWarning)): |
| 248 | lines = list(fi) |
| 249 | self.assertEqual(lines, ["A\n", "B\n", "C\n", "D"]) |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 250 | |
Serhiy Storchaka | 946cfc3 | 2014-05-14 21:08:33 +0300 | [diff] [blame] | 251 | def test_stdin_binary_mode(self): |
| 252 | with mock.patch('sys.stdin') as m_stdin: |
| 253 | m_stdin.buffer = BytesIO(b'spam, bacon, sausage, and spam') |
| 254 | fi = FileInput(files=['-'], mode='rb') |
| 255 | lines = list(fi) |
| 256 | self.assertEqual(lines, [b'spam, bacon, sausage, and spam']) |
| 257 | |
R David Murray | 830207e | 2016-01-02 15:41:41 -0500 | [diff] [blame] | 258 | def test_detached_stdin_binary_mode(self): |
| 259 | orig_stdin = sys.stdin |
| 260 | try: |
| 261 | sys.stdin = BytesIO(b'spam, bacon, sausage, and spam') |
| 262 | self.assertFalse(hasattr(sys.stdin, 'buffer')) |
| 263 | fi = FileInput(files=['-'], mode='rb') |
| 264 | lines = list(fi) |
| 265 | self.assertEqual(lines, [b'spam, bacon, sausage, and spam']) |
| 266 | finally: |
| 267 | sys.stdin = orig_stdin |
| 268 | |
Guido van Rossum | e22905a | 2007-08-27 23:09:25 +0000 | [diff] [blame] | 269 | def test_file_opening_hook(self): |
| 270 | try: |
| 271 | # cannot use openhook and inplace mode |
| 272 | fi = FileInput(inplace=1, openhook=lambda f, m: None) |
| 273 | self.fail("FileInput should raise if both inplace " |
| 274 | "and openhook arguments are given") |
| 275 | except ValueError: |
| 276 | pass |
| 277 | try: |
| 278 | fi = FileInput(openhook=1) |
| 279 | self.fail("FileInput should check openhook for being callable") |
| 280 | except ValueError: |
| 281 | pass |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 282 | |
| 283 | class CustomOpenHook: |
| 284 | def __init__(self): |
| 285 | self.invoked = False |
| 286 | def __call__(self, *args): |
| 287 | self.invoked = True |
| 288 | return open(*args) |
| 289 | |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 290 | t = self.writeTmp("\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 291 | custom_open_hook = CustomOpenHook() |
| 292 | with FileInput([t], openhook=custom_open_hook) as fi: |
| 293 | fi.readline() |
| 294 | self.assertTrue(custom_open_hook.invoked, "openhook not invoked") |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 295 | |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 296 | def test_readline(self): |
| 297 | with open(TESTFN, 'wb') as f: |
| 298 | f.write(b'A\nB\r\nC\r') |
| 299 | # Fill TextIOWrapper buffer. |
| 300 | f.write(b'123456789\n' * 1000) |
| 301 | # Issue #20501: readline() shouldn't read whole file. |
| 302 | f.write(b'\x80') |
| 303 | self.addCleanup(safe_unlink, TESTFN) |
| 304 | |
| 305 | with FileInput(files=TESTFN, |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 306 | openhook=hook_encoded('ascii')) as fi: |
Serhiy Storchaka | 682ea5f | 2014-03-03 21:17:17 +0200 | [diff] [blame] | 307 | try: |
| 308 | self.assertEqual(fi.readline(), 'A\n') |
| 309 | self.assertEqual(fi.readline(), 'B\n') |
| 310 | self.assertEqual(fi.readline(), 'C\n') |
| 311 | except UnicodeDecodeError: |
| 312 | self.fail('Read to end of file') |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 313 | with self.assertRaises(UnicodeDecodeError): |
| 314 | # Read to the end of file. |
| 315 | list(fi) |
Serhiy Storchaka | 314464d | 2015-11-01 16:43:58 +0200 | [diff] [blame] | 316 | self.assertEqual(fi.readline(), '') |
| 317 | self.assertEqual(fi.readline(), '') |
| 318 | |
| 319 | def test_readline_binary_mode(self): |
| 320 | with open(TESTFN, 'wb') as f: |
| 321 | f.write(b'A\nB\r\nC\rD') |
| 322 | self.addCleanup(safe_unlink, TESTFN) |
| 323 | |
| 324 | with FileInput(files=TESTFN, mode='rb') as fi: |
| 325 | self.assertEqual(fi.readline(), b'A\n') |
| 326 | self.assertEqual(fi.readline(), b'B\r\n') |
| 327 | self.assertEqual(fi.readline(), b'C\rD') |
| 328 | # Read to the end of file. |
| 329 | self.assertEqual(fi.readline(), b'') |
| 330 | self.assertEqual(fi.readline(), b'') |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 331 | |
Berker Peksag | be6dbfb | 2019-04-29 17:55:39 +0300 | [diff] [blame] | 332 | def test_inplace_binary_write_mode(self): |
| 333 | temp_file = self.writeTmp(b'Initial text.', mode='wb') |
| 334 | with FileInput(temp_file, mode='rb', inplace=True) as fobj: |
| 335 | line = fobj.readline() |
| 336 | self.assertEqual(line, b'Initial text.') |
| 337 | # print() cannot be used with files opened in binary mode. |
| 338 | sys.stdout.write(b'New line.') |
| 339 | with open(temp_file, 'rb') as f: |
| 340 | self.assertEqual(f.read(), b'New line.') |
| 341 | |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 342 | def test_context_manager(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 343 | t1 = self.writeTmp("A\nB\nC") |
| 344 | t2 = self.writeTmp("D\nE\nF") |
| 345 | with FileInput(files=(t1, t2)) as fi: |
| 346 | lines = list(fi) |
| 347 | self.assertEqual(lines, ["A\n", "B\n", "C", "D\n", "E\n", "F"]) |
| 348 | self.assertEqual(fi.filelineno(), 3) |
| 349 | self.assertEqual(fi.lineno(), 6) |
| 350 | self.assertEqual(fi._files, ()) |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 351 | |
| 352 | def test_close_on_exception(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 353 | t1 = self.writeTmp("") |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 354 | try: |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 355 | with FileInput(files=t1) as fi: |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 356 | raise OSError |
| 357 | except OSError: |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 358 | self.assertEqual(fi._files, ()) |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 359 | |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 360 | def test_empty_files_list_specified_to_constructor(self): |
| 361 | with FileInput(files=[]) as fi: |
Brett Cannon | d47af53 | 2011-03-15 15:55:12 -0400 | [diff] [blame] | 362 | self.assertEqual(fi._files, ('-',)) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 363 | |
Berker Peksag | 84a13fb | 2018-08-11 09:05:04 +0300 | [diff] [blame] | 364 | @support.ignore_warnings(category=DeprecationWarning) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 365 | def test__getitem__(self): |
| 366 | """Tests invoking FileInput.__getitem__() with the current |
| 367 | line number""" |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 368 | t = self.writeTmp("line1\nline2\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 369 | with FileInput(files=[t]) as fi: |
| 370 | retval1 = fi[0] |
| 371 | self.assertEqual(retval1, "line1\n") |
| 372 | retval2 = fi[1] |
| 373 | self.assertEqual(retval2, "line2\n") |
| 374 | |
Berker Peksag | 84a13fb | 2018-08-11 09:05:04 +0300 | [diff] [blame] | 375 | def test__getitem___deprecation(self): |
| 376 | t = self.writeTmp("line1\nline2\n") |
| 377 | with self.assertWarnsRegex(DeprecationWarning, |
| 378 | r'Use iterator protocol instead'): |
| 379 | with FileInput(files=[t]) as fi: |
| 380 | self.assertEqual(fi[0], "line1\n") |
| 381 | |
| 382 | @support.ignore_warnings(category=DeprecationWarning) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 383 | def test__getitem__invalid_key(self): |
| 384 | """Tests invoking FileInput.__getitem__() with an index unequal to |
| 385 | the line number""" |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 386 | t = self.writeTmp("line1\nline2\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 387 | with FileInput(files=[t]) as fi: |
| 388 | with self.assertRaises(RuntimeError) as cm: |
| 389 | fi[1] |
Brett Cannon | d47af53 | 2011-03-15 15:55:12 -0400 | [diff] [blame] | 390 | self.assertEqual(cm.exception.args, ("accessing lines out of order",)) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 391 | |
Berker Peksag | 84a13fb | 2018-08-11 09:05:04 +0300 | [diff] [blame] | 392 | @support.ignore_warnings(category=DeprecationWarning) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 393 | def test__getitem__eof(self): |
| 394 | """Tests invoking FileInput.__getitem__() with the line number but at |
| 395 | end-of-input""" |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 396 | t = self.writeTmp('') |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 397 | with FileInput(files=[t]) as fi: |
| 398 | with self.assertRaises(IndexError) as cm: |
| 399 | fi[0] |
Brett Cannon | d47af53 | 2011-03-15 15:55:12 -0400 | [diff] [blame] | 400 | self.assertEqual(cm.exception.args, ("end of input reached",)) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 401 | |
| 402 | def test_nextfile_oserror_deleting_backup(self): |
| 403 | """Tests invoking FileInput.nextfile() when the attempt to delete |
| 404 | the backup file would raise OSError. This error is expected to be |
| 405 | silently ignored""" |
| 406 | |
| 407 | os_unlink_orig = os.unlink |
| 408 | os_unlink_replacement = UnconditionallyRaise(OSError) |
| 409 | try: |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 410 | t = self.writeTmp("\n") |
| 411 | self.addCleanup(support.unlink, t + '.bak') |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 412 | with FileInput(files=[t], inplace=True) as fi: |
| 413 | next(fi) # make sure the file is opened |
| 414 | os.unlink = os_unlink_replacement |
| 415 | fi.nextfile() |
| 416 | finally: |
| 417 | os.unlink = os_unlink_orig |
| 418 | |
| 419 | # sanity check to make sure that our test scenario was actually hit |
| 420 | self.assertTrue(os_unlink_replacement.invoked, |
| 421 | "os.unlink() was not invoked") |
| 422 | |
| 423 | def test_readline_os_fstat_raises_OSError(self): |
| 424 | """Tests invoking FileInput.readline() when os.fstat() raises OSError. |
| 425 | This exception should be silently discarded.""" |
| 426 | |
| 427 | os_fstat_orig = os.fstat |
| 428 | os_fstat_replacement = UnconditionallyRaise(OSError) |
| 429 | try: |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 430 | t = self.writeTmp("\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 431 | with FileInput(files=[t], inplace=True) as fi: |
| 432 | os.fstat = os_fstat_replacement |
| 433 | fi.readline() |
| 434 | finally: |
| 435 | os.fstat = os_fstat_orig |
| 436 | |
| 437 | # sanity check to make sure that our test scenario was actually hit |
| 438 | self.assertTrue(os_fstat_replacement.invoked, |
| 439 | "os.fstat() was not invoked") |
| 440 | |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 441 | def test_readline_os_chmod_raises_OSError(self): |
| 442 | """Tests invoking FileInput.readline() when os.chmod() raises OSError. |
| 443 | This exception should be silently discarded.""" |
| 444 | |
| 445 | os_chmod_orig = os.chmod |
| 446 | os_chmod_replacement = UnconditionallyRaise(OSError) |
| 447 | try: |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 448 | t = self.writeTmp("\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 449 | with FileInput(files=[t], inplace=True) as fi: |
| 450 | os.chmod = os_chmod_replacement |
| 451 | fi.readline() |
| 452 | finally: |
| 453 | os.chmod = os_chmod_orig |
| 454 | |
| 455 | # sanity check to make sure that our test scenario was actually hit |
| 456 | self.assertTrue(os_chmod_replacement.invoked, |
| 457 | "os.fstat() was not invoked") |
| 458 | |
| 459 | def test_fileno_when_ValueError_raised(self): |
| 460 | class FilenoRaisesValueError(UnconditionallyRaise): |
| 461 | def __init__(self): |
| 462 | UnconditionallyRaise.__init__(self, ValueError) |
| 463 | def fileno(self): |
| 464 | self.__call__() |
| 465 | |
| 466 | unconditionally_raise_ValueError = FilenoRaisesValueError() |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 467 | t = self.writeTmp("\n") |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 468 | with FileInput(files=[t]) as fi: |
| 469 | file_backup = fi._file |
| 470 | try: |
| 471 | fi._file = unconditionally_raise_ValueError |
| 472 | result = fi.fileno() |
| 473 | finally: |
| 474 | fi._file = file_backup # make sure the file gets cleaned up |
| 475 | |
| 476 | # sanity check to make sure that our test scenario was actually hit |
| 477 | self.assertTrue(unconditionally_raise_ValueError.invoked, |
| 478 | "_file.fileno() was not invoked") |
| 479 | |
| 480 | self.assertEqual(result, -1, "fileno() should return -1") |
| 481 | |
Serhiy Storchaka | cc2dbc5 | 2016-03-08 18:28:36 +0200 | [diff] [blame] | 482 | def test_readline_buffering(self): |
| 483 | src = LineReader() |
| 484 | with FileInput(files=['line1\nline2', 'line3\n'], |
| 485 | openhook=src.openhook) as fi: |
| 486 | self.assertEqual(src.linesread, []) |
| 487 | self.assertEqual(fi.readline(), 'line1\n') |
| 488 | self.assertEqual(src.linesread, ['line1\n']) |
| 489 | self.assertEqual(fi.readline(), 'line2') |
| 490 | self.assertEqual(src.linesread, ['line2']) |
| 491 | self.assertEqual(fi.readline(), 'line3\n') |
| 492 | self.assertEqual(src.linesread, ['', 'line3\n']) |
| 493 | self.assertEqual(fi.readline(), '') |
| 494 | self.assertEqual(src.linesread, ['']) |
| 495 | self.assertEqual(fi.readline(), '') |
| 496 | self.assertEqual(src.linesread, []) |
| 497 | |
| 498 | def test_iteration_buffering(self): |
| 499 | src = LineReader() |
| 500 | with FileInput(files=['line1\nline2', 'line3\n'], |
| 501 | openhook=src.openhook) as fi: |
| 502 | self.assertEqual(src.linesread, []) |
| 503 | self.assertEqual(next(fi), 'line1\n') |
| 504 | self.assertEqual(src.linesread, ['line1\n']) |
| 505 | self.assertEqual(next(fi), 'line2') |
| 506 | self.assertEqual(src.linesread, ['line2']) |
| 507 | self.assertEqual(next(fi), 'line3\n') |
| 508 | self.assertEqual(src.linesread, ['', 'line3\n']) |
| 509 | self.assertRaises(StopIteration, next, fi) |
| 510 | self.assertEqual(src.linesread, ['']) |
| 511 | self.assertRaises(StopIteration, next, fi) |
| 512 | self.assertEqual(src.linesread, []) |
| 513 | |
Roy Williams | 002665a | 2017-05-22 22:24:17 -0700 | [diff] [blame] | 514 | def test_pathlib_file(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 515 | t1 = Path(self.writeTmp("Pathlib file.")) |
| 516 | with FileInput(t1) as fi: |
| 517 | line = fi.readline() |
| 518 | self.assertEqual(line, 'Pathlib file.') |
| 519 | self.assertEqual(fi.lineno(), 1) |
| 520 | self.assertEqual(fi.filelineno(), 1) |
| 521 | self.assertEqual(fi.filename(), os.fspath(t1)) |
Roy Williams | 002665a | 2017-05-22 22:24:17 -0700 | [diff] [blame] | 522 | |
Zhiming Wang | 06de1ae | 2017-09-05 01:37:24 +0800 | [diff] [blame] | 523 | def test_pathlib_file_inplace(self): |
Serhiy Storchaka | 5f48e26 | 2018-06-05 12:08:36 +0300 | [diff] [blame] | 524 | t1 = Path(self.writeTmp('Pathlib file.')) |
| 525 | with FileInput(t1, inplace=True) as fi: |
| 526 | line = fi.readline() |
| 527 | self.assertEqual(line, 'Pathlib file.') |
| 528 | print('Modified %s' % line) |
| 529 | with open(t1) as f: |
| 530 | self.assertEqual(f.read(), 'Modified Pathlib file.\n') |
Zhiming Wang | 06de1ae | 2017-09-05 01:37:24 +0800 | [diff] [blame] | 531 | |
Roy Williams | 002665a | 2017-05-22 22:24:17 -0700 | [diff] [blame] | 532 | |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 533 | class MockFileInput: |
| 534 | """A class that mocks out fileinput.FileInput for use during unit tests""" |
| 535 | |
| 536 | def __init__(self, files=None, inplace=False, backup="", bufsize=0, |
| 537 | mode="r", openhook=None): |
| 538 | self.files = files |
| 539 | self.inplace = inplace |
| 540 | self.backup = backup |
| 541 | self.bufsize = bufsize |
| 542 | self.mode = mode |
| 543 | self.openhook = openhook |
| 544 | self._file = None |
| 545 | self.invocation_counts = collections.defaultdict(lambda: 0) |
| 546 | self.return_values = {} |
| 547 | |
| 548 | def close(self): |
| 549 | self.invocation_counts["close"] += 1 |
| 550 | |
| 551 | def nextfile(self): |
| 552 | self.invocation_counts["nextfile"] += 1 |
| 553 | return self.return_values["nextfile"] |
| 554 | |
| 555 | def filename(self): |
| 556 | self.invocation_counts["filename"] += 1 |
| 557 | return self.return_values["filename"] |
| 558 | |
| 559 | def lineno(self): |
| 560 | self.invocation_counts["lineno"] += 1 |
| 561 | return self.return_values["lineno"] |
| 562 | |
| 563 | def filelineno(self): |
| 564 | self.invocation_counts["filelineno"] += 1 |
| 565 | return self.return_values["filelineno"] |
| 566 | |
| 567 | def fileno(self): |
| 568 | self.invocation_counts["fileno"] += 1 |
| 569 | return self.return_values["fileno"] |
| 570 | |
| 571 | def isfirstline(self): |
| 572 | self.invocation_counts["isfirstline"] += 1 |
| 573 | return self.return_values["isfirstline"] |
| 574 | |
| 575 | def isstdin(self): |
| 576 | self.invocation_counts["isstdin"] += 1 |
| 577 | return self.return_values["isstdin"] |
| 578 | |
| 579 | class BaseFileInputGlobalMethodsTest(unittest.TestCase): |
| 580 | """Base class for unit tests for the global function of |
| 581 | the fileinput module.""" |
| 582 | |
| 583 | def setUp(self): |
| 584 | self._orig_state = fileinput._state |
| 585 | self._orig_FileInput = fileinput.FileInput |
| 586 | fileinput.FileInput = MockFileInput |
| 587 | |
| 588 | def tearDown(self): |
| 589 | fileinput.FileInput = self._orig_FileInput |
| 590 | fileinput._state = self._orig_state |
| 591 | |
| 592 | def assertExactlyOneInvocation(self, mock_file_input, method_name): |
| 593 | # assert that the method with the given name was invoked once |
| 594 | actual_count = mock_file_input.invocation_counts[method_name] |
| 595 | self.assertEqual(actual_count, 1, method_name) |
| 596 | # assert that no other unexpected methods were invoked |
| 597 | actual_total_count = len(mock_file_input.invocation_counts) |
| 598 | self.assertEqual(actual_total_count, 1) |
| 599 | |
| 600 | class Test_fileinput_input(BaseFileInputGlobalMethodsTest): |
| 601 | """Unit tests for fileinput.input()""" |
| 602 | |
| 603 | def test_state_is_not_None_and_state_file_is_not_None(self): |
| 604 | """Tests invoking fileinput.input() when fileinput._state is not None |
| 605 | and its _file attribute is also not None. Expect RuntimeError to |
| 606 | be raised with a meaningful error message and for fileinput._state |
| 607 | to *not* be modified.""" |
| 608 | instance = MockFileInput() |
| 609 | instance._file = object() |
| 610 | fileinput._state = instance |
| 611 | with self.assertRaises(RuntimeError) as cm: |
| 612 | fileinput.input() |
| 613 | self.assertEqual(("input() already active",), cm.exception.args) |
| 614 | self.assertIs(instance, fileinput._state, "fileinput._state") |
| 615 | |
| 616 | def test_state_is_not_None_and_state_file_is_None(self): |
| 617 | """Tests invoking fileinput.input() when fileinput._state is not None |
| 618 | but its _file attribute *is* None. Expect it to create and return |
| 619 | a new fileinput.FileInput object with all method parameters passed |
| 620 | explicitly to the __init__() method; also ensure that |
| 621 | fileinput._state is set to the returned instance.""" |
| 622 | instance = MockFileInput() |
| 623 | instance._file = None |
| 624 | fileinput._state = instance |
| 625 | self.do_test_call_input() |
| 626 | |
| 627 | def test_state_is_None(self): |
| 628 | """Tests invoking fileinput.input() when fileinput._state is None |
| 629 | Expect it to create and return a new fileinput.FileInput object |
| 630 | with all method parameters passed explicitly to the __init__() |
| 631 | method; also ensure that fileinput._state is set to the returned |
| 632 | instance.""" |
| 633 | fileinput._state = None |
| 634 | self.do_test_call_input() |
| 635 | |
| 636 | def do_test_call_input(self): |
| 637 | """Tests that fileinput.input() creates a new fileinput.FileInput |
| 638 | object, passing the given parameters unmodified to |
| 639 | fileinput.FileInput.__init__(). Note that this test depends on the |
| 640 | monkey patching of fileinput.FileInput done by setUp().""" |
| 641 | files = object() |
| 642 | inplace = object() |
| 643 | backup = object() |
| 644 | bufsize = object() |
| 645 | mode = object() |
| 646 | openhook = object() |
| 647 | |
| 648 | # call fileinput.input() with different values for each argument |
| 649 | result = fileinput.input(files=files, inplace=inplace, backup=backup, |
| 650 | bufsize=bufsize, |
| 651 | mode=mode, openhook=openhook) |
| 652 | |
| 653 | # ensure fileinput._state was set to the returned object |
| 654 | self.assertIs(result, fileinput._state, "fileinput._state") |
| 655 | |
| 656 | # ensure the parameters to fileinput.input() were passed directly |
| 657 | # to FileInput.__init__() |
| 658 | self.assertIs(files, result.files, "files") |
| 659 | self.assertIs(inplace, result.inplace, "inplace") |
| 660 | self.assertIs(backup, result.backup, "backup") |
| 661 | self.assertIs(bufsize, result.bufsize, "bufsize") |
| 662 | self.assertIs(mode, result.mode, "mode") |
| 663 | self.assertIs(openhook, result.openhook, "openhook") |
| 664 | |
| 665 | class Test_fileinput_close(BaseFileInputGlobalMethodsTest): |
| 666 | """Unit tests for fileinput.close()""" |
| 667 | |
| 668 | def test_state_is_None(self): |
| 669 | """Tests that fileinput.close() does nothing if fileinput._state |
| 670 | is None""" |
| 671 | fileinput._state = None |
| 672 | fileinput.close() |
| 673 | self.assertIsNone(fileinput._state) |
| 674 | |
| 675 | def test_state_is_not_None(self): |
| 676 | """Tests that fileinput.close() invokes close() on fileinput._state |
| 677 | and sets _state=None""" |
| 678 | instance = MockFileInput() |
| 679 | fileinput._state = instance |
| 680 | fileinput.close() |
| 681 | self.assertExactlyOneInvocation(instance, "close") |
| 682 | self.assertIsNone(fileinput._state) |
| 683 | |
| 684 | class Test_fileinput_nextfile(BaseFileInputGlobalMethodsTest): |
| 685 | """Unit tests for fileinput.nextfile()""" |
| 686 | |
| 687 | def test_state_is_None(self): |
| 688 | """Tests fileinput.nextfile() when fileinput._state is None. |
| 689 | Ensure that it raises RuntimeError with a meaningful error message |
| 690 | and does not modify fileinput._state""" |
| 691 | fileinput._state = None |
| 692 | with self.assertRaises(RuntimeError) as cm: |
| 693 | fileinput.nextfile() |
| 694 | self.assertEqual(("no active input()",), cm.exception.args) |
| 695 | self.assertIsNone(fileinput._state) |
| 696 | |
| 697 | def test_state_is_not_None(self): |
| 698 | """Tests fileinput.nextfile() when fileinput._state is not None. |
| 699 | Ensure that it invokes fileinput._state.nextfile() exactly once, |
| 700 | returns whatever it returns, and does not modify fileinput._state |
| 701 | to point to a different object.""" |
| 702 | nextfile_retval = object() |
| 703 | instance = MockFileInput() |
| 704 | instance.return_values["nextfile"] = nextfile_retval |
| 705 | fileinput._state = instance |
| 706 | retval = fileinput.nextfile() |
| 707 | self.assertExactlyOneInvocation(instance, "nextfile") |
| 708 | self.assertIs(retval, nextfile_retval) |
| 709 | self.assertIs(fileinput._state, instance) |
| 710 | |
| 711 | class Test_fileinput_filename(BaseFileInputGlobalMethodsTest): |
| 712 | """Unit tests for fileinput.filename()""" |
| 713 | |
| 714 | def test_state_is_None(self): |
| 715 | """Tests fileinput.filename() when fileinput._state is None. |
| 716 | Ensure that it raises RuntimeError with a meaningful error message |
| 717 | and does not modify fileinput._state""" |
| 718 | fileinput._state = None |
| 719 | with self.assertRaises(RuntimeError) as cm: |
| 720 | fileinput.filename() |
| 721 | self.assertEqual(("no active input()",), cm.exception.args) |
| 722 | self.assertIsNone(fileinput._state) |
| 723 | |
| 724 | def test_state_is_not_None(self): |
| 725 | """Tests fileinput.filename() when fileinput._state is not None. |
| 726 | Ensure that it invokes fileinput._state.filename() exactly once, |
| 727 | returns whatever it returns, and does not modify fileinput._state |
| 728 | to point to a different object.""" |
| 729 | filename_retval = object() |
| 730 | instance = MockFileInput() |
| 731 | instance.return_values["filename"] = filename_retval |
| 732 | fileinput._state = instance |
| 733 | retval = fileinput.filename() |
| 734 | self.assertExactlyOneInvocation(instance, "filename") |
| 735 | self.assertIs(retval, filename_retval) |
| 736 | self.assertIs(fileinput._state, instance) |
| 737 | |
| 738 | class Test_fileinput_lineno(BaseFileInputGlobalMethodsTest): |
| 739 | """Unit tests for fileinput.lineno()""" |
| 740 | |
| 741 | def test_state_is_None(self): |
| 742 | """Tests fileinput.lineno() when fileinput._state is None. |
| 743 | Ensure that it raises RuntimeError with a meaningful error message |
| 744 | and does not modify fileinput._state""" |
| 745 | fileinput._state = None |
| 746 | with self.assertRaises(RuntimeError) as cm: |
| 747 | fileinput.lineno() |
| 748 | self.assertEqual(("no active input()",), cm.exception.args) |
| 749 | self.assertIsNone(fileinput._state) |
| 750 | |
| 751 | def test_state_is_not_None(self): |
| 752 | """Tests fileinput.lineno() when fileinput._state is not None. |
| 753 | Ensure that it invokes fileinput._state.lineno() exactly once, |
| 754 | returns whatever it returns, and does not modify fileinput._state |
| 755 | to point to a different object.""" |
| 756 | lineno_retval = object() |
| 757 | instance = MockFileInput() |
| 758 | instance.return_values["lineno"] = lineno_retval |
| 759 | fileinput._state = instance |
| 760 | retval = fileinput.lineno() |
| 761 | self.assertExactlyOneInvocation(instance, "lineno") |
| 762 | self.assertIs(retval, lineno_retval) |
| 763 | self.assertIs(fileinput._state, instance) |
| 764 | |
| 765 | class Test_fileinput_filelineno(BaseFileInputGlobalMethodsTest): |
| 766 | """Unit tests for fileinput.filelineno()""" |
| 767 | |
| 768 | def test_state_is_None(self): |
| 769 | """Tests fileinput.filelineno() when fileinput._state is None. |
| 770 | Ensure that it raises RuntimeError with a meaningful error message |
| 771 | and does not modify fileinput._state""" |
| 772 | fileinput._state = None |
| 773 | with self.assertRaises(RuntimeError) as cm: |
| 774 | fileinput.filelineno() |
| 775 | self.assertEqual(("no active input()",), cm.exception.args) |
| 776 | self.assertIsNone(fileinput._state) |
| 777 | |
| 778 | def test_state_is_not_None(self): |
| 779 | """Tests fileinput.filelineno() when fileinput._state is not None. |
| 780 | Ensure that it invokes fileinput._state.filelineno() exactly once, |
| 781 | returns whatever it returns, and does not modify fileinput._state |
| 782 | to point to a different object.""" |
| 783 | filelineno_retval = object() |
| 784 | instance = MockFileInput() |
| 785 | instance.return_values["filelineno"] = filelineno_retval |
| 786 | fileinput._state = instance |
| 787 | retval = fileinput.filelineno() |
| 788 | self.assertExactlyOneInvocation(instance, "filelineno") |
| 789 | self.assertIs(retval, filelineno_retval) |
| 790 | self.assertIs(fileinput._state, instance) |
| 791 | |
| 792 | class Test_fileinput_fileno(BaseFileInputGlobalMethodsTest): |
| 793 | """Unit tests for fileinput.fileno()""" |
| 794 | |
| 795 | def test_state_is_None(self): |
| 796 | """Tests fileinput.fileno() when fileinput._state is None. |
| 797 | Ensure that it raises RuntimeError with a meaningful error message |
| 798 | and does not modify fileinput._state""" |
| 799 | fileinput._state = None |
| 800 | with self.assertRaises(RuntimeError) as cm: |
| 801 | fileinput.fileno() |
| 802 | self.assertEqual(("no active input()",), cm.exception.args) |
| 803 | self.assertIsNone(fileinput._state) |
| 804 | |
| 805 | def test_state_is_not_None(self): |
| 806 | """Tests fileinput.fileno() when fileinput._state is not None. |
| 807 | Ensure that it invokes fileinput._state.fileno() exactly once, |
| 808 | returns whatever it returns, and does not modify fileinput._state |
| 809 | to point to a different object.""" |
| 810 | fileno_retval = object() |
| 811 | instance = MockFileInput() |
| 812 | instance.return_values["fileno"] = fileno_retval |
| 813 | instance.fileno_retval = fileno_retval |
| 814 | fileinput._state = instance |
| 815 | retval = fileinput.fileno() |
| 816 | self.assertExactlyOneInvocation(instance, "fileno") |
| 817 | self.assertIs(retval, fileno_retval) |
| 818 | self.assertIs(fileinput._state, instance) |
| 819 | |
| 820 | class Test_fileinput_isfirstline(BaseFileInputGlobalMethodsTest): |
| 821 | """Unit tests for fileinput.isfirstline()""" |
| 822 | |
| 823 | def test_state_is_None(self): |
| 824 | """Tests fileinput.isfirstline() when fileinput._state is None. |
| 825 | Ensure that it raises RuntimeError with a meaningful error message |
| 826 | and does not modify fileinput._state""" |
| 827 | fileinput._state = None |
| 828 | with self.assertRaises(RuntimeError) as cm: |
| 829 | fileinput.isfirstline() |
| 830 | self.assertEqual(("no active input()",), cm.exception.args) |
| 831 | self.assertIsNone(fileinput._state) |
| 832 | |
| 833 | def test_state_is_not_None(self): |
| 834 | """Tests fileinput.isfirstline() when fileinput._state is not None. |
| 835 | Ensure that it invokes fileinput._state.isfirstline() exactly once, |
| 836 | returns whatever it returns, and does not modify fileinput._state |
| 837 | to point to a different object.""" |
| 838 | isfirstline_retval = object() |
| 839 | instance = MockFileInput() |
| 840 | instance.return_values["isfirstline"] = isfirstline_retval |
| 841 | fileinput._state = instance |
| 842 | retval = fileinput.isfirstline() |
| 843 | self.assertExactlyOneInvocation(instance, "isfirstline") |
| 844 | self.assertIs(retval, isfirstline_retval) |
| 845 | self.assertIs(fileinput._state, instance) |
| 846 | |
| 847 | class Test_fileinput_isstdin(BaseFileInputGlobalMethodsTest): |
| 848 | """Unit tests for fileinput.isstdin()""" |
| 849 | |
| 850 | def test_state_is_None(self): |
| 851 | """Tests fileinput.isstdin() when fileinput._state is None. |
| 852 | Ensure that it raises RuntimeError with a meaningful error message |
| 853 | and does not modify fileinput._state""" |
| 854 | fileinput._state = None |
| 855 | with self.assertRaises(RuntimeError) as cm: |
| 856 | fileinput.isstdin() |
| 857 | self.assertEqual(("no active input()",), cm.exception.args) |
| 858 | self.assertIsNone(fileinput._state) |
| 859 | |
| 860 | def test_state_is_not_None(self): |
| 861 | """Tests fileinput.isstdin() when fileinput._state is not None. |
| 862 | Ensure that it invokes fileinput._state.isstdin() exactly once, |
| 863 | returns whatever it returns, and does not modify fileinput._state |
| 864 | to point to a different object.""" |
| 865 | isstdin_retval = object() |
| 866 | instance = MockFileInput() |
| 867 | instance.return_values["isstdin"] = isstdin_retval |
| 868 | fileinput._state = instance |
| 869 | retval = fileinput.isstdin() |
| 870 | self.assertExactlyOneInvocation(instance, "isstdin") |
| 871 | self.assertIs(retval, isstdin_retval) |
| 872 | self.assertIs(fileinput._state, instance) |
| 873 | |
| 874 | class InvocationRecorder: |
| 875 | def __init__(self): |
| 876 | self.invocation_count = 0 |
| 877 | def __call__(self, *args, **kwargs): |
| 878 | self.invocation_count += 1 |
| 879 | self.last_invocation = (args, kwargs) |
| 880 | |
| 881 | class Test_hook_compressed(unittest.TestCase): |
| 882 | """Unit tests for fileinput.hook_compressed()""" |
| 883 | |
| 884 | def setUp(self): |
| 885 | self.fake_open = InvocationRecorder() |
| 886 | |
| 887 | def test_empty_string(self): |
| 888 | self.do_test_use_builtin_open("", 1) |
| 889 | |
| 890 | def test_no_ext(self): |
| 891 | self.do_test_use_builtin_open("abcd", 2) |
| 892 | |
Ezio Melotti | c3afbb9 | 2011-05-14 10:10:53 +0300 | [diff] [blame] | 893 | @unittest.skipUnless(gzip, "Requires gzip and zlib") |
briancurtin | 5eb3591 | 2011-03-15 10:59:36 -0400 | [diff] [blame] | 894 | def test_gz_ext_fake(self): |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 895 | original_open = gzip.open |
| 896 | gzip.open = self.fake_open |
| 897 | try: |
| 898 | result = fileinput.hook_compressed("test.gz", 3) |
| 899 | finally: |
| 900 | gzip.open = original_open |
| 901 | |
| 902 | self.assertEqual(self.fake_open.invocation_count, 1) |
| 903 | self.assertEqual(self.fake_open.last_invocation, (("test.gz", 3), {})) |
| 904 | |
briancurtin | f84f3c3 | 2011-03-18 13:03:17 -0500 | [diff] [blame] | 905 | @unittest.skipUnless(bz2, "Requires bz2") |
briancurtin | 5eb3591 | 2011-03-15 10:59:36 -0400 | [diff] [blame] | 906 | def test_bz2_ext_fake(self): |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 907 | original_open = bz2.BZ2File |
| 908 | bz2.BZ2File = self.fake_open |
| 909 | try: |
| 910 | result = fileinput.hook_compressed("test.bz2", 4) |
| 911 | finally: |
| 912 | bz2.BZ2File = original_open |
| 913 | |
| 914 | self.assertEqual(self.fake_open.invocation_count, 1) |
| 915 | self.assertEqual(self.fake_open.last_invocation, (("test.bz2", 4), {})) |
| 916 | |
| 917 | def test_blah_ext(self): |
| 918 | self.do_test_use_builtin_open("abcd.blah", 5) |
| 919 | |
briancurtin | 5eb3591 | 2011-03-15 10:59:36 -0400 | [diff] [blame] | 920 | def test_gz_ext_builtin(self): |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 921 | self.do_test_use_builtin_open("abcd.Gz", 6) |
| 922 | |
briancurtin | 5eb3591 | 2011-03-15 10:59:36 -0400 | [diff] [blame] | 923 | def test_bz2_ext_builtin(self): |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 924 | self.do_test_use_builtin_open("abcd.Bz2", 7) |
| 925 | |
| 926 | def do_test_use_builtin_open(self, filename, mode): |
| 927 | original_open = self.replace_builtin_open(self.fake_open) |
| 928 | try: |
| 929 | result = fileinput.hook_compressed(filename, mode) |
| 930 | finally: |
| 931 | self.replace_builtin_open(original_open) |
| 932 | |
| 933 | self.assertEqual(self.fake_open.invocation_count, 1) |
| 934 | self.assertEqual(self.fake_open.last_invocation, |
| 935 | ((filename, mode), {})) |
| 936 | |
| 937 | @staticmethod |
| 938 | def replace_builtin_open(new_open_func): |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 939 | original_open = builtins.open |
| 940 | builtins.open = new_open_func |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 941 | return original_open |
| 942 | |
| 943 | class Test_hook_encoded(unittest.TestCase): |
| 944 | """Unit tests for fileinput.hook_encoded()""" |
| 945 | |
| 946 | def test(self): |
| 947 | encoding = object() |
Serhiy Storchaka | b275210 | 2016-04-27 23:13:46 +0300 | [diff] [blame] | 948 | errors = object() |
| 949 | result = fileinput.hook_encoded(encoding, errors=errors) |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 950 | |
| 951 | fake_open = InvocationRecorder() |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 952 | original_open = builtins.open |
| 953 | builtins.open = fake_open |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 954 | try: |
| 955 | filename = object() |
| 956 | mode = object() |
| 957 | open_result = result(filename, mode) |
| 958 | finally: |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 959 | builtins.open = original_open |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 960 | |
| 961 | self.assertEqual(fake_open.invocation_count, 1) |
| 962 | |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 963 | args, kwargs = fake_open.last_invocation |
briancurtin | 906f0c4 | 2011-03-15 10:29:41 -0400 | [diff] [blame] | 964 | self.assertIs(args[0], filename) |
| 965 | self.assertIs(args[1], mode) |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 966 | self.assertIs(kwargs.pop('encoding'), encoding) |
Serhiy Storchaka | b275210 | 2016-04-27 23:13:46 +0300 | [diff] [blame] | 967 | self.assertIs(kwargs.pop('errors'), errors) |
Florent Xicluna | a011e2b | 2011-11-07 19:43:07 +0100 | [diff] [blame] | 968 | self.assertFalse(kwargs) |
Georg Brandl | 6cb7b65 | 2010-07-31 20:08:15 +0000 | [diff] [blame] | 969 | |
Serhiy Storchaka | b275210 | 2016-04-27 23:13:46 +0300 | [diff] [blame] | 970 | def test_errors(self): |
| 971 | with open(TESTFN, 'wb') as f: |
| 972 | f.write(b'\x80abc') |
| 973 | self.addCleanup(safe_unlink, TESTFN) |
| 974 | |
| 975 | def check(errors, expected_lines): |
| 976 | with FileInput(files=TESTFN, mode='r', |
| 977 | openhook=hook_encoded('utf-8', errors=errors)) as fi: |
| 978 | lines = list(fi) |
| 979 | self.assertEqual(lines, expected_lines) |
| 980 | |
| 981 | check('ignore', ['abc']) |
| 982 | with self.assertRaises(UnicodeDecodeError): |
| 983 | check('strict', ['abc']) |
| 984 | check('replace', ['\ufffdabc']) |
| 985 | check('backslashreplace', ['\\x80abc']) |
| 986 | |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 987 | def test_modes(self): |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 988 | with open(TESTFN, 'wb') as f: |
Serhiy Storchaka | 682ea5f | 2014-03-03 21:17:17 +0200 | [diff] [blame] | 989 | # UTF-7 is a convenient, seldom used encoding |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 990 | f.write(b'A\nB\r\nC\rD+IKw-') |
| 991 | self.addCleanup(safe_unlink, TESTFN) |
| 992 | |
| 993 | def check(mode, expected_lines): |
| 994 | with FileInput(files=TESTFN, mode=mode, |
| 995 | openhook=hook_encoded('utf-7')) as fi: |
| 996 | lines = list(fi) |
| 997 | self.assertEqual(lines, expected_lines) |
| 998 | |
| 999 | check('r', ['A\n', 'B\n', 'C\n', 'D\u20ac']) |
Serhiy Storchaka | 9fff849 | 2014-02-26 21:03:19 +0200 | [diff] [blame] | 1000 | with self.assertWarns(DeprecationWarning): |
| 1001 | check('rU', ['A\n', 'B\n', 'C\n', 'D\u20ac']) |
| 1002 | with self.assertWarns(DeprecationWarning): |
| 1003 | check('U', ['A\n', 'B\n', 'C\n', 'D\u20ac']) |
Serhiy Storchaka | 517b747 | 2014-02-26 20:59:43 +0200 | [diff] [blame] | 1004 | with self.assertRaises(ValueError): |
| 1005 | check('rb', ['A\n', 'B\r\n', 'C\r', 'D\u20ac']) |
| 1006 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1007 | |
Martin Panter | 7978e10 | 2016-01-16 06:26:54 +0000 | [diff] [blame] | 1008 | class MiscTest(unittest.TestCase): |
| 1009 | |
| 1010 | def test_all(self): |
Serhiy Storchaka | 674e2d0 | 2016-03-08 18:35:19 +0200 | [diff] [blame] | 1011 | support.check__all__(self, fileinput) |
Martin Panter | 7978e10 | 2016-01-16 06:26:54 +0000 | [diff] [blame] | 1012 | |
| 1013 | |
Guido van Rossum | d8faa36 | 2007-04-27 19:54:29 +0000 | [diff] [blame] | 1014 | if __name__ == "__main__": |
Brett Cannon | 3e9a9ae | 2013-06-12 21:25:59 -0400 | [diff] [blame] | 1015 | unittest.main() |