Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test: use T.TempDir to create temporary test directory #3560

Merged
merged 2 commits into from
Feb 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions agent/acs/handler/attach_eni_handler_common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ func testENIAckTimeout(t *testing.T, attachmentType string) {
defer ctrl.Finish()

taskEngineState := dockerstate.NewTaskEngineState()
dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

expiresAt := time.Now().Add(time.Millisecond * waitTimeoutMillis)
err := addENIAttachmentToState(attachmentType, attachmentArn, taskArn, randomMAC, expiresAt, taskEngineState, dataClient)
Expand Down Expand Up @@ -110,8 +109,7 @@ func testHandleENIAttachment(t *testing.T, attachmentType, taskArn string) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

taskEngineState := dockerstate.NewTaskEngineState()
expiresAt := time.Now().Add(time.Millisecond * waitTimeoutMillis)
Expand Down
22 changes: 9 additions & 13 deletions agent/acs/handler/payload_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"reflect"
"sync"
"testing"
Expand Down Expand Up @@ -150,8 +148,7 @@ func TestHandlePayloadMessageSaveData(t *testing.T) {
}).Times(1)
tester.mockTaskEngine.EXPECT().AddTask(gomock.Any()).Times(1)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)
tester.payloadHandler.dataClient = dataClient

go tester.payloadHandler.start()
Expand Down Expand Up @@ -190,8 +187,7 @@ func TestHandlePayloadMessageSaveDataError(t *testing.T) {
tester := setup(t)
defer tester.ctrl.Finish()

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

// Save added task in the addedTask variable
var addedTask *apitask.Task
Expand Down Expand Up @@ -225,17 +221,17 @@ func TestHandlePayloadMessageSaveDataError(t *testing.T) {
assert.Equal(t, expectedTask, addedTask, "added task is not expected")
}

func newTestDataClient(t *testing.T) (data.Client, func()) {
testDir, err := ioutil.TempDir("", "agent_acs_handler_unit_test")
require.NoError(t, err)
func newTestDataClient(t *testing.T) data.Client {
testDir := t.TempDir()

testClient, err := data.NewWithSetup(testDir)
require.NoError(t, err)

cleanup := func() {
t.Cleanup(func() {
require.NoError(t, testClient.Close())
require.NoError(t, os.RemoveAll(testDir))
}
return testClient, cleanup
})

return testClient
}

// TestHandlePayloadMessageAckedWhenTaskAdded tests if the handler generates an ack
Expand Down
15 changes: 5 additions & 10 deletions agent/acs/handler/task_manifest_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,7 @@ func TestManifestHandlerKillAllTasks(t *testing.T) {
ctx := context.TODO()
mockWSClient := mock_wsclient.NewMockClientServer(ctrl)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

newTaskManifest := newTaskManifestHandler(ctx, cluster, containerInstanceArn, mockWSClient,
dataClient, taskEngine, aws.Int64(11))
Expand Down Expand Up @@ -145,8 +144,7 @@ func TestManifestHandlerKillFewTasks(t *testing.T) {
ctx := context.TODO()
mockWSClient := mock_wsclient.NewMockClientServer(ctrl)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

newTaskManifest := newTaskManifestHandler(ctx, cluster, containerInstanceArn, mockWSClient,
dataClient, taskEngine, aws.Int64(11))
Expand Down Expand Up @@ -249,8 +247,7 @@ func TestManifestHandlerKillNoTasks(t *testing.T) {
ctx := context.TODO()
mockWSClient := mock_wsclient.NewMockClientServer(ctrl)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

newTaskManifest := newTaskManifestHandler(ctx, cluster, containerInstanceArn, mockWSClient,
dataClient, taskEngine, aws.Int64(11))
Expand Down Expand Up @@ -339,8 +336,7 @@ func TestManifestHandlerDifferentTaskLists(t *testing.T) {
ctx := context.TODO()
mockWSClient := mock_wsclient.NewMockClientServer(ctrl)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

newTaskManifest := newTaskManifestHandler(ctx, cluster, containerInstanceArn, mockWSClient,
dataClient, taskEngine, aws.Int64(11))
Expand Down Expand Up @@ -433,8 +429,7 @@ func TestManifestHandlerDifferentTaskLists(t *testing.T) {
}

func TestManifestHandlerSequenceNumbers(t *testing.T) {
dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

testcases := []struct {
name string
Expand Down
21 changes: 5 additions & 16 deletions agent/app/agent_capability_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import (
"context"
"errors"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"
Expand All @@ -42,10 +41,6 @@ import (
"github.com/stretchr/testify/require"
)

const (
testTempDirPrefix = "agent-capability-test-"
)

func init() {
mockPathExists(false)
}
Expand Down Expand Up @@ -1281,20 +1276,17 @@ func TestCapabilitiesNoServiceConnect(t *testing.T) {
}

func TestDefaultGetSubDirectories(t *testing.T) {
rootDir, err := ioutil.TempDir(os.TempDir(), testTempDirPrefix)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(rootDir)
rootDir := t.TempDir()

subDir, err := ioutil.TempDir(rootDir, "dir")
if err != nil {
t.Fatal(err)
}
_, err = ioutil.TempFile(rootDir, "file")
file, err := ioutil.TempFile(rootDir, "file")
if err != nil {
t.Fatal(err)
}
defer require.NoError(t, file.Close())
notExistingPath := filepath.Join(rootDir, "not-existing")

testCases := []struct {
Expand Down Expand Up @@ -1333,16 +1325,13 @@ func TestDefaultGetSubDirectories(t *testing.T) {
}

func TestDefaultPathExistsd(t *testing.T) {
rootDir, err := ioutil.TempDir(os.TempDir(), testTempDirPrefix)
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(rootDir)
rootDir := t.TempDir()

file, err := ioutil.TempFile(rootDir, "file")
if err != nil {
t.Fatal(err)
}
defer require.NoError(t, file.Close())
notExistingPath := filepath.Join(rootDir, "not-existing")
testCases := []struct {
name string
Expand Down
6 changes: 2 additions & 4 deletions agent/app/agent_compatibility_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@ func TestCompatibilityNotSetFail(t *testing.T) {
cfg.Checkpoint = config.BooleanDefaultFalse{Value: config.ExplicitlyEnabled}
cfg.TaskCPUMemLimit = config.BooleanDefaultTrue{Value: config.NotSet}

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)
populateBoltDB(dataClient, t)

// Put a bad task in previously saved state.
Expand Down Expand Up @@ -122,8 +121,7 @@ func TestCompatibilityExplicitlyEnabledFail(t *testing.T) {
cfg.Checkpoint = config.BooleanDefaultFalse{Value: config.ExplicitlyEnabled}
cfg.TaskCPUMemLimit = config.BooleanDefaultTrue{Value: config.ExplicitlyEnabled}

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)
populateBoltDB(dataClient, t)

// Put a bad task in previously saved state.
Expand Down
40 changes: 15 additions & 25 deletions agent/app/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ import (
"context"
"errors"
"fmt"
"io/ioutil"
"os"
"sort"
"sync"
"testing"
Expand Down Expand Up @@ -471,8 +469,7 @@ func testDoStartHappyPathWithConditions(t *testing.T, blackholed bool, warmPools
cfg.Cluster = clusterName
ctx, cancel := context.WithCancel(context.TODO())

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

// Cancel the context to cancel async routines
agent := &ecsAgent{
Expand Down Expand Up @@ -549,8 +546,7 @@ func TestNewTaskEngineRestoreFromCheckpointNoEC2InstanceIDToLoadHappyPath(t *tes
ec2MetadataClient.EXPECT().InstanceID().Return(expectedInstanceID, nil),
)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

ctx, cancel := context.WithCancel(context.TODO())
// Cancel the context to cancel async routines
Expand Down Expand Up @@ -613,8 +609,7 @@ func TestNewTaskEngineRestoreFromCheckpointPreviousEC2InstanceIDLoadedHappyPath(
ec2MetadataClient.EXPECT().InstanceID().Return(expectedInstanceID, nil),
)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

ctx, cancel := context.WithCancel(context.TODO())
// Cancel the context to cancel async routines
Expand Down Expand Up @@ -675,8 +670,7 @@ func TestNewTaskEngineRestoreFromCheckpointClusterIDMismatch(t *testing.T) {
ec2MetadataClient.EXPECT().InstanceID().Return(ec2InstanceID, nil),
)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

ctx, cancel := context.WithCancel(context.TODO())
// Cancel the context to cancel async routines
Expand Down Expand Up @@ -721,8 +715,7 @@ func TestNewTaskEngineRestoreFromCheckpointNewStateManagerError(t *testing.T) {
nil, errors.New("error")),
)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

ctx, cancel := context.WithCancel(context.TODO())
// Cancel the context to cancel async routines
Expand Down Expand Up @@ -768,8 +761,7 @@ func TestNewTaskEngineRestoreFromCheckpointStateLoadError(t *testing.T) {
stateManager.EXPECT().Load().Return(errors.New("error")),
)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

ctx, cancel := context.WithCancel(context.TODO())
// Cancel the context to cancel async routines
Expand Down Expand Up @@ -804,8 +796,8 @@ func TestNewTaskEngineRestoreFromCheckpoint(t *testing.T) {

ec2MetadataClient.EXPECT().InstanceID().Return(testEC2InstanceID, nil)

dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

// Populate boldtb with test data.
populateBoltDB(dataClient, t)

Expand Down Expand Up @@ -1628,8 +1620,7 @@ func TestSpotInstanceActionCheck_NoInstanceActionYet(t *testing.T) {
}

func TestSaveMetadata(t *testing.T) {
dataClient, cleanup := newTestDataClient(t)
defer cleanup()
dataClient := newTestDataClient(t)

agent := &ecsAgent{
dataClient: dataClient,
Expand All @@ -1646,17 +1637,16 @@ func getTestConfig() config.Config {
return cfg
}

func newTestDataClient(t *testing.T) (data.Client, func()) {
testDir, err := ioutil.TempDir("", "agent_app_unit_test")
require.NoError(t, err)
func newTestDataClient(t *testing.T) data.Client {
testDir := t.TempDir()

testClient, err := data.NewWithSetup(testDir)
require.NoError(t, err)

cleanup := func() {
t.Cleanup(func() {
require.NoError(t, testClient.Close())
require.NoError(t, os.RemoveAll(testDir))
}
return testClient, cleanup
})
return testClient
}

type targetLifecycleFuncDetail struct {
Expand Down
25 changes: 10 additions & 15 deletions agent/app/data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ package app

import (
"context"
"io/ioutil"
"os"
"strconv"
"testing"

Expand Down Expand Up @@ -89,8 +87,7 @@ func TestLoadDataNoPreviousState(t *testing.T) {
_, stateManagerFactory, _, execCmdMgr, serviceConnectManager := setup(t)
defer ctrl.Finish()

stateManager, dataClient, cleanup := newTestClient(t)
defer cleanup()
stateManager, dataClient := newTestClient(t)

cfg := getTestConfig()
cfg.Checkpoint = config.BooleanDefaultFalse{Value: config.ExplicitlyEnabled}
Expand Down Expand Up @@ -123,8 +120,8 @@ func TestLoadDataLoadFromBoltDB(t *testing.T) {
_, stateManagerFactory, _, execCmdMgr, serviceConnectManager := setup(t)
defer ctrl.Finish()

_, dataClient, cleanup := newTestClient(t)
defer cleanup()
_, dataClient := newTestClient(t)

// Populate boltdb with test data.
populateBoltDB(dataClient, t)

Expand Down Expand Up @@ -154,8 +151,8 @@ func TestLoadDataLoadFromStateFile(t *testing.T) {
_, stateManagerFactory, _, execCmdMgr, serviceConnectManager := setup(t)
defer ctrl.Finish()

stateManager, dataClient, cleanup := newTestClient(t)
defer cleanup()
stateManager, dataClient := newTestClient(t)

// Generate a state file with test data.
generateStateFile(stateManager, t)

Expand Down Expand Up @@ -215,20 +212,18 @@ func checkLoadedData(state dockerstate.TaskEngineState, s *savedData, t *testing
assert.Equal(t, testLatestSeqNumberTaskManifest, s.latestTaskManifestSeqNum)
}

func newTestClient(t *testing.T) (statemanager.StateManager, data.Client, func()) {
testDir, err := ioutil.TempDir("", "agent_app_unit_test")
require.NoError(t, err)
func newTestClient(t *testing.T) (statemanager.StateManager, data.Client) {
testDir := t.TempDir()

stateManager, err := statemanager.NewStateManager(&config.Config{DataDir: testDir})
require.NoError(t, err)

dataClient, err := data.NewWithSetup(testDir)

cleanup := func() {
t.Cleanup(func() {
require.NoError(t, dataClient.Close())
require.NoError(t, os.RemoveAll(testDir))
}
return stateManager, dataClient, cleanup
})
return stateManager, dataClient
}

func generateStateFile(stateManager statemanager.StateManager, t *testing.T) {
Expand Down
Loading