Skip to content

Commit

Permalink
Fix recent lint offenses
Browse files Browse the repository at this point in the history
  • Loading branch information
MrSerth committed Nov 12, 2024
1 parent 0c7400d commit c65f137
Show file tree
Hide file tree
Showing 17 changed files with 59 additions and 51 deletions.
2 changes: 0 additions & 2 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ linters:
- varnamelen
- wsl
# Deprecated
- execinquery
- exportloopref
- gomnd

linters-settings:
cyclop:
Expand Down
2 changes: 1 addition & 1 deletion cmd/poseidon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ func watchMemoryAndAlert(options config.Profiling) {
log.WithField("interval", options.MemoryInterval).Error("Configured memory interval too big")
return
}
intervalDuration := time.Duration(options.MemoryInterval) * time.Millisecond //nolint:gosec // We check for an integer overflow right above.
intervalDuration := time.Duration(options.MemoryInterval) * time.Millisecond

var exceeded bool
for {
Expand Down
2 changes: 1 addition & 1 deletion internal/api/environments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import (
"github.com/stretchr/testify/suite"
)

const jobHCLBasicFormat = "job \"%s\" {}"
const jobHCLBasicFormat = `job "%s" {}`

type EnvironmentControllerTestSuite struct {
tests.MemoryLeakTestSuite
Expand Down
2 changes: 1 addition & 1 deletion internal/api/runners.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (r *RunnerController) fileContent(writer http.ResponseWriter, request *http
privilegedExecution = false
}

writer.Header().Set("Content-Disposition", "attachment; filename=\""+path+"\"")
writer.Header().Set("Content-Disposition", `attachment; filename="`+path+`"`)
logging.StartSpan(request.Context(), "api.fs.read", "File Content", func(ctx context.Context, _ *sentry.Span) {
err = targetRunner.GetFileContent(ctx, path, writer, privilegedExecution)
})
Expand Down
26 changes: 17 additions & 9 deletions internal/api/websocket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ func newRunnerWithNotMockedRunnerManager(s *MainTestSuite, apiMock *nomad.Execut

runnerID := tests.DefaultRunnerID
runnerJob := runner.NewNomadJob(s.TestCtx, runnerID, nil, apiMock, nil)
nomadEnvironment, err := environment.NewNomadEnvironment(s.TestCtx, 0, apiMock, "job \"template-0\" {}")
nomadEnvironment, err := environment.NewNomadEnvironment(s.TestCtx, 0, apiMock, `job "template-0" {}`)
s.Require().NoError(err)
eID, err := nomad.EnvironmentIDFromRunnerID(runnerID)
s.Require().NoError(err)
Expand Down Expand Up @@ -487,13 +487,21 @@ func mockAPIExecute(api *nomad.ExecutorAPIMock, request *dto.ExecutionRequest,
mock.Anything,
mock.Anything)
call.Run(func(args mock.Arguments) {
exit, err := run(args.Get(0).(context.Context),
args.Get(1).(string),
args.Get(2).(string),
args.Get(3).(bool),
args.Get(5).(io.Reader),
args.Get(6).(io.Writer),
args.Get(7).(io.Writer))
call.ReturnArguments = mock.Arguments{exit, err}
mockCtx, errCtx := args.Get(0).(context.Context)
mockRunnerID, errRunnerID := args.Get(1).(string)
mockCommand, errCommand := args.Get(2).(string)
mockTty, errTty := args.Get(3).(bool)
mockStdin, errStdin := args.Get(5).(io.Reader)
mockStdout, errStdout := args.Get(6).(io.Writer)
mockStderr, errStderr := args.Get(7).(io.Writer)

if !errCtx || !errRunnerID || !errCommand || !errTty || !errStdin || !errStdout || !errStderr {
call.ReturnArguments = mock.Arguments{1, fmt.Errorf(
"%w: errCtx=%v, errRunnerId=%v, errCommand=%v, errTty=%v, errStdin=%v, errStdout=%v, errStderr=%v",
tests.ErrDefault, errCtx, errRunnerID, errCommand, errTty, errStdin, errStdout, errStderr)}
} else {
exit, err := run(mockCtx, mockRunnerID, mockCommand, mockTty, mockStdin, mockStdout, mockStderr)
call.ReturnArguments = mock.Arguments{exit, err}
}
})
}
10 changes: 5 additions & 5 deletions internal/api/ws/codeocean_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,27 +51,27 @@ func (s *MainTestSuite) TestRawToCodeOceanWriter() {
type sendExitInfoTestCase struct {
name string
info *runner.ExitInfo
message dto.WebSocketMessage
message *dto.WebSocketMessage
}

func (s *MainTestSuite) TestCodeOceanOutputWriter_SendExitInfo() {
testCases := []sendExitInfoTestCase{
{
"Timeout", &runner.ExitInfo{Err: runner.ErrRunnerInactivityTimeout},
dto.WebSocketMessage{Type: dto.WebSocketMetaTimeout},
&dto.WebSocketMessage{Type: dto.WebSocketMetaTimeout},
},
{
"Error", &runner.ExitInfo{Err: websocket.ErrCloseSent},
dto.WebSocketMessage{Type: dto.WebSocketOutputError, Data: "Error executing the request"},
&dto.WebSocketMessage{Type: dto.WebSocketOutputError, Data: "Error executing the request"},
},
// CodeOcean expects this exact string in case of a OOM Killed runner.
{
"Specific data for OOM Killed runner", &runner.ExitInfo{Err: runner.ErrOOMKilled},
dto.WebSocketMessage{Type: dto.WebSocketOutputError, Data: "the allocation was OOM Killed"},
&dto.WebSocketMessage{Type: dto.WebSocketOutputError, Data: "the allocation was OOM Killed"},
},
{
"Exit", &runner.ExitInfo{Code: 21},
dto.WebSocketMessage{Type: dto.WebSocketExit, ExitCode: 21},
&dto.WebSocketMessage{Type: dto.WebSocketExit, ExitCode: 21},
},
}

Expand Down
2 changes: 1 addition & 1 deletion internal/environment/nomad_manager_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (s *MainTestSuite) TestNewNomadEnvironmentManager() {
})

s.Run("loads template environment job from file", func() {
templateJobHCL := "job \"" + tests.DefaultTemplateJobID + "\" {}"
templateJobHCL := `job "` + tests.DefaultTemplateJobID + `" {}`

environment, err := NewNomadEnvironment(s.TestCtx, tests.DefaultEnvironmentIDAsInteger, executorAPIMock, templateJobHCL)
s.Require().NoError(err)
Expand Down
2 changes: 1 addition & 1 deletion internal/nomad/command_execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ func injectStartDebugMessage(command string, start uint, end int) string {
}

description := strings.Join(commandFields, " ")
if strings.HasPrefix(description, "\"") && strings.HasSuffix(description, "\"") {
if strings.HasPrefix(description, `"`) && strings.HasSuffix(description, `"`) {
description = description[1 : len(description)-1]
}
if description == "" {
Expand Down
2 changes: 1 addition & 1 deletion internal/nomad/command_execution_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (s *ExecuteCommandTestSuite) SetupTest() {
s.MemoryLeakTestSuite.SetupTest()
s.allocationID = "test-allocation-id"
s.ctx = context.Background()
s.testCommand = "echo \"do nothing\""
s.testCommand = `echo "do nothing"`
s.expectedStdout = "stdout"
s.expectedStderr = "stderr"
s.apiMock = &apiQuerierMock{}
Expand Down
2 changes: 1 addition & 1 deletion internal/nomad/sentry_debug_writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func (s *MainTestSuite) TestSentryDebugWriter_regression_593_empty_command() {
debugWriter := NewSentryDebugWriter(s.TestCtx, buf)

const commandFieldAfterEnv = 4 // instead of "env CODEOCEAN=true /bin/bash -c sleep infinity" just "sleep infinity".
command := injectStartDebugMessage("env CODEOCEAN=true /bin/bash -c \"\"", commandFieldAfterEnv, -1)
command := injectStartDebugMessage(`env CODEOCEAN=true /bin/bash -c ""`, commandFieldAfterEnv, -1)
cmd := exec.Command("/bin/bash", "-c", command)
stdout, err := cmd.Output()
s.Require().NoError(err)
Expand Down
2 changes: 1 addition & 1 deletion internal/runner/aws_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,5 +248,5 @@ func hideEnvironmentVariables(request *dto.ExecutionRequest, unsetPrefix string)
if request.Environment == nil {
request.Environment = make(map[string]string)
}
request.Command = "unset \"${!" + unsetPrefix + "@}\" && " + request.Command
request.Command = `unset "${!` + unsetPrefix + `@}" && ` + request.Command
}
4 changes: 2 additions & 2 deletions internal/runner/nomad_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ func (r *NomadJob) MappedPorts() []*dto.MappedPort {
log.WithError(util.ErrOverflow).WithField("mapping", portMapping.To).Warn("not a valid port")
}
ports = append(ports, &dto.MappedPort{
ExposedPort: uint(portMapping.To), //nolint:gosec // We check for an overflow right above.
ExposedPort: uint(portMapping.To),
HostAddress: fmt.Sprintf("%s:%d", portMapping.HostIP, portMapping.Value),
})
}
Expand All @@ -140,7 +140,7 @@ func (r *NomadJob) UpdateMappedPorts(ports []*dto.MappedPort) error {

mapping = append(mapping, nomadApi.PortMapping{
Value: port,
To: int(portMapping.ExposedPort), //nolint:gosec // We check for an integer overflow right above.
To: int(portMapping.ExposedPort),
HostIP: hostAddress[0],
})
}
Expand Down
2 changes: 1 addition & 1 deletion internal/runner/nomad_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func (s *MainTestSuite) TestMarshalRunner() {
runner := NewNomadJob(s.TestCtx, tests.DefaultRunnerID, nil, apiMock, func(_ Runner) error { return nil })
marshal, err := json.Marshal(runner)
s.Require().NoError(err)
s.Equal("{\"runnerId\":\""+tests.DefaultRunnerID+"\"}", string(marshal))
s.JSONEq(`{"runnerId":"`+tests.DefaultRunnerID+`"}`, string(marshal))
s.Require().NoError(runner.Destroy(nil))
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/dto/dto.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ type WebSocketMessage struct {

// MarshalJSON implements the json.Marshaler interface.
// This converts the WebSocketMessage into the expected schema (see docs/websocket.schema.json).
func (m WebSocketMessage) MarshalJSON() (res []byte, err error) {
func (m *WebSocketMessage) MarshalJSON() (res []byte, err error) {
switch m.Type {
case WebSocketOutputStdout, WebSocketOutputStderr, WebSocketOutputError:
res, err = json.Marshal(struct {
Expand Down
2 changes: 1 addition & 1 deletion pkg/nullio/ls2json.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ func (w *Ls2JsonWriter) Write(lsData []byte) (int, error) {

func (w *Ls2JsonWriter) initializeJSONObject() (count int, err error) {
if !w.jsonStartSent {
count, err = w.Target.Write([]byte("{\"files\": ["))
count, err = w.Target.Write([]byte(`{"files": [`))
if count == 0 || err != nil {
log.WithContext(w.Ctx).WithError(err).Warn("Could not write to target")
err = fmt.Errorf("could not write to target: %w", err)
Expand Down
42 changes: 22 additions & 20 deletions pkg/nullio/ls2json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteCreationAndClose() {
s.Zero(count)
s.Require().NoError(err)

s.Equal("{\"files\": [", s.buf.String())
s.Equal(`{"files": [`, s.buf.String()) //nolint:testifylint // The expected string is not a valid JSON

s.writer.Close()
s.Equal("{\"files\": []}", s.buf.String())
s.JSONEq(`{"files": []}`, s.buf.String())
}

func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteFile() {
Expand All @@ -48,8 +48,8 @@ func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteFile() {
s.Require().NoError(err)
s.writer.Close()

s.Equal("{\"files\": [{\"name\":\"flag\",\"entryType\":\"-\",\"size\":0,\"modificationTime\":1660763446"+
",\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"}]}",
s.JSONEq(`{"files": [{"name":"flag","entryType":"-","size":0,"modificationTime":1660763446`+
`,"permissions":"rw-rw-r--","owner":"kali","group":"kali"}]}`,
s.buf.String())
}

Expand All @@ -62,40 +62,42 @@ func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteRecursive() {
s.Require().NoError(err)
s.writer.Close()

s.Equal("{\"files\": ["+
"{\"name\":\"./dir\",\"entryType\":\"d\",\"size\":4096,\"modificationTime\":1660764411,"+
"\"permissions\":\"rwxrwxr-x\",\"owner\":\"kali\",\"group\":\"kali\"},"+
"{\"name\":\"./flag\",\"entryType\":\"-\",\"size\":0,\"modificationTime\":1660763446,"+
"\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"},"+
"{\"name\":\"./dir/another.txt\",\"entryType\":\"-\",\"size\":3,\"modificationTime\":1660764366,"+
"\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"}"+
"]}",
s.JSONEq(`{"files": [`+
`{"name":"./dir","entryType":"d","size":4096,"modificationTime":1660764411,`+
`"permissions":"rwxrwxr-x","owner":"kali","group":"kali"},`+
`{"name":"./flag","entryType":"-","size":0,"modificationTime":1660763446,`+
`"permissions":"rw-rw-r--","owner":"kali","group":"kali"},`+
`{"name":"./dir/another.txt","entryType":"-","size":3,"modificationTime":1660764366,`+
`"permissions":"rw-rw-r--","owner":"kali","group":"kali"}`+
`]}`,
s.buf.String())
}

func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteRemaining() {
input1 := "total 4\n" + perm664 + "1 " + ownerGroupKali + "3 1660764366 an.txt\n" + perm664 + "1 kal"
_, err := s.writer.Write([]byte(input1))
s.Require().NoError(err)
s.Equal("{\"files\": [{\"name\":\"an.txt\",\"entryType\":\"-\",\"size\":3,\"modificationTime\":1660764366,"+
"\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"}", s.buf.String())
//nolint:testifylint // The expected string is not a valid JSON
s.Equal(`{"files": [{"name":"an.txt","entryType":"-","size":3,"modificationTime":1660764366,`+
`"permissions":"rw-rw-r--","owner":"kali","group":"kali"}`, s.buf.String())

input2 := "i kali 0 1660763446 flag\n"
_, err = s.writer.Write([]byte(input2))
s.Require().NoError(err)
s.writer.Close()
s.Equal("{\"files\": [{\"name\":\"an.txt\",\"entryType\":\"-\",\"size\":3,\"modificationTime\":1660764366,"+
"\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"},"+
"{\"name\":\"flag\",\"entryType\":\"-\",\"size\":0,\"modificationTime\":1660763446,"+
"\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"}]}", s.buf.String())
//nolint:testifylint // The expected string is not a valid JSON
s.Equal(`{"files": [{"name":"an.txt","entryType":"-","size":3,"modificationTime":1660764366,`+
`"permissions":"rw-rw-r--","owner":"kali","group":"kali"},`+
`{"name":"flag","entryType":"-","size":0,"modificationTime":1660763446,`+
`"permissions":"rw-rw-r--","owner":"kali","group":"kali"}]}`, s.buf.String())
}

func (s *Ls2JsonTestSuite) TestLs2JsonWriter_WriteLink() {
input1 := "total 4\nlrw-rw-r-- 1 " + ownerGroupKali + "3 1660764366 another.txt -> /bin/bash\n"
_, err := s.writer.Write([]byte(input1))
s.Require().NoError(err)
s.writer.Close()
s.Equal("{\"files\": [{\"name\":\"another.txt\",\"entryType\":\"l\",\"linkTarget\":\"/bin/bash\",\"size\":3,"+
"\"modificationTime\":1660764366,\"permissions\":\"rw-rw-r--\",\"owner\":\"kali\",\"group\":\"kali\"}]}",
s.JSONEq(`{"files": [{"name":"another.txt","entryType":"l","linkTarget":"/bin/bash","size":3,`+
`"modificationTime":1660764366,"permissions":"rw-rw-r--","owner":"kali","group":"kali"}]}`,
s.buf.String())
}
4 changes: 2 additions & 2 deletions tests/e2e/runners_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ func (s *E2ETestSuite) TestListFileSystem_Nomad() {
s.Equal(http.StatusOK, response.StatusCode)
data, err := io.ReadAll(response.Body)
s.Require().NoError(err)
s.Equal("{\"files\": []}", string(data))
s.JSONEq(`{"files": []}`, string(data))
})

s.Run("With file", func() {
Expand Down Expand Up @@ -458,7 +458,7 @@ func (s *E2ETestSuite) TestGetFileContent_Nomad() {
s.Require().NoError(err)
s.Equal(http.StatusOK, response.StatusCode)
s.Equal(strconv.Itoa(len(newFileContent)), response.Header.Get("Content-Length"))
s.Equal("attachment; filename=\""+tests.DefaultFileName+"\"", response.Header.Get("Content-Disposition"))
s.Equal(`attachment; filename="`+tests.DefaultFileName+`"`, response.Header.Get("Content-Disposition"))
content, err := io.ReadAll(response.Body)
s.Require().NoError(err)
s.Equal(newFileContent, content)
Expand Down

0 comments on commit c65f137

Please sign in to comment.