test_background_update.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. from mock import Mock
  2. from twisted.internet import defer
  3. from tests import unittest
  4. from tests.utils import setup_test_homeserver
  5. class BackgroundUpdateTestCase(unittest.TestCase):
  6. @defer.inlineCallbacks
  7. def setUp(self):
  8. hs = yield setup_test_homeserver(self.addCleanup)
  9. self.store = hs.get_datastore()
  10. self.clock = hs.get_clock()
  11. self.update_handler = Mock()
  12. yield self.store.register_background_update_handler(
  13. "test_update", self.update_handler
  14. )
  15. # run the real background updates, to get them out the way
  16. # (perhaps we should run them as part of the test HS setup, since we
  17. # run all of the other schema setup stuff there?)
  18. while True:
  19. res = yield self.store.do_next_background_update(1000)
  20. if res is None:
  21. break
  22. @defer.inlineCallbacks
  23. def test_do_background_update(self):
  24. desired_count = 1000
  25. duration_ms = 42
  26. # first step: make a bit of progress
  27. @defer.inlineCallbacks
  28. def update(progress, count):
  29. self.clock.advance_time_msec(count * duration_ms)
  30. progress = {"my_key": progress["my_key"] + 1}
  31. yield self.store.runInteraction(
  32. "update_progress",
  33. self.store._background_update_progress_txn,
  34. "test_update",
  35. progress,
  36. )
  37. return count
  38. self.update_handler.side_effect = update
  39. yield self.store.start_background_update("test_update", {"my_key": 1})
  40. self.update_handler.reset_mock()
  41. result = yield self.store.do_next_background_update(duration_ms * desired_count)
  42. self.assertIsNotNone(result)
  43. self.update_handler.assert_called_once_with(
  44. {"my_key": 1}, self.store.DEFAULT_BACKGROUND_BATCH_SIZE
  45. )
  46. # second step: complete the update
  47. @defer.inlineCallbacks
  48. def update(progress, count):
  49. yield self.store._end_background_update("test_update")
  50. return count
  51. self.update_handler.side_effect = update
  52. self.update_handler.reset_mock()
  53. result = yield self.store.do_next_background_update(duration_ms * desired_count)
  54. self.assertIsNotNone(result)
  55. self.update_handler.assert_called_once_with({"my_key": 2}, desired_count)
  56. # third step: we don't expect to be called any more
  57. self.update_handler.reset_mock()
  58. result = yield self.store.do_next_background_update(duration_ms * desired_count)
  59. self.assertIsNone(result)
  60. self.assertFalse(self.update_handler.called)