__init__.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. # Copyright 2019-2021 The 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. """
  15. Utilities for running the unit tests
  16. """
  17. import json
  18. import sys
  19. import warnings
  20. from asyncio import Future
  21. from binascii import unhexlify
  22. from typing import TYPE_CHECKING, Any, Awaitable, Callable, Optional, Tuple, TypeVar
  23. from unittest.mock import Mock
  24. import attr
  25. import zope.interface
  26. from twisted.internet.interfaces import IProtocol
  27. from twisted.python.failure import Failure
  28. from twisted.web.client import ResponseDone
  29. from twisted.web.http import RESPONSES
  30. from twisted.web.http_headers import Headers
  31. from twisted.web.iweb import IResponse
  32. from synapse.types import JsonDict
  33. if TYPE_CHECKING:
  34. from sys import UnraisableHookArgs
  35. TV = TypeVar("TV")
  36. def get_awaitable_result(awaitable: Awaitable[TV]) -> TV:
  37. """Get the result from an Awaitable which should have completed
  38. Asserts that the given awaitable has a result ready, and returns its value
  39. """
  40. i = awaitable.__await__()
  41. try:
  42. next(i)
  43. except StopIteration as e:
  44. # awaitable returned a result
  45. return e.value
  46. # if next didn't raise, the awaitable hasn't completed.
  47. raise Exception("awaitable has not yet completed")
  48. def make_awaitable(result: TV) -> Awaitable[TV]:
  49. """
  50. Makes an awaitable, suitable for mocking an `async` function.
  51. This uses Futures as they can be awaited multiple times so can be returned
  52. to multiple callers.
  53. """
  54. future: Future[TV] = Future()
  55. future.set_result(result)
  56. return future
  57. def setup_awaitable_errors() -> Callable[[], None]:
  58. """
  59. Convert warnings from a non-awaited coroutines into errors.
  60. """
  61. warnings.simplefilter("error", RuntimeWarning)
  62. # unraisablehook was added in Python 3.8.
  63. if not hasattr(sys, "unraisablehook"):
  64. return lambda: None
  65. # State shared between unraisablehook and check_for_unraisable_exceptions.
  66. unraisable_exceptions = []
  67. orig_unraisablehook = sys.unraisablehook
  68. def unraisablehook(unraisable: "UnraisableHookArgs") -> None:
  69. unraisable_exceptions.append(unraisable.exc_value)
  70. def cleanup() -> None:
  71. """
  72. A method to be used as a clean-up that fails a test-case if there are any new unraisable exceptions.
  73. """
  74. sys.unraisablehook = orig_unraisablehook
  75. if unraisable_exceptions:
  76. exc = unraisable_exceptions.pop()
  77. assert exc is not None
  78. raise exc
  79. sys.unraisablehook = unraisablehook
  80. return cleanup
  81. def simple_async_mock(
  82. return_value: Optional[TV] = None, raises: Optional[Exception] = None
  83. ) -> Mock:
  84. # AsyncMock is not available in python3.5, this mimics part of its behaviour
  85. async def cb(*args: Any, **kwargs: Any) -> Optional[TV]:
  86. if raises:
  87. raise raises
  88. return return_value
  89. return Mock(side_effect=cb)
  90. # Type ignore: it does not fully implement IResponse, but is good enough for tests
  91. @zope.interface.implementer(IResponse)
  92. @attr.s(slots=True, frozen=True, auto_attribs=True)
  93. class FakeResponse: # type: ignore[misc]
  94. """A fake twisted.web.IResponse object
  95. there is a similar class at treq.test.test_response, but it lacks a `phrase`
  96. attribute, and didn't support deliverBody until recently.
  97. """
  98. version: Tuple[bytes, int, int] = (b"HTTP", 1, 1)
  99. # HTTP response code
  100. code: int = 200
  101. # body of the response
  102. body: bytes = b""
  103. headers: Headers = attr.Factory(Headers)
  104. @property
  105. def phrase(self) -> bytes:
  106. return RESPONSES.get(self.code, b"Unknown Status")
  107. @property
  108. def length(self) -> int:
  109. return len(self.body)
  110. def deliverBody(self, protocol: IProtocol) -> None:
  111. protocol.dataReceived(self.body)
  112. protocol.connectionLost(Failure(ResponseDone()))
  113. @classmethod
  114. def json(cls, *, code: int = 200, payload: JsonDict) -> "FakeResponse":
  115. headers = Headers({"Content-Type": ["application/json"]})
  116. body = json.dumps(payload).encode("utf-8")
  117. return cls(code=code, body=body, headers=headers)
  118. # A small image used in some tests.
  119. #
  120. # Resolution: 1×1, MIME type: image/png, Extension: png, Size: 67 B
  121. SMALL_PNG = unhexlify(
  122. b"89504e470d0a1a0a0000000d4948445200000001000000010806"
  123. b"0000001f15c4890000000a49444154789c63000100000500010d"
  124. b"0a2db40000000049454e44ae426082"
  125. )