unittest.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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(
  31. twisted.logger.LogLevel.levelWithName(log_level),
  32. log_entry.replace("{", r"(").replace("}", r")"),
  33. )
  34. handler = ToTwistedHandler()
  35. formatter = logging.Formatter(log_format)
  36. handler.setFormatter(formatter)
  37. handler.addFilter(LoggingContextFilter(request=""))
  38. rootLogger.addHandler(handler)
  39. def around(target):
  40. """A CLOS-style 'around' modifier, which wraps the original method of the
  41. given instance with another piece of code.
  42. @around(self)
  43. def method_name(orig, *args, **kwargs):
  44. return orig(*args, **kwargs)
  45. """
  46. def _around(code):
  47. name = code.__name__
  48. orig = getattr(target, name)
  49. def new(*args, **kwargs):
  50. return code(orig, *args, **kwargs)
  51. setattr(target, name, new)
  52. return _around
  53. class TestCase(unittest.TestCase):
  54. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  55. attributes on both itself and its individual test methods, to override the
  56. root logger's logging level while that test (case|method) runs."""
  57. def __init__(self, methodName, *args, **kwargs):
  58. super(TestCase, self).__init__(methodName, *args, **kwargs)
  59. method = getattr(self, methodName)
  60. level = getattr(method, "loglevel", getattr(self, "loglevel", logging.ERROR))
  61. @around(self)
  62. def setUp(orig):
  63. # enable debugging of delayed calls - this means that we get a
  64. # traceback when a unit test exits leaving things on the reactor.
  65. twisted.internet.base.DelayedCall.debug = True
  66. old_level = logging.getLogger().level
  67. if old_level != level:
  68. @around(self)
  69. def tearDown(orig):
  70. ret = orig()
  71. logging.getLogger().setLevel(old_level)
  72. return ret
  73. logging.getLogger().setLevel(level)
  74. return orig()
  75. def assertObjectHasAttributes(self, attrs, obj):
  76. """Asserts that the given object has each of the attributes given, and
  77. that the value of each matches according to assertEquals."""
  78. for (key, value) in attrs.items():
  79. if not hasattr(obj, key):
  80. raise AssertionError("Expected obj to have a '.%s'" % key)
  81. try:
  82. self.assertEquals(attrs[key], getattr(obj, key))
  83. except AssertionError as e:
  84. raise (type(e))(e.message + " for '.%s'" % key)
  85. def assert_dict(self, required, actual):
  86. """Does a partial assert of a dict.
  87. Args:
  88. required (dict): The keys and value which MUST be in 'actual'.
  89. actual (dict): The test result. Extra keys will not be checked.
  90. """
  91. for key in required:
  92. self.assertEquals(required[key], actual[key],
  93. msg="%s mismatch. %s" % (key, actual))
  94. def DEBUG(target):
  95. """A decorator to set the .loglevel attribute to logging.DEBUG.
  96. Can apply to either a TestCase or an individual test method."""
  97. target.loglevel = logging.DEBUG
  98. return target