Debian Codegraph @

autopage/tests/test_autopage.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import codecs
14 import subprocess
15 import sys
16 import unittest
17 from unittest import mock
18
19 import fixtures # type: ignore
20
21 from typing import Optional, List, Dict
22
23 from autopage.tests import sinks
24
25 import autopage
26 from autopage import command
27
28
29 _PagerConfig = command.PagerConfig
30
31
32 class PagedStreamTest(fixtures.TestWithFixtures):
33 def setUp(self) -> None:
34 out = sinks.TTYFixture()
35 self.useFixture(out)
36 self.stream = out.stream
37 self.useFixture(fixtures.MonkeyPatch('sys.stdout', self.stream))
38 popen = fixtures.MockPatch('subprocess.Popen')
39 self.useFixture(popen)
40 self.popen = popen.mock
41
42 def test_defaults(self) -> None:
43 class TestCommand(command.PagerCommand):
44 def command(self) -> List[str]:
45 return []
46
47 def environment_variables(
48 self,
49 config: _PagerConfig) -> Optional[Dict[str, str]]:
50 return None
51
52 tc = TestCommand()
53 ap = autopage.AutoPager(pager_command=tc, line_buffering=False)
54 with mock.patch.object(ap, '_pager_env') as get_env, \
55 mock.patch.object(tc, 'command') as cmd:
56 stream = ap._paged_stream()
57 self.popen.assert_called_once_with(
58 cmd.return_value,
59 env=get_env.return_value,
60 bufsize=-1,
61 universal_newlines=True,
62 encoding='utf-8',
63 errors='strict',
64 stdin=subprocess.PIPE,
65 stdout=None)
66 self.assertIs(stream, self.popen.return_value.stdin)
67
68 def test_defaults_cmd_as_class(self) -> None:
69 class TestCommand(command.PagerCommand):
70 def command(self) -> List[str]:
71 return []
72
73 def environment_variables(
74 self,
75 config: _PagerConfig) -> Optional[Dict[str, str]]:
76 return None
77
78 with mock.patch.object(TestCommand, 'command') as cmd:
79 ap = autopage.AutoPager(pager_command=TestCommand,
80 line_buffering=False)
81 with mock.patch.object(ap, '_pager_env') as get_env:
82 stream = ap._paged_stream()
83 self.popen.assert_called_once_with(
84 cmd.return_value,
85 env=get_env.return_value,
86 bufsize=-1,
87 universal_newlines=True,
88 encoding='utf-8',
89 errors='strict',
90 stdin=subprocess.PIPE,
91 stdout=None)
92 self.assertIs(stream, self.popen.return_value.stdin)
93
94 def test_defaults_cmd_as_string(self) -> None:
95 ap = autopage.AutoPager(pager_command='foo bar',
96 line_buffering=False)
97 with mock.patch.object(ap, '_pager_env') as get_env:
98 stream = ap._paged_stream()
99 self.popen.assert_called_once_with(
100 ['foo', 'bar'],
101 env=get_env.return_value,
102 bufsize=-1,
103 universal_newlines=True,
104 encoding='utf-8',
105 errors='strict',
106 stdin=subprocess.PIPE,
107 stdout=None)
108 self.assertIs(stream, self.popen.return_value.stdin)
109
110 def test_defaults_cmd_as_int(self) -> None:
111 self.assertRaises(TypeError, autopage.AutoPager,
112 pager_command=42)
113
114 def test_line_buffering(self) -> None:
115 ap = autopage.AutoPager(line_buffering=True)
116 stream = ap._paged_stream()
117 self.popen.assert_called_once_with(
118 mock.ANY,
119 env=mock.ANY,
120 bufsize=1,
121 universal_newlines=True,
122 encoding=mock.ANY,
123 errors=mock.ANY,
124 stdin=subprocess.PIPE,
125 stdout=None)
126 self.assertIs(stream, self.popen.return_value.stdin)
127
128 def test_errors(self) -> None:
129 ap = autopage.AutoPager(errors=autopage.ErrorStrategy.NAME_REPLACE)
130 stream = ap._paged_stream()
131 self.popen.assert_called_once_with(
132 mock.ANY,
133 env=mock.ANY,
134 bufsize=mock.ANY,
135 universal_newlines=mock.ANY,
136 encoding=mock.ANY,
137 errors='namereplace',
138 stdin=subprocess.PIPE,
139 stdout=None)
140 self.assertIs(stream, self.popen.return_value.stdin)
141
142 def test_explicit_stdout_stream(self) -> None:
143 ap = autopage.AutoPager(self.stream)
144 stream = ap._paged_stream()
145 self.popen.assert_called_once_with(
146 mock.ANY,
147 env=mock.ANY,
148 bufsize=mock.ANY,
149 universal_newlines=mock.ANY,
150 encoding=mock.ANY,
151 errors=mock.ANY,
152 stdin=subprocess.PIPE,
153 stdout=None)
154 self.assertIs(stream, self.popen.return_value.stdin)
155
156 def test_explicit_stream(self) -> None:
157 with sinks.TTYFixture() as tty:
158 ap = autopage.AutoPager(tty.stream)
159 stream = ap._paged_stream()
160 self.popen.assert_called_once_with(
161 mock.ANY,
162 env=mock.ANY,
163 bufsize=mock.ANY,
164 universal_newlines=mock.ANY,
165 encoding=mock.ANY,
166 errors=mock.ANY,
167 stdin=subprocess.PIPE,
168 stdout=tty.stream)
169 self.assertIs(stream, self.popen.return_value.stdin)
170
171
172 class ToTerminalTest(unittest.TestCase):
173 def test_pty(self) -> None:
174 with sinks.TTYFixture() as out:
175 ap = autopage.AutoPager(out.stream)
176 self.assertTrue(ap.to_terminal())
177
178 def test_stringio(self) -> None:
179 with sinks.BufferFixture() as out:
180 ap = autopage.AutoPager(out.stream)
181 self.assertFalse(ap.to_terminal())
182
183 def test_file(self) -> None:
184 with sinks.TempFixture() as out:
185 ap = autopage.AutoPager(out.stream)
186 self.assertFalse(ap.to_terminal())
187
188 def test_default_pty(self) -> None:
189 with sinks.TTYFixture() as out:
190 with fixtures.MonkeyPatch('sys.stdout', out.stream):
191 ap = autopage.AutoPager()
192 self.assertTrue(ap.to_terminal())
193
194 def test_default_file(self) -> None:
195 with sinks.TempFixture() as out:
196 with fixtures.MonkeyPatch('sys.stdout', out.stream):
197 ap = autopage.AutoPager()
198 self.assertFalse(ap.to_terminal())
199
200 def test_launch_pager(self) -> None:
201 ap = autopage.AutoPager()
202 with mock.patch.object(ap, 'to_terminal', return_value=True), \
203 mock.patch.object(ap, '_paged_stream') as page, \
204 mock.patch.object(ap, '_reconfigure_output_stream') as reconf:
205 with ap as stream:
206 page.assert_called_once()
207 self.assertIs(page.return_value, stream)
208 reconf.assert_not_called()
209
210 def test_launch_pager_fail(self) -> None:
211 outstream = mock.Mock()
212 ap = autopage.AutoPager(outstream)
213 with mock.patch.object(ap, 'to_terminal', return_value=True), \
214 mock.patch.object(ap, '_paged_stream',
215 side_effect=OSError) as page, \
216 mock.patch.object(ap, '_reconfigure_output_stream') as reconf:
217 with ap as stream:
218 page.assert_called_once()
219 reconf.assert_called_once()
220 self.assertIs(outstream, stream)
221
222 def test_no_pager(self) -> None:
223 outstream = mock.Mock()
224 ap = autopage.AutoPager(outstream)
225 with mock.patch.object(ap, 'to_terminal', return_value=False), \
226 mock.patch.object(ap, '_paged_stream') as page, \
227 mock.patch.object(ap, '_reconfigure_output_stream') as reconf:
228 with ap as stream:
229 page.assert_not_called()
230 self.assertIs(outstream, stream)
231 reconf.assert_called_once()
232
233 def test_pager_cat(self) -> None:
234 outstream = mock.Mock()
235 cat = command.CustomPager('cat')
236 ap = autopage.AutoPager(outstream, pager_command=cat)
237 with mock.patch.object(ap, 'to_terminal', return_value=True), \
238 mock.patch.object(ap, '_paged_stream') as page, \
239 mock.patch.object(ap, '_reconfigure_output_stream') as reconf:
240 with ap as stream:
241 page.assert_not_called()
242 self.assertIs(outstream, stream)
243 reconf.assert_called_once()
244
245
246 class ExitCodeTest(fixtures.TestWithFixtures):
247 def setUp(self) -> None:
248 out = sinks.BufferFixture()
249 self.useFixture(out)
250 self.ap = autopage.AutoPager(out.stream)
251
252 def test_success(self) -> None:
253 with self.ap:
254 pass
255 self.assertEqual(0, self.ap.exit_code())
256
257 def test_pager_broken_pipe_flush(self) -> None:
258 flush = mock.MagicMock(side_effect=BrokenPipeError)
259 with sinks.TTYFixture() as out:
260 ap = autopage.AutoPager(out.stream)
261 with fixtures.MockPatch('subprocess.Popen') as popen:
262 with sinks.BufferFixture() as pager_in:
263 popen.mock.return_value.stdin = pager_in.stream
264 with ap as stream:
265 stream.write('foo')
266 stream.close = flush # type: ignore
267 self.assertEqual(141, ap.exit_code())
268
269 def test_no_pager_broken_pipe_flush(self) -> None:
270 flush = mock.MagicMock(side_effect=BrokenPipeError)
271 with self.ap as stream:
272 stream.write('foo')
273 stream.flush = flush # type: ignore
274 self.assertEqual(141, self.ap.exit_code())
275
276 def test_broken_pipe(self) -> None:
277 with self.ap:
278 raise BrokenPipeError
279 self.assertEqual(141, self.ap.exit_code())
280
281 def test_exception(self) -> None:
282 class MyException(Exception):
283 pass
284
285 def run() -> None:
286 with self.ap:
287 raise MyException
288
289 self.assertRaises(MyException, run)
290 self.assertEqual(1, self.ap.exit_code())
291
292 def test_exception_on_error_default(self) -> None:
293 class MyException(Exception):
294 pass
295
296 def run() -> None:
297 with self.ap:
298 raise MyException
299
300 self.assertRaises(MyException, run)
301 self.assertEqual(2, self.ap.exit_code(on_error_default=2))
302
303 def test_base_exception(self) -> None:
304 class MyBaseException(BaseException):
305 pass
306
307 def run() -> None:
308 with self.ap:
309 raise MyBaseException
310
311 self.assertRaises(MyBaseException, run)
312 self.assertEqual(1, self.ap.exit_code())
313
314 def test_interrupt(self) -> None:
315 def run() -> None:
316 with self.ap:
317 raise KeyboardInterrupt
318
319 self.assertRaises(KeyboardInterrupt, run)
320 self.assertEqual(130, self.ap.exit_code())
321
322 def test_system_exit(self) -> None:
323 def run() -> None:
324 with self.ap:
325 raise SystemExit(42)
326
327 self.assertRaises(SystemExit, run)
328 self.assertEqual(42, self.ap.exit_code())
329
330 def test_system_exit_on_error_default(self) -> None:
331 def run() -> None:
332 with self.ap:
333 raise SystemExit(42)
334
335 self.assertRaises(SystemExit, run)
336 self.assertEqual(42, self.ap.exit_code(on_error_default=3))
337
338 def test_system_exit_string(self) -> None:
339 def run() -> None:
340 with self.ap:
341 raise SystemExit("nope")
342
343 self.assertRaises(SystemExit, run)
344 self.assertEqual(1, self.ap.exit_code())
345
346 def test_system_exit_string_on_error_default(self) -> None:
347 def run() -> None:
348 with self.ap:
349 raise SystemExit("nope")
350
351 self.assertRaises(SystemExit, run)
352 self.assertEqual(3, self.ap.exit_code(on_error_default=3))
353
354
355 class CleanupTest(unittest.TestCase):
356 def test_no_pager_stream_not_closed(self) -> None:
357 flush = mock.MagicMock()
358 with sinks.BufferFixture() as out:
359 with autopage.AutoPager(out.stream) as stream:
360 stream.flush = flush # type: ignore
361 stream.write('foo')
362 self.assertFalse(out.stream.closed)
363 flush.assert_called_once()
364
365 def test_no_pager_broken_pipe(self) -> None:
366 flush = mock.MagicMock(side_effect=BrokenPipeError)
367 with sinks.BufferFixture() as out:
368 with autopage.AutoPager(out.stream) as stream:
369 stream.flush = flush # type: ignore
370 stream.write('foo')
371 self.assertTrue(out.stream.closed)
372 flush.assert_called_once()
373
374 def test_no_pager_broken_pipe_flush(self) -> None:
375 flush = mock.MagicMock(side_effect=BrokenPipeError)
376 with sinks.BufferFixture() as out:
377 with autopage.AutoPager(out.stream) as stream:
378 stream.write('foo')
379 stream.flush = flush # type: ignore
380 self.assertTrue(out.stream.closed)
381 flush.assert_called_once()
382
383 def test_no_pager_stream_closed(self) -> None:
384 flush = mock.MagicMock(side_effect=ValueError)
385 with sinks.BufferFixture() as out:
386 with autopage.AutoPager(out.stream) as stream:
387 stream.write('foo')
388 stream.close()
389 # Calling flush() on a closed stream raises an exception for
390 # real streams (but not for StringIO).
391 stream.flush = flush # type: ignore
392 self.assertTrue(out.stream.closed)
393
394 def test_pager_stream_not_closed(self) -> None:
395 with sinks.TTYFixture() as out:
396 ap = autopage.AutoPager(out.stream)
397 with fixtures.MockPatch('subprocess.Popen') as popen:
398 with sinks.BufferFixture() as pager_in:
399 popen.mock.return_value.stdin = pager_in.stream
400 with ap as stream:
401 self.assertIs(pager_in.stream, stream)
402 self.assertTrue(pager_in.stream.closed)
403
404 def test_pager_stream_not_closed_interrupt(self) -> None:
405 with sinks.TTYFixture() as out:
406 ap = autopage.AutoPager(out.stream)
407 with fixtures.MockPatch('subprocess.Popen') as popen:
408 with sinks.BufferFixture() as pager_in:
409 popen.mock.return_value.stdin = pager_in.stream
410
411 def run() -> None:
412 with ap as stream:
413 self.assertIs(pager_in.stream, stream)
414 raise KeyboardInterrupt
415
416 self.assertRaises(KeyboardInterrupt, run)
417 self.assertTrue(pager_in.stream.closed)
418
419 def test_pager_broken_pipe(self) -> None:
420 flush = mock.MagicMock(side_effect=BrokenPipeError)
421 with sinks.TTYFixture() as out:
422 ap = autopage.AutoPager(out.stream)
423 with fixtures.MockPatch('subprocess.Popen') as popen:
424 with sinks.BufferFixture() as pager_in:
425 popen.mock.return_value.stdin = pager_in.stream
426 pager_in.stream.flush = flush
427 with ap as stream:
428 self.assertIs(pager_in.stream, stream)
429 self.assertTrue(pager_in.stream.closed)
430 popen.mock.return_value.wait.assert_called_once()
431
432 def test_pager_stream_closed(self) -> None:
433 with sinks.TTYFixture() as out:
434 ap = autopage.AutoPager(out.stream)
435 with fixtures.MockPatch('subprocess.Popen') as popen:
436 with sinks.BufferFixture() as pager_in:
437 popen.mock.return_value.stdin = pager_in.stream
438 with ap as stream:
439 self.assertIs(pager_in.stream, stream)
440 stream.close()
441 popen.mock.return_value.wait.assert_called_once()
442
443
444 class StreamConfigureTest(fixtures.TestWithFixtures):
445 def setUp(self) -> None:
446 out = sinks.TempFixture()
447 self.useFixture(out)
448 self.stream = out.stream
449 self.default_lb = self.stream.line_buffering
450 self.default_errors = self.stream.errors
451 self.encoding = codecs.lookup(self.stream.encoding).name
452
453 def test_line_buffering_on(self) -> None:
454 ap = autopage.AutoPager(self.stream, line_buffering=True)
455 ap._reconfigure_output_stream()
456 self.addCleanup(ap._out.close)
457 self.assertTrue(ap._out.line_buffering)
458 self.assertEqual(self.default_errors, ap._out.errors)
459 self.assertEqual(self.encoding, ap._encoding())
460 self.assertIs(True, ap._line_buffering())
461 self.assertEqual(self.default_errors, ap._errors())
462
463 def test_line_buffering_off(self) -> None:
464 ap = autopage.AutoPager(self.stream, line_buffering=False)
465 ap._reconfigure_output_stream()
466 self.addCleanup(ap._out.close)
467 self.assertFalse(ap._out.line_buffering)
468 self.assertEqual(self.default_errors, ap._out.errors)
469 self.assertEqual(self.encoding, ap._encoding())
470 self.assertIs(False, ap._line_buffering())
471 self.assertEqual(self.default_errors, ap._errors())
472
473 def test_stdout_line_buffering_on(self) -> None:
474 with fixtures.MonkeyPatch('sys.stdout', self.stream):
475 ap = autopage.AutoPager(line_buffering=True)
476 ap._reconfigure_output_stream()
477 self.addCleanup(ap._out.close)
478 self.assertTrue(sys.stdout.line_buffering)
479 self.assertEqual(self.default_errors, sys.stdout.errors)
480 self.assertEqual(self.encoding,
481 codecs.lookup(sys.stdout.encoding).name)
482
483 def test_errors(self) -> None:
484 ap = autopage.AutoPager(self.stream,
485 errors=autopage.ErrorStrategy.NAME_REPLACE)
486 ap._reconfigure_output_stream()
487 self.addCleanup(ap._out.close)
488 self.assertEqual(self.default_lb, ap._out.line_buffering)
489 self.assertEqual('namereplace', ap._out.errors)
490 self.assertNotEqual(self.default_errors, ap._out.errors)
491 self.assertEqual(self.encoding, ap._encoding())
492 self.assertEqual('namereplace', ap._errors())
493 self.assertEqual(self.default_lb, ap._line_buffering())
494
495 def test_errors_string(self) -> None:
496 ap = autopage.AutoPager(self.stream,
497 errors='namereplace') # type: ignore
498 ap._reconfigure_output_stream()
499 self.addCleanup(ap._out.close)
500 self.assertEqual(self.default_lb, ap._out.line_buffering)
501 self.assertEqual('namereplace', ap._out.errors)
502 self.assertNotEqual(self.default_errors, ap._out.errors)
503 self.assertEqual(self.encoding, ap._encoding())
504 self.assertEqual('namereplace', ap._errors())
505 self.assertEqual(self.default_lb, ap._line_buffering())
506
507 def test_errors_bogus_string(self) -> None:
508 self.assertRaises(ValueError,
509 autopage.AutoPager,
510 self.stream, errors='panic')
511
512 def test_line_buffering_on_errors(self) -> None:
513 ap = autopage.AutoPager(self.stream,
514 line_buffering=True,
515 errors=autopage.ErrorStrategy.NAME_REPLACE)
516 ap._reconfigure_output_stream()
517 self.addCleanup(ap._out.close)
518 self.assertTrue(ap._out.line_buffering)
519 self.assertEqual('namereplace', ap._out.errors)
520 self.assertNotEqual(self.default_errors, ap._out.errors)
521 self.assertEqual(self.encoding, ap._encoding())
522 self.assertIs(True, ap._line_buffering())
523 self.assertEqual('namereplace', ap._errors())