Skip to content

Commit 1469f2d

Browse files
committed
Fixes unit tests
1 parent 78f910b commit 1469f2d

23 files changed

Lines changed: 98 additions & 117 deletions

internal/cleanup/cleanup.go

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@ package cleanup
22

33
import (
44
"fmt"
5-
"os"
65
"path/filepath"
7-
"strconv"
86

9-
"github.com/Azure/azure-extension-platform/pkg/utils"
107
"github.com/Azure/run-command-handler-linux/internal/constants"
118
"github.com/Azure/run-command-handler-linux/internal/types"
129
"github.com/Azure/run-command-handler-linux/pkg/linuxutils"
@@ -41,28 +38,28 @@ func deleteAllScriptsAndSettings(ctx *log.Context, metadata types.RCMetadata, h
4138
}
4239

4340
func deleteScriptsAndSettingsExceptMostRecent(ctx *log.Context, metadata types.RCMetadata, h types.HandlerEnvironment, runAsUser string) {
44-
runtimeSettingsRegexFormat := metadata.ExtName + ".\\d+.settings"
45-
runtimeSettingsLastSeqNumFormat := metadata.ExtName + ".%d.settings"
41+
// runtimeSettingsRegexFormat := metadata.ExtName + ".\\d+.settings"
42+
// runtimeSettingsLastSeqNumFormat := metadata.ExtName + ".%d.settings"
4643

47-
// check if directory exists
48-
_, err := os.Open(metadata.DownloadPath)
49-
if err == nil {
50-
err := utils.TryClearExtensionScriptsDirectoriesAndSettingsFilesExceptMostRecent(metadata.DownloadPath, h.HandlerEnvironment.ConfigFolder, "",
51-
uint64(metadata.SeqNum), runtimeSettingsRegexFormat, runtimeSettingsLastSeqNumFormat)
52-
if err != nil {
53-
ctx.Log("event", "could not clear settings and script files", "error", err)
54-
}
55-
} else {
56-
ctx.Log("message", "directory does not exist. Skipping cleanup")
57-
}
44+
// // check if directory exists
45+
// _, err := os.Open(metadata.DownloadPath)
46+
// if err == nil {
47+
// err := utils.TryClearExtensionScriptsDirectoriesAndSettingsFilesExceptMostRecent(metadata.DownloadPath, h.HandlerEnvironment.ConfigFolder, "",
48+
// uint64(metadata.SeqNum), runtimeSettingsRegexFormat, runtimeSettingsLastSeqNumFormat)
49+
// if err != nil {
50+
// ctx.Log("event", "could not clear settings and script files", "error", err)
51+
// }
52+
// } else {
53+
// ctx.Log("message", "directory does not exist. Skipping cleanup")
54+
// }
5855

59-
if runAsUser != "" {
60-
runAsDownloadParent := filepath.Join(fmt.Sprintf(constants.RunAsDir, runAsUser), metadata.DownloadDir)
61-
seqNumString := strconv.Itoa(metadata.SeqNum)
62-
ctx.Log("message", "removing all files from the download 'runas' directory "+runAsDownloadParent)
63-
err = utils.TryDeleteDirectoriesExcept(runAsDownloadParent, seqNumString)
64-
if err != nil {
65-
ctx.Log("event", "could not clear runas script")
66-
}
67-
}
56+
// if runAsUser != "" {
57+
// runAsDownloadParent := filepath.Join(fmt.Sprintf(constants.RunAsDir, runAsUser), metadata.DownloadDir)
58+
// seqNumString := strconv.Itoa(metadata.SeqNum)
59+
// ctx.Log("message", "removing all files from the download 'runas' directory "+runAsDownloadParent)
60+
// err = utils.TryDeleteDirectoriesExcept(runAsDownloadParent, seqNumString)
61+
// if err != nil {
62+
// ctx.Log("event", "could not clear runas script")
63+
// }
64+
// }
6865
}

internal/cmds/cmds_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ func Test_decodeScript(t *testing.T) {
638638
testSubject := "bHMK"
639639
s, info, err := decodeScript(testSubject)
640640

641-
require.NoError(t, err)
641+
require.Nil(t, err)
642642
require.Equal(t, info, "4;3;gzip=0")
643643
require.Equal(t, s, "ls\n")
644644
}
@@ -647,7 +647,7 @@ func Test_decodeScriptGzip(t *testing.T) {
647647
testSubject := "H4sIACD731kAA8sp5gIAfShLWgMAAAA="
648648
s, info, err := decodeScript(testSubject)
649649

650-
require.NoError(t, err)
650+
require.Nil(t, err)
651651
require.Equal(t, info, "32;3;gzip=1")
652652
require.Equal(t, s, "ls\n")
653653
}

internal/constants/errorclarification.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ const (
8787
CommandExecution_TimedOut = 4
8888
CommandExecution_RunAsCreateProcessFailed = 5
8989
CommandExecution_RunAsUserLogonFailed = 6
90+
CommandExecution_CouldNotStart = 7
9091

9192
CustomerInput_StorageCredsAndMIBothSpecified = 26
9293
CustomerInput_ClientIdObjectIdBothSpecified = 27

internal/exec/exec.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,13 @@ func Exec(ctx *log.Context, cmd, workdir string, stdout, stderr io.WriteCloser,
157157
commandFailedErr := fmt.Errorf("command terminated with exit status=%d", commandExitCode)
158158
return exitCode, vmextension.NewErrorWithClarificationPtr(exitCode, commandFailedErr)
159159
}
160+
} else {
161+
startErr, ok := err.(*exec.Error)
162+
if ok {
163+
exitCode = constants.CommandExecution_CouldNotStart
164+
commandFailedErr := fmt.Errorf("Command failed to start with error=%s", startErr)
165+
return exitCode, vmextension.NewErrorWithClarificationPtr(exitCode, commandFailedErr)
166+
}
160167
}
161168
}
162169

