Skip to content

Instantly share code, notes, and snippets.

@JulienBreux
Last active April 24, 2024 15:11
Show Gist options
  • Save JulienBreux/3892189373cb246c180a0d8d2d1928c7 to your computer and use it in GitHub Desktop.
Save JulienBreux/3892189373cb246c180a0d8d2d1928c7 to your computer and use it in GitHub Desktop.
TestContainers - Forward test
package tcgot
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"strings"
"testing"
// go.work // replace github.com/testcontainers/testcontainers-go => /......./testcontainers-go
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
type StdoutLogConsumer struct{}
func (lc *StdoutLogConsumer) Accept(l testcontainers.Log) {
fmt.Print("LOGGER: ")
fmt.Print(string(l.Content))
}
var lc = StdoutLogConsumer{}
func TestContainerPortForwarding(t *testing.T) {
s := mockHTTPServer()
_, err := curl(t, "http://host.testcontainers.internal:7171/")
if err != nil {
t.Fatal(err)
}
s.Close()
}
func mockHTTPServer() *http.Server {
s := &http.Server{
Addr: ":7171",
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "hello")
})
go func() {
if err := s.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("HTTP server error: %v", err)
}
}()
return s
}
func curl(t *testing.T, url string) (testcontainers.Container, error) {
ctx := context.Background()
c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
Started: true,
ContainerRequest: testcontainers.ContainerRequest{
Image: "alpine",
HostAccessPorts: []int{7171},
LogConsumerCfg: &testcontainers.LogConsumerConfig{
Consumers: []testcontainers.LogConsumer{&lc},
},
WaitingFor: wait.ForAll(
wait.ForLog("ready"),
),
Cmd: []string{"/bin/sh", "-c", "apk add curl && echo ready && sleep 5"},
},
})
if err != nil {
return c, err
}
cmd, reader, err := c.Exec(ctx, []string{"curl", "-s", "-L", url})
if err != nil {
t.Fatal(err)
}
if cmd != 0 {
t.Fatalf("Unable to CURL URL %s, expected return code 1, got %v\n", url, cmd)
}
buf := new(strings.Builder)
_, err = io.Copy(buf, reader)
if err != nil {
t.Fatal(err)
}
o := buf.String()
if !strings.HasSuffix(o, "hello") {
t.Fatalf("Bad CURL content, expected return string hello, got %v\n", o)
}
return c, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment