diff --git a/.golangci.yml b/.golangci.yml index 8d668831de..563e2fa088 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,6 +20,7 @@ linters: - testifylint - thelper - usestdlibvars + - usetesting exclusions: presets: - comments @@ -81,6 +82,10 @@ linters: - float-compare - go-require enable-all: true + usetesting: + # Enable/disable `os.Setenv()` detections. + # Default: true + os-setenv: false output: formats: text: diff --git a/container_test.go b/container_test.go index 55da19e445..4d937d19b1 100644 --- a/container_test.go +++ b/container_test.go @@ -285,7 +285,7 @@ func Test_BuildImageWithContexts(t *testing.T) { testCase := testCase t.Run(testCase.Name, func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() a, err := testCase.ContextArchive() require.NoError(t, err) @@ -316,7 +316,7 @@ func TestCustomLabelsImage(t *testing.T) { myLabelValue = "my-label-value" ) - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run(ctx, "alpine:latest", testcontainers.WithLabels(map[string]string{myLabelName: myLabelValue})) testcontainers.CleanupContainer(t, ctr) @@ -335,7 +335,7 @@ func TestCustomLabelsBuildOptionsModifier(t *testing.T) { myBuildOptionValue = "my-bo-label-value" ) - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run( ctx, "", @@ -360,7 +360,7 @@ func TestCustomLabelsBuildOptionsModifier(t *testing.T) { } func Test_GetLogsFromFailedContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // directDockerHubReference { c, err := testcontainers.Run( ctx, "alpine", @@ -461,7 +461,7 @@ func TestImageSubstitutors(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run(ctx, test.image, testcontainers.WithImageSubstitutors(test.substitutors...)) testcontainers.CleanupContainer(t, ctr) if test.expectedError != nil { @@ -476,7 +476,7 @@ func TestImageSubstitutors(t *testing.T) { } func TestShouldStartContainersInParallel(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Minute) t.Cleanup(cancel) for i := range 3 { diff --git a/docker_auth_test.go b/docker_auth_test.go index 74042fc573..196cac1ed2 100644 --- a/docker_auth_test.go +++ b/docker_auth_test.go @@ -102,7 +102,7 @@ func TestDockerImageAuth(t *testing.T) { username, password := "gopher", "secret" creds := setAuthConfig(t, exampleAuth, username, password) - registry, cfg, err := DockerImageAuth(context.Background(), exampleAuth+"/my/image:latest") + registry, cfg, err := DockerImageAuth(t.Context(), exampleAuth+"/my/image:latest") require.NoError(t, err) require.Equal(t, exampleAuth, registry) require.Equal(t, username, cfg.Username) @@ -115,7 +115,7 @@ func TestDockerImageAuth(t *testing.T) { imagePath := "/my/image:latest" base64 := setAuthConfig(t, exampleAuth, "gopher", "secret") - registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath) + registry, cfg, err := DockerImageAuth(t.Context(), imageReg+imagePath) require.NoError(t, err) require.Equal(t, imageReg, registry) require.Equal(t, "gopher", cfg.Username) @@ -130,7 +130,7 @@ func TestDockerImageAuth(t *testing.T) { setAuthConfig(t, invalidRegistryURL, "gopher", "secret") - registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath) + registry, cfg, err := DockerImageAuth(t.Context(), imageReg+imagePath) require.ErrorIs(t, err, dockercfg.ErrCredentialsNotFound) require.Empty(t, cfg) require.Equal(t, imageReg, registry) @@ -150,7 +150,7 @@ func TestDockerImageAuth(t *testing.T) { setAuthConfig(t, "example-auth.com", "gopher", "secret") - registry, cfg, err := DockerImageAuth(context.Background(), imageReg+imagePath) + registry, cfg, err := DockerImageAuth(t.Context(), imageReg+imagePath) require.ErrorIs(t, err, dockercfg.ErrCredentialsNotFound) require.Empty(t, cfg) require.Equal(t, imageReg, registry) @@ -158,7 +158,7 @@ func TestDockerImageAuth(t *testing.T) { } func TestBuildContainerFromDockerfile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() redisC, err := Run(ctx, "", WithDockerfile(FromDockerfile{ @@ -175,7 +175,7 @@ func TestBuildContainerFromDockerfile(t *testing.T) { // removeImageFromLocalCache removes the image from the local cache func removeImageFromLocalCache(t *testing.T, img string) { t.Helper() - ctx := context.Background() + ctx := t.Context() testcontainersClient, err := NewDockerClientWithOpts(ctx, client.WithVersion(daemonMaxVersion)) if err != nil { @@ -198,7 +198,7 @@ func TestBuildContainerFromDockerfileWithDockerAuthConfig(t *testing.T) { // using the same credentials as in the Docker Registry setAuthConfig(t, registryHost, "testuser", "testpassword") - ctx := context.Background() + ctx := t.Context() redisC, err := Run(ctx, "", WithDockerfile(FromDockerfile{ @@ -223,7 +223,7 @@ func TestBuildContainerFromDockerfileShouldFailWithWrongDockerAuthConfig(t *test // using different credentials than in the Docker Registry setAuthConfig(t, registryHost, "foo", "bar") - ctx := context.Background() + ctx := t.Context() redisC, err := Run(ctx, "", WithDockerfile(FromDockerfile{ @@ -247,7 +247,7 @@ func TestCreateContainerFromPrivateRegistry(t *testing.T) { // using the same credentials as in the Docker Registry setAuthConfig(t, registryHost, "testuser", "testpassword") - ctx := context.Background() + ctx := t.Context() redisContainer, err := Run(ctx, registryHost+"/redis:5.0-alpine", WithAlwaysPull(), WithExposedPorts("6379/tcp"), WithWaitStrategy(wait.ForLog("Ready to accept connections"))) CleanupContainer(t, redisContainer) @@ -256,7 +256,7 @@ func TestCreateContainerFromPrivateRegistry(t *testing.T) { func prepareLocalRegistryWithAuth(t *testing.T) string { t.Helper() - ctx := context.Background() + ctx := t.Context() wd, err := os.Getwd() require.NoError(t, err) // copyDirectoryToContainer { diff --git a/docker_client_test.go b/docker_client_test.go index 13c873f37b..520babfb98 100644 --- a/docker_client_test.go +++ b/docker_client_test.go @@ -1,7 +1,6 @@ package testcontainers import ( - "context" "sync" "testing" @@ -10,7 +9,7 @@ import ( func TestGetDockerInfo(t *testing.T) { t.Run("works", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := NewDockerClientWithOpts(ctx) require.NoError(t, err) @@ -20,7 +19,7 @@ func TestGetDockerInfo(t *testing.T) { }) t.Run("is goroutine safe", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := NewDockerClientWithOpts(ctx) require.NoError(t, err) diff --git a/docker_exec_test.go b/docker_exec_test.go index 18787628be..a14ce56742 100644 --- a/docker_exec_test.go +++ b/docker_exec_test.go @@ -2,7 +2,6 @@ package testcontainers import ( "bytes" - "context" "io" "testing" @@ -46,7 +45,7 @@ func TestExecWithOptions(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, nginxAlpineImage) CleanupContainer(t, ctr) @@ -72,7 +71,7 @@ func TestExecWithOptions(t *testing.T) { } func TestExecWithMultiplexedResponse(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, nginxAlpineImage) CleanupContainer(t, ctr) @@ -93,7 +92,7 @@ func TestExecWithMultiplexedResponse(t *testing.T) { } func TestExecWithNonMultiplexedResponse(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, nginxAlpineImage) CleanupContainer(t, ctr) diff --git a/docker_files_test.go b/docker_files_test.go index 1ab7897c35..8b575bbc7b 100644 --- a/docker_files_test.go +++ b/docker_files_test.go @@ -16,7 +16,7 @@ import ( const testBashImage string = "bash:5.2.26" func TestCopyFileToContainer(t *testing.T) { - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // copyFileOnCreate { @@ -42,7 +42,7 @@ func TestCopyFileToContainer(t *testing.T) { } func TestCopyFileToRunningContainer(t *testing.T) { - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // Not using the assertations here to avoid leaking the library into the example @@ -74,7 +74,7 @@ func TestCopyFileToRunningContainer(t *testing.T) { } func TestCopyDirectoryToContainer(t *testing.T) { - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // Not using the assertations here to avoid leaking the library into the example @@ -100,7 +100,7 @@ func TestCopyDirectoryToContainer(t *testing.T) { } func TestCopyDirectoryToRunningContainerAsFile(t *testing.T) { - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // copyDirectoryToRunningContainerAsFile { @@ -131,7 +131,7 @@ func TestCopyDirectoryToRunningContainerAsFile(t *testing.T) { } func TestCopyDirectoryToRunningContainerAsDir(t *testing.T) { - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // Not using the assertations here to avoid leaking the library into the example diff --git a/docker_test.go b/docker_test.go index e4506e756e..54505b52d8 100644 --- a/docker_test.go +++ b/docker_test.go @@ -55,7 +55,7 @@ func TestContainerWithHostNetworkOptions(t *testing.T) { t.Skip("Skipping test that requires host network access when running in a container") } - ctx := context.Background() + ctx := t.Context() SkipIfDockerDesktop(t, ctx) absPath, err := filepath.Abs(filepath.Join("testdata", "nginx-highport.conf")) @@ -86,7 +86,7 @@ func TestContainerWithHostNetworkOptions(t *testing.T) { } func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testing.T) { - ctx := context.Background() + ctx := t.Context() opts := []ContainerCustomizer{ WithExposedPorts(nginxDefaultPort), @@ -115,7 +115,7 @@ func TestContainerWithHostNetwork(t *testing.T) { t.Skip("Skipping test that requires host network access when running in a container") } - ctx := context.Background() + ctx := t.Context() SkipIfDockerDesktop(t, ctx) absPath, err := filepath.Abs(filepath.Join("testdata", "nginx-highport.conf")) @@ -151,7 +151,7 @@ func TestContainerWithHostNetwork(t *testing.T) { } func TestContainerReturnItsContainerID(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxA, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort)) CleanupContainer(t, nginxA) require.NoError(t, err) @@ -173,7 +173,7 @@ func (l *testLogConsumer) Accept(log Log) { } func TestContainerTerminationResetsState(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxA, err := Run( ctx, nginxAlpineImage, @@ -205,7 +205,7 @@ func TestContainerStateAfterTermination(t *testing.T) { } t.Run("after-termination/nil-state", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginx, err := createContainerFn(ctx) CleanupContainer(t, nginx) require.NoError(t, err) @@ -221,7 +221,7 @@ func TestContainerStateAfterTermination(t *testing.T) { }) t.Run("termination-timeout", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginx, err := createContainerFn(ctx) require.NoError(t, err) @@ -233,7 +233,7 @@ func TestContainerStateAfterTermination(t *testing.T) { }) t.Run("after-termination/nil-state-if-raw", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginx, err := createContainerFn(ctx) CleanupContainer(t, nginx) require.NoError(t, err) @@ -254,7 +254,7 @@ func TestContainerStateAfterTermination(t *testing.T) { func TestContainerTerminationRemovesDockerImage(t *testing.T) { t.Run("not-built-from-Dockerfile", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dockerClient, err := NewDockerClientWithOpts(ctx) require.NoError(t, err) defer dockerClient.Close() @@ -271,7 +271,7 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) { }) t.Run("built-from-Dockerfile", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dockerClient, err := NewDockerClientWithOpts(ctx) require.NoError(t, err) defer dockerClient.Close() @@ -300,7 +300,7 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) { } func TestTwoContainersExposingTheSamePort(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxA, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort), WithWaitStrategy(wait.ForHTTP("/").WithPort(nginxDefaultPort)), @@ -335,7 +335,7 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) { } func TestContainerCreation(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort), @@ -365,7 +365,7 @@ func TestContainerCreation(t *testing.T) { } func TestContainerCreationWithName(t *testing.T) { - ctx := context.Background() + ctx := t.Context() creationName := fmt.Sprintf("%s_%d", "test_container", time.Now().Unix()) expectedName := "/" + creationName // inspect adds '/' in the beginning @@ -416,7 +416,7 @@ func TestContainerCreationWithName(t *testing.T) { } func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // delayed-nginx will wait 2s before opening port nginxC, err := Run(ctx, nginxDelayedImage, @@ -436,7 +436,7 @@ func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) { } func TestContainerCreationTimesOut(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // delayed-nginx will wait 2s before opening port nginxC, err := Run(ctx, nginxDelayedImage, WithExposedPorts(nginxDefaultPort), @@ -448,7 +448,7 @@ func TestContainerCreationTimesOut(t *testing.T) { } func TestContainerRespondsWithHttp200ForIndex(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort), @@ -467,7 +467,7 @@ func TestContainerRespondsWithHttp200ForIndex(t *testing.T) { } func TestContainerCreationTimesOutWithHttp(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // delayed-nginx will wait 2s before opening port nginxC, err := Run(ctx, nginxDelayedImage, WithExposedPorts(nginxDefaultPort), @@ -478,7 +478,7 @@ func TestContainerCreationTimesOutWithHttp(t *testing.T) { } func TestContainerCreationWaitsForLogContextTimeout(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, mysqlImage, WithExposedPorts("3306/tcp", "33060/tcp"), WithEnv(map[string]string{ @@ -492,7 +492,7 @@ func TestContainerCreationWaitsForLogContextTimeout(t *testing.T) { } func TestContainerCreationWaitsForLog(t *testing.T) { - ctx := context.Background() + ctx := t.Context() mysqlC, err := Run(ctx, mysqlImage, WithExposedPorts("3306/tcp", "33060/tcp"), WithEnv(map[string]string{ @@ -506,7 +506,7 @@ func TestContainerCreationWaitsForLog(t *testing.T) { } func Test_BuildContainerFromDockerfileWithBuildArgs(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // fromDockerfileWithBuildArgs { ba := "build args value" @@ -549,7 +549,7 @@ func Test_BuildContainerFromDockerfileWithBuildLog(t *testing.T) { os.Stderr = oldStderr }) - ctx := context.Background() + ctx := t.Context() opts := []ContainerCustomizer{ WithDockerfile(FromDockerfile{ @@ -576,7 +576,7 @@ func Test_BuildContainerFromDockerfileWithBuildLog(t *testing.T) { func Test_BuildContainerFromDockerfileWithBuildLogWriter(t *testing.T) { var buffer bytes.Buffer - ctx := context.Background() + ctx := t.Context() opts := []ContainerCustomizer{ WithDockerfile(FromDockerfile{ @@ -596,7 +596,7 @@ func Test_BuildContainerFromDockerfileWithBuildLogWriter(t *testing.T) { } func TestContainerCreationWaitsForLogAndPortContextTimeout(t *testing.T) { - ctx := context.Background() + ctx := t.Context() c, err := Run( ctx, mysqlImage, WithExposedPorts("3306/tcp", "33060/tcp"), @@ -614,7 +614,7 @@ func TestContainerCreationWaitsForLogAndPortContextTimeout(t *testing.T) { } func TestContainerCreationWaitingForHostPort(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // exposePorts { nginx, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort), @@ -626,7 +626,7 @@ func TestContainerCreationWaitingForHostPort(t *testing.T) { } func TestContainerCreationWaitingForHostPortWithoutBashThrowsAnError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginx, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort), WithWaitStrategy(wait.ForListeningPort(nginxDefaultPort)), @@ -642,7 +642,7 @@ func TestCMD(t *testing.T) { and it will be run when we run the container */ - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, alpineImage, WithCmd("echo", "command override!"), @@ -661,7 +661,7 @@ func TestEntrypoint(t *testing.T) { and it will be run when we run the container */ - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, alpineImage, WithEntrypoint("echo", "entrypoint override!"), @@ -680,7 +680,7 @@ func TestWorkingDir(t *testing.T) { ContainerRequest and it will be used for the container */ - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, alpineImage, WithEntrypoint("pwd"), @@ -862,7 +862,7 @@ func ExampleContainer_MappedPort() { func TestContainerCreationWithVolumeAndFileWritingToIt(t *testing.T) { absPath, err := filepath.Abs(filepath.Join(".", "testdata", "hello.sh")) require.NoError(t, err) - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // Create the volume. @@ -886,7 +886,7 @@ func TestContainerCreationWithVolumeAndFileWritingToIt(t *testing.T) { func TestContainerCreationWithVolumeCleaning(t *testing.T) { absPath, err := filepath.Abs(filepath.Join(".", "testdata", "hello.sh")) require.NoError(t, err) - ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cnl := context.WithTimeout(t.Context(), 30*time.Second) defer cnl() // Create the volume. @@ -939,7 +939,7 @@ func TestContainerTerminationOptions(t *testing.T) { } func TestContainerWithTmpFs(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "busybox", WithCmd("sleep", "10"), WithTmpfs(map[string]string{"/testtmpfs": "rw"}), @@ -975,14 +975,14 @@ func TestContainerWithTmpFs(t *testing.T) { func TestContainerContextCancellation(t *testing.T) { t.Run("image-not-found/no-propagate-error", func(t *testing.T) { - ctr, err := Run(context.Background(), "postgres:nonexistent-version") + ctr, err := Run(t.Context(), "postgres:nonexistent-version") CleanupContainer(t, ctr) require.ErrorIs(t, err, errdefs.ErrNotFound, "the error should have been an errdefs.ErrNotFound: %v", err) }) t.Run("propagate-error", func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) defer cancel() c, err := Run(ctx, "postgres:12", WithWaitStrategy(wait.ForLog("log"))) CleanupContainer(t, c) @@ -997,7 +997,7 @@ func TestContainerCustomPlatformImage(t *testing.T) { t.Run("non-existent-platform", func(t *testing.T) { t.Parallel() nonExistentPlatform := "windows/arm12" - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() c, err := Run(ctx, "redis:latest", WithImagePlatform(nonExistentPlatform), WithNoStart()) CleanupContainer(t, c) @@ -1006,7 +1006,7 @@ func TestContainerCustomPlatformImage(t *testing.T) { t.Run("valid-platform", func(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, "mysql:8.0.36", WithImagePlatform("linux/amd64"), WithNoStart()) CleanupContainer(t, c) @@ -1027,7 +1027,7 @@ func TestContainerCustomPlatformImage(t *testing.T) { } func TestContainerWithCustomHostname(t *testing.T) { - ctx := context.Background() + ctx := t.Context() name := fmt.Sprintf("some-nginx-%s-%d", t.Name(), rand.Int()) hostname := fmt.Sprintf("my-nginx-%s-%d", t.Name(), rand.Int()) @@ -1045,32 +1045,34 @@ func TestContainerWithCustomHostname(t *testing.T) { } func TestContainerInspect_RawInspectIsCleanedOnStop(t *testing.T) { - ctr, err := Run(context.Background(), nginxImage) + ctr, err := Run(t.Context(), nginxImage) CleanupContainer(t, ctr) require.NoError(t, err) - inspect, err := ctr.Inspect(context.Background()) + inspect, err := ctr.Inspect(t.Context()) require.NoError(t, err) require.NotEmpty(t, inspect.ID) - require.NoError(t, ctr.Stop(context.Background(), nil)) + require.NoError(t, ctr.Stop(t.Context(), nil)) } func readHostname(tb testing.TB, containerID string) string { tb.Helper() - containerClient, err := NewDockerClientWithOpts(context.Background()) + ctx := tb.Context() + + containerClient, err := NewDockerClientWithOpts(ctx) require.NoErrorf(tb, err, "Failed to create Docker client") defer containerClient.Close() - containerDetails, err := containerClient.ContainerInspect(context.Background(), containerID) + containerDetails, err := containerClient.ContainerInspect(ctx, containerID) require.NoErrorf(tb, err, "Failed to inspect container") return containerDetails.Config.Hostname } func TestDockerContainerCopyFileToContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string @@ -1105,7 +1107,7 @@ func TestDockerContainerCopyFileToContainer(t *testing.T) { } func TestDockerContainerCopyDirToContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxImage, WithExposedPorts(nginxDefaultPort), @@ -1126,7 +1128,7 @@ func TestDockerContainerCopyDirToContainer(t *testing.T) { } func TestDockerCreateContainerWithFiles(t *testing.T) { - ctx := context.Background() + ctx := t.Context() hostFileName := filepath.Join(".", "testdata", "hello.sh") copiedFileName := "/hello_copy.sh" tests := []struct { @@ -1191,7 +1193,7 @@ func TestDockerCreateContainerWithFiles(t *testing.T) { } func TestDockerCreateContainerWithDirs(t *testing.T) { - ctx := context.Background() + ctx := t.Context() hostDirName := "testdata" abs, err := filepath.Abs(filepath.Join(".", hostDirName)) @@ -1261,7 +1263,7 @@ func TestDockerCreateContainerWithDirs(t *testing.T) { } func TestDockerContainerCopyToContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string @@ -1300,7 +1302,7 @@ func TestDockerContainerCopyToContainer(t *testing.T) { func TestDockerContainerCopyFileFromContainer(t *testing.T) { fileContent, err := os.ReadFile(filepath.Join(".", "testdata", "hello.sh")) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxImage, WithExposedPorts(nginxDefaultPort), @@ -1325,7 +1327,7 @@ func TestDockerContainerCopyFileFromContainer(t *testing.T) { } func TestDockerContainerCopyEmptyFileFromContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxImage, WithExposedPorts(nginxDefaultPort), @@ -1357,7 +1359,7 @@ func TestDockerContainerResources(t *testing.T) { t.Skip("Rootless Docker does not support setting rlimit") } - ctx := context.Background() + ctx := t.Context() expected := []*container.Ulimit{ { @@ -1401,7 +1403,7 @@ func TestContainerCapAdd(t *testing.T) { t.Skip("Rootless Podman does not support setting cap-add/cap-drop") } - ctx := context.Background() + ctx := t.Context() expected := "CAP_IPC_LOCK" @@ -1427,7 +1429,7 @@ func TestContainerCapAdd(t *testing.T) { } func TestContainerRunningCheckingStatusCode(t *testing.T) { - ctx := context.Background() + ctx := t.Context() influx, err := Run(ctx, "influxdb:1.8.10-alpine", WithExposedPorts("8086/tcp"), WithImagePlatform("linux/amd64"), // influxdb doesn't provide an alpine+arm build (https://github.com/influxdata/influxdata-docker/issues/335) @@ -1446,7 +1448,7 @@ func TestContainerRunningCheckingStatusCode(t *testing.T) { func TestContainerWithUserID(t *testing.T) { const expectedUserID = "60125" - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, alpineImage, WithCmd("sh", "-c", "id -u"), WithWaitStrategy(wait.ForExit()), @@ -1467,7 +1469,7 @@ func TestContainerWithUserID(t *testing.T) { } func TestContainerWithNoUserID(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, alpineImage, WithCmd("sh", "-c", "id -u"), WithWaitStrategy(wait.ForExit()), @@ -1496,13 +1498,13 @@ func TestGetGatewayIP(t *testing.T) { t.Skip("provider is not a DockerProvider") } - ip, err := dockerProvider.GetGatewayIP(context.Background()) + ip, err := dockerProvider.GetGatewayIP(t.Context()) require.NoError(t, err) require.NotEmpty(t, ip) } func TestNetworkModeWithContainerReference(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nginxA, err := Run(ctx, nginxAlpineImage) CleanupContainer(t, nginxA) require.NoError(t, err) @@ -1564,7 +1566,7 @@ func assertExtractedFiles(t *testing.T, ctx context.Context, container Container } func TestDockerProviderFindContainerByName(t *testing.T) { - ctx := context.Background() + ctx := t.Context() provider, err := NewDockerProvider(WithLogger(log.TestLogger(t))) require.NoError(t, err) defer provider.Close() @@ -1605,7 +1607,7 @@ func TestImageBuiltFromDockerfile_KeepBuiltImage(t *testing.T) { for _, tt := range tests { t.Run(strconv.FormatBool(tt.keepBuiltImage), func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // Set up CLI. provider, err := NewDockerProvider() require.NoError(t, err, "get docker provider should not fail") @@ -1734,7 +1736,7 @@ func TestDockerProvider_BuildImage_Retries(t *testing.T) { p.client = m // give a chance to retry - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() _, err = p.BuildImage(ctx, &ContainerRequest{ FromDockerfile: FromDockerfile{ @@ -1794,7 +1796,7 @@ func TestDockerProvider_waitContainerCreation_retries(t *testing.T) { p.client = m // give a chance to retry - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() _, _ = p.waitContainerCreation(ctx, "someID") @@ -1855,7 +1857,7 @@ func TestDockerProvider_attemptToPullImage_retries(t *testing.T) { p.client = m // give a chance to retry - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Second) defer cancel() _ = p.attemptToPullImage(ctx, "someTag", image.PullOptions{}) @@ -1869,7 +1871,7 @@ func TestCustomPrefixTrailingSlashIsProperlyRemovedIfPresent(t *testing.T) { hubPrefixWithTrailingSlash := "public.ecr.aws/" dockerImage := "amazonlinux/amazonlinux:2023" - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, dockerImage, WithImageSubstitutors(newPrependHubRegistry(hubPrefixWithTrailingSlash))) CleanupContainer(t, c) require.NoError(t, err) @@ -1879,7 +1881,7 @@ func TestCustomPrefixTrailingSlashIsProperlyRemovedIfPresent(t *testing.T) { // TODO: remove this skip check when context rework is merged alongside [core.DockerEnvFile] removal. func Test_Provider_DaemonHost_Issue2897(t *testing.T) { - ctx := context.Background() + ctx := t.Context() provider, err := NewDockerProvider() require.NoError(t, err) t.Cleanup(func() { diff --git a/examples/nginx/nginx_test.go b/examples/nginx/nginx_test.go index fe662daf07..bd40a9f42e 100644 --- a/examples/nginx/nginx_test.go +++ b/examples/nginx/nginx_test.go @@ -1,7 +1,6 @@ package nginx import ( - "context" "net/http" "testing" @@ -15,7 +14,7 @@ func TestIntegrationNginxLatestReturn(t *testing.T) { t.Skip("skipping integration test") } - ctx := context.Background() + ctx := t.Context() nginxC, err := startContainer(ctx) testcontainers.CleanupContainer(t, nginxC) diff --git a/examples_test.go b/examples_test.go index d5225222e2..07900c584e 100644 --- a/examples_test.go +++ b/examples_test.go @@ -104,7 +104,7 @@ func ExampleRun() { // files // copyFileFromContainer { - f, err := ctr.CopyFileFromContainer(context.Background(), "/tmp/file.txt") + f, err := ctr.CopyFileFromContainer(ctx, "/tmp/file.txt") if err != nil { log.Printf("failed to copy file from container: %s", err) return diff --git a/from_dockerfile_test.go b/from_dockerfile_test.go index 22245b6abb..5a9c372c10 100644 --- a/from_dockerfile_test.go +++ b/from_dockerfile_test.go @@ -23,7 +23,7 @@ func TestBuildImageFromDockerfile(t *testing.T) { cli := provider.Client() - ctx := context.Background() + ctx := t.Context() tag, err := provider.BuildImage(ctx, &ContainerRequest{ // fromDockerfileIncludingRepo { @@ -57,7 +57,7 @@ func TestBuildImageFromDockerfile_NoRepo(t *testing.T) { cli := provider.Client() - ctx := context.Background() + ctx := t.Context() tag, err := provider.BuildImage(ctx, &ContainerRequest{ FromDockerfile: FromDockerfile{ @@ -82,7 +82,7 @@ func TestBuildImageFromDockerfile_NoRepo(t *testing.T) { } func TestBuildImageFromDockerfile_BuildError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "", WithDockerfile(FromDockerfile{ @@ -101,7 +101,7 @@ func TestBuildImageFromDockerfile_NoTag(t *testing.T) { cli := provider.Client() - ctx := context.Background() + ctx := t.Context() tag, err := provider.BuildImage(ctx, &ContainerRequest{ FromDockerfile: FromDockerfile{ @@ -128,7 +128,7 @@ func TestBuildImageFromDockerfile_NoTag(t *testing.T) { func TestBuildImageFromDockerfile_Target(t *testing.T) { // there are three targets: target0, target1 and target2. for i := range 3 { - ctx := context.Background() + ctx := t.Context() c, err := Run(ctx, "", WithDockerfile(FromDockerfile{ Context: "testdata", @@ -195,7 +195,7 @@ func ExampleGenericContainer_buildFromDockerfile() { func TestBuildImageFromDockerfile_TargetDoesNotExist(t *testing.T) { // the context cancellation will happen with enough time for the build to fail. - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) defer cancel() ctr, err := Run(ctx, "", diff --git a/generic_test.go b/generic_test.go index 99e207562f..1afc403f9f 100644 --- a/generic_test.go +++ b/generic_test.go @@ -20,7 +20,7 @@ const ( ) func TestGenericReusableContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() reusableContainerName := reusableContainerName + "_" + time.Now().Format("20060102150405") @@ -99,7 +99,7 @@ func TestGenericContainerShouldReturnRefOnError(t *testing.T) { // In this test, we are going to cancel the context to exit the `wait.Strategy`. // We want to make sure that the Run call will still return a reference to the // created container, so that we can Destroy it. - ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) defer cancel() c, err := Run(ctx, nginxAlpineImage, WithWaitStrategy(wait.ForLog("this string should not be present in the logs"))) @@ -127,12 +127,12 @@ func TestGenericReusableContainerInSubprocess(t *testing.T) { wg.Wait() - cli, err := NewDockerClientWithOpts(context.Background()) + cli, err := NewDockerClientWithOpts(t.Context()) require.NoError(t, err) f := filters.NewArgs(filters.KeyValuePair{Key: "name", Value: reusableContainerName}) - ctrs, err := cli.ContainerList(context.Background(), container.ListOptions{ + ctrs, err := cli.ContainerList(t.Context(), container.ListOptions{ All: true, Filters: f, }) @@ -144,7 +144,7 @@ func TestGenericReusableContainerInSubprocess(t *testing.T) { provider.SetClient(cli) - nginxC, err := provider.ContainerFromType(context.Background(), ctrs[0]) + nginxC, err := provider.ContainerFromType(t.Context(), ctrs[0]) CleanupContainer(t, nginxC) require.NoError(t, err) } @@ -168,7 +168,7 @@ func TestHelperContainerStarterProcess(t *testing.T) { t.Skip("Skipping helper test function. It's not a real test") } - ctx := context.Background() + ctx := t.Context() nginxC, err := Run(ctx, nginxDelayedImage, WithExposedPorts(nginxDefaultPort), diff --git a/image_substitutors_test.go b/image_substitutors_test.go index ed4cf2631d..465fb00799 100644 --- a/image_substitutors_test.go +++ b/image_substitutors_test.go @@ -1,7 +1,6 @@ package testcontainers import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -101,7 +100,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { func TestSubstituteBuiltImage(t *testing.T) { t.Run("should not use the properties prefix on built images", func(t *testing.T) { config.Reset() - c, err := Run(context.Background(), "", WithDockerfile(FromDockerfile{ + c, err := Run(t.Context(), "", WithDockerfile(FromDockerfile{ Context: "testdata", Dockerfile: "echo.Dockerfile", Tag: "my-image", @@ -110,7 +109,7 @@ func TestSubstituteBuiltImage(t *testing.T) { CleanupContainer(t, c) require.NoError(t, err) - json, err := c.Inspect(context.Background()) + json, err := c.Inspect(t.Context()) require.NoError(t, err) require.Equalf(t, "my-registry/my-repo:my-image", json.Config.Image, "expected my-registry/my-repo:my-image, got %s", json.Config.Image) diff --git a/image_test.go b/image_test.go index 06832afaa6..0cb1ede4aa 100644 --- a/image_test.go +++ b/image_test.go @@ -1,7 +1,6 @@ package testcontainers import ( - "context" "os" "path/filepath" "testing" @@ -13,7 +12,9 @@ import ( ) func TestImageList(t *testing.T) { - t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(context.Background())) + ctx := t.Context() + + t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(ctx)) provider, err := ProviderDocker.GetProvider() require.NoErrorf(t, err, "failed to get provider") @@ -27,11 +28,11 @@ func TestImageList(t *testing.T) { Image: "redis:latest", } - ctr, err := provider.CreateContainer(context.Background(), req) - CleanupContainer(t, ctr) + ctr, err := provider.CreateContainer(ctx, req) require.NoErrorf(t, err, "creating test container") + CleanupContainer(t, ctr) - images, err := provider.ListImages(context.Background()) + images, err := provider.ListImages(ctx) require.NoErrorf(t, err, "listing images") require.NotEmptyf(t, images, "no images retrieved") @@ -47,7 +48,8 @@ func TestImageList(t *testing.T) { } func TestSaveImages(t *testing.T) { - t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(context.Background())) + ctx := t.Context() + t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(ctx)) provider, err := ProviderDocker.GetProvider() require.NoErrorf(t, err, "failed to get provider") @@ -61,12 +63,12 @@ func TestSaveImages(t *testing.T) { Image: "redis:latest", } - ctr, err := provider.CreateContainer(context.Background(), req) - CleanupContainer(t, ctr) + ctr, err := provider.CreateContainer(ctx, req) require.NoErrorf(t, err, "creating test container") + CleanupContainer(t, ctr) output := filepath.Join(t.TempDir(), "images.tar") - err = provider.SaveImages(context.Background(), output, req.Image) + err = provider.SaveImages(ctx, output, req.Image) require.NoErrorf(t, err, "saving image %q", req.Image) info, err := os.Stat(output) @@ -76,7 +78,8 @@ func TestSaveImages(t *testing.T) { } func TestSaveImagesWithOpts(t *testing.T) { - t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(context.Background())) + ctx := t.Context() + t.Setenv("DOCKER_HOST", core.MustExtractDockerHost(ctx)) provider, err := ProviderDocker.GetProvider() require.NoErrorf(t, err, "failed to get provider") @@ -94,13 +97,13 @@ func TestSaveImagesWithOpts(t *testing.T) { p, err := platforms.ParseAll([]string{"linux/amd64"}) require.NoError(t, err) - ctr, err := provider.CreateContainer(context.Background(), req) - CleanupContainer(t, ctr) + ctr, err := provider.CreateContainer(ctx, req) require.NoErrorf(t, err, "creating test container") + CleanupContainer(t, ctr) output := filepath.Join(t.TempDir(), "images.tar") err = provider.SaveImagesWithOpts( - context.Background(), output, []string{req.Image}, SaveDockerImageWithPlatforms(p...), + ctx, output, []string{req.Image}, SaveDockerImageWithPlatforms(p...), ) require.NoErrorf(t, err, "saving image %q", req.Image) diff --git a/internal/core/docker_host_test.go b/internal/core/docker_host_test.go index ccd33e52c3..83d67dbbf1 100644 --- a/internal/core/docker_host_test.go +++ b/internal/core/docker_host_test.go @@ -72,23 +72,26 @@ func TestExtractDockerHost(t *testing.T) { expected := "/path/to/docker.sock" t.Setenv("DOCKER_HOST", expected) - host := MustExtractDockerHost(context.Background()) + ctx := t.Context() + + host := MustExtractDockerHost(ctx) require.Equal(t, expected, host) t.Setenv("DOCKER_HOST", "/path/to/another/docker.sock") - host = MustExtractDockerHost(context.Background()) + host = MustExtractDockerHost(ctx) require.Equal(t, expected, host) }) t.Run("Testcontainers Host is resolved first", func(t *testing.T) { t.Setenv("DOCKER_HOST", "/path/to/docker.sock") content := "tc.host=" + testRemoteHost + ctx := t.Context() setupTestcontainersProperties(t, content) - host, err := extractDockerHost(context.Background()) + host, err := extractDockerHost(ctx) require.NoError(t, err) require.Equal(t, testRemoteHost, host) }) @@ -96,20 +99,22 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Testcontainers Host is resolved first but not reachable", func(t *testing.T) { t.Setenv("DOCKER_HOST", "/path/to/docker.sock") content := "tc.host=" + testRemoteHost + ctx := t.Context() setupTestcontainersProperties(t, content) // mock the callback check to return an error mockCallbackCheck(t, testCallbackCheckError) - host, err := extractDockerHost(context.Background()) + host, err := extractDockerHost(ctx) require.Error(t, err) require.Empty(t, host) }) t.Run("Docker Host as environment variable", func(t *testing.T) { t.Setenv("DOCKER_HOST", "/path/to/docker.sock") - host, err := extractDockerHost(context.Background()) + ctx := t.Context() + host, err := extractDockerHost(ctx) require.NoError(t, err) require.Equal(t, "/path/to/docker.sock", host) }) @@ -118,7 +123,7 @@ func TestExtractDockerHost(t *testing.T) { setupDockerSocketNotFound(t) setupRootlessNotFound(t) - ctx := context.Background() + ctx := t.Context() host, err := extractDockerHost(context.WithValue(ctx, DockerHostContextKey, "path-to-docker-sock")) require.Error(t, err) @@ -128,7 +133,7 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Malformed Schema Docker Host is passed in context", func(t *testing.T) { setupDockerSocketNotFound(t) setupRootlessNotFound(t) - ctx := context.Background() + ctx := t.Context() host, err := extractDockerHost(context.WithValue(ctx, DockerHostContextKey, "http://path to docker sock")) require.Error(t, err) @@ -136,7 +141,7 @@ func TestExtractDockerHost(t *testing.T) { }) t.Run("Unix Docker Host is passed in context", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() host, err := extractDockerHost(context.WithValue(ctx, DockerHostContextKey, DockerSocketSchema+"/this/is/a/sample.sock")) require.NoError(t, err) @@ -147,10 +152,11 @@ func TestExtractDockerHost(t *testing.T) { setupDockerSocketNotFound(t) setupRootlessNotFound(t) content := "docker.host=" + DockerSocketSchema + "/this/is/a/sample.sock" + ctx := t.Context() setupTestcontainersProperties(t, content) - host, err := extractDockerHost(context.Background()) + host, err := extractDockerHost(ctx) require.NoError(t, err) require.Equal(t, DockerSocketSchema+"/this/is/a/sample.sock", host) }) @@ -158,8 +164,9 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Default Docker socket", func(t *testing.T) { setupRootlessNotFound(t) tmpSocket := setupDockerSocket(t) + ctx := t.Context() - host, err := extractDockerHost(context.Background()) + host, err := extractDockerHost(ctx) require.NoError(t, err) require.Equal(t, tmpSocket, host) }) @@ -167,7 +174,8 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Error when empty", func(t *testing.T) { setupDockerSocketNotFound(t) setupRootlessNotFound(t) - host, err := extractDockerHost(context.Background()) + ctx := t.Context() + host, err := extractDockerHost(ctx) require.Error(t, err) require.Empty(t, host) }) @@ -179,10 +187,11 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Testcontainers host is defined in properties", func(t *testing.T) { t.Run("TCP host", func(t *testing.T) { content := "tc.host=" + testRemoteHost + ctx := t.Context() setupTestcontainersProperties(t, content) - socket, err := testcontainersHostFromProperties(context.Background()) + socket, err := testcontainersHostFromProperties(ctx) require.NoError(t, err) require.Equal(t, testRemoteHost, socket) }) @@ -190,10 +199,11 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Unix socket host preserves schema", func(t *testing.T) { unixSocket := "unix:///var/run/docker.sock" content := "tc.host=" + unixSocket + ctx := t.Context() setupTestcontainersProperties(t, content) - socket, err := testcontainersHostFromProperties(context.Background()) + socket, err := testcontainersHostFromProperties(ctx) require.NoError(t, err) require.Equal(t, unixSocket, socket) }) @@ -201,10 +211,11 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Testcontainers host is not defined in properties", func(t *testing.T) { content := "ryuk.disabled=false" + ctx := t.Context() setupTestcontainersProperties(t, content) - socket, err := testcontainersHostFromProperties(context.Background()) + socket, err := testcontainersHostFromProperties(ctx) require.ErrorIs(t, err, ErrTestcontainersHostNotSetInProperties) require.Empty(t, socket) }) @@ -213,18 +224,20 @@ func TestExtractDockerHost(t *testing.T) { tmpDir := t.TempDir() tmpSocket := filepath.Join(tmpDir, "docker.sock") t.Setenv("DOCKER_HOST", tmpSocket) + ctx := t.Context() err := createTmpDockerSocket(tmpDir) require.NoError(t, err) - socket, err := dockerHostFromEnv(context.Background()) + socket, err := dockerHostFromEnv(ctx) require.NoError(t, err) require.Equal(t, tmpSocket, socket) }) t.Run("DOCKER_HOST is not set", func(t *testing.T) { t.Setenv("DOCKER_HOST", "") + ctx := t.Context() - socket, err := dockerHostFromEnv(context.Background()) + socket, err := dockerHostFromEnv(ctx) require.ErrorIs(t, err, ErrDockerHostNotSet) require.Empty(t, socket) }) @@ -254,7 +267,7 @@ func TestExtractDockerHost(t *testing.T) { }) t.Run("Context sets the Docker socket", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() socket, err := dockerHostFromContext(context.WithValue(ctx, DockerHostContextKey, DockerSocketSchema+"/this/is/a/sample.sock")) require.NoError(t, err) @@ -262,7 +275,7 @@ func TestExtractDockerHost(t *testing.T) { }) t.Run("Context sets a malformed Docker socket", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() socket, err := dockerHostFromContext(context.WithValue(ctx, DockerHostContextKey, "path-to-docker-sock")) require.Error(t, err) @@ -270,7 +283,7 @@ func TestExtractDockerHost(t *testing.T) { }) t.Run("Context sets a malformed schema for the Docker socket", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() socket, err := dockerHostFromContext(context.WithValue(ctx, DockerHostContextKey, "http://example.com/docker.sock")) require.ErrorIs(t, err, ErrNoUnixSchema) @@ -279,8 +292,9 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Docker socket exists", func(t *testing.T) { tmpSocket := setupDockerSocket(t) + ctx := t.Context() - socket, err := dockerSocketPath(context.Background()) + socket, err := dockerSocketPath(ctx) require.NoError(t, err) require.Equal(t, tmpSocket, socket) }) @@ -288,28 +302,31 @@ func TestExtractDockerHost(t *testing.T) { t.Run("Docker host is defined in properties", func(t *testing.T) { tmpSocket := "unix:///this/is/a/sample.sock" content := "docker.host=" + tmpSocket + ctx := t.Context() setupTestcontainersProperties(t, content) - socket, err := dockerHostFromProperties(context.Background()) + socket, err := dockerHostFromProperties(ctx) require.NoError(t, err) require.Equal(t, tmpSocket, socket) }) t.Run("Docker host is not defined in properties", func(t *testing.T) { content := "ryuk.disabled=false" + ctx := t.Context() setupTestcontainersProperties(t, content) - socket, err := dockerHostFromProperties(context.Background()) + socket, err := dockerHostFromProperties(ctx) require.ErrorIs(t, err, ErrDockerSocketNotSetInProperties) require.Empty(t, socket) }) t.Run("Docker socket does not exist", func(t *testing.T) { + ctx := t.Context() setupDockerSocketNotFound(t) - socket, err := dockerSocketPath(context.Background()) + socket, err := dockerSocketPath(ctx) require.ErrorIs(t, err, ErrSocketNotFoundInPath) require.Empty(t, socket) }) @@ -341,44 +358,47 @@ func TestExtractDockerSocketFromClient(t *testing.T) { setupTestcontainersProperties(t, content) - socket := extractDockerSocketFromClient(context.Background(), mockCli{OS: "foo"}) + socket := extractDockerSocketFromClient(t.Context(), mockCli{OS: "foo"}) require.Equal(t, DockerSocketPath, socket) }) t.Run("Docker socket from Testcontainers host takes precedence over TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", func(t *testing.T) { content := "tc.host=" + testRemoteHost + ctx := t.Context() setupTestcontainersProperties(t, content) t.Cleanup(resetSocketOverrideFn) t.Setenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", "/path/to/docker.sock") - socket := extractDockerSocketFromClient(context.Background(), mockCli{OS: "foo"}) + socket := extractDockerSocketFromClient(ctx, mockCli{OS: "foo"}) require.Equal(t, DockerSocketPath, socket) }) t.Run("Docker Socket as Testcontainers environment variable", func(t *testing.T) { + ctx := t.Context() setupTestcontainersProperties(t, "") t.Cleanup(resetSocketOverrideFn) t.Setenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", "/path/to/docker.sock") - host := extractDockerSocketFromClient(context.Background(), mockCli{OS: "foo"}) + host := extractDockerSocketFromClient(ctx, mockCli{OS: "foo"}) require.Equal(t, "/path/to/docker.sock", host) }) t.Run("Docker Socket as Testcontainers environment variable, removes prefixes", func(t *testing.T) { + ctx := t.Context() setupTestcontainersProperties(t, "") t.Cleanup(resetSocketOverrideFn) t.Setenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", DockerSocketSchema+"/path/to/docker.sock") - host := extractDockerSocketFromClient(context.Background(), mockCli{OS: "foo"}) + host := extractDockerSocketFromClient(ctx, mockCli{OS: "foo"}) require.Equal(t, "/path/to/docker.sock", host) t.Setenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", testRemoteHost) - host = extractDockerSocketFromClient(context.Background(), mockCli{OS: "foo"}) + host = extractDockerSocketFromClient(ctx, mockCli{OS: "foo"}) require.Equal(t, DockerSocketPath, host) }) @@ -392,7 +412,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") t.Setenv("DOCKER_HOST", DockerSocketSchema+"/this/is/a/sample.sock") @@ -407,7 +427,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") t.Setenv("DOCKER_HOST", DockerSocketSchema+"/this/is/a/sample.sock") @@ -421,7 +441,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") t.Setenv("DOCKER_HOST", DockerSocketSchema+"/this/is/a/sample.sock") @@ -435,7 +455,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") t.Setenv("DOCKER_HOST", DockerSocketSchema+"/this/is/a/sample.sock") @@ -454,7 +474,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") os.Unsetenv("DOCKER_HOST") @@ -469,7 +489,7 @@ func TestExtractDockerSocketFromClient(t *testing.T) { t.Cleanup(resetSocketOverrideFn) - ctx := context.Background() + ctx := t.Context() os.Unsetenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE") os.Unsetenv("DOCKER_HOST") diff --git a/internal/core/docker_rootless_test.go b/internal/core/docker_rootless_test.go index d6a338acdb..4250e158e8 100644 --- a/internal/core/docker_rootless_test.go +++ b/internal/core/docker_rootless_test.go @@ -1,7 +1,6 @@ package core import ( - "context" "os" "path/filepath" "strconv" @@ -68,7 +67,7 @@ func TestRootlessDockerSocketPathNotSupportedOnWindows(t *testing.T) { }) t.Setenv("GOOS", "windows") - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.ErrorIs(t, err, ErrRootlessDockerNotSupportedWindows) require.Empty(t, socketPath) } @@ -98,7 +97,7 @@ func TestRootlessDockerSocketPath(t *testing.T) { err := createTmpDockerSocket(tmpDir) require.NoError(t, err) - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.NoError(t, err) assert.NotEmpty(t, socketPath) }) @@ -117,7 +116,7 @@ func TestRootlessDockerSocketPath(t *testing.T) { require.NoError(t, err) t.Setenv("HOME", tmpDir) - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.NoError(t, err) assert.Equal(t, DockerSocketSchema+runDir+"/docker.sock", socketPath) }) @@ -136,7 +135,7 @@ func TestRootlessDockerSocketPath(t *testing.T) { require.NoError(t, err) t.Setenv("HOME", tmpDir) - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.NoError(t, err) assert.Equal(t, DockerSocketSchema+desktopDir+"/docker.sock", socketPath) }) @@ -165,7 +164,7 @@ func TestRootlessDockerSocketPath(t *testing.T) { err = createTmpDockerSocket(runDir) require.NoError(t, err) - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.NoError(t, err) assert.Equal(t, DockerSocketSchema+runDir+"/docker.sock", socketPath) }) @@ -177,7 +176,7 @@ func TestRootlessDockerSocketPath(t *testing.T) { setupRootlessNotFound(t) - socketPath, err := rootlessDockerSocketPath(context.Background()) + socketPath, err := rootlessDockerSocketPath(t.Context()) require.ErrorIs(t, err, ErrRootlessDockerNotFoundXDGRuntimeDir) require.Empty(t, socketPath) }) diff --git a/lifecycle_test.go b/lifecycle_test.go index 2e60ce0613..df5b7eaeb8 100644 --- a/lifecycle_test.go +++ b/lifecycle_test.go @@ -23,7 +23,7 @@ import ( ) func TestPreCreateModifierHook(t *testing.T) { - ctx := context.Background() + ctx := t.Context() provider, err := NewDockerProvider() require.NoError(t, err) @@ -493,7 +493,7 @@ func TestLifecycleHooks(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { prints := []string{} - ctx := context.Background() + ctx := t.Context() // optsWithLifecycleHooks { opts := []ContainerCustomizer{ WithAdditionalLifecycleHooks(ContainerLifecycleHooks{ @@ -627,7 +627,7 @@ func (l *inMemoryLogger) Printf(format string, args ...any) { // } func TestLifecycleHooks_WithDefaultLogger(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // optsWithDefaultLoggingHook { dl := inMemoryLogger{} @@ -700,26 +700,26 @@ func TestCombineLifecycleHooks(t *testing.T) { // call all the hooks in the right order, honouring the lifecycle req := ContainerRequest{} - err := hooks.Creating(context.Background())(req) + err := hooks.Creating(t.Context())(req) require.NoError(t, err) c := &DockerContainer{} - err = hooks.Created(context.Background())(c) + err = hooks.Created(t.Context())(c) require.NoError(t, err) - err = hooks.Starting(context.Background())(c) + err = hooks.Starting(t.Context())(c) require.NoError(t, err) - err = hooks.Started(context.Background())(c) + err = hooks.Started(t.Context())(c) require.NoError(t, err) - err = hooks.Readied(context.Background())(c) + err = hooks.Readied(t.Context())(c) require.NoError(t, err) - err = hooks.Stopping(context.Background())(c) + err = hooks.Stopping(t.Context())(c) require.NoError(t, err) - err = hooks.Stopped(context.Background())(c) + err = hooks.Stopped(t.Context())(c) require.NoError(t, err) - err = hooks.Terminating(context.Background())(c) + err = hooks.Terminating(t.Context())(c) require.NoError(t, err) - err = hooks.Terminated(context.Background())(c) + err = hooks.Terminated(t.Context())(c) require.NoError(t, err) // assertions @@ -790,7 +790,7 @@ func TestCombineLifecycleHooks(t *testing.T) { } func TestLifecycleHooks_WithMultipleHooks(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dl := inMemoryLogger{} @@ -826,7 +826,7 @@ func (l *linesTestLogger) Printf(format string, args ...any) { } func TestPrintContainerLogsOnError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() arrayOfLinesLogger := linesTestLogger{ data: []string{}, @@ -970,7 +970,7 @@ func Test_combineContainerHooks(t *testing.T) { PostTerminates: []ContainerHook{userContainerHook, defaultContainerHook}, } - ctx := context.Background() + ctx := t.Context() ctxVal := reflect.ValueOf(ctx) var req ContainerRequest reqVal := reflect.ValueOf(req) diff --git a/logconsumer_test.go b/logconsumer_test.go index cfbd763d32..ecd340984f 100644 --- a/logconsumer_test.go +++ b/logconsumer_test.go @@ -68,7 +68,7 @@ func devNullAcceptorChan() chan string { } func Test_LogConsumerGetsCalled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() g := TestLogConsumer{ msgs: []string{}, @@ -128,7 +128,7 @@ func (t *TestLogTypeConsumer) Accept(l Log) { } func Test_ShouldRecognizeLogTypes(t *testing.T) { - ctx := context.Background() + ctx := t.Context() g := TestLogTypeConsumer{ LogTypes: map[string]string{}, @@ -172,7 +172,7 @@ func Test_ShouldRecognizeLogTypes(t *testing.T) { } func Test_MultipleLogConsumers(t *testing.T) { - ctx := context.Background() + ctx := t.Context() first := TestLogConsumer{ msgs: []string{}, @@ -233,7 +233,7 @@ func TestContainerLogWithErrClosed(t *testing.T) { // First spin up a docker-in-docker container, then spin up an inner container within that dind container // Logs are being read from the inner container via the dind container's tcp port, which can be briefly // closed to test behaviour in connection-closed situations. - ctx := context.Background() + ctx := t.Context() dind, err := Run( ctx, "docker:dind", @@ -343,7 +343,7 @@ func TestContainerLogWithErrClosed(t *testing.T) { } func TestContainerLogsShouldBeWithoutStreamHeader(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "alpine:latest", WithCmd("sh", "-c", "echo 'abcdefghi' && echo 'foo'"), @@ -361,7 +361,7 @@ func TestContainerLogsShouldBeWithoutStreamHeader(t *testing.T) { } func TestContainerLogsTty(t *testing.T) { - ctx := context.Background() + ctx := t.Context() opts := []ContainerCustomizer{ WithCmd("sh", "-c", "echo 'abcdefghi' && echo 'foo'"), @@ -384,7 +384,7 @@ func TestContainerLogsTty(t *testing.T) { } func TestContainerLogsEnableAtStart(t *testing.T) { - ctx := context.Background() + ctx := t.Context() g := TestLogConsumer{ msgs: []string{}, Done: make(chan struct{}), @@ -430,7 +430,7 @@ func TestContainerLogsEnableAtStart(t *testing.T) { } func Test_StartLogProductionStillStartsWithTooLowTimeout(t *testing.T) { - ctx := context.Background() + ctx := t.Context() g := TestLogConsumer{ msgs: []string{}, @@ -457,7 +457,7 @@ func Test_StartLogProductionStillStartsWithTooLowTimeout(t *testing.T) { } func Test_StartLogProductionStillStartsWithTooHighTimeout(t *testing.T) { - ctx := context.Background() + ctx := t.Context() g := TestLogConsumer{ msgs: []string{}, @@ -526,7 +526,7 @@ func Test_MultiContainerLogConsumer_CancelledContext(t *testing.T) { }) // Context with cancellation functionality for simulating user interruption - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() // Ensure it gets called. first := TestLogConsumer{ @@ -651,7 +651,7 @@ func NewFooLogConsumer(t *testing.T) *FooLogConsumer { func TestRestartContainerWithLogConsumer(t *testing.T) { logConsumer := NewFooLogConsumer(t) - ctx := context.Background() + ctx := t.Context() ctr, err := Run( ctx, "hello-world", WithAlwaysPull(), diff --git a/modulegen/_template/module_test.go.tmpl b/modulegen/_template/module_test.go.tmpl index 1850e568c9..7ca7a8dda0 100644 --- a/modulegen/_template/module_test.go.tmpl +++ b/modulegen/_template/module_test.go.tmpl @@ -11,7 +11,7 @@ import ( ) func Test{{ $title }}(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := {{ $lower }}.{{ $entrypoint }}(ctx, "{{ $image }}") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/aerospike/aerospike_test.go b/modules/aerospike/aerospike_test.go index 685e0d0724..17262f45b4 100644 --- a/modules/aerospike/aerospike_test.go +++ b/modules/aerospike/aerospike_test.go @@ -22,7 +22,7 @@ const ( // The tests use the testcontainers-go library to manage container lifecycle func TestAeroSpike(t *testing.T) { t.Run("valid-image-succeeds", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() container, err := aerospike.Run(ctx, aerospikeImage) testcontainers.CleanupContainer(t, container) require.NoError(t, err) @@ -30,7 +30,7 @@ func TestAeroSpike(t *testing.T) { }) t.Run("applies-container-customizations", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() customEnv := "TEST_ENV=value" container, err := aerospike.Run(ctx, aerospikeImage, testcontainers.WithEnv(map[string]string{"CUSTOM_ENV": customEnv})) @@ -40,7 +40,7 @@ func TestAeroSpike(t *testing.T) { }) t.Run("respects-context-cancellation", func(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Millisecond) defer cancel() container, err := aerospike.Run(ctx, aerospikeImage) testcontainers.CleanupContainer(t, container) diff --git a/modules/arangodb/arangodb_test.go b/modules/arangodb/arangodb_test.go index 8f4f78afcc..afaa1736e4 100644 --- a/modules/arangodb/arangodb_test.go +++ b/modules/arangodb/arangodb_test.go @@ -1,7 +1,6 @@ package arangodb_test import ( - "context" "testing" "github.com/arangodb/go-driver/v2/arangodb" @@ -13,7 +12,7 @@ import ( ) func TestArangoDB(t *testing.T) { - ctx := context.Background() + ctx := t.Context() const password = "t3stc0ntain3rs!" @@ -33,7 +32,7 @@ func TestArangoDB(t *testing.T) { client := arangodb.NewClient(conn) - versionInfo, err := client.Version(context.Background()) + versionInfo, err := client.Version(ctx) require.NoError(t, err) require.Equal(t, "arango", versionInfo.Server) } diff --git a/modules/arangodb/examples_test.go b/modules/arangodb/examples_test.go index 8e3398cc8c..977e1e256f 100644 --- a/modules/arangodb/examples_test.go +++ b/modules/arangodb/examples_test.go @@ -84,7 +84,7 @@ func ExampleRun_usingClient() { client := arangodb.NewClient(conn) // Ask the version of the server - versionInfo, err := client.Version(context.Background()) + versionInfo, err := client.Version(ctx) if err != nil { log.Printf("Failed to get version info: %v", err) return diff --git a/modules/artemis/artemis_test.go b/modules/artemis/artemis_test.go index 70dcab9440..aab522fdd3 100644 --- a/modules/artemis/artemis_test.go +++ b/modules/artemis/artemis_test.go @@ -1,7 +1,6 @@ package artemis_test import ( - "context" "encoding/json" "net/http" "testing" @@ -16,7 +15,7 @@ import ( ) func TestArtemis(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string @@ -126,7 +125,7 @@ func TestArtemis(t *testing.T) { func expectQueue(t *testing.T, container *artemis.Container, queueName string) { t.Helper() - u, err := container.ConsoleURL(context.Background()) + u, err := container.ConsoleURL(t.Context()) require.NoError(t, err) r, err := http.Get(u + `/jolokia/read/org.apache.activemq.artemis:broker="0.0.0.0"/QueueNames`) diff --git a/modules/azure/azurite/azurite_test.go b/modules/azure/azurite/azurite_test.go index 1809ae767e..509b23f979 100644 --- a/modules/azure/azurite/azurite_test.go +++ b/modules/azure/azurite/azurite_test.go @@ -1,7 +1,6 @@ package azurite_test import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -11,7 +10,7 @@ import ( ) func TestAzurite(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := azurite.Run(ctx, "mcr.microsoft.com/azure-storage/azurite:3.23.0") testcontainers.CleanupContainer(t, ctr) @@ -21,7 +20,7 @@ func TestAzurite(t *testing.T) { } func TestAzurite_inMemoryPersistence(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("v28-above", func(t *testing.T) { ctr, err := azurite.Run(ctx, "mcr.microsoft.com/azure-storage/azurite:3.28.0", azurite.WithInMemoryPersistence(64)) @@ -37,7 +36,7 @@ func TestAzurite_inMemoryPersistence(t *testing.T) { } func TestAzurite_serviceURL(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := azurite.Run(ctx, "mcr.microsoft.com/azure-storage/azurite:3.23.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/azure/azurite/examples_test.go b/modules/azure/azurite/examples_test.go index 9fc8c91f21..9ef4799b53 100644 --- a/modules/azure/azurite/examples_test.go +++ b/modules/azure/azurite/examples_test.go @@ -99,7 +99,7 @@ func ExampleRun_blobOperations() { // ===== 1. Create a container ===== // createContainer { containerName := "testcontainer" - _, err = client.CreateContainer(context.TODO(), containerName, nil) + _, err = client.CreateContainer(ctx, containerName, nil) if err != nil { log.Printf("failed to create container: %s", err) return @@ -111,7 +111,7 @@ func ExampleRun_blobOperations() { blobData := "Hello world!" blobName := "HelloWorld.txt" - _, err = client.UploadStream(context.TODO(), + _, err = client.UploadStream(ctx, containerName, blobName, strings.NewReader(blobData), @@ -125,7 +125,7 @@ func ExampleRun_blobOperations() { } // Download the blob's contents and ensure that the download worked properly - blobDownloadResponse, err := client.DownloadStream(context.TODO(), containerName, blobName, nil) + blobDownloadResponse, err := client.DownloadStream(ctx, containerName, blobName, nil) if err != nil { log.Printf("failed to download blob: %s", err) return @@ -155,7 +155,7 @@ func ExampleRun_blobOperations() { // PageResponse() can be used to iterate over the results of the specific page. pager := client.NewListBlobsFlatPager(containerName, nil) for pager.More() { - resp, err := pager.NextPage(context.TODO()) + resp, err := pager.NextPage(ctx) if err != nil { log.Printf("failed to list blobs: %s", err) return @@ -167,7 +167,7 @@ func ExampleRun_blobOperations() { // Delete the blob. // deleteBlob { - _, err = client.DeleteBlob(context.TODO(), containerName, blobName, nil) + _, err = client.DeleteBlob(ctx, containerName, blobName, nil) if err != nil { log.Printf("failed to delete blob: %s", err) return @@ -176,7 +176,7 @@ func ExampleRun_blobOperations() { // Delete the container. // deleteContainer { - _, err = client.DeleteContainer(context.TODO(), containerName, nil) + _, err = client.DeleteContainer(ctx, containerName, nil) if err != nil { log.Printf("failed to delete container: %s", err) return @@ -239,7 +239,7 @@ func ExampleRun_queueOperations() { // createQueue { queueName := "testqueue" - _, err = client.CreateQueue(context.TODO(), queueName, &azqueue.CreateOptions{ + _, err = client.CreateQueue(ctx, queueName, &azqueue.CreateOptions{ Metadata: map[string]*string{"hello": to.Ptr("world")}, }) if err != nil { @@ -256,7 +256,7 @@ func ExampleRun_queueOperations() { // list pre-existing queues for pager.More() { - resp, err := pager.NextPage(context.Background()) + resp, err := pager.NextPage(ctx) if err != nil { log.Printf("failed to list queues: %s", err) return @@ -269,7 +269,7 @@ func ExampleRun_queueOperations() { // ===== 3. Delete the queue ===== // deleteQueue { - _, err = client.DeleteQueue(context.TODO(), queueName, &azqueue.DeleteOptions{}) + _, err = client.DeleteQueue(ctx, queueName, &azqueue.DeleteOptions{}) if err != nil { log.Printf("failed to delete queue: %s", err) return @@ -332,7 +332,7 @@ func ExampleRun_tableOperations() { // ===== 1. Create a table ===== // createTable { tableName := "fromServiceClient" - _, err = client.CreateTable(context.TODO(), tableName, nil) + _, err = client.CreateTable(ctx, tableName, nil) if err != nil { log.Printf("failed to create table: %s", err) return @@ -343,7 +343,7 @@ func ExampleRun_tableOperations() { // listTables { pager := client.NewListTablesPager(nil) for pager.More() { - resp, err := pager.NextPage(context.Background()) + resp, err := pager.NextPage(ctx) if err != nil { log.Printf("failed to list tables: %s", err) return @@ -356,7 +356,7 @@ func ExampleRun_tableOperations() { // ===== 3. Delete a table ===== // deleteTable { - _, err = client.DeleteTable(context.TODO(), tableName, nil) + _, err = client.DeleteTable(ctx, tableName, nil) if err != nil { fmt.Println(err) return diff --git a/modules/azure/eventhubs/eventhubs_test.go b/modules/azure/eventhubs/eventhubs_test.go index 2e49b16872..caba112b49 100644 --- a/modules/azure/eventhubs/eventhubs_test.go +++ b/modules/azure/eventhubs/eventhubs_test.go @@ -1,7 +1,6 @@ package eventhubs_test import ( - "context" _ "embed" "io" "strings" @@ -17,7 +16,7 @@ import ( var eventhubsConfig string func TestEventHubs_topology(t *testing.T) { - ctx := context.Background() + ctx := t.Context() const azuriteImage = "mcr.microsoft.com/azure-storage/azurite:3.33.0" @@ -50,7 +49,7 @@ func TestEventHubs_topology(t *testing.T) { } func TestEventHubs_withConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() const azuriteImage = "mcr.microsoft.com/azure-storage/azurite:3.33.0" @@ -75,7 +74,7 @@ func TestEventHubs_withConfig(t *testing.T) { } func TestEventHubs_noEULA(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := eventhubs.Run(ctx, "mcr.microsoft.com/azure-messaging/eventhubs-emulator:2.1.0") require.Error(t, err) diff --git a/modules/azure/eventhubs/examples_test.go b/modules/azure/eventhubs/examples_test.go index 727e7daae3..295ea28db1 100644 --- a/modules/azure/eventhubs/examples_test.go +++ b/modules/azure/eventhubs/examples_test.go @@ -98,7 +98,7 @@ func ExampleRun_sendEventsToEventHub() { log.Printf("failed to create producer client: %s", err) return } - defer producerClient.Close(context.TODO()) + defer producerClient.Close(ctx) // } // ===== 2. Create sample events ===== @@ -122,7 +122,7 @@ func ExampleRun_sendEventsToEventHub() { // Retry creating the event data batch 3 times, because the event hub is created from the configuration // and Testcontainers cannot add a wait strategy for the event hub to be created. for retries := 0; retries < maxRetries; retries++ { - batch, err = producerClient.NewEventDataBatch(context.TODO(), newBatchOptions) + batch, err = producerClient.NewEventDataBatch(ctx, newBatchOptions) if err == nil { break } @@ -144,7 +144,7 @@ func ExampleRun_sendEventsToEventHub() { // ===== 4. Send the batch of events to the event hub ===== // sendEventDataBatch { - err = producerClient.SendEventDataBatch(context.TODO(), batch, nil) + err = producerClient.SendEventDataBatch(ctx, batch, nil) if err != nil { log.Printf("failed to send event data batch: %s", err) return diff --git a/modules/azure/servicebus/examples_test.go b/modules/azure/servicebus/examples_test.go index b30f77e5d8..905c252653 100644 --- a/modules/azure/servicebus/examples_test.go +++ b/modules/azure/servicebus/examples_test.go @@ -118,7 +118,7 @@ func ExampleRun_authenticateCreateClient() { log.Printf("failed to create sender: %s", err) return } - defer sender.Close(context.TODO()) + defer sender.Close(ctx) sbMessage := &azservicebus.Message{ Body: []byte(message), @@ -127,7 +127,7 @@ func ExampleRun_authenticateCreateClient() { // Retry sending the message 3 times, because the queue is created from the configuration // and Testcontainers cannot add a wait strategy for the queue to be created. for retries := 0; retries < maxRetries; retries++ { - err = sender.SendMessage(context.TODO(), sbMessage, nil) + err = sender.SendMessage(ctx, sbMessage, nil) if err == nil { break } @@ -146,12 +146,12 @@ func ExampleRun_authenticateCreateClient() { fmt.Printf("failed to create receiver: %s", err) return } - defer receiver.Close(context.TODO()) + defer receiver.Close(ctx) // Receive 1 message from the queue messagesCount := 1 - messages, err := receiver.ReceiveMessages(context.TODO(), messagesCount, nil) + messages, err := receiver.ReceiveMessages(ctx, messagesCount, nil) if err != nil { fmt.Printf("failed to receive messages: %s", err) return @@ -163,7 +163,7 @@ func ExampleRun_authenticateCreateClient() { body := message.Body fmt.Printf("%s\n", string(body)) - err = receiver.CompleteMessage(context.TODO(), message, nil) + err = receiver.CompleteMessage(ctx, message, nil) if err != nil { fmt.Printf("failed to complete message: %s", err) return diff --git a/modules/azure/servicebus/servicebus_test.go b/modules/azure/servicebus/servicebus_test.go index e8db5e47ee..b09132a5a1 100644 --- a/modules/azure/servicebus/servicebus_test.go +++ b/modules/azure/servicebus/servicebus_test.go @@ -1,7 +1,6 @@ package servicebus_test import ( - "context" _ "embed" "io" "strings" @@ -17,7 +16,7 @@ import ( var servicebusConfig string func TestServiceBus_topology(t *testing.T) { - ctx := context.Background() + ctx := t.Context() const mssqlImage = "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04" @@ -50,7 +49,7 @@ func TestServiceBus_topology(t *testing.T) { } func TestServiceBus_withConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() const mssqlImage = "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04" @@ -75,7 +74,7 @@ func TestServiceBus_withConfig(t *testing.T) { } func TestServiceBus_noEULA(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := servicebus.Run(ctx, "mcr.microsoft.com/azure-messaging/servicebus-emulator:1.1.2") require.Error(t, err) diff --git a/modules/azurite/azurite_test.go b/modules/azurite/azurite_test.go index 618fc28b0b..8a2fc8cd7f 100644 --- a/modules/azurite/azurite_test.go +++ b/modules/azurite/azurite_test.go @@ -1,7 +1,6 @@ package azurite_test import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -11,7 +10,7 @@ import ( ) func TestAzurite(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := azurite.Run(ctx, "mcr.microsoft.com/azure-storage/azurite:3.23.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/cassandra/cassandra_test.go b/modules/cassandra/cassandra_test.go index 4ca7385235..21596ac233 100644 --- a/modules/cassandra/cassandra_test.go +++ b/modules/cassandra/cassandra_test.go @@ -1,7 +1,6 @@ package cassandra_test import ( - "context" "path/filepath" "testing" @@ -18,7 +17,7 @@ type Test struct { } func TestCassandra(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := cassandra.Run(ctx, "cassandra:4.1.3") testcontainers.CleanupContainer(t, ctr) @@ -50,7 +49,7 @@ func TestCassandra(t *testing.T) { } func TestCassandraWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithConfigFile(filepath.Join("testdata", "config.yaml"))) testcontainers.CleanupContainer(t, ctr) @@ -72,7 +71,7 @@ func TestCassandraWithConfigFile(t *testing.T) { func TestCassandraWithInitScripts(t *testing.T) { t.Run("with init cql script", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // withInitScripts { ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithInitScripts(filepath.Join("testdata", "init.cql"))) @@ -97,7 +96,7 @@ func TestCassandraWithInitScripts(t *testing.T) { }) t.Run("with init bash script", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := cassandra.Run(ctx, "cassandra:4.1.3", cassandra.WithInitScripts(filepath.Join("testdata", "init.sh"))) testcontainers.CleanupContainer(t, ctr) diff --git a/modules/chroma/chroma_test.go b/modules/chroma/chroma_test.go index 5d975c3602..ad0285b96c 100644 --- a/modules/chroma/chroma_test.go +++ b/modules/chroma/chroma_test.go @@ -1,7 +1,6 @@ package chroma_test import ( - "context" "net/http" "testing" @@ -13,7 +12,7 @@ import ( ) func TestChroma(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := chroma.Run(ctx, "chromadb/chroma:0.4.24") testcontainers.CleanupContainer(t, ctr) @@ -35,13 +34,14 @@ func TestChroma(t *testing.T) { t.Run("GetClient", func(tt *testing.T) { // restEndpoint { - endpoint, err := ctr.RESTEndpoint(context.Background()) + ctx := tt.Context() + endpoint, err := ctr.RESTEndpoint(ctx) require.NoErrorf(tt, err, "failed to get REST endpoint") chromaClient, err := chromago.NewClient(endpoint) // } require.NoErrorf(tt, err, "failed to create client") - hb, err := chromaClient.Heartbeat(context.TODO()) + hb, err := chromaClient.Heartbeat(ctx) require.NoError(tt, err) require.NotNil(tt, hb["nanosecond heartbeat"]) }) diff --git a/modules/chroma/examples_test.go b/modules/chroma/examples_test.go index dcbe4772ba..df11809bd7 100644 --- a/modules/chroma/examples_test.go +++ b/modules/chroma/examples_test.go @@ -55,7 +55,7 @@ func ExampleChromaContainer_connectWithClient() { return } - endpoint, err := chromaContainer.RESTEndpoint(context.Background()) + endpoint, err := chromaContainer.RESTEndpoint(ctx) if err != nil { log.Printf("failed to get REST endpoint: %s", err) return @@ -66,7 +66,7 @@ func ExampleChromaContainer_connectWithClient() { return } - hbs, errHb := chromaClient.Heartbeat(context.Background()) + hbs, errHb := chromaClient.Heartbeat(ctx) // } if _, ok := hbs["nanosecond heartbeat"]; ok { fmt.Println(ok) @@ -95,7 +95,7 @@ func ExampleChromaContainer_collections() { // getClient { // create the client connection and confirm that we can access the server with it - endpoint, err := chromaContainer.RESTEndpoint(context.Background()) + endpoint, err := chromaContainer.RESTEndpoint(ctx) if err != nil { log.Printf("failed to get REST endpoint: %s", err) return @@ -107,7 +107,7 @@ func ExampleChromaContainer_collections() { return } // reset { - reset, err := chromaClient.Reset(context.Background()) + reset, err := chromaClient.Reset(ctx) // } if err != nil { log.Printf("failed to reset: %s", err) @@ -117,7 +117,7 @@ func ExampleChromaContainer_collections() { // createCollection { // for testing we use a dummy hashing function NewConsistentHashEmbeddingFunction - col, err := chromaClient.CreateCollection(context.Background(), "test-collection", map[string]any{}, true, types.NewConsistentHashEmbeddingFunction(), types.L2) + col, err := chromaClient.CreateCollection(ctx, "test-collection", map[string]any{}, true, types.NewConsistentHashEmbeddingFunction(), types.L2) // } if err != nil { log.Printf("failed to create collection: %s", err) @@ -129,7 +129,7 @@ func ExampleChromaContainer_collections() { // addData { // verify it's possible to add data to the collection col1, err := col.Add( - context.Background(), + ctx, nil, // embeddings []map[string]any{}, // metadata []string{"test-doc-1", "test-doc-2"}, // documents @@ -141,12 +141,12 @@ func ExampleChromaContainer_collections() { return } - fmt.Println(col1.Count(context.Background())) + fmt.Println(col1.Count(ctx)) // queryCollection { // verify it's possible to query the collection queryResults, err := col1.QueryWithOptions( - context.Background(), + ctx, types.WithQueryTexts([]string{"test-doc-1"}), types.WithInclude(types.IDocuments, types.IEmbeddings, types.IMetadatas), types.WithNResults(1), @@ -160,7 +160,7 @@ func ExampleChromaContainer_collections() { fmt.Printf("Result of query: %v\n", queryResults) // listCollections { - cols, err := chromaClient.ListCollections(context.Background()) + cols, err := chromaClient.ListCollections(ctx) // } if err != nil { log.Printf("failed to list collections: %s", err) @@ -170,7 +170,7 @@ func ExampleChromaContainer_collections() { fmt.Println(len(cols)) // deleteCollection { - _, err = chromaClient.DeleteCollection(context.Background(), "test-collection") + _, err = chromaClient.DeleteCollection(ctx, "test-collection") // } if err != nil { log.Printf("failed to delete collection: %s", err) diff --git a/modules/clickhouse/clickhouse_test.go b/modules/clickhouse/clickhouse_test.go index 2b522598df..9c306eeeb8 100644 --- a/modules/clickhouse/clickhouse_test.go +++ b/modules/clickhouse/clickhouse_test.go @@ -28,7 +28,7 @@ type Test struct { } func TestClickHouseDefaultConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := clickhouse.Run(ctx, "clickhouse/clickhouse-server:23.3.8.21-alpine") testcontainers.CleanupContainer(t, ctr) @@ -49,12 +49,12 @@ func TestClickHouseDefaultConfig(t *testing.T) { require.NotNil(t, conn) defer conn.Close() - err = conn.Ping(context.Background()) + err = conn.Ping(t.Context()) require.NoError(t, err) } func TestClickHouseConnectionHost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := clickhouse.Run(ctx, "clickhouse/clickhouse-server:23.3.8.21-alpine", @@ -89,7 +89,7 @@ func TestClickHouseConnectionHost(t *testing.T) { } func TestClickHouseDSN(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := clickhouse.Run(ctx, "clickhouse/clickhouse-server:23.3.8.21-alpine", @@ -121,7 +121,7 @@ func TestClickHouseDSN(t *testing.T) { } func TestClickHouseWithInitScripts(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // withInitScripts { ctr, err := clickhouse.Run(ctx, @@ -151,13 +151,13 @@ func TestClickHouseWithInitScripts(t *testing.T) { defer conn.Close() // perform assertions - data, err := getAllRows(conn) + data, err := getAllRows(ctx, conn) require.NoError(t, err) require.Len(t, data, 1) } func TestClickHouseWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() testCases := []struct { desc string @@ -202,7 +202,7 @@ func TestClickHouseWithConfigFile(t *testing.T) { } func TestClickHouseWithZookeeper(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // withZookeeper { zkPort := nat.Port("2181/tcp") @@ -257,17 +257,17 @@ func performReplicatedCRUD(t *testing.T, conn driver.Conn) ([]Test, error) { t.Helper() return backoff.RetryNotifyWithData( func() ([]Test, error) { - err := conn.Exec(context.Background(), "CREATE TABLE replicated_test_table (id UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/mdb.data_transfer_cp_cdc', '{replica}') PRIMARY KEY (id) ORDER BY (id) SETTINGS index_granularity = 8192;") + err := conn.Exec(t.Context(), "CREATE TABLE replicated_test_table (id UInt64) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/mdb.data_transfer_cp_cdc', '{replica}') PRIMARY KEY (id) ORDER BY (id) SETTINGS index_granularity = 8192;") if err != nil { return nil, err } - err = conn.Exec(context.Background(), "INSERT INTO replicated_test_table (id) VALUES (1);") + err = conn.Exec(t.Context(), "INSERT INTO replicated_test_table (id) VALUES (1);") if err != nil { return nil, err } - rows, err := conn.Query(context.Background(), "SELECT * FROM replicated_test_table;") + rows, err := conn.Query(t.Context(), "SELECT * FROM replicated_test_table;") if err != nil { return nil, err } @@ -296,17 +296,18 @@ func performCRUD(t *testing.T, conn driver.Conn) ([]Test, error) { t.Helper() return backoff.RetryNotifyWithData( func() ([]Test, error) { - err := conn.Exec(context.Background(), "create table if not exists test_table (id UInt64) engine = MergeTree PRIMARY KEY (id) ORDER BY (id) SETTINGS index_granularity = 8192;") + ctx := t.Context() + err := conn.Exec(ctx, "create table if not exists test_table (id UInt64) engine = MergeTree PRIMARY KEY (id) ORDER BY (id) SETTINGS index_granularity = 8192;") if err != nil { return nil, err } - err = conn.Exec(context.Background(), "INSERT INTO test_table (id) VALUES (1);") + err = conn.Exec(ctx, "INSERT INTO test_table (id) VALUES (1);") if err != nil { return nil, err } - return getAllRows(conn) + return getAllRows(ctx, conn) }, backoff.NewExponentialBackOff(), func(err error, _ time.Duration) { @@ -315,8 +316,8 @@ func performCRUD(t *testing.T, conn driver.Conn) ([]Test, error) { ) } -func getAllRows(conn driver.Conn) ([]Test, error) { - rows, err := conn.Query(context.Background(), "SELECT * FROM test_table;") +func getAllRows(ctx context.Context, conn driver.Conn) ([]Test, error) { + rows, err := conn.Query(ctx, "SELECT * FROM test_table;") if err != nil { return nil, err } diff --git a/modules/cockroachdb/cockroachdb_test.go b/modules/cockroachdb/cockroachdb_test.go index e3a7bb1f12..4da5c49393 100644 --- a/modules/cockroachdb/cockroachdb_test.go +++ b/modules/cockroachdb/cockroachdb_test.go @@ -1,7 +1,6 @@ package cockroachdb_test import ( - "context" "database/sql" "testing" @@ -36,7 +35,7 @@ func TestRun_WithInsecure(t *testing.T) { }) t.Run("invalid-password-insecure", func(t *testing.T) { - _, err := cockroachdb.Run(context.Background(), testImage, + _, err := cockroachdb.Run(t.Context(), testImage, cockroachdb.WithPassword("testPassword"), cockroachdb.WithInsecure(), ) @@ -44,7 +43,7 @@ func TestRun_WithInsecure(t *testing.T) { }) t.Run("invalid-insecure-password", func(t *testing.T) { - _, err := cockroachdb.Run(context.Background(), testImage, + _, err := cockroachdb.Run(t.Context(), testImage, cockroachdb.WithInsecure(), cockroachdb.WithPassword("testPassword"), ) @@ -56,7 +55,7 @@ func TestRun_WithInsecure(t *testing.T) { func testContainer(t *testing.T, opts ...testcontainers.ContainerCustomizer) { t.Helper() - ctx := context.Background() + ctx := t.Context() ctr, err := cockroachdb.Run(ctx, testImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) diff --git a/modules/compose/compose_api_test.go b/modules/compose/compose_api_test.go index 020116cbfb..91da34a22d 100644 --- a/modules/compose/compose_api_test.go +++ b/modules/compose/compose_api_test.go @@ -28,7 +28,7 @@ func TestDockerComposeAPI(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, Wait(true)) @@ -36,7 +36,7 @@ func TestDockerComposeAPI(t *testing.T) { require.NoError(t, err, "compose.Up()") for _, service := range compose.Services() { - container, err := compose.ServiceContainer(context.Background(), service) + container, err := compose.ServiceContainer(t.Context(), service) require.NoError(t, err, "compose.ServiceContainer()") require.True(t, container.IsRunning()) } @@ -47,7 +47,7 @@ func TestDockerComposeAPIStrategyForInvalidService(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -68,7 +68,7 @@ func TestDockerComposeAPIWithWaitLogStrategy(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -89,7 +89,7 @@ func TestDockerComposeAPIWithRunServices(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -100,7 +100,7 @@ func TestDockerComposeAPIWithRunServices(t *testing.T) { serviceNames := compose.Services() - _, err = compose.ServiceContainer(context.Background(), "api-mysql") + _, err = compose.ServiceContainer(t.Context(), "api-mysql") require.Error(t, err, "Make sure there is no mysql container") require.Len(t, serviceNames, 1) @@ -146,7 +146,7 @@ func TestDockerComposeAPIWithProfiles(t *testing.T) { compose, err := NewDockerComposeWith(WithStackFiles(path), WithProfiles(test.withProfiles...)) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) for _, service := range test.wantServices { @@ -166,7 +166,7 @@ func TestDockerComposeAPI_TestcontainersLabelsArePresent(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -183,7 +183,7 @@ func TestDockerComposeAPI_TestcontainersLabelsArePresent(t *testing.T) { // all the services in the compose have the Testcontainers Labels for _, serviceName := range serviceNames { - c, err := compose.ServiceContainer(context.Background(), serviceName) + c, err := compose.ServiceContainer(t.Context(), serviceName) require.NoError(t, err, "compose.ServiceContainer()") inspect, err := compose.dockerClient.ContainerInspect(ctx, c.GetContainerID()) @@ -209,7 +209,7 @@ func TestDockerComposeAPI_WithReaper(t *testing.T) { // reaper is enabled, so we don't need to manually stop the containers: Ryuk will do it for us - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -236,7 +236,7 @@ func TestDockerComposeAPI_WithoutReaper(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -259,7 +259,7 @@ func TestDockerComposeAPIWithStopServices(t *testing.T) { WithLogger(log.TestLogger(t))) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, Wait(true)) @@ -273,7 +273,7 @@ func TestDockerComposeAPIWithStopServices(t *testing.T) { require.Contains(t, serviceNames, "api-mysql") // close mysql container in purpose - mysqlContainer, err := compose.ServiceContainer(context.Background(), "api-mysql") + mysqlContainer, err := compose.ServiceContainer(t.Context(), "api-mysql") require.NoError(t, err, "Get mysql container") stopTimeout := 10 * time.Second @@ -292,7 +292,7 @@ func TestDockerComposeAPIWithWaitForService(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -315,7 +315,7 @@ func TestDockerComposeAPIWithWaitHTTPStrategy(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -338,7 +338,7 @@ func TestDockerComposeAPIWithContainerName(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -361,7 +361,7 @@ func TestDockerComposeAPIWithWaitStrategy_NoExposedPorts(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -381,7 +381,7 @@ func TestDockerComposeAPIWithMultipleWaitStrategies(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -403,7 +403,7 @@ func TestDockerComposeAPIWithFailedStrategy(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -428,7 +428,7 @@ func TestDockerComposeAPIComplex(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, Wait(true)) @@ -457,7 +457,7 @@ services: compose, err := NewDockerComposeWith(WithStackReaders(strings.NewReader(composeContent)), identifier) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -474,7 +474,7 @@ services: require.Len(t, serviceNames, 1) assert.Contains(t, serviceNames, "api-nginx") - require.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveVolumes(true), RemoveImagesLocal), "compose.Down()") + require.NoError(t, compose.Down(t.Context(), RemoveOrphans(true), RemoveVolumes(true), RemoveImagesLocal), "compose.Down()") // check files where removed f, err := os.Stat(compose.configs[0]) @@ -501,7 +501,7 @@ services: ) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -535,7 +535,7 @@ func TestDockerComposeAPIWithEnvironment(t *testing.T) { compose, err := NewDockerComposeWith(WithStackFiles(path), identifier) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -571,7 +571,7 @@ func TestDockerComposeAPIWithMultipleComposeFiles(t *testing.T) { compose, err := NewDockerComposeWith(composeFiles, identifier) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -605,7 +605,7 @@ func TestDockerComposeAPIWithVolume(t *testing.T) { cleanup(t, compose) - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, Wait(true)) @@ -617,7 +617,7 @@ func TestDockerComposeAPIWithRecreate(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, WithRecreate(api.RecreateNever), WithRecreateDependencies(api.RecreateNever), Wait(true)) @@ -632,14 +632,14 @@ func TestDockerComposeAPIVolumesDeletedOnDown(t *testing.T) { compose, err := NewDockerComposeWith(stackFiles, StackIdentifier(identifier)) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose.Up(ctx, Wait(true)) cleanup(t, compose) require.NoError(t, err, "compose.Up()") - err = compose.Down(context.Background(), RemoveOrphans(true), RemoveVolumes(true), RemoveImagesLocal) + err = compose.Down(t.Context(), RemoveOrphans(true), RemoveVolumes(true), RemoveImagesLocal) require.NoError(t, err, "compose.Down()") volumeListFilters := filters.NewArgs() @@ -658,7 +658,7 @@ func TestDockerComposeAPIWithBuild(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -673,7 +673,7 @@ func TestDockerComposeApiWithWaitForShortLifespanService(t *testing.T) { compose, err := NewDockerCompose(path) require.NoError(t, err, "NewDockerCompose()") - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) err = compose. @@ -700,7 +700,7 @@ func cleanup(t *testing.T, compose ComposeStack) { t.Helper() t.Cleanup(func() { require.NoError(t, compose.Down( - context.Background(), + t.Context(), RemoveOrphans(true), RemoveVolumes(true), RemoveImagesLocal, diff --git a/modules/compose/compose_examples_test.go b/modules/compose/compose_examples_test.go index e1c44a4fd0..3bcfe7faf1 100644 --- a/modules/compose/compose_examples_test.go +++ b/modules/compose/compose_examples_test.go @@ -60,7 +60,7 @@ func ExampleNewDockerComposeWith() { } defer func() { err = stack.Down( - context.Background(), + ctx, compose.RemoveOrphans(true), compose.RemoveVolumes(true), compose.RemoveImagesLocal, @@ -82,14 +82,14 @@ func ExampleNewDockerComposeWith() { // nginx container is started // getServiceContainer { - nginxContainer, err := stack.ServiceContainer(context.Background(), "nginx") + nginxContainer, err := stack.ServiceContainer(ctx, "nginx") if err != nil { log.Printf("Failed to get container: %v", err) return } // } - inspect, err := nginxContainer.Inspect(context.Background()) + inspect, err := nginxContainer.Inspect(ctx) if err != nil { log.Printf("Failed to inspect container: %v", err) return @@ -145,7 +145,7 @@ func ExampleNewDockerComposeWith_waitForService() { } defer func() { err = stack.Down( - context.Background(), + ctx, compose.RemoveOrphans(true), compose.RemoveVolumes(true), compose.RemoveImagesLocal, diff --git a/modules/compose/compose_test.go b/modules/compose/compose_test.go index c9c8a6a56a..c3793145ec 100644 --- a/modules/compose/compose_test.go +++ b/modules/compose/compose_test.go @@ -1,7 +1,6 @@ package compose import ( - "context" "fmt" "path/filepath" "regexp" @@ -371,10 +370,11 @@ func TestLocalDockerComposeWithVolume(t *testing.T) { func assertVolumeDoesNotExist(tb testing.TB, volumeName string) { tb.Helper() - containerClient, err := testcontainers.NewDockerClientWithOpts(context.Background()) + ctx := tb.Context() + containerClient, err := testcontainers.NewDockerClientWithOpts(ctx) require.NoErrorf(tb, err, "Failed to get provider") - volumeList, err := containerClient.VolumeList(context.Background(), volume.ListOptions{Filters: filters.NewArgs(filters.Arg("name", volumeName))}) + volumeList, err := containerClient.VolumeList(ctx, volume.ListOptions{Filters: filters.NewArgs(filters.Arg("name", volumeName))}) require.NoErrorf(tb, err, "Failed to list volumes") if len(volumeList.Warnings) > 0 { @@ -391,10 +391,11 @@ func assertContainerEnvironmentVariables( absent map[string]string, ) { tb.Helper() - containerClient, err := testcontainers.NewDockerClientWithOpts(context.Background()) + ctx := tb.Context() + containerClient, err := testcontainers.NewDockerClientWithOpts(ctx) require.NoErrorf(tb, err, "Failed to get provider") - containers, err := containerClient.ContainerList(context.Background(), container.ListOptions{}) + containers, err := containerClient.ContainerList(ctx, container.ListOptions{}) require.NoErrorf(tb, err, "Failed to list containers") require.NotEmptyf(tb, containers, "container list empty") @@ -411,7 +412,7 @@ containerLoop: } } - details, err := containerClient.ContainerInspect(context.Background(), containerID) + details, err := containerClient.ContainerInspect(ctx, containerID) require.NoErrorf(tb, err, "Failed to inspect container") for k, v := range present { diff --git a/modules/consul/consul_test.go b/modules/consul/consul_test.go index 6f359b7261..3d7785eaf5 100644 --- a/modules/consul/consul_test.go +++ b/modules/consul/consul_test.go @@ -1,7 +1,6 @@ package consul_test import ( - "context" "net/http" "path/filepath" "testing" @@ -14,7 +13,7 @@ import ( ) func TestConsul(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string opts []testcontainers.ContainerCustomizer diff --git a/modules/couchbase/couchbase_test.go b/modules/couchbase/couchbase_test.go index 7cf1597b22..a2b4d2e1b8 100644 --- a/modules/couchbase/couchbase_test.go +++ b/modules/couchbase/couchbase_test.go @@ -20,7 +20,7 @@ const ( ) func TestCouchbaseWithCommunityContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // withBucket { bucketName := "testBucket" @@ -43,7 +43,7 @@ func TestCouchbaseWithCommunityContainer(t *testing.T) { } func TestCouchbaseWithEnterpriseContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucketName := "testBucket" bucket := tccouchbase.NewBucket(bucketName). @@ -65,7 +65,7 @@ func TestCouchbaseWithEnterpriseContainer(t *testing.T) { } func TestCouchbaseWithReuse(t *testing.T) { - ctx := context.Background() + ctx := t.Context() containerName := "couchbase-" + testcontainers.SessionID() @@ -108,7 +108,7 @@ func TestCouchbaseWithReuse(t *testing.T) { } func TestWithCredentials(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucketName := "testBucket" ctr, err := tccouchbase.Run(ctx, @@ -120,7 +120,7 @@ func TestWithCredentials(t *testing.T) { } func TestWithCredentials_Password_LessThan_6(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucketName := "testBucket" ctr, err := tccouchbase.Run(ctx, @@ -132,7 +132,7 @@ func TestWithCredentials_Password_LessThan_6(t *testing.T) { } func TestAnalyticsServiceWithCommunityContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucketName := "testBucket" ctr, err := tccouchbase.Run(ctx, @@ -144,7 +144,7 @@ func TestAnalyticsServiceWithCommunityContainer(t *testing.T) { } func TestEventingServiceWithCommunityContainer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bucketName := "testBucket" ctr, err := tccouchbase.Run(ctx, diff --git a/modules/databend/databend_test.go b/modules/databend/databend_test.go index 58ac71e327..77e394cead 100644 --- a/modules/databend/databend_test.go +++ b/modules/databend/databend_test.go @@ -1,7 +1,6 @@ package databend_test import ( - "context" "database/sql" "testing" @@ -13,7 +12,7 @@ import ( ) func TestDatabend(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := databend.Run(ctx, "datafuselabs/databend:v1.2.615") testcontainers.CleanupContainer(t, ctr) @@ -43,7 +42,7 @@ func TestDatabend(t *testing.T) { } func TestDatabendWithDefaultUserAndPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := databend.Run(ctx, "datafuselabs/databend:v1.2.615", diff --git a/modules/dind/dind_test.go b/modules/dind/dind_test.go index 1b7ff2b929..cebc2ca455 100644 --- a/modules/dind/dind_test.go +++ b/modules/dind/dind_test.go @@ -15,7 +15,7 @@ import ( func Test_LoadImages(t *testing.T) { // Give up to three minutes to run this test - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Minute)) + ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(3*time.Minute)) defer cancel() dindContainer, err := dind.Run(ctx, "docker:28.0.1-dind") diff --git a/modules/dockermcpgateway/dockermcpgateway_test.go b/modules/dockermcpgateway/dockermcpgateway_test.go index 351cdcad1a..3ebe25c77b 100644 --- a/modules/dockermcpgateway/dockermcpgateway_test.go +++ b/modules/dockermcpgateway/dockermcpgateway_test.go @@ -1,7 +1,6 @@ package dockermcpgateway_test import ( - "context" "io" "testing" @@ -12,7 +11,7 @@ import ( ) func TestDockerMCPGateway(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dmcpg.Run(ctx, "docker/mcp-gateway:latest") testcontainers.CleanupContainer(t, ctr) @@ -22,7 +21,7 @@ func TestDockerMCPGateway(t *testing.T) { } func TestDockerMCPGateway_withServerAndTools(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dmcpg.Run( ctx, "docker/mcp-gateway:latest", @@ -50,7 +49,7 @@ func TestDockerMCPGateway_withServerAndTools(t *testing.T) { } func TestDockerMCPGateway_withSecret(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dmcpg.Run( ctx, "docker/mcp-gateway:latest", @@ -68,7 +67,7 @@ func TestDockerMCPGateway_withSecret(t *testing.T) { } func TestDockerMCPGateway_withSecrets(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dmcpg.Run( ctx, "docker/mcp-gateway:latest", diff --git a/modules/dockermodelrunner/docker_desktop_test.go b/modules/dockermodelrunner/docker_desktop_test.go index e0ca4f7524..2275d72c2f 100644 --- a/modules/dockermodelrunner/docker_desktop_test.go +++ b/modules/dockermodelrunner/docker_desktop_test.go @@ -15,7 +15,7 @@ import ( // using the testing library and the log.TestLogger of Testcontainers func skipIfDockerDesktopNotRunning(t *testing.T) { t.Helper() - isDDRunning, err := isDockerDesktopRunning(log.TestLogger(t)) + isDDRunning, err := isDockerDesktopRunning(t.Context(), log.TestLogger(t)) require.NoError(t, err) if !isDDRunning { @@ -24,13 +24,13 @@ func skipIfDockerDesktopNotRunning(t *testing.T) { } // isDockerDesktopRunning checks if Docker Desktop is running. -func isDockerDesktopRunning(l log.Logger) (bool, error) { - cli, err := testcontainers.NewDockerClientWithOpts(context.Background()) +func isDockerDesktopRunning(ctx context.Context, l log.Logger) (bool, error) { + cli, err := testcontainers.NewDockerClientWithOpts(ctx) if err != nil { return false, fmt.Errorf("failed to create docker client: %w", err) } - info, err := cli.Info(context.Background()) + info, err := cli.Info(ctx) if err != nil { return false, fmt.Errorf("failed to get docker info: %w", err) } diff --git a/modules/dockermodelrunner/dockermodelrunner_test.go b/modules/dockermodelrunner/dockermodelrunner_test.go index 577df45996..243994073b 100644 --- a/modules/dockermodelrunner/dockermodelrunner_test.go +++ b/modules/dockermodelrunner/dockermodelrunner_test.go @@ -24,7 +24,7 @@ const ( func TestRun(t *testing.T) { skipIfDockerDesktopNotRunning(t) - ctx := context.Background() + ctx := t.Context() t.Run("success", func(t *testing.T) { ctr, err := dockermodelrunner.Run(ctx) @@ -47,7 +47,7 @@ func TestRun(t *testing.T) { func TestRun_client(t *testing.T) { skipIfDockerDesktopNotRunning(t) - ctx := context.Background() + ctx := t.Context() ctr, err := dockermodelrunner.Run(ctx) testcontainers.CleanupContainer(t, ctr) diff --git a/modules/dockermodelrunner/examples_test.go b/modules/dockermodelrunner/examples_test.go index b91e078b94..5354c6c78f 100644 --- a/modules/dockermodelrunner/examples_test.go +++ b/modules/dockermodelrunner/examples_test.go @@ -18,7 +18,8 @@ import ( ) func ExampleRun_withModel() { - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -29,7 +30,6 @@ func ExampleRun_withModel() { } // runWithModel { - ctx := context.Background() const ( modelNamespace = "ai" @@ -66,7 +66,8 @@ func ExampleRun_withModel() { } func ExampleRun_pullModel() { - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -77,8 +78,6 @@ func ExampleRun_pullModel() { return } - ctx := context.Background() - dmrCtr, err := dockermodelrunner.Run(ctx) defer func() { if err := testcontainers.TerminateContainer(dmrCtr); err != nil { @@ -129,7 +128,8 @@ func ExampleRun_inspectModel() { modelTag = "360M-Q4_K_M" ) - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -139,8 +139,6 @@ func ExampleRun_inspectModel() { return } - ctx := context.Background() - dmrCtr, err := dockermodelrunner.Run(ctx) defer func() { if err := testcontainers.TerminateContainer(dmrCtr); err != nil { @@ -178,7 +176,8 @@ func ExampleRun_listModels() { modelTag = "360M-Q4_K_M" ) - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -188,8 +187,6 @@ func ExampleRun_listModels() { return } - ctx := context.Background() - dmrCtr, err := dockermodelrunner.Run(ctx) defer func() { if err := testcontainers.TerminateContainer(dmrCtr); err != nil { @@ -225,7 +222,8 @@ func ExampleRun_listModels() { } func ExampleRun_openAI() { - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -235,8 +233,6 @@ func ExampleRun_openAI() { return } - ctx := context.Background() - dmrCtr, err := dockermodelrunner.Run(ctx) defer func() { if err := testcontainers.TerminateContainer(dmrCtr); err != nil { @@ -293,7 +289,8 @@ func ExampleRun_openAI() { } func ExampleRun_langchaingo() { - ok, err := isDockerDesktopRunning(log.Default()) + ctx := context.Background() + ok, err := isDockerDesktopRunning(ctx, log.Default()) if err != nil { log.Printf("failed to check if Docker Desktop is running: %s", err) return @@ -303,8 +300,6 @@ func ExampleRun_langchaingo() { return } - ctx := context.Background() - dmrCtr, err := dockermodelrunner.Run(ctx) defer func() { if err := testcontainers.TerminateContainer(dmrCtr); err != nil { diff --git a/modules/dolt/dolt_test.go b/modules/dolt/dolt_test.go index a1e46cc976..ed1b6b9070 100644 --- a/modules/dolt/dolt_test.go +++ b/modules/dolt/dolt_test.go @@ -1,7 +1,6 @@ package dolt_test import ( - "context" "database/sql" "os" "path/filepath" @@ -16,7 +15,7 @@ import ( ) func TestDolt(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dolt.Run(ctx, "dolthub/dolt-sql-server:1.32.4") testcontainers.CleanupContainer(t, ctr) @@ -44,7 +43,7 @@ func TestDolt(t *testing.T) { } func TestDoltWithNonRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dolt.Run(ctx, "dolthub/dolt-sql-server:1.32.4", @@ -56,7 +55,7 @@ func TestDoltWithNonRootUserAndEmptyPassword(t *testing.T) { } func TestDoltWithPublicRemoteCloneUrl(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dolt.Run(ctx, "dolthub/dolt-sql-server:1.32.4", @@ -80,7 +79,7 @@ func createTestCredsFile(t *testing.T) string { } func TestDoltWithPrivateRemoteCloneUrl(t *testing.T) { - ctx := context.Background() + ctx := t.Context() filename := createTestCredsFile(t) ctr, err := dolt.Run(ctx, @@ -97,7 +96,7 @@ func TestDoltWithPrivateRemoteCloneUrl(t *testing.T) { } func TestDoltWithRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dolt.Run(ctx, "dolthub/dolt-sql-server:1.32.4", @@ -126,7 +125,7 @@ func TestDoltWithRootUserAndEmptyPassword(t *testing.T) { } func TestDoltWithScripts(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := dolt.Run(ctx, "dolthub/dolt-sql-server:1.32.4", diff --git a/modules/dynamodb/dynamodb_test.go b/modules/dynamodb/dynamodb_test.go index dd6e967492..25559e539b 100644 --- a/modules/dynamodb/dynamodb_test.go +++ b/modules/dynamodb/dynamodb_test.go @@ -28,7 +28,7 @@ const ( var image2_2_1 = baseImage + "2.2.1" func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, image2_2_1) testcontainers.CleanupContainer(t, ctr) @@ -47,7 +47,7 @@ func TestRun(t *testing.T) { } func TestRun_withCustomImageVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, "amazon/dynamodb-local:2.2.0") testcontainers.CleanupContainer(t, ctr) @@ -55,14 +55,14 @@ func TestRun_withCustomImageVersion(t *testing.T) { } func TestRun_withInvalidCustomImageVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := tcdynamodb.Run(ctx, "amazon/dynamodb-local:0.0.7") require.Error(t, err) } func TestRun_withoutEndpointResolver(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, image2_2_1) testcontainers.CleanupContainer(t, ctr) @@ -70,12 +70,12 @@ func TestRun_withoutEndpointResolver(t *testing.T) { cli := dynamodb.New(dynamodb.Options{}) - err = createTable(cli) + err = createTable(ctx, cli) require.Error(t, err) } func TestRun_withSharedDB(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, image2_2_1, tcdynamodb.WithSharedDB()) testcontainers.CleanupContainer(t, ctr) @@ -96,7 +96,7 @@ func TestRun_withSharedDB(t *testing.T) { // list tables and verify - result, err := cli2.ListTables(context.Background(), nil) + result, err := cli2.ListTables(t.Context(), nil) require.NoError(t, err, "dynamodb list tables operation failed") actualTableName := result.TableNames[0] @@ -113,7 +113,7 @@ func TestRun_withSharedDB(t *testing.T) { } func TestRun_withoutSharedDB(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr1, err := tcdynamodb.Run(ctx, image2_2_1) testcontainers.CleanupContainer(t, ctr1) @@ -135,13 +135,13 @@ func TestRun_withoutSharedDB(t *testing.T) { // list tables and verify - result, err := cli.ListTables(context.Background(), nil) + result, err := cli.ListTables(t.Context(), nil) require.NoError(t, err, "dynamodb list tables operation failed") require.Empty(t, result.TableNames, "table should not exist after restarting container") } func TestRun_shouldStartWithTelemetryDisabled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, image2_2_1, tcdynamodb.WithDisableTelemetry()) testcontainers.CleanupContainer(t, ctr) @@ -149,15 +149,15 @@ func TestRun_shouldStartWithTelemetryDisabled(t *testing.T) { } func TestRun_shouldStartWithSharedDBEnabledAndTelemetryDisabled(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcdynamodb.Run(ctx, image2_2_1, tcdynamodb.WithSharedDB(), tcdynamodb.WithDisableTelemetry()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) } -func createTable(client *dynamodb.Client) error { - _, err := client.CreateTable(context.Background(), &dynamodb.CreateTableInput{ +func createTable(ctx context.Context, client *dynamodb.Client) error { + _, err := client.CreateTable(ctx, &dynamodb.CreateTableInput{ TableName: aws.String(tableName), KeySchema: []types.KeySchemaElement{ { @@ -183,7 +183,7 @@ func createTable(client *dynamodb.Client) error { func addDataToTable(t *testing.T, client *dynamodb.Client, val string) { t.Helper() - _, err := client.PutItem(context.Background(), &dynamodb.PutItemInput{ + _, err := client.PutItem(t.Context(), &dynamodb.PutItemInput{ TableName: aws.String(tableName), Item: map[string]types.AttributeValue{ pkColumnName: &types.AttributeValueMemberS{Value: val}, @@ -195,7 +195,7 @@ func addDataToTable(t *testing.T, client *dynamodb.Client, val string) { func queryItem(t *testing.T, client *dynamodb.Client, val string) string { t.Helper() - output, err := client.GetItem(context.Background(), &dynamodb.GetItemInput{ + output, err := client.GetItem(t.Context(), &dynamodb.GetItemInput{ TableName: aws.String(tableName), Key: map[string]types.AttributeValue{ pkColumnName: &types.AttributeValueMemberS{Value: val}, @@ -225,12 +225,12 @@ func getDynamoDBClient(t *testing.T, c *tcdynamodb.DynamoDBContainer) *dynamodb. // createClient { var errs []error - hostPort, err := c.ConnectionString(context.Background()) + hostPort, err := c.ConnectionString(t.Context()) if err != nil { errs = append(errs, fmt.Errorf("get connection string: %w", err)) } - cfg, err := config.LoadDefaultConfig(context.Background(), config.WithCredentialsProvider(credentials.StaticCredentialsProvider{ + cfg, err := config.LoadDefaultConfig(t.Context(), config.WithCredentialsProvider(credentials.StaticCredentialsProvider{ Value: aws.Credentials{ AccessKeyID: "DUMMYIDEXAMPLE", SecretAccessKey: "DUMMYEXAMPLEKEY", @@ -249,10 +249,12 @@ func getDynamoDBClient(t *testing.T, c *tcdynamodb.DynamoDBContainer) *dynamodb. func requireTableExists(t *testing.T, cli *dynamodb.Client, tableName string) { t.Helper() - err := createTable(cli) + ctx := t.Context() + + err := createTable(ctx, cli) require.NoError(t, err) - result, err := cli.ListTables(context.Background(), nil) + result, err := cli.ListTables(ctx, nil) require.NoError(t, err, "dynamodb list tables operation failed") actualTableName := result.TableNames[0] diff --git a/modules/elasticsearch/elasticsearch_test.go b/modules/elasticsearch/elasticsearch_test.go index 7605f64d34..0549e1d897 100644 --- a/modules/elasticsearch/elasticsearch_test.go +++ b/modules/elasticsearch/elasticsearch_test.go @@ -1,7 +1,6 @@ package elasticsearch_test import ( - "context" "crypto/tls" "crypto/x509" "encoding/json" @@ -73,7 +72,7 @@ func TestElasticsearch(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() opts := []testcontainers.ContainerCustomizer{} @@ -151,7 +150,7 @@ func TestElasticsearch8WithoutSSL(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := elasticsearch.Run( ctx, baseImage8, @@ -167,7 +166,7 @@ func TestElasticsearch8WithoutSSL(t *testing.T) { } func TestElasticsearch8WithoutCredentials(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := elasticsearch.Run(ctx, baseImage8) testcontainers.CleanupContainer(t, ctr) @@ -194,7 +193,7 @@ func TestElasticsearch8WithoutCredentials(t *testing.T) { } func TestElasticsearchOSSCannotUseWithPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ossImage := elasticsearch.DefaultBaseImageOSS + ":7.9.2" diff --git a/modules/etcd/etcd_test.go b/modules/etcd/etcd_test.go index 5c0bc702bc..c1b7041ef0 100644 --- a/modules/etcd/etcd_test.go +++ b/modules/etcd/etcd_test.go @@ -15,7 +15,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := etcd.Run(ctx, "gcr.io/etcd-development/etcd:v3.5.14") testcontainers.CleanupContainer(t, ctr) @@ -32,11 +32,11 @@ func TestRun(t *testing.T) { func TestPutGet(t *testing.T) { t.Run("single_node", func(t *testing.T) { - ctr, err := etcd.Run(context.Background(), "gcr.io/etcd-development/etcd:v3.5.14") + ctr, err := etcd.Run(t.Context(), "gcr.io/etcd-development/etcd:v3.5.14") testPutGet(t, ctr, err) }) t.Run("multiple_nodes", func(t *testing.T) { - ctr, err := etcd.Run(context.Background(), "gcr.io/etcd-development/etcd:v3.5.14", etcd.WithNodes("etcd-1", "etcd-2", "etcd-3")) + ctr, err := etcd.Run(t.Context(), "gcr.io/etcd-development/etcd:v3.5.14", etcd.WithNodes("etcd-1", "etcd-2", "etcd-3")) testPutGet(t, ctr, err) }) } @@ -48,7 +48,7 @@ func testPutGet(t *testing.T, ctr *etcd.EtcdContainer, err error) { require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() clientEndpoints, err := ctr.ClientEndpoints(ctx) require.NoError(t, err) diff --git a/modules/etcd/etcd_unit_test.go b/modules/etcd/etcd_unit_test.go index cefacb1cf7..c8334d3830 100644 --- a/modules/etcd/etcd_unit_test.go +++ b/modules/etcd/etcd_unit_test.go @@ -1,7 +1,6 @@ package etcd import ( - "context" "fmt" "io" "testing" @@ -16,7 +15,7 @@ import ( ) func TestRunCluster1Node(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "gcr.io/etcd-development/etcd:v3.5.14") testcontainers.CleanupContainer(t, ctr) @@ -33,7 +32,7 @@ func TestRunClusterMultipleNodes(t *testing.T) { } func TestTerminate(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "gcr.io/etcd-development/etcd:v3.5.14", WithNodes("etcd-1", "etcd-2", "etcd-3")) require.NoError(t, err) @@ -41,24 +40,24 @@ func TestTerminate(t *testing.T) { // verify that the network and the containers does no longer exist - cli, err := testcontainers.NewDockerClientWithOpts(context.Background()) + cli, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) defer cli.Close() - _, err = cli.ContainerInspect(context.Background(), ctr.GetContainerID()) + _, err = cli.ContainerInspect(t.Context(), ctr.GetContainerID()) require.True(t, errdefs.IsNotFound(err)) for _, child := range ctr.childNodes { - _, err := cli.ContainerInspect(context.Background(), child.GetContainerID()) + _, err := cli.ContainerInspect(t.Context(), child.GetContainerID()) require.True(t, errdefs.IsNotFound(err)) } - _, err = cli.NetworkInspect(context.Background(), ctr.opts.clusterNetwork.ID, network.InspectOptions{}) + _, err = cli.NetworkInspect(t.Context(), ctr.opts.clusterNetwork.ID, network.InspectOptions{}) require.True(t, errdefs.IsNotFound(err)) } func TestTerminate_partiallyInitialised(t *testing.T) { - newNetwork, err := tcnetwork.New(context.Background()) + newNetwork, err := tcnetwork.New(t.Context()) require.NoError(t, err) ctr := &EtcdContainer{ @@ -67,13 +66,13 @@ func TestTerminate_partiallyInitialised(t *testing.T) { }, } - require.NoError(t, ctr.Terminate(context.Background())) + require.NoError(t, ctr.Terminate(t.Context())) - cli, err := testcontainers.NewDockerClientWithOpts(context.Background()) + cli, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) defer cli.Close() - _, err = cli.NetworkInspect(context.Background(), ctr.opts.clusterNetwork.ID, network.InspectOptions{}) + _, err = cli.NetworkInspect(t.Context(), ctr.opts.clusterNetwork.ID, network.InspectOptions{}) require.True(t, errdefs.IsNotFound(err)) } @@ -84,7 +83,7 @@ func testCluster(t *testing.T, node1 string, node2 string, nodes ...string) func return func(tt *testing.T) { const clusterToken string = "My-cluster-t0k3n" - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "gcr.io/etcd-development/etcd:v3.5.14", WithNodes(node1, node2, nodes...), WithClusterToken(clusterToken)) testcontainers.CleanupContainer(t, ctr) diff --git a/modules/gcloud/bigquery/bigquery_test.go b/modules/gcloud/bigquery/bigquery_test.go index 3a4dc346a3..4c26b5612d 100644 --- a/modules/gcloud/bigquery/bigquery_test.go +++ b/modules/gcloud/bigquery/bigquery_test.go @@ -2,7 +2,6 @@ package bigquery_test import ( "bytes" - "context" _ "embed" "errors" "testing" @@ -23,7 +22,7 @@ import ( var dataYaml []byte func TestBigQueryWithDataYAML(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("valid", func(t *testing.T) { bigQueryContainer, err := tcbigquery.Run( diff --git a/modules/gcloud/bigtable/bigtable_test.go b/modules/gcloud/bigtable/bigtable_test.go index d3d6d9204b..60ff145050 100644 --- a/modules/gcloud/bigtable/bigtable_test.go +++ b/modules/gcloud/bigtable/bigtable_test.go @@ -1,7 +1,6 @@ package bigtable_test import ( - "context" "testing" "cloud.google.com/go/bigtable" @@ -15,7 +14,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() bigTableContainer, err := tcbigtable.Run( ctx, diff --git a/modules/gcloud/datastore/datastore_test.go b/modules/gcloud/datastore/datastore_test.go index e844ec0e99..0d59305089 100644 --- a/modules/gcloud/datastore/datastore_test.go +++ b/modules/gcloud/datastore/datastore_test.go @@ -1,7 +1,6 @@ package datastore_test import ( - "context" "log" "testing" @@ -16,7 +15,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() datastoreContainer, err := tcdatastore.Run( ctx, diff --git a/modules/gcloud/firestore/firestore_test.go b/modules/gcloud/firestore/firestore_test.go index c1db5c0e18..c5b15d19c3 100644 --- a/modules/gcloud/firestore/firestore_test.go +++ b/modules/gcloud/firestore/firestore_test.go @@ -1,7 +1,6 @@ package firestore_test import ( - "context" "testing" "cloud.google.com/go/datastore" @@ -16,7 +15,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() firestoreContainer, err := tcfirestore.Run( ctx, @@ -62,7 +61,7 @@ func TestRun(t *testing.T) { } func TestRunWithDatastore(t *testing.T) { - ctx := context.Background() + ctx := t.Context() firestoreContainer, err := tcfirestore.Run( ctx, diff --git a/modules/gcloud/pubsub/pubsub_test.go b/modules/gcloud/pubsub/pubsub_test.go index f8979b05ff..83d17c5992 100644 --- a/modules/gcloud/pubsub/pubsub_test.go +++ b/modules/gcloud/pubsub/pubsub_test.go @@ -16,7 +16,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() pubsubContainer, err := tcpubsub.Run( ctx, diff --git a/modules/gcloud/spanner/spanner_test.go b/modules/gcloud/spanner/spanner_test.go index 94a7d9a2de..652a39ed31 100644 --- a/modules/gcloud/spanner/spanner_test.go +++ b/modules/gcloud/spanner/spanner_test.go @@ -1,7 +1,6 @@ package spanner_test import ( - "context" "fmt" "log" "testing" @@ -22,7 +21,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() spannerContainer, err := tcspanner.Run( ctx, diff --git a/modules/grafana-lgtm/grafana_test.go b/modules/grafana-lgtm/grafana_test.go index 1981123dc8..1cae05b50f 100644 --- a/modules/grafana-lgtm/grafana_test.go +++ b/modules/grafana-lgtm/grafana_test.go @@ -1,7 +1,6 @@ package grafanalgtm_test import ( - "context" "encoding/json" "fmt" "net/http" @@ -15,7 +14,7 @@ import ( ) func TestGrafanaLGTM(t *testing.T) { - ctx := context.Background() + ctx := t.Context() grafanaLgtmContainer, err := grafanalgtm.Run(ctx, "grafana/otel-lgtm:0.6.0") testcontainers.CleanupContainer(t, grafanaLgtmContainer) diff --git a/modules/inbucket/inbucket_test.go b/modules/inbucket/inbucket_test.go index 2bdb5e7ad8..081290506d 100644 --- a/modules/inbucket/inbucket_test.go +++ b/modules/inbucket/inbucket_test.go @@ -1,7 +1,6 @@ package inbucket import ( - "context" "net/smtp" "testing" @@ -12,7 +11,7 @@ import ( ) func TestInbucket(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "inbucket/inbucket:sha-2d409bb") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/influxdb/influxdb_test.go b/modules/influxdb/influxdb_test.go index 3e640f7e7d..531664557f 100644 --- a/modules/influxdb/influxdb_test.go +++ b/modules/influxdb/influxdb_test.go @@ -1,7 +1,6 @@ package influxdb_test import ( - "context" "encoding/json" "path/filepath" "testing" @@ -17,7 +16,7 @@ import ( ) func TestV1Container(t *testing.T) { - ctx := context.Background() + ctx := t.Context() influxDBContainer, err := influxdb.Run(ctx, "influxdb:1.8.10") testcontainers.CleanupContainer(t, influxDBContainer) require.NoError(t, err) @@ -29,7 +28,7 @@ func TestV1Container(t *testing.T) { } func TestV2Container(t *testing.T) { - ctx := context.Background() + ctx := t.Context() influxDBContainer, err := influxdb.Run(ctx, "influxdb:2.7.5-alpine", influxdb.WithDatabase("foo"), @@ -412,7 +411,7 @@ func TestV2Options(t *testing.T) { } func TestRun_V2WithOptions(t *testing.T) { - ctx := context.Background() + ctx := t.Context() username := "username" password := "password" @@ -455,7 +454,7 @@ func TestRun_V2WithOptions(t *testing.T) { } func TestWithInitDb(t *testing.T) { - ctx := context.Background() + ctx := t.Context() influxDBContainer, err := influxdb.Run(ctx, "influxdb:1.8.10", influxdb.WithInitDb("testdata"), @@ -488,20 +487,20 @@ func TestWithInitDb(t *testing.T) { func TestWithConfigFile(t *testing.T) { influxVersion := "1.8.10" - influxDBContainer, err := influxdb.Run(context.Background(), + influxDBContainer, err := influxdb.Run(t.Context(), "influxdb:"+influxVersion, influxdb.WithConfigFile(filepath.Join("testdata", "influxdb.conf")), ) testcontainers.CleanupContainer(t, influxDBContainer) require.NoError(t, err) - if state, err := influxDBContainer.State(context.Background()); err != nil || !state.Running { + if state, err := influxDBContainer.State(t.Context()); err != nil || !state.Running { require.NoError(t, err) } /// influxConnectionUrl { cli, err := influxclient.NewHTTPClient(influxclient.HTTPConfig{ - Addr: influxDBContainer.MustConnectionUrl(context.Background()), + Addr: influxDBContainer.MustConnectionUrl(t.Context()), }) // } require.NoError(t, err) diff --git a/modules/k3s/k3s_test.go b/modules/k3s/k3s_test.go index 3328a56d3d..2eeebad48f 100644 --- a/modules/k3s/k3s_test.go +++ b/modules/k3s/k3s_test.go @@ -20,7 +20,7 @@ import ( func Test_LoadImages(t *testing.T) { // Give up to three minutes to run this test - ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(3*time.Minute)) + ctx, cancel := context.WithDeadline(t.Context(), time.Now().Add(3*time.Minute)) defer cancel() k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1") @@ -103,7 +103,7 @@ func getTestPodState(ctx context.Context, k8s *kubernetes.Clientset) (corev1.Con } func Test_APIServerReady(t *testing.T) { - ctx := context.Background() + ctx := t.Context() k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1") testcontainers.CleanupContainer(t, k3sContainer) @@ -136,12 +136,12 @@ func Test_APIServerReady(t *testing.T) { }, } - _, err = k8s.CoreV1().Pods("default").Create(context.Background(), pod, metav1.CreateOptions{}) + _, err = k8s.CoreV1().Pods("default").Create(t.Context(), pod, metav1.CreateOptions{}) require.NoError(t, err) } func Test_WithManifestOption(t *testing.T) { - ctx := context.Background() + ctx := t.Context() k3sContainer, err := k3s.Run(ctx, "rancher/k3s:v1.27.1-k3s1", diff --git a/modules/k6/k6_test.go b/modules/k6/k6_test.go index bc40bd13a6..de3d838ee1 100644 --- a/modules/k6/k6_test.go +++ b/modules/k6/k6_test.go @@ -1,7 +1,6 @@ package k6_test import ( - "context" "net/url" "path/filepath" "strings" @@ -53,12 +52,12 @@ func TestK6(t *testing.T) { require.NoError(t, err) defer provider.Close() - require.NoError(t, provider.Client().VolumeRemove(context.Background(), cacheMount, true)) + require.NoError(t, provider.Client().VolumeRemove(t.Context(), cacheMount, true)) }) for _, tc := range testCases { t.Run(tc.title, func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() var options testcontainers.CustomizeRequestOption if !strings.HasPrefix(tc.script, "http") { diff --git a/modules/kafka/kafka_test.go b/modules/kafka/kafka_test.go index af858f849f..6401e7a581 100644 --- a/modules/kafka/kafka_test.go +++ b/modules/kafka/kafka_test.go @@ -1,7 +1,6 @@ package kafka_test import ( - "context" "strings" "testing" @@ -15,7 +14,7 @@ import ( func TestKafka(t *testing.T) { topic := "some-topic" - ctx := context.Background() + ctx := t.Context() kafkaContainer, err := kafka.Run(ctx, "confluentinc/confluent-local:7.5.0", kafka.WithClusterID("kraftCluster")) testcontainers.CleanupContainer(t, kafkaContainer) @@ -37,7 +36,7 @@ func TestKafka(t *testing.T) { consumer, ready, done, cancel := NewTestKafkaConsumer(t) defer cancel() go func() { - if err := client.Consume(context.Background(), []string{topic}, consumer); err != nil { + if err := client.Consume(t.Context(), []string{topic}, consumer); err != nil { cancel() } }() @@ -67,7 +66,7 @@ func TestKafka(t *testing.T) { } func TestKafka_invalidVersion(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := kafka.Run(ctx, "confluentinc/confluent-local:6.3.3", kafka.WithClusterID("kraftCluster")) testcontainers.CleanupContainer(t, ctr) @@ -78,12 +77,12 @@ func TestKafka_invalidVersion(t *testing.T) { // - The BROKER:// protocol is using the hostname of the Kafka container func assertAdvertisedListeners(t *testing.T, container testcontainers.Container) { t.Helper() - inspect, err := container.Inspect(context.Background()) + inspect, err := container.Inspect(t.Context()) require.NoError(t, err) brokerURL := "BROKER://" + inspect.Config.Hostname + ":9092" - ctx := context.Background() + ctx := t.Context() bs := testcontainers.RequireContainerExec(ctx, t, container, []string{"cat", "/usr/sbin/testcontainers_start.sh"}) diff --git a/modules/localstack/localstack_test.go b/modules/localstack/localstack_test.go index d371a9d60f..728a29c2c9 100644 --- a/modules/localstack/localstack_test.go +++ b/modules/localstack/localstack_test.go @@ -1,7 +1,6 @@ package localstack import ( - "context" "io" "strings" "testing" @@ -66,7 +65,7 @@ func TestConfigureDockerHost(t *testing.T) { defer dockerProvider.Close() // because the daemon host could be a remote one, we need to get it from the provider - expectedDaemonHost, err := dockerProvider.DaemonHost(context.Background()) + expectedDaemonHost, err := dockerProvider.DaemonHost(t.Context()) require.NoError(t, err) req := generateContainerRequest() @@ -169,7 +168,7 @@ func TestRunContainer(t *testing.T) { } for _, tt := range tests { - ctx := context.Background() + ctx := t.Context() ctr, err := Run( ctx, @@ -200,7 +199,7 @@ func TestRunContainer(t *testing.T) { } func TestStartWithoutOverride(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "localstack/localstack:2.0.0") testcontainers.CleanupContainer(t, ctr) @@ -209,7 +208,7 @@ func TestStartWithoutOverride(t *testing.T) { } func TestStartV2WithNetwork(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) require.NoError(t, err) diff --git a/modules/localstack/v1/s3_test.go b/modules/localstack/v1/s3_test.go index a35bbe98b2..da06d545fc 100644 --- a/modules/localstack/v1/s3_test.go +++ b/modules/localstack/v1/s3_test.go @@ -60,7 +60,7 @@ func awsSession(ctx context.Context, l *localstack.LocalStackContainer) (*sessio // } func TestS3(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := localstack.Run(ctx, "localstack/localstack:1.4.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/localstack/v2/s3_test.go b/modules/localstack/v2/s3_test.go index 2df71dcb39..1f874068a6 100644 --- a/modules/localstack/v2/s3_test.go +++ b/modules/localstack/v2/s3_test.go @@ -57,7 +57,7 @@ func s3Client(ctx context.Context, l *localstack.LocalStackContainer) (*s3.Clien return nil, err } - awsCfg, err := config.LoadDefaultConfig(context.TODO(), + awsCfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accesskey, secretkey, token)), ) @@ -78,7 +78,7 @@ func s3Client(ctx context.Context, l *localstack.LocalStackContainer) (*s3.Clien // } func TestS3(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := localstack.Run(ctx, "localstack/localstack:1.4.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/mariadb/mariadb_test.go b/modules/mariadb/mariadb_test.go index 706ee2eb76..736993bc03 100644 --- a/modules/mariadb/mariadb_test.go +++ b/modules/mariadb/mariadb_test.go @@ -15,7 +15,7 @@ import ( ) func TestMariaDB(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mariadb.Run(ctx, "mariadb:11.0.3") testcontainers.CleanupContainer(t, ctr) @@ -46,7 +46,7 @@ func TestMariaDB(t *testing.T) { } func TestMariaDBWithNonRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := mariadb.Run(ctx, "mariadb:11.0.3", @@ -57,7 +57,7 @@ func TestMariaDBWithNonRootUserAndEmptyPassword(t *testing.T) { } func TestMariaDBWithRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mariadb.Run(ctx, "mariadb:11.0.3", @@ -86,7 +86,7 @@ func TestMariaDBWithRootUserAndEmptyPassword(t *testing.T) { } func TestMariaDBWithMySQLEnvVars(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mariadb.Run(ctx, "mariadb:10.3.29", mariadb.WithScripts(filepath.Join("testdata", "schema.sql"))) @@ -97,7 +97,7 @@ func TestMariaDBWithMySQLEnvVars(t *testing.T) { } func TestMariaDBWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mariadb.Run(ctx, "mariadb:11.0.3", mariadb.WithConfigFile(filepath.Join("testdata", "my.cnf"))) @@ -130,7 +130,7 @@ func TestMariaDBWithConfigFile(t *testing.T) { } func TestMariaDBWithScripts(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mariadb.Run(ctx, "mariadb:11.0.3", diff --git a/modules/meilisearch/meilisearch_test.go b/modules/meilisearch/meilisearch_test.go index fe50c72258..cc3405b6bf 100644 --- a/modules/meilisearch/meilisearch_test.go +++ b/modules/meilisearch/meilisearch_test.go @@ -1,7 +1,6 @@ package meilisearch_test import ( - "context" "io" "net/http" "net/url" @@ -14,7 +13,7 @@ import ( ) func TestMeilisearch(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := meilisearch.Run(ctx, "getmeili/meilisearch:v1.10.3") testcontainers.CleanupContainer(t, ctr) @@ -32,7 +31,7 @@ func TestMeilisearch(t *testing.T) { } func TestMeilisearch_WithDataDump(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := meilisearch.Run(ctx, "getmeili/meilisearch:v1.10.3", meilisearch.WithDumpImport("testdata/movies.dump"), diff --git a/modules/memcached/memcached_test.go b/modules/memcached/memcached_test.go index bac3295405..06a5a9f4be 100644 --- a/modules/memcached/memcached_test.go +++ b/modules/memcached/memcached_test.go @@ -1,7 +1,6 @@ package memcached_test import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -11,7 +10,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := memcached.Run(ctx, "memcached:1.6-alpine") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/milvus/milvus_test.go b/modules/milvus/milvus_test.go index c1ad0a070e..bd8c6d1ebb 100644 --- a/modules/milvus/milvus_test.go +++ b/modules/milvus/milvus_test.go @@ -1,7 +1,6 @@ package milvus_test import ( - "context" "testing" "github.com/milvus-io/milvus-sdk-go/v2/client" @@ -12,7 +11,7 @@ import ( ) func TestMilvus(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := milvus.Run(ctx, "milvusdb/milvus:v2.3.9") testcontainers.CleanupContainer(t, ctr) @@ -24,7 +23,7 @@ func TestMilvus(t *testing.T) { // } require.NoError(t, err) - milvusClient, err := client.NewGrpcClient(context.Background(), connectionStr) + milvusClient, err := client.NewGrpcClient(t.Context(), connectionStr) require.NoError(t, err) defer milvusClient.Close() diff --git a/modules/minio/minio_test.go b/modules/minio/minio_test.go index e7c3d9b170..286645d663 100644 --- a/modules/minio/minio_test.go +++ b/modules/minio/minio_test.go @@ -1,7 +1,6 @@ package minio_test import ( - "context" "io" "strings" "testing" @@ -15,7 +14,7 @@ import ( ) func TestMinio(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcminio.Run(ctx, "minio/minio:RELEASE.2024-01-16T16-07-38Z", diff --git a/modules/mockserver/examples_test.go b/modules/mockserver/examples_test.go index e642878af3..7e6f6058ad 100644 --- a/modules/mockserver/examples_test.go +++ b/modules/mockserver/examples_test.go @@ -7,6 +7,7 @@ import ( "log" "net/http" "strings" + "time" client "github.com/BraspagDevelopers/mock-server-client" @@ -16,7 +17,8 @@ import ( func ExampleRun() { // runMockServerContainer { - ctx := context.Background() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() mockserverContainer, err := mockserver.Run(ctx, "mockserver/mockserver:5.15.0") defer func() { diff --git a/modules/mongodb/atlaslocal/atlaslocal_test.go b/modules/mongodb/atlaslocal/atlaslocal_test.go index caae6c68e6..5cee4181be 100644 --- a/modules/mongodb/atlaslocal/atlaslocal_test.go +++ b/modules/mongodb/atlaslocal/atlaslocal_test.go @@ -25,7 +25,7 @@ import ( const latestImage = "mongodb/mongodb-atlas-local:latest" func TestMongoDBAtlasLocal(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := atlaslocal.Run(ctx, latestImage) testcontainers.CleanupContainer(t, ctr) @@ -190,7 +190,7 @@ func TestSCRAMAuth(t *testing.T) { }) // Create the MongoDB Atlas Local container with the specified options. - ctr, err := atlaslocal.Run(context.Background(), latestImage, opts...) + ctr, err := atlaslocal.Run(t.Context(), latestImage, opts...) testcontainers.CleanupContainer(t, ctr) if tc.wantRunErr != "" { @@ -213,14 +213,14 @@ func TestSCRAMAuth(t *testing.T) { requireEnvVar(t, ctr, "MONGODB_INITDB_ROOT_PASSWORD_FILE", "/run/secrets/mongo-root-password") } - client, td := newMongoClient(t, context.Background(), ctr) + client, td := newMongoClient(t, t.Context(), ctr) defer td() // Execute an insert operation to verify the connection and // authentication. coll := client.Database("test").Collection("foo") - _, err = coll.InsertOne(context.Background(), bson.D{{Key: "test", Value: "value"}}) + _, err = coll.InsertOne(t.Context(), bson.D{{Key: "test", Value: "value"}}) require.NoError(t, err, "Failed to insert document with authentication") }) } @@ -228,7 +228,7 @@ func TestSCRAMAuth(t *testing.T) { func TestWithNoTelemetry(t *testing.T) { t.Run("with", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, atlaslocal.WithNoTelemetry()) + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithNoTelemetry()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -236,7 +236,7 @@ func TestWithNoTelemetry(t *testing.T) { }) t.Run("without", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage) + ctr, err := atlaslocal.Run(t.Context(), latestImage) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -246,7 +246,7 @@ func TestWithNoTelemetry(t *testing.T) { func TestWithMongotLogFile(t *testing.T) { t.Run("with", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, atlaslocal.WithMongotLogFile()) + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithMongotLogFile()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -257,7 +257,7 @@ func TestWithMongotLogFile(t *testing.T) { }) t.Run("without", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage) + ctr, err := atlaslocal.Run(t.Context(), latestImage) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -268,7 +268,7 @@ func TestWithMongotLogFile(t *testing.T) { }) t.Run("to stdout", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithMongotLogToStdout()) testcontainers.CleanupContainer(t, ctr) @@ -283,7 +283,7 @@ func TestWithMongotLogFile(t *testing.T) { }) t.Run("to stderr", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithMongotLogToStderr()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -301,7 +301,7 @@ func TestWithRunnerLogFile(t *testing.T) { const runnerLogFile = "/tmp/runner.log" t.Run("with", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, atlaslocal.WithRunnerLogFile()) + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithRunnerLogFile()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -310,7 +310,7 @@ func TestWithRunnerLogFile(t *testing.T) { }) t.Run("without", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage) + ctr, err := atlaslocal.Run(t.Context(), latestImage) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -320,7 +320,7 @@ func TestWithRunnerLogFile(t *testing.T) { }) t.Run("to stdout", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithRunnerLogToStdout()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -334,7 +334,7 @@ func TestWithRunnerLogFile(t *testing.T) { }) t.Run("to stderr", func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, + ctr, err := atlaslocal.Run(t.Context(), latestImage, atlaslocal.WithRunnerLogToStderr()) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -359,21 +359,21 @@ func TestWithInitDatabase(t *testing.T) { atlaslocal.WithInitScripts(tmpDir), } - ctr, err := atlaslocal.Run(context.Background(), latestImage, opts...) + ctr, err := atlaslocal.Run(t.Context(), latestImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) requireInitScriptsExist(t, ctr, initScripts) requireEnvVar(t, ctr, "MONGODB_INITDB_DATABASE", "mydb") - client, td := newMongoClient(t, context.Background(), ctr) + client, td := newMongoClient(t, t.Context(), ctr) defer td() coll := client.Database("mydb").Collection("foo") seed := bson.D{{Key: "_id", Value: int32(1)}, {Key: "seeded", Value: true}} - res := coll.FindOne(context.Background(), seed) + res := coll.FindOne(t.Context(), seed) require.NoError(t, res.Err()) var doc bson.D @@ -436,24 +436,24 @@ func TestWithInitScripts(t *testing.T) { atlaslocal.WithInitScripts(tmpDir), } - ctr, err := atlaslocal.Run(context.Background(), latestImage, opts...) + ctr, err := atlaslocal.Run(t.Context(), latestImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) requireInitScriptsExist(t, ctr, tc.initScripts) // Connect to the server. - client, td := newMongoClient(t, context.Background(), ctr) + client, td := newMongoClient(t, t.Context(), ctr) defer td() // Fetch the seeded data. coll := client.Database("test").Collection("foo") - cur, err := coll.Find(context.Background(), bson.D{}) + cur, err := coll.Find(t.Context(), bson.D{}) require.NoError(t, err) var results []bson.D - require.NoError(t, cur.All(context.Background(), &results)) + require.NoError(t, cur.All(t.Context(), &results)) require.ElementsMatch(t, results, tc.want, "Seeded documents do not match expected values") }) @@ -481,7 +481,7 @@ func TestWithInitScripts_MultipleScripts(t *testing.T) { atlaslocal.WithInitScripts(tmpDir2), } - ctr, err := atlaslocal.Run(context.Background(), latestImage, opts...) + ctr, err := atlaslocal.Run(t.Context(), latestImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -532,11 +532,11 @@ func TestConnectionString(t *testing.T) { for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { - ctr, err := atlaslocal.Run(context.Background(), latestImage, tc.opts...) + ctr, err := atlaslocal.Run(t.Context(), latestImage, tc.opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) - csRaw, err := ctr.ConnectionString(context.Background()) + csRaw, err := ctr.ConnectionString(t.Context()) require.NoError(t, err) connString, err := connstring.ParseAndValidate(csRaw) @@ -563,7 +563,7 @@ func requireEnvVar(t *testing.T, ctr testcontainers.Container, envVarName, expec // testcontainers-go's Exec() returns a multiplexed stream in the same format // used by the Docker API. Each frame is prefixed with an 8-byte header. - exitCode, reader, err := ctr.Exec(context.Background(), []string{"sh", "-c", "echo $" + envVarName}, exec.Multiplexed()) + exitCode, reader, err := ctr.Exec(t.Context(), []string{"sh", "-c", "echo $" + envVarName}, exec.Multiplexed()) require.NoError(t, err) require.Equal(t, 0, exitCode) @@ -578,7 +578,7 @@ func requireMongotLogs(t *testing.T, ctr testcontainers.Container) { t.Helper() // Pull the log file and require non-empty. - reader, err := ctr.(*atlaslocal.Container).ReadMongotLogs(context.Background()) + reader, err := ctr.(*atlaslocal.Container).ReadMongotLogs(t.Context()) require.NoError(t, err) defer reader.Close() @@ -590,7 +590,7 @@ func requireNoMongotLogs(t *testing.T, ctr testcontainers.Container) { t.Helper() // Pull the log file and require non-empty. - reader, err := ctr.(*atlaslocal.Container).ReadMongotLogs(context.Background()) + reader, err := ctr.(*atlaslocal.Container).ReadMongotLogs(t.Context()) require.ErrorIs(t, err, os.ErrNotExist) if reader != nil { // Failure case where reader is non-nil @@ -602,7 +602,7 @@ func requireRunnerLogs(t *testing.T, ctr testcontainers.Container) { t.Helper() // Pull the log file and require non-empty. - reader, err := ctr.(*atlaslocal.Container).ReadRunnerLogs(context.Background()) + reader, err := ctr.(*atlaslocal.Container).ReadRunnerLogs(t.Context()) require.NoError(t, err) defer reader.Close() @@ -615,7 +615,7 @@ func requireNoRunnerLogs(t *testing.T, ctr testcontainers.Container) { t.Helper() // Pull the log file and require non-empty. - reader, err := ctr.(*atlaslocal.Container).ReadRunnerLogs(context.Background()) + reader, err := ctr.(*atlaslocal.Container).ReadRunnerLogs(t.Context()) require.ErrorIs(t, err, os.ErrNotExist) if reader != nil { // Failure case where reader is non-nil @@ -645,15 +645,15 @@ func createSearchIndex(t *testing.T, ctx context.Context, coll *mongo.Collection func executeAggregation(t *testing.T, ctr testcontainers.Container) { t.Helper() - client, td := newMongoClient(t, context.Background(), ctr) + client, td := newMongoClient(t, t.Context(), ctr) defer td() - err := client.Database("test").CreateCollection(context.Background(), "search") + err := client.Database("test").CreateCollection(t.Context(), "search") require.NoError(t, err) coll := client.Database("test").Collection("search") - siCtx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + siCtx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) defer cancel() // Create a search index on the collection. @@ -661,7 +661,7 @@ func executeAggregation(t *testing.T, ctr testcontainers.Container) { // Insert a document into the collection and aggregate it using the search // index which should log the operation to the mongot log file. - _, err = coll.InsertOne(context.Background(), bson.D{{Key: "txt", Value: "hello"}}) + _, err = coll.InsertOne(t.Context(), bson.D{{Key: "txt", Value: "hello"}}) require.NoError(t, err) pipeline := mongo.Pipeline{{ @@ -670,10 +670,10 @@ func executeAggregation(t *testing.T, ctr testcontainers.Container) { }}, }} - cur, err := coll.Aggregate(context.Background(), pipeline) + cur, err := coll.Aggregate(t.Context(), pipeline) require.NoError(t, err) - err = cur.Close(context.Background()) + err = cur.Close(t.Context()) require.NoError(t, err) } @@ -698,7 +698,7 @@ func newMongoClient( require.NoError(t, err) return client, func() { - err := client.Disconnect(context.Background()) + err := client.Disconnect(t.Context()) require.NoError(t, err, "Failed to disconnect MongoDB client") } } @@ -726,7 +726,7 @@ func requireInitScriptsExist(t *testing.T, ctr testcontainers.Container, expecte const dstDir = "/docker-entrypoint-initdb.d" - exit, r, err := ctr.Exec(context.Background(), []string{"sh", "-lc", "ls -l " + dstDir}, exec.Multiplexed()) + exit, r, err := ctr.Exec(t.Context(), []string{"sh", "-lc", "ls -l " + dstDir}, exec.Multiplexed()) require.NoError(t, err) // If the map is empty, the command returns exit code 2. @@ -744,7 +744,7 @@ func requireInitScriptsExist(t *testing.T, ctr testcontainers.Container, expecte for name, want := range expectedScripts { require.Contains(t, listing, name, "Init script %s not found in container", name) - rc, err := ctr.CopyFileFromContainer(context.Background(), filepath.Join(dstDir, name)) + rc, err := ctr.CopyFileFromContainer(t.Context(), filepath.Join(dstDir, name)) require.NoError(t, err, "Failed to copy init script %s from container", name) got, err := io.ReadAll(rc) @@ -763,7 +763,7 @@ func requireInitScriptsDoesNotExist(t *testing.T, ctr testcontainers.Container, // Sanity check to verify that all scripts are present. for filename := range expectedScripts { cmd := []string{"sh", "-lc", "ls -1 /docker-entrypoint-initdb.d 2>/dev/null || true"} - _, reader, err := ctr.Exec(context.Background(), cmd, exec.Multiplexed()) + _, reader, err := ctr.Exec(t.Context(), cmd, exec.Multiplexed()) require.NoError(t, err) raw, err := io.ReadAll(reader) @@ -776,7 +776,7 @@ func requireInitScriptsDoesNotExist(t *testing.T, ctr testcontainers.Container, func requireContainerLogsNotEmpty(t *testing.T, ctr testcontainers.Container) { t.Helper() - logs, err := ctr.Logs(context.Background()) + logs, err := ctr.Logs(t.Context()) require.NoError(t, err) defer logs.Close() diff --git a/modules/mongodb/mongodb_test.go b/modules/mongodb/mongodb_test.go index d85debc2cb..64199aae8c 100644 --- a/modules/mongodb/mongodb_test.go +++ b/modules/mongodb/mongodb_test.go @@ -1,7 +1,6 @@ package mongodb_test import ( - "context" "fmt" "net/url" "testing" @@ -118,7 +117,7 @@ func TestMongoDB(t *testing.T) { t.Run(tc.name, func(tt *testing.T) { tt.Parallel() - ctx := context.Background() + ctx := tt.Context() mongodbContainer, err := mongodb.Run(ctx, tc.img, tc.opts...) testcontainers.CleanupContainer(t, mongodbContainer) diff --git a/modules/mssql/mssql_test.go b/modules/mssql/mssql_test.go index 10052b8d40..d3b67997ed 100644 --- a/modules/mssql/mssql_test.go +++ b/modules/mssql/mssql_test.go @@ -16,7 +16,7 @@ import ( ) func TestMSSQLServer(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mssql.Run(ctx, "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04", @@ -45,7 +45,7 @@ func TestMSSQLServer(t *testing.T) { } func TestMSSQLServerWithMissingEulaOption(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("empty", func(t *testing.T) { ctr, err := mssql.Run(ctx, @@ -70,7 +70,7 @@ func TestMSSQLServerWithMissingEulaOption(t *testing.T) { } func TestMSSQLServerWithConnectionStringParameters(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mssql.Run(ctx, "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04", @@ -100,7 +100,7 @@ func TestMSSQLServerWithConnectionStringParameters(t *testing.T) { } func TestMSSQLServerWithCustomStrongPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mssql.Run(ctx, "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04", @@ -124,7 +124,7 @@ func TestMSSQLServerWithCustomStrongPassword(t *testing.T) { // tests that a weak password is not accepted by the container due to Microsoft's password strength policy func TestMSSQLServerWithInvalidPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mssql.Run(ctx, "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04", @@ -191,7 +191,7 @@ func TestMSSQLServerWithScriptsDDL(t *testing.T) { require.Equal(t, want, got) } - ctx := context.Background() + ctx := t.Context() t.Run("WithPassword/beforeWithScripts", func(t *testing.T) { assertContainer(t, ctx, diff --git a/modules/mysql/mysql_test.go b/modules/mysql/mysql_test.go index 364f2a97a8..9c3892e276 100644 --- a/modules/mysql/mysql_test.go +++ b/modules/mysql/mysql_test.go @@ -1,7 +1,6 @@ package mysql_test import ( - "context" "database/sql" "path/filepath" "testing" @@ -15,7 +14,7 @@ import ( ) func TestMySQL(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mysql.Run(ctx, "mysql:8.0.36") testcontainers.CleanupContainer(t, ctr) @@ -46,7 +45,7 @@ func TestMySQL(t *testing.T) { } func TestMySQLWithNonRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mysql.Run(ctx, "mysql:8.0.36", @@ -58,7 +57,7 @@ func TestMySQLWithNonRootUserAndEmptyPassword(t *testing.T) { } func TestMySQLWithRootUserAndEmptyPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mysql.Run(ctx, "mysql:8.0.36", @@ -87,7 +86,7 @@ func TestMySQLWithRootUserAndEmptyPassword(t *testing.T) { } func TestMySQLWithScripts(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := mysql.Run(ctx, "mysql:8.0.36", diff --git a/modules/nats/examples_test.go b/modules/nats/examples_test.go index b88fba4c4a..a3106049d5 100644 --- a/modules/nats/examples_test.go +++ b/modules/nats/examples_test.go @@ -86,7 +86,8 @@ func ExampleRun_cluster() { } defer func() { - if err := nwr.Remove(context.Background()); err != nil { + ctx := context.Background() + if err := nwr.Remove(ctx); err != nil { log.Printf("failed to remove network: %s", err) } }() diff --git a/modules/nats/nats_test.go b/modules/nats/nats_test.go index 9cd7a3d0cf..270819d664 100644 --- a/modules/nats/nats_test.go +++ b/modules/nats/nats_test.go @@ -2,7 +2,6 @@ package nats_test import ( "bufio" - "context" "strings" "testing" "time" @@ -15,7 +14,7 @@ import ( ) func TestNATS(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // createNATSContainer { ctr, err := tcnats.Run(ctx, "nats:2.9") @@ -68,7 +67,7 @@ authorization { token: "s3cr3t" } ` - ctx := context.Background() + ctx := t.Context() ctr, err := tcnats.Run(ctx, "nats:2.9", tcnats.WithConfigFile(strings.NewReader(natsConf))) testcontainers.CleanupContainer(t, ctr) diff --git a/modules/nebulagraph/nebulagraph_test.go b/modules/nebulagraph/nebulagraph_test.go index 89186a5acc..4bc7b68aa5 100644 --- a/modules/nebulagraph/nebulagraph_test.go +++ b/modules/nebulagraph/nebulagraph_test.go @@ -23,7 +23,7 @@ const ( ) func TestNebulaGraphContainer(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Minute) defer cancel() container, err := nebulagraph.RunCluster(ctx, diff --git a/modules/neo4j/neo4j_test.go b/modules/neo4j/neo4j_test.go index ba2c18e072..cfccd65ca5 100644 --- a/modules/neo4j/neo4j_test.go +++ b/modules/neo4j/neo4j_test.go @@ -18,7 +18,7 @@ const testPassword = "letmein!" func TestNeo4j(outer *testing.T) { outer.Parallel() - ctx := context.Background() + ctx := outer.Context() ctr, err := setupNeo4j(ctx) testcontainers.CleanupContainer(outer, ctr) @@ -53,7 +53,7 @@ func TestNeo4j(outer *testing.T) { func TestNeo4jWithEnterpriseLicense(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() images := map[string]string{ "StandardEdition": "neo4j:4.4", @@ -82,7 +82,7 @@ func TestNeo4jWithEnterpriseLicense(t *testing.T) { func TestNeo4jWithWrongSettings(outer *testing.T) { outer.Parallel() - ctx := context.Background() + ctx := outer.Context() outer.Run("without authentication", func(t *testing.T) { ctr, err := neo4j.Run(ctx, "neo4j:4.4") diff --git a/modules/ollama/examples_test.go b/modules/ollama/examples_test.go index c5a12d491c..2e9dc6c89d 100644 --- a/modules/ollama/examples_test.go +++ b/modules/ollama/examples_test.go @@ -149,7 +149,7 @@ func ExampleRun_withModel_llama2_langchain() { } completion, err := llm.Call( - context.Background(), + ctx, "how can Testcontainers help with testing?", llms.WithSeed(42), // the lower the seed, the more deterministic the completion llms.WithTemperature(0.0), // the lower the temperature, the more creative the completion @@ -221,7 +221,7 @@ func ExampleRun_withLocal() { } completion, err := llm.Call( - context.Background(), + ctx, "how can Testcontainers help with testing?", llms.WithSeed(42), // the lower the seed, the more deterministic the completion llms.WithTemperature(0.0), // the lower the temperature, the more creative the completion @@ -246,13 +246,15 @@ func ExampleRun_withLocal() { } func ExampleRun_withImageMount() { - cli, err := testcontainers.NewDockerClientWithOpts(context.Background()) + ctx := context.Background() + + cli, err := testcontainers.NewDockerClientWithOpts(ctx) if err != nil { log.Printf("failed to create docker client: %s", err) return } - info, err := cli.Info(context.Background()) + info, err := cli.Info(ctx) if err != nil { log.Printf("failed to get docker info: %s", err) return @@ -264,8 +266,6 @@ func ExampleRun_withImageMount() { return } - ctx := context.Background() - ollamaContainer, err := tcollama.Run(ctx, "ollama/ollama:0.5.12") if err != nil { log.Printf("failed to start container: %s", err) @@ -324,6 +324,7 @@ func ExampleRun_withImageMount() { log.Printf("failed to get request: %s", err) return } + defer resp.Body.Close() fmt.Println(resp.StatusCode) diff --git a/modules/ollama/local_test.go b/modules/ollama/local_test.go index 06961ceadf..1abbab4384 100644 --- a/modules/ollama/local_test.go +++ b/modules/ollama/local_test.go @@ -40,7 +40,7 @@ func TestRun_local(t *testing.T) { t.Skip("local ollama binary not found, skipping") } - ctx := context.Background() + ctx := t.Context() ollamaContainer, err := ollama.Run( ctx, testImage, @@ -307,7 +307,7 @@ func TestRun_local(t *testing.T) { } func TestRun_localWithCustomLogFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() logFile := filepath.Join(t.TempDir(), "server.log") t.Run("parent-env", func(t *testing.T) { @@ -354,7 +354,7 @@ func TestRun_localWithCustomLogFile(t *testing.T) { } func TestRun_localWithCustomHost(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("parent-env", func(t *testing.T) { t.Setenv("OLLAMA_HOST", "127.0.0.1:1234") @@ -438,7 +438,7 @@ func TestRun_localExec(t *testing.T) { t.Skip("local ollama binary not found, skipping") } - ctx := context.Background() + ctx := t.Context() ollamaContainer, err := ollama.Run(ctx, testImage, ollama.WithUseLocal()) testcontainers.CleanupContainer(t, ollamaContainer) @@ -529,7 +529,7 @@ func TestRun_localValidateRequest(t *testing.T) { t.Skip("local ollama binary not found, skipping") } - ctx := context.Background() + ctx := t.Context() t.Run("waiting-for-nil", func(t *testing.T) { ollamaContainer, err := ollama.Run( ctx, diff --git a/modules/ollama/ollama_test.go b/modules/ollama/ollama_test.go index 40e54fda2a..3d29c447de 100644 --- a/modules/ollama/ollama_test.go +++ b/modules/ollama/ollama_test.go @@ -1,7 +1,6 @@ package ollama_test import ( - "context" "fmt" "io" "net/http" @@ -17,7 +16,7 @@ import ( ) func TestOllama(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := ollama.Run(ctx, "ollama/ollama:0.5.7") testcontainers.CleanupContainer(t, ctr) @@ -40,10 +39,10 @@ func TestOllama(t *testing.T) { t.Run("Pull and Run Model", func(t *testing.T) { model := "all-minilm" - _, _, err = ctr.Exec(context.Background(), []string{"ollama", "pull", model}) + _, _, err = ctr.Exec(t.Context(), []string{"ollama", "pull", model}) require.NoError(t, err) - _, _, err = ctr.Exec(context.Background(), []string{"ollama", "run", model}) + _, _, err = ctr.Exec(t.Context(), []string{"ollama", "run", model}) require.NoError(t, err) assertLoadedModel(t, ctr) @@ -56,12 +55,12 @@ func TestOllama(t *testing.T) { // Users can change the way this is generated, but it should be unique. targetImage := fmt.Sprintf("%s-%s", ollama.DefaultOllamaImage, strings.ToLower(uuid.New().String()[:4])) - err := ctr.Commit(context.Background(), targetImage) + err := ctr.Commit(t.Context(), targetImage) // } require.NoError(t, err) newOllamaContainer, err := ollama.Run( - context.Background(), + t.Context(), targetImage, ) testcontainers.CleanupContainer(t, newOllamaContainer) @@ -72,7 +71,7 @@ func TestOllama(t *testing.T) { } func TestOllama_withReuse(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := ollama.Run(ctx, "ollama/ollama:0.5.7", testcontainers.WithReuseByName("ollama-container")) testcontainers.CleanupContainer(t, ctr) @@ -80,10 +79,10 @@ func TestOllama_withReuse(t *testing.T) { model := "all-minilm" - _, _, err = ctr.Exec(context.Background(), []string{"ollama", "pull", model}) + _, _, err = ctr.Exec(t.Context(), []string{"ollama", "pull", model}) require.NoError(t, err) - _, _, err = ctr.Exec(context.Background(), []string{"ollama", "run", model}) + _, _, err = ctr.Exec(t.Context(), []string{"ollama", "run", model}) require.NoError(t, err) assertLoadedModel(t, ctr) @@ -93,10 +92,10 @@ func TestOllama_withReuse(t *testing.T) { testcontainers.CleanupContainer(t, ctr2) require.NoError(t, err) - _, _, err = ctr2.Exec(context.Background(), []string{"ollama", "pull", model}) + _, _, err = ctr2.Exec(t.Context(), []string{"ollama", "pull", model}) require.NoError(t, err) - _, _, err = ctr2.Exec(context.Background(), []string{"ollama", "run", model}) + _, _, err = ctr2.Exec(t.Context(), []string{"ollama", "run", model}) require.NoError(t, err) assertLoadedModel(t, ctr2) @@ -108,7 +107,7 @@ func TestOllama_withReuse(t *testing.T) { // contains the model name. func assertLoadedModel(t *testing.T, c *ollama.OllamaContainer) { t.Helper() - url, err := c.ConnectionString(context.Background()) + url, err := c.ConnectionString(t.Context()) require.NoError(t, err) httpCli := &http.Client{} @@ -126,7 +125,7 @@ func assertLoadedModel(t *testing.T, c *ollama.OllamaContainer) { } func TestRunContainer_withModel_error(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ollamaContainer, err := ollama.Run( ctx, diff --git a/modules/openfga/examples_test.go b/modules/openfga/examples_test.go index cef1784993..5bd1bbd88b 100644 --- a/modules/openfga/examples_test.go +++ b/modules/openfga/examples_test.go @@ -46,7 +46,8 @@ func ExampleRun() { } func ExampleRun_connectToPlayground() { - openfgaContainer, err := openfga.Run(context.Background(), "openfga/openfga:v1.5.0") + ctx := context.Background() + openfgaContainer, err := openfga.Run(ctx, "openfga/openfga:v1.5.0") defer func() { if err := testcontainers.TerminateContainer(openfgaContainer); err != nil { log.Printf("failed to terminate container: %s", err) @@ -58,7 +59,7 @@ func ExampleRun_connectToPlayground() { } // playgroundEndpoint { - playgroundEndpoint, err := openfgaContainer.PlaygroundEndpoint(context.Background()) + playgroundEndpoint, err := openfgaContainer.PlaygroundEndpoint(ctx) if err != nil { log.Printf("failed to get playground endpoint: %s", err) return @@ -80,7 +81,8 @@ func ExampleRun_connectToPlayground() { } func ExampleRun_connectWithSDKClient() { - openfgaContainer, err := openfga.Run(context.Background(), "openfga/openfga:v1.5.0") + ctx := context.Background() + openfgaContainer, err := openfga.Run(ctx, "openfga/openfga:v1.5.0") defer func() { if err := testcontainers.TerminateContainer(openfgaContainer); err != nil { log.Printf("failed to terminate container: %s", err) @@ -92,7 +94,7 @@ func ExampleRun_connectWithSDKClient() { } // httpEndpoint { - httpEndpoint, err := openfgaContainer.HttpEndpoint(context.Background()) + httpEndpoint, err := openfgaContainer.HttpEndpoint(ctx) if err != nil { log.Printf("failed to get HTTP endpoint: %s", err) return @@ -108,7 +110,7 @@ func ExampleRun_connectWithSDKClient() { return } - list, err := fgaClient.ListStores(context.Background()).Execute() + list, err := fgaClient.ListStores(ctx).Execute() if err != nil { log.Printf("failed to list stores: %s", err) return @@ -116,7 +118,7 @@ func ExampleRun_connectWithSDKClient() { fmt.Println(len(list.Stores)) - store, err := fgaClient.CreateStore(context.Background()).Body(client.ClientCreateStoreRequest{Name: "test"}).Execute() + store, err := fgaClient.CreateStore(ctx).Body(client.ClientCreateStoreRequest{Name: "test"}).Execute() if err != nil { log.Printf("failed to create store: %s", err) return @@ -124,7 +126,7 @@ func ExampleRun_connectWithSDKClient() { fmt.Println(store.Name) - list, err = fgaClient.ListStores(context.Background()).Execute() + list, err = fgaClient.ListStores(ctx).Execute() if err != nil { log.Printf("failed to list stores: %s", err) return @@ -139,10 +141,11 @@ func ExampleRun_connectWithSDKClient() { } func ExampleRun_writeModel() { + ctx := context.Background() // openFGAwriteModel { secret := "openfga-secret" openfgaContainer, err := openfga.Run( - context.Background(), + ctx, "openfga/openfga:v1.5.0", testcontainers.WithEnv(map[string]string{ "OPENFGA_LOG_LEVEL": "warn", @@ -160,7 +163,7 @@ func ExampleRun_writeModel() { return } - httpEndpoint, err := openfgaContainer.HttpEndpoint(context.Background()) + httpEndpoint, err := openfgaContainer.HttpEndpoint(ctx) if err != nil { log.Printf("failed to get HTTP endpoint: %s", err) return @@ -205,7 +208,7 @@ func ExampleRun_writeModel() { return } - resp, err := fgaClient.WriteAuthorizationModel(context.Background()).Body(body).Execute() + resp, err := fgaClient.WriteAuthorizationModel(ctx).Body(body).Execute() if err != nil { log.Printf("failed to write authorization model: %v", err) return diff --git a/modules/openfga/openfga_test.go b/modules/openfga/openfga_test.go index 85e1966198..de327088e8 100644 --- a/modules/openfga/openfga_test.go +++ b/modules/openfga/openfga_test.go @@ -1,7 +1,6 @@ package openfga_test import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -11,7 +10,7 @@ import ( ) func TestOpenFGA(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := openfga.Run(ctx, "openfga/openfga:v1.5.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/openldap/openldap_test.go b/modules/openldap/openldap_test.go index b73a8dce36..3cbbb7ede3 100644 --- a/modules/openldap/openldap_test.go +++ b/modules/openldap/openldap_test.go @@ -1,7 +1,6 @@ package openldap_test import ( - "context" "os" "testing" @@ -13,7 +12,7 @@ import ( ) func TestOpenLDAP(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := openldap.Run(ctx, "bitnami/openldap:2.6.6") testcontainers.CleanupContainer(t, ctr) @@ -21,7 +20,7 @@ func TestOpenLDAP(t *testing.T) { } func TestOpenLDAPWithAdminUsernameAndPassword(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := openldap.Run(ctx, "bitnami/openldap:2.6.6", @@ -44,7 +43,7 @@ func TestOpenLDAPWithAdminUsernameAndPassword(t *testing.T) { } func TestOpenLDAPWithDifferentRoot(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := openldap.Run(ctx, "bitnami/openldap:2.6.6", openldap.WithRoot("dc=mydomain,dc=com")) testcontainers.CleanupContainer(t, ctr) @@ -65,7 +64,7 @@ func TestOpenLDAPWithDifferentRoot(t *testing.T) { } func TestOpenLDAPLoadLdif(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := openldap.Run(ctx, "bitnami/openldap:2.6.6") testcontainers.CleanupContainer(t, ctr) @@ -109,7 +108,7 @@ userPassword: Password1 } func TestOpenLDAPWithInitialLdif(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ldif := `dn: uid=test.user,ou=users,dc=example,dc=org changetype: add diff --git a/modules/opensearch/opensearch_test.go b/modules/opensearch/opensearch_test.go index 15304dbfd6..f03cb724d8 100644 --- a/modules/opensearch/opensearch_test.go +++ b/modules/opensearch/opensearch_test.go @@ -1,7 +1,6 @@ package opensearch_test import ( - "context" "net/http" "testing" @@ -12,7 +11,7 @@ import ( ) func TestOpenSearch(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := opensearch.Run(ctx, "opensearchproject/opensearch:2.11.1") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/pinecone/pinecone_test.go b/modules/pinecone/pinecone_test.go index d96a95011d..28f0036d9c 100644 --- a/modules/pinecone/pinecone_test.go +++ b/modules/pinecone/pinecone_test.go @@ -1,7 +1,6 @@ package pinecone_test import ( - "context" "testing" "github.com/pinecone-io/go-pinecone/v2/pinecone" @@ -12,7 +11,7 @@ import ( ) func TestPinecone(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcpinecone.Run(ctx, "ghcr.io/pinecone-io/pinecone-local:v0.7.0") testcontainers.CleanupContainer(t, ctr) @@ -33,7 +32,7 @@ func TestPinecone(t *testing.T) { } func TestPinecone_index(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tcpinecone.Run(ctx, "ghcr.io/pinecone-io/pinecone-local:v0.7.0") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/postgres/postgres_test.go b/modules/postgres/postgres_test.go index b429002b89..8d13e5896a 100644 --- a/modules/postgres/postgres_test.go +++ b/modules/postgres/postgres_test.go @@ -1,7 +1,6 @@ package postgres_test import ( - "context" "database/sql" "errors" "fmt" @@ -66,7 +65,7 @@ func createSSLCerts(t *testing.T) (*tlscert.Certificate, *tlscert.Certificate, e } func TestPostgres(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string @@ -140,7 +139,7 @@ func TestPostgres(t *testing.T) { } func TestContainerWithWaitForSQL(t *testing.T) { - ctx := context.Background() + ctx := t.Context() port := "5432/tcp" dbURL := func(host string, port nat.Port) string { @@ -188,7 +187,7 @@ func TestContainerWithWaitForSQL(t *testing.T) { } func TestWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := postgres.Run(ctx, "postgres:16-alpine", @@ -212,7 +211,7 @@ func TestWithConfigFile(t *testing.T) { } func TestWithSSL(t *testing.T) { - ctx := context.Background() + ctx := t.Context() caCert, serverCerts, err := createSSLCerts(t) require.NoError(t, err) @@ -245,7 +244,7 @@ func TestWithSSL(t *testing.T) { } func TestSSLValidatesKeyMaterialPath(t *testing.T) { - ctx := context.Background() + ctx := t.Context() _, err := postgres.Run(ctx, "postgres:16-alpine", @@ -262,7 +261,7 @@ func TestSSLValidatesKeyMaterialPath(t *testing.T) { } func TestWithInitScript(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := postgres.Run(ctx, "postgres:15.2-alpine", @@ -291,7 +290,7 @@ func TestWithInitScript(t *testing.T) { } func TestWithOrderedInitScript(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := postgres.Run(ctx, "postgres:15.2-alpine", @@ -367,7 +366,7 @@ func TestSnapshot(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // snapshotAndReset { - ctx := context.Background() + ctx := t.Context() // 1. Start the postgres ctr and run any migrations on it ctr, err := postgres.Run( @@ -401,16 +400,16 @@ func TestSnapshot(t *testing.T) { require.NoError(t, err) }) - conn, err := pgx.Connect(context.Background(), dbURL) + conn, err := pgx.Connect(t.Context(), dbURL) require.NoError(t, err) - defer conn.Close(context.Background()) + defer conn.Close(t.Context()) _, err = conn.Exec(ctx, "INSERT INTO users(name, age) VALUES ($1, $2)", "test", 42) require.NoError(t, err) var name string var age int64 - err = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) + err = conn.QueryRow(t.Context(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) require.NoError(t, err) require.Equal(t, "test", name) @@ -424,13 +423,13 @@ func TestSnapshot(t *testing.T) { require.NoError(t, err) }) - conn, err := pgx.Connect(context.Background(), dbURL) + conn, err := pgx.Connect(t.Context(), dbURL) require.NoError(t, err) - defer conn.Close(context.Background()) + defer conn.Close(t.Context()) var name string var age int64 - err = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) + err = conn.QueryRow(t.Context(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) require.ErrorIs(t, err, pgx.ErrNoRows) }) // } @@ -439,7 +438,7 @@ func TestSnapshot(t *testing.T) { } func TestSnapshotWithOverrides(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dbname := "other-db" user := "other-user" @@ -472,12 +471,12 @@ func TestSnapshotWithOverrides(t *testing.T) { err = ctr.Restore(ctx) require.NoError(t, err) - conn, err := pgx.Connect(context.Background(), dbURL) + conn, err := pgx.Connect(t.Context(), dbURL) require.NoError(t, err) - defer conn.Close(context.Background()) + defer conn.Close(t.Context()) var count int64 - err = conn.QueryRow(context.Background(), "SELECT COUNT(1) FROM users").Scan(&count) + err = conn.QueryRow(t.Context(), "SELECT COUNT(1) FROM users").Scan(&count) require.NoError(t, err) require.Zero(t, count) @@ -485,7 +484,7 @@ func TestSnapshotWithOverrides(t *testing.T) { } func TestSnapshotDuplicate(t *testing.T) { - ctx := context.Background() + ctx := t.Context() dbname := "other-db" user := "other-user" @@ -513,7 +512,7 @@ func TestSnapshotDuplicate(t *testing.T) { } func TestSnapshotWithDockerExecFallback(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // postgresWithSQLDriver { // 1. Start the postgres container and run any migrations on it @@ -550,16 +549,16 @@ func TestSnapshotWithDockerExecFallback(t *testing.T) { require.NoError(t, err) }) - conn, err2 := pgx.Connect(context.Background(), dbURL) + conn, err2 := pgx.Connect(t.Context(), dbURL) require.NoError(t, err2) - defer conn.Close(context.Background()) + defer conn.Close(t.Context()) _, err2 = conn.Exec(ctx, "INSERT INTO users(name, age) VALUES ($1, $2)", "test", 42) require.NoError(t, err2) var name string var age int64 - err2 = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) + err2 = conn.QueryRow(t.Context(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) require.NoError(t, err2) require.Equal(t, "test", name) @@ -573,13 +572,13 @@ func TestSnapshotWithDockerExecFallback(t *testing.T) { require.NoError(t, err) }) - conn, err2 := pgx.Connect(context.Background(), dbURL) + conn, err2 := pgx.Connect(t.Context(), dbURL) require.NoError(t, err2) - defer conn.Close(context.Background()) + defer conn.Close(t.Context()) var name string var age int64 - err2 = conn.QueryRow(context.Background(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) + err2 = conn.QueryRow(t.Context(), "SELECT name, age FROM users LIMIT 1").Scan(&name, &age) require.ErrorIs(t, err2, pgx.ErrNoRows) }) // } diff --git a/modules/pulsar/pulsar_test.go b/modules/pulsar/pulsar_test.go index 1fa07923d0..7afdbd752c 100644 --- a/modules/pulsar/pulsar_test.go +++ b/modules/pulsar/pulsar_test.go @@ -29,7 +29,7 @@ type noopLogConsumer struct{} func (*noopLogConsumer) Accept(testcontainers.Log) {} func TestPulsar(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() nw, err := tcnetwork.New(ctx) diff --git a/modules/qdrant/examples_test.go b/modules/qdrant/examples_test.go index 11ea896877..451e4b2265 100644 --- a/modules/qdrant/examples_test.go +++ b/modules/qdrant/examples_test.go @@ -43,8 +43,9 @@ func ExampleRun() { } func ExampleRun_createPoints() { + ctx := context.Background() // fullExample { - qdrantContainer, err := qdrant.Run(context.Background(), "qdrant/qdrant:v1.7.4") + qdrantContainer, err := qdrant.Run(ctx, "qdrant/qdrant:v1.7.4") defer func() { if err := testcontainers.TerminateContainer(qdrantContainer); err != nil { log.Printf("failed to terminate container: %s", err) @@ -55,7 +56,7 @@ func ExampleRun_createPoints() { return } - grpcEndpoint, err := qdrantContainer.GRPCEndpoint(context.Background()) + grpcEndpoint, err := qdrantContainer.GRPCEndpoint(ctx) if err != nil { log.Printf("failed to get gRPC endpoint: %s", err) return @@ -79,7 +80,7 @@ func ExampleRun_createPoints() { // 1. create the collection var defaultSegmentNumber uint64 = 2 - _, err = collectionsClient.Create(context.Background(), &pb.CreateCollection{ + _, err = collectionsClient.Create(ctx, &pb.CreateCollection{ CollectionName: collectionName, VectorsConfig: &pb.VectorsConfig{Config: &pb.VectorsConfig_Params{ Params: &pb.VectorParams{ @@ -97,7 +98,7 @@ func ExampleRun_createPoints() { } // 2. Contact the server and print out its response. - ctx, cancel := context.WithTimeout(context.Background(), time.Second) + ctx, cancel := context.WithTimeout(ctx, time.Second) defer cancel() r, err := collectionsClient.List(ctx, &pb.ListCollectionsRequest{}) if err != nil { @@ -112,7 +113,7 @@ func ExampleRun_createPoints() { // 4. Create keyword field index fieldIndex1Type := pb.FieldType_FieldTypeKeyword fieldIndex1Name := "city" - _, err = pointsClient.CreateFieldIndex(context.Background(), &pb.CreateFieldIndexCollection{ + _, err = pointsClient.CreateFieldIndex(ctx, &pb.CreateFieldIndexCollection{ CollectionName: collectionName, FieldName: fieldIndex1Name, FieldType: &fieldIndex1Type, @@ -125,7 +126,7 @@ func ExampleRun_createPoints() { // 5. Create integer field index fieldIndex2Type := pb.FieldType_FieldTypeInteger fieldIndex2Name := "count" - _, err = pointsClient.CreateFieldIndex(context.Background(), &pb.CreateFieldIndexCollection{ + _, err = pointsClient.CreateFieldIndex(ctx, &pb.CreateFieldIndexCollection{ CollectionName: collectionName, FieldName: fieldIndex2Name, FieldType: &fieldIndex2Type, @@ -259,7 +260,7 @@ func ExampleRun_createPoints() { Payload: map[string]*pb.Value{}, }, } - _, err = pointsClient.Upsert(context.Background(), &pb.UpsertPoints{ + _, err = pointsClient.Upsert(ctx, &pb.UpsertPoints{ CollectionName: collectionName, Wait: &waitUpsert, Points: upsertPoints, @@ -270,7 +271,7 @@ func ExampleRun_createPoints() { } // 7. Retrieve points by ids - pointsByID, err := pointsClient.Get(context.Background(), &pb.GetPoints{ + pointsByID, err := pointsClient.Get(ctx, &pb.GetPoints{ CollectionName: collectionName, Ids: []*pb.PointId{ {PointIdOptions: &pb.PointId_Num{Num: 1}}, @@ -285,7 +286,7 @@ func ExampleRun_createPoints() { fmt.Printf("Retrieved points: %d\n", len(pointsByID.GetResult())) // 8. Unfiltered search - unfilteredSearchResult, err := pointsClient.Search(context.Background(), &pb.SearchPoints{ + unfilteredSearchResult, err := pointsClient.Search(ctx, &pb.SearchPoints{ CollectionName: collectionName, Vector: []float32{0.2, 0.1, 0.9, 0.7}, Limit: 3, diff --git a/modules/qdrant/qdrant_test.go b/modules/qdrant/qdrant_test.go index 57f98fe9fc..83a3c92d23 100644 --- a/modules/qdrant/qdrant_test.go +++ b/modules/qdrant/qdrant_test.go @@ -1,7 +1,6 @@ package qdrant_test import ( - "context" "net/http" "testing" @@ -14,7 +13,7 @@ import ( ) func TestQdrant(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := qdrant.Run(ctx, "qdrant/qdrant:v1.7.4") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/rabbitmq/examples_test.go b/modules/rabbitmq/examples_test.go index b9c4e9fdf2..9dc85368e6 100644 --- a/modules/rabbitmq/examples_test.go +++ b/modules/rabbitmq/examples_test.go @@ -187,7 +187,7 @@ func ExampleRun_withPlugins() { return } - if err = assertPlugins(rabbitmqContainer, "rabbitmq_shovel", "rabbitmq_random_exchange"); err != nil { + if err = assertPlugins(ctx, rabbitmqContainer, "rabbitmq_shovel", "rabbitmq_random_exchange"); err != nil { log.Printf("failed to find plugin: %s", err) return } @@ -232,9 +232,7 @@ func ExampleRun_withCustomConfigFile() { // true } -func assertPlugins(container testcontainers.Container, plugins ...string) error { - ctx := context.Background() - +func assertPlugins(ctx context.Context, container testcontainers.Container, plugins ...string) error { for _, plugin := range plugins { _, out, err := container.Exec(ctx, []string{"rabbitmq-plugins", "is_enabled", plugin}) if err != nil { diff --git a/modules/rabbitmq/rabbitmq_test.go b/modules/rabbitmq/rabbitmq_test.go index 0190cb97e5..f01b0b7f5d 100644 --- a/modules/rabbitmq/rabbitmq_test.go +++ b/modules/rabbitmq/rabbitmq_test.go @@ -1,7 +1,6 @@ package rabbitmq_test import ( - "context" "crypto/tls" "crypto/x509" "fmt" @@ -18,7 +17,7 @@ import ( ) func TestRunContainer_connectUsingAmqp(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rabbitmqContainer, err := rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine") testcontainers.CleanupContainer(t, rabbitmqContainer) @@ -35,7 +34,7 @@ func TestRunContainer_connectUsingAmqp(t *testing.T) { } func TestRunContainer_connectUsingAmqps(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tmpDir := t.TempDir() @@ -89,7 +88,7 @@ func TestRunContainer_connectUsingAmqps(t *testing.T) { } func TestRunContainer_withAllSettings(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rabbitmqContainer, err := rabbitmq.Run(ctx, "rabbitmq:3.12.11-management-alpine", @@ -219,7 +218,7 @@ func TestRunContainer_withAllSettings(t *testing.T) { func requireEntity(t *testing.T, container testcontainers.Container, listCommand string, entities ...string) { t.Helper() - ctx := context.Background() + ctx := t.Context() cmd := []string{"rabbitmqadmin", "list", listCommand} @@ -232,7 +231,7 @@ func requireEntity(t *testing.T, container testcontainers.Container, listCommand func requireEntityWithVHost(t *testing.T, container testcontainers.Container, listCommand string, vhostID int, entities ...string) { t.Helper() - ctx := context.Background() + ctx := t.Context() cmd := []string{"rabbitmqadmin", "list", listCommand} if vhostID > 0 { @@ -248,7 +247,7 @@ func requireEntityWithVHost(t *testing.T, container testcontainers.Container, li func requirePluginIsEnabled(t *testing.T, container testcontainers.Container, plugins ...string) { t.Helper() - ctx := context.Background() + ctx := t.Context() for _, plugin := range plugins { diff --git a/modules/redis/redis_test.go b/modules/redis/redis_test.go index 6fdcc45d0e..395fface46 100644 --- a/modules/redis/redis_test.go +++ b/modules/redis/redis_test.go @@ -16,7 +16,7 @@ import ( ) func TestIntegrationSetGet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() redisContainer, err := tcredis.Run(ctx, "redis:7") testcontainers.CleanupContainer(t, redisContainer) @@ -26,7 +26,7 @@ func TestIntegrationSetGet(t *testing.T) { } func TestRedisWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() redisContainer, err := tcredis.Run(ctx, "redis:7", tcredis.WithConfigFile(filepath.Join("testdata", "redis7.conf"))) testcontainers.CleanupContainer(t, redisContainer) @@ -41,7 +41,7 @@ func TestRedisWithConfigFile(t *testing.T) { } func TestRedisWithLogLevel(t *testing.T) { - ctx := context.Background() + ctx := t.Context() redisContainer, err := tcredis.Run(ctx, "redis:7", tcredis.WithLogLevel(tcredis.LogLevelVerbose)) testcontainers.CleanupContainer(t, redisContainer) @@ -56,7 +56,7 @@ func TestRedisWithLogLevel(t *testing.T) { } func TestRedisWithSnapshotting(t *testing.T) { - ctx := context.Background() + ctx := t.Context() redisContainer, err := tcredis.Run(ctx, "redis:7", tcredis.WithSnapshotting(10, 1)) testcontainers.CleanupContainer(t, redisContainer) @@ -71,7 +71,7 @@ func TestRedisWithSnapshotting(t *testing.T) { } func TestRedisWithTLS(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("mtls-disabled", func(t *testing.T) { redisContainer, err := tcredis.Run(ctx, "redis:7", tcredis.WithTLS()) diff --git a/modules/redpanda/redpanda_test.go b/modules/redpanda/redpanda_test.go index da90cb7d79..78e8b4619e 100644 --- a/modules/redpanda/redpanda_test.go +++ b/modules/redpanda/redpanda_test.go @@ -28,7 +28,7 @@ import ( const testImage = "docker.redpanda.com/redpandadata/redpanda:v25.2.4" func TestRedpanda(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := redpanda.Run(ctx, testImage) testcontainers.CleanupContainer(t, ctr) @@ -90,7 +90,7 @@ func TestRedpanda(t *testing.T) { } func TestRedpandaWithAuthentication(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // redpandaCreateContainer { ctr, err := redpanda.Run(ctx, testImage, @@ -205,7 +205,7 @@ func TestRedpandaWithAuthentication(t *testing.T) { } func TestRedpandaWithBootstrapUserAuthentication(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := redpanda.Run(ctx, testImage, redpanda.WithEnableSASL(), @@ -315,7 +315,7 @@ func TestRedpandaWithBootstrapUserAuthentication(t *testing.T) { } func TestRedpandaWithOldVersionAndWasm(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // this would fail to start if we weren't ignoring wasm transforms for older versions ctr, err := redpanda.Run(ctx, "redpandadata/redpanda:v23.2.18", @@ -440,7 +440,7 @@ func TestRedpandaWithOldVersionAndWasm(t *testing.T) { } func TestRedpandaProduceWithAutoCreateTopics(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := redpanda.Run(ctx, testImage, redpanda.WithAutoCreateTopics()) testcontainers.CleanupContainer(t, ctr) @@ -461,7 +461,7 @@ func TestRedpandaProduceWithAutoCreateTopics(t *testing.T) { } func TestRedpandaWithTLS(t *testing.T) { - ctx := context.Background() + ctx := t.Context() containerHostAddress, err := containerHost(ctx) require.NoError(t, err) @@ -524,7 +524,7 @@ func TestRedpandaWithTLS(t *testing.T) { } func TestRedpandaWithTLSAndSASL(t *testing.T) { - ctx := context.Background() + ctx := t.Context() containerHostAddress, err := containerHost(ctx) require.NoError(t, err) @@ -566,7 +566,7 @@ func TestRedpandaWithTLSAndSASL(t *testing.T) { } func TestRedpandaListener_Simple(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // 1. Create network rpNetwork, err := network.New(ctx) @@ -629,7 +629,7 @@ func TestRedpandaListener_Simple(t *testing.T) { } func TestRedpandaListener_InvalidPort(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // 1. Create network RPNetwork, err := network.New(ctx) @@ -647,7 +647,7 @@ func TestRedpandaListener_InvalidPort(t *testing.T) { } func TestRedpandaListener_NoNetwork(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // 1. Attempt Start Redpanda ctr ctr, err := redpanda.Run(ctx, @@ -659,7 +659,7 @@ func TestRedpandaListener_NoNetwork(t *testing.T) { } func TestRedpandaBootstrapConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() container, err := redpanda.RunContainer(ctx, redpanda.WithEnableWasmTransform(), @@ -714,7 +714,7 @@ func TestRedpandaBootstrapConfig(t *testing.T) { } func TestRedpandaHTTPProxy(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := redpanda.Run(ctx, testImage) testcontainers.CleanupContainer(t, ctr) @@ -753,7 +753,7 @@ func TestRedpandaHTTPProxy(t *testing.T) { } func TestHTTPProxyWithBasicAuthentication(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := redpanda.Run(ctx, testImage, redpanda.WithEnableKafkaAuthorization(), diff --git a/modules/registry/examples_test.go b/modules/registry/examples_test.go index e73dc045b4..05ef1130ec 100644 --- a/modules/registry/examples_test.go +++ b/modules/registry/examples_test.go @@ -155,7 +155,7 @@ func ExampleRun_pushImage() { repo := registryContainer.RegistryName + "/customredis" tag := "v1.2.3" - redisC, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ + redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: filepath.Join("testdata", "redis"), @@ -185,7 +185,7 @@ func ExampleRun_pushImage() { // repo is localhost:32878/customredis // tag is v1.2.3 newImage := fmt.Sprintf("%s:%s", repo, tag) - err = registryContainer.PushImage(context.Background(), fmt.Sprintf("%s:%s", repo, tag)) + err = registryContainer.PushImage(ctx, fmt.Sprintf("%s:%s", repo, tag)) if err != nil { log.Printf("failed to push image: %s", err) return @@ -224,7 +224,7 @@ func ExampleRun_pushImage() { } // } - err = registryContainer.PushImage(context.Background(), taggedImage) + err = registryContainer.PushImage(ctx, taggedImage) if err != nil { log.Printf("failed to push image: %s", err) return @@ -235,19 +235,19 @@ func ExampleRun_pushImage() { // deletingImage { // newImage is customredis:v1.2.3 - err = registryContainer.DeleteImage(context.Background(), newImage) + err = registryContainer.DeleteImage(ctx, newImage) if err != nil { log.Printf("failed to delete image: %s", err) return } // } - err = registryContainer.DeleteImage(context.Background(), taggedImage) + err = registryContainer.DeleteImage(ctx, taggedImage) if err != nil { log.Printf("failed to delete image: %s", err) return } - newRedisC, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ + newRedisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ Image: taggedImage, ExposedPorts: []string{"6379/tcp"}, @@ -265,7 +265,7 @@ func ExampleRun_pushImage() { return } - state, err := newRedisC.State(context.Background()) + state, err := newRedisC.State(ctx) if err != nil { log.Printf("failed to get redis container state from %s: %s", taggedImage, err) return diff --git a/modules/registry/registry_test.go b/modules/registry/registry_test.go index 3315269fb5..2002488309 100644 --- a/modules/registry/registry_test.go +++ b/modules/registry/registry_test.go @@ -1,7 +1,6 @@ package registry_test import ( - "context" "encoding/json" "net/http" "path/filepath" @@ -19,7 +18,7 @@ import ( ) func TestRegistry_unauthenticated(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := registry.Run(ctx, registry.DefaultImage) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -35,7 +34,7 @@ func TestRegistry_unauthenticated(t *testing.T) { } func TestRunContainer_authenticated(t *testing.T) { - ctx := context.Background() + ctx := t.Context() registryContainer, err := registry.Run( ctx, registry.DefaultImage, @@ -96,7 +95,7 @@ func TestRunContainer_authenticated(t *testing.T) { t.Run("build images with wrong credentials fails", func(tt *testing.T) { setAuthConfig(tt, registryHost, "foo", "bar") - redisC, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ + redisC, err := testcontainers.GenericContainer(t.Context(), testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: filepath.Join("testdata", "redis"), @@ -123,7 +122,7 @@ func TestRunContainer_authenticated(t *testing.T) { // The container should start because the authentication // is correct. - redisC, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ + redisC, err := testcontainers.GenericContainer(t.Context(), testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: filepath.Join("testdata", "redis"), @@ -140,14 +139,14 @@ func TestRunContainer_authenticated(t *testing.T) { testcontainers.CleanupContainer(tt, redisC) require.NoError(tt, err) - state, err := redisC.State(context.Background()) + state, err := redisC.State(t.Context()) require.NoError(tt, err) require.True(tt, state.Running, "expected redis container to be running, but it is not") }) } func TestRunContainer_authenticated_withCredentials(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // htpasswdString { registryContainer, err := registry.Run( ctx, @@ -176,7 +175,7 @@ func TestRunContainer_authenticated_withCredentials(t *testing.T) { func TestRunContainer_authenticated_htpasswd_atomic_per_container(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() r := require.New(t) type container struct { @@ -236,7 +235,7 @@ func TestRunContainer_authenticated_htpasswd_atomic_per_container(t *testing.T) } func TestRunContainer_wrongData(t *testing.T) { - ctx := context.Background() + ctx := t.Context() registryContainer, err := registry.Run( ctx, registry.DefaultImage, @@ -256,7 +255,7 @@ func TestRunContainer_wrongData(t *testing.T) { // The container won't be able to start because the data // directory is wrong. - redisC, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{ + redisC, err := testcontainers.GenericContainer(t.Context(), testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: filepath.Join("testdata", "redis"), @@ -275,7 +274,7 @@ func TestRunContainer_wrongData(t *testing.T) { } func TestPullImage_samePlatform(t *testing.T) { - ctx := context.Background() + ctx := t.Context() registryContainer, err := registry.Run(ctx, registry.DefaultImage) testcontainers.CleanupContainer(t, registryContainer) require.NoError(t, err) diff --git a/modules/scylladb/scylladb_test.go b/modules/scylladb/scylladb_test.go index 9ec7565359..1ecc51ad58 100644 --- a/modules/scylladb/scylladb_test.go +++ b/modules/scylladb/scylladb_test.go @@ -25,7 +25,7 @@ import ( var scyllaYaml []byte func TestScyllaDB(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := scylladb.Run(ctx, "scylladb/scylla:6.2", @@ -64,7 +64,7 @@ func TestScyllaDB(t *testing.T) { } func TestScyllaWithConfig(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := scylladb.Run(ctx, "scylladb/scylla:6.2", @@ -110,7 +110,7 @@ func TestScyllaWithConfig(t *testing.T) { } func TestScyllaAlternator(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("test-with-alternator", func(t *testing.T) { ctr, err := scylladb.Run(ctx, @@ -154,12 +154,12 @@ func (r *scyllaAlternatorResolver) ResolveEndpoint(_ context.Context, _ dynamodb func getDynamoAlternatorClient(t *testing.T, c *scylladb.Container) (*dynamodb.Client, error) { t.Helper() - hostPort, err := c.AlternatorConnectionHost(context.Background()) + hostPort, err := c.AlternatorConnectionHost(t.Context()) if err != nil { return nil, fmt.Errorf("connection host: %w", err) } - cfg, err := config.LoadDefaultConfig(context.Background(), config.WithCredentialsProvider(credentials.StaticCredentialsProvider{ + cfg, err := config.LoadDefaultConfig(t.Context(), config.WithCredentialsProvider(credentials.StaticCredentialsProvider{ Value: aws.Credentials{ AccessKeyID: "SCYLLA_ALTERNATOR_ACCESS_KEY_ID", SecretAccessKey: "SCYLLA_ALTERNATOR_SECRET_ACCESS", @@ -176,7 +176,7 @@ func getDynamoAlternatorClient(t *testing.T, c *scylladb.Container) (*dynamodb.C func requireCreateTable(t *testing.T, client *dynamodb.Client) { t.Helper() - _, err := client.CreateTable(context.Background(), &dynamodb.CreateTableInput{ + _, err := client.CreateTable(t.Context(), &dynamodb.CreateTableInput{ TableName: aws.String("demo_table"), KeySchema: []types.KeySchemaElement{ { diff --git a/modules/socat/socat_test.go b/modules/socat/socat_test.go index 414cc4d7b6..d91050e8cd 100644 --- a/modules/socat/socat_test.go +++ b/modules/socat/socat_test.go @@ -1,7 +1,6 @@ package socat_test import ( - "context" "io" "net/http" "testing" @@ -14,7 +13,7 @@ import ( ) func TestSocat(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := socat.Run(ctx, socat.DefaultImage) testcontainers.CleanupContainer(t, ctr) @@ -24,7 +23,7 @@ func TestSocat(t *testing.T) { } func TestRun_helloWorld(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) testcontainers.CleanupNetwork(t, nw) @@ -72,7 +71,7 @@ func TestRun_helloWorld(t *testing.T) { } func TestRun_helloWorldDifferentPort(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) testcontainers.CleanupNetwork(t, nw) @@ -126,7 +125,7 @@ func TestRun_helloWorldDifferentPort(t *testing.T) { } func TestRun_helloWorld_WrongImage(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) testcontainers.CleanupNetwork(t, nw) @@ -161,7 +160,7 @@ func TestRun_helloWorld_WrongImage(t *testing.T) { } func TestRun_multipleTargets(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) testcontainers.CleanupNetwork(t, nw) diff --git a/modules/solace/examples_test.go b/modules/solace/examples_test.go index 68b7b6e612..0d86a227f3 100644 --- a/modules/solace/examples_test.go +++ b/modules/solace/examples_test.go @@ -62,7 +62,7 @@ func ExampleRun_withTopicAndQueue() { fmt.Println(err) // the [testMessagePublishAndConsume] function is responsible for printing the output // to the console, so be aware of that when adding it to other examples. - err = testMessagePublishAndConsume(ctr, "TestQueue", "Topic/MyTopic") + err = testMessagePublishAndConsume(ctx, ctr, "TestQueue", "Topic/MyTopic") fmt.Println(err) // Output: @@ -73,9 +73,9 @@ func ExampleRun_withTopicAndQueue() { // } -func testMessagePublishAndConsume(ctr *sc.Container, queueName, topicName string) error { +func testMessagePublishAndConsume(ctx context.Context, ctr *sc.Container, queueName, topicName string) error { // Get the SMF service URL from the container - smfURL, err := ctr.BrokerURLFor(context.Background(), sc.ServiceSMF) + smfURL, err := ctr.BrokerURLFor(ctx, sc.ServiceSMF) if err != nil { return fmt.Errorf("failed to get SMF URL: %w", err) } diff --git a/modules/solace/solace_test.go b/modules/solace/solace_test.go index 779d90b569..5f1fd95000 100644 --- a/modules/solace/solace_test.go +++ b/modules/solace/solace_test.go @@ -1,7 +1,6 @@ package solace_test import ( - "context" "log" "testing" @@ -12,7 +11,7 @@ import ( ) func TestSolace(t *testing.T) { - ctx := context.Background() + ctx := t.Context() queueName := "TestQueue" topicName := "Topic/ActualTopic" @@ -46,6 +45,6 @@ func TestSolace(t *testing.T) { require.Contains(t, origin, "amqp://") // Test message publishing and consumption using Solace SDK - err = testMessagePublishAndConsume(ctr, queueName, topicName) + err = testMessagePublishAndConsume(ctx, ctr, queueName, topicName) require.NoError(t, err, "Message publish and consume test should pass") } diff --git a/modules/surrealdb/surrealdb_test.go b/modules/surrealdb/surrealdb_test.go index 4bc12a6f60..06007042b4 100644 --- a/modules/surrealdb/surrealdb_test.go +++ b/modules/surrealdb/surrealdb_test.go @@ -1,7 +1,6 @@ package surrealdb import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -11,7 +10,7 @@ import ( ) func TestSurrealDBSelect(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "surrealdb/surrealdb:v1.1.1") testcontainers.CleanupContainer(t, ctr) @@ -48,7 +47,7 @@ func TestSurrealDBSelect(t *testing.T) { } func TestSurrealDBWithAuth(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, "surrealdb/surrealdb:v1.1.1", WithAuthentication()) testcontainers.CleanupContainer(t, ctr) diff --git a/modules/toxiproxy/options_test.go b/modules/toxiproxy/options_test.go index 6447168730..ec51a7ed41 100644 --- a/modules/toxiproxy/options_test.go +++ b/modules/toxiproxy/options_test.go @@ -1,7 +1,6 @@ package toxiproxy import ( - "context" "encoding/json" "strings" "testing" @@ -108,7 +107,7 @@ func TestRun_withConfigFile_and_proxy(t *testing.T) { } ]` - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) require.NoError(t, err) diff --git a/modules/toxiproxy/toxiproxy_test.go b/modules/toxiproxy/toxiproxy_test.go index 119f271e70..94e940c328 100644 --- a/modules/toxiproxy/toxiproxy_test.go +++ b/modules/toxiproxy/toxiproxy_test.go @@ -2,7 +2,6 @@ package toxiproxy_test import ( "bytes" - "context" _ "embed" "fmt" "testing" @@ -20,7 +19,7 @@ import ( ) func TestRun(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := tctoxiproxy.Run(ctx, "ghcr.io/shopify/toxiproxy:2.12.0") testcontainers.CleanupContainer(t, ctr) @@ -33,7 +32,7 @@ func TestRun(t *testing.T) { var configFile []byte func TestRun_withConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() nw, err := network.New(ctx) require.NoError(t, err) diff --git a/modules/valkey/valkey_test.go b/modules/valkey/valkey_test.go index ef8eead8cc..643ff23275 100644 --- a/modules/valkey/valkey_test.go +++ b/modules/valkey/valkey_test.go @@ -16,7 +16,7 @@ import ( ) func TestIntegrationSetGet(t *testing.T) { - ctx := context.Background() + ctx := t.Context() valkeyContainer, err := tcvalkey.Run(ctx, "valkey/valkey:7.2.5") testcontainers.CleanupContainer(t, valkeyContainer) @@ -26,7 +26,7 @@ func TestIntegrationSetGet(t *testing.T) { } func TestValkeyWithConfigFile(t *testing.T) { - ctx := context.Background() + ctx := t.Context() valkeyContainer, err := tcvalkey.Run(ctx, "valkey/valkey:7.2.5", tcvalkey.WithConfigFile(filepath.Join("testdata", "valkey7.conf"))) testcontainers.CleanupContainer(t, valkeyContainer) @@ -36,7 +36,7 @@ func TestValkeyWithConfigFile(t *testing.T) { } func TestValkeyWithImage(t *testing.T) { - ctx := context.Background() + ctx := t.Context() tests := []struct { name string @@ -61,7 +61,7 @@ func TestValkeyWithImage(t *testing.T) { } func TestValkeyWithLogLevel(t *testing.T) { - ctx := context.Background() + ctx := t.Context() valkeyContainer, err := tcvalkey.Run(ctx, "valkey/valkey:7.2.5", tcvalkey.WithLogLevel(tcvalkey.LogLevelVerbose)) testcontainers.CleanupContainer(t, valkeyContainer) @@ -71,7 +71,7 @@ func TestValkeyWithLogLevel(t *testing.T) { } func TestValkeyWithSnapshotting(t *testing.T) { - ctx := context.Background() + ctx := t.Context() valkeyContainer, err := tcvalkey.Run(ctx, "valkey/valkey:7.2.5", tcvalkey.WithSnapshotting(10, 1)) testcontainers.CleanupContainer(t, valkeyContainer) @@ -81,7 +81,7 @@ func TestValkeyWithSnapshotting(t *testing.T) { } func TestRedisWithTLS(t *testing.T) { - ctx := context.Background() + ctx := t.Context() t.Run("mtls-disabled", func(t *testing.T) { valkeyContainer, err := tcvalkey.Run(ctx, "valkey/valkey:7.2.5", tcvalkey.WithTLS()) diff --git a/modules/vault/vault_test.go b/modules/vault/vault_test.go index 22b87930bb..bf8fceaa52 100644 --- a/modules/vault/vault_test.go +++ b/modules/vault/vault_test.go @@ -1,7 +1,6 @@ package vault_test import ( - "context" "io" "net/http" "testing" @@ -22,7 +21,7 @@ const ( ) func TestVault(t *testing.T) { - ctx := context.Background() + ctx := t.Context() opts := []testcontainers.ContainerCustomizer{ // WithToken { testcontainervault.WithToken(token), @@ -44,7 +43,7 @@ func TestVault(t *testing.T) { t.Run("Get secret path", func(t *testing.T) { t.Run("From vault CLI", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // containerCliRead { exec, reader, err := vaultContainer.Exec(ctx, []string{"vault", "kv", "get", "-format=json", "secret/test1"}) @@ -75,7 +74,7 @@ func TestVault(t *testing.T) { }) t.Run("From vault client library", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() // clientLibRead { client, err := vaultClient.New( diff --git a/modules/vearch/vearch_test.go b/modules/vearch/vearch_test.go index 4caf25e633..60755c3714 100644 --- a/modules/vearch/vearch_test.go +++ b/modules/vearch/vearch_test.go @@ -1,7 +1,6 @@ package vearch_test import ( - "context" "net/http" "testing" @@ -12,7 +11,7 @@ import ( ) func TestVearch(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := vearch.Run(ctx, "vearch/vearch:3.5.1") testcontainers.CleanupContainer(t, ctr) diff --git a/modules/weaviate/weaviate_test.go b/modules/weaviate/weaviate_test.go index 1cf8b0fa6e..ebd038c61f 100644 --- a/modules/weaviate/weaviate_test.go +++ b/modules/weaviate/weaviate_test.go @@ -1,7 +1,6 @@ package weaviate_test import ( - "context" "fmt" "net/http" "testing" @@ -18,7 +17,7 @@ import ( ) func TestWeaviate(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := weaviate.Run(ctx, "semitechnologies/weaviate:1.29.0") testcontainers.CleanupContainer(t, ctr) @@ -50,7 +49,7 @@ func TestWeaviate(t *testing.T) { conn, err := grpc.NewClient(host, opts...) require.NoErrorf(t, err, "failed to dial connection") client := grpc_health_v1.NewHealthClient(conn) - check, err := client.Check(context.TODO(), &grpc_health_v1.HealthCheckRequest{}) + check, err := client.Check(ctx, &grpc_health_v1.HealthCheckRequest{}) require.NoErrorf(t, err, "failed to get a health check") require.Equalf(t, grpc_health_v1.HealthCheckResponse_SERVING.Enum().Number(), check.Status.Number(), "unexpected status code: %d", check.Status.Number()) }) diff --git a/modules/yugabytedb/yugabytedb_test.go b/modules/yugabytedb/yugabytedb_test.go index 38a93f0c89..4393031ab8 100644 --- a/modules/yugabytedb/yugabytedb_test.go +++ b/modules/yugabytedb/yugabytedb_test.go @@ -1,7 +1,6 @@ package yugabytedb_test import ( - "context" "database/sql" "fmt" "net" @@ -18,7 +17,7 @@ import ( func TestYugabyteDB_YSQL(t *testing.T) { t.Run("Run", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := yugabytedb.Run(ctx, "yugabytedb/yugabyte:2024.1.3.0-b105") testcontainers.CleanupContainer(t, ctr) @@ -43,7 +42,7 @@ func TestYugabyteDB_YSQL(t *testing.T) { }) t.Run("custom-options", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := yugabytedb.Run(ctx, "yugabytedb/yugabyte:2024.1.3.0-b105", yugabytedb.WithDatabaseName("custom-db"), yugabytedb.WithDatabaseUser("custom-user"), @@ -73,7 +72,7 @@ func TestYugabyteDB_YSQL(t *testing.T) { func TestYugabyteDB_YCQL(t *testing.T) { t.Run("Run", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := yugabytedb.Run(ctx, "yugabytedb/yugabyte:2024.1.3.0-b105") testcontainers.CleanupContainer(t, ctr) @@ -98,7 +97,7 @@ func TestYugabyteDB_YCQL(t *testing.T) { }) t.Run("custom-options", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() ctr, err := yugabytedb.Run(ctx, "yugabytedb/yugabyte:2024.1.3.0-b105", yugabytedb.WithKeyspace("custom-keyspace"), diff --git a/mounts_test.go b/mounts_test.go index 8402529a49..c4d6970cf7 100644 --- a/mounts_test.go +++ b/mounts_test.go @@ -1,7 +1,6 @@ package testcontainers_test import ( - "context" "testing" "github.com/docker/docker/api/types/mount" @@ -224,7 +223,7 @@ func TestContainerMounts_PrepareMounts(t *testing.T) { func TestCreateContainerWithVolume(t *testing.T) { // volumeMounts { volumeName := "test-volume" - ctx := context.Background() + ctx := t.Context() c, err := testcontainers.Run(ctx, "alpine", testcontainers.WithMounts(testcontainers.ContainerMount{ @@ -250,7 +249,7 @@ func TestCreateContainerWithVolume(t *testing.T) { func TestMountsReceiveRyukLabels(t *testing.T) { volumeName := "app-data" - ctx := context.Background() + ctx := t.Context() client, err := testcontainers.NewDockerClientWithOpts(ctx) require.NoError(t, err) diff --git a/network/network_test.go b/network/network_test.go index 58f02b0e9b..569dd8e449 100644 --- a/network/network_test.go +++ b/network/network_test.go @@ -23,7 +23,7 @@ const ( ) func TestNew(t *testing.T) { - ctx := context.Background() + ctx := t.Context() net, err := network.New(ctx, network.WithAttachable(), @@ -44,10 +44,10 @@ func TestNew(t *testing.T) { testcontainers.CleanupContainer(t, nginxC) require.NoError(t, err) - client, err := testcontainers.NewDockerClientWithOpts(context.Background()) + client, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) - resources, err := client.NetworkList(context.Background(), dockernetwork.ListOptions{ + resources, err := client.NetworkList(t.Context(), dockernetwork.ListOptions{ Filters: filters.NewArgs(filters.Arg("name", networkName)), }) require.NoError(t, err) @@ -65,7 +65,7 @@ func TestNew(t *testing.T) { // testNetworkAliases { func TestContainerAttachedToNewNetwork(t *testing.T) { - ctx := context.Background() + ctx := t.Context() newNetwork, err := network.New(ctx) require.NoError(t, err) @@ -108,7 +108,7 @@ func TestContainerAttachedToNewNetwork(t *testing.T) { // } func TestContainerIPs(t *testing.T) { - ctx := context.Background() + ctx := t.Context() newNetwork, err := network.New(ctx) require.NoError(t, err) @@ -133,7 +133,7 @@ func TestContainerWithReaperNetwork(t *testing.T) { t.Skip("Skip for Windows. See https://stackoverflow.com/questions/43784916/docker-for-windows-networking-container-with-multiple-network-interfaces") } - ctx := context.Background() + ctx := t.Context() networks := []string{} maxNetworksCount := 2 @@ -173,7 +173,7 @@ func TestContainerWithReaperNetwork(t *testing.T) { } func TestMultipleContainersInTheNewNetwork(t *testing.T) { - ctx := context.Background() + ctx := t.Context() net, err := network.New(ctx, network.WithDriver("bridge")) require.NoError(t, err) @@ -208,7 +208,7 @@ func TestMultipleContainersInTheNewNetwork(t *testing.T) { func TestNew_withOptions(t *testing.T) { // newNetworkWithOptions { - ctx := context.Background() + ctx := t.Context() // dockernetwork is the alias used for github.com/docker/docker/api/types/network ipamConfig := dockernetwork.IPAM{ @@ -253,7 +253,7 @@ func TestNew_withOptions(t *testing.T) { func TestWithNetwork(t *testing.T) { // first create the network to be reused - nw, err := network.New(context.Background(), network.WithLabels(map[string]string{"network-type": "unique"})) + nw, err := network.New(t.Context(), network.WithLabels(map[string]string{"network-type": "unique"})) require.NoError(t, err) testcontainers.CleanupNetwork(t, nw) @@ -276,10 +276,10 @@ func TestWithNetwork(t *testing.T) { } // verify that the network is created only once - client, err := testcontainers.NewDockerClientWithOpts(context.Background()) + client, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) - resources, err := client.NetworkList(context.Background(), dockernetwork.ListOptions{ + resources, err := client.NetworkList(t.Context(), dockernetwork.ListOptions{ Filters: filters.NewArgs(filters.Arg("name", networkName)), }) require.NoError(t, err) @@ -357,10 +357,10 @@ func TestWithSyntheticNetwork(t *testing.T) { require.Equal(t, map[string][]string{networkName: {"alias"}}, req.NetworkAliases) // verify that the network is created only once - client, err := testcontainers.NewDockerClientWithOpts(context.Background()) + client, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) - resources, err := client.NetworkList(context.Background(), dockernetwork.ListOptions{ + resources, err := client.NetworkList(t.Context(), dockernetwork.ListOptions{ Filters: filters.NewArgs(filters.Arg("name", networkName)), }) require.NoError(t, err) @@ -372,7 +372,7 @@ func TestWithNewNetwork(t *testing.T) { ContainerRequest: testcontainers.ContainerRequest{}, } - err := network.WithNewNetwork(context.Background(), []string{"alias"}, + err := network.WithNewNetwork(t.Context(), []string{"alias"}, network.WithAttachable(), network.WithInternal(), network.WithLabels(map[string]string{"this-is-a-test": "value"}), @@ -385,10 +385,10 @@ func TestWithNewNetwork(t *testing.T) { require.Len(t, req.NetworkAliases, 1) require.Equal(t, map[string][]string{networkName: {"alias"}}, req.NetworkAliases) - client, err := testcontainers.NewDockerClientWithOpts(context.Background()) + client, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) - resources, err := client.NetworkList(context.Background(), dockernetwork.ListOptions{ + resources, err := client.NetworkList(t.Context(), dockernetwork.ListOptions{ Filters: filters.NewArgs(filters.Arg("name", networkName)), }) require.NoError(t, err) @@ -396,7 +396,7 @@ func TestWithNewNetwork(t *testing.T) { newNetwork := resources[0] defer func() { - require.NoError(t, client.NetworkRemove(context.Background(), newNetwork.ID)) + require.NoError(t, client.NetworkRemove(t.Context(), newNetwork.ID)) }() expectedLabels := testcontainers.GenericLabels() @@ -413,7 +413,7 @@ func TestWithNewNetworkContextTimeout(t *testing.T) { ContainerRequest: testcontainers.ContainerRequest{}, } - ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 1*time.Millisecond) defer cancel() err := network.WithNewNetwork(ctx, []string{"alias"}, @@ -439,7 +439,7 @@ func TestContainerWithNetworkModeAndNetworkTogether(t *testing.T) { } // skipIfDockerDesktop { - ctx := context.Background() + ctx := t.Context() testcontainers.SkipIfDockerDesktop(t, ctx) // } diff --git a/options_test.go b/options_test.go index 149b4aa0c4..f782ebd1d7 100644 --- a/options_test.go +++ b/options_test.go @@ -80,7 +80,7 @@ func (lc *msgsLogConsumer) Accept(l testcontainers.Log) { func TestWithLogConsumers(t *testing.T) { lc := &msgsLogConsumer{} - ctx := context.Background() + ctx := t.Context() c, err := testcontainers.Run( ctx, "mysql:8.0.36", testcontainers.WithWaitStrategy(wait.ForLog("port: 3306 MySQL Community Server - GPL")), @@ -134,14 +134,14 @@ func TestWithStartupCommand(t *testing.T) { testExec := testcontainers.NewRawCommand([]string{"touch", ".testcontainers"}, exec.WithWorkingDir("/tmp")) c, err := testcontainers.Run( - context.Background(), "alpine", + t.Context(), "alpine", testcontainers.WithEntrypoint("tail", "-f", "/dev/null"), testcontainers.WithStartupCommand(testExec), ) testcontainers.CleanupContainer(t, c) require.NoError(t, err) - _, reader, err := c.Exec(context.Background(), []string{"ls", "/tmp/.testcontainers"}, exec.Multiplexed()) + _, reader, err := c.Exec(t.Context(), []string{"ls", "/tmp/.testcontainers"}, exec.Multiplexed()) require.NoError(t, err) content, err := io.ReadAll(reader) @@ -152,11 +152,11 @@ func TestWithStartupCommand(t *testing.T) { func TestWithAfterReadyCommand(t *testing.T) { testExec := testcontainers.NewRawCommand([]string{"touch", "/tmp/.testcontainers"}) - c, err := testcontainers.Run(context.Background(), "alpine", testcontainers.WithEntrypoint("tail", "-f", "/dev/null"), testcontainers.WithAfterReadyCommand(testExec)) + c, err := testcontainers.Run(t.Context(), "alpine", testcontainers.WithEntrypoint("tail", "-f", "/dev/null"), testcontainers.WithAfterReadyCommand(testExec)) testcontainers.CleanupContainer(t, c) require.NoError(t, err) - _, reader, err := c.Exec(context.Background(), []string{"ls", "/tmp/.testcontainers"}, exec.Multiplexed()) + _, reader, err := c.Exec(t.Context(), []string{"ls", "/tmp/.testcontainers"}, exec.Multiplexed()) require.NoError(t, err) content, err := io.ReadAll(reader) @@ -646,10 +646,10 @@ func TestWithDockerfile(t *testing.T) { } func TestWithImageMount(t *testing.T) { - cli, err := testcontainers.NewDockerClientWithOpts(context.Background()) + cli, err := testcontainers.NewDockerClientWithOpts(t.Context()) require.NoError(t, err) - info, err := cli.Info(context.Background()) + info, err := cli.Info(t.Context()) require.NoError(t, err) // skip if the major version of the server is not v28 or greater diff --git a/parallel_test.go b/parallel_test.go index 2d78b88184..fa0a862e77 100644 --- a/parallel_test.go +++ b/parallel_test.go @@ -1,7 +1,6 @@ package testcontainers import ( - "context" "fmt" "testing" "time" @@ -97,7 +96,7 @@ func TestParallelContainers(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - res, err := ParallelContainers(context.Background(), tc.reqs, ParallelContainersOptions{}) + res, err := ParallelContainers(t.Context(), tc.reqs, ParallelContainersOptions{}) for _, c := range res { CleanupContainer(t, c) } @@ -148,7 +147,7 @@ func TestParallelContainersWithReuse(t *testing.T) { req, } - ctx := context.Background() + ctx := t.Context() res, err := ParallelContainers(ctx, parallelRequest, ParallelContainersOptions{}) for _, c := range res { diff --git a/port_forwarding_test.go b/port_forwarding_test.go index cd101cf0fb..a206ae63db 100644 --- a/port_forwarding_test.go +++ b/port_forwarding_test.go @@ -69,7 +69,7 @@ func TestExposeHostPorts(t *testing.T) { func testExposeHostPorts(t *testing.T, hostPorts []int, hasNetwork, hasHostAccess bool) { t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + ctx, cancel := context.WithTimeout(t.Context(), time.Second*10) defer cancel() var hostAccessPorts []int @@ -111,7 +111,7 @@ func testExposeHostPorts(t *testing.T, hostPorts []int, hasNetwork, hasHostAcces // [testcontainers.HostInternal] address. func httpRequest(t *testing.T, c testcontainers.Container, port int) (int, string) { t.Helper() - ctx, cancel := context.WithTimeout(context.Background(), time.Second) + ctx, cancel := context.WithTimeout(t.Context(), time.Second) defer cancel() // wgetHostInternal { diff --git a/provider_test.go b/provider_test.go index 94206e46bf..9203322b45 100644 --- a/provider_test.go +++ b/provider_test.go @@ -1,7 +1,6 @@ package testcontainers import ( - "context" "testing" "github.com/stretchr/testify/require" @@ -10,7 +9,7 @@ import ( ) func TestProviderTypeGetProviderAutodetect(t *testing.T) { - dockerHost := core.MustExtractDockerHost(context.Background()) + dockerHost := core.MustExtractDockerHost(t.Context()) const podmanSocket = "unix://$XDG_RUNTIME_DIR/podman/podman.sock" tests := []struct { diff --git a/reaper_test.go b/reaper_test.go index 1eea122f0e..eaefce1f64 100644 --- a/reaper_test.go +++ b/reaper_test.go @@ -67,13 +67,13 @@ func (m *mockReaperProvider) Config() TestcontainersConfig { } // expectedReaperRequest creates the expected reaper container request with the given customizations. -func expectedReaperRequest(customize ...func(*ContainerRequest)) ContainerRequest { +func expectedReaperRequest(ctx context.Context, customize ...func(*ContainerRequest)) ContainerRequest { req := ContainerRequest{ Image: config.ReaperDefaultImage, ExposedPorts: []string{"8080/tcp"}, Labels: core.DefaultLabels(testSessionID), HostConfigModifier: func(hostConfig *container.HostConfig) { - hostConfig.Binds = []string{core.MustExtractDockerSocket(context.Background()) + ":/var/run/docker.sock"} + hostConfig.Binds = []string{core.MustExtractDockerSocket(ctx) + ":/var/run/docker.sock"} hostConfig.Privileged = true }, WaitingFor: wait.ForListeningPort(nat.Port("8080/tcp")), @@ -105,7 +105,7 @@ func reaperDisable(t *testing.T, disabled bool) { func testContainerStart(t *testing.T) { t.Helper() - ctx := context.Background() + ctx := t.Context() ctr, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort)) CleanupContainer(t, ctr) @@ -116,7 +116,7 @@ func testContainerStart(t *testing.T) { func testReaperRunning(t *testing.T) { t.Helper() - ctx := context.Background() + ctx := t.Context() sessionID := core.SessionID() reaperContainer, err := spawner.lookupContainer(ctx, sessionID) require.NoError(t, err) @@ -160,7 +160,7 @@ func TestContainer(t *testing.T) { func testContainerStop(t *testing.T) { t.Helper() - ctx := context.Background() + ctx := t.Context() nginxA, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort)) CleanupContainer(t, nginxA) @@ -183,7 +183,7 @@ func testContainerStop(t *testing.T) { // testContainerTerminate tests terminating a container. func testContainerTerminate(t *testing.T) { t.Helper() - ctx := context.Background() + ctx := t.Context() nginxA, err := Run(ctx, nginxAlpineImage, WithExposedPorts(nginxDefaultPort)) CleanupContainer(t, nginxA) @@ -203,7 +203,7 @@ func testContainerTerminate(t *testing.T) { func Test_NewReaper(t *testing.T) { reaperDisable(t, false) - ctx := context.Background() + ctx := t.Context() t.Run("non-privileged", func(t *testing.T) { testNewReaper(ctx, t, @@ -211,7 +211,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: time.Minute, RyukReconnectionTimeout: 10 * time.Second, }, - expectedReaperRequest(), + expectedReaperRequest(ctx), false, ) }) @@ -223,7 +223,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: time.Minute, RyukReconnectionTimeout: 10 * time.Second, }, - expectedReaperRequest(), + expectedReaperRequest(ctx), true, ) }) @@ -235,7 +235,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: 2 * time.Minute, RyukReconnectionTimeout: 20 * time.Second, }, - expectedReaperRequest(func(req *ContainerRequest) { + expectedReaperRequest(ctx, func(req *ContainerRequest) { req.Env = map[string]string{ "RYUK_CONNECTION_TIMEOUT": "2m0s", "RYUK_RECONNECTION_TIMEOUT": "20s", @@ -251,7 +251,7 @@ func Test_NewReaper(t *testing.T) { RyukPrivileged: true, RyukVerbose: true, }, - expectedReaperRequest(func(req *ContainerRequest) { + expectedReaperRequest(ctx, func(req *ContainerRequest) { req.Env = map[string]string{ "RYUK_VERBOSE": "true", } @@ -266,7 +266,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: time.Minute, RyukReconnectionTimeout: 10 * time.Second, }, - expectedReaperRequest(func(req *ContainerRequest) { + expectedReaperRequest(ctx, func(req *ContainerRequest) { req.HostConfigModifier = func(hostConfig *container.HostConfig) { hostConfig.Binds = []string{core.MustExtractDockerSocket(ctx) + ":/var/run/docker.sock"} } @@ -283,7 +283,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: time.Minute, RyukReconnectionTimeout: 10 * time.Second, }, - expectedReaperRequest(func(req *ContainerRequest) { + expectedReaperRequest(ctx, func(req *ContainerRequest) { req.Image = config.ReaperDefaultImage req.HostConfigModifier = func(hc *container.HostConfig) { hc.Privileged = true @@ -304,7 +304,7 @@ func Test_NewReaper(t *testing.T) { RyukConnectionTimeout: time.Minute, RyukReconnectionTimeout: 10 * time.Second, }, - expectedReaperRequest(func(req *ContainerRequest) { + expectedReaperRequest(ctx, func(req *ContainerRequest) { req.Image = config.ReaperDefaultImage req.HostConfigModifier = func(hc *container.HostConfig) { hc.Privileged = true @@ -350,7 +350,7 @@ func Test_ReaperReusedIfHealthy(t *testing.T) { SkipIfProviderIsNotHealthy(t) - ctx := context.Background() + ctx := t.Context() // As other integration tests run with the (shared) Reaper as well, re-use the instance to not interrupt other tests if spawner.instance != nil { t.Cleanup(func() { @@ -389,7 +389,7 @@ func Test_RecreateReaperIfTerminated(t *testing.T) { provider, err := ProviderDocker.GetProvider() require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() reaper, err := spawner.reaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider) cleanupReaper(t, reaper, spawner) require.NoError(t, err, "creating the Reaper should not error") @@ -446,7 +446,7 @@ func TestReaper_reuseItFromOtherTestProgramUsingDocker(t *testing.T) { SkipIfProviderIsNotHealthy(t) - ctx := context.Background() + ctx := t.Context() // As other integration tests run with the (shared) Reaper as well, // re-use the instance to not interrupt other tests. if spawner.instance != nil { @@ -494,7 +494,7 @@ func TestReaper_ReuseRunning(t *testing.T) { const concurrency = 64 - timeout, cancel := context.WithTimeout(context.Background(), time.Minute) + timeout, cancel := context.WithTimeout(t.Context(), time.Minute) defer cancel() sessionID := SessionID() diff --git a/reuse_test.go b/reuse_test.go index d86acefb97..ed6cd6bdd5 100644 --- a/reuse_test.go +++ b/reuse_test.go @@ -1,7 +1,6 @@ package testcontainers_test import ( - "context" "errors" "testing" @@ -19,17 +18,17 @@ func TestGenericContainer_stop_start_withReuse(t *testing.T) { testcontainers.WithReuseByName(containerName), } - ctr, err := testcontainers.Run(context.Background(), nginxAlpineImage, opts...) + ctr, err := testcontainers.Run(t.Context(), nginxAlpineImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) require.NotNil(t, ctr) - err = ctr.Stop(context.Background(), nil) + err = ctr.Stop(t.Context(), nil) require.NoError(t, err) // Run another container with same container name: // The checks for the exposed ports must not fail when restarting the container. - ctr1, err := testcontainers.Run(context.Background(), nginxAlpineImage, opts...) + ctr1, err := testcontainers.Run(t.Context(), nginxAlpineImage, opts...) testcontainers.CleanupContainer(t, ctr1) require.NoError(t, err) require.NotNil(t, ctr1) @@ -43,21 +42,21 @@ func TestGenericContainer_pause_start_withReuse(t *testing.T) { testcontainers.WithReuseByName(containerName), } - ctr, err := testcontainers.Run(context.Background(), nginxAlpineImage, opts...) + ctr, err := testcontainers.Run(t.Context(), nginxAlpineImage, opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) require.NotNil(t, ctr) // Pause the container is not supported by our API, but we can do it manually // by using the Docker client. - cli, err := core.NewClient(context.Background()) + cli, err := core.NewClient(t.Context()) require.NoError(t, err) - err = cli.ContainerPause(context.Background(), ctr.GetContainerID()) + err = cli.ContainerPause(t.Context(), ctr.GetContainerID()) require.NoError(t, err) // Because the container is paused, it should not be possible to start it again. - ctr1, err := testcontainers.Run(context.Background(), nginxAlpineImage, opts...) + ctr1, err := testcontainers.Run(t.Context(), nginxAlpineImage, opts...) testcontainers.CleanupContainer(t, ctr1) require.ErrorIs(t, err, errors.ErrUnsupported) } diff --git a/testing.go b/testing.go index 704af99c32..ecae0161ee 100644 --- a/testing.go +++ b/testing.go @@ -27,7 +27,7 @@ func SkipIfProviderIsNotHealthy(t *testing.T) { } }() - ctx := context.Background() + ctx := t.Context() provider, err := ProviderDocker.GetProvider() if err != nil { t.Skipf("Docker is not running. Testcontainers can't perform is work without it: %s", err) @@ -105,7 +105,7 @@ func CleanupNetwork(tb testing.TB, network Network) { tb.Cleanup(func() { if !isNil(network) { - noErrorOrIgnored(tb, network.Remove(context.Background())) + noErrorOrIgnored(tb, network.Remove(tb.Context())) } }) } diff --git a/wait/all_test.go b/wait/all_test.go index 4a8d019f24..df05a0524a 100644 --- a/wait/all_test.go +++ b/wait/all_test.go @@ -27,7 +27,7 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { name: "returns error when no WaitStrategies are passed", strategy: ForAll(), args: args{ - ctx: context.Background(), + ctx: t.Context(), target: NopStrategyTarget{}, }, wantErr: true, @@ -42,7 +42,7 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { ), ), args: args{ - ctx: context.Background(), + ctx: t.Context(), target: NopStrategyTarget{}, }, wantErr: true, @@ -61,7 +61,7 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { ForLog("docker"), ).WithDeadline(1 * time.Second), args: args{ - ctx: context.Background(), + ctx: t.Context(), target: NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }, @@ -82,7 +82,7 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { ForLog("docker"), ).WithStartupTimeoutDefault(1 * time.Second), args: args{ - ctx: context.Background(), + ctx: t.Context(), target: NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }, @@ -103,7 +103,7 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { ForLog("docker"), ).WithStartupTimeoutDefault(1 * time.Second), args: args{ - ctx: context.Background(), + ctx: t.Context(), target: NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }, @@ -128,13 +128,13 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { func TestMultiStrategy_handleNils(t *testing.T) { t.Run("nil-strategy", func(t *testing.T) { strategy := ForAll(nil) - err := strategy.WaitUntilReady(context.Background(), NopStrategyTarget{}) + err := strategy.WaitUntilReady(t.Context(), NopStrategyTarget{}) require.NoError(t, err) }) t.Run("nil-strategy-in-the-middle", func(t *testing.T) { strategy := ForAll(nil, ForLog("docker")) - err := strategy.WaitUntilReady(context.Background(), NopStrategyTarget{ + err := strategy.WaitUntilReady(t.Context(), NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }) require.NoError(t, err) @@ -142,7 +142,7 @@ func TestMultiStrategy_handleNils(t *testing.T) { t.Run("nil-strategy-last", func(t *testing.T) { strategy := ForAll(ForLog("docker"), nil) - err := strategy.WaitUntilReady(context.Background(), NopStrategyTarget{ + err := strategy.WaitUntilReady(t.Context(), NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }) require.NoError(t, err) @@ -152,7 +152,7 @@ func TestMultiStrategy_handleNils(t *testing.T) { var nilStrategy Strategy strategy := ForAll(ForLog("docker"), nilStrategy) - err := strategy.WaitUntilReady(context.Background(), NopStrategyTarget{ + err := strategy.WaitUntilReady(t.Context(), NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }) require.NoError(t, err) @@ -166,7 +166,7 @@ func TestMultiStrategy_handleNils(t *testing.T) { var strategyInterface Strategy = nilPointerStrategy strategy := ForAll(ForLog("docker"), strategyInterface) - err := strategy.WaitUntilReady(context.Background(), NopStrategyTarget{ + err := strategy.WaitUntilReady(t.Context(), NopStrategyTarget{ ReaderCloser: io.NopCloser(bytes.NewReader([]byte("docker"))), }) require.NoError(t, err) diff --git a/wait/exec_test.go b/wait/exec_test.go index 3946002895..81a281b304 100644 --- a/wait/exec_test.go +++ b/wait/exec_test.go @@ -108,14 +108,14 @@ func TestExecStrategyWaitUntilReady(t *testing.T) { target := mockExecTarget{} wg := wait.NewExecStrategy([]string{"true"}). WithStartupTimeout(30 * time.Second) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } func TestExecStrategyWaitUntilReadyForExec(t *testing.T) { target := mockExecTarget{} wg := wait.ForExec([]string{"true"}) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -126,12 +126,12 @@ func TestExecStrategyWaitUntilReady_MultipleChecks(t *testing.T) { } wg := wait.NewExecStrategy([]string{"true"}). WithPollInterval(500 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } func TestExecStrategyWaitUntilReady_DeadlineExceeded(t *testing.T) { - ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) defer cancel() target := mockExecTarget{ @@ -149,7 +149,7 @@ func TestExecStrategyWaitUntilReady_CustomExitCode(t *testing.T) { wg := wait.NewExecStrategy([]string{"true"}).WithExitCodeMatcher(func(exitCode int) bool { return exitCode == 10 }) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -160,19 +160,19 @@ func TestExecStrategyWaitUntilReady_withExitCode(t *testing.T) { wg := wait.NewExecStrategy([]string{"true"}).WithExitCode(10) // Default is 60. Let's shorten that wg.WithStartupTimeout(time.Second * 2) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) // Ensure we aren't spuriously returning on any code wg = wait.NewExecStrategy([]string{"true"}).WithExitCode(0) wg.WithStartupTimeout(time.Second * 2) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.Errorf(t, err, "Expected strategy to timeout out") } func TestExecStrategyWaitUntilReady_CustomResponseMatcher(t *testing.T) { // waitForExecExitCodeResponse { - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run( ctx, "nginx:latest", testcontainers.WithWaitStrategy(wait.ForExec([]string{"echo", "hello world!"}). diff --git a/wait/exit_test.go b/wait/exit_test.go index 409d4e1d48..0ef0acde4c 100644 --- a/wait/exit_test.go +++ b/wait/exit_test.go @@ -56,6 +56,6 @@ func TestWaitForExit(t *testing.T) { isRunning: false, } wg := NewExitStrategy().WithExitTimeout(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } diff --git a/wait/file_test.go b/wait/file_test.go index 488ebc2022..c546c04fab 100644 --- a/wait/file_test.go +++ b/wait/file_test.go @@ -40,7 +40,7 @@ func testForFile() *wait.FileStrategy { func TestForFile(t *testing.T) { errNotFound := errdefs.ErrNotFound.WithMessage("file not found") - ctx := context.Background() + ctx := t.Context() t.Run("not-found", func(t *testing.T) { target := newRunningTarget() @@ -78,7 +78,7 @@ func TestForFile(t *testing.T) { func TestFileStrategyWaitUntilReady_WithMatcher(t *testing.T) { // waitForFileWithMatcher { var out bytes.Buffer - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run( ctx, "nginx:latest", testcontainers.WithWaitStrategy(wait.ForFile("/etc/nginx/nginx.conf"). diff --git a/wait/health_test.go b/wait/health_test.go index 1850e09250..6f42fb07ae 100644 --- a/wait/health_test.go +++ b/wait/health_test.go @@ -76,7 +76,7 @@ func TestWaitForHealthTimesOutForUnhealthy(t *testing.T) { }, } wg := NewHealthStrategy().WithStartupTimeout(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) require.ErrorIs(t, err, context.DeadlineExceeded) @@ -91,7 +91,7 @@ func TestWaitForHealthSucceeds(t *testing.T) { }, } wg := NewHealthStrategy().WithStartupTimeout(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -116,7 +116,7 @@ func TestWaitForHealthWithNil(t *testing.T) { target.setState(&container.Health{Status: types.Healthy}) }(target) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -132,7 +132,7 @@ func TestWaitFailsForNilHealth(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) require.ErrorIs(t, err, context.DeadlineExceeded) } @@ -147,7 +147,7 @@ func TestWaitForHealthFailsDueToOOMKilledContainer(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) require.EqualError(t, err, "container crashed with out-of-memory (OOMKilled)") } @@ -163,7 +163,7 @@ func TestWaitForHealthFailsDueToExitedContainer(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) require.EqualError(t, err, "container exited with code 1") } @@ -178,7 +178,7 @@ func TestWaitForHealthFailsDueToUnexpectedContainerStatus(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) require.EqualError(t, err, "unexpected container status \"dead\"") } diff --git a/wait/host_port_test.go b/wait/host_port_test.go index cd89d21918..fe4ea93fb9 100644 --- a/wait/host_port_test.go +++ b/wait/host_port_test.go @@ -57,7 +57,7 @@ func TestWaitForListeningPortSucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -102,7 +102,7 @@ func TestWaitForListeningPortInternallySucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -139,7 +139,7 @@ func TestWaitForMappedPortSucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -210,7 +210,7 @@ func TestWaitForExposedPortSkipChecksSucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -239,7 +239,7 @@ func TestHostPortStrategyFailsWhileGettingPortDueToOOMKilledContainer(t *testing WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container crashed with out-of-memory (OOMKilled)") } } @@ -270,7 +270,7 @@ func TestHostPortStrategyFailsWhileGettingPortDueToExitedContainer(t *testing.T) WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container exited with code 1") } } @@ -300,7 +300,7 @@ func TestHostPortStrategyFailsWhileGettingPortDueToUnexpectedContainerStatus(t * WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "unexpected container status \"dead\"") } } @@ -325,7 +325,7 @@ func TestHostPortStrategyFailsWhileExternalCheckingDueToOOMKilledContainer(t *te WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container crashed with out-of-memory (OOMKilled)") } } @@ -351,7 +351,7 @@ func TestHostPortStrategyFailsWhileExternalCheckingDueToExitedContainer(t *testi WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container exited with code 1") } } @@ -376,7 +376,7 @@ func TestHostPortStrategyFailsWhileExternalCheckingDueToUnexpectedContainerStatu WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "unexpected container status \"dead\"") } } @@ -416,7 +416,7 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToOOMKilledContainer(t *te WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container crashed with out-of-memory (OOMKilled)") } } @@ -457,7 +457,7 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToExitedContainer(t *testi WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "container exited with code 1") } } @@ -497,7 +497,7 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToUnexpectedContainerStatu WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.ErrorContains(t, err, "unexpected container status \"dead\"") } } @@ -559,7 +559,7 @@ func TestHostPortStrategySucceedsGivenShellIsNotInstalled(t *testing.T) { tclog.SetDefault(oldLogger) }) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) require.Contains(t, buf.String(), "Shell not executable in container, only external port validated") @@ -622,7 +622,7 @@ func TestHostPortStrategySucceedsGivenShellIsNotFound(t *testing.T) { tclog.SetDefault(oldLogger) }) - err = wg.WaitUntilReady(context.Background(), target) + err = wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) require.Contains(t, buf.String(), "Shell not found in container") diff --git a/wait/http_test.go b/wait/http_test.go index a8aeb3d86d..55ac9bdb25 100644 --- a/wait/http_test.go +++ b/wait/http_test.go @@ -227,14 +227,14 @@ func TestHTTPStrategyWaitUntilReady(t *testing.T) { ), } - ctr, err := testcontainers.Run(context.Background(), "", opts...) + ctr, err := testcontainers.Run(t.Context(), "", opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) - host, err := ctr.Host(context.Background()) + host, err := ctr.Host(t.Context()) require.NoError(t, err) - port, err := ctr.MappedPort(context.Background(), "6443/tcp") + port, err := ctr.MappedPort(t.Context(), "6443/tcp") require.NoError(t, err) client := http.Client{ @@ -278,14 +278,14 @@ func TestHTTPStrategyWaitUntilReadyWithQueryString(t *testing.T) { })), } - ctr, err := testcontainers.Run(context.Background(), "", opts...) + ctr, err := testcontainers.Run(t.Context(), "", opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) - host, err := ctr.Host(context.Background()) + host, err := ctr.Host(t.Context()) require.NoError(t, err) - port, err := ctr.MappedPort(context.Background(), "6443/tcp") + port, err := ctr.MappedPort(t.Context(), "6443/tcp") require.NoError(t, err) client := http.Client{ @@ -338,7 +338,7 @@ func TestHTTPStrategyWaitUntilReadyNoBasicAuth(t *testing.T) { } // } - ctx := context.Background() + ctx := t.Context() ctr, err := testcontainers.Run(ctx, "", opts...) testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) @@ -412,7 +412,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToOOMKilledContainer(t *testing.T) WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container crashed with out-of-memory (OOMKilled)" require.EqualError(t, err, expected) } @@ -458,7 +458,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToExitedContainer(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container exited with code 1" require.EqualError(t, err, expected) } @@ -503,7 +503,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToUnexpectedContainerStatus(t *test WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "unexpected container status \"dead\"" require.EqualError(t, err, expected) } @@ -543,7 +543,7 @@ func TestHTTPStrategyFailsWhileRequestSendingDueToOOMKilledContainer(t *testing. WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container crashed with out-of-memory (OOMKilled)" require.EqualError(t, err, expected) } @@ -584,7 +584,7 @@ func TestHttpStrategyFailsWhileRequestSendingDueToExitedContainer(t *testing.T) WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container exited with code 1" require.EqualError(t, err, expected) } @@ -624,7 +624,7 @@ func TestHttpStrategyFailsWhileRequestSendingDueToUnexpectedContainerStatus(t *t WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "unexpected container status \"dead\"" require.EqualError(t, err, expected) } @@ -663,7 +663,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToNoExposedPorts(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "no exposed tcp ports or mapped ports - cannot wait for status" require.EqualError(t, err, expected) } @@ -709,7 +709,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToOnlyUDPPorts(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "no exposed tcp ports or mapped ports - cannot wait for status" require.EqualError(t, err, expected) } @@ -750,7 +750,7 @@ func TestHttpStrategyFailsWhileGettingPortDueToExposedPortNoBindings(t *testing. WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "no exposed tcp ports or mapped ports - cannot wait for status" require.EqualError(t, err, expected) } diff --git a/wait/log_test.go b/wait/log_test.go index 5cff60b35b..e8302a2ded 100644 --- a/wait/log_test.go +++ b/wait/log_test.go @@ -33,7 +33,7 @@ func TestWaitForLog(t *testing.T) { ReaderCloser: readCloser("docker"), } wg := wait.NewLogStrategy("docker").WithStartupTimeout(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) @@ -44,7 +44,7 @@ func TestWaitForLog(t *testing.T) { // get all words that start with "ip", end with "m" and has a whitespace before the "ip" wg := wait.NewLogStrategy(`\sip[\w]+m`).WithStartupTimeout(100 * time.Millisecond).AsRegexp() - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) @@ -59,7 +59,7 @@ func TestWaitForLog(t *testing.T) { } return nil }) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) @@ -74,7 +74,7 @@ func TestWaitForLog(t *testing.T) { } return nil }) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) var permanentError *wait.PermanentError require.ErrorAs(t, err, &permanentError) @@ -101,7 +101,7 @@ func TestWaitForLog(t *testing.T) { return wait.NewPermanentError(fmt.Errorf("`%s` matched %d times, expected %d (permanent)", pattern, len(submatches), 3)) } }) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) } @@ -114,7 +114,7 @@ func TestWaitWithExactNumberOfOccurrences(t *testing.T) { wg := wait.NewLogStrategy("docker"). WithStartupTimeout(100 * time.Millisecond). WithOccurrence(2) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) @@ -127,7 +127,7 @@ func TestWaitWithExactNumberOfOccurrences(t *testing.T) { // there are three occurrences of this pattern in the string: // one "ipsum mauris" and two "ipsum dolor sit am" wg := wait.NewLogStrategy(`ip(.*)m`).WithStartupTimeout(100 * time.Millisecond).AsRegexp().WithOccurrence(3) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) }) } @@ -140,7 +140,7 @@ func TestWaitWithExactNumberOfOccurrencesButItWillNeverHappen(t *testing.T) { wg := wait.NewLogStrategy("containerd"). WithStartupTimeout(logTimeout). WithOccurrence(2) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) }) @@ -152,7 +152,7 @@ func TestWaitWithExactNumberOfOccurrencesButItWillNeverHappen(t *testing.T) { // get texts from "ip" to the next "m". // there are only three occurrences matching wg := wait.NewLogStrategy(`do(.*)ck.+`).WithStartupTimeout(100 * time.Millisecond).AsRegexp().WithOccurrence(4) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) }) } @@ -165,7 +165,7 @@ func TestWaitShouldFailWithExactNumberOfOccurrences(t *testing.T) { wg := wait.NewLogStrategy("docker"). WithStartupTimeout(logTimeout). WithOccurrence(2) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) }) @@ -177,7 +177,7 @@ func TestWaitShouldFailWithExactNumberOfOccurrences(t *testing.T) { // get "Maecenas". // there are only one occurrence matching wg := wait.NewLogStrategy(`^Mae[\w]?enas\s`).WithStartupTimeout(100 * time.Millisecond).AsRegexp().WithOccurrence(2) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.Error(t, err) }) } @@ -197,7 +197,7 @@ func TestWaitForLogFailsDueToOOMKilledContainer(t *testing.T) { t.Run("string", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container crashed with out-of-memory (OOMKilled)" require.EqualError(t, err, expected) }) @@ -205,7 +205,7 @@ func TestWaitForLogFailsDueToOOMKilledContainer(t *testing.T) { t.Run("regexp", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout).AsRegexp() - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container crashed with out-of-memory (OOMKilled)" require.EqualError(t, err, expected) }) @@ -227,7 +227,7 @@ func TestWaitForLogFailsDueToExitedContainer(t *testing.T) { t.Run("string", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container exited with code 1" require.EqualError(t, err, expected) }) @@ -235,7 +235,7 @@ func TestWaitForLogFailsDueToExitedContainer(t *testing.T) { t.Run("regexp", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout).AsRegexp() - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "container exited with code 1" require.EqualError(t, err, expected) }) @@ -256,7 +256,7 @@ func TestWaitForLogFailsDueToUnexpectedContainerStatus(t *testing.T) { t.Run("string", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "unexpected container status \"dead\"" require.EqualError(t, err, expected) }) @@ -264,7 +264,7 @@ func TestWaitForLogFailsDueToUnexpectedContainerStatus(t *testing.T) { t.Run("regexp", func(t *testing.T) { wg := wait.ForLog("docker").WithStartupTimeout(logTimeout).AsRegexp() - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) expected := "unexpected container status \"dead\"" require.EqualError(t, err, expected) }) diff --git a/wait/sql_test.go b/wait/sql_test.go index 1c0f641b2b..67c14113e9 100644 --- a/wait/sql_test.go +++ b/wait/sql_test.go @@ -99,7 +99,7 @@ func TestWaitForSQLSucceeds(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.NoError(t, err) } @@ -128,7 +128,7 @@ func TestWaitForSQLFailsWhileGettingPortDueToOOMKilledContainer(t *testing.T) { WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "container crashed with out-of-memory (OOMKilled)") } } @@ -159,7 +159,7 @@ func TestWaitForSQLFailsWhileGettingPortDueToExitedContainer(t *testing.T) { WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "container exited with code 1") } } @@ -189,7 +189,7 @@ func TestWaitForSQLFailsWhileGettingPortDueToUnexpectedContainerStatus(t *testin WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "unexpected container status \"dead\"") } } @@ -214,7 +214,7 @@ func TestWaitForSQLFailsWhileQueryExecutingDueToOOMKilledContainer(t *testing.T) WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "container crashed with out-of-memory (OOMKilled)") } } @@ -240,7 +240,7 @@ func TestWaitForSQLFailsWhileQueryExecutingDueToExitedContainer(t *testing.T) { WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "container exited with code 1") } } @@ -265,7 +265,7 @@ func TestWaitForSQLFailsWhileQueryExecutingDueToUnexpectedContainerStatus(t *tes WithPollInterval(100 * time.Millisecond) { - err := wg.WaitUntilReady(context.Background(), target) + err := wg.WaitUntilReady(t.Context(), target) require.EqualError(t, err, "unexpected container status \"dead\"") } } diff --git a/wait/tls_test.go b/wait/tls_test.go index 9a766bd30b..8e1c5930a4 100644 --- a/wait/tls_test.go +++ b/wait/tls_test.go @@ -46,7 +46,7 @@ func testForTLSCert() *wait.TLSStrategy { func TestForCert(t *testing.T) { errNotFound := errdefs.ErrNotFound.WithMessage("file not found") - ctx := context.Background() + ctx := t.Context() t.Run("ca-not-found", func(t *testing.T) { target := newRunningTarget()