signal_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //go:build linux || darwin
  2. package token
  3. import (
  4. "os"
  5. "syscall"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "github.com/stretchr/testify/require"
  10. )
  11. func TestSignalHandler(t *testing.T) {
  12. sigHandler := signalHandler{signals: []os.Signal{syscall.SIGUSR1}}
  13. handlerRan := false
  14. done := make(chan struct{})
  15. timer := time.NewTimer(time.Second)
  16. sigHandler.register(func() {
  17. handlerRan = true
  18. done <- struct{}{}
  19. })
  20. p, err := os.FindProcess(os.Getpid())
  21. require.Nil(t, err)
  22. p.Signal(syscall.SIGUSR1)
  23. // Blocks for up to one second to make sure the handler callback runs before the assert.
  24. select {
  25. case <-done:
  26. assert.True(t, handlerRan)
  27. case <-timer.C:
  28. t.Fail()
  29. }
  30. sigHandler.deregister()
  31. }
  32. func TestSignalHandlerClose(t *testing.T) {
  33. sigHandler := signalHandler{signals: []os.Signal{syscall.SIGUSR1}}
  34. done := make(chan struct{})
  35. timer := time.NewTimer(time.Second)
  36. sigHandler.register(func() { done <- struct{}{} })
  37. sigHandler.deregister()
  38. p, err := os.FindProcess(os.Getpid())
  39. require.Nil(t, err)
  40. p.Signal(syscall.SIGUSR1)
  41. select {
  42. case <-done:
  43. t.Fail()
  44. case <-timer.C:
  45. }
  46. }