osutil_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2015 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package osutil
  15. import (
  16. "os"
  17. "os/signal"
  18. "reflect"
  19. "syscall"
  20. "testing"
  21. "time"
  22. )
  23. func TestUnsetenv(t *testing.T) {
  24. tests := []string{
  25. "data",
  26. "space data",
  27. "equal=data",
  28. }
  29. for i, tt := range tests {
  30. key := "ETCD_UNSETENV_TEST"
  31. if os.Getenv(key) != "" {
  32. t.Fatalf("#%d: cannot get empty %s", i, key)
  33. }
  34. env := os.Environ()
  35. if err := os.Setenv(key, tt); err != nil {
  36. t.Fatalf("#%d: cannot set %s: %v", i, key, err)
  37. }
  38. if err := Unsetenv(key); err != nil {
  39. t.Errorf("#%d: unsetenv %s error: %v", i, key, err)
  40. }
  41. if g := os.Environ(); !reflect.DeepEqual(g, env) {
  42. t.Errorf("#%d: env = %+v, want %+v", i, g, env)
  43. }
  44. }
  45. }
  46. func waitSig(t *testing.T, c <-chan os.Signal, sig os.Signal) {
  47. select {
  48. case s := <-c:
  49. if s != sig {
  50. t.Fatalf("signal was %v, want %v", s, sig)
  51. }
  52. case <-time.After(1 * time.Second):
  53. t.Fatalf("timeout waiting for %v", sig)
  54. }
  55. }
  56. func TestHandleInterrupts(t *testing.T) {
  57. for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM} {
  58. n := 1
  59. RegisterInterruptHandler(func() { n++ })
  60. RegisterInterruptHandler(func() { n *= 2 })
  61. c := make(chan os.Signal, 2)
  62. signal.Notify(c, sig)
  63. HandleInterrupts()
  64. syscall.Kill(syscall.Getpid(), sig)
  65. // we should receive the signal once from our own kill and
  66. // a second time from HandleInterrupts
  67. waitSig(t, c, sig)
  68. waitSig(t, c, sig)
  69. if n == 3 {
  70. t.Fatalf("interrupt handlers were called in wrong order")
  71. }
  72. if n != 4 {
  73. t.Fatalf("interrupt handlers were not called properly")
  74. }
  75. // reset interrupt handlers
  76. interruptHandlers = interruptHandlers[:0]
  77. interruptExitMu.Unlock()
  78. }
  79. }