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