test_phone_home.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright 2019 Matrix.org Foundation C.I.C.
  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. import resource
  15. from unittest import mock
  16. from synapse.app.phone_stats_home import phone_stats_home
  17. from synapse.types import JsonDict
  18. from tests.unittest import HomeserverTestCase
  19. class PhoneHomeStatsTestCase(HomeserverTestCase):
  20. def test_performance_frozen_clock(self) -> None:
  21. """
  22. If time doesn't move, don't error out.
  23. """
  24. past_stats = [
  25. (self.hs.get_clock().time(), resource.getrusage(resource.RUSAGE_SELF))
  26. ]
  27. stats: JsonDict = {}
  28. self.get_success(phone_stats_home(self.hs, stats, past_stats))
  29. self.assertEqual(stats["cpu_average"], 0)
  30. def test_performance_100(self) -> None:
  31. """
  32. 1 second of usage over 1 second is 100% CPU usage.
  33. """
  34. real_res = resource.getrusage(resource.RUSAGE_SELF)
  35. old_resource = mock.Mock(spec=real_res)
  36. old_resource.ru_utime = real_res.ru_utime - 1
  37. old_resource.ru_stime = real_res.ru_stime
  38. old_resource.ru_maxrss = real_res.ru_maxrss
  39. past_stats = [(self.hs.get_clock().time(), old_resource)]
  40. stats: JsonDict = {}
  41. self.reactor.advance(1)
  42. # `old_resource` has type `Mock` instead of `struct_rusage`
  43. self.get_success(phone_stats_home(self.hs, stats, past_stats)) # type: ignore[arg-type]
  44. self.assertApproximates(stats["cpu_average"], 100, tolerance=2.5)