Skip to content

Commit 083487e

Browse files
Add compose exec_in_container method (#151)
* Add compose exec_in_container method * Update testcontainers/compose.py Co-authored-by: Till Hoffmann <[email protected]>
1 parent 3bd7ae9 commit 083487e

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

testcontainers/compose.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,31 @@ def get_logs(self):
110110
)
111111
return result.stdout, result.stderr
112112

113+
def exec_in_container(self, service_name, command):
114+
"""
115+
Executes a command in the container of one of the services.
116+
117+
Parameters
118+
----------
119+
service_name: str
120+
Name of the docker compose service to run the command in
121+
command: list[str]
122+
The command to execute
123+
124+
Returns
125+
-------
126+
tuple[str, str, int]
127+
stdout, stderr, return code
128+
"""
129+
exec_cmd = self.docker_compose_command() + ['exec', '-T', service_name] + command
130+
result = subprocess.run(
131+
exec_cmd,
132+
cwd=self.filepath,
133+
stdout=subprocess.PIPE,
134+
stderr=subprocess.PIPE,
135+
)
136+
return result.stdout.decode("utf-8"), result.stderr.decode("utf-8"), result.returncode
137+
113138
def get_service_port(self, service_name, port):
114139
return self._get_service_info(service_name, port)[1]
115140

tests/test_docker_compose.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,3 +82,11 @@ def test_can_pass_env_params_by_env_file():
8282
check_env_is_set_cmd = 'docker exec tests_mysql_1 printenv | grep TEST_ASSERT_KEY'.split()
8383
out = subprocess.run(check_env_is_set_cmd, stdout=subprocess.PIPE)
8484
assert out.stdout.decode('utf-8').splitlines()[0], 'test_is_passed'
85+
86+
87+
def test_can_exec_commands():
88+
with DockerCompose("tests") as compose:
89+
result = compose.exec_in_container('hub', ['echo', 'my_test'])
90+
assert result[0] == 'my_test\n', "The echo should be successful"
91+
assert result[1] == '', "stderr should be empty"
92+
assert result[2] == 0, 'The exit code should be successful'

0 commit comments

Comments
 (0)