osutil_test.go 2.2 KB

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