internal/exec/exec_test.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ func TestExec_SuccessExitCodeOkay(t *testing.T) {
3333
errw := newCloseRecorder()
3434

3535
exitCode, err := Exec(newCtx(), "echo hi", t.TempDir(), out, errw, cfg)
36-
require.NoError(t, err)
36+
require.Nil(t, err)
3737
require.Equal(t, constants.ExitCode_Okay, exitCode)
3838
require.Contains(t, out.String(), "hi")
3939
}
@@ -584,9 +584,7 @@ func fileExists(t *testing.T, path string) bool {
584584
return false
585585
}
586586

587-
func VerifyErrorClarification(t *testing.T, expectedCode int, err error) {
588-
require.NotNil(t, err, "No error returned when one was expected")
589-
var ewc vmextension.ErrorWithClarification
590-
require.True(t, errors.As(err, &ewc), "Error is not of type ErrorWithClarification")
587+
func VerifyErrorClarification(t *testing.T, expectedCode int, ewc *vmextension.ErrorWithClarification) {
588+
require.NotNil(t, ewc, "No error returned when one was expected")
591589
require.Equal(t, expectedCode, ewc.ErrorCode, "Expected error %d but received %d", expectedCode, ewc.ErrorCode)
592590
}

internal/files/files_test.go

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package files
22

33
import (
4-
"errors"
54
"fmt"
65
"io/ioutil"
76
"net/http/httptest"
@@ -241,7 +240,7 @@ func TestGetDownloaders_NonBlobURL_ReturnsPublicOnly(t *testing.T) {
241240
mock := &mockMsiDownloader{providerToReturn: providerSuccess()}
242241
downloaders, err := getDownloaders(publicURL, nil, mock)
243242

244-
require.NoError(t, err)
243+
require.Nil(t, err)
245244
require.Len(t, downloaders, 1, "non-blob URL must return only public downloader")
246245
require.Equal(t, 0, mock.calledGet+mock.calledByClientID+mock.calledByObjectID,
247246
"msi downloader must not be used for non-blob URL")
@@ -253,10 +252,8 @@ func TestGetDownloaders_EmptyURL_ReturnsClarification(t *testing.T) {
253252
VerifyErrorClarification(t, constants.FileDownload_Empty, err)
254253
}
255254

256-
func VerifyErrorClarification(t *testing.T, expectedCode int, err error) {
257-
require.NotNil(t, err, "No error returned when one was expected")
258-
var ewc vmextension.ErrorWithClarification
259-
require.True(t, errors.As(err, &ewc), "Error is not of type ErrorWithClarification")
255+
func VerifyErrorClarification(t *testing.T, expectedCode int, ewc *vmextension.ErrorWithClarification) {
256+
require.NotNil(t, ewc, "No error returned when one was expected")
260257
require.Equal(t, expectedCode, ewc.ErrorCode, "Expected error %d but received %d", expectedCode, ewc.ErrorCode)
261258
}
262259

internal/goalstate/goalstatefromvmsettings_test.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,10 +117,8 @@ func Test_GetFilteredImmediateVMSettingsFailedToRetrieve(t *testing.T) {
117117

118118
func Test_GetFilteredImmediateVMSettings_NoCommunicator(t *testing.T) {
119119
ctx := log.NewContext(log.NewSyncLogger(log.NewLogfmtLogger(os.Stdout))).With("time", log.DefaultTimestamp)
120-
_, _, err := goalstate.GetImmediateRunCommandGoalStates(ctx, nil, "")
121-
require.NotNil(t, err, "No error returned when one was expected")
122-
var ewc vmextension.ErrorWithClarification
123-
require.True(t, errors.As(err, &ewc), "Error is not of type ErrorWithClarification")
120+
_, _, ewc := goalstate.GetImmediateRunCommandGoalStates(ctx, nil, "")
121+
require.NotNil(t, ewc, "No error returned when one was expected")
124122
require.Equal(t, constants.Hgap_InternalArgumentError, ewc.ErrorCode, "Expected error %d but received %d", constants.Hgap_InternalArgumentError, ewc.ErrorCode)
125123
}
126124

internal/handlersettings/handlerenv_test.go

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ func TestParseHandlerEnv_InvalidConfigCount_Zero(t *testing.T) {
2828
b, err := json.Marshal([]types.HandlerEnvironment{})
2929
require.NoError(t, err)
3030

31-
_, err = ParseHandlerEnv(b)
32-
VerifyErrorClarification(t, constants.HandlerEnv_InvalidConfigCount, err)
31+
_, ewc := ParseHandlerEnv(b)
32+
VerifyErrorClarification(t, constants.HandlerEnv_InvalidConfigCount, ewc)
3333
}
3434

3535
func TestParseHandlerEnv_InvalidConfigCount_Two(t *testing.T) {
@@ -39,8 +39,8 @@ func TestParseHandlerEnv_InvalidConfigCount_Two(t *testing.T) {
3939
})
4040
require.NoError(t, err)
4141

42-
_, err = ParseHandlerEnv(b)
43-
VerifyErrorClarification(t, constants.HandlerEnv_InvalidConfigCount, err)
42+
_, ewc := ParseHandlerEnv(b)
43+
VerifyErrorClarification(t, constants.HandlerEnv_InvalidConfigCount, ewc)
4444
}
4545

4646
func TestParseHandlerEnv_Success(t *testing.T) {
@@ -62,8 +62,8 @@ func TestParseHandlerEnv_Success(t *testing.T) {
6262
b, err := json.Marshal([]types.HandlerEnvironment{want})
6363
require.NoError(t, err)
6464

65-
got, err := ParseHandlerEnv(b)
66-
require.NoError(t, err)
65+
got, ewc := ParseHandlerEnv(b)
66+
require.Nil(t, ewc)
6767
require.Equal(t, want, got)
6868
}
6969

@@ -85,8 +85,8 @@ func TestGetHandlerEnv_FindsHandlerEnvironmentNextToExecutable(t *testing.T) {
8585
t.Cleanup(func() { os.Args[0] = origArgs0 })
8686
os.Args[0] = exePath
8787

88-
got, err := GetHandlerEnv()
89-
require.NoError(t, err)
88+
got, ewc := GetHandlerEnv()
89+
require.Nil(t, ewc)
9090
require.Equal(t, want, got)
9191
}
9292

@@ -108,8 +108,8 @@ func TestGetHandlerEnv_FindsHandlerEnvironmentOneLevelAboveExecutable(t *testing
108108
t.Cleanup(func() { os.Args[0] = origArgs0 })
109109
os.Args[0] = exePath
110110

111-
got, err := GetHandlerEnv()
112-
require.NoError(t, err)
111+
got, ewc := GetHandlerEnv()
112+
require.Nil(t, ewc)
113113
require.Equal(t, want, got)
114114
}
115115

internal/handlersettings/handlersettings_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ func Test_handlerSettingsValidate(t *testing.T) {
1212
require.Equal(t, errSourceNotSpecified, HandlerSettings{
1313
PublicSettings{Source: &ScriptSource{Script: "foo", ScriptURI: "bar"}},
1414
ProtectedSettings{},
15-
}.validate())
15+
}.validate().Err)
1616

1717
// // commandToExecute not specified
1818
// require.Equal(t, errCmdMissing, handlerSettings{

internal/handlersettings/handlersettingscommon.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ type RunTimeSettingsFile struct {
2626
// ReadSettings locates the .settings file and returns public settings
2727
// JSON, and protected settings JSON (by decrypting it with the keys in
2828
// configFolder).
29-
func ReadSettings(configFilePath string) (public, protected map[string]interface{}, _ error) {
29+
func ReadSettings(configFilePath string) (public, protected map[string]interface{}, _ *vmextension.ErrorWithClarification) {
3030
// cf, err := settingsPath(configFolder)
3131
// if err != nil {
3232
// return nil, nil, fmt.Errorf("canot locate settings file: %v", err)

0 commit comments

Comments
 (0)