Files

99 lines
2.5 KiB
Go

package main
import (
"errors"
"os"
"os/exec"
"path/filepath"
"syscall"
"testing"
"time"
)
func TestInitializePathsCreatesProtectedEmptyLog(t *testing.T) {
root := t.TempDir()
paths := Paths{
ConfigDir: filepath.Join(root, "config"),
CacheDir: filepath.Join(root, "cache"),
LogFile: filepath.Join(root, "cache", "barnard-ui.log"),
}
if err := initialize_paths(paths); err != nil {
t.Fatal(err)
}
info, err := os.Stat(paths.LogFile)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0600 || info.Size() != 0 {
t.Fatalf("log mode and size = %o, %d; want 600, 0", info.Mode().Perm(), info.Size())
}
}
func TestRunExternalForwardsTerminationSignal(t *testing.T) {
sleep, err := exec.LookPath("sleep")
if err != nil {
t.Skip("sleep is not installed")
}
ui := &TerminalUI{termination: make(chan os.Signal, 1)}
ui.termination <- syscall.SIGTERM
started := time.Now()
err = run_external(ui, exec.Command(sleep, "30"))
var signalErr *terminalSignalError
if !errors.As(err, &signalErr) || signalErr.signal != syscall.SIGTERM {
t.Fatalf("run_external error = %v; want SIGTERM error", err)
}
if time.Since(started) > 5*time.Second {
t.Fatal("run_external did not promptly terminate the child")
}
}
func TestRunExternalReportsChildSignal(t *testing.T) {
shell, err := exec.LookPath("sh")
if err != nil {
t.Skip("sh is not installed")
}
ui := &TerminalUI{termination: make(chan os.Signal, 1)}
err = run_external(ui, exec.Command(shell, "-c", "kill -TERM $$"))
var signalErr *terminalSignalError
if !errors.As(err, &signalErr) || signalErr.signal != syscall.SIGTERM {
t.Fatalf("run_external error = %v; want child SIGTERM error", err)
}
}
func TestWritePasswordFilePreservesPasswordAndMode(t *testing.T) {
path, err := write_password_file(t.TempDir(), " secret value ")
if err != nil {
t.Fatal(err)
}
defer os.Remove(path)
contents, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(contents) != " secret value " {
t.Fatalf("password contents = %q", string(contents))
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0600 {
t.Fatalf("password file mode = %o; want 600", info.Mode().Perm())
}
}
func TestExpandUserPath(t *testing.T) {
home, err := os.UserHomeDir()
if err != nil {
t.Fatal(err)
}
got, err := expand_user_path("~/certificate.pem")
if err != nil {
t.Fatal(err)
}
want := filepath.Join(home, "certificate.pem")
if got != want {
t.Fatalf("expanded path = %q; want %q", got, want)
}
}