shell_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package shell
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. )
  7. // Benchmark to measure CPU efficiency
  8. func BenchmarkShellQuickCommands(b *testing.B) {
  9. shell := newPersistentShell(b.TempDir())
  10. b.ReportAllocs()
  11. for b.Loop() {
  12. _, _, err := shell.Exec(context.Background(), "echo test")
  13. exitCode := ExitCode(err)
  14. if err != nil || exitCode != 0 {
  15. b.Fatalf("Command failed: %v, exit code: %d", err, exitCode)
  16. }
  17. }
  18. }
  19. func TestTestTimeout(t *testing.T) {
  20. ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond)
  21. t.Cleanup(cancel)
  22. shell := newPersistentShell(t.TempDir())
  23. _, _, err := shell.Exec(ctx, "sleep 10")
  24. if status := ExitCode(err); status == 0 {
  25. t.Fatalf("Expected non-zero exit status, got %d", status)
  26. }
  27. if !IsInterrupt(err) {
  28. t.Fatalf("Expected command to be interrupted, but it was not")
  29. }
  30. if err == nil {
  31. t.Fatalf("Expected an error due to timeout, but got none")
  32. }
  33. }
  34. func TestTestCancel(t *testing.T) {
  35. ctx, cancel := context.WithCancel(t.Context())
  36. cancel() // immediately cancel the context
  37. shell := newPersistentShell(t.TempDir())
  38. _, _, err := shell.Exec(ctx, "sleep 10")
  39. if status := ExitCode(err); status == 0 {
  40. t.Fatalf("Expected non-zero exit status, got %d", status)
  41. }
  42. if !IsInterrupt(err) {
  43. t.Fatalf("Expected command to be interrupted, but it was not")
  44. }
  45. if err == nil {
  46. t.Fatalf("Expected an error due to cancel, but got none")
  47. }
  48. }
  49. func TestRunCommandError(t *testing.T) {
  50. shell := newPersistentShell(t.TempDir())
  51. _, _, err := shell.Exec(t.Context(), "nopenopenope")
  52. if status := ExitCode(err); status == 0 {
  53. t.Fatalf("Expected non-zero exit status, got %d", status)
  54. }
  55. if IsInterrupt(err) {
  56. t.Fatalf("Expected command to not be interrupted, but it was")
  57. }
  58. if err == nil {
  59. t.Fatalf("Expected an error, got nil")
  60. }
  61. }
  62. func TestRunContinuity(t *testing.T) {
  63. shell := newPersistentShell(t.TempDir())
  64. shell.Exec(t.Context(), "export FOO=bar")
  65. dst := t.TempDir()
  66. shell.Exec(t.Context(), "cd "+dst)
  67. out, _, _ := shell.Exec(t.Context(), "echo $FOO ; pwd")
  68. expect := "bar\n" + dst + "\n"
  69. if out != expect {
  70. t.Fatalf("Expected output %q, got %q", expect, out)
  71. }
  72. }