diff --git a/podman/domain/containers.py b/podman/domain/containers.py index d2ef2e3e..f7fdd340 100644 --- a/podman/domain/containers.py +++ b/podman/domain/containers.py @@ -42,11 +42,15 @@ def image(self): @property def labels(self): """dict[str, str]: Returns labels associated with container.""" + labels = None with suppress(KeyError): + # Container created from ``list()`` operation if "Labels" in self.attrs: - return self.attrs["Labels"] - return self.attrs["Config"]["Labels"] - return {} + labels = self.attrs["Labels"] + # Container created from ``get()`` operation + else: + labels = self.attrs["Config"].get("Labels", {}) + return labels or {} @property def status(self): diff --git a/podman/tests/integration/test_containers.py b/podman/tests/integration/test_containers.py index 07b08b91..d92a7d7a 100644 --- a/podman/tests/integration/test_containers.py +++ b/podman/tests/integration/test_containers.py @@ -195,6 +195,31 @@ def test_container_rm_anonymous_volume(self): volume_list = self.client.volumes.list() self.assertEqual(len(volume_list), len(existing_volumes)) + def test_container_labels(self): + labels = {'label1': 'value1', 'label2': 'value2'} + labeled_container = self.client.containers.create(self.alpine_image, labels=labels) + unlabeled_container = self.client.containers.create( + self.alpine_image, + ) + + # inspect and list have 2 different schemas so we need to verify that we can + # successfully retrieve the labels on both + try: + # inspect schema + self.assertEqual(labeled_container.labels, labels) + self.assertEqual(unlabeled_container.labels, {}) + + # list schema + for container in self.client.containers.list(all=True): + if container.id == labeled_container.id: + self.assertEqual(container.labels, labels) + elif container.id == unlabeled_container.id: + self.assertEqual(container.labels, {}) + + finally: + labeled_container.remove(v=True) + unlabeled_container.remove(v=True) + if __name__ == '__main__': unittest.main()