unittest.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 twisted
  16. from twisted.trial import unittest
  17. import logging
  18. # logging doesn't have a "don't log anything at all EVARRRR setting,
  19. # but since the highest value is 50, 1000000 should do ;)
  20. NEVER = 1000000
  21. handler = logging.StreamHandler()
  22. handler.setFormatter(logging.Formatter(
  23. "%(levelname)s:%(name)s:%(message)s [%(pathname)s:%(lineno)d]"
  24. ))
  25. logging.getLogger().addHandler(handler)
  26. logging.getLogger().setLevel(NEVER)
  27. logging.getLogger("synapse.storage.SQL").setLevel(NEVER)
  28. logging.getLogger("synapse.storage.txn").setLevel(NEVER)
  29. def around(target):
  30. """A CLOS-style 'around' modifier, which wraps the original method of the
  31. given instance with another piece of code.
  32. @around(self)
  33. def method_name(orig, *args, **kwargs):
  34. return orig(*args, **kwargs)
  35. """
  36. def _around(code):
  37. name = code.__name__
  38. orig = getattr(target, name)
  39. def new(*args, **kwargs):
  40. return code(orig, *args, **kwargs)
  41. setattr(target, name, new)
  42. return _around
  43. class TestCase(unittest.TestCase):
  44. """A subclass of twisted.trial's TestCase which looks for 'loglevel'
  45. attributes on both itself and its individual test methods, to override the
  46. root logger's logging level while that test (case|method) runs."""
  47. def __init__(self, methodName, *args, **kwargs):
  48. super(TestCase, self).__init__(methodName, *args, **kwargs)
  49. method = getattr(self, methodName)
  50. level = getattr(method, "loglevel", getattr(self, "loglevel", NEVER))
  51. @around(self)
  52. def setUp(orig):
  53. # enable debugging of delayed calls - this means that we get a
  54. # traceback when a unit test exits leaving things on the reactor.
  55. twisted.internet.base.DelayedCall.debug = True
  56. old_level = logging.getLogger().level
  57. if old_level != level:
  58. @around(self)
  59. def tearDown(orig):
  60. ret = orig()
  61. logging.getLogger().setLevel(old_level)
  62. return ret
  63. logging.getLogger().setLevel(level)
  64. return orig()
  65. def assertObjectHasAttributes(self, attrs, obj):
  66. """Asserts that the given object has each of the attributes given, and
  67. that the value of each matches according to assertEquals."""
  68. for (key, value) in attrs.items():
  69. if not hasattr(obj, key):
  70. raise AssertionError("Expected obj to have a '.%s'" % key)
  71. try:
  72. self.assertEquals(attrs[key], getattr(obj, key))
  73. except AssertionError as e:
  74. raise (type(e))(e.message + " for '.%s'" % key)
  75. def DEBUG(target):
  76. """A decorator to set the .loglevel attribute to logging.DEBUG.
  77. Can apply to either a TestCase or an individual test method."""
  78. target.loglevel = logging.DEBUG
  79. return target