util.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package parser
  2. import (
  3. "math"
  4. "strings"
  5. "time"
  6. )
  7. // parseTestFunctionDuration parses the duration in seconds as a float64
  8. // from a line of go test output that looks something like this:
  9. // --- PASS: TestOldSchool_PassesWithMessage (0.03 seconds)
  10. func parseTestFunctionDuration(line string) float64 {
  11. line = strings.Replace(line, "(", "", 1)
  12. line = strings.Replace(line, ")", "", 1)
  13. fields := strings.Split(line, " ")
  14. return parseDurationInSeconds(fields[3], 2)
  15. }
  16. func parseDurationInSeconds(raw string, precision int) float64 {
  17. elapsed, err := time.ParseDuration(raw)
  18. if err != nil {
  19. elapsed, _ = time.ParseDuration(raw + "s")
  20. }
  21. return round(elapsed.Seconds(), precision)
  22. }
  23. // round returns the rounded version of x with precision.
  24. //
  25. // Special cases are:
  26. // round(±0) = ±0
  27. // round(±Inf) = ±Inf
  28. // round(NaN) = NaN
  29. //
  30. // Why, oh why doesn't the math package come with a round function?
  31. // Inspiration: http://play.golang.org/p/ZmFfr07oHp
  32. func round(x float64, precision int) float64 {
  33. var rounder float64
  34. pow := math.Pow(10, float64(precision))
  35. intermediate := x * pow
  36. if intermediate < 0.0 {
  37. intermediate -= 0.5
  38. } else {
  39. intermediate += 0.5
  40. }
  41. rounder = float64(int64(intermediate))
  42. return rounder / float64(pow)
  43. }