Skip to content

Commit a1b73b5

Browse files
authored
Resolved race condition during Redis backend teardown (#418)
1 parent cadcc9e commit a1b73b5

File tree

1 file changed

+21
-7
lines changed
  • src/pytest_celery/vendors/redis/backend

1 file changed

+21
-7
lines changed

src/pytest_celery/vendors/redis/backend/api.py

+21-7
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,30 @@
88

99
import gc
1010

11+
from celery.result import AsyncResult
12+
1113
from pytest_celery.api.backend import CeleryTestBackend
1214

1315

1416
class RedisTestBackend(CeleryTestBackend):
1517
def teardown(self) -> None:
16-
# When a test that has a AsyncResult object is finished
17-
# there's a race condition between the AsyncResult object
18-
# and the Redis container. The AsyncResult object tries
19-
# to release the connection but the Redis container has already
20-
# exited. This causes a warning to be logged. To avoid this
21-
# warning to our best effort we force a garbage collection here.
22-
gc.collect(1)
18+
"""When a test that has a AsyncResult object is finished there's a race
19+
condition between the AsyncResult object and the Redis container.
20+
21+
The AsyncResult object tries to release the connection but the
22+
Redis container has already exited.
23+
"""
24+
# First, force a garbage collection to clean up unreachable objects
25+
gc.collect()
26+
27+
# Next, find all live AsyncResult objects and clean them up
28+
async_results = [obj for obj in gc.get_objects() if isinstance(obj, AsyncResult)]
29+
30+
for async_result in async_results:
31+
try:
32+
# Remove the backend reference to prevent interaction with Redis
33+
async_result.backend = None
34+
except Exception:
35+
pass
36+
2337
super().teardown()

0 commit comments

Comments
 (0)