Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package snapshot
import (
"errors"
"os"
"testing"
"github.com/agiledragon/gomonkey/v2"
"github.com/stretchr/testify/assert"
)
func TestIsProcessAlive(t *testing.T) {
currentPID := os.Getpid()
if !isProcessAlive(currentPID) {
t.Errorf("Current process should be alive")
}
nonExistentPID := 999999
if isProcessAlive(nonExistentPID) {
t.Errorf("Non-existent process should not be alive")
}
}
func TestRunCmd(t *testing.T) {
cmd := "echo"
args := []string{"hello"}
env := os.Environ()
exitCode, err := RunCmd(cmd, args, env, -1)
if err != nil {
t.Errorf("RunCmd failed: %v", err)
}
if exitCode != 0 {
t.Errorf("Expected exit code 0, got %d", exitCode)
}
sleepCmd := "sleep"
sleepArgs := []string{"2"}
timeout := 1
exitCode, err = RunCmd(sleepCmd, sleepArgs, env, timeout)
if err == nil {
t.Errorf("Expected timeout error, got nil")
}
if !errors.Is(err, ErrCommandTimeout) && !errors.Is(err, ErrCommandKillFailed) {
t.Errorf("Expected timeout error, got %v", err)
}
exitCode, err = RunCmd(cmd, args, env, 0)
if err != nil {
t.Errorf("RunCmd with timeout=0 failed: %v", err)
}
if exitCode != 0 {
t.Errorf("Expected exit code 0 for async run, got %d", exitCode)
}
}
func TestTerminate(t *testing.T) {
patches := gomonkey.ApplyFunc(isProcessAlive, func(pid int) bool {
return false
})
defer patches.Reset()
err := terminate(999999999)
assert.NoError(t, err)
patches = gomonkey.ApplyFunc(isProcessAlive, func(pid int) bool {
return true
})
defer patches.Reset()
err = terminate(999999999)
assert.Error(t, err)
assert.Contains(t, err.Error(), "but process is still running")
}