test_session.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import subprocess
  2. import time
  3. from unittest.mock import call, patch
  4. from drill.session import TmuxSession
  5. class TestTmuxSession:
  6. def test_create_and_kill(self):
  7. session = TmuxSession(name="drill-test-create", cols=80, rows=24)
  8. session.create()
  9. result = subprocess.run(
  10. ["tmux", "has-session", "-t", "drill-test-create"],
  11. capture_output=True,
  12. )
  13. assert result.returncode == 0
  14. session.kill()
  15. result = subprocess.run(
  16. ["tmux", "has-session", "-t", "drill-test-create"],
  17. capture_output=True,
  18. )
  19. assert result.returncode != 0
  20. def test_send_keys_and_capture(self):
  21. session = TmuxSession(name="drill-test-keys", cols=80, rows=24)
  22. session.create()
  23. try:
  24. session.send_keys("echo hello-drill-test")
  25. time.sleep(0.5)
  26. output = session.capture()
  27. assert "hello-drill-test" in output
  28. finally:
  29. session.kill()
  30. def test_send_keys_pastes_text_then_submits(self):
  31. session = TmuxSession(name="drill-test-command-shape")
  32. with (
  33. patch("drill.session.subprocess.run") as run,
  34. patch("drill.session.time.sleep") as sleep,
  35. ):
  36. session.send_keys("hello `weird` text")
  37. assert run.call_args_list == [
  38. call(
  39. [
  40. "tmux",
  41. "set-buffer",
  42. "-b",
  43. "drill-test-command-shape-input",
  44. "hello `weird` text",
  45. ],
  46. check=True,
  47. ),
  48. call(
  49. [
  50. "tmux",
  51. "paste-buffer",
  52. "-d",
  53. "-b",
  54. "drill-test-command-shape-input",
  55. "-t",
  56. "drill-test-command-shape",
  57. ],
  58. check=True,
  59. ),
  60. call(["tmux", "send-keys", "-t", "drill-test-command-shape", "Enter"], check=True),
  61. ]
  62. sleep.assert_called_once_with(0.1)
  63. def test_launch_command(self, tmp_path):
  64. session = TmuxSession(name="drill-test-launch", cols=80, rows=24)
  65. session.create()
  66. try:
  67. session.launch(["python3", "-c", "import time; time.sleep(30)"], cwd=str(tmp_path))
  68. time.sleep(0.5)
  69. assert session.is_process_alive()
  70. finally:
  71. session.kill()
  72. def test_send_special_key(self, tmp_path):
  73. session = TmuxSession(name="drill-test-special", cols=80, rows=24)
  74. proof_file = tmp_path / "after-ctrl-c"
  75. session.create()
  76. try:
  77. session.send_keys("cat")
  78. time.sleep(0.3)
  79. session.send_special_key("ctrl-c")
  80. time.sleep(0.3)
  81. session.send_keys(f"touch {proof_file}")
  82. time.sleep(0.3)
  83. assert proof_file.exists()
  84. finally:
  85. session.kill()