metrics_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package metrics
  15. import (
  16. "expvar"
  17. "testing"
  18. )
  19. // TestPublish tests function Publish and related creation functions.
  20. func TestPublish(t *testing.T) {
  21. defer reset()
  22. Publish("string", new(expvar.String))
  23. NewCounter("counter")
  24. NewGauge("gauge")
  25. NewMap("map")
  26. keys := []string{"counter", "gauge", "map", "string"}
  27. i := 0
  28. Do(func(kv expvar.KeyValue) {
  29. if kv.Key != keys[i] {
  30. t.Errorf("#%d: key = %s, want %s", i, kv.Key, keys[i])
  31. }
  32. i++
  33. })
  34. }
  35. func TestDuplicatePublish(t *testing.T) {
  36. defer reset()
  37. num1 := new(expvar.Int)
  38. num1.Set(10)
  39. Publish("number", num1)
  40. num2 := new(expvar.Int)
  41. num2.Set(20)
  42. Publish("number", num2)
  43. if g := Get("number").String(); g != "20" {
  44. t.Errorf("number str = %s, want %s", g, "20")
  45. }
  46. }
  47. // TestMap tests the basic usage of Map.
  48. func TestMap(t *testing.T) {
  49. m := &Map{Map: new(expvar.Map).Init()}
  50. c := m.NewCounter("number")
  51. c.Add()
  52. c.AddBy(10)
  53. if w := "11"; c.String() != w {
  54. t.Errorf("counter = %s, want %s", c, w)
  55. }
  56. g := m.NewGauge("price")
  57. g.Set(100)
  58. if w := "100"; g.String() != w {
  59. t.Errorf("gauge = %s, want %s", g, w)
  60. }
  61. if w := `{"number": 11, "price": 100}`; m.String() != w {
  62. t.Errorf("map = %s, want %s", m, w)
  63. }
  64. m.Delete("price")
  65. if w := `{"number": 11}`; m.String() != w {
  66. t.Errorf("map after deletion = %s, want %s", m, w)
  67. }
  68. }