test_asyncio.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # coding: utf-8
  2. # Copyright 2016 Étienne Bersac
  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 asyncio
  16. import unittest
  17. import six
  18. from tenacity import RetryError
  19. from tenacity import _asyncio as tasyncio
  20. from tenacity import retry, stop_after_attempt
  21. from tenacity.tests.test_tenacity import NoIOErrorAfterCount
  22. def asynctest(callable_):
  23. callable_ = asyncio.coroutine(callable_)
  24. @six.wraps(callable_)
  25. def wrapper(*a, **kw):
  26. loop = asyncio.get_event_loop()
  27. return loop.run_until_complete(callable_(*a, **kw))
  28. return wrapper
  29. @retry
  30. @asyncio.coroutine
  31. def _retryable_coroutine(thing):
  32. yield from asyncio.sleep(0.00001)
  33. thing.go()
  34. @retry(stop=stop_after_attempt(2))
  35. @asyncio.coroutine
  36. def _retryable_coroutine_with_2_attempts(thing):
  37. yield from asyncio.sleep(0.00001)
  38. thing.go()
  39. class TestAsync(unittest.TestCase):
  40. @asynctest
  41. def test_retry(self):
  42. assert asyncio.iscoroutinefunction(_retryable_coroutine)
  43. thing = NoIOErrorAfterCount(5)
  44. yield from _retryable_coroutine(thing)
  45. assert thing.counter == thing.count
  46. @asynctest
  47. def test_stop_after_attempt(self):
  48. assert asyncio.iscoroutinefunction(
  49. _retryable_coroutine_with_2_attempts)
  50. thing = NoIOErrorAfterCount(2)
  51. try:
  52. yield from _retryable_coroutine_with_2_attempts(thing)
  53. except RetryError:
  54. assert thing.counter == 2
  55. def test_repr(self):
  56. repr(tasyncio.AsyncRetrying())
  57. if __name__ == '__main__':
  58. unittest.main()