Skip to content

Commit c614ec9

Browse files
committed
Release resources in test
1 parent 25485b9 commit c614ec9

File tree

1 file changed

+34
-27
lines changed

1 file changed

+34
-27
lines changed

tests/test_asyncio/test_cwe_404.py

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -41,25 +41,32 @@ def set_delay(self, delay: float = 0.0):
4141
Allow to override the delay for parts of tests which aren't time dependent,
4242
to speed up execution.
4343
"""
44-
old = self.delay
44+
old_delay = self.delay
4545
self.delay = delay
4646
try:
4747
yield
4848
finally:
49-
self.delay = old
49+
self.delay = old_delay
5050

5151
async def handle(self, reader, writer):
5252
# establish connection to redis
5353
redis_reader, redis_writer = await asyncio.open_connection(*self.redis_addr)
54-
pipe1 = asyncio.create_task(
55-
self.pipe(reader, redis_writer, "to redis:", self.send_event)
56-
)
57-
pipe2 = asyncio.create_task(self.pipe(redis_reader, writer, "from redis:"))
58-
await asyncio.gather(pipe1, pipe2)
54+
try:
55+
pipe1 = asyncio.create_task(
56+
self.pipe(reader, redis_writer, "to redis:", self.send_event)
57+
)
58+
pipe2 = asyncio.create_task(self.pipe(redis_reader, writer, "from redis:"))
59+
await asyncio.gather(pipe1, pipe2)
60+
finally:
61+
redis_writer.close()
5962

6063
async def stop(self):
6164
# clean up enough so that we can reuse the looper
6265
self.ROUTINE.cancel()
66+
try:
67+
await self.ROUTINE
68+
except asyncio.CancelledError:
69+
pass
6370
loop = self.server.get_loop()
6471
await loop.shutdown_asyncgens()
6572

@@ -183,25 +190,25 @@ async def test_cluster(request, redis_addr):
183190
dp = DelayProxy(addr=("127.0.0.1", 5381), redis_addr=redis_addr)
184191
await dp.start()
185192

186-
r = RedisCluster.from_url("redis://127.0.0.1:5381")
187-
await r.initialize()
188-
await r.set("foo", "foo")
189-
await r.set("bar", "bar")
190-
191-
async def op(r):
192-
with dp.set_delay(delay):
193-
return await r.get("foo")
194-
195-
dp.send_event.clear()
196-
t = asyncio.create_task(op(r))
197-
await dp.send_event.wait()
198-
await asyncio.sleep(0.01)
199-
t.cancel()
200-
with pytest.raises(asyncio.CancelledError):
201-
await t
202-
203-
assert await r.get("bar") == b"bar"
204-
assert await r.ping()
205-
assert await r.get("foo") == b"foo"
193+
with contextlib.closing(RedisCluster.from_url("redis://127.0.0.1:5381")) as r:
194+
await r.initialize()
195+
await r.set("foo", "foo")
196+
await r.set("bar", "bar")
197+
198+
async def op(r):
199+
with dp.set_delay(delay):
200+
return await r.get("foo")
201+
202+
dp.send_event.clear()
203+
t = asyncio.create_task(op(r))
204+
await dp.send_event.wait()
205+
await asyncio.sleep(0.01)
206+
t.cancel()
207+
with pytest.raises(asyncio.CancelledError):
208+
await t
209+
210+
assert await r.get("bar") == b"bar"
211+
assert await r.ping()
212+
assert await r.get("foo") == b"foo"
206213

207214
await dp.stop()

0 commit comments

Comments
 (0)