From 4890864d65a427847cca8d58b9281e3eaab82994 Mon Sep 17 00:00:00 2001 From: Karl Kuehn Date: Tue, 30 Jan 2018 14:28:37 -0800 Subject: [PATCH] add ports to containers Signed-off-by: Karl Kuehn --- docker/models/containers.py | 7 +++++++ tests/integration/models_containers_test.py | 22 +++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docker/models/containers.py b/docker/models/containers.py index 6cd33a61..11d8f0a3 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -62,6 +62,13 @@ class Container(Model): return self.attrs['State']['Status'] return self.attrs['State'] + @property + def ports(self): + """ + The ports that the container exposes as a dictionary. + """ + return self.attrs.get('NetworkSettings', {}).get('Ports', {}) + def attach(self, **kwargs): """ Attach to this container. diff --git a/tests/integration/models_containers_test.py b/tests/integration/models_containers_test.py index c7d897eb..f0c3083b 100644 --- a/tests/integration/models_containers_test.py +++ b/tests/integration/models_containers_test.py @@ -346,6 +346,28 @@ class ContainerTest(BaseIntegrationTest): 'memory_stats', 'blkio_stats']: assert key in stats + def test_ports(self): + client = docker.from_env(version=TEST_API_VERSION) + target_ports = {'2222/tcp': None} + container = client.containers.run( + "alpine", "sleep 100", detach=True, + ports=target_ports + ) + self.tmp_containers.append(container.id) + container.reload() # required to get auto-assigned ports + actual_ports = container.ports + assert sorted(target_ports.keys()) == sorted(actual_ports.keys()) + for target_client, target_host in target_ports.items(): + for actual_port in actual_ports[target_client]: + actual_keys = sorted(actual_port.keys()) + assert sorted(['HostIp', 'HostPort']) == actual_keys + if target_host is None: + int(actual_port['HostPort']) + elif isinstance(target_host, (list, tuple)): + raise NotImplementedError() + else: + assert actual_port['HostPort'] == target_host.split('/', 1) + def test_stop(self): client = docker.from_env(version=TEST_API_VERSION) container = client.containers.run("alpine", "top", detach=True)