Skip to content

Commit

Permalink
Add more content on how to use Exec function (testcontainers#1970)
Browse files Browse the repository at this point in the history
* docs(features): add more content on exec function

* test(docker-test): add the reader from a command execution to the docker tests

* docs(feature): add embedded code blocks to the docs
  • Loading branch information
danvergara authored Dec 15, 2023
1 parent e983907 commit 9c97abf
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
15 changes: 14 additions & 1 deletion docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1298,21 +1298,34 @@ func TestContainerWithTmpFs(t *testing.T) {

path := "/testtmpfs/test.file"

c, _, err := container.Exec(ctx, []string{"ls", path})
// exec_reader_example {
c, reader, err := container.Exec(ctx, []string{"ls", path})
if err != nil {
t.Fatal(err)
}
if c != 1 {
t.Fatalf("File %s should not have existed, expected return code 1, got %v", path, c)
}

buf := new(strings.Builder)
_, err = io.Copy(buf, reader)
if err != nil {
t.Fatal(err)
}

// See the logs from the command execution.
t.Log(buf.String())
// }

// exec_example {
c, _, err = container.Exec(ctx, []string{"touch", path})
if err != nil {
t.Fatal(err)
}
if c != 0 {
t.Fatalf("File %s should have been created successfully, expected return code 0, got %v", path, c)
}
// }

c, _, err = container.Exec(ctx, []string{"ls", path})
if err != nil {
Expand Down
24 changes: 21 additions & 3 deletions docs/features/override_container_command.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
# Sending a CMD to a Container
# Executing commands

If you would like to send a CMD (command) to a container, you can pass it in to
the container request via the `Cmd` field...
## Container startup command

By default the container will execute whatever command is specified in the image's Dockerfile. If you would like to send a CMD (command) to a container, you can pass it in to
the container request via the `Cmd` field. For example:

```go
req := ContainerRequest{
Expand All @@ -13,3 +15,19 @@ req := ContainerRequest{
}
```

## Executing a command

You can execute a command inside a running container, similar to a `docker exec` call:

<!--codeinclude-->
[Executing a command](../../docker_test.go) inside_block:exec_example
<!--/codeinclude-->

This can be useful for software that has a command line administration tool. You can also get the logs of the command execution (from an object that implements the [io.Reader](https://pkg.go.dev/io#Reader) interface). For example:


<!--codeinclude-->
[Command logs](../../docker_test.go) inside_block:exec_reader_example
<!--/codeinclude-->

This is done this way, because it brings more flexibility to the user, rather than returning a string.

0 comments on commit 9c97abf

Please sign in to comment.