|
| 1 | +# |
| 2 | +# This file is licensed under the Affero General Public License (AGPL) version 3. |
| 3 | +# |
| 4 | +# Copyright (C) 2025 Element Creations Ltd |
| 5 | +# |
| 6 | +# This program is free software: you can redistribute it and/or modify |
| 7 | +# it under the terms of the GNU Affero General Public License as |
| 8 | +# published by the Free Software Foundation, either version 3 of the |
| 9 | +# License, or (at your option) any later version. |
| 10 | +# |
| 11 | +# See the GNU Affero General Public License for more details: |
| 12 | +# <https://www.gnu.org/licenses/agpl-3.0.html>. |
| 13 | +# |
| 14 | +# |
| 15 | + |
| 16 | +import weakref |
| 17 | + |
| 18 | +from synapse.util.duration import Duration |
| 19 | + |
| 20 | +from tests.unittest import HomeserverTestCase |
| 21 | + |
| 22 | + |
| 23 | +class ClockTestCase(HomeserverTestCase): |
| 24 | + def test_looping_calls_are_gced(self) -> None: |
| 25 | + """Test that looping calls are garbage collected after being stopped. |
| 26 | +
|
| 27 | + The `Clock` tracks looping calls so to allow stopping of all looping |
| 28 | + calls via the clock. |
| 29 | + """ |
| 30 | + clock = self.hs.get_clock() |
| 31 | + |
| 32 | + # Create a new looping call, and take a weakref to it. |
| 33 | + call = clock.looping_call(lambda: None, Duration(seconds=1)) |
| 34 | + |
| 35 | + weak_call = weakref.ref(call) |
| 36 | + |
| 37 | + # Stop the looping call. It should get garbage collected after this. |
| 38 | + call.stop() |
| 39 | + |
| 40 | + # Delete our strong reference to the call (otherwise it won't get garbage collected). |
| 41 | + del call |
| 42 | + |
| 43 | + # Check that the call has been garbage collected. |
| 44 | + self.assertIsNone(weak_call()) |
| 45 | + |
| 46 | + def test_looping_calls_stopped_on_clock_shutdown(self) -> None: |
| 47 | + """Test that looping calls are stopped when the clock is shut down.""" |
| 48 | + clock = self.hs.get_clock() |
| 49 | + |
| 50 | + was_called = False |
| 51 | + |
| 52 | + def on_call() -> None: |
| 53 | + nonlocal was_called |
| 54 | + was_called = True |
| 55 | + |
| 56 | + # Create a new looping call. |
| 57 | + call = clock.looping_call(on_call, Duration(seconds=1)) |
| 58 | + weak_call = weakref.ref(call) |
| 59 | + del call # Remove our strong reference to the call. |
| 60 | + |
| 61 | + # The call should still exist. |
| 62 | + self.assertIsNotNone(weak_call()) |
| 63 | + |
| 64 | + # Advance the clock to trigger the call. |
| 65 | + self.reactor.advance(2) |
| 66 | + self.assertTrue(was_called) |
| 67 | + |
| 68 | + # Shut down the clock, which should stop the looping call. |
| 69 | + clock.shutdown() |
| 70 | + |
| 71 | + # The call should have been garbage collected. |
| 72 | + self.assertIsNone(weak_call()) |
| 73 | + |
| 74 | + # Advance the clock again; the call should not be called again. |
| 75 | + was_called = False |
| 76 | + self.reactor.advance(2) |
| 77 | + self.assertFalse(was_called) |
0 commit comments