Skip to content

Commit

Permalink
Add stream_logs arg to compose start (gabrieldemarmiesse#508)
Browse files Browse the repository at this point in the history
  • Loading branch information
HemaZ authored and fuentes73 committed Nov 29, 2023
1 parent e0eccd1 commit f94570b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
31 changes: 29 additions & 2 deletions python_on_whales/components/compose/cli_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -743,20 +743,47 @@ def run(
else:
return result

def start(self, services: Union[str, List[str], None] = None):
@overload
def start(
self,
services: Union[str, List[str], None] = ...,
stream_logs: Literal[True] = ...,
) -> Iterable[Tuple[str, bytes]]:
...

@overload
def start(
self,
services: Union[str, List[str], None] = ...,
stream_logs: Literal[False] = ...,
) -> None:
...

def start(
self, services: Union[str, List[str], None] = None, stream_logs: bool = False
):
"""Start the specified services.
Parameters:
services: The names of one or more services to start.
If `None` (the default), it means all services will start.
If an empty list is provided, this function call is a no-op.
stream_logs: If `False` this function returns None. If `True`, this
function returns an Iterable of `Tuple[str, bytes]` where the first element
is the type of log (`"stdin"` or `"stdout"`). The second element is the log itself,
as bytes, you'll need to call `.decode()` if you want the logs as `str`.
See [the streaming guide](https://gabrieldemarmiesse.github.io/python-on-whales/user_guide/docker_run/#stream-the-output) if you are
not familiar with the streaming of logs in Python-on-whales.
"""
full_cmd = self.docker_compose_cmd + ["start"]
if services == []:
return
elif services is not None:
full_cmd += to_list(services)
run(full_cmd)
if stream_logs:
return stream_stdout_and_stderr(full_cmd)
else:
run(full_cmd)

@overload
def stop(
Expand Down
13 changes: 13 additions & 0 deletions tests/python_on_whales/components/test_compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,19 @@ def test_docker_compose_start():
docker.compose.down(timeout=1)


def test_docker_compose_start_stream():
docker.compose.create(["busybox"])
assert not docker.compose.ps(all=True)[0].state.running
assert docker.compose.ps() == []
logs = list(docker.compose.start(["busybox"], stream_logs=True))
assert len(logs) >= 2
full_logs_as_binary = b"".join(log for _, log in logs)
assert b"Container components_busybox_1 Starting" in full_logs_as_binary
assert b"Container components_busybox_1 Started" in full_logs_as_binary
assert docker.compose.ps()[0].state.running
docker.compose.down(timeout=1)


def test_docker_compose_restart():
docker.compose.up(["my_service"], detach=True)
time.sleep(2)
Expand Down

0 comments on commit f94570b

Please sign in to comment.