ping_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package ping
  2. import (
  3. "errors"
  4. "strings"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestSystemPing(t *testing.T) {
  9. type testCase struct {
  10. // constructors
  11. address string
  12. // results
  13. expectedMatch float64
  14. err error
  15. }
  16. t.Run("ping localhost (via 127.0.0.1)", func(t *testing.T) {
  17. tests := []testCase{{"127.0.0.1", 0, nil}}
  18. for _, test := range tests {
  19. result, err := runPing(test.address)
  20. // result data prep
  21. lines := strings.Split(strings.ReplaceAll(string(*result), "\r\n", "\n"), "\n")
  22. var has_addr bool
  23. for _, line := range lines {
  24. if strings.Contains(line, "127.0.0.1") {
  25. has_addr = true
  26. }
  27. }
  28. // assertions
  29. assert.NoError(t, err)
  30. assert.True(t, has_addr)
  31. }
  32. })
  33. }
  34. func TestSplitBytes(t *testing.T) {
  35. type testCase struct {
  36. // test data
  37. bytes *[]byte
  38. // expected results
  39. lines []string
  40. }
  41. t.Run("test bytes to lines", func(t *testing.T) {
  42. var tests []testCase
  43. // init tests
  44. for range 5 {
  45. bytes, _ := runPing("127.0.0.1")
  46. lines := strings.Split(strings.ReplaceAll(string(*bytes), "\r\n", "\n"), "\n")
  47. tests = append(tests, testCase{bytes: bytes, lines: lines})
  48. }
  49. // run tests
  50. for _, test := range tests {
  51. lines := splitBytesToLines(test.bytes)
  52. assert.Equal(t, lines, test.lines)
  53. }
  54. })
  55. }
  56. func TestPing(t *testing.T) {
  57. type testCase struct {
  58. address string
  59. delay float64
  60. err error
  61. }
  62. t.Run("test golang ping interface", func(t *testing.T) {
  63. var tests []testCase
  64. // init tests
  65. for range 5 {
  66. tests = append(tests, testCase{
  67. address: "127.0.0.1",
  68. delay: 0,
  69. err: nil,
  70. })
  71. }
  72. tests = append(tests, testCase{address: "willneverresolveever", delay: -1, err: errors.New("test failure")})
  73. for _, test := range tests {
  74. delay, err := Ping(test.address)
  75. assert.GreaterOrEqual(t, delay, test.delay)
  76. if test.err != nil {
  77. assert.Error(t, err)
  78. assert.Equal(t, delay, test.delay)
  79. } else {
  80. assert.NoError(t, err)
  81. }
  82. }
  83. })
  84. }