timer_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package timer
  14. import (
  15. "testing"
  16. "time"
  17. . "github.com/onsi/gomega"
  18. )
  19. var currentTime time.Time
  20. func init() {
  21. setCurrentTimeSinceEpoch(0)
  22. now = func() time.Time { return currentTime }
  23. }
  24. func setCurrentTimeSinceEpoch(duration time.Duration) {
  25. currentTime = time.Unix(0, duration.Nanoseconds())
  26. }
  27. func testUsageWithDefer(timer *TestPhaseTimer) {
  28. defer timer.StartPhase(33, "two").End()
  29. setCurrentTimeSinceEpoch(6*time.Second + 500*time.Millisecond)
  30. }
  31. func TestTimer(t *testing.T) {
  32. RegisterTestingT(t)
  33. timer := NewTestPhaseTimer()
  34. setCurrentTimeSinceEpoch(1 * time.Second)
  35. phaseOne := timer.StartPhase(1, "one")
  36. setCurrentTimeSinceEpoch(3 * time.Second)
  37. testUsageWithDefer(timer)
  38. Expect(timer.PrintJSON()).To(MatchJSON(`{
  39. "version": "v1",
  40. "dataItems": [
  41. {
  42. "data": {
  43. "001-one": 5.5,
  44. "033-two": 3.5
  45. },
  46. "unit": "s",
  47. "labels": {
  48. "test": "phases",
  49. "ended": "false"
  50. }
  51. }
  52. ]
  53. }`))
  54. Expect(timer.PrintHumanReadable()).To(Equal(`Phase 001-one: 5.5s so far
  55. Phase 033-two: 3.5s
  56. `))
  57. setCurrentTimeSinceEpoch(7*time.Second + 500*time.Millisecond)
  58. phaseOne.End()
  59. Expect(timer.PrintJSON()).To(MatchJSON(`{
  60. "version": "v1",
  61. "dataItems": [
  62. {
  63. "data": {
  64. "001-one": 6.5,
  65. "033-two": 3.5
  66. },
  67. "unit": "s",
  68. "labels": {
  69. "test": "phases"
  70. }
  71. }
  72. ]
  73. }`))
  74. Expect(timer.PrintHumanReadable()).To(Equal(`Phase 001-one: 6.5s
  75. Phase 033-two: 3.5s
  76. `))
  77. }