util.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package test
  2. import (
  3. "net"
  4. "strconv"
  5. "testing"
  6. "time"
  7. )
  8. // WaitForPortUp waits up to 7s for a port to come up and fails t if that fails
  9. func WaitForPortUp(t *testing.T, port int) {
  10. success := false
  11. for i := 0; i < 500; i++ {
  12. startTime := time.Now()
  13. conn, _ := net.DialTimeout("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port)), 10*time.Millisecond)
  14. if conn != nil {
  15. success = true
  16. conn.Close()
  17. break
  18. }
  19. if time.Since(startTime) < 10*time.Millisecond {
  20. time.Sleep(10*time.Millisecond - time.Since(startTime))
  21. }
  22. }
  23. if !success {
  24. t.Fatalf("Failed waiting for port %d to be UP", port)
  25. }
  26. }
  27. // WaitForPortDown waits up to 5s for a port to come down and fails t if that fails
  28. func WaitForPortDown(t *testing.T, port int) {
  29. success := false
  30. for i := 0; i < 100; i++ {
  31. conn, _ := net.DialTimeout("tcp", net.JoinHostPort("", strconv.Itoa(port)), 50*time.Millisecond)
  32. if conn == nil {
  33. success = true
  34. break
  35. }
  36. conn.Close()
  37. }
  38. if !success {
  39. t.Fatalf("Failed waiting for port %d to be DOWN", port)
  40. }
  41. }