Пример #1
0
def test_link_id():
    assert Style().link_id == ""
    assert Style.parse("").link_id == ""
    assert Style.parse("red").link_id == ""
    style = Style.parse("red link https://example.org")
    assert isinstance(style.link_id, str)
    assert len(style.link_id) > 1
Пример #2
0
def test_get_row_style():
    console = Console()
    table = Table()
    table.add_row("foo")
    table.add_row("bar", style="on red")
    assert table.get_row_style(console, 0) == Style.parse("")
    assert table.get_row_style(console, 1) == Style.parse("on red")
Пример #3
0
def test_decode():
    console = Console(force_terminal=True,
                      legacy_windows=False,
                      color_system="truecolor")
    console.begin_capture()
    console.print("Hello")
    console.print("[b]foo[/b]")
    console.print("[link http://example.org]bar")
    console.print("[#ff0000 on color(200)]red")
    console.print("[color(200) on #ff0000]red")
    terminal_codes = console.end_capture()

    decoder = AnsiDecoder()
    lines = list(decoder.decode(terminal_codes))

    expected = [
        Text("Hello"),
        Text("foo", spans=[Span(0, 3, Style.parse("bold"))]),
        Text("bar", spans=[Span(0, 3,
                                Style.parse("link http://example.org"))]),
        Text("red", spans=[Span(0, 3, Style.parse("#ff0000 on color(200)"))]),
        Text("red", spans=[Span(0, 3, Style.parse("color(200) on #ff0000"))]),
    ]

    assert lines == expected
Пример #4
0
def test_get_number_styles():
    syntax = Syntax(CODE, "python", theme="monokai", line_numbers=True)
    console = Console(color_system="windows")
    assert syntax._get_number_styles(console=console) == (
        Style.parse("on #272822"),
        Style.parse("dim on #272822"),
        Style.parse("not dim on #272822"),
    )
Пример #5
0
def test_theme_stack():
    theme = Theme({"warning": "red"})
    stack = ThemeStack(theme)
    assert stack.get("warning") == Style.parse("red")
    new_theme = Theme({"warning": "bold yellow"})
    stack.push_theme(new_theme)
    assert stack.get("warning") == Style.parse("bold yellow")
    stack.pop_theme()
    assert stack.get("warning") == Style.parse("red")
    with pytest.raises(ThemeStackError):
        stack.pop_theme()
Пример #6
0
def test_style_context():
    console = Console()

    with StyleContext(console, None):
        assert console._current_style == Style()

    with StyleContext(console, "bold"):
        assert console._current_style == Style.parse("bold")
        with StyleContext(console, "red"):
            assert console._current_style == Style.parse("bold red")
        assert console._current_style == Style.parse("bold")
    assert console._current_style == Style()
Пример #7
0
def test_rich_console(live_render):
    options = ConsoleOptions(
        legacy_windows=False,
        min_width=10,
        max_width=20,
        is_terminal=False,
        encoding="utf-8",
    )
    rich_console = live_render.__rich_console__(Console(), options)
    assert [Segment("my string", Style.parse("none"))] == list(rich_console)
    live_render.style = "red"
    rich_console = live_render.__rich_console__(Console(), options)
    assert [Segment("my string", Style.parse("red"))] == list(rich_console)
Пример #8
0
def is_valid_style(style: str) -> bool:
    """Checks whether the entered color is a valid color according to rich
    Parameters
    ----------
    style : :class:`str`
        The style to check whether it is valid.
    Returns
    -------
    Boolean
        Returns whether it is valid style or not according to rich.
    """
    try:
        Style.parse(style)
        return True
    except StyleSyntaxError:
        return False
Пример #9
0
    def test_write_styled(
        SetConsoleTextAttribute,
        win32_console_getters,
        win32_handle,
        capsys,
    ):
        style = Style.parse("black on red")
        text = "Hello, world!"
        term = LegacyWindowsTerm(sys.stdout)

        term.write_styled(text, style)

        captured = capsys.readouterr()
        assert captured.out == text

        # Ensure we set the text attributes and then reset them after writing styled text
        call_args = SetConsoleTextAttribute.call_args_list
        assert len(call_args) == 2
        first_args, first_kwargs = call_args[0]
        second_args, second_kwargs = call_args[1]

        assert first_args == (win32_handle,)
        assert first_kwargs["attributes"].value == 64
        assert second_args == (win32_handle,)
        assert second_kwargs["attributes"] == DEFAULT_STYLE_ATTRIBUTE
