Skip to content

Commit

Permalink
feat(service): Add docker service ls --filter option
Browse files Browse the repository at this point in the history
  • Loading branch information
fuentes73 committed Mar 9, 2024
1 parent bf1c60d commit 9ffdd5e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
7 changes: 6 additions & 1 deletion python_on_whales/components/service/cli_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,13 +353,18 @@ def logs(
else:
return "".join(x[1].decode() for x in iterator)

def list(self) -> List[Service]:
def list(self, filters: Dict[str, str] = {}) -> List[Service]:
"""Returns the list of services
Parameters:
filters: If you want to filter the results based on a given condition.
For example, `docker.service.list(filters=dict(label="my_label=hello"))`.
# Returns
A `List[python_on_whales.Services]`
"""
full_cmd = self.docker_cmd + ["service", "list", "--quiet"]
full_cmd.add_args_list("--filter", format_dict_for_cli(filters))

ids_truncated = run(full_cmd).splitlines()

Expand Down
25 changes: 24 additions & 1 deletion tests/python_on_whales/components/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from python_on_whales import DockerClient
from python_on_whales.components.service.models import ServiceInspectResult
from python_on_whales.exceptions import NoSuchService, NotASwarmManager
from python_on_whales.test_utils import get_all_jsons
from python_on_whales.test_utils import get_all_jsons, random_name


@pytest.mark.parametrize("json_file", get_all_jsons("services"))
Expand Down Expand Up @@ -45,6 +45,29 @@ def test_get_list_of_services(docker_client: DockerClient):
assert [my_service] == list_of_services


@pytest.mark.usefixtures("swarm_mode")
def test_filters(docker_client: DockerClient):
random_label_value = random_name()
with docker_client.service.create(
"busybox",
["sleep", "infinity"],
labels=dict(dodo=random_label_value),
) as my_service:
with docker_client.service.create(
"busybox",
["sleep", "infinity"],
labels=dict(dodo="something"),
):
expected_services = docker_client.service.list(
filters=dict(label=f"dodo={random_label_value}")
)
assert expected_services == [my_service]
no_expected_services = docker_client.service.list(
filters=dict(label=f"dodo={random_name()}")
)
assert len(no_expected_services) == 0


@pytest.mark.usefixtures("swarm_mode")
def test_get_list_of_services_no_services(docker_client: DockerClient):
assert docker_client.service.list() == []
Expand Down

0 comments on commit 9ffdd5e

Please sign in to comment.