__init__.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """
  17. Utilities for running the unit tests
  18. """
  19. from asyncio import Future
  20. from typing import Any, Awaitable, TypeVar
  21. TV = TypeVar("TV")
  22. def get_awaitable_result(awaitable: Awaitable[TV]) -> TV:
  23. """Get the result from an Awaitable which should have completed
  24. Asserts that the given awaitable has a result ready, and returns its value
  25. """
  26. i = awaitable.__await__()
  27. try:
  28. next(i)
  29. except StopIteration as e:
  30. # awaitable returned a result
  31. return e.value
  32. # if next didn't raise, the awaitable hasn't completed.
  33. raise Exception("awaitable has not yet completed")
  34. def make_awaitable(result: Any) -> Awaitable[Any]:
  35. """
  36. Makes an awaitable, suitable for mocking an `async` function.
  37. This uses Futures as they can be awaited multiple times so can be returned
  38. to multiple callers.
  39. """
  40. future = Future() # type: ignore
  41. future.set_result(result)
  42. return future