osutil_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. "go.uber.org/zap"
  23. )
  24. func init() { setDflSignal = func(syscall.Signal) {} }
  25. func TestUnsetenv(t *testing.T) {
  26. tests := []string{
  27. "data",
  28. "space data",
  29. "equal=data",
  30. }
  31. for i, tt := range tests {
  32. key := "ETCD_UNSETENV_TEST"
  33. if os.Getenv(key) != "" {
  34. t.Fatalf("#%d: cannot get empty %s", i, key)
  35. }
  36. env := os.Environ()
  37. if err := os.Setenv(key, tt); err != nil {
  38. t.Fatalf("#%d: cannot set %s: %v", i, key, err)
  39. }
  40. if err := Unsetenv(key); err != nil {
  41. t.Errorf("#%d: unsetenv %s error: %v", i, key, err)
  42. }
  43. if g := os.Environ(); !reflect.DeepEqual(g, env) {
  44. t.Errorf("#%d: env = %+v, want %+v", i, g, env)
  45. }
  46. }
  47. }
  48. func waitSig(t *testing.T, c <-chan os.Signal, sig os.Signal) {
  49. select {
  50. case s := <-c:
  51. if s != sig {
  52. t.Fatalf("signal was %v, want %v", s, sig)
  53. }
  54. case <-time.After(1 * time.Second):
  55. t.Fatalf("timeout waiting for %v", sig)
  56. }
  57. }
  58. func TestHandleInterrupts(t *testing.T) {
  59. for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM} {
  60. n := 1
  61. RegisterInterruptHandler(func() { n++ })
  62. RegisterInterruptHandler(func() { n *= 2 })
  63. c := make(chan os.Signal, 2)
  64. signal.Notify(c, sig)
  65. HandleInterrupts(zap.NewExample())
  66. syscall.Kill(syscall.Getpid(), sig)
  67. // we should receive the signal once from our own kill and
  68. // a second time from HandleInterrupts
  69. waitSig(t, c, sig)
  70. waitSig(t, c, sig)
  71. if n == 3 {
  72. t.Fatalf("interrupt handlers were called in wrong order")
  73. }
  74. if n != 4 {
  75. t.Fatalf("interrupt handlers were not called properly")
  76. }
  77. // reset interrupt handlers
  78. interruptHandlers = interruptHandlers[:0]
  79. interruptExitMu.Unlock()
  80. }
  81. }