|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "strings" |
| 8 | + "sync/atomic" |
| 9 | + "syscall" |
| 10 | + "testing" |
| 11 | +) |
| 12 | + |
| 13 | +// ── tryReexec tests ────────────────────────────────────────────────── |
| 14 | + |
| 15 | +func TestTryReexec_ExecFails(t *testing.T) { |
| 16 | + // Swap execFunc to simulate a failure. |
| 17 | + orig := execFunc |
| 18 | + execCalled := false |
| 19 | + execFunc = func(argv0 string, argv []string, envv []string) error { |
| 20 | + execCalled = true |
| 21 | + return errors.New("exec failed: no such file") |
| 22 | + } |
| 23 | + defer func() { execFunc = orig }() |
| 24 | + |
| 25 | + // Capture stderr. |
| 26 | + origStderr := os.Stderr |
| 27 | + r, w, err := os.Pipe() |
| 28 | + if err != nil { |
| 29 | + t.Fatal(err) |
| 30 | + } |
| 31 | + os.Stderr = w |
| 32 | + defer func() { os.Stderr = origStderr }() |
| 33 | + |
| 34 | + err = tryReexec() |
| 35 | + w.Close() |
| 36 | + |
| 37 | + if !execCalled { |
| 38 | + t.Error("tryReexec() did not call execFunc") |
| 39 | + } |
| 40 | + if err == nil { |
| 41 | + t.Error("tryReexec() should return error when exec fails") |
| 42 | + } |
| 43 | + if !strings.Contains(err.Error(), "exec failed") { |
| 44 | + t.Errorf("unexpected error: %v", err) |
| 45 | + } |
| 46 | + |
| 47 | + // Read captured stderr. |
| 48 | + stderr := make([]byte, 4096) |
| 49 | + n, _ := r.Read(stderr) |
| 50 | + output := string(stderr[:n]) |
| 51 | + if !strings.Contains(output, "re-executing") { |
| 52 | + t.Errorf("stderr missing 're-executing': %q", output) |
| 53 | + } |
| 54 | + if !strings.Contains(output, "restart failed") { |
| 55 | + t.Errorf("stderr missing 'restart failed': %q", output) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +func TestTryReexec_ExecCalledWithCorrectArgs(t *testing.T) { |
| 60 | + orig := execFunc |
| 61 | + var capturedArgv0 string |
| 62 | + var capturedEnv []string |
| 63 | + execFunc = func(argv0 string, argv []string, envv []string) error { |
| 64 | + capturedArgv0 = argv0 |
| 65 | + capturedEnv = envv |
| 66 | + return nil // simulate success (though real Exec never returns) |
| 67 | + } |
| 68 | + defer func() { execFunc = orig }() |
| 69 | + |
| 70 | + _ = tryReexec() |
| 71 | + |
| 72 | + if capturedArgv0 == "" { |
| 73 | + t.Error("execFunc was not called with argv0") |
| 74 | + } |
| 75 | + // argv[0] should be the resolved executable path (via os.Executable()), |
| 76 | + // not necessarily os.Args[0] (which might be a bare name). |
| 77 | + if !strings.Contains(capturedArgv0, "odek") { |
| 78 | + t.Errorf("argv0 = %q, want path containing 'odek'", capturedArgv0) |
| 79 | + } |
| 80 | + if len(capturedEnv) == 0 { |
| 81 | + t.Error("execFunc was called with empty env") |
| 82 | + } |
| 83 | + // Verify the environment contains PATH (basic sanity check). |
| 84 | + found := false |
| 85 | + for _, e := range capturedEnv { |
| 86 | + if strings.HasPrefix(e, "PATH=") { |
| 87 | + found = true |
| 88 | + break |
| 89 | + } |
| 90 | + } |
| 91 | + if !found { |
| 92 | + t.Error("captured env does not contain PATH") |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +func TestTryReexec_ReturnsNilOnSuccess(t *testing.T) { |
| 97 | + orig := execFunc |
| 98 | + execFunc = func(argv0 string, argv []string, envv []string) error { |
| 99 | + return nil |
| 100 | + } |
| 101 | + defer func() { execFunc = orig }() |
| 102 | + |
| 103 | + err := tryReexec() |
| 104 | + if err != nil { |
| 105 | + t.Errorf("tryReexec() should return nil on success, got %v", err) |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +// ── restartRequested (atomic.Bool) tests ───────────────────────────── |
| 110 | + |
| 111 | +func TestRestartRequested_DefaultFalse(t *testing.T) { |
| 112 | + var restartRequested atomic.Bool |
| 113 | + if restartRequested.Load() { |
| 114 | + t.Error("restartRequested should default to false") |
| 115 | + } |
| 116 | +} |
| 117 | + |
| 118 | +func TestRestartRequested_SetTrue(t *testing.T) { |
| 119 | + var restartRequested atomic.Bool |
| 120 | + restartRequested.Store(true) |
| 121 | + if !restartRequested.Load() { |
| 122 | + t.Error("restartRequested should be true after Store(true)") |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +func TestRestartRequested_StoreThenLoad(t *testing.T) { |
| 127 | + var restartRequested atomic.Bool |
| 128 | + |
| 129 | + // Simulate the /restart command flow without actually sending SIGHUP |
| 130 | + // (which would kill the test process). |
| 131 | + // 1. Store(true) |
| 132 | + // 2. (SIGHUP would be sent here in production) |
| 133 | + // 3. Signal handler cancels context, loop exits |
| 134 | + // 4. Load() checked to decide between restart vs exit |
| 135 | + |
| 136 | + restartRequested.Store(true) |
| 137 | + |
| 138 | + if !restartRequested.Load() { |
| 139 | + t.Error("restartRequested.Load() should return true after Store(true)") |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +func TestRestartRequested_CompareAndSwap(t *testing.T) { |
| 144 | + var restartRequested atomic.Bool |
| 145 | + |
| 146 | + // Only set from false → true. |
| 147 | + swapped := restartRequested.CompareAndSwap(false, true) |
| 148 | + if !swapped { |
| 149 | + t.Error("first CAS should succeed") |
| 150 | + } |
| 151 | + if !restartRequested.Load() { |
| 152 | + t.Error("should be true after first CAS") |
| 153 | + } |
| 154 | + |
| 155 | + // Second CAS should fail (already true). |
| 156 | + swapped = restartRequested.CompareAndSwap(false, true) |
| 157 | + if swapped { |
| 158 | + t.Error("second CAS should fail, value is already true") |
| 159 | + } |
| 160 | + |
| 161 | + // But we can CAS true → false. |
| 162 | + swapped = restartRequested.CompareAndSwap(true, false) |
| 163 | + if !swapped { |
| 164 | + t.Error("CAS true→false should succeed") |
| 165 | + } |
| 166 | + if restartRequested.Load() { |
| 167 | + t.Error("should be false after true→false CAS") |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// ── Signal handling behavior tests ─────────────────────────────────── |
| 172 | + |
| 173 | +func TestSIGHUPTriggersCancel(t *testing.T) { |
| 174 | + // This test verifies the conceptual flow: |
| 175 | + // 1. SIGHUP is sent |
| 176 | + // 2. Signal handler receives it |
| 177 | + // 3. Context is cancelled |
| 178 | + // |
| 179 | + // We can't fully test syscall.Exec or signal.NotifyContext |
| 180 | + // in unit tests, but we can verify the signal notification |
| 181 | + // channel works correctly. |
| 182 | + |
| 183 | + sigCh := make(chan os.Signal, 1) |
| 184 | + |
| 185 | + // Simulate what signal.Notify would do — send SIGHUP to the channel. |
| 186 | + go func() { |
| 187 | + sigCh <- syscall.SIGHUP |
| 188 | + }() |
| 189 | + |
| 190 | + sig := <-sigCh |
| 191 | + if sig != syscall.SIGHUP { |
| 192 | + t.Errorf("expected SIGHUP, got %v", sig) |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +func TestSIGTERMDoesNotTriggerRestart(t *testing.T) { |
| 197 | + // SIGTERM should shut down WITHOUT re-exec. |
| 198 | + // We test the conceptual flow: signal != SIGHUP → cancel without restart. |
| 199 | + |
| 200 | + sigCh := make(chan os.Signal, 1) |
| 201 | + go func() { |
| 202 | + sigCh <- syscall.SIGTERM |
| 203 | + }() |
| 204 | + |
| 205 | + sig := <-sigCh |
| 206 | + if sig == syscall.SIGHUP { |
| 207 | + t.Error("SIGTERM should not be SIGHUP") |
| 208 | + } |
| 209 | + // In the real code, this path sets restartRequested=false (default) |
| 210 | + // and cancels the context, causing graceful exit without re-exec. |
| 211 | +} |
| 212 | + |
| 213 | +// ── Integration: restart message format ────────────────────────────── |
| 214 | + |
| 215 | +func TestRestartMessage_ContainsExpectedContent(t *testing.T) { |
| 216 | + // The restart confirmation message sent to the user should contain |
| 217 | + // key phrases so the user knows what's happening. |
| 218 | + msg := fmt.Sprintf("%s %s", |
| 219 | + "\U0001F504", // 🔄 |
| 220 | + "*Restarting...*\n\nThe bot will restart momentarily. This may take a few seconds.", |
| 221 | + ) |
| 222 | + |
| 223 | + if !strings.Contains(msg, "Restarting") { |
| 224 | + t.Errorf("restart message missing 'Restarting': %q", msg) |
| 225 | + } |
| 226 | + if !strings.Contains(msg, "🔄") { |
| 227 | + t.Errorf("restart message missing 🔄 emoji: %q", msg) |
| 228 | + } |
| 229 | + if !strings.Contains(msg, "few seconds") { |
| 230 | + t.Errorf("restart message missing 'few seconds': %q", msg) |
| 231 | + } |
| 232 | +} |
| 233 | + |
| 234 | +// ── Stderr logging format tests ────────────────────────────────────── |
| 235 | + |
| 236 | +func TestRestartStderrMessage_Format(t *testing.T) { |
| 237 | + // Verify the stderr message format printed during restart. |
| 238 | + msg := fmt.Sprintf("odek telegram: re-executing %s %v...\n", "/usr/local/bin/odek", []string{"telegram"}) |
| 239 | + if !strings.Contains(msg, "odek telegram: re-executing") { |
| 240 | + t.Errorf("stderr restart message missing prefix: %q", msg) |
| 241 | + } |
| 242 | + if !strings.Contains(msg, "/usr/local/bin/odek") { |
| 243 | + t.Errorf("stderr restart message missing binary path: %q", msg) |
| 244 | + } |
| 245 | +} |
| 246 | + |
| 247 | +// ── Edge case: no binary path ──────────────────────────────────────── |
| 248 | + |
| 249 | +func TestRestartStderrMessage_NoArgs(t *testing.T) { |
| 250 | + // When os.Args is just the binary with no subcommand (shouldn't happen |
| 251 | + // in practice, but test the format doesn't panic). |
| 252 | + msg := fmt.Sprintf("odek telegram: re-executing %s %v...\n", "/usr/local/bin/odek", []string{}) |
| 253 | + if !strings.Contains(msg, "odek telegram: re-executing") { |
| 254 | + t.Errorf("stderr restart message missing prefix: %q", msg) |
| 255 | + } |
| 256 | + if !strings.Contains(msg, "[]") { |
| 257 | + t.Errorf("stderr restart message should show empty args as []: %q", msg) |
| 258 | + } |
| 259 | +} |
0 commit comments