diff --git a/docker/models/containers.py b/docker/models/containers.py index 9c9e92c90f..3221a222d7 100644 --- a/docker/models/containers.py +++ b/docker/models/containers.py @@ -823,6 +823,8 @@ def run(self, image, command=None, stdout=True, stderr=False, volumes_from (:py:class:`list`): List of container names or IDs to get volumes from. + wait_condition (dict): A dictionary to configure the wait mechanism. + Passed directly to the :py:meth:`Container.wait` method. working_dir (str): Path to the working directory. Returns: @@ -853,6 +855,7 @@ def run(self, image, command=None, stdout=True, stderr=False, stream = kwargs.pop('stream', False) detach = kwargs.pop('detach', False) platform = kwargs.get('platform', None) + waitcond = kwargs.pop('wait_condition', {}) if detach and remove: if version_gte(self.client.api._version, '1.25'): @@ -894,7 +897,7 @@ def run(self, image, command=None, stdout=True, stderr=False, stdout=stdout, stderr=stderr, stream=True, follow=True ) - exit_status = container.wait()['StatusCode'] + exit_status = container.wait(**waitcond)['StatusCode'] if exit_status != 0: out = None if not kwargs.get('auto_remove'): diff --git a/tests/integration/models_containers_test.py b/tests/integration/models_containers_test.py index 8727455932..d7969f8a69 100644 --- a/tests/integration/models_containers_test.py +++ b/tests/integration/models_containers_test.py @@ -25,6 +25,12 @@ def test_run_detach(self): assert container.attrs['Config']['Image'] == "alpine" assert container.attrs['Config']['Cmd'] == ['sleep', '300'] + def test_run_with_timeout(self): + client = docker.from_env(version=TEST_API_VERSION) + with pytest.raises(docker.errors.requests.exceptions.ConnectionError) as cm: + client.containers.run("alpine", "sh -c 'echo a && sleep 10 && echo b'", wait_condition={'timeout': 3}) + assert "Error" in cm.exconly() + def test_run_with_error(self): client = docker.from_env(version=TEST_API_VERSION) with pytest.raises(docker.errors.ContainerError) as cm: diff --git a/tests/unit/models_containers_test.py b/tests/unit/models_containers_test.py index 0e2ae341a9..f7fc72bc58 100644 --- a/tests/unit/models_containers_test.py +++ b/tests/unit/models_containers_test.py @@ -260,6 +260,16 @@ def test_run_pull(self): 'alpine', platform=None, tag='latest', all_tags=False, stream=True ) + def test_run_with_timeout(self): + client = make_fake_client() + client.api.logs.return_value = b"a\n" + client.api.wait.return_value = {'StatusCode': 127} + + with pytest.raises(docker.errors.ContainerError) as cm: + client.containers.run('alpine', "sh -c 'echo a && sleep 10 && echo b'", wait_condition={'timeout': 3}) + assert cm.value.exit_status == 127 + assert 'a\\n' in cm.exconly() + def test_run_with_error(self): client = make_fake_client() client.api.logs.return_value = "some error"