| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
import argparse |
| 14 |
|
| 15 |
import fixtures |
| 16 |
|
| 17 |
import typing |
| 18 |
|
| 19 |
import autopage |
| 20 |
import autopage.argparse |
| 21 |
|
| 22 |
|
| 23 |
class ArgumentParseTest(fixtures.TestWithFixtures): |
| 24 |
def setUp(self) -> None: |
| 25 |
self.useFixture(fixtures.EnvironmentVariable('PYTHON_COLORS', '1')) |
| 26 |
patch_ap = self.useFixture(fixtures.MockPatch('autopage.AutoPager')) |
| 27 |
self.pager = patch_ap.mock |
| 28 |
self.stream = self.useFixture(fixtures.StringStream('stdout')).stream |
| 29 |
self.pager.return_value.__enter__.return_value = self.stream |
| 30 |
|
| 31 |
def test_argparse(self, |
| 32 |
module: typing.Any = autopage.argparse, |
| 33 |
color: bool = True) -> None: |
| 34 |
self.pager.return_value.to_terminal.return_value = color |
| 35 |
parser = module.ArgumentParser() |
| 36 |
try: |
| 37 |
parser.parse_args(['foo', '--help']) |
| 38 |
except SystemExit as exit: |
| 39 |
self.assertIs(self.pager.return_value.exit_code.return_value, |
| 40 |
exit.code) |
| 41 |
self.pager.assert_called_once_with(None, |
| 42 |
allow_color=True, |
| 43 |
line_buffering=False, |
| 44 |
reset_on_exit=False) |
| 45 |
self.pager.return_value.__enter__.assert_called_once() |
| 46 |
self.stream.seek(0) |
| 47 |
output = self.stream.read() |
| 48 |
self.assertEqual(any(c in output for c in ('\033', '\x1b')), color) |
| 49 |
|
| 50 |
def test_argparse_no_color(self) -> None: |
| 51 |
self.test_argparse(color=False) |
| 52 |
|
| 53 |
def test_monkey_patch(self, color: bool = True) -> None: |
| 54 |
patch = self.useFixture(fixtures.MockPatch('argparse._HelpAction')) |
| 55 |
autopage.argparse.monkey_patch() |
| 56 |
self.assertIsNot(patch.mock, argparse._HelpAction) |
| 57 |
self.test_argparse(argparse, color) |
| 58 |
|
| 59 |
def test_monkey_patch_no_color(self) -> None: |
| 60 |
self.test_monkey_patch(color=False) |
| 61 |
|
| 62 |
def test_monkey_patch_context(self, color: bool = True) -> None: |
| 63 |
patch = self.useFixture(fixtures.MockPatch('argparse._HelpAction')) |
| 64 |
with autopage.argparse.monkey_patch(): |
| 65 |
self.assertIsNot(patch.mock, argparse._HelpAction) |
| 66 |
self.test_argparse(argparse, color) |
| 67 |
self.assertIs(patch.mock, argparse._HelpAction) |
| 68 |
|
| 69 |
def test_monkey_patch_context_no_color(self) -> None: |
| 70 |
self.test_monkey_patch_context(color=False) |