You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.1 KiB

  1. package os_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "os/exec"
  8. "syscall"
  9. "testing"
  10. "time"
  11. tmos "github.com/tendermint/tendermint/libs/os"
  12. )
  13. func TestCopyFile(t *testing.T) {
  14. tmpfile, err := ioutil.TempFile("", "example")
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. defer os.Remove(tmpfile.Name())
  19. content := []byte("hello world")
  20. if _, err := tmpfile.Write(content); err != nil {
  21. t.Fatal(err)
  22. }
  23. copyfile := fmt.Sprintf("%s.copy", tmpfile.Name())
  24. if err := tmos.CopyFile(tmpfile.Name(), copyfile); err != nil {
  25. t.Fatal(err)
  26. }
  27. if _, err := os.Stat(copyfile); os.IsNotExist(err) {
  28. t.Fatal("copy should exist")
  29. }
  30. data, err := ioutil.ReadFile(copyfile)
  31. if err != nil {
  32. t.Fatal(err)
  33. }
  34. if !bytes.Equal(data, content) {
  35. t.Fatalf("copy file content differs: expected %v, got %v", content, data)
  36. }
  37. os.Remove(copyfile)
  38. }
  39. func TestTrapSignal(t *testing.T) {
  40. if os.Getenv("TM_TRAP_SIGNAL_TEST") == "1" {
  41. t.Log("inside test process")
  42. killer()
  43. return
  44. }
  45. cmd, _, mockStderr := newTestProgram(t, "TM_TRAP_SIGNAL_TEST")
  46. err := cmd.Run()
  47. if err == nil {
  48. wantStderr := "exiting"
  49. if mockStderr.String() != wantStderr {
  50. t.Fatalf("stderr: want %q, got %q", wantStderr, mockStderr.String())
  51. }
  52. return
  53. }
  54. if e, ok := err.(*exec.ExitError); ok && !e.Success() {
  55. t.Fatalf("wrong exit code, want 0, got %d", e.ExitCode())
  56. }
  57. t.Fatal("this error should not be triggered")
  58. }
  59. type mockLogger struct{}
  60. func (ml mockLogger) Info(msg string, keyvals ...interface{}) {}
  61. func killer() {
  62. logger := mockLogger{}
  63. tmos.TrapSignal(logger, func() { _, _ = fmt.Fprintf(os.Stderr, "exiting") })
  64. time.Sleep(1 * time.Second)
  65. p, err := os.FindProcess(os.Getpid())
  66. if err != nil {
  67. panic(err)
  68. }
  69. if err := p.Signal(syscall.SIGTERM); err != nil {
  70. panic(err)
  71. }
  72. time.Sleep(1 * time.Second)
  73. }
  74. func newTestProgram(t *testing.T, environVar string) (cmd *exec.Cmd, stdout *bytes.Buffer, stderr *bytes.Buffer) {
  75. t.Helper()
  76. cmd = exec.Command(os.Args[0], "-test.run="+t.Name())
  77. stdout, stderr = bytes.NewBufferString(""), bytes.NewBufferString("")
  78. cmd.Env = append(os.Environ(), fmt.Sprintf("%s=1", environVar))
  79. cmd.Stdout = stdout
  80. cmd.Stderr = stderr
  81. return
  82. }