csv_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "testing"
  8. "testing/iotest"
  9. )
  10. func TestOperations(t *testing.T) {
  11. data := [][]float64{
  12. {10, 20, 15, 30, 45, 50, 100, 30},
  13. {5.5, 8, 2.2, 9.75, 8.45, 3, 2.5, 10.25, 4.75, 6.1, 7.67, 12.287, 5.47},
  14. {-10, -20},
  15. {102, 37, 44, 57, 67, 129},
  16. }
  17. testCases := []struct {
  18. name string
  19. op statsFunc
  20. exp []float64
  21. }{
  22. {"Sum", sum, []float64{300, 85.927, -30, 436}},
  23. {"Avg", avg, []float64{37.5, 6.609769230769231, -15, 72.666666666666666}},
  24. }
  25. for _, tc := range testCases {
  26. for k, exp := range tc.exp {
  27. name := fmt.Sprintf("%sData%d", tc.name, k+1)
  28. t.Run(name, func(t *testing.T) {
  29. res := tc.op(data[k])
  30. if res != exp {
  31. t.Errorf("Expected %g, got %g instead", exp, res)
  32. }
  33. })
  34. }
  35. }
  36. }
  37. func TestCSV2Float(t *testing.T) {
  38. csvData := `IP Address,Requests,Response Time
  39. 192.168.0.199,2056,236
  40. 192.168.0.88,899,220
  41. 192.168.0.199,3054,226
  42. 192.168.0.100,4133,218
  43. 192.168.0.199,950,238
  44. `
  45. // Test cases for CSV2Float Test
  46. testCases := []struct {
  47. name string
  48. col int
  49. exp []float64
  50. expErr error
  51. r io.Reader
  52. }{
  53. {name: "Column2", col: 2,
  54. exp: []float64{2056, 899, 3054, 4133, 950}, expErr: nil,
  55. r: bytes.NewBufferString(csvData),
  56. },
  57. {name: "Column3", col: 3,
  58. exp: []float64{236, 220, 226, 218, 238}, expErr: nil,
  59. r: bytes.NewBufferString(csvData),
  60. },
  61. {name: "FailRead", col: 1,
  62. exp: nil,
  63. expErr: iotest.ErrTimeout,
  64. r: iotest.TimeoutReader(bytes.NewReader([]byte{0})),
  65. },
  66. {name: "FailedNotNumber", col: 1,
  67. exp: nil,
  68. expErr: ErrNotNumber,
  69. r: bytes.NewBufferString(csvData),
  70. },
  71. {name: "FailedInvalidColumn", col: 4,
  72. exp: nil,
  73. expErr: ErrInvalidColumn,
  74. r: bytes.NewBufferString(csvData),
  75. }}
  76. for _, tc := range testCases {
  77. t.Run(tc.name, func(t *testing.T) {
  78. res, err := csv2float(tc.r, tc.col)
  79. if tc.expErr != nil {
  80. if err == nil {
  81. t.Errorf("Expected error. Got nill instead")
  82. }
  83. if !errors.Is(err, tc.expErr) {
  84. t.Errorf("Expected error %q, got %q instead", tc.expErr, err)
  85. }
  86. return
  87. }
  88. if err != nil {
  89. t.Errorf("Unexpected error: %q", err)
  90. }
  91. for i, exp := range tc.exp {
  92. if res[i] != exp {
  93. t.Errorf("Expected %g, got %g instead", exp, res[i])
  94. }
  95. }
  96. })
  97. }
  98. }