From 1cd56b9f0c85af580c59597643a307b3177ab7c9 Mon Sep 17 00:00:00 2001 From: Frank Sachsenheim Date: Sat, 4 Mar 2017 00:22:19 +0100 Subject: [PATCH] Adds a 'labels' property to the container model The Docker API seems to respond with a 'null' value for the 'Labels' attribute from containers that were created with older Docker versions. An empty dictionary is returned in this case. Signed-off-by: Frank Sachsenheim --- docker/models/containers.py | 8 ++++++++ docs/containers.rst | 1 + tests/unit/fake_api.py | 2 +- tests/unit/models_containers_test.py | 5 +++++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docker/models/containers.py b/docker/models/containers.py index fb10ba90..493f1804 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -18,6 +18,14 @@ class Container(Model): if self.attrs.get('Name') is not None: return self.attrs['Name'].lstrip('/') + @property + def labels(self): + """ + The labels of a container as dictionary. + """ + result = self.attrs['Config'].get('Labels') + return result or {} + @property def status(self): """ diff --git a/docs/containers.rst b/docs/containers.rst index 20529b0e..b67a066d 100644 --- a/docs/containers.rst +++ b/docs/containers.rst @@ -25,6 +25,7 @@ Container objects .. autoattribute:: short_id .. autoattribute:: name .. autoattribute:: status + .. autoattribute:: labels .. py:attribute:: attrs The raw representation of this object from the server. diff --git a/tests/unit/fake_api.py b/tests/unit/fake_api.py index 2d0a0b45..2914b63a 100644 --- a/tests/unit/fake_api.py +++ b/tests/unit/fake_api.py @@ -134,7 +134,7 @@ def get_fake_inspect_container(tty=False): status_code = 200 response = { 'Id': FAKE_CONTAINER_ID, - 'Config': {'Privileged': True, 'Tty': tty}, + 'Config': {'Labels': {'foo': 'bar'}, 'Privileged': True, 'Tty': tty}, 'ID': FAKE_CONTAINER_ID, 'Image': 'busybox:latest', 'Name': 'foobar', diff --git a/tests/unit/models_containers_test.py b/tests/unit/models_containers_test.py index ae1bd12a..a5ef4a11 100644 --- a/tests/unit/models_containers_test.py +++ b/tests/unit/models_containers_test.py @@ -390,6 +390,11 @@ class ContainerTest(unittest.TestCase): container.kill(signal=5) client.api.kill.assert_called_with(FAKE_CONTAINER_ID, signal=5) + def test_labels(self): + client = make_fake_client() + container = client.containers.get(FAKE_CONTAINER_ID) + assert container.labels == {'foo': 'bar'} + def test_logs(self): client = make_fake_client() container = client.containers.get(FAKE_CONTAINER_ID)