另客网go项目公用的代码库

run_test.go 1012B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package timeout_test
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. "git.links123.net/links123.com/pkg/timeout"
  7. )
  8. type ExcuteChan struct {
  9. c chan bool
  10. once sync.Once
  11. }
  12. func Run(limit time.Duration, f func()) bool {
  13. done := make(chan bool)
  14. go func() {
  15. f()
  16. done <- true
  17. close(done)
  18. }()
  19. select {
  20. case <-time.After(limit):
  21. return false
  22. case <-done:
  23. return true
  24. }
  25. }
  26. func Run1(limit time.Duration, f func()) bool {
  27. ec := &ExcuteChan{c: make(chan bool), once: sync.Once{}}
  28. go func() {
  29. f()
  30. ec.once.Do(func() {
  31. ec.c <- true
  32. close(ec.c)
  33. })
  34. }()
  35. select {
  36. case <-time.After(limit):
  37. return false
  38. case <-ec.c:
  39. return true
  40. }
  41. }
  42. func TestRun(t *testing.T) {
  43. // timeout: OK
  44. if !timeout.Run(1*time.Second, func() {
  45. time.Sleep(2 * time.Second)
  46. }) {
  47. t.Log("time out: OK")
  48. } else {
  49. t.Fatal("time out: FAILED")
  50. }
  51. // timeout: FAILED
  52. if !timeout.Run(3*time.Second, func() {
  53. time.Sleep(2 * time.Second)
  54. }) {
  55. t.Log("time out: OK")
  56. } else {
  57. t.Fatal("time out: FAILED")
  58. }
  59. }