__init__.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright 2019 New Vector Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C
  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. """
  16. Utilities for running the unit tests
  17. """
  18. import sys
  19. import warnings
  20. from asyncio import Future
  21. from typing import Any, Awaitable, Callable, TypeVar
  22. from unittest.mock import Mock
  23. import attr
  24. from twisted.python.failure import Failure
  25. from twisted.web.client import ResponseDone
  26. TV = TypeVar("TV")
  27. def get_awaitable_result(awaitable: Awaitable[TV]) -> TV:
  28. """Get the result from an Awaitable which should have completed
  29. Asserts that the given awaitable has a result ready, and returns its value
  30. """
  31. i = awaitable.__await__()
  32. try:
  33. next(i)
  34. except StopIteration as e:
  35. # awaitable returned a result
  36. return e.value
  37. # if next didn't raise, the awaitable hasn't completed.
  38. raise Exception("awaitable has not yet completed")
  39. def make_awaitable(result: Any) -> Awaitable[Any]:
  40. """
  41. Makes an awaitable, suitable for mocking an `async` function.
  42. This uses Futures as they can be awaited multiple times so can be returned
  43. to multiple callers.
  44. """
  45. future = Future() # type: ignore
  46. future.set_result(result)
  47. return future
  48. def setup_awaitable_errors() -> Callable[[], None]:
  49. """
  50. Convert warnings from a non-awaited coroutines into errors.
  51. """
  52. warnings.simplefilter("error", RuntimeWarning)
  53. # unraisablehook was added in Python 3.8.
  54. if not hasattr(sys, "unraisablehook"):
  55. return lambda: None
  56. # State shared between unraisablehook and check_for_unraisable_exceptions.
  57. unraisable_exceptions = []
  58. orig_unraisablehook = sys.unraisablehook # type: ignore
  59. def unraisablehook(unraisable):
  60. unraisable_exceptions.append(unraisable.exc_value)
  61. def cleanup():
  62. """
  63. A method to be used as a clean-up that fails a test-case if there are any new unraisable exceptions.
  64. """
  65. sys.unraisablehook = orig_unraisablehook # type: ignore
  66. if unraisable_exceptions:
  67. raise unraisable_exceptions.pop()
  68. sys.unraisablehook = unraisablehook # type: ignore
  69. return cleanup
  70. def simple_async_mock(return_value=None, raises=None) -> Mock:
  71. # AsyncMock is not available in python3.5, this mimics part of its behaviour
  72. async def cb(*args, **kwargs):
  73. if raises:
  74. raise raises
  75. return return_value
  76. return Mock(side_effect=cb)
  77. @attr.s
  78. class FakeResponse:
  79. """A fake twisted.web.IResponse object
  80. there is a similar class at treq.test.test_response, but it lacks a `phrase`
  81. attribute, and didn't support deliverBody until recently.
  82. """
  83. # HTTP response code
  84. code = attr.ib(type=int)
  85. # HTTP response phrase (eg b'OK' for a 200)
  86. phrase = attr.ib(type=bytes)
  87. # body of the response
  88. body = attr.ib(type=bytes)
  89. def deliverBody(self, protocol):
  90. protocol.dataReceived(self.body)
  91. protocol.connectionLost(Failure(ResponseDone()))