| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "strings" |
| 6 | "testing" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | func TestRunGitRespectsContextTimeout(t *testing.T) { |
| 11 | // Use an already-expired context to verify the command fails fast. |
| 12 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) |
| 13 | defer cancel() |
| 14 | time.Sleep(5 * time.Millisecond) |
| 15 | |
| 16 | _, err := runGit(ctx, "", "sleep", "60") |
| 17 | if err == nil { |
| 18 | t.Fatal("expected error from timed-out context") |
| 19 | } |
| 20 | if !strings.Contains(err.Error(), "timed out") && !strings.Contains(err.Error(), "context deadline exceeded") { |
| 21 | t.Errorf("expected timeout-related error, got: %v", err) |
| 22 | } |
| 23 | } |
| 24 | |
| 25 | func TestRunGitNetworkRespectsContextTimeout(t *testing.T) { |
| 26 | ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) |
| 27 | defer cancel() |
| 28 | time.Sleep(5 * time.Millisecond) |
| 29 | |
| 30 | _, err := runGitNetwork(ctx, "", "sleep", "60") |
| 31 | if err == nil { |
| 32 | t.Fatal("expected error from timed-out context") |
| 33 | } |
| 34 | if !strings.Contains(err.Error(), "timed out") && !strings.Contains(err.Error(), "context deadline exceeded") { |
| 35 | t.Errorf("expected timeout-related error, got: %v", err) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | func TestEnsureTimeoutNoOverride(t *testing.T) { |
| 40 | // If the context already has a shorter deadline, ensureTimeout should not extend it. |
| 41 | shortTimeout := 10 * time.Millisecond |
| 42 | ctx, cancel := context.WithTimeout(context.Background(), shortTimeout) |
| 43 | defer cancel() |
| 44 | |
| 45 | newCtx, newCancel := ensureTimeout(ctx, 5*time.Minute) |
| 46 | defer newCancel() |
| 47 | |
| 48 | deadline, ok := newCtx.Deadline() |
| 49 | if !ok { |
| 50 | t.Fatal("expected deadline to be set") |
| 51 | } |
| 52 | remaining := time.Until(deadline) |
| 53 | if remaining > 1*time.Second { |
| 54 | t.Errorf("deadline should be close to original short timeout, but remaining = %v", remaining) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func TestEnsureTimeoutAppliesDefault(t *testing.T) { |
| 59 | ctx := context.Background() |
| 60 | timeout := 42 * time.Second |
| 61 | |
| 62 | newCtx, cancel := ensureTimeout(ctx, timeout) |
| 63 | defer cancel() |
| 64 | |
| 65 | deadline, ok := newCtx.Deadline() |
| 66 | if !ok { |
| 67 | t.Fatal("expected deadline to be set") |
| 68 | } |
| 69 | remaining := time.Until(deadline) |
| 70 | if remaining < 40*time.Second || remaining > 43*time.Second { |
| 71 | t.Errorf("expected deadline ~42s from now, got %v", remaining) |
| 72 | } |
| 73 | } |