diff options
author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2019-06-26 02:33:18 -0400 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2019-06-26 02:33:18 -0400 |
commit | e34bba44ef53228aeba613ac6e928b2c315111cf (patch) | |
tree | a39a736c3a36426fe6c278105ce9f6ec5696d16c | |
parent | e6f65e607c6ad2350dfce05f3d5080d0ffbe35f1 (diff) | |
download | cmd2-git-e34bba44ef53228aeba613ac6e928b2c315111cf.tar.gz |
Moved code related to ANSI escape codes to new file called ansi.py
-rw-r--r-- | cmd2/ansi.py | 118 | ||||
-rw-r--r-- | cmd2/argparse_completer.py | 2 | ||||
-rw-r--r-- | cmd2/cmd2.py | 51 | ||||
-rw-r--r-- | cmd2/constants.py | 70 | ||||
-rw-r--r-- | cmd2/transcript.py | 10 | ||||
-rw-r--r-- | cmd2/utils.py | 62 | ||||
-rwxr-xr-x | examples/pirate.py | 3 | ||||
-rw-r--r-- | tests/test_cmd2.py | 24 | ||||
-rw-r--r-- | tests/test_utils.py | 11 |
9 files changed, 173 insertions, 178 deletions
diff --git a/cmd2/ansi.py b/cmd2/ansi.py new file mode 100644 index 00000000..889f1cb3 --- /dev/null +++ b/cmd2/ansi.py @@ -0,0 +1,118 @@ +# coding=utf-8 +"""Support for ANSI escape codes which are used for things like applying style to text""" +import re +from typing import Any + +import colorama +from colorama import Fore, Back, Style +from wcwidth import wcswidth + +# Regular expression to match ANSI escape codes +ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') + +# Foreground color presets +FG_COLORS = { + 'black': Fore.BLACK, + 'red': Fore.RED, + 'green': Fore.GREEN, + 'yellow': Fore.YELLOW, + 'blue': Fore.BLUE, + 'magenta': Fore.MAGENTA, + 'cyan': Fore.CYAN, + 'white': Fore.WHITE, + 'gray': Fore.LIGHTBLACK_EX, + 'lightred': Fore.LIGHTRED_EX, + 'lightblue': Fore.LIGHTBLUE_EX, + 'lightgreen': Fore.LIGHTGREEN_EX, + 'lightyellow': Fore.LIGHTYELLOW_EX, + 'lightmagenta': Fore.LIGHTMAGENTA_EX, + 'lightcyan': Fore.LIGHTCYAN_EX, + 'lightwhite': Fore.LIGHTWHITE_EX, + 'reset': Fore.RESET, +} + +# Background color presets +BG_COLORS = { + 'black': Back.BLACK, + 'red': Back.RED, + 'green': Back.GREEN, + 'yellow': Back.YELLOW, + 'blue': Back.BLUE, + 'magenta': Back.MAGENTA, + 'cyan': Back.CYAN, + 'white': Back.WHITE, + 'gray': Back.LIGHTBLACK_EX, + 'lightred': Back.LIGHTRED_EX, + 'lightblue': Back.LIGHTBLUE_EX, + 'lightgreen': Back.LIGHTGREEN_EX, + 'lightyellow': Back.LIGHTYELLOW_EX, + 'lightmagenta': Back.LIGHTMAGENTA_EX, + 'lightcyan': Back.LIGHTCYAN_EX, + 'lightwhite': Back.LIGHTWHITE_EX, + 'reset': Back.RESET, +} + + +def strip_ansi(text: str) -> str: + """Strip ANSI escape codes from a string. + + :param text: string which may contain ANSI escape codes + :return: the same string with any ANSI escape codes removed + """ + return ANSI_ESCAPE_RE.sub('', text) + + +def ansi_safe_wcswidth(text: str) -> int: + """ + Wraps wcswidth to make it compatible with colored strings + + :param text: the string being measured + """ + # Strip ANSI escape codes since they cause wcswidth to return -1 + return wcswidth(strip_ansi(text)) + + +def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, underline: bool = False) -> str: + """ + Applies styles to text + + :param text: Any object compatible with str.format() + :param fg: foreground color. Accepts color names like 'red' or 'blue' + :param bg: background color. Accepts color names like 'red' or 'blue' + :param bold: apply the bold style if True. Defaults to False. + :param underline: apply the underline style if True. Defaults to False. + """ + values = [] + text = "{}".format(text) + + # Add styles + if fg: + try: + values.append(FG_COLORS[fg.lower()]) + except KeyError: + raise ValueError('Color {} does not exist.'.format(fg)) + if bg: + try: + values.append(BG_COLORS[bg.lower()]) + except KeyError: + raise ValueError('Color {} does not exist.'.format(bg)) + if bold: + values.append(Style.BRIGHT) + if underline: + underline_enable = colorama.ansi.code_to_chars(4) + values.append(underline_enable) + + values.append(text) + + # Remove styles + if fg: + values.append(FG_COLORS['reset']) + if bg: + values.append(BG_COLORS['reset']) + if bold: + values.append(Style.NORMAL) + if underline: + underline_disable = colorama.ansi.code_to_chars(24) + values.append(underline_disable) + + return "".join(values) diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py index 6b3f5298..c3f73552 100644 --- a/cmd2/argparse_completer.py +++ b/cmd2/argparse_completer.py @@ -68,8 +68,8 @@ from typing import List, Dict, Tuple, Callable, Union from colorama import Fore +from .ansi import ansi_safe_wcswidth from .rl_utils import rl_force_redisplay -from .utils import ansi_safe_wcswidth # attribute that can optionally added to an argparse argument (called an Action) to # define the completion choices for the argument. You may provide a Collection or a Function. diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index 75cee55d..20e26e15 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -45,6 +45,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, Un import colorama from colorama import Fore +from . import ansi from . import constants from . import plugin from . import utils @@ -374,7 +375,7 @@ class Cmd(cmd.Cmd): self.quit_on_sigint = False # Quit the loop on interrupt instead of just resetting prompt # Attributes which ARE dynamically settable at runtime - self.colors = constants.COLORS_TERMINAL + self.colors = constants.ANSI_TERMINAL self.continuation_prompt = '> ' self.debug = False self.echo = False @@ -559,7 +560,7 @@ class Cmd(cmd.Cmd): :return: prompt stripped of any ANSI escape codes """ - return utils.strip_ansi(self.prompt) + return ansi.strip_ansi(self.prompt) @property def aliases(self) -> Dict[str, str]: @@ -579,12 +580,11 @@ class Cmd(cmd.Cmd): def _decolorized_write(self, fileobj: IO, msg: str) -> None: """Write a string to a fileobject, stripping ANSI escape sequences if necessary - Honor the current colors setting, which requires us to check whether the - fileobject is a tty. + Honor the current colors setting, which requires us to check whether the fileobject is a tty. """ - if self.colors.lower() == constants.COLORS_NEVER.lower() or \ - (self.colors.lower() == constants.COLORS_TERMINAL.lower() and not fileobj.isatty()): - msg = utils.strip_ansi(msg) + if self.colors.lower() == constants.ANSI_NEVER.lower() or \ + (self.colors.lower() == constants.ANSI_TERMINAL.lower() and not fileobj.isatty()): + msg = ansi.strip_ansi(msg) fileobj.write(msg) def poutput(self, msg: Any, *, end: str = '\n') -> None: @@ -617,7 +617,7 @@ class Cmd(cmd.Cmd): the message text already has the desired style. Defaults to True. """ if add_color: - final_msg = utils.style(msg, fg='lightred') + final_msg = ansi.style(msg, fg='lightred') else: final_msg = "{}".format(msg) self._decolorized_write(sys.stderr, final_msg + end) @@ -640,11 +640,11 @@ class Cmd(cmd.Cmd): final_msg = "{}".format(msg) if add_color: - final_msg = utils.style(final_msg, fg='lightred') + final_msg = ansi.style(final_msg, fg='lightred') if not self.debug: warning = "\nTo enable full traceback, run the following command: 'set debug true'" - final_msg += utils.style(warning, fg="lightyellow") + final_msg += ansi.style(warning, fg="lightyellow") # Set add_color to False since style has already been applied self.perror(final_msg, end=end, add_color=False) @@ -692,8 +692,8 @@ class Cmd(cmd.Cmd): # Don't attempt to use a pager that can block if redirecting or running a script (either text or Python) # Also only attempt to use a pager if actually running in a real fully functional terminal if functional_terminal and not self._redirecting and not self._in_py and not self._script_dir: - if self.colors.lower() == constants.COLORS_NEVER.lower(): - msg_str = utils.strip_ansi(msg_str) + if self.colors.lower() == constants.ANSI_NEVER.lower(): + msg_str = ansi.strip_ansi(msg_str) pager = self.pager if chop: @@ -1278,7 +1278,7 @@ class Cmd(cmd.Cmd): longest_match_length = 0 for cur_match in matches_to_display: - cur_length = utils.ansi_safe_wcswidth(cur_match) + cur_length = ansi.ansi_safe_wcswidth(cur_match) if cur_length > longest_match_length: longest_match_length = cur_length else: @@ -2750,7 +2750,7 @@ class Cmd(cmd.Cmd): widest = 0 # measure the commands for command in cmds: - width = utils.ansi_safe_wcswidth(command) + width = ansi.ansi_safe_wcswidth(command) if width > widest: widest = width # add a 4-space pad @@ -3247,7 +3247,7 @@ class Cmd(cmd.Cmd): if args.__statement__.command == "pyscript": warning = ("pyscript has been renamed and will be removed in the next release, " "please use run_pyscript instead\n") - self.perror(utils.style(warning, fg="lightyellow")) + self.perror(ansi.style(warning, fg="lightyellow")) return py_return @@ -3556,7 +3556,7 @@ class Cmd(cmd.Cmd): # Check if all commands ran if commands_run < len(history): warning = "Command {} triggered a stop and ended transcript generation early".format(commands_run) - self.perror(utils.style(warning, fg="lightyellow")) + self.perror(ansi.style(warning, fg="lightyellow")) # finally, we can write the transcript out to the file try: @@ -3676,7 +3676,7 @@ class Cmd(cmd.Cmd): if args.__statement__.command == "load": warning = ("load has been renamed and will be removed in the next release, " "please use run_script instead\n") - self.perror(utils.style(warning, fg="lightyellow")) + self.perror(ansi.style(warning, fg="lightyellow")) # load has been deprecated do_load = do_run_script @@ -3703,7 +3703,7 @@ class Cmd(cmd.Cmd): if args.__statement__.command == "_relative_load": warning = ("_relative_load has been renamed and will be removed in the next release, " "please use _relative_run_script instead\n") - self.perror(utils.style(warning, fg="lightyellow")) + self.perror(ansi.style(warning, fg="lightyellow")) file_path = args.file_path # NOTE: Relative path is an absolute path, it is just relative to the current script directory @@ -3724,7 +3724,6 @@ class Cmd(cmd.Cmd): import time import unittest import cmd2 - from colorama import Style from .transcript import Cmd2TestCase class TestMyAppCase(Cmd2TestCase): @@ -3740,12 +3739,12 @@ class Cmd(cmd.Cmd): verinfo = ".".join(map(str, sys.version_info[:3])) num_transcripts = len(transcripts_expanded) plural = '' if len(transcripts_expanded) == 1 else 's' - self.poutput(Style.BRIGHT + utils.center_text('cmd2 transcript test', pad='=') + Style.NORMAL) + self.poutput(ansi.style(utils.center_text('cmd2 transcript test', pad='='), bold=True)) self.poutput('platform {} -- Python {}, cmd2-{}, readline-{}'.format(sys.platform, verinfo, cmd2.__version__, rl_type)) self.poutput('cwd: {}'.format(os.getcwd())) self.poutput('cmd2 app: {}'.format(sys.argv[0])) - self.poutput(Style.BRIGHT + 'collected {} transcript{}'.format(num_transcripts, plural) + Style.NORMAL) + self.poutput(ansi.style('collected {} transcript{}'.format(num_transcripts, plural), bold=True)) self.__class__.testfiles = transcripts_expanded sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() @@ -3758,8 +3757,8 @@ class Cmd(cmd.Cmd): if test_results.wasSuccessful(): self._decolorized_write(sys.stderr, stream.read()) finish_msg = '{0} transcript{1} passed in {2:.3f} seconds'.format(num_transcripts, plural, execution_time) - finish_msg = utils.style(utils.center_text(finish_msg, pad='='), fg="green") - self.poutput(Style.BRIGHT + finish_msg + Style.NORMAL) + finish_msg = ansi.style(utils.center_text(finish_msg, pad='='), fg="green", bold=True) + self.poutput(finish_msg) else: # Strip off the initial traceback which isn't particularly useful for end users error_str = stream.read() @@ -3827,14 +3826,14 @@ class Cmd(cmd.Cmd): # That will be included in the input lines calculations since that is where the cursor is. num_prompt_terminal_lines = 0 for line in prompt_lines[:-1]: - line_width = utils.ansi_safe_wcswidth(line) + line_width = ansi.ansi_safe_wcswidth(line) num_prompt_terminal_lines += int(line_width / terminal_size.columns) + 1 # Now calculate how many terminal lines are take up by the input last_prompt_line = prompt_lines[-1] - last_prompt_line_width = utils.ansi_safe_wcswidth(last_prompt_line) + last_prompt_line_width = ansi.ansi_safe_wcswidth(last_prompt_line) - input_width = last_prompt_line_width + utils.ansi_safe_wcswidth(readline.get_line_buffer()) + input_width = last_prompt_line_width + ansi.ansi_safe_wcswidth(readline.get_line_buffer()) num_input_terminal_lines = int(input_width / terminal_size.columns) + 1 diff --git a/cmd2/constants.py b/cmd2/constants.py index f0cdf816..ac8822c0 100644 --- a/cmd2/constants.py +++ b/cmd2/constants.py @@ -2,11 +2,6 @@ # coding=utf-8 """Constants and definitions""" -import re - -import colorama -from colorama import Fore, Back - # Used for command parsing, output redirection, tab completion and word # breaks. Do not change. QUOTES = ['"', "'"] @@ -18,66 +13,11 @@ REDIRECTION_TOKENS = [REDIRECTION_PIPE, REDIRECTION_OUTPUT, REDIRECTION_APPEND] COMMENT_CHAR = '#' MULTILINE_TERMINATOR = ';' -# Regular expression to match ANSI escape codes -ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m') - LINE_FEED = '\n' -# Values for colors setting -COLORS_NEVER = 'Never' -COLORS_TERMINAL = 'Terminal' -COLORS_ALWAYS = 'Always' - - -# Foreground color presets. -FG_COLORS = { - 'black': Fore.BLACK, - 'red': Fore.RED, - 'green': Fore.GREEN, - 'yellow': Fore.YELLOW, - 'blue': Fore.BLUE, - 'magenta': Fore.MAGENTA, - 'cyan': Fore.CYAN, - 'white': Fore.WHITE, - 'gray': Fore.LIGHTBLACK_EX, - 'lightred': Fore.LIGHTRED_EX, - 'lightblue': Fore.LIGHTBLUE_EX, - 'lightgreen': Fore.LIGHTGREEN_EX, - 'lightyellow': Fore.LIGHTYELLOW_EX, - 'lightmagenta': Fore.LIGHTMAGENTA_EX, - 'lightcyan': Fore.LIGHTCYAN_EX, - 'lightwhite': Fore.LIGHTWHITE_EX, - 'reset': Fore.RESET, -} - -# Background color presets. -BG_COLORS = { - 'black': Back.BLACK, - 'red': Back.RED, - 'green': Back.GREEN, - 'yellow': Back.YELLOW, - 'blue': Back.BLUE, - 'magenta': Back.MAGENTA, - 'cyan': Back.CYAN, - 'white': Back.WHITE, - 'gray': Back.LIGHTBLACK_EX, - 'lightred': Back.LIGHTRED_EX, - 'lightblue': Back.LIGHTBLUE_EX, - 'lightgreen': Back.LIGHTGREEN_EX, - 'lightyellow': Back.LIGHTYELLOW_EX, - 'lightmagenta': Back.LIGHTMAGENTA_EX, - 'lightcyan': Back.LIGHTCYAN_EX, - 'lightwhite': Back.LIGHTWHITE_EX, - 'reset': Back.RESET, -} - - -# Underline style built upon Colorama class -class UnderlineStyle(colorama.ansi.AnsiCodes): - ENABLE = 4 - DISABLE = 24 - - -Underline = UnderlineStyle() - DEFAULT_SHORTCUTS = {'?': 'help', '!': 'shell', '@': 'run_script', '@@': '_relative_run_script'} + +# Values for cmd2 setting that determines when to allow ANSI escape codes +ANSI_NEVER = 'Never' +ANSI_TERMINAL = 'Terminal' +ANSI_ALWAYS = 'Always' diff --git a/cmd2/transcript.py b/cmd2/transcript.py index 316592ce..25a79310 100644 --- a/cmd2/transcript.py +++ b/cmd2/transcript.py @@ -13,7 +13,7 @@ import re import unittest from typing import Tuple -from . import utils +from . import ansi, utils class Cmd2TestCase(unittest.TestCase): @@ -56,13 +56,13 @@ class Cmd2TestCase(unittest.TestCase): def _test_transcript(self, fname: str, transcript): line_num = 0 finished = False - line = utils.strip_ansi(next(transcript)) + line = ansi.strip_ansi(next(transcript)) line_num += 1 while not finished: # Scroll forward to where actual commands begin while not line.startswith(self.cmdapp.visible_prompt): try: - line = utils.strip_ansi(next(transcript)) + line = ansi.strip_ansi(next(transcript)) except StopIteration: finished = True break @@ -89,7 +89,7 @@ class Cmd2TestCase(unittest.TestCase): result = self.cmdapp.stdout.read() stop_msg = 'Command indicated application should quit, but more commands in transcript' # Read the expected result from transcript - if utils.strip_ansi(line).startswith(self.cmdapp.visible_prompt): + if ansi.strip_ansi(line).startswith(self.cmdapp.visible_prompt): message = '\nFile {}, line {}\nCommand was:\n{}\nExpected: (nothing)\nGot:\n{}\n'.format( fname, line_num, command, result) self.assertTrue(not (result.strip()), message) @@ -97,7 +97,7 @@ class Cmd2TestCase(unittest.TestCase): self.assertFalse(stop, stop_msg) continue expected = [] - while not utils.strip_ansi(line).startswith(self.cmdapp.visible_prompt): + while not ansi.strip_ansi(line).startswith(self.cmdapp.visible_prompt): expected.append(line) try: line = next(transcript) diff --git a/cmd2/utils.py b/cmd2/utils.py index a5b7f43f..812fa227 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -12,71 +12,9 @@ import threading import unicodedata from typing import Any, Iterable, List, Optional, TextIO, Union -from colorama import Style -from wcwidth import wcswidth - from . import constants -def strip_ansi(text: str) -> str: - """Strip ANSI escape codes from a string. - - :param text: string which may contain ANSI escape codes - :return: the same string with any ANSI escape codes removed - """ - return constants.ANSI_ESCAPE_RE.sub('', text) - - -def ansi_safe_wcswidth(text: str) -> int: - """ - Wraps wcswidth to make it compatible with colored strings - - :param text: the string being measured - """ - # Strip ANSI escape codes since they cause wcswidth to return -1 - return wcswidth(strip_ansi(text)) - - -def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, underline: bool = False) -> str: - """ - Applies style to text - - :param text: Any object compatible with str.format() - :param fg: foreground color. Accepts color names like 'red' or 'blue' - :param bg: background color. Accepts color names like 'red' or 'blue' - :param bold: apply the bold style if True. Defaults to False. - :param underline: apply the underline style if True. Defaults to False. - """ - values = [] - text = "{}".format(text) - if fg: - try: - values.append(constants.FG_COLORS[fg.lower()]) - except KeyError: - raise ValueError('Color {} does not exist.'.format(fg)) - if bg: - try: - values.append(constants.BG_COLORS[bg.lower()]) - except KeyError: - raise ValueError('Color {} does not exist.'.format(bg)) - if bold: - values.append(Style.BRIGHT) - if underline: - values.append(constants.Underline.ENABLE) - - values.append(text) - if fg: - values.append(constants.FG_COLORS['reset']) - if bg: - values.append(constants.BG_COLORS['reset']) - if bold: - values.append(Style.NORMAL) - if underline: - values.append(constants.Underline.DISABLE) - - return "".join(values) - - def is_quoted(arg: str) -> bool: """ Checks if a string is quoted diff --git a/examples/pirate.py b/examples/pirate.py index 41d7d3f4..0d9d89bc 100755 --- a/examples/pirate.py +++ b/examples/pirate.py @@ -9,7 +9,6 @@ It demonstrates many features of cmd2. import argparse import cmd2 -from cmd2 import utils from cmd2.constants import MULTILINE_TERMINATOR @@ -70,7 +69,7 @@ class Pirate(cmd2.Cmd): def do_sing(self, arg): """Sing a colorful song.""" - self.poutput(utils.style(arg, fg=self.songcolor)) + self.poutput(cmd2.ansi.style(arg, fg=self.songcolor)) yo_parser = argparse.ArgumentParser() yo_parser.add_argument('--ho', type=int, default=2, help="How often to chant 'ho'") diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 5ff8513f..3b6089f4 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -21,7 +21,7 @@ except ImportError: from unittest import mock import cmd2 -from cmd2 import clipboard, constants, utils +from cmd2 import ansi, clipboard, constants, utils from .conftest import run_cmd, normalize, verify_help_text, HELP_HISTORY, SHORTCUTS_TXT, SHOW_TXT, SHOW_LONG def CreateOutsimApp(): @@ -1460,7 +1460,7 @@ def test_poutput_none(outsim_app): def test_poutput_color_always(outsim_app): msg = 'Hello World' outsim_app.colors = 'Always' - outsim_app.poutput(utils.style(msg, fg='cyan')) + outsim_app.poutput(ansi.style(msg, fg='cyan')) out = outsim_app.stdout.getvalue() expected = Fore.CYAN + msg + Fore.RESET + '\n' assert out == expected @@ -1468,7 +1468,7 @@ def test_poutput_color_always(outsim_app): def test_poutput_color_never(outsim_app): msg = 'Hello World' outsim_app.colors = 'Never' - outsim_app.poutput(utils.style(msg, fg='cyan')) + outsim_app.poutput(ansi.style(msg, fg='cyan')) out = outsim_app.stdout.getvalue() expected = msg + '\n' assert out == expected @@ -1767,7 +1767,7 @@ def test_ppaged(outsim_app): def test_ppaged_strips_color_when_redirecting(outsim_app): msg = 'testing...' end = '\n' - outsim_app.colors = cmd2.constants.COLORS_TERMINAL + outsim_app.colors = cmd2.constants.ANSI_TERMINAL outsim_app._redirecting = True outsim_app.ppaged(Fore.RED + msg) out = outsim_app.stdout.getvalue() @@ -1776,7 +1776,7 @@ def test_ppaged_strips_color_when_redirecting(outsim_app): def test_ppaged_strips_color_when_redirecting_if_always(outsim_app): msg = 'testing...' end = '\n' - outsim_app.colors = cmd2.constants.COLORS_ALWAYS + outsim_app.colors = cmd2.constants.ANSI_ALWAYS outsim_app._redirecting = True outsim_app.ppaged(Fore.RED + msg) out = outsim_app.stdout.getvalue() @@ -1912,11 +1912,11 @@ class ColorsApp(cmd2.Cmd): def test_colors_default(): app = ColorsApp() - assert app.colors == cmd2.constants.COLORS_TERMINAL + assert app.colors == cmd2.constants.ANSI_TERMINAL def test_colors_pouterr_always_tty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_ALWAYS + app.colors = cmd2.constants.ANSI_ALWAYS mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -1938,7 +1938,7 @@ def test_colors_pouterr_always_tty(mocker, capsys): def test_colors_pouterr_always_notty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_ALWAYS + app.colors = cmd2.constants.ANSI_ALWAYS mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) @@ -1960,7 +1960,7 @@ def test_colors_pouterr_always_notty(mocker, capsys): def test_colors_terminal_tty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_TERMINAL + app.colors = cmd2.constants.ANSI_TERMINAL mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -1981,7 +1981,7 @@ def test_colors_terminal_tty(mocker, capsys): def test_colors_terminal_notty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_TERMINAL + app.colors = cmd2.constants.ANSI_TERMINAL mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) @@ -1995,7 +1995,7 @@ def test_colors_terminal_notty(mocker, capsys): def test_colors_never_tty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_NEVER + app.colors = cmd2.constants.ANSI_NEVER mocker.patch.object(app.stdout, 'isatty', return_value=True) mocker.patch.object(sys.stderr, 'isatty', return_value=True) @@ -2009,7 +2009,7 @@ def test_colors_never_tty(mocker, capsys): def test_colors_never_notty(mocker, capsys): app = ColorsApp() - app.colors = cmd2.constants.COLORS_NEVER + app.colors = cmd2.constants.ANSI_NEVER mocker.patch.object(app.stdout, 'isatty', return_value=False) mocker.patch.object(sys.stderr, 'isatty', return_value=False) diff --git a/tests/test_utils.py b/tests/test_utils.py index e1f34b8a..88eb0901 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -10,6 +10,7 @@ import pytest from colorama import Fore, Back import cmd2.utils as cu +import cmd2.ansi as ansi HELLO_WORLD = 'Hello, world!' @@ -18,28 +19,28 @@ def test_strip_ansi(): base_str = HELLO_WORLD ansi_str = Fore.GREEN + base_str + Fore.RESET assert base_str != ansi_str - assert base_str == cu.strip_ansi(ansi_str) + assert base_str == ansi.strip_ansi(ansi_str) def test_ansi_safe_wcswidth(): base_str = HELLO_WORLD ansi_str = Fore.GREEN + base_str + Fore.RESET - assert cu.ansi_safe_wcswidth(ansi_str) != len(ansi_str) + assert ansi.ansi_safe_wcswidth(ansi_str) != len(ansi_str) def test_style(): base_str = HELLO_WORLD ansi_str = Fore.BLUE + Back.GREEN + base_str + Fore.RESET + Back.RESET - assert cu.style(base_str, fg='blue', bg='green') == ansi_str + assert ansi.style(base_str, fg='blue', bg='green') == ansi_str def test_style_color_not_exist(): base_str = HELLO_WORLD try: - cu.style(base_str, fg='hello', bg='green') + ansi.style(base_str, fg='hello', bg='green') assert False except ValueError: assert True try: - cu.style(base_str, fg='blue', bg='hello') + ansi.style(base_str, fg='blue', bg='hello') assert False except ValueError: assert True |