Пример #10
0
def test_text_with_style(legacy_term_mock):
    text = "Hello, world!"
    style = Style.parse("black on red")
    buffer = [Segment(text, style)]

    legacy_windows_render(buffer, legacy_term_mock)

    legacy_term_mock.write_styled.assert_called_once_with(text, style)
Пример #11
0
def unify_styles(*styles: str | Style) -> Style:
    """Unify styles."""
    parsed_styles = []
    for style in styles:
        if isinstance(style, str) and style in theme.styles:
            parsed_styles.append(theme.styles[style])
        elif isinstance(style, str):
            parsed_styles.append(Style.parse(style))
        else:
            parsed_styles.append(style)
    return Style.combine(parsed_styles)
Пример #12
0
def test_highlight_background_color():
    syntax = Syntax(
        CODE,
        lexer_name="python",
        line_numbers=True,
        line_range=(2, 10),
        theme="foo",
        code_width=60,
        word_wrap=True,
        background_color="red",
    )
    assert syntax.highlight(CODE).style == Style.parse("on red")
Пример #13
0
    def test_write_styled_reverse(_, SetConsoleTextAttribute, win32_handle):
        style = Style.parse("dim bright_red on blue")
        text = "Hello, world!"
        term = LegacyWindowsTerm(sys.stdout)

        term.write_styled(text, style)

        call_args = SetConsoleTextAttribute.call_args_list
        first_args, first_kwargs = call_args[0]

        expected_attr = 4 + 16  # 4 for red text (after dim), +16 for blue bg
        assert first_args == (win32_handle, )
        assert first_kwargs["attributes"].value == expected_attr
Пример #14
0
    def test_write_styled_bold(_, SetConsoleTextAttribute, win32_handle):
        style = Style.parse("bold black on red")
        text = "Hello, world!"
        term = LegacyWindowsTerm(sys.stdout)

        term.write_styled(text, style)

        call_args = SetConsoleTextAttribute.call_args_list
        first_args, first_kwargs = call_args[0]

        expected_attr = 64 + 8  # 64 for red bg, +8 for bright black
        assert first_args == (win32_handle, )
        assert first_kwargs["attributes"].value == expected_attr
Пример #15
0
    def test_write_styled_no_foreground_color(_, SetConsoleTextAttribute,
                                              win32_handle):
        style = Style.parse("on blue")
        text = "Hello, world!"
        term = LegacyWindowsTerm(sys.stdout)

        term.write_styled(text, style)

        call_args = SetConsoleTextAttribute.call_args_list
        first_args, first_kwargs = call_args[0]

        expected_attr = 16 | term._default_fore  # 16 for blue bg, plus default fg color
        assert first_args == (win32_handle, )
        assert first_kwargs["attributes"].value == expected_attr
Пример #16
0
    def test_write_styled_reverse(
        SetConsoleTextAttribute, win32_console_getters, win32_handle
    ):
        style = Style.parse("reverse red on blue")
        text = "Hello, world!"
        term = LegacyWindowsTerm(sys.stdout)

        term.write_styled(text, style)

        call_args = SetConsoleTextAttribute.call_args_list
        first_args, first_kwargs = call_args[0]

        expected_attr = 64 + 1  # 64 for red bg (after reverse), +1 for blue fg
        assert first_args == (win32_handle,)
        assert first_kwargs["attributes"].value == expected_attr
Пример #17
0
def test_lines_justify():
    console = Console()
    lines1 = Lines([Text("foo", style="b"), Text("test", style="b")])
    lines1.justify(console, 10, justify="left")
    assert lines1._lines == [Text("foo       "), Text("test      ")]
    lines1.justify(console, 10, justify="center")
    assert lines1._lines == [Text("   foo    "), Text("   test   ")]
    lines1.justify(console, 10, justify="right")
    assert lines1._lines == [Text("       foo"), Text("      test")]

    lines2 = Lines([Text("foo bar", style="b"), Text("test", style="b")])
    lines2.justify(console, 7, justify="full")
    print(repr(lines2._lines[0].spans))
    assert lines2._lines == [
        Text(
            "foo bar",
            spans=[Span(0, 3, "b"), Span(3, 4, Style.parse("bold")), Span(4, 7, "b")],
        ),
        Text("test"),
    ]
