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.

86 lines
2.1 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. package autofile
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "syscall"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/require"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. "github.com/tendermint/tendermint/libs/errors"
  11. )
  12. func TestSIGHUP(t *testing.T) {
  13. // First, create an AutoFile writing to a tempfile dir
  14. file, err := ioutil.TempFile("", "sighup_test")
  15. require.NoError(t, err)
  16. err = file.Close()
  17. require.NoError(t, err)
  18. name := file.Name()
  19. // Here is the actual AutoFile
  20. af, err := OpenAutoFile(name)
  21. require.NoError(t, err)
  22. // Write to the file.
  23. _, err = af.Write([]byte("Line 1\n"))
  24. require.NoError(t, err)
  25. _, err = af.Write([]byte("Line 2\n"))
  26. require.NoError(t, err)
  27. // Move the file over
  28. err = os.Rename(name, name+"_old")
  29. require.NoError(t, err)
  30. // Send SIGHUP to self.
  31. syscall.Kill(syscall.Getpid(), syscall.SIGHUP)
  32. // Wait a bit... signals are not handled synchronously.
  33. time.Sleep(time.Millisecond * 10)
  34. // Write more to the file.
  35. _, err = af.Write([]byte("Line 3\n"))
  36. require.NoError(t, err)
  37. _, err = af.Write([]byte("Line 4\n"))
  38. require.NoError(t, err)
  39. err = af.Close()
  40. require.NoError(t, err)
  41. // Both files should exist
  42. if body := cmn.MustReadFile(name + "_old"); string(body) != "Line 1\nLine 2\n" {
  43. t.Errorf("Unexpected body %s", body)
  44. }
  45. if body := cmn.MustReadFile(name); string(body) != "Line 3\nLine 4\n" {
  46. t.Errorf("Unexpected body %s", body)
  47. }
  48. }
  49. // Manually modify file permissions, close, and reopen using autofile:
  50. // We expect the file permissions to be changed back to the intended perms.
  51. func TestOpenAutoFilePerms(t *testing.T) {
  52. file, err := ioutil.TempFile("", "permission_test")
  53. require.NoError(t, err)
  54. err = file.Close()
  55. require.NoError(t, err)
  56. name := file.Name()
  57. // open and change permissions
  58. af, err := OpenAutoFile(name)
  59. require.NoError(t, err)
  60. err = af.file.Chmod(0755)
  61. require.NoError(t, err)
  62. err = af.Close()
  63. require.NoError(t, err)
  64. // reopen and expect an ErrPermissionsChanged as Cause
  65. af, err = OpenAutoFile(name)
  66. require.Error(t, err)
  67. if e, ok := err.(*errors.ErrPermissionsChanged); ok {
  68. t.Logf("%v", e)
  69. } else {
  70. t.Errorf("unexpected error %v", e)
  71. }
  72. }