def test_wrap_long(): test = Text("abracadabra", justify="left") lines = test.wrap(Console(), 4) assert len(lines) == 3 assert lines[0] == Text("abra") assert lines[1] == Text("cada") assert lines[2] == Text("bra ")
def test_console_width(): console = Console() test = Text("Hello World!\nfoobarbaz") assert test.__rich_measure__(console, 80) == Measurement(9, 12) assert Text(" " * 4).__rich_measure__(console, 80) == Measurement(4, 4) assert Text(" \n \n ").__rich_measure__(console, 80) == Measurement(3, 3)
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
def test_highlight_words(): test = Text("Do NOT! touch anything!") words = ["NOT", "!"] count = test.highlight_words(words, "red") assert count == 3 assert sorted(test._spans) == [ Span(3, 6, "red"), # NOT Span(6, 7, "red"), # ! Span(22, 23, "red"), # ! ] # regex escape test test = Text("[o|u]aeiou") words = ["[a|e|i]", "[o|u]"] count = test.highlight_words(words, "red") assert count == 1 assert test._spans == [Span(0, 5, "red")] # case sensitive test = Text("AB Ab aB ab") words = ["AB"] count = test.highlight_words(words, "red") assert count == 1 assert test._spans == [Span(0, 2, "red")] test = Text("AB Ab aB ab") count = test.highlight_words(words, "red", case_sensitive=False) assert count == 4
def ansify(style: Style, text: Union[Text, str]) -> Text: if isinstance(text, Text): spans = [Span(s.start, s.end, s.style + style) for s in text.spans] return Text(text.plain, spans=spans, style=text.style + style) elif isinstance(text, str): spans = [Span(0, len(text), style)] return Text(text, spans=spans)
def test_highlight_regex(): test = Text("peek-a-boo") count = test.highlight_regex(r"NEVER_MATCH", "red") assert count == 0 assert len(test._spans) == 0 # text: peek-a-boo # indx: 0123456789 count = test.highlight_regex(r"[a|e|o]+", "red") assert count == 3 assert sorted(test._spans) == [ Span(1, 3, "red"), Span(5, 6, "red"), Span(8, 10, "red"), ] test = Text("Ada Lovelace, Alan Turing") count = test.highlight_regex( r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*" ) # The number of matched name should be 2 assert count == 2 assert sorted(test._spans) == [ Span(0, 3, "yellow"), # Ada Span(4, 12, "red"), # Lovelace Span(14, 18, "yellow"), # Alan Span(19, 25, "red"), # Turing ]
def test_wrap_4(): test = Text("foo bar baz", justify="left") lines = test.wrap(Console(), 4) assert len(lines) == 3 assert lines[0] == Text("foo ") assert lines[1] == Text("bar ") assert lines[2] == Text("baz ")
def walk_directory(directory: pathlib.Path, tree: Tree) -> None: """Recursively build a Tree with directory contents.""" # Sort dirs first then by filename paths = sorted( pathlib.Path(directory).iterdir(), key=lambda path: (path.is_file(), path.name.lower()), ) for path in paths: # Remove hidden files if path.name.startswith("."): continue if path.is_dir(): style = "dim" if path.name.startswith("__") else "" branch = tree.add( f"[bold magenta]:open_file_folder: [link file://{path}]{escape(path.name)}", style=style, guide_style=style, ) walk_directory(path, branch) else: text_filename = Text(path.name, "green") text_filename.highlight_regex(r"\..*$", "bold red") text_filename.stylize(f"link file://{path}") file_size = path.stat().st_size text_filename.append(f" ({decimal(file_size)})", "blue") icon = "🐍 " if path.suffix == ".py" else "📄 " tree.add(Text(icon) + text_filename)
def test_wrap_overflow(): test = Text("Some more words") lines = test.wrap(Console(), 4, overflow="ellipsis") assert (len(lines)) == 3 assert lines[0] == Text("Some") assert lines[1] == Text("more") assert lines[2] == Text("wor…")
def test_wrap_3(): test = Text("foo bar baz") lines = test.wrap(Console(), 3) print(repr(lines)) assert len(lines) == 3 assert lines[0] == Text("foo") assert lines[1] == Text("bar") assert lines[2] == Text("baz")
def test_wrap_long_words(): test = Text("X 123456789", justify="left") lines = test.wrap(Console(), 4) assert len(lines) == 3 assert lines[0] == Text("X 12") assert lines[1] == Text("3456") assert lines[2] == Text("789 ")
def _err_too_few_args(self, num): if self.max_args is not None and self.min_args != self.max_args: return Text( f"#-1 FUNCTION ({self.name.upper()}) EXPECTS BETWEEN {self.min_args} AND {self.max_args} ARGUMENTS BUT GOT {num}" ) else: return Text( f"#-1 FUNCTION ({self.name.upper()}) EXPECTS AT LEAST {self.min_args} ARGUMENTS BUT GOT {num}" )
def test_plain_property_setter(): test = Text("foo") test.plain = "bar" assert str(test) == "bar" test = Text() test.append("Hello, World", "bold") test.plain = "Hello" assert str(test) == "Hello" assert test._spans == [Span(0, 5, "bold")]
async def announce_logout(self, from_linkdead: bool = False): if from_linkdead: to_send = Text(" has been idled-out due to link-deadedness!") for neighbor in self.neighbors(): neighbor.msg(neighbor.get_dub_or_keyphrase_for(self) + to_send) else: self.msg(Text("You have left the game.")) to_send = Text(" has left the game!") for neighbor in self.neighbors(): neighbor.msg(neighbor.get_dub_or_keyphrase_for(self) + to_send)
async def do_execute(self): try: result = await self.math_execute() except ValueError as err: return Text(str(err)) except ZeroDivisionError: return Text("#-1 DIVISION BY ZERO") if isinstance(result, float) and int(result) == result: return Text(str(int(result))) else: return Text(str(result))
def from_html(text: Union[Text, str], tag: str, **kwargs) -> Text: mark = ProtoStyle() mark.tag = tag mark.xml_attr = kwargs style = mark.convert() if isinstance(text, Text): spans = [Span(s.start, s.end, s.style + style) for s in text.spans] return Text(text.plain, spans=spans, style=text.style + style) elif isinstance(text, str): spans = [Span(0, len(text), mark.convert())] return Text(text, spans=spans)
async def announce_login(self, from_linkdead: bool = False): if from_linkdead: self.msg(Text("You return from link-dead!")) to_send = Text(" is no longer link-dead!") for neighbor in self.neighbors(): neighbor.msg(neighbor.get_dub_or_keyphrase_for(self) + to_send) else: self.msg(Text("You have entered the game.")) to_send = Text(" has entered the game!") for neighbor in self.neighbors(): neighbor.msg(neighbor.get_dub_or_keyphrase_for(self) + to_send)
async def api_request(self, request: AttributeRequest): if not self.api_access(request): request.error = Text("PERMISSION DENIED FOR ATTRIBUTES") return if request.req_type == AttributeRequestType.SET: self.api_set(request) elif request.req_type == AttributeRequestType.GET: self.api_get(request) else: request.error = Text("Malformed API request!")
def test_append(): test = Text("foo") test.append("bar") assert str(test) == "foobar" test.append(Text("baz", "bold")) assert str(test) == "foobarbaz" assert test._spans == [Span(6, 9, "bold")] with pytest.raises(ValueError): test.append(Text("foo"), "bar") with pytest.raises(TypeError): test.append(1)
def test_detect_indentation(): test = """\ foo bar """ assert Text(test).detect_indentation() == 4 test = """\ foo bar baz """ assert Text(test).detect_indentation() == 2 assert Text("").detect_indentation() == 1 assert Text(" ").detect_indentation() == 1
def make_filename_text(filename): path = os.path.abspath(os.path.join(root_path, filename)) text = Text(filename, style="bold blue" if os.path.isdir(path) else "default") text.stylize(f"link file://{path}") text.highlight_regex(r"\..*?$", "bold") return text
def test_tabs_to_spaces(): test = Text("\tHello\tWorld", tab_size=8) test.expand_tabs() assert test.plain == " Hello World" test = Text("\tHello\tWorld", tab_size=4) test.expand_tabs() assert test.plain == " Hello World" test = Text(".\t..\t...\t....\t", tab_size=4) test.expand_tabs() assert test.plain == ". .. ... .... " test = Text("No Tabs") test.expand_tabs() assert test.plain == "No Tabs"
def split_args(self): escaped = False text = self.args_data plain = text.plain paren_depth = 0 i = 0 segment_start = i while i < len(plain): if escaped: escaped = False continue else: c = plain[i] if c == "\\": escaped = True elif c == "(": paren_depth += 1 elif c == ")" and paren_depth: paren_depth -= 1 elif c == "," and not paren_depth: self.args_count += 1 self.args.append(text[segment_start:i]) segment_start = i + 1 i += 1 if i > segment_start: self.args.append(text[segment_start:i]) total = len(self.args) diff = self.args_count - total if diff: for _ in range(diff): self.args.append(Text(""))
def test_highlight_regex(test: str, spans: List[Span]): """Tests for the regular expressions used in ReprHighlighter.""" text = Text(test) highlighter = ReprHighlighter() highlighter.highlight(text) print(text.spans) assert text.spans == spans
def test_rich() -> None: color = Color.parse("red") as_text = color.__rich__() print(repr(as_text)) print(repr(as_text.spans)) assert as_text == Text("<color 'red' (standard)⬤ >", spans=[Span(23, 24, Style(color=color))])
def test_split_spans(): test = Text.from_markup("[red]Hello\n[b]World") lines = test.split("\n") assert lines[0].plain == "Hello" assert lines[1].plain == "World" assert lines[0].spans == [Span(0, 5, "red")] assert lines[1].spans == [Span(0, 5, "red"), Span(0, 5, "bold")]
def test_copy(): test = Text() test.append("Hello", "bold") test.append(" ") test.append("World", "italic") test_copy = test.copy() assert test == test_copy assert test is not test_copy
def test_render(): console = Console(width=15, record=True) test = Text.from_markup( "[u][b]Where[/b] there is a [i]Will[/i], there is a Way.[/u]") console.print(test) output = console.export_text(styles=True) expected = "\x1b[1;4mWhere\x1b[0m\x1b[4m there is \x1b[0m\n\x1b[4ma \x1b[0m\x1b[3;4mWill\x1b[0m\x1b[4m, there \x1b[0m\n\x1b[4mis a Way.\x1b[0m\n" assert output == expected
def test_width_of_none(): console = Console() constrain = Constrain(Text("foo"), width=None) min_width, max_width = constrain.__rich_measure__( console, console.options.update_width(80) ) assert min_width == 3 assert max_width == 3
def test_split(): test = Text() test.append("foo", "red") test.append("\n") test.append("bar", "green") test.append("\n") line1 = Text() line1.append("foo", "red") line2 = Text() line2.append("bar", "green") split = test.split("\n") assert len(split) == 2 assert split[0] == line1 assert split[1] == line2 assert list(Text("foo").split("\n")) == [Text("foo")]