test_metrics.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from synapse.metrics import InFlightGauge
  16. from tests import unittest
  17. class TestMauLimit(unittest.TestCase):
  18. def test_basic(self):
  19. gauge = InFlightGauge(
  20. "test1", "",
  21. labels=["test_label"],
  22. sub_metrics=["foo", "bar"],
  23. )
  24. def handle1(metrics):
  25. metrics.foo += 2
  26. metrics.bar = max(metrics.bar, 5)
  27. def handle2(metrics):
  28. metrics.foo += 3
  29. metrics.bar = max(metrics.bar, 7)
  30. gauge.register(("key1",), handle1)
  31. self.assert_dict({
  32. "test1_total": {("key1",): 1},
  33. "test1_foo": {("key1",): 2},
  34. "test1_bar": {("key1",): 5},
  35. }, self.get_metrics_from_gauge(gauge))
  36. gauge.unregister(("key1",), handle1)
  37. self.assert_dict({
  38. "test1_total": {("key1",): 0},
  39. "test1_foo": {("key1",): 0},
  40. "test1_bar": {("key1",): 0},
  41. }, self.get_metrics_from_gauge(gauge))
  42. gauge.register(("key1",), handle1)
  43. gauge.register(("key2",), handle2)
  44. self.assert_dict({
  45. "test1_total": {("key1",): 1, ("key2",): 1},
  46. "test1_foo": {("key1",): 2, ("key2",): 3},
  47. "test1_bar": {("key1",): 5, ("key2",): 7},
  48. }, self.get_metrics_from_gauge(gauge))
  49. gauge.unregister(("key2",), handle2)
  50. gauge.register(("key1",), handle2)
  51. self.assert_dict({
  52. "test1_total": {("key1",): 2, ("key2",): 0},
  53. "test1_foo": {("key1",): 5, ("key2",): 0},
  54. "test1_bar": {("key1",): 7, ("key2",): 0},
  55. }, self.get_metrics_from_gauge(gauge))
  56. def get_metrics_from_gauge(self, gauge):
  57. results = {}
  58. for r in gauge.collect():
  59. results[r.name] = {
  60. tuple(labels[x] for x in gauge.labels): value
  61. for _, labels, value in r.samples
  62. }
  63. return results