|
21 | 21 | sys.path[0:0] = [""] |
22 | 22 |
|
23 | 23 | from pymongo.periodic_executor import _EXECUTORS |
24 | | -from test import client_context, unittest, IntegrationTest |
25 | | -from test.utils import single_client, one, connected, wait_until |
| 24 | + |
| 25 | +from test import unittest, IntegrationTest |
| 26 | +from test.utils import (connected, |
| 27 | + ServerAndTopologyEventListener, |
| 28 | + single_client, |
| 29 | + wait_until) |
26 | 30 |
|
27 | 31 |
|
28 | 32 | def unregistered(ref): |
29 | 33 | gc.collect() |
30 | 34 | return ref not in _EXECUTORS |
31 | 35 |
|
32 | 36 |
|
| 37 | +def get_executors(client): |
| 38 | + executors = [] |
| 39 | + for server in client._topology._servers.values(): |
| 40 | + executors.append(server._monitor._executor) |
| 41 | + executors.append(client._kill_cursors_executor) |
| 42 | + executors.append(client._topology._Topology__events_executor) |
| 43 | + return [e for e in executors if e is not None] |
| 44 | + |
| 45 | + |
| 46 | +def create_client(): |
| 47 | + listener = ServerAndTopologyEventListener() |
| 48 | + client = single_client(event_listeners=[listener]) |
| 49 | + connected(client) |
| 50 | + return client |
| 51 | + |
| 52 | + |
33 | 53 | class TestMonitor(IntegrationTest): |
34 | | - def test_atexit_hook(self): |
35 | | - client = single_client(client_context.host, client_context.port) |
36 | | - executor = one(client._topology._servers.values())._monitor._executor |
37 | | - connected(client) |
| 54 | + def test_cleanup_executors_on_client_del(self): |
| 55 | + client = create_client() |
| 56 | + executors = get_executors(client) |
| 57 | + self.assertEqual(len(executors), 3) |
38 | 58 |
|
39 | | - # The executor stores a weakref to itself in _EXECUTORS. |
40 | | - ref = one([r for r in _EXECUTORS.copy() if r() is executor]) |
| 59 | + # Each executor stores a weakref to itself in _EXECUTORS. |
| 60 | + executor_refs = [ |
| 61 | + (r, r()._name) for r in _EXECUTORS.copy() if r() in executors] |
41 | 62 |
|
42 | | - del executor |
| 63 | + del executors |
43 | 64 | del client |
44 | 65 |
|
45 | | - wait_until(partial(unregistered, ref), 'unregister executor', |
46 | | - timeout=5) |
| 66 | + for ref, name in executor_refs: |
| 67 | + wait_until(partial(unregistered, ref), |
| 68 | + 'unregister executor: %s' % (name,), |
| 69 | + timeout=5) |
| 70 | + |
| 71 | + def test_cleanup_executors_on_client_close(self): |
| 72 | + client = create_client() |
| 73 | + executors = get_executors(client) |
| 74 | + self.assertEqual(len(executors), 3) |
| 75 | + |
| 76 | + client.close() |
| 77 | + |
| 78 | + for executor in executors: |
| 79 | + wait_until(lambda: executor._stopped, |
| 80 | + 'closed executor: %s' % (executor._name,), |
| 81 | + timeout=5) |
47 | 82 |
|
48 | 83 |
|
49 | 84 | if __name__ == "__main__": |
|
0 commit comments