Skip to content

Commit

Permalink
Add a testcontainers_wiremock#RunContainerAndStopOnCleanup() method…
Browse files Browse the repository at this point in the history
… to simplify automatic termination (#30)

* testcontainter with auto termination

* testcontainter with auto termination

* id for WithMappingFile() function is paramparameterized

* fix for RunContainerAndStopOnCleanup

* using the updated RunContainerAndStopOnCleanup on quickstart_test.go
  • Loading branch information
Vayras authored Aug 17, 2023
1 parent b31889e commit 85753b7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 12 deletions.
17 changes: 5 additions & 12 deletions examples/quickstart/quickstart_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,16 @@ import (
)

func TestWireMock(t *testing.T) {
// Create Container
ctx := context.Background()
container, err := RunContainer(ctx,
WithMappingFile("hello", "hello-world.json"),
)
mappingFileName := "hello-world.json"

container, err := RunContainerAndStopOnCleanup(ctx, t, []testcontainers.ContainerCustomizer{
WithMappingFile(mappingFileName),
})
if err != nil {
t.Fatal(err)
}

// Clean up the container after the test is complete
t.Cleanup(func() {
if err := container.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})

// Send a simple HTTP GET request to the mocked API
statusCode, out, err := SendHttpGet(container, "/hello", nil)
if err != nil {
t.Fatal(err, "Failed to get a response")
Expand Down
18 changes: 18 additions & 0 deletions tc-wiremock.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"net/url"
"path/filepath"
"testing"

"github.com/docker/go-connections/nat"
"github.com/testcontainers/testcontainers-go"
Expand Down Expand Up @@ -190,3 +191,20 @@ func addQueryParamsToURL(endpoint string, queryParams map[string]string) (string

return parsedURL.String(), nil
}

func RunContainerAndStopOnCleanup(ctx context.Context, t *testing.T, customizers []testcontainers.ContainerCustomizer) (testcontainers.Container, error) {
container, err := RunContainer(ctx, customizers...)
if err != nil {
t.Fatal(err)
return nil, err
}

t.Cleanup(func() {
if err := container.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})

return container, nil
}

0 comments on commit 85753b7

Please sign in to comment.