From 290ee89a8c1fc0a9f791c0c1dc6c2f0e59a7173a Mon Sep 17 00:00:00 2001 From: Stuart Thomson Date: Tue, 4 Aug 2020 19:19:38 +0100 Subject: [PATCH 1/2] Allow container name property from sparse list When listing containers with `sparse=True` the container's name property does not work because there is no 'Name' attribue on the object returned by the Docker API. Instead the name is in the 'Names' attribute. Signed-off-by: Stuart Thomson --- docker/models/containers.py | 2 ++ tests/integration/models_containers_test.py | 3 ++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/docker/models/containers.py b/docker/models/containers.py index 0c2b855a..7ae1ad34 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -28,6 +28,8 @@ class Container(Model): """ if self.attrs.get('Name') is not None: return self.attrs['Name'].lstrip('/') + if self.attrs.get('Names') is not None: + return self.attrs['Names'][0].lstrip('/') @property def image(self): diff --git a/tests/integration/models_containers_test.py b/tests/integration/models_containers_test.py index eac4c979..c9e0d06b 100644 --- a/tests/integration/models_containers_test.py +++ b/tests/integration/models_containers_test.py @@ -210,7 +210,7 @@ class ContainerCollectionTest(BaseIntegrationTest): def test_list_sparse(self): client = docker.from_env(version=TEST_API_VERSION) container_id = client.containers.run( - "alpine", "sleep 300", detach=True).id + "alpine", "sleep 300", detach=True, name='a_container').id self.tmp_containers.append(container_id) containers = [c for c in client.containers.list(sparse=True) if c.id == container_id] @@ -220,6 +220,7 @@ class ContainerCollectionTest(BaseIntegrationTest): assert container.attrs['Image'] == 'alpine' assert container.status == 'running' assert container.image == client.images.get('alpine') + assert container.name == 'a_container' with pytest.raises(docker.errors.DockerException): container.labels From 2bf5d56c73a03fc314e5bd539cad5018a9e24d5e Mon Sep 17 00:00:00 2001 From: Stuart Thomson Date: Sat, 29 Aug 2020 22:45:22 +0100 Subject: [PATCH 2/2] Update name behaviour to match Docker CLI Signed-off-by: Stuart Thomson --- docker/models/containers.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docker/models/containers.py b/docker/models/containers.py index 7ae1ad34..4f27a1d4 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -29,7 +29,11 @@ class Container(Model): if self.attrs.get('Name') is not None: return self.attrs['Name'].lstrip('/') if self.attrs.get('Names') is not None: - return self.attrs['Names'][0].lstrip('/') + stripped_names = [name.lstrip('/') for name in self.attrs['Names']] + for name in stripped_names: + if '/' not in name: + return name + return ','.join(stripped_names) @property def image(self):