Пример #18
0
def test_lines_justify():
    console = Console()
    lines1 = Lines([Text("foo"), Text("test")])
    lines1.justify(console, 10, justify="left")
    assert lines1._lines == [Text("foo       "), Text("test      ")]
    lines1.justify(console, 10, justify="center")
    assert lines1._lines == [Text("   foo    "), Text("   test   ")]
    lines1.justify(console, 10, justify="right")
    assert lines1._lines == [Text("       foo"), Text("      test")]

    lines2 = Lines([Text("foo bar"), Text("test")])
    lines2.justify(console, 7, justify="full")
    assert lines2._lines == [
        Text(
            "foo bar",
            spans=[
                Span(0, 3, ""),
                Span(3, 4, Style.parse("none")),
                Span(4, 7, "")
            ],
        ),
        Text("test"),
    ]
Пример #19
0
# coding: utf-8

import sys

from rich.style import Style
from rich.theme import Theme

SVĚTLÉ_BARVY = {
    'červená': Style.parse('bright_red'),
    'modrá': Style.parse('bright_blue'),
    'fialová': Style.parse('bright_magenta'),
    'tyrkys': Style.parse('bright_cyan'),
}

TUČNÉ_SVĚTLÉ_BARVY = {
    'červená': Style.parse('bold bright_red'),
    'modrá': Style.parse('bold bright_blue'),
    'fialová': Style.parse('bold bright_magenta'),
    'tyrkys': Style.parse('bold bright_cyan'),
}

TMAVÉ_BARVY = {
    'červená': Style.parse('red'),
    'modrá': Style.parse('blue'),
    'fialová': Style.parse('magenta'),
    'tyrkys': Style.parse('cyan'),
}

ŽÁDNÉ_BARVY = {
    'červená': Style(),
    'modrá': Style(),
Пример #20
0
from rich.console import Console
from rich.style import Style
from rich.highlighter import RegexHighlighter


class RequestHighlighter(RegexHighlighter):
    base_style = "req."
    highlights = [
        r"^(?P<protocol>\w+) (?P<method>\w+) (?P<path>\S+) (?P<result>\w+) (?P<stats>\[.+\])$",
        r"\/(?P<filename>\w+\..{3,4})",
    ]


console = Console()
console.push_styles({
    "req.protocol": Style.parse("dim bold green"),
    "req.method": Style.parse("bold cyan"),
    "req.path": Style.parse("magenta"),
    "req.filename": Style.parse("bright_magenta"),
    "req.result": Style.parse("yellow"),
    "req.stats": Style.parse("dim"),
})

console.log("Server starting...")
console.log("Serving on http://127.0.0.1:8000")

time.sleep(1)

request_highlighter = RequestHighlighter()

console.log(
Пример #21
0
        r"(?P<operator_name>\w[acos]+)",
        r"(?P<number>[0-9]+)",
        r"(?P<parentheses>[()]+)",
        r"(?P<superscript>[╦Б╩ИрХ╗рхќ╩│╦брхЌрхўрхЏ╩и╩░РЂ▒╩▓рхЈ╦АрхљРЂ┐рхњрхЃрхЄрХюрхѕрхЅрХархЇр┤Йр┤┐рхђрхЂрхѓр┤┤р┤хр┤Хр┤ир┤Ир┤╣р┤║р┤╝р┤гр┤«р┤░р┤▒р┤│рхархАрхЪрхърхЮРЂИРЂ╣╦ѓРЂ╝╦ЃРЂ░┬╣┬▓┬│РЂ┤РЂхРЂХРЂиРЂйРЂЙРѓЅРѓѕРѓЄРѓєРѓЁРѓёРѓЃРѓѓРѓЂРѓђРѓІРѓІРѓіРѓјРѓЇрхерхфрхЕрхдрхД]+)",
        r"(?P<operators>[-+/*РѕџрХ┤Рќ│РѕФРѕЉ╬а]+)",
        r"(?P<equal>[=РєњРЄњ]+)",
        r"(?P<deriv>[Рѕѓ/Рѕѓ]+)",
        r"(?P<deriv>[d/d]+)",
        r"(?P<mathb>[РѕЁ­ЮњЕРёѓРёЏРёІРё░РёњРё│РёџРёцРёЇРёЎРёЮAРёгРёЉРё»РёњРёІРё░РёЏРёі­ЮњЕ]+)",
    ]


theme = Theme({
    ".operator_name": light_blue_light,
    ".number": amber_lighter,
    ".superscript": Style.parse(f"bold {amber_light}"),
    ".parentheses": cyan_light,
    ".operators": orange_darker,
    ".variables": Style.parse(f"italic {orange}"),
    ".equal": Style.parse(f"bold {pink}"),
    ".deriv": Style.parse(f"bold {pink}"),
    ".mathb": cyan,
})

# set console for printing
console = Console(highlighter=Highlighter(), theme=theme)
rich._console = console
"""
    Colors used to highlight string expressions
    for nice printing with Rich.
"""
Пример #22
0
try:
    from mpi4py import MPI
    root = MPI.COMM_WORLD.Get_rank() == 0
    using_mpi = MPI.COMM_WORLD.Get_size() > 1
except ImportError:
    root = True
    using_mpi = False

# workaround for a bug in OpenMPI (or anything else that screws up the terminal size);
# see https://github.com/willmcgugan/rich/issues/127
import shutil
width = None if shutil.get_terminal_size().columns != 0 else 80

theme = Theme({
    "variables": Style.parse("yellow"),
    "warn": Style.parse("yellow"),
    "affirm": Style.parse("green"),
    "error": Style.parse("red"),
    "cell-name": Style.parse("yellow"),
})

console = Console(width=width, theme=theme)


def show_console(cell, rule=False, verbose=False, no_show=False):
    if rule:
        console.print(Rule(cell.type_name() if verbose else ''))

    if not no_show:
        cell.show_console(console)
Пример #23
0
def test_pygments_syntax_theme():
    style = PygmentsSyntaxTheme("default")
    assert style.get_style_for_token("abc") == Style.parse("none")
Пример #24
0
                ))


