unittest.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket 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. import logging
  16. import twisted
  17. import twisted.logger
  18. from twisted.trial import unittest
  19. from synapse.util.logcontext import LoggingContextFilter
  20. # Set up putting Synapse's logs into Trial's.
  21. rootLogger = logging.getLogger()
  22. log_format = (
  23. "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(request)s - %(message)s"
  24. )
  25. class ToTwistedHandler(logging.Handler):
  26. tx_log = twisted.logger.Logger()
  27. def emit(self, record):
  28. log_entry = self.format(record)
  29. log_level = record.levelname.lower().replace('warning', 'warn')
  30. self.tx_log.emit(twisted.logger.LogLevel.levelWithName(log_level), log_entry)
  31. handler = ToTwistedHandler()
  32. formatter = logging.Formatter(log_format)
  33. handler.setFormatter(formatter)
  34. handler.addFilter(LoggingContextFilter(request=""))
  35. rootLogger.addHandler(handler)
  36. def around(target):
  37. """A CLOS-style 'around' modifier, which wraps the original method of the
  38. given instance with another piece of code.
  39. @around(self)
  40. def method_name(orig, *args, **kwargs):
  41. return orig(*args, **kwargs)
  42. """
  43. def _around(code):
  44. name = code.__name__
  45. orig = getattr(target, name)
  46. def new(*args, **kwargs):
  47. return code(orig, *args, **kwargs)
  48. setattr(target, name, new)
  49. return _around
  50. class TestCase(unittest.TestCase):
  51. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  52. attributes on both itself and its individual test methods, to override the
  53. root logger's logging level while that test (case|method) runs."""
  54. def __init__(self, methodName, *args, **kwargs):
  55. super(TestCase, self).__init__(methodName, *args, **kwargs)
  56. method = getattr(self, methodName)
  57. level = getattr(method, "loglevel", getattr(self, "loglevel", logging.ERROR))
  58. @around(self)
  59. def setUp(orig):
  60. # enable debugging of delayed calls - this means that we get a
  61. # traceback when a unit test exits leaving things on the reactor.
  62. twisted.internet.base.DelayedCall.debug = True
  63. old_level = logging.getLogger().level
  64. if old_level != level:
  65. @around(self)
  66. def tearDown(orig):
  67. ret = orig()
  68. logging.getLogger().setLevel(old_level)
  69. return ret
  70. logging.getLogger().setLevel(level)
  71. return orig()
  72. def assertObjectHasAttributes(self, attrs, obj):
  73. """Asserts that the given object has each of the attributes given, and
  74. that the value of each matches according to assertEquals."""
  75. for (key, value) in attrs.items():
  76. if not hasattr(obj, key):
  77. raise AssertionError("Expected obj to have a '.%s'" % key)
  78. try:
  79. self.assertEquals(attrs[key], getattr(obj, key))
  80. except AssertionError as e:
  81. raise (type(e))(e.message + " for '.%s'" % key)
  82. def DEBUG(target):
  83. """A decorator to set the .loglevel attribute to logging.DEBUG.
  84. Can apply to either a TestCase or an individual test method."""
  85. target.loglevel = logging.DEBUG
  86. return target