Skip to content

Commit

Permalink
Automatically create task for events
Browse files Browse the repository at this point in the history
  • Loading branch information
cecton committed Jul 26, 2017
1 parent 7097cb1 commit 20965e0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
13 changes: 11 additions & 2 deletions aiodocker/docker.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,13 +485,16 @@ def __init__(self, docker):
self.docker = docker
self.channel = Channel()
self.json_stream = None
self.task = None

def listen(self):
warnings.warn("use subscribe() method instead",
DeprecationWarning, stacklevel=2)
return self.channel.subscribe()

def subscribe(self):
def subscribe(self, create_task=True):
if create_task:
self.task = self.docker.loop.create_task(self.run())
return self.channel.subscribe()

def _transform_event(self, data):
Expand Down Expand Up @@ -531,8 +534,14 @@ async def run(self, **params):
self.json_stream = None

async def stop(self):
if self.json_stream:
if self.json_stream is not None:
await self.json_stream.close()
if self.task:
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass


class DockerLog:
Expand Down
22 changes: 22 additions & 0 deletions tests/test_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import asyncio

import pytest


def test_events_default_task(docker):
docker.events.subscribe()
assert docker.events.task is not None
docker.loop.run_until_complete(docker.events.stop())
assert docker.events.task.done()
assert docker.events.json_stream is None


def test_events_provided_task(docker):
task = docker.loop.create_task(docker.events.run())
docker.events.subscribe(create_task=False)
assert docker.events.task is None
docker.loop.run_until_complete(docker.events.stop())
assert docker.events.json_stream is None
task.cancel()
with pytest.raises(asyncio.CancelledError):
docker.loop.run_until_complete(task)
2 changes: 0 additions & 2 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,6 @@ async def test_port(docker, testing_images, redis_container):

@pytest.mark.asyncio
async def test_events(docker, testing_images, event_loop):
monitor_task = event_loop.create_task(docker.events.run())
subscriber = docker.events.subscribe()

# Do some stuffs to generate events.
Expand Down Expand Up @@ -232,4 +231,3 @@ async def test_events(docker, testing_images, event_loop):
break

assert events_occurred == ['create', 'start', 'kill', 'die', 'destroy']
monitor_task.cancel()

0 comments on commit 20965e0

Please sign in to comment.