test_print_formatted_text.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """
  2. Test the `print` function.
  3. """
  4. from __future__ import annotations
  5. import pytest
  6. from prompt_toolkit import print_formatted_text as pt_print
  7. from prompt_toolkit.formatted_text import HTML, FormattedText, to_formatted_text
  8. from prompt_toolkit.output import ColorDepth
  9. from prompt_toolkit.styles import Style
  10. from prompt_toolkit.utils import is_windows
  11. class _Capture:
  12. "Emulate an stdout object."
  13. def __init__(self):
  14. self._data = []
  15. def write(self, data):
  16. self._data.append(data)
  17. @property
  18. def data(self):
  19. return "".join(self._data)
  20. def flush(self):
  21. pass
  22. def isatty(self):
  23. return True
  24. def fileno(self):
  25. # File descriptor is not used for printing formatted text.
  26. # (It is only needed for getting the terminal size.)
  27. return -1
  28. @pytest.mark.skipif(is_windows(), reason="Doesn't run on Windows yet.")
  29. def test_print_formatted_text():
  30. f = _Capture()
  31. pt_print([("", "hello"), ("", "world")], file=f)
  32. assert "hello" in f.data
  33. assert "world" in f.data
  34. @pytest.mark.skipif(is_windows(), reason="Doesn't run on Windows yet.")
  35. def test_print_formatted_text_backslash_r():
  36. f = _Capture()
  37. pt_print("hello\r\n", file=f)
  38. assert "hello" in f.data
  39. @pytest.mark.skipif(is_windows(), reason="Doesn't run on Windows yet.")
  40. def test_formatted_text_with_style():
  41. f = _Capture()
  42. style = Style.from_dict(
  43. {
  44. "hello": "#ff0066",
  45. "world": "#44ff44 italic",
  46. }
  47. )
  48. tokens = FormattedText(
  49. [
  50. ("class:hello", "Hello "),
  51. ("class:world", "world"),
  52. ]
  53. )
  54. # NOTE: We pass the default (8bit) color depth, so that the unit tests
  55. # don't start failing when environment variables change.
  56. pt_print(tokens, style=style, file=f, color_depth=ColorDepth.DEFAULT)
  57. assert "\x1b[0;38;5;197mHello" in f.data
  58. assert "\x1b[0;38;5;83;3mworld" in f.data
  59. @pytest.mark.skipif(is_windows(), reason="Doesn't run on Windows yet.")
  60. def test_html_with_style():
  61. """
  62. Text `print_formatted_text` with `HTML` wrapped in `to_formatted_text`.
  63. """
  64. f = _Capture()
  65. html = HTML("<ansigreen>hello</ansigreen> <b>world</b>")
  66. formatted_text = to_formatted_text(html, style="class:myhtml")
  67. pt_print(formatted_text, file=f, color_depth=ColorDepth.DEFAULT)
  68. assert (
  69. f.data
  70. == "\x1b[0m\x1b[?7h\x1b[0;32mhello\x1b[0m \x1b[0;1mworld\x1b[0m\r\n\x1b[0m"
  71. )