Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cache http wait request body #339

Merged
merged 3 commits into from
Aug 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func Test_MultipleContainersInTheNewNetwork(t *testing.T) {
hp := wait.ForListeningPort("5672/tcp")
hp.WithStartupTimeout(3 * time.Minute)
amqpRequest := ContainerRequest{
Image: "rabbitmq:management-alpine",
Image: "rabbitmq:3.8.19-management-alpine",
ExposedPorts: []string{"15672/tcp", "5672/tcp"},
Env: env,
AutoRemove: true,
Expand Down
13 changes: 12 additions & 1 deletion wait/http.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package wait

import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"strconv"
Expand Down Expand Up @@ -184,12 +186,21 @@ func (ws *HTTPStrategy) WaitUntilReady(ctx context.Context, target StrategyTarge
address := net.JoinHostPort(ipAddress, strconv.Itoa(port.Int()))
endpoint := fmt.Sprintf("%s://%s%s", proto, address, ws.Path)

// cache the body into a byte-slice so that it can be iterated over multiple times
var body []byte
if ws.Body != nil {
body, err = ioutil.ReadAll(ws.Body)
if err != nil {
return
}
}

for {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(ws.PollInterval):
req, err := http.NewRequestWithContext(ctx, ws.Method, endpoint, ws.Body)
req, err := http.NewRequestWithContext(ctx, ws.Method, endpoint, bytes.NewReader(body))
if err != nil {
return err
}
Expand Down
5 changes: 5 additions & 0 deletions wait/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func TestHTTPStrategyWaitUntilReady(t *testing.T) {
}

tlsconfig := &tls.Config{RootCAs: certpool, ServerName: "testcontainer.go.test"}
var i int
dockerReq := testcontainers.ContainerRequest{
FromDockerfile: testcontainers.FromDockerfile{
Context: workdir + "/testdata",
Expand All @@ -73,6 +74,10 @@ func TestHTTPStrategyWaitUntilReady(t *testing.T) {
data, _ := ioutil.ReadAll(body)
return bytes.Equal(data, []byte("pong"))
}).
WithStatusCodeMatcher(func(status int) bool {
i++ // always fail the first try in order to force the polling loop to be re-run
return i > 1 && status == 200
}).
WithMethod(http.MethodPost).WithBody(bytes.NewReader([]byte("ping"))),
}

Expand Down