示例#1
0
def test_console_soft_wrap() -> None:
    """Assures long prints on console are not wrapped when requested."""
    console = Console(file=io.StringIO(),
                      width=20,
                      record=True,
                      soft_wrap=True,
                      redirect=False)
    text = 21 * "x"
    console.print(text, end="")
    assert console.file.getvalue() == text  # type: ignore
    result = console.export_text()
    assert text in result
示例#2
0
def test_rich_console_ex() -> None:
    """Validate that ConsoleEx can capture output from print() calls."""
    console = Console(record=True, redirect=True)
    console.print("alpha")
    print("beta")
    sys.stdout.write("gamma\n")
    sys.stderr.write("delta\n")
    # While not supposed to happen we want to be sure that this will not raise
    # an exception. Some libraries may still sometimes send bytes to the
    # streams, notable example being click.
    # sys.stdout.write(b"epsilon\n")  # type: ignore
    text = console.export_text()
    assert text == "alpha\nbeta\ngamma\ndelta\n"
示例#3
0
def bootstrap() -> Console:
    Markdown.elements["code_block"] = MyCodeBlock

    # We also initialize the logging console
    logging_console = Console(file=sys.stderr, force_terminal=1, theme=theme)

    logger = logging.getLogger()  # type: logging.Logger
    # logger.setLevel(logging.DEBUG)

    handler = RichHandler(console=logging_console,
                          show_time=False,
                          show_path=False,
                          markup=True)  # type: ignore
    # logger.addHandler(handler)
    logger.handlers = [handler]
    logger.propagate = False

    return Console(
        theme=theme,
        highlighter=rich.highlighter.ReprHighlighter(),
        record=True,
        soft_wrap=True,
        redirect=True,
    )
示例#4
0
def test_rich_console_ex_ansi() -> None:
    """Validate that ANSI sent to sys.stdout does not become garbage in record."""
    print()
    console = Console(force_terminal=True, record=True, redirect=True)
    console.print("[green]this from Console.print()[/green]", style="red")

    text = console.export_text(clear=False)
    assert "this from Console" in text

    html = console.export_html(clear=False)
    assert "#008000" in html
示例#5
0
def test_console_print_ansi() -> None:
    """Validates that Console.print() with ANSI does not make break them."""
    console = Console(force_terminal=True,
                      record=True,
                      soft_wrap=True,
                      redirect=True)
    text = "\033[92mfuture is green!\033[0m"
    console.print(text)
    text_result = console.export_text(clear=False)
    assert "future is green!" in text_result
    html_result = console.export_html()
    assert "#00ff00" in html_result
示例#6
0
def rich_logger_fixture() -> Tuple[logging.Logger, RichHandler]:
    """Returns tuple with logger and handler to be tested."""
    rich_handler = RichHandler(
        console=Console(
            file=io.StringIO(),
            force_terminal=True,
            width=80,
            color_system="truecolor",
            soft_wrap=True,
        ),
        enable_link_path=False,
    )

    logging.basicConfig(level="NOTSET",
                        format="%(message)s",
                        datefmt="[DATE]",
                        handlers=[rich_handler])
    rich_log = logging.getLogger("rich")
    rich_log.addHandler(rich_handler)
    return (rich_log, rich_handler)
示例#7
0
def test_rich_console_ex_ansi() -> None:
    """Validate that ANSI sent to sys.stdout does not become garbage in record."""
    print()
    console = Console(force_terminal=True, record=True, redirect=True)
    console.print("[green]this from Console.print()[/green]", style="red")
    proc = run(r'echo -e "\033[31mred\033[0m"')
    assert proc.returncode == 0
    assert "red" in proc.stdout

    # validate that what rich recorded is the same as what the subprocess produced
    text = console.export_text(clear=False)
    assert "red" in text

    # validate that html export also contains at least the "red" text
    html = console.export_html(clear=False)
    assert '<span class="r3">red</span>' in html