if __name__ == "__main__":  # type: ignore
    from rich import print

    inspect = Inspect({}, docs=True, methods=True, dunder=True)
    print(inspect)

    t = Text("Hello, World")
    print(Inspect(t))

    from rich.style import Style
    from rich.color import Color

    print(Inspect(Style.parse("bold red on black"), methods=True, docs=True))
    print(Inspect(Color.parse("#ffe326"), methods=True, docs=True))

    from rich import get_console

    print(Inspect(get_console(), methods=False))

    print(Inspect(open("foo.txt", "wt"), methods=False))

    print(Inspect("Hello", methods=False, dunder=True))
    print(Inspect(inspect, methods=False, dunder=False, docs=False))

    class Foo:
        @property
        def broken(self):
            1 / 0
Пример #25
0
 def time_parse_mixed_complex_style(self):
     Style.parse("dim bold reverse #00ee00 on rgb(123,12,50)")
Пример #26
0
 def setup(self):
     self.console = Console(
         file=StringIO(), color_system="truecolor", legacy_windows=False, width=100
     )
     self.style1 = Style.parse("blue on red")
     self.style2 = Style.parse("green italic bold")
Пример #27
0
 def time_parse_ansi(self):
     Style.parse("red on blue")
Пример #28
0
        SetConsoleTitle(title)


if __name__ == "__main__":
    handle = GetStdHandle()

    from rich.console import Console

    console = Console()

    term = LegacyWindowsTerm(sys.stdout)
    term.set_title("Win32 Console Examples")

    style = Style(color="black", bgcolor="red")

    heading = Style.parse("black on green")

    # Check colour output
    console.rule("Checking colour output")
    console.print("[on red]on red!")
    console.print("[blue]blue!")
    console.print("[yellow]yellow!")
    console.print("[bold yellow]bold yellow!")
    console.print("[bright_yellow]bright_yellow!")
    console.print("[dim bright_yellow]dim bright_yellow!")
    console.print("[italic cyan]italic cyan!")
    console.print("[bold white on blue]bold white on blue!")
    console.print("[reverse bold white on blue]reverse bold white on blue!")
    console.print("[bold black on cyan]bold black on cyan!")
    console.print("[black on green]black on green!")
    console.print("[blue on green]blue on green!")
Пример #29
0
 def get_style(text: str) -> Style:
     return Style.parse(
         f"bold yellow link https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={text}"
     )
Пример #30
0
 def time_parse_hex(self):
     Style.parse("#f0f0f0 on #e2e28a")