test_timeout.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. # -*- coding: utf-8 -*-
  2. from __future__ import absolute_import, print_function, unicode_literals
  3. import logging
  4. import time
  5. from salt.utils.timeout import wait_for
  6. from tests.support.helpers import slowTest
  7. from tests.support.unit import TestCase
  8. log = logging.getLogger(__name__)
  9. def return_something_after(seconds, something=True):
  10. start = time.time()
  11. end = start + seconds
  12. log.debug("Will return %s at %s", something, end)
  13. def actual():
  14. t = time.time()
  15. condition = t >= end
  16. log.debug("Return something at %s ? %s", t, condition)
  17. if condition:
  18. return something
  19. else:
  20. return False
  21. return actual
  22. def return_args_after(seconds):
  23. start = time.time()
  24. end = start + seconds
  25. def actual(*args):
  26. if time.time() >= end:
  27. return args
  28. else:
  29. return False
  30. return actual
  31. def return_kwargs_after(seconds):
  32. start = time.time()
  33. end = start + seconds
  34. def actual(**kwargs):
  35. if time.time() >= end:
  36. return kwargs
  37. else:
  38. return False
  39. return actual
  40. class WaitForTests(TestCase):
  41. def setUp(self):
  42. self.true_after_1s = return_something_after(1)
  43. self.self_after_1s = return_something_after(1, something=self)
  44. def tearDown(self):
  45. del self.true_after_1s
  46. del self.self_after_1s
  47. @slowTest
  48. def test_wait_for_true(self):
  49. ret = wait_for(self.true_after_1s, timeout=2, step=0.5)
  50. self.assertTrue(ret)
  51. @slowTest
  52. def test_wait_for_self(self):
  53. ret = wait_for(self.self_after_1s, timeout=2, step=0.5)
  54. self.assertEqual(ret, self)
  55. def test_wait_for_too_long(self):
  56. ret = wait_for(self.true_after_1s, timeout=0.5, step=0.1, default=False)
  57. self.assertFalse(ret)
  58. @slowTest
  59. def test_wait_for_with_big_step(self):
  60. ret = wait_for(self.true_after_1s, timeout=1.5, step=2)
  61. self.assertTrue(ret)
  62. @slowTest
  63. def test_wait_for_custom_args(self):
  64. args_after_1s = return_args_after(1)
  65. args = ("one", "two")
  66. ret = wait_for(args_after_1s, timeout=2, step=0.5, func_args=args)
  67. self.assertEqual(ret, args)
  68. @slowTest
  69. def test_wait_for_custom_kwargs(self):
  70. kwargs_after_1s = return_kwargs_after(1)
  71. kwargs = {"one": 1, "two": 2}
  72. ret = wait_for(kwargs_after_1s, timeout=2, step=0.5, func_kwargs=kwargs)
  73. self.assertEqual(ret, kwargs)
  74. def test_return_false(self):
  75. ret = self.true_after_1s()
  76. self.assertFalse(ret)