test_background_update.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. from tests import unittest
  2. from twisted.internet import defer
  3. from tests.utils import setup_test_homeserver
  4. from mock import Mock
  5. class BackgroundUpdateTestCase(unittest.TestCase):
  6. @defer.inlineCallbacks
  7. def setUp(self):
  8. hs = yield setup_test_homeserver() # type: synapse.server.HomeServer
  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. defer.returnValue(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(
  42. duration_ms * desired_count
  43. )
  44. self.assertIsNotNone(result)
  45. self.update_handler.assert_called_once_with(
  46. {"my_key": 1}, self.store.DEFAULT_BACKGROUND_BATCH_SIZE
  47. )
  48. # second step: complete the update
  49. @defer.inlineCallbacks
  50. def update(progress, count):
  51. yield self.store._end_background_update("test_update")
  52. defer.returnValue(count)
  53. self.update_handler.side_effect = update
  54. self.update_handler.reset_mock()
  55. result = yield self.store.do_next_background_update(
  56. duration_ms * desired_count
  57. )
  58. self.assertIsNotNone(result)
  59. self.update_handler.assert_called_once_with(
  60. {"my_key": 2}, desired_count
  61. )
  62. # third step: we don't expect to be called any more
  63. self.update_handler.reset_mock()
  64. result = yield self.store.do_next_background_update(
  65. duration_ms * desired_count
  66. )
  67. self.assertIsNone(result)
  68. self.assertFalse(self.update_handler.called)