示例#8
0
            self._config.scenario.name,
            underscore(self.__class__.__name__),
            extra={"markup": True},
        )
        rt = func(*args, **kwargs)
        # section close code goes here
        return rt

    return wrapper


@lru_cache()
def get_section_loggers() -> Iterable[Callable]:
    """Return a list of section wrappers to be added."""
    default_section_loggers = [section_logger]
    if not os.getenv("CI"):
        return default_section_loggers
    elif os.getenv("GITHUB_ACTIONS"):
        return [github_actions_groups] + default_section_loggers
    elif os.getenv("GITLAB_CI"):
        return [gitlab_ci_sections] + default_section_loggers
    elif os.getenv("TRAVIS"):
        return [travis_ci_folds] + default_section_loggers
    # CI is set but no extra section_loggers apply.
    return default_section_loggers


LOGGING_CONSOLE = Console(file=sys.stderr,
                          force_terminal=should_do_markup(),
                          theme=theme)
示例#9
0
        return False

    # User configuration requested colors
    if py_colors is not None:
        return to_bool(py_colors)

    term = os.environ.get("TERM", "")
    if "xterm" in term:
        return True

    if term == "dumb":
        return False

    # Use tty detection logic as last resort because there are numerous
    # factors that can make isatty return a misleading value, including:
    # - stdin.isatty() is the only one returning true, even on a real terminal
    # - stderr returting false if user user uses a error stream coloring solution
    return sys.stdout.isatty()


console = Console(force_terminal=should_do_markup(),
                  theme=theme,
                  record=True,
                  redirect=True)
# Define ANSIBLE_FORCE_COLOR if markup is enabled and another value is not
# already given. This assures that Ansible subprocesses are still colored,
# even if they do not run with a real TTY.
if should_do_markup():
    os.environ["ANSIBLE_FORCE_COLOR"] = os.environ.get("ANSIBLE_FORCE_COLOR",
                                                       "1")
示例#10
0
    text = 10 * "x"  # a long text that would likely wrap on a normal console
    logger.error("%s %s", text, 123)

    # verify that the long text was not wrapped
    output = strip_ansi_escape(
        rich_handler.console.file.getvalue())  # type: ignore
    assert text in output
    assert "ERROR" in output
    assert "\n" not in output[:-1]


if __name__ == "__main__":
    handler = RichHandler(
        console=Console(
            force_terminal=True,
            width=55510,  # this is expected to have no effect
            color_system="truecolor",
            soft_wrap=True,
        ),
        enable_link_path=False,
        show_time=True,
        show_level=True,
        show_path=True,
    )
    logging.basicConfig(
        level="NOTSET",
        format="%(message)s",
        # datefmt="[DATE]",
        handlers=[handler],
    )
    log = logging.getLogger("rich")
    # log.addHandler(handler)
示例#11
0
    if term == "dumb":
        return False

    # Use tty detection logic as last resort because there are numerous
    # factors that can make isatty return a misleading value, including:
    # - stdin.isatty() is the only one returning true, even on a real terminal
    # - stderr returting false if user user uses a error stream coloring solution
    return sys.stdout.isatty()


console_options: Dict[str, Any] = {
    "emoji": False,
    "theme": theme,
    "soft_wrap": True
}

console = Console(force_terminal=should_do_markup(),
                  theme=theme,
                  record=True,
                  redirect=True)
console_options_stderr = console_options.copy()
console_options_stderr["stderr"] = True
console_stderr: Console = Console(**console_options_stderr)

# Define ANSIBLE_FORCE_COLOR if markup is enabled and another value is not
# already given. This assures that Ansible subprocesses are still colored,
# even if they do not run with a real TTY.
if should_do_markup():
    os.environ["ANSIBLE_FORCE_COLOR"] = os.environ.get("ANSIBLE_FORCE_COLOR",
                                                       "1")