Debian Codegraph @

tests/test_text.py

raw
1 import re
2 from io import StringIO
3 from typing import List
4
5 import pytest
6
7 from rich.console import Console, Group
8 from rich.measure import Measurement
9 from rich.style import Style
10 from rich.text import Span, Text
11
12
13 def test_span():
14 span = Span(1, 10, "foo")
15 repr(span)
16 assert bool(span)
17 assert not Span(10, 10, "foo")
18
19
20 def test_span_split():
21 assert Span(5, 10, "foo").split(2) == (Span(5, 10, "foo"), None)
22 assert Span(5, 10, "foo").split(15) == (Span(5, 10, "foo"), None)
23 assert Span(0, 10, "foo").split(5) == (Span(0, 5, "foo"), Span(5, 10, "foo"))
24
25
26 def test_span_move():
27 assert Span(5, 10, "foo").move(2) == Span(7, 12, "foo")
28
29
30 def test_span_right_crop():
31 assert Span(5, 10, "foo").right_crop(15) == Span(5, 10, "foo")
32 assert Span(5, 10, "foo").right_crop(7) == Span(5, 7, "foo")
33
34
35 def test_len():
36 assert len(Text("foo")) == 3
37
38
39 def test_cell_len():
40 assert Text("foo").cell_len == 3
41 assert Text("πŸ˜€").cell_len == 2
42
43
44 def test_bool():
45 assert Text("foo")
46 assert not Text("")
47
48
49 def test_str():
50 assert str(Text("foo")) == "foo"
51
52
53 def test_repr():
54 assert isinstance(repr(Text("foo")), str)
55
56
57 def test_add():
58 text = Text("foo") + Text("bar")
59 assert str(text) == "foobar"
60 assert Text("foo").__add__(1) == NotImplemented
61
62
63 def test_eq():
64 assert Text("foo") == Text("foo")
65 assert Text("foo") != Text("bar")
66 assert Text("foo").__eq__(1) == NotImplemented
67
68
69 def test_contain():
70 text = Text("foobar")
71 assert "foo" in text
72 assert "foo " not in text
73 assert Text("bar") in text
74 assert None not in text
75
76
77 def test_plain_property():
78 text = Text("foo")
79 text.append("bar")
80 text.append("baz")
81 assert text.plain == "foobarbaz"
82
83
84 def test_plain_property_setter():
85 text = Text("foo")
86 text.plain = "bar"
87 assert str(text) == "bar"
88 text = Text()
89 text.append("Hello, World", "bold")
90 text.plain = "Hello"
91 assert str(text) == "Hello"
92 assert text._spans == [Span(0, 5, "bold")]
93
94
95 def test_from_markup():
96 text = Text.from_markup("Hello, [bold]World![/bold]")
97 assert str(text) == "Hello, World!"
98 assert text._spans == [Span(7, 13, "bold")]
99
100
101 def test_from_ansi():
102 text = Text.from_ansi("Hello, \033[1mWorld!\033[0m")
103 assert str(text) == "Hello, World!"
104 assert text._spans == [Span(7, 13, Style(bold=True))]
105
106 text = Text.from_ansi("Hello, \033[1m\nWorld!\033[0m")
107 assert str(text) == "Hello, \nWorld!"
108 assert text._spans == [Span(8, 14, Style(bold=True))]
109
110 text = Text.from_ansi("\033[1mBOLD\033[m not bold")
111 assert str(text) == "BOLD not bold"
112 assert text._spans == [Span(0, 4, Style(bold=True))]
113
114 text = Text.from_ansi("\033[1m\033[Kfoo barmbaz")
115 assert str(text) == "foo barmbaz"
116 assert text._spans == [Span(0, 11, Style(bold=True))]
117
118
119 def test_copy():
120 text = Text()
121 text.append("Hello", "bold")
122 text.append(" ")
123 text.append("World", "italic")
124 test_copy = text.copy()
125 assert text == test_copy
126 assert text is not test_copy
127
128
129 def test_rstrip():
130 text = Text("Hello, World! ")
131 text.rstrip()
132 assert str(text) == "Hello, World!"
133
134
135 def test_rstrip_end():
136 text = Text("Hello, World! ")
137 text.rstrip_end(14)
138 assert str(text) == "Hello, World! "
139
140
141 def test_stylize():
142 text = Text("Hello, World!")
143 text.stylize("bold", 7, 11)
144 assert text._spans == [Span(7, 11, "bold")]
145 text.stylize("bold", 20, 25)
146 assert text._spans == [Span(7, 11, "bold")]
147
148
149 def test_stylize_before():
150 text = Text("Hello, World!")
151 text.stylize("bold", 0, 5)
152 text.stylize_before("italic", 2, 7)
153 assert text._spans == [Span(2, 7, "italic"), Span(0, 5, "bold")]
154
155
156 def test_stylize_negative_index():
157 text = Text("Hello, World!")
158 text.stylize("bold", -6, -1)
159 assert text._spans == [Span(7, 12, "bold")]
160
161
162 def test_highlight_regex():
163 # As a string
164 text = Text("peek-a-boo")
165
166 count = text.highlight_regex(r"NEVER_MATCH", "red")
167 assert count == 0
168 assert len(text._spans) == 0
169
170 # text: peek-a-boo
171 # indx: 0123456789
172 count = text.highlight_regex(r"[a|e|o]+", "red")
173 assert count == 3
174 assert sorted(text._spans) == [
175 Span(1, 3, "red"),
176 Span(5, 6, "red"),
177 Span(8, 10, "red"),
178 ]
179
180 text = Text("Ada Lovelace, Alan Turing")
181
182 count = text.highlight_regex(
183 r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*"
184 )
185
186 # The number of matched name should be 2
187 assert count == 2
188 assert sorted(text._spans) == [
189 Span(0, 3, "yellow"), # Ada
190 Span(4, 12, "red"), # Lovelace
191 Span(14, 18, "yellow"), # Alan
192 Span(19, 25, "red"), # Turing
193 ]
194
195 # As a regular expression object
196 text = Text("peek-a-boo")
197
198 count = text.highlight_regex(re.compile(r"NEVER_MATCH"), "red")
199 assert count == 0
200 assert len(text._spans) == 0
201
202 # text: peek-a-boo
203 # indx: 0123456789
204 count = text.highlight_regex(re.compile(r"[a|e|o]+"), "red")
205 assert count == 3
206 assert sorted(text._spans) == [
207 Span(1, 3, "red"),
208 Span(5, 6, "red"),
209 Span(8, 10, "red"),
210 ]
211
212 text = Text("Ada Lovelace, Alan Turing")
213
214 count = text.highlight_regex(
215 re.compile(
216 r"(?P<yellow>[A-Za-z]+)[ ]+(?P<red>[A-Za-z]+)(?P<NEVER_MATCH>NEVER_MATCH)*"
217 )
218 )
219
220 # The number of matched name should be 2
221 assert count == 2
222 assert sorted(text._spans) == [
223 Span(0, 3, "yellow"), # Ada
224 Span(4, 12, "red"), # Lovelace
225 Span(14, 18, "yellow"), # Alan
226 Span(19, 25, "red"), # Turing
227 ]
228
229
230 def test_highlight_regex_callable():
231 text = Text("Vulnerability CVE-2018-6543 detected")
232 re_cve = r"CVE-\d{4}-\d+"
233 compiled_re_cve = re.compile(r"CVE-\d{4}-\d+")
234
235 def get_style(text: str) -> Style:
236 return Style.parse(
237 f"bold yellow link https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={text}"
238 )
239
240 # string
241 count = text.highlight_regex(re_cve, get_style)
242 assert count == 1
243 assert len(text._spans) == 1
244 assert text._spans[0].start == 14
245 assert text._spans[0].end == 27
246 assert (
247 text._spans[0].style.link
248 == "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543"
249 )
250
251 # Clear the tracked _spans for the regular expression object's use
252 text._spans.clear()
253
254 # regular expression object
255 count = text.highlight_regex(compiled_re_cve, get_style)
256 assert count == 1
257 assert len(text._spans) == 1
258 assert text._spans[0].start == 14
259 assert text._spans[0].end == 27
260 assert (
261 text._spans[0].style.link
262 == "https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword=CVE-2018-6543"
263 )
264
265
266 def test_highlight_words():
267 text = Text("Do NOT! touch anything!")
268 words = ["NOT", "!"]
269 count = text.highlight_words(words, "red")
270 assert count == 3
271 assert sorted(text._spans) == [
272 Span(3, 6, "red"), # NOT
273 Span(6, 7, "red"), # !
274 Span(22, 23, "red"), # !
275 ]
276
277 # regex escape test
278 text = Text("[o|u]aeiou")
279 words = ["[a|e|i]", "[o|u]"]
280 count = text.highlight_words(words, "red")
281 assert count == 1
282 assert text._spans == [Span(0, 5, "red")]
283
284 # case sensitive
285 text = Text("AB Ab aB ab")
286 words = ["AB"]
287
288 count = text.highlight_words(words, "red")
289 assert count == 1
290 assert text._spans == [Span(0, 2, "red")]
291
292 text = Text("AB Ab aB ab")
293 count = text.highlight_words(words, "red", case_sensitive=False)
294 assert count == 4
295
296
297 def test_set_length():
298 text = Text("Hello")
299 text.set_length(5)
300 assert text == Text("Hello")
301
302 text = Text("Hello")
303 text.set_length(10)
304 assert text == Text("Hello ")
305
306 text = Text("Hello World")
307 text.stylize("bold", 0, 5)
308 text.stylize("italic", 7, 9)
309
310 text.set_length(3)
311 expected = Text()
312 expected.append("Hel", "bold")
313 assert text == expected
314
315
316 def test_console_width():
317 console = Console()
318 text = Text("Hello World!\nfoobarbaz")
319 assert text.__rich_measure__(console, 80) == Measurement(9, 12)
320 assert Text(" " * 4).__rich_measure__(console, 80) == Measurement(4, 4)
321 assert Text(" \n \n ").__rich_measure__(console, 80) == Measurement(3, 3)
322
323
324 def test_join():
325 text = Text("bar").join([Text("foo", "red"), Text("baz", "blue")])
326 assert str(text) == "foobarbaz"
327 assert text._spans == [Span(0, 3, "red"), Span(6, 9, "blue")]
328
329
330 def test_trim_spans():
331 text = Text("Hello")
332 text._spans[:] = [Span(0, 3, "red"), Span(3, 6, "green"), Span(6, 9, "blue")]
333 text._trim_spans()
334 assert text._spans == [Span(0, 3, "red"), Span(3, 5, "green")]
335
336
337 def test_pad_left():
338 text = Text("foo")
339 text.pad_left(3, "X")
340 assert str(text) == "XXXfoo"
341
342
343 def test_pad_right():
344 text = Text("foo")
345 text.pad_right(3, "X")
346 assert str(text) == "fooXXX"
347
348
349 def test_append():
350 text = Text("foo")
351 text.append("bar")
352 assert str(text) == "foobar"
353 text.append(Text("baz", "bold"))
354 assert str(text) == "foobarbaz"
355 assert text._spans == [Span(6, 9, "bold")]
356
357 with pytest.raises(ValueError):
358 text.append(Text("foo"), "bar")
359
360 with pytest.raises(TypeError):
361 text.append(1)
362
363
364 def test_append_text():
365 text = Text("foo")
366 text.append_text(Text("bar", style="bold"))
367 assert str(text) == "foobar"
368 assert text._spans == [Span(3, 6, "bold")]
369
370
371 def test_end():
372 console = Console(width=20, file=StringIO())
373 text = Group(Text.from_markup("foo", end=" "), Text.from_markup("bar"))
374 console.print(text)
375 assert console.file.getvalue() == "foo bar\n"
376
377
378 def test_split():
379 text = Text()
380 text.append("foo", "red")
381 text.append("\n")
382 text.append("bar", "green")
383 text.append("\n")
384
385 line1 = Text()
386 line1.append("foo", "red")
387 line2 = Text()
388 line2.append("bar", "green")
389 split = text.split("\n")
390 assert len(split) == 2
391 assert split[0] == line1
392 assert split[1] == line2
393
394 assert list(Text("foo").split("\n")) == [Text("foo")]
395
396
397 def test_split_spans():
398 text = Text.from_markup("[red]Hello\n[b]World")
399 lines = text.split("\n")
400 assert lines[0].plain == "Hello"
401 assert lines[1].plain == "World"
402 assert lines[0].spans == [Span(0, 5, "red")]
403 assert lines[1].spans == [Span(0, 5, "red"), Span(0, 5, "bold")]
404
405
406 def test_divide():
407 lines = Text("foo").divide([])
408 assert len(lines) == 1
409 assert lines[0] == Text("foo")
410
411 text = Text()
412 text.append("foo", "bold")
413 lines = text.divide([1, 2])
414 assert len(lines) == 3
415 assert str(lines[0]) == "f"
416 assert str(lines[1]) == "o"
417 assert str(lines[2]) == "o"
418 assert lines[0]._spans == [Span(0, 1, "bold")]
419 assert lines[1]._spans == [Span(0, 1, "bold")]
420 assert lines[2]._spans == [Span(0, 1, "bold")]
421
422 text = Text()
423 text.append("foo", "red")
424 text.append("bar", "green")
425 text.append("baz", "blue")
426 lines = text.divide([8])
427 assert len(lines) == 2
428 assert str(lines[0]) == "foobarba"
429 assert str(lines[1]) == "z"
430 assert lines[0]._spans == [
431 Span(0, 3, "red"),
432 Span(3, 6, "green"),
433 Span(6, 8, "blue"),
434 ]
435 assert lines[1]._spans == [Span(0, 1, "blue")]
436
437 lines = text.divide([1])
438 assert len(lines) == 2
439 assert str(lines[0]) == "f"
440 assert str(lines[1]) == "oobarbaz"
441 assert lines[0]._spans == [Span(0, 1, "red")]
442 assert lines[1]._spans == [
443 Span(0, 2, "red"),
444 Span(2, 5, "green"),
445 Span(5, 8, "blue"),
446 ]
447
448
449 def test_right_crop():
450 text = Text()
451 text.append("foobar", "red")
452 text.right_crop(3)
453 assert str(text) == "foo"
454 assert text._spans == [Span(0, 3, "red")]
455
456
457 def test_wrap_3():
458 text = Text("foo bar baz")
459 lines = text.wrap(Console(), 3)
460 print(repr(lines))
461 assert len(lines) == 3
462 assert lines[0] == Text("foo")
463 assert lines[1] == Text("bar")
464 assert lines[2] == Text("baz")
465
466
467 def test_wrap_4():
468 text = Text("foo bar baz", justify="left")
469 lines = text.wrap(Console(), 4)
470 assert len(lines) == 3
471 assert lines[0] == Text("foo ")
472 assert lines[1] == Text("bar ")
473 assert lines[2] == Text("baz ")
474
475
476 def test_wrap_wrapped_word_length_greater_than_available_width():
477 text = Text("1234 12345678")
478 lines = text.wrap(Console(), 7)
479 assert lines._lines == [
480 Text("1234 "),
481 Text("1234567"),
482 Text("8"),
483 ]
484
485
486 def test_wrap_cjk():
487 text = Text("わさび")
488 lines = text.wrap(Console(), 4)
489 assert lines._lines == [
490 Text("わさ"),
491 Text("び"),
492 ]
493
494
495 def test_wrap_cjk_width_mid_character():
496 text = Text("わさび")
497 lines = text.wrap(Console(), 3)
498 assert lines._lines == [
499 Text("わ"),
500 Text("さ"),
501 Text("び"),
502 ]
503
504
505 def test_wrap_cjk_mixed():
506 """Regression test covering https://github.com/Textualize/rich/issues/3176 and
507 https://github.com/Textualize/textual/issues/3567 - double width characters could
508 result in text going missing when wrapping."""
509 text = Text("123γ‚γ‚ŠγŒγ¨γ†γ”γ–γ„γΎγ—γŸ")
510 console = Console(width=20) # let's ensure the width passed to wrap() wins.
511
512 wrapped_lines = text.wrap(console, width=8)
513 with console.capture() as capture:
514 console.print(wrapped_lines)
515
516 assert capture.get() == "123γ‚γ‚Š\nγŒγ¨γ†γ”\nざいまし\nた\n"
517
518
519 def test_wrap_long():
520 text = Text("abracadabra", justify="left")
521 lines = text.wrap(Console(), 4)
522 assert len(lines) == 3
523 assert lines[0] == Text("abra")
524 assert lines[1] == Text("cada")
525 assert lines[2] == Text("bra ")
526
527
528 def test_wrap_long_multi_codepoint():
529 female_mechanic = "πŸ‘©\u200dπŸ”§"
530 text = Text(female_mechanic * 5, justify="left")
531 lines = text.wrap(Console(), 4)
532 assert len(lines) == 3
533 assert lines[0] == Text(female_mechanic * 2)
534 assert lines[1] == Text(female_mechanic * 2)
535 assert lines[2] == Text(female_mechanic + " ")
536
537
538 def test_wrap_overflow():
539 text = Text("Some more words")
540 lines = text.wrap(Console(), 4, overflow="ellipsis")
541 assert (len(lines)) == 3
542 assert lines[0] == Text("Some")
543 assert lines[1] == Text("more")
544 assert lines[2] == Text("wor…")
545
546
547 def test_wrap_overflow_long():
548 text = Text("bigword" * 10)
549 lines = text.wrap(Console(), 4, overflow="ellipsis")
550 assert len(lines) == 1
551 assert lines[0] == Text("big…")
552
553
554 def test_wrap_long_words():
555 text = Text("XX 12345678912")
556 lines = text.wrap(Console(), 4)
557
558 assert lines._lines == [
559 Text("XX "),
560 Text("1234"),
561 Text("5678"),
562 Text("912"),
563 ]
564
565
566 def test_wrap_long_words_2():
567 # https://github.com/Textualize/rich/issues/2273
568 text = Text("Hello, World...123")
569 lines = text.wrap(Console(), 10)
570 assert lines._lines == [
571 Text("Hello, "),
572 Text("World...12"),
573 Text("3"),
574 ]
575
576
577 def test_wrap_long_words_followed_by_other_words():
578 """After folding a word across multiple lines, we should continue from
579 the next word immediately after the folded word (don't take a newline
580 following completion of the folded word)."""
581 text = Text("123 12345678 123 123")
582 lines = text.wrap(Console(), 6)
583 assert lines._lines == [
584 Text("123 "),
585 Text("123456"),
586 Text("78 123"),
587 Text("123"),
588 ]
589
590
591 def test_wrap_long_word_preceeded_by_word_of_full_line_length():
592 """The width of the first word is the same as the available width.
593 Ensures that folding works correctly when there's no space available
594 on the current line."""
595 text = Text("123456 12345678 123 123")
596 lines = text.wrap(Console(), 6)
597 assert lines._lines == [
598 Text("123456"),
599 Text("123456"),
600 Text("78 123"),
601 Text("123"),
602 ]
603
604
605 def test_wrap_multiple_consecutive_spaces():
606 """Adding multiple consecutive spaces at the end of a line does not impact
607 the location at which a break will be added during the process of wrapping."""
608 text = Text("123456 12345678 123 123")
609 lines = text.wrap(Console(), 6)
610 assert lines._lines == [
611 Text("123456"),
612 Text("123456"),
613 Text("78 123"),
614 Text("123"),
615 ]
616
617
618 def test_wrap_multi_codepoint():
619 """Test wrapping of multi-codepoint characters."""
620 female_mechanic = "πŸ‘©\u200dπŸ”§"
621 text = Text(female_mechanic * 6 + " " + female_mechanic * 4)
622 lines = text.wrap(Console(), 12)
623 print(repr(lines))
624 assert lines._lines == [
625 Text(female_mechanic * 6),
626 Text(female_mechanic * 4),
627 ]
628
629
630 def test_wrap_long_words_justify_left():
631 text = Text("X 123456789", justify="left")
632 lines = text.wrap(Console(), 4)
633
634 assert len(lines) == 4
635 assert lines[0] == Text("X ")
636 assert lines[1] == Text("1234")
637 assert lines[2] == Text("5678")
638 assert lines[3] == Text("9 ")
639
640
641 def test_wrap_leading_and_trailing_whitespace():
642 text = Text(" 123 456 789 ")
643 lines = text.wrap(Console(), 4)
644 assert lines._lines == [
645 Text(" 1"),
646 Text("23 "),
647 Text("456 "),
648 Text("789 "),
649 ]
650
651
652 def test_no_wrap_no_crop():
653 text = Text("Hello World!" * 3)
654
655 console = Console(width=20, file=StringIO())
656 console.print(text, no_wrap=True)
657 console.print(text, no_wrap=True, crop=False, overflow="ignore")
658
659 print(repr(console.file.getvalue()))
660 assert (
661 console.file.getvalue()
662 == "Hello World!Hello Wo\nHello World!Hello World!Hello World!\n"
663 )
664
665
666 def test_fit():
667 text = Text("Hello\nWorld")
668 lines = text.fit(3)
669 assert str(lines[0]) == "Hel"
670 assert str(lines[1]) == "Wor"
671
672
673 def test_wrap_tabs():
674 text = Text("foo\tbar", justify="left")
675 lines = text.wrap(Console(), 4)
676 assert len(lines) == 2
677 assert str(lines[0]) == "foo "
678 assert str(lines[1]) == "bar "
679
680
681 def test_render():
682 console = Console(width=15, record=True)
683 text = Text.from_markup(
684 "[u][b]Where[/b] there is a [i]Will[/i], there is a Way.[/u]"
685 )
686 console.print(text)
687 output = console.export_text(styles=True)
688 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"
689 assert output == expected
690
691
692 def test_render_simple():
693 console = Console(width=80)
694 console.begin_capture()
695 console.print(Text("foo"))
696 result = console.end_capture()
697 assert result == "foo\n"
698
699
700 @pytest.mark.parametrize(
701 "print_text,result",
702 [
703 (("."), ".\n"),
704 ((".", "."), ". .\n"),
705 (("Hello", "World", "!"), "Hello World !\n"),
706 ],
707 )
708 def test_print(print_text, result):
709 console = Console(record=True)
710 console.print(*print_text)
711 assert console.export_text(styles=False) == result
712
713
714 @pytest.mark.parametrize(
715 "print_text,result",
716 [
717 (("."), ".X"),
718 ((".", "."), "..X"),
719 (("Hello", "World", "!"), "HelloWorld!X"),
720 ],
721 )
722 def test_print_sep_end(print_text, result):
723 console = Console(record=True, file=StringIO())
724 console.print(*print_text, sep="", end="X")
725 assert console.file.getvalue() == result
726
727
728 def test_tabs_to_spaces():
729 text = Text("\tHello\tWorld", tab_size=8)
730 text.expand_tabs()
731 assert text.plain == " Hello World"
732
733 text = Text("\tHello\tWorld", tab_size=4)
734 text.expand_tabs()
735 assert text.plain == " Hello World"
736
737 text = Text(".\t..\t...\t....\t", tab_size=4)
738 text.expand_tabs()
739 assert text.plain == ". .. ... .... "
740
741 text = Text("No Tabs")
742 text.expand_tabs()
743 assert text.plain == "No Tabs"
744
745 text = Text("No Tabs", style="bold")
746 text.expand_tabs()
747 assert text.plain == "No Tabs"
748 assert text.style == "bold"
749
750
751 @pytest.mark.parametrize(
752 "markup,tab_size,expected_text,expected_spans",
753 [
754 ("", 4, "", []),
755 ("\t", 4, " ", []),
756 ("\tbar", 4, " bar", []),
757 ("foo\tbar", 4, "foo bar", []),
758 ("foo\nbar\nbaz", 4, "foo\nbar\nbaz", []),
759 (
760 "[bold]foo\tbar",
761 4,
762 "foo bar",
763 [
764 Span(0, 4, "bold"),
765 Span(4, 7, "bold"),
766 ],
767 ),
768 (
769 "[bold]\tbar",
770 4,
771 " bar",
772 [
773 Span(0, 4, "bold"),
774 Span(4, 7, "bold"),
775 ],
776 ),
777 (
778 "\t[bold]bar",
779 4,
780 " bar",
781 [
782 Span(4, 7, "bold"),
783 ],
784 ),
785 (
786 "[red]foo\tbar\n[green]egg\tbaz",
787 8,
788 "foo bar\negg baz",
789 [
790 Span(0, 8, "red"),
791 Span(8, 12, "red"),
792 Span(12, 20, "red"),
793 Span(12, 20, "green"),
794 Span(20, 23, "red"),
795 Span(20, 23, "green"),
796 ],
797 ),
798 (
799 "[bold]X\tY",
800 8,
801 "X Y",
802 [
803 Span(0, 8, "bold"),
804 Span(8, 9, "bold"),
805 ],
806 ),
807 (
808 "[bold]πŸ’©\tπŸ’©",
809 8,
810 "πŸ’© πŸ’©",
811 [
812 Span(0, 7, "bold"),
813 Span(7, 8, "bold"),
814 ],
815 ),
816 (
817 "[bold]πŸ’©πŸ’©πŸ’©πŸ’©\tπŸ’©",
818 8,
819 "πŸ’©πŸ’©πŸ’©πŸ’© πŸ’©",
820 [
821 Span(0, 12, "bold"),
822 Span(12, 13, "bold"),
823 ],
824 ),
825 ],
826 )
827 def test_tabs_to_spaces_spans(
828 markup: str, tab_size: int, expected_text: str, expected_spans: List[Span]
829 ):
830 """Test spans are correct after expand_tabs"""
831 text = Text.from_markup(markup)
832 text.expand_tabs(tab_size)
833 print(text._spans)
834 assert text.plain == expected_text
835 assert text._spans == expected_spans
836
837
838 def test_markup_switch():
839 """Test markup can be disabled."""
840 console = Console(file=StringIO(), markup=False)
841 console.print("[bold]foo[/bold]")
842 assert console.file.getvalue() == "[bold]foo[/bold]\n"
843
844
845 def test_emoji():
846 """Test printing emoji codes."""
847 console = Console(file=StringIO())
848 console.print(":+1:")
849 assert console.file.getvalue() == "πŸ‘\n"
850
851
852 def test_emoji_switch():
853 """Test emoji can be disabled."""
854 console = Console(file=StringIO(), emoji=False)
855 console.print(":+1:")
856 assert console.file.getvalue() == ":+1:\n"
857
858
859 def test_assemble():
860 text = Text.assemble("foo", ("bar", "bold"))
861 assert str(text) == "foobar"
862 assert text._spans == [Span(3, 6, "bold")]
863
864
865 def test_assemble_meta():
866 text = Text.assemble("foo", ("bar", "bold"), meta={"foo": "bar"})
867 assert str(text) == "foobar"
868
869 spans = text._spans
870 expected = [Span(3, 6, "bold"), Span(0, 6, Style(meta={"foo": "bar"}))]
871
872 assert spans == expected
873
874 console = Console()
875 assert text.get_style_at_offset(console, 0).meta == {"foo": "bar"}
876
877
878 def test_styled():
879 text = Text.styled("foo", "bold red")
880 assert text.style == ""
881 assert str(text) == "foo"
882 assert text._spans == [Span(0, 3, "bold red")]
883
884
885 def test_strip_control_codes():
886 text = Text("foo\rbar")
887 assert str(text) == "foobar"
888 text.append("\x08")
889 assert str(text) == "foobar"
890
891
892 def test_get_style_at_offset():
893 console = Console()
894 text = Text.from_markup("Hello [b]World[/b]")
895 assert text.get_style_at_offset(console, 0) == Style()
896 assert text.get_style_at_offset(console, 6) == Style(bold=True)
897
898
899 @pytest.mark.parametrize(
900 "input, count, expected",
901 [
902 ("Hello", 10, "Hello"),
903 ("Hello", 5, "Hello"),
904 ("Hello", 4, "Hel…"),
905 ("Hello", 3, "He…"),
906 ("Hello", 2, "H…"),
907 ("Hello", 1, "…"),
908 ],
909 )
910 def test_truncate_ellipsis(input, count, expected):
911 text = Text(input)
912 text.truncate(count, overflow="ellipsis")
913 assert text.plain == expected
914
915
916 @pytest.mark.parametrize(
917 "input, count, expected",
918 [
919 ("Hello", 5, "Hello"),
920 ("Hello", 10, "Hello "),
921 ("Hello", 3, "He…"),
922 ],
923 )
924 def test_truncate_ellipsis_pad(input, count, expected):
925 text = Text(input)
926 text.truncate(count, overflow="ellipsis", pad=True)
927 assert text.plain == expected
928
929
930 def test_pad():
931 text = Text("foo")
932 text.pad(2)
933 assert text.plain == " foo "
934
935
936 def test_align_left():
937 text = Text("foo")
938 text.align("left", 10)
939 assert text.plain == "foo "
940
941
942 def test_align_right():
943 text = Text("foo")
944 text.align("right", 10)
945 assert text.plain == " foo"
946
947
948 def test_align_center():
949 text = Text("foo")
950 text.align("center", 10)
951 assert text.plain == " foo "
952
953
954 def test_detect_indentation():
955 text = """\
956 foo
957 bar
958 """
959 assert Text(text).detect_indentation() == 4
960 text = """\
961 foo
962 bar
963 baz
964 """
965 assert Text(text).detect_indentation() == 2
966 assert Text("").detect_indentation() == 1
967 assert Text(" ").detect_indentation() == 1
968
969
970 def test_indentation_guides():
971 text = Text(
972 """\
973 for a in range(10):
974 print(a)
975
976 foo = [
977 1,
978 {
979 2
980 }
981 ]
982
983 """
984 )
985 result = text.with_indent_guides()
986 print(result.plain)
987 print(repr(result.plain))
988 expected = "for a in range(10):\nβ”‚ print(a)\n\nfoo = [\nβ”‚ 1,\nβ”‚ {\nβ”‚ β”‚ 2\nβ”‚ }\n]\n\n"
989 assert result.plain == expected
990
991
992 def test_slice():
993 text = Text.from_markup("[red]foo [bold]bar[/red] baz[/bold]")
994 assert text[0] == Text("f", spans=[Span(0, 1, "red")])
995 assert text[4] == Text("b", spans=[Span(0, 1, "red"), Span(0, 1, "bold")])
996
997 assert text[:3] == Text("foo", spans=[Span(0, 3, "red")])
998 assert text[:4] == Text("foo ", spans=[Span(0, 4, "red")])
999 assert text[:5] == Text("foo b", spans=[Span(0, 5, "red"), Span(4, 5, "bold")])
1000 assert text[4:] == Text("bar baz", spans=[Span(0, 3, "red"), Span(0, 7, "bold")])
1001
1002 with pytest.raises(TypeError):
1003 text[::-1]
1004
1005
1006 def test_wrap_invalid_style():
1007 # https://github.com/textualize/rich/issues/987
1008 console = Console(width=100, color_system="truecolor")
1009 a = "[#######.................] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx [#######.................]"
1010 console.print(a, justify="full")
1011
1012
1013 def test_apply_meta():
1014 text = Text("foobar")
1015 text.apply_meta({"foo": "bar"}, 1, 3)
1016
1017 console = Console()
1018 assert text.get_style_at_offset(console, 0).meta == {}
1019 assert text.get_style_at_offset(console, 1).meta == {"foo": "bar"}
1020 assert text.get_style_at_offset(console, 2).meta == {"foo": "bar"}
1021 assert text.get_style_at_offset(console, 3).meta == {}
1022
1023
1024 def test_on():
1025 console = Console()
1026 text = Text("foo")
1027 text.on({"foo": "bar"}, click="CLICK")
1028 expected = {"foo": "bar", "@click": "CLICK"}
1029 assert text.get_style_at_offset(console, 0).meta == expected
1030 assert text.get_style_at_offset(console, 1).meta == expected
1031 assert text.get_style_at_offset(console, 2).meta == expected
1032
1033
1034 def test_markup_property():
1035 assert Text("").markup == ""
1036 assert Text("foo").markup == "foo"
1037 assert Text("foo", style="bold").markup == "[bold]foo[/bold]"
1038 assert Text.from_markup("foo [red]bar[/red]").markup == "foo [red]bar[/red]"
1039 assert (
1040 Text.from_markup("foo [red]bar[/red]", style="bold").markup
1041 == "[bold]foo [red]bar[/red][/bold]"
1042 )
1043 assert (
1044 Text.from_markup("[bold]foo [italic]bar[/bold] baz[/italic]").markup
1045 == "[bold]foo [italic]bar[/bold] baz[/italic]"
1046 )
1047 assert Text("[bold]foo").markup == "\\[bold]foo"
1048
1049
1050 def test_extend_style():
1051 text = Text.from_markup("[red]foo[/red] [bold]bar")
1052 text.extend_style(0)
1053
1054 assert text.plain == "foo bar"
1055 assert text.spans == [Span(0, 3, "red"), Span(4, 7, "bold")]
1056
1057 text.extend_style(-1)
1058 assert text.plain == "foo bar"
1059 assert text.spans == [Span(0, 3, "red"), Span(4, 7, "bold")]
1060
1061 text.extend_style(2)
1062 assert text.plain == "foo bar "
1063 assert text.spans == [Span(0, 3, "red"), Span(4, 9, "bold")]
1064
1065
1066 def test_append_tokens() -> None:
1067 """Regression test for https://github.com/Textualize/rich/issues/3014"""
1068
1069 console = Console()
1070 t = Text().append_tokens(
1071 [
1072 (
1073 "long text that will be wrapped with a control code \r\n",
1074 "red",
1075 ),
1076 ]
1077 )
1078 with console.capture() as capture:
1079 console.print(t, width=40)
1080
1081 output = capture.get()
1082 print(repr(output))
1083 assert output == "long text that will be wrapped with a \ncontrol code \n\n"
1084
1085
1086 def test_append_loop_regression() -> None:
1087 """Regression text for https://github.com/Textualize/rich/issues/3479"""
1088 a = Text("one", "blue")
1089 a.append(a)
1090 assert a.plain == "oneone"
1091
1092 b = Text("two", "blue")
1093 b.append_text(b)
1094 assert b.plain == "twotwo"
1095
1096
1097 def test_soft_wrap() -> None:
1098 """Regression test for https://github.com/Textualize/rich/issues/3841
1099
1100 Soft wrap should not strip trailing whitespace.
1101
1102 """
1103 console = Console(color_system="standard", width=80, force_terminal=True)
1104 text = Text(" Hello World ", style="white on blue")
1105
1106 with console.capture() as capture:
1107 console.print(text, soft_wrap=True)
1108
1109 output = capture.get()
1110 print(repr(output))
1111 expected = "\x1b[37;44m Hello World \x1b[0m\n"
1112 assert output == expected
1113
1114
1115 def test_soft_wrap_styled() -> None:
1116 """Regression test for https://github.com/Textualize/rich/issues/3838
1117
1118 If soft_wrap is True and a style is set, we don't want to style the new lines.
1119 """
1120 console = Console(color_system="standard", width=80, force_terminal=True)
1121 with console.capture() as capture:
1122 console.print("soft wrap is on", style="blue on white", soft_wrap=True)
1123 console.print("Next line")
1124
1125 output = capture.get()
1126 print(repr(output))
1127 # Background is reset before \n
1128 expected = "\x1b[34;47msoft wrap is on\x1b[0m\nNext line\n"
1129 assert output == expected