test_shortcuts.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from __future__ import annotations
  2. from prompt_toolkit.shortcuts import print_container
  3. from prompt_toolkit.shortcuts.prompt import _split_multiline_prompt
  4. from prompt_toolkit.widgets import Frame, TextArea
  5. def test_split_multiline_prompt():
  6. # Test 1: no newlines:
  7. tokens = [("class:testclass", "ab")]
  8. has_before_tokens, before, first_input_line = _split_multiline_prompt(
  9. lambda: tokens
  10. )
  11. assert has_before_tokens() is False
  12. assert before() == []
  13. assert first_input_line() == [
  14. ("class:testclass", "a"),
  15. ("class:testclass", "b"),
  16. ]
  17. # Test 1: multiple lines.
  18. tokens = [("class:testclass", "ab\ncd\nef")]
  19. has_before_tokens, before, first_input_line = _split_multiline_prompt(
  20. lambda: tokens
  21. )
  22. assert has_before_tokens() is True
  23. assert before() == [
  24. ("class:testclass", "a"),
  25. ("class:testclass", "b"),
  26. ("class:testclass", "\n"),
  27. ("class:testclass", "c"),
  28. ("class:testclass", "d"),
  29. ]
  30. assert first_input_line() == [
  31. ("class:testclass", "e"),
  32. ("class:testclass", "f"),
  33. ]
  34. # Edge case 1: starting with a newline.
  35. tokens = [("class:testclass", "\nab")]
  36. has_before_tokens, before, first_input_line = _split_multiline_prompt(
  37. lambda: tokens
  38. )
  39. assert has_before_tokens() is True
  40. assert before() == []
  41. assert first_input_line() == [("class:testclass", "a"), ("class:testclass", "b")]
  42. # Edge case 2: starting with two newlines.
  43. tokens = [("class:testclass", "\n\nab")]
  44. has_before_tokens, before, first_input_line = _split_multiline_prompt(
  45. lambda: tokens
  46. )
  47. assert has_before_tokens() is True
  48. assert before() == [("class:testclass", "\n")]
  49. assert first_input_line() == [("class:testclass", "a"), ("class:testclass", "b")]
  50. def test_print_container(tmpdir):
  51. # Call `print_container`, render to a dummy file.
  52. f = tmpdir.join("output")
  53. with open(f, "w") as fd:
  54. print_container(Frame(TextArea(text="Hello world!\n"), title="Title"), file=fd)
  55. # Verify rendered output.
  56. with open(f) as fd:
  57. text = fd.read()
  58. assert "Hello world" in text
  59. assert "Title" in text