1
0

test_timeout.py 2.5 KB

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