Enable errcheck linter for golangci-lint (#8899)

This commit is contained in:
gillespi314 2022-12-05 16:50:49 -06:00 committed by GitHub
parent 2d0f33f369
commit 6fb3a87ae9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
67 changed files with 286 additions and 216 deletions

View File

@ -13,6 +13,7 @@ linters:
- typecheck
- unconvert
- unused
- errcheck
linters-settings:
depguard:
@ -21,6 +22,14 @@ linters-settings:
packages-with-error-message:
- github.com/pkg/errors: "use ctxerr if a context.Context is available or stdlib errors.New / fmt.Errorf with the %w verb"
errcheck:
check-type-assertions: false
check-blank: false
ignore: fmt:.*
disable-default-exclusions: false
exclude-functions:
- "(github.com/go-kit/log.Logger).Log"
gosec:
config:
G306: "0644"

View File

@ -71,7 +71,8 @@ func cpe() string {
file, err := os.Create(filepath.Join(cwd, "etagenv"))
panicif(err)
file.WriteString(fmt.Sprintf(`ETAG=%s`, remoteEtag))
_, err = file.WriteString(fmt.Sprintf(`ETAG=%s`, remoteEtag))
panicif(err)
file.Close()
return dbPath

View File

@ -22,7 +22,7 @@ Subcommands for initializing Fleet infrastructure
To setup Fleet infrastructure, use one of the available commands.
`,
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
cmd.Help() //nolint:errcheck
},
}

View File

@ -307,7 +307,9 @@ the way that the Fleet server works.
os.Exit(1)
}
} else {
ds.ApplyEnrollSecrets(cmd.Context(), nil, []*fleet.EnrollSecret{{Secret: config.Packaging.GlobalEnrollSecret}})
if err := ds.ApplyEnrollSecrets(cmd.Context(), nil, []*fleet.EnrollSecret{{Secret: config.Packaging.GlobalEnrollSecret}}); err != nil {
level.Debug(logger).Log("err", err, "msg", "failed to apply enroll secrets")
}
}
}
@ -673,7 +675,7 @@ the way that the Fleet server works.
rw.WriteHeader(http.StatusNotFound)
return
}
rw.Write(testPage)
rw.Write(testPage) //nolint:errcheck
rw.WriteHeader(http.StatusOK)
})
}
@ -754,6 +756,7 @@ the way that the Fleet server works.
}()
}()
// block on errs signal
logger.Log("terminated", <-errs)
},
}

View File

@ -670,7 +670,7 @@ func TestAutomationsScheduleIntervalChange(t *testing.T) {
}
mockLocker := schedule.SetupMockLocker("automations", "test_instance", time.Now().UTC())
mockLocker.AddChannels(t, "locked")
require.NoError(t, mockLocker.AddChannels(t, "locked"))
ds.LockFunc = mockLocker.Lock
ds.UnlockFunc = mockLocker.Unlock

View File

@ -80,7 +80,7 @@ func TestApplyUserRoles(t *testing.T) {
require.NoError(t, err)
defer os.Remove(tmpFile.Name())
tmpFile.WriteString(`
_, err = tmpFile.WriteString(`
---
apiVersion: v1
kind: user_roles
@ -95,7 +95,7 @@ spec:
- role: maintainer
team: team1
`)
require.NoError(t, err)
assert.Equal(t, "[+] applied user roles\n", runAppForTest(t, []string{"apply", "-f", tmpFile.Name()}))
require.Len(t, userRoleSpecList[1].Teams, 1)
assert.Equal(t, fleet.RoleMaintainer, userRoleSpecList[1].Teams[0].Role)
@ -320,7 +320,7 @@ func TestApplyAppConfigDryRunIssue(t *testing.T) {
return nil
}
var currentAppConfig = &fleet.AppConfig{
currentAppConfig := &fleet.AppConfig{
OrgInfo: fleet.OrgInfo{OrgName: "Fleet"}, ServerSettings: fleet.ServerSettings{ServerURL: "https://example.org"},
}
ds.AppConfigFunc = func(ctx context.Context) (*fleet.AppConfig, error) {

View File

@ -164,6 +164,6 @@ func TestCustomHeadersConfig(t *testing.T) {
"--custom-header", "X-Fleet-MoreTest:another",
"--address", srv.URL,
})
runAppNoChecks([]string{"get", "packs", "--config", configFile})
runAppNoChecks([]string{"get", "packs", "--config", configFile}) //nolint:errcheck
require.True(t, called)
}

View File

@ -26,7 +26,7 @@ func init() {
func main() {
app := createApp(os.Stdin, os.Stdout, exitErrHandler)
app.Run(os.Args)
app.Run(os.Args) //nolint:errcheck
}
// exitErrHandler implements cli.ExitErrHandlerFunc. If there is an error, prints it to stderr and exits with status 1.

View File

@ -513,7 +513,7 @@ func getLabelsCommand() *cli.Command {
if c.Bool(yamlFlagName) || c.Bool(jsonFlagName) {
for _, label := range labels {
printLabel(c, label)
printLabel(c, label) //nolint:errcheck
}
return nil
}
@ -547,7 +547,7 @@ func getLabelsCommand() *cli.Command {
return err
}
printLabel(c, label)
printLabel(c, label) //nolint:errcheck
return nil
},
}

View File

@ -253,7 +253,7 @@ To add this device to Fleet, double-click to open your installer.
To add other devices to Fleet, distribute this installer using Chef, Ansible, Jamf, or Puppet. Learn how: https://fleetdm.com/docs/using-fleet/adding-hosts
`, path)
if !disableOpenFolder {
open.Start(filepath.Dir(path))
open.Start(filepath.Dir(path)) //nolint:errcheck
}
return nil
},

View File

@ -261,7 +261,9 @@ Use the stop and reset subcommands to manage the server and dependencies once st
context = "preview"
config.Contexts["preview"] = contextConfig
}
c.Set("context", context)
if err := c.Set("context", context); err != nil {
return fmt.Errorf("Error setting context: %w", err)
}
if err := writeConfig(configPath, config); err != nil {
return fmt.Errorf("Error writing fleetctl configuration: %w", err)

View File

@ -24,7 +24,7 @@ func TestPreview(t *testing.T) {
})
var output *bytes.Buffer
nettest.RunWithNetRetry(t, func() error {
require.NoError(t, nettest.RunWithNetRetry(t, func() error {
var err error
output, err = runAppNoChecks([]string{
"preview", "--config", configPath,
@ -32,7 +32,7 @@ func TestPreview(t *testing.T) {
"--disable-open-browser",
})
return err
})
}))
queriesRe := regexp.MustCompile(`applied ([0-9]+) queries`)
policiesRe := regexp.MustCompile(`applied ([0-9]+) policies`)

View File

@ -152,7 +152,9 @@ func main() {
if strings.HasPrefix(executable, "/var/lib/orbit") {
rootDir = "/var/lib/orbit"
}
c.Set("root-dir", rootDir)
if err := c.Set("root-dir", rootDir); err != nil {
return fmt.Errorf("failed to set root-dir: %w", err)
}
}
return nil

View File

@ -79,7 +79,7 @@ func killPID(pid int32) error {
for _, process := range processes {
if pid == process.Pid {
process.Kill()
process.Kill() //nolint:errcheck
break
}
}

View File

@ -123,7 +123,9 @@ func (r *Runner) Interrupt(err error) {
cancel()
}
if srv := r.getSrv(); srv != nil {
srv.Shutdown(context.Background())
if err := srv.Shutdown(context.Background()); err != nil {
log.Debug().Err(err).Msg("shutdown extension")
}
}
}

View File

@ -16,7 +16,7 @@ func TestLoadOrGenerate(t *testing.T) {
defer os.Remove(file)
rw := NewReadWriter(file)
rw.LoadOrGenerate()
require.NoError(t, rw.LoadOrGenerate())
token, err := rw.Read()
require.NoError(t, err)
require.NotEmpty(t, token)
@ -79,7 +79,7 @@ func TestLoadOrGenerate(t *testing.T) {
require.NoError(t, err)
_, err = file.WriteString("test")
require.NoError(t, err)
file.Chmod(0x600)
require.NoError(t, file.Chmod(0x600))
defer os.Remove(file.Name())
rw := NewReadWriter(file.Name())

View File

@ -1231,8 +1231,8 @@ func (man Manager) getInterfaceVal(key string) interface{} {
// addConfigString adds a string config to the config options
func (man Manager) addConfigString(key, defVal, usage string) {
man.command.PersistentFlags().String(flagNameFromConfigKey(key), defVal, getFlagUsage(key, usage))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key)))
man.viper.BindEnv(key, envNameFromConfigKey(key))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key))) //nolint:errcheck
man.viper.BindEnv(key, envNameFromConfigKey(key)) //nolint:errcheck
// Add default
man.addDefault(key, defVal)
@ -1269,8 +1269,8 @@ func (man Manager) getConfigTLSProfile() string {
// addConfigInt adds a int config to the config options
func (man Manager) addConfigInt(key string, defVal int, usage string) {
man.command.PersistentFlags().Int(flagNameFromConfigKey(key), defVal, getFlagUsage(key, usage))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key)))
man.viper.BindEnv(key, envNameFromConfigKey(key))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key))) //nolint:errcheck
man.viper.BindEnv(key, envNameFromConfigKey(key)) //nolint:errcheck
// Add default
man.addDefault(key, defVal)
@ -1290,8 +1290,8 @@ func (man Manager) getConfigInt(key string) int {
// addConfigBool adds a bool config to the config options
func (man Manager) addConfigBool(key string, defVal bool, usage string) {
man.command.PersistentFlags().Bool(flagNameFromConfigKey(key), defVal, getFlagUsage(key, usage))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key)))
man.viper.BindEnv(key, envNameFromConfigKey(key))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key))) //nolint:errcheck
man.viper.BindEnv(key, envNameFromConfigKey(key)) //nolint:errcheck
// Add default
man.addDefault(key, defVal)
@ -1311,8 +1311,8 @@ func (man Manager) getConfigBool(key string) bool {
// addConfigDuration adds a duration config to the config options
func (man Manager) addConfigDuration(key string, defVal time.Duration, usage string) {
man.command.PersistentFlags().Duration(flagNameFromConfigKey(key), defVal, getFlagUsage(key, usage))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key)))
man.viper.BindEnv(key, envNameFromConfigKey(key))
man.viper.BindPFlag(key, man.command.PersistentFlags().Lookup(flagNameFromConfigKey(key))) //nolint:errcheck
man.viper.BindEnv(key, envNameFromConfigKey(key)) //nolint:errcheck
// Add default
man.addDefault(key, defVal)

View File

@ -1727,7 +1727,7 @@ func testHostsAdditional(t *testing.T, ds *Datastore) {
// Add additional
additional := json.RawMessage(`{"additional": "result"}`)
ds.SaveHostAdditional(context.Background(), h.ID, &additional)
require.NoError(t, ds.SaveHostAdditional(context.Background(), h.ID, &additional))
// Additional should not be loaded for HostLite
h, err = ds.HostLite(context.Background(), h.ID)
@ -1757,7 +1757,7 @@ func testHostsAdditional(t *testing.T, ds *Datastore) {
// Update additional
additional = json.RawMessage(`{"other": "additional"}`)
ds.SaveHostAdditional(context.Background(), h.ID, &additional)
require.NoError(t, ds.SaveHostAdditional(context.Background(), h.ID, &additional))
require.NoError(t, err)
h, err = ds.HostLite(context.Background(), h.ID)
@ -3664,12 +3664,16 @@ func testHostDeviceMapping(t *testing.T, ds *Datastore) {
require.NoError(t, err)
// add device mapping for host
ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
_, err = ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
h.ID, "a@b.c", "src1")
ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
require.NoError(t, err)
_, err = ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
h.ID, "b@b.c", "src1")
ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
require.NoError(t, err)
_, err = ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
h.ID, "a@b.c", "src2")
require.NoError(t, err)
// non-existent host should have empty device mapping
dms, err := ds.ListHostDeviceMapping(ctx, h.ID+1)
@ -3704,8 +3708,9 @@ func testHostDeviceMapping(t *testing.T, ds *Datastore) {
require.NoError(t, err)
// add device mapping for second host
ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
_, err = ds.writer.ExecContext(ctx, `INSERT INTO host_emails (host_id, email, source) VALUES (?, ?, ?)`,
h2.ID, "a@b.c", "src2")
require.NoError(t, err)
// create third host with no device mapping
_, err = ds.NewHost(ctx, &fleet.Host{

View File

@ -130,10 +130,10 @@ func testLocksDBLocks(t *testing.T, ds *Datastore) {
// cause a deadlock (see https://stackoverflow.com/a/31552794/1094941)
tx1, err := ds.writer.BeginTxx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
require.NoError(t, err)
defer tx1.Rollback()
defer tx1.Rollback() //nolint:errcheck
tx2, err := ds.writer.BeginTxx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
require.NoError(t, err)
defer tx2.Rollback()
defer tx2.Rollback() //nolint:errcheck
wait := make(chan struct{})
go func() {

View File

@ -47,7 +47,9 @@ func Labels2() []fleet.Label {
func Up_20170223171234(tx *sql.Tx) error {
// Remove the old labels
Down_20161229171615(tx)
if err := Down_20161229171615(tx); err != nil {
return err
}
// Insert the new labels
sql := `
@ -85,7 +87,9 @@ func Down_20170223171234(tx *sql.Tx) error {
}
// Insert the old labels
Up_20161229171615(tx)
if err := Up_20161229171615(tx); err != nil {
return err
}
return nil
}

View File

@ -102,7 +102,7 @@ func Up_20220708095046(tx *sql.Tx) error {
if !locked || err != nil {
logger.Warn.Println("Could not acquire lock, might not be able to remove duplicates in a reliable way...")
} else {
defer releaseLock(tx, identifier)
defer releaseLock(tx, identifier) //nolint:errcheck
}
}

View File

@ -40,11 +40,13 @@ func TestMigrationStatus(t *testing.T) {
assert.Empty(t, status.MissingData)
// Insert unknown migration.
ds.writer.Exec(`INSERT INTO ` + tables.MigrationClient.TableName + ` (version_id, is_applied) VALUES (1638994765, 1)`)
_, err = ds.writer.Exec(`INSERT INTO ` + tables.MigrationClient.TableName + ` (version_id, is_applied) VALUES (1638994765, 1)`)
require.NoError(t, err)
status, err = ds.MigrationStatus(context.Background())
require.NoError(t, err)
assert.EqualValues(t, fleet.UnknownMigrations, status.StatusCode)
ds.writer.Exec(`DELETE FROM ` + tables.MigrationClient.TableName + ` WHERE version_id = 1638994765`)
_, err = ds.writer.Exec(`DELETE FROM ` + tables.MigrationClient.TableName + ` WHERE version_id = 1638994765`)
require.NoError(t, err)
status, err = ds.MigrationStatus(context.Background())
require.NoError(t, err)

View File

@ -341,7 +341,9 @@ func New(config config.MysqlConfig, c clock.Clock, opts ...DBOption) (*Datastore
for _, setOpt := range opts {
if setOpt != nil {
setOpt(options)
if err := setOpt(options); err != nil {
return nil, err
}
}
}
@ -508,8 +510,14 @@ func (ds *Datastore) loadMigrations(
reader dbReader,
) (tableRecs []int64, dataRecs []int64, err error) {
// We need to run the following to trigger the creation of the migration status tables.
tables.MigrationClient.GetDBVersion(writer)
data.MigrationClient.GetDBVersion(writer)
_, err = tables.MigrationClient.GetDBVersion(writer)
if err != nil {
return nil, nil, err
}
_, err = data.MigrationClient.GetDBVersion(writer)
if err != nil {
return nil, nil, err
}
// version_id > 0 to skip the bootstrap migration that creates the migration tables.
if err := sqlx.SelectContext(ctx, reader, &tableRecs,
"SELECT version_id FROM "+tables.MigrationClient.TableName+" WHERE version_id > 0 AND is_applied ORDER BY id ASC",

View File

@ -642,7 +642,7 @@ func TestWithRetryTxWithRollback(t *testing.T) {
func TestWithRetryTxWillRollbackWhenPanic(t *testing.T) {
mock, ds := mockDatastore(t)
defer ds.Close()
defer func() { recover() }()
defer func() { recover() }() //nolint:errcheck
mock.ExpectBegin()
mock.ExpectExec("SELECT 1").WillReturnError(errors.New("let's rollback!"))
@ -674,7 +674,7 @@ func TestWithTxWithRollback(t *testing.T) {
func TestWithTxWillRollbackWhenPanic(t *testing.T) {
mock, ds := mockDatastore(t)
defer ds.Close()
defer func() { recover() }()
defer func() { recover() }() //nolint:errcheck
mock.ExpectBegin()
mock.ExpectExec("SELECT 1").WillReturnError(errors.New("let's rollback!"))
@ -977,7 +977,6 @@ func TestDebugs(t *testing.T) {
}
func TestANSIQuotesEnabled(t *testing.T) {
// Ensure sql_mode=ANSI_QUOTES is enabled for tests
ds := CreateMySQLDS(t)

View File

@ -345,17 +345,17 @@ func TestCleanupHostOperatingSystems(t *testing.T) {
assertDeletedOS([]uint{})
// nothing to clean up
ds.CleanupHostOperatingSystems(ctx)
require.NoError(t, ds.CleanupHostOperatingSystems(ctx))
assertDeletedHostOS([]uint{})
assertDeletedOS([]uint{})
// delete some hosts
var deletedHostIDs []uint
ds.DeleteHost(ctx, testHosts[0].ID)
ds.DeleteHost(ctx, testHosts[1].ID)
require.NoError(t, ds.DeleteHost(ctx, testHosts[0].ID))
require.NoError(t, ds.DeleteHost(ctx, testHosts[1].ID))
deletedHostIDs = append(deletedHostIDs, testHosts[0].ID, testHosts[1].ID)
ds.CleanupHostOperatingSystems(ctx)
require.NoError(t, ds.CleanupHostOperatingSystems(ctx))
// clean up removes host_operating_system record for deleted hosts
assertDeletedHostOS(deletedHostIDs)
@ -364,10 +364,10 @@ func TestCleanupHostOperatingSystems(t *testing.T) {
assertDeletedOS([]uint{})
// delete remaining host for seedOSList[0]
ds.DeleteHost(ctx, testHosts[5].ID)
require.NoError(t, ds.DeleteHost(ctx, testHosts[5].ID))
deletedHostIDs = append(deletedHostIDs, testHosts[5].ID)
ds.CleanupHostOperatingSystems(ctx)
require.NoError(t, ds.CleanupHostOperatingSystems(ctx))
// clean up removes host_operating_system record for deleted hosts
assertDeletedHostOS(deletedHostIDs)

View File

@ -395,7 +395,7 @@ func (ds *Datastore) PolicyQueriesForHost(ctx context.Context, host *fleet.Host)
if host.FleetPlatform() == "" {
// We log to help troubleshooting in case this happens, as the host
// won't be receiving any policies targeted for specific platforms.
level.Error(ds.logger).Log("err", fmt.Sprintf("host %d with empty platform", host.ID))
level.Error(ds.logger).Log("err", fmt.Sprintf("host %d with empty platform", host.ID)) //nolint:errcheck
}
q := dialect.From("policies").Select(
goqu.I("id"),

View File

@ -286,11 +286,11 @@ func testListSoftwareCPEs(t *testing.T, ds *Datastore) {
debian := test.NewHost(t, ds, "host3", "", "host3key", "host3uuid", time.Now())
debian.Platform = "debian"
ds.UpdateHost(ctx, debian)
require.NoError(t, ds.UpdateHost(ctx, debian))
ubuntu := test.NewHost(t, ds, "host4", "", "host4key", "host4uuid", time.Now())
ubuntu.Platform = "ubuntu"
ds.UpdateHost(ctx, ubuntu)
require.NoError(t, ds.UpdateHost(ctx, ubuntu))
software := []fleet.Software{
{Name: "foo", Version: "0.0.1", Source: "chrome_extensions"},
@ -1292,7 +1292,8 @@ func testHostsBySoftwareIDs(t *testing.T, ds *Datastore) {
ID: 2,
Hostname: "host2",
DisplayName: "host2",
}})
},
})
hosts, err = ds.HostsBySoftwareIDs(ctx, []uint{barRpm.ID})
require.NoError(t, err)
@ -1594,7 +1595,7 @@ func testListSoftwareForVulnDetection(t *testing.T, ds *Datastore) {
host := test.NewHost(t, ds, "host3", "", "host3key", "host3uuid", time.Now())
host.Platform = "debian"
ds.UpdateHost(ctx, host)
require.NoError(t, ds.UpdateHost(ctx, host))
software := []fleet.Software{
{Name: "foo", Version: "0.0.1", Source: "chrome_extensions"},
@ -1633,11 +1634,11 @@ func testSoftwareByID(t *testing.T, ds *Datastore) {
hostA := test.NewHost(t, ds, "hostA", "", "hostAkey", "hostAuuid", time.Now())
hostA.Platform = "ubuntu"
ds.UpdateHost(ctx, hostA)
require.NoError(t, ds.UpdateHost(ctx, hostA))
hostB := test.NewHost(t, ds, "hostB", "", "hostBkey", "hostBuuid", time.Now())
hostB.Platform = "ubuntu"
ds.UpdateHost(ctx, hostB)
require.NoError(t, ds.UpdateHost(ctx, hostB))
software := []fleet.Software{
{Name: "foo_123", Version: "0.0.1", Source: "chrome_extensions"},

View File

@ -54,7 +54,7 @@ func (ds *Datastore) ShouldSendStatistics(ctx context.Context, frequency time.Du
}
amountPolicyViolationDaysActual, amountPolicyViolationDaysPossible, err := amountPolicyViolationDaysDB(ctx, ds.writer)
if err == sql.ErrNoRows {
level.Debug(ds.logger).Log("msg", "amount policy violation days", "err", err)
level.Debug(ds.logger).Log("msg", "amount policy violation days", "err", err) //nolint:errcheck
} else if err != nil {
return ctxerr.Wrap(ctx, err, "amount policy violation days")
}

View File

@ -219,7 +219,7 @@ func TestPublishHasListeners(t *testing.T) {
require.False(t, ok)
// one listener on a different node
redis.BindConn(pool, sconn, "b")
require.NoError(t, redis.BindConn(pool, sconn, "b"))
psc := redigo.PubSubConn{Conn: sconn}
require.NoError(t, psc.Subscribe(prefix+"{a}"))
waitForSub(t, psc, defaultTimeout)

View File

@ -207,16 +207,16 @@ func (h *Handler) storeError(ctx context.Context, err error) {
jsonKey := fmt.Sprintf("error:{%s}:json", errorHash)
countKey := fmt.Sprintf("error:{%s}:count", errorHash)
conn.Send("SET", jsonKey, errorJson)
conn.Send("INCR", countKey)
conn.Send("SET", jsonKey, errorJson) //nolint:errcheck
conn.Send("INCR", countKey) //nolint:errcheck
if h.ttl > 0 {
secs := int(h.ttl.Seconds())
if secs <= 0 {
secs = 1 // EXPIRE fails if ttl is <= 0
}
conn.Send("EXPIRE", jsonKey, secs)
conn.Send("EXPIRE", countKey, secs)
conn.Send("EXPIRE", jsonKey, secs) //nolint:errcheck
conn.Send("EXPIRE", countKey, secs) //nolint:errcheck
}
if _, err := conn.Do(""); err != nil {
@ -285,5 +285,5 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(bytes)
w.Write(bytes) //nolint:errcheck
}

View File

@ -24,9 +24,11 @@ import (
"github.com/stretchr/testify/require"
)
var eh = ctxerr.MockHandler{}
var ctxb = context.Background()
var ctx = ctxerr.NewContext(ctxb, eh)
var (
eh = ctxerr.MockHandler{}
ctxb = context.Background()
ctx = ctxerr.NewContext(ctxb, eh)
)
func alwaysErrors() error { return pkgErrors.New("always errors") }
@ -221,7 +223,7 @@ func testErrorHandlerCollectsErrors(t *testing.T, pool fleet.RedisPool, wd strin
<-chGo
for i := 0; i < 3; i++ {
alwaysNewError(eh)
alwaysNewError(eh) //nolint:errcheck
}
<-chDone
@ -283,15 +285,15 @@ func testErrorHandlerCollectsDifferentErrors(t *testing.T, pool fleet.RedisPool,
// those two errors are different because from a different strack trace
// (different line)
alwaysNewError(eh)
alwaysNewError(eh)
alwaysNewError(eh) //nolint:errcheck
alwaysNewError(eh) //nolint:errcheck
// while those two are the same, only one gets store
for i := 0; i < 2; i++ {
alwaysNewError(eh)
alwaysNewError(eh) //nolint:errcheck
}
alwaysNewErrorTwo(eh)
alwaysNewErrorTwo(eh) //nolint:errcheck
<-chDone

View File

@ -47,7 +47,7 @@ func NewFilesystemLogWriter(path string, appLogger log.Logger, enableRotation bo
Filename: path,
MaxSize: 500, // megabytes
MaxBackups: 3,
MaxAge: 28, //days
MaxAge: 28, // days
Compress: enableCompression,
}
appLogger = log.With(appLogger, "component", "osqueryd-logger")
@ -55,7 +55,7 @@ func NewFilesystemLogWriter(path string, appLogger log.Logger, enableRotation bo
signal.Notify(sig, syscall.SIGHUP)
go func() {
for {
<-sig //block on signal
<-sig // block on signal
if err := osquerydLogger.Rotate(); err != nil {
appLogger.Log("err", err)
}
@ -107,7 +107,7 @@ func (l *rawLogWriter) Write(b []byte) (int, error) {
return 0, errors.New("filesystemLogWriter: can't write to closed file")
}
if _, statErr := os.Stat(l.file.Name()); errors.Is(statErr, os.ErrNotExist) {
f, err := secure.OpenFile(l.file.Name(), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
f, err := secure.OpenFile(l.file.Name(), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
if err != nil {
return 0, fmt.Errorf("create file for filesystemLogWriter %s: %w", l.file.Name(), err)
}
@ -148,5 +148,5 @@ func (l *rawLogWriter) Close() error {
}
func openFile(path string) (*os.File, error) {
return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
return os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o644)
}

View File

@ -18,7 +18,7 @@ import (
func TestFilesystemLogger(t *testing.T) {
ctx := context.Background()
tempPath := t.TempDir()
require.NoError(t, os.Chmod(tempPath, 0755))
require.NoError(t, os.Chmod(tempPath, 0o755))
fileName := filepath.Join(tempPath, "filesystemLogWriter")
lgr, err := NewFilesystemLogWriter(fileName, log.NewNopLogger(), false, false)
require.Nil(t, err)
@ -33,7 +33,7 @@ func TestFilesystemLogger(t *testing.T) {
var logs []json.RawMessage
for i := 0; i < logCount; i++ {
randInput := make([]byte, logSize)
rand.Read(randInput)
rand.Read(randInput) //nolint:errcheck
logs = append(logs, randInput)
}
@ -57,14 +57,13 @@ func TestFilesystemLogger(t *testing.T) {
require.Nil(t, err)
// + 1 below is for newlines that should be appended to each log
assert.Equal(t, int64(batches*logCount*(logSize+1)), info.Size())
}
// TestFilesystemLoggerPermission tests that NewFilesystemLogWriter fails
// if the process does not have permissions to write to the provided path.
func TestFilesystemLoggerPermission(t *testing.T) {
tempPath := t.TempDir()
require.NoError(t, os.Chmod(tempPath, 0000))
require.NoError(t, os.Chmod(tempPath, 0o000))
fileName := filepath.Join(tempPath, "filesystemLogWriter")
for _, tc := range []struct {
name string
@ -92,7 +91,7 @@ func BenchmarkFilesystemLogger(b *testing.B) {
var logs []json.RawMessage
for i := 0; i < 50; i++ {
randInput := make([]byte, 512)
rand.Read(randInput)
rand.Read(randInput) //nolint:errcheck
logs = append(logs, randInput)
}
b.ResetTimer()
@ -128,7 +127,7 @@ func benchLumberjack(b *testing.B, compression bool) {
var logs []json.RawMessage
for i := 0; i < 50; i++ {
randInput := make([]byte, 512)
rand.Read(randInput)
rand.Read(randInput) //nolint:errcheck
logs = append(logs, randInput)
}
// first lumberjack write opens file so we count that as part of initialization

View File

@ -170,7 +170,7 @@ func (r *redisQueryResults) ReadChannel(ctx context.Context, query fleet.Distrib
go func() {
wg.Wait()
psc.Unsubscribe(pubSubName)
psc.Unsubscribe(pubSubName) //nolint:errcheck
conn.Close()
}()

View File

@ -242,7 +242,7 @@ func echoHandler() http.Handler {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(dump)
w.Write(dump) //nolint:errcheck
})
}

View File

@ -56,10 +56,12 @@ func setupAppleMDMService(t *testing.T) (fleet.Service, context.Context) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.Contains(r.URL.Path, "/server/devices"):
w.Write([]byte("{}"))
_, err := w.Write([]byte("{}"))
require.NoError(t, err)
return
case strings.Contains(r.URL.Path, "/session"):
w.Write([]byte(`{"auth_session_token": "yoo"}`))
_, err := w.Write([]byte(`{"auth_session_token": "yoo"}`))
require.NoError(t, err)
return
}
}))

View File

@ -194,7 +194,7 @@ func testRecordHostLastSeenSync(t *testing.T, ds *mock.Store, pool fleet.RedisPo
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", hostSeenRecordedHostIDsKey, hostSeenProcessingHostIDsKey)
defer conn.Do("DEL", hostSeenRecordedHostIDsKey, hostSeenProcessingHostIDsKey) //nolint:errcheck
n, err := redigo.Int(conn.Do("EXISTS", hostSeenRecordedHostIDsKey))
require.NoError(t, err)
@ -234,7 +234,7 @@ func testRecordHostLastSeenAsync(t *testing.T, ds *mock.Store, pool fleet.RedisP
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", hostSeenRecordedHostIDsKey, hostSeenProcessingHostIDsKey)
defer conn.Do("DEL", hostSeenRecordedHostIDsKey, hostSeenProcessingHostIDsKey) //nolint:errcheck
n, err := redigo.Int(conn.Do("SCARD", hostSeenRecordedHostIDsKey))
require.NoError(t, err)

View File

@ -283,7 +283,7 @@ func testRecordLabelQueryExecutionsSync(t *testing.T, ds *mock.Store, pool fleet
LabelUpdatedAt: lastYear,
}
var yes, no = true, false
yes, no := true, false
results := map[uint]*bool{1: &yes, 2: &yes, 3: &no, 4: nil}
keySet, keyTs := fmt.Sprintf(labelMembershipHostKey, host.ID), fmt.Sprintf(labelMembershipReportedKey, host.ID)
@ -299,7 +299,7 @@ func testRecordLabelQueryExecutionsSync(t *testing.T, ds *mock.Store, pool fleet
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", keySet, keyTs)
defer conn.Do("DEL", keySet, keyTs) //nolint:errcheck
n, err := redigo.Int(conn.Do("EXISTS", keySet))
require.NoError(t, err)
@ -326,7 +326,7 @@ func testRecordLabelQueryExecutionsAsync(t *testing.T, ds *mock.Store, pool flee
Platform: "linux",
LabelUpdatedAt: lastYear,
}
var yes, no = true, false
yes, no := true, false
results := map[uint]*bool{1: &yes, 2: &yes, 3: &no, 4: nil}
keySet, keyTs := fmt.Sprintf(labelMembershipHostKey, host.ID), fmt.Sprintf(labelMembershipReportedKey, host.ID)
@ -348,7 +348,7 @@ func testRecordLabelQueryExecutionsAsync(t *testing.T, ds *mock.Store, pool flee
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", keySet, keyTs)
defer conn.Do("DEL", keySet, keyTs) //nolint:errcheck
res, err := redigo.IntMap(conn.Do("ZPOPMIN", keySet, 10))
require.NoError(t, err)

View File

@ -307,7 +307,7 @@ func testRecordPolicyQueryExecutionsSync(t *testing.T, ds *mock.Store, pool flee
PolicyUpdatedAt: lastYear,
}
var yes, no = true, false
yes, no := true, false
results := map[uint]*bool{1: &yes, 2: &yes, 3: &no, 4: nil}
keyList, keyTs := fmt.Sprintf(policyPassHostKey, host.ID), fmt.Sprintf(policyPassReportedKey, host.ID)
@ -323,7 +323,7 @@ func testRecordPolicyQueryExecutionsSync(t *testing.T, ds *mock.Store, pool flee
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", keyList, keyTs)
defer conn.Do("DEL", keyList, keyTs) //nolint:errcheck
n, err := redigo.Int(conn.Do("EXISTS", keyList))
require.NoError(t, err)
@ -350,7 +350,7 @@ func testRecordPolicyQueryExecutionsAsync(t *testing.T, ds *mock.Store, pool fle
Platform: "linux",
PolicyUpdatedAt: lastYear,
}
var yes, no = true, false
yes, no := true, false
results := map[uint]*bool{1: &yes, 2: &yes, 3: &no, 4: nil}
keyList, keyTs := fmt.Sprintf(policyPassHostKey, host.ID), fmt.Sprintf(policyPassReportedKey, host.ID)
@ -372,7 +372,7 @@ func testRecordPolicyQueryExecutionsAsync(t *testing.T, ds *mock.Store, pool fle
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", keyList, keyTs)
defer conn.Do("DEL", keyList, keyTs) //nolint:errcheck
res, err := redigo.Strings(conn.Do("LRANGE", keyList, 0, -1))
require.NoError(t, err)

View File

@ -184,7 +184,7 @@ func testRecordScheduledQueryStatsSync(t *testing.T, ds *mock.Store, pool fleet.
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", hashKey)
defer conn.Do("DEL", hashKey) //nolint:errcheck
n, err := redigo.Int(conn.Do("EXISTS", hashKey))
require.NoError(t, err)
@ -228,7 +228,7 @@ func testRecordScheduledQueryStatsAsync(t *testing.T, ds *mock.Store, pool fleet
conn := redis.ConfigureDoer(pool, pool.Get())
defer conn.Close()
defer conn.Do("DEL", hashKey)
defer conn.Do("DEL", hashKey) //nolint:errcheck
res, err := redigo.StringMap(conn.Do("HGETALL", hashKey))
require.NoError(t, err)

View File

@ -106,7 +106,7 @@ func (c *collector) exec(ctx context.Context) {
c.addSkipStats(failed)
return
}
defer conn.Do("DEL", keyLock)
defer conn.Do("DEL", keyLock) //nolint:errcheck
// at this point, the lock has been acquired, execute the collector handler
ctx, cancel := context.WithTimeout(ctx, time.Duration(c.lockTimeout.Seconds())*time.Second)

View File

@ -61,7 +61,7 @@ func jsonHandler(
rw.WriteHeader(http.StatusInternalServerError)
return
}
rw.Write(b)
rw.Write(b) //nolint:errcheck
}
}

View File

@ -47,7 +47,7 @@ func makeStreamDistributedQueryCampaignResultsHandler(svc fleet.Service, logger
defer func() {
if p := recover(); p != nil {
logger.Log("err", p, "msg", "panic in result handler")
conn.WriteJSONError("panic in result handler")
conn.WriteJSONError("panic in result handler") //nolint:errcheck
}
session.Close(0, "none")
}()
@ -63,7 +63,7 @@ func makeStreamDistributedQueryCampaignResultsHandler(svc fleet.Service, logger
vc, err := authViewer(context.Background(), string(token), svc)
if err != nil || !vc.CanPerformActions() {
logger.Log("err", err, "msg", "unauthorized viewer")
conn.WriteJSONError("unauthorized")
conn.WriteJSONError("unauthorized") //nolint:errcheck
return
}
@ -72,12 +72,12 @@ func makeStreamDistributedQueryCampaignResultsHandler(svc fleet.Service, logger
msg, err := conn.ReadJSONMessage()
if err != nil {
logger.Log("err", err, "msg", "reading select_campaign JSON")
conn.WriteJSONError("error reading select_campaign")
conn.WriteJSONError("error reading select_campaign") //nolint:errcheck
return
}
if msg.Type != "select_campaign" {
logger.Log("err", "unexpected msg type, expected select_campaign", "msg-type", msg.Type)
conn.WriteJSONError("expected select_campaign")
conn.WriteJSONError("expected select_campaign") //nolint:errcheck
return
}
@ -87,12 +87,12 @@ func makeStreamDistributedQueryCampaignResultsHandler(svc fleet.Service, logger
err = json.Unmarshal(*(msg.Data.(*json.RawMessage)), &info)
if err != nil {
logger.Log("err", err, "msg", "unmarshaling select_campaign data")
conn.WriteJSONError("error unmarshaling select_campaign data")
conn.WriteJSONError("error unmarshaling select_campaign data") //nolint:errcheck
return
}
if info.CampaignID == 0 {
logger.Log("err", "campaign ID not set")
conn.WriteJSONError("0 is not a valid campaign ID")
conn.WriteJSONError("0 is not a valid campaign ID") //nolint:errcheck
return
}

View File

@ -36,7 +36,7 @@ func TestJira(t *testing.T) {
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`
_, err := w.Write([]byte(`
{
"id": "10000",
"key": "ED-24",
@ -50,7 +50,9 @@ func TestJira(t *testing.T) {
}
}
`))
require.NoError(t, err)
}))
defer srv.Close()
t.Run("failure", func(t *testing.T) {

View File

@ -48,7 +48,9 @@ func NewZendeskClient(opts *ZendeskOptions) (*Zendesk, error) {
subparts := strings.Split(url.Host, ".")
subdomain := subparts[0]
client.SetSubdomain(subdomain)
if err := client.SetSubdomain(subdomain); err != nil {
return nil, err
}
client.SetCredential(zendesk.NewAPITokenCredential(opts.Email, opts.APIToken))
return &Zendesk{
@ -154,7 +156,9 @@ func NewZendeskTestClient(opts *ZendeskOptions) (*Zendesk, error) {
return nil, err
}
testURL := fmt.Sprint(opts.URL, "/api/v2")
client.SetEndpointURL(testURL)
if err := client.SetEndpointURL(testURL); err != nil {
return nil, err
}
client.SetCredential(zendesk.NewAPITokenCredential(opts.Email, opts.APIToken))
return &Zendesk{

View File

@ -41,7 +41,8 @@ func TestZendesk(t *testing.T) {
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"ticket": {"id": 35436}}`))
_, err := w.Write([]byte(`{"ticket": {"id": 35436}}`))
require.NoError(t, err)
}))
defer srv.Close()

View File

@ -217,7 +217,7 @@ func addMetrics(r *mux.Router) {
route.Handler(PrometheusMetricsHandler(route.GetName(), route.GetHandler()))
return nil
}
r.Walk(walkFn)
r.Walk(walkFn) //nolint:errcheck
}
// desktopRateLimitMaxBurst is the max burst used for device request rate limiting.

View File

@ -2414,10 +2414,10 @@ func (s *integrationTestSuite) TestHostDeviceMapping() {
require.Len(t, listResp.DeviceMapping, 0)
// create some mappings
s.ds.ReplaceHostDeviceMapping(ctx, hosts[0].ID, []*fleet.HostDeviceMapping{
require.NoError(t, s.ds.ReplaceHostDeviceMapping(ctx, hosts[0].ID, []*fleet.HostDeviceMapping{
{HostID: hosts[0].ID, Email: "a@b.c", Source: "google_chrome_profiles"},
{HostID: hosts[0].ID, Email: "b@b.c", Source: "google_chrome_profiles"},
})
}))
s.DoJSON("GET", fmt.Sprintf("/api/latest/fleet/hosts/%d/device_mapping", hosts[0].ID), nil, http.StatusOK, &listResp)
require.Len(t, listResp.DeviceMapping, 2)
@ -2498,7 +2498,7 @@ func (s *integrationTestSuite) TestListHostsDeviceMappingSize() {
mappings = append(mappings, &fleet.HostDeviceMapping{HostID: hosts[0].ID, Email: testEmail, Source: "google_chrome_profiles"})
}
s.ds.ReplaceHostDeviceMapping(ctx, hosts[0].ID, mappings)
require.NoError(t, s.ds.ReplaceHostDeviceMapping(ctx, hosts[0].ID, mappings))
var listHosts listHostsResponse
s.DoJSON("GET", "/api/latest/fleet/hosts?device_mapping=true", nil, http.StatusOK, &listHosts)
@ -5957,7 +5957,8 @@ func startExternalServiceWebServer(t *testing.T) string {
case "/rest/api/2/project/qux":
switch usr, _, _ := r.BasicAuth(); usr {
case "ok":
w.Write([]byte(jiraProjectResponsePayload))
_, err := w.Write([]byte(jiraProjectResponsePayload))
require.NoError(t, err)
case "fail":
w.WriteHeader(http.StatusUnauthorized)
default:
@ -5966,7 +5967,8 @@ func startExternalServiceWebServer(t *testing.T) string {
case "/rest/api/2/project/qux2":
switch usr, _, _ := r.BasicAuth(); usr {
case "ok":
w.Write([]byte(jiraProjectResponsePayload))
_, err := w.Write([]byte(jiraProjectResponsePayload))
require.NoError(t, err)
case "fail":
w.WriteHeader(http.StatusUnauthorized)
default:
@ -5975,7 +5977,8 @@ func startExternalServiceWebServer(t *testing.T) string {
case "/api/v2/groups/122.json":
switch _, pwd, _ := r.BasicAuth(); pwd {
case "ok":
w.Write([]byte(`{"group": {"id": 122,"name": "test122"}}`))
_, err := w.Write([]byte(`{"group": {"id": 122,"name": "test122"}}`))
require.NoError(t, err)
case "fail":
w.WriteHeader(http.StatusUnauthorized)
default:
@ -5984,7 +5987,8 @@ func startExternalServiceWebServer(t *testing.T) string {
case "/api/v2/groups/123.json":
switch _, pwd, _ := r.BasicAuth(); pwd {
case "ok":
w.Write([]byte(`{"group": {"id": 123,"name": "test123"}}`))
_, err := w.Write([]byte(`{"group": {"id": 123,"name": "test123"}}`))
require.NoError(t, err)
case "fail":
w.WriteHeader(http.StatusUnauthorized)
default:

View File

@ -25,10 +25,10 @@ func (s *integrationTestSuite) TestDeviceAuthenticatedEndpoints() {
require.NoError(t, err)
// create some mappings and MDM/Munki data
s.ds.ReplaceHostDeviceMapping(context.Background(), hosts[0].ID, []*fleet.HostDeviceMapping{
require.NoError(t, s.ds.ReplaceHostDeviceMapping(context.Background(), hosts[0].ID, []*fleet.HostDeviceMapping{
{HostID: hosts[0].ID, Email: "a@b.c", Source: "google_chrome_profiles"},
{HostID: hosts[0].ID, Email: "b@b.c", Source: "google_chrome_profiles"},
})
}))
require.NoError(t, s.ds.SetOrUpdateMDMData(context.Background(), hosts[0].ID, false, true, "url", false, ""))
require.NoError(t, s.ds.SetOrUpdateMunkiInfo(context.Background(), hosts[0].ID, "1.3.0", nil, nil))
// create a battery for hosts[0]
@ -54,8 +54,8 @@ func (s *integrationTestSuite) TestDeviceAuthenticatedEndpoints() {
// get host with valid token
var getHostResp getDeviceHostResponse
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token, nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getHostResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getHostResp))
require.NoError(t, res.Body.Close())
require.Equal(t, hosts[0].ID, getHostResp.Host.ID)
require.False(t, getHostResp.Host.RefetchRequested)
require.Equal(t, "http://example.com/logo", getHostResp.OrgLogoURL)
@ -77,19 +77,19 @@ func (s *integrationTestSuite) TestDeviceAuthenticatedEndpoints() {
// host should have that flag turned to true
getHostResp = getDeviceHostResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token, nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getHostResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getHostResp))
require.NoError(t, res.Body.Close())
require.True(t, getHostResp.Host.RefetchRequested)
// request a refetch for an invalid token
res = s.DoRawNoAuth("POST", "/api/latest/fleet/device/no_such_token/refetch", nil, http.StatusUnauthorized)
res.Body.Close()
require.NoError(t, res.Body.Close())
// list device mappings for valid token
var listDMResp listHostDeviceMappingResponse
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/device_mapping", nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&listDMResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&listDMResp))
require.NoError(t, res.Body.Close())
require.Equal(t, hosts[0].ID, listDMResp.HostID)
require.Len(t, listDMResp.DeviceMapping, 2)
devDMs := listDMResp.DeviceMapping
@ -102,13 +102,13 @@ func (s *integrationTestSuite) TestDeviceAuthenticatedEndpoints() {
// list device mappings for invalid token
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/no_such_token/device_mapping", nil, http.StatusUnauthorized)
res.Body.Close()
require.NoError(t, res.Body.Close())
// get macadmins for valid token
var getMacadm macadminsDataResponse
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/macadmins", nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getMacadm)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getMacadm))
require.NoError(t, res.Body.Close())
require.Equal(t, "1.3.0", getMacadm.Macadmins.Munki.Version)
devMacadm := getMacadm.Macadmins
@ -119,28 +119,28 @@ func (s *integrationTestSuite) TestDeviceAuthenticatedEndpoints() {
// get macadmins for invalid token
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/no_such_token/macadmins", nil, http.StatusUnauthorized)
res.Body.Close()
require.NoError(t, res.Body.Close())
// response includes license info
getHostResp = getDeviceHostResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token, nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getHostResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getHostResp))
require.NoError(t, res.Body.Close())
require.NotNil(t, getHostResp.License)
require.Equal(t, getHostResp.License.Tier, "free")
// device policies are not accessible for free endpoints
listPoliciesResp := listDevicePoliciesResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/policies", nil, http.StatusPaymentRequired)
json.NewDecoder(res.Body).Decode(&getHostResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getHostResp))
require.NoError(t, res.Body.Close())
require.Nil(t, listPoliciesResp.Policies)
// /device/desktop is not accessible for free endpoints
getDesktopResp := fleetDesktopResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/desktop", nil, http.StatusPaymentRequired)
json.NewDecoder(res.Body).Decode(&getDesktopResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getDesktopResp))
require.NoError(t, res.Body.Close())
require.Nil(t, getDesktopResp.FailingPolicies)
}
@ -177,8 +177,8 @@ func (s *integrationTestSuite) TestDefaultTransparencyURL() {
// confirm device endpoint returns initial default url
deviceResp := &transparencyURLResponse{}
rawResp := s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, fleet.DefaultTransparencyURL, rawResp.Header.Get("Location"))
@ -191,8 +191,8 @@ func (s *integrationTestSuite) TestDefaultTransparencyURL() {
// device endpoint returns default url
deviceResp = &transparencyURLResponse{}
rawResp = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, fleet.DefaultTransparencyURL, rawResp.Header.Get("Location"))
@ -203,8 +203,8 @@ func (s *integrationTestSuite) TestDefaultTransparencyURL() {
// device endpoint still returns default url
deviceResp = &transparencyURLResponse{}
rawResp = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, fleet.DefaultTransparencyURL, rawResp.Header.Get("Location"))
}

View File

@ -1321,16 +1321,16 @@ func (s *integrationEnterpriseTestSuite) TestListDevicePolicies() {
// GET `/api/_version_/fleet/device/{token}/policies`
listDevicePoliciesResp := listDevicePoliciesResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/policies", nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&listDevicePoliciesResp)
res.Body.Close()
json.NewDecoder(res.Body).Decode(&listDevicePoliciesResp) //nolint:errcheck
res.Body.Close() //nolint:errcheck
require.Len(t, listDevicePoliciesResp.Policies, 2)
require.NoError(t, listDevicePoliciesResp.Err)
// GET `/api/_version_/fleet/device/{token}`
getDeviceHostResp := getDeviceHostResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token, nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getDeviceHostResp)
res.Body.Close()
json.NewDecoder(res.Body).Decode(&getDeviceHostResp) //nolint:errcheck
res.Body.Close() //nolint:errcheck
require.NoError(t, getDeviceHostResp.Err)
require.Equal(t, host.ID, getDeviceHostResp.Host.ID)
require.False(t, getDeviceHostResp.Host.RefetchRequested)
@ -1340,8 +1340,8 @@ func (s *integrationEnterpriseTestSuite) TestListDevicePolicies() {
// GET `/api/_version_/fleet/device/{token}/desktop`
getDesktopResp := fleetDesktopResponse{}
res = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/desktop", nil, http.StatusOK)
json.NewDecoder(res.Body).Decode(&getDesktopResp)
res.Body.Close()
require.NoError(t, json.NewDecoder(res.Body).Decode(&getDesktopResp))
require.NoError(t, res.Body.Close())
require.NoError(t, getDesktopResp.Err)
require.Equal(t, *getDesktopResp.FailingPolicies, uint(1))
}
@ -1379,8 +1379,8 @@ func (s *integrationEnterpriseTestSuite) TestCustomTransparencyURL() {
// confirm device endpoint returns initial default url
deviceResp := &transparencyURLResponse{}
rawResp := s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, fleet.DefaultTransparencyURL, rawResp.Header.Get("Location"))
@ -1393,8 +1393,8 @@ func (s *integrationEnterpriseTestSuite) TestCustomTransparencyURL() {
// device endpoint returns custom url
deviceResp = &transparencyURLResponse{}
rawResp = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, "customURL", rawResp.Header.Get("Location"))
@ -1407,8 +1407,8 @@ func (s *integrationEnterpriseTestSuite) TestCustomTransparencyURL() {
// device endpoint returns default url
deviceResp = &transparencyURLResponse{}
rawResp = s.DoRawNoAuth("GET", "/api/latest/fleet/device/"+token+"/transparency", nil, http.StatusTemporaryRedirect)
json.NewDecoder(rawResp.Body).Decode(deviceResp)
rawResp.Body.Close()
json.NewDecoder(rawResp.Body).Decode(deviceResp) //nolint:errcheck
rawResp.Body.Close() //nolint:errcheck
require.NoError(t, deviceResp.Err)
require.Equal(t, fleet.DefaultTransparencyURL, rawResp.Header.Get("Location"))
}

View File

@ -1012,7 +1012,7 @@ func TestDetailQueriesWithEmptyStrings(t *testing.T) {
}
// Verify that results are ingested properly
svc.SubmitDistributedQueryResults(ctx, results, map[string]fleet.OsqueryStatus{}, map[string]string{})
require.NoError(t, svc.SubmitDistributedQueryResults(ctx, results, map[string]fleet.OsqueryStatus{}, map[string]string{}))
// osquery_info
assert.Equal(t, "darwin", gotHost.Platform)

View File

@ -349,7 +349,7 @@ func TestScheduleHoldLock(t *testing.T) {
jobDuration := 2100 * time.Millisecond
ml := SetupMockLocker(name, instance, time.Now().Add(-schedInterval))
ml.AddChannels(t, "unlocked")
require.NoError(t, ml.AddChannels(t, "unlocked"))
ms := SetUpMockStatsStore(name, fleet.CronStats{
ID: 1,
@ -407,7 +407,8 @@ func TestMultipleScheduleInstancesConfigChangesDS(t *testing.T) {
ds := mysql.CreateMySQLDS(t)
defer ds.Close()
ds.InsertCronStats(ctx, fleet.CronStatsTypeScheduled, name, "a", fleet.CronStatsStatusCompleted)
_, err := ds.InsertCronStats(ctx, fleet.CronStatsTypeScheduled, name, "a", fleet.CronStatsStatusCompleted)
require.NoError(t, err)
ac, err := ds.AppConfig(ctx)
require.NoError(t, err)
@ -485,13 +486,13 @@ func TestTriggerSingleInstance(t *testing.T) {
schedInterval := 1 * time.Second
jobRuntime := 200 * time.Millisecond
locker := SetupMockLocker(name, instanceID, time.Now().Add(-schedInterval))
locker := SetupMockLocker(name, instanceID, time.Now().Add(-2*schedInterval))
statsStore := SetUpMockStatsStore(name, fleet.CronStats{
ID: 1,
StatsType: fleet.CronStatsTypeScheduled,
Name: name,
Instance: instanceID,
CreatedAt: time.Now().Add(-schedInterval).Add(-jobRuntime),
CreatedAt: time.Now().Add(-2 * schedInterval).Add(-jobRuntime),
UpdatedAt: time.Now().Add(-schedInterval),
Status: fleet.CronStatsStatusCompleted,
})
@ -509,22 +510,33 @@ func TestTriggerSingleInstance(t *testing.T) {
ticker := time.NewTicker(schedInterval) // 1s interval
time.Sleep(100 * time.Millisecond)
s.Trigger() // triggered run starts at 0.1s and runs until 0.3s
s.Trigger() // ignored
s.Trigger() // ignored
s.Trigger() // ignored
s.Trigger() // ignored
_, err := s.Trigger() // triggered run starts at 0.1s and runs until 0.3s
require.NoError(t, err)
_, err = s.Trigger() // ignored
require.NoError(t, err)
_, err = s.Trigger() // ignored
require.NoError(t, err)
_, err = s.Trigger() // ignored
require.NoError(t, err)
_, err = s.Trigger() // ignored
require.NoError(t, err)
<-ticker.C // scheduled run starts at 1s and runs until 1.2s
_, err = s.Trigger() // ignored
require.NoError(t, err)
<-ticker.C // scheduled run starts at 1s and runs until 1.2s
s.Trigger() // ignored
time.Sleep(100 * time.Millisecond)
s.Trigger() // ignored
_, err = s.Trigger() // ignored
require.NoError(t, err)
time.Sleep(200 * time.Millisecond)
s.Trigger() // triggered run starts at 1.3s and runs until 1.5s
_, err = s.Trigger() // triggered run starts at 1.3s and runs until 1.5s
require.NoError(t, err)
<-ticker.C // sheduled run starts at 2s and runs until at 2.2s
time.Sleep(900 * time.Millisecond)
s.Trigger() // triggered run starts at 2.9s and runs until at 3.1s
_, err = s.Trigger() // triggered run starts at 2.9s and runs until at 3.1s
require.NoError(t, err)
<-ticker.C // scheduled run at 3s gets skipped because triggered run is pending
@ -603,7 +615,8 @@ func TestTriggerMultipleInstances(t *testing.T) {
go func() {
time.Sleep(c.triggerDelay)
scheduleInstances[1].Trigger()
_, err := scheduleInstances[1].Trigger()
require.NoError(t, err)
}()
<-timer.C

View File

@ -41,21 +41,21 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
// happened with the actual value for this query.
if err := svc.authz.Authorize(ctx, &fleet.TargetedQuery{Query: &fleet.Query{ObserverCanRun: true}}, fleet.ActionRun); err != nil {
level.Info(svc.logger).Log("err", "stream results authorization failed")
conn.WriteJSONError(authz.ForbiddenErrorMessage)
conn.WriteJSONError(authz.ForbiddenErrorMessage) //nolint:errcheck
return
}
vc, ok := viewer.FromContext(ctx)
if !ok {
level.Info(svc.logger).Log("err", "stream results viewer missing")
conn.WriteJSONError(authz.ForbiddenErrorMessage)
conn.WriteJSONError(authz.ForbiddenErrorMessage) //nolint:errcheck
return
}
// Find the campaign and ensure it is active
campaign, err := svc.ds.DistributedQueryCampaign(ctx, campaignID)
if err != nil {
conn.WriteJSONError(fmt.Sprintf("cannot find campaign for ID %d", campaignID))
conn.WriteJSONError(fmt.Sprintf("cannot find campaign for ID %d", campaignID)) //nolint:errcheck
return
}
@ -66,7 +66,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
"expected", campaign.UserID,
"got", vc.User.ID,
)
conn.WriteJSONError(authz.ForbiddenErrorMessage)
conn.WriteJSONError(authz.ForbiddenErrorMessage) //nolint:errcheck
return
}
@ -74,7 +74,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
// (probably from the redis pubsub implementation)
readChan, cancelFunc, err := svc.GetCampaignReader(ctx, campaign)
if err != nil {
conn.WriteJSONError("error getting campaign reader: " + err.Error())
conn.WriteJSONError("error getting campaign reader: " + err.Error()) //nolint:errcheck
return
}
defer cancelFunc()
@ -82,7 +82,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
// Setting the status to completed stops the query from being sent to
// targets. If this fails, there is a background job that will clean up
// this campaign.
defer svc.CompleteCampaign(ctx, campaign)
defer svc.CompleteCampaign(ctx, campaign) //nolint:errcheck
status := campaignStatus{
Status: campaignStatusPending,
@ -108,7 +108,7 @@ func (svc Service) StreamCampaignResults(ctx context.Context, conn *websocket.Co
targets, err := svc.ds.DistributedQueryCampaignTargetIDs(ctx, campaign.ID)
if err != nil {
conn.WriteJSONError("error retrieving campaign targets: " + err.Error())
conn.WriteJSONError("error retrieving campaign targets: " + err.Error()) //nolint:errcheck
return
}

View File

@ -97,14 +97,14 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
} else {
w.WriteHeader(http.StatusUnprocessableEntity)
}
enc.Encode(ve)
enc.Encode(ve) //nolint:errcheck
case permissionErrorInterface:
pe := jsonError{
Message: "Permission Denied",
Errors: e.PermissionError(),
}
w.WriteHeader(http.StatusForbidden)
enc.Encode(pe)
enc.Encode(pe) //nolint:errcheck
return
case mailError:
me := jsonError{
@ -112,7 +112,7 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
Errors: e.MailError(),
}
w.WriteHeader(http.StatusInternalServerError)
enc.Encode(me)
enc.Encode(me) //nolint:errcheck
case osqueryError:
// osquery expects to receive the node_invalid key when a TLS
// request provides an invalid node_key for authentication. It
@ -132,28 +132,28 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
}
enc.Encode(errMap)
enc.Encode(errMap) //nolint:errcheck
case notFoundErrorInterface:
je := jsonError{
Message: "Resource Not Found",
Errors: baseError(e.Error()),
}
w.WriteHeader(http.StatusNotFound)
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
case existsErrorInterface:
je := jsonError{
Message: "Resource Already Exists",
Errors: baseError(e.Error()),
}
w.WriteHeader(http.StatusConflict)
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
case badRequestErrorInterface:
je := jsonError{
Message: "Bad request",
Errors: baseError(e.Error()),
}
w.WriteHeader(http.StatusBadRequest)
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
case *mysql.MySQLError:
je := jsonError{
Message: "Validation Failed",
@ -164,14 +164,14 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
statusCode = http.StatusConflict
}
w.WriteHeader(statusCode)
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
case *fleet.Error:
je := jsonError{
Message: e.Error(),
Code: e.Code,
}
w.WriteHeader(http.StatusUnprocessableEntity)
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
default:
// when there's a tcp read timeout, the error is *net.OpError but the cause is an internal
// poll.DeadlineExceeded which we cannot match against, so we match against the original error
@ -182,7 +182,7 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
Message: opErr.Error(),
Errors: baseError(opErr.Error()),
}
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
return
}
if fleet.IsForeignKey(err) {
@ -191,7 +191,7 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
Errors: baseError(err.Error()),
}
w.WriteHeader(http.StatusUnprocessableEntity)
enc.Encode(ve)
enc.Encode(ve) //nolint:errcheck
return
}
@ -225,7 +225,7 @@ func encodeError(ctx context.Context, err error, w http.ResponseWriter) {
Message: msg,
Errors: baseError(reason),
}
enc.Encode(je)
enc.Encode(je) //nolint:errcheck
}
}

View File

@ -1283,7 +1283,7 @@ func TestTeamAdminAddRoleOtherTeam(t *testing.T) {
}
ctx = viewer.NewContext(ctx, viewer.Viewer{User: adminTeam2})
adminTeam2.SetPassword("p4ssw0rd.", 10, 10)
require.NoError(t, adminTeam2.SetPassword("p4ssw0rd.1337", 10, 10))
// adminTeam2 tries to add itself to team with ID=3 as admin.
_, err := svc.ModifyUser(ctx, adminTeam2.ID, fleet.UserPayload{

View File

@ -43,7 +43,6 @@ rICQDchR6/cxoQCkoyf+/YTpY492MafV</ds:X509Certificate>
`
func TestParseMetadata(t *testing.T) {
settings, err := ParseMetadata(metadata)
require.Nil(t, err)
@ -59,7 +58,8 @@ func TestParseMetadata(t *testing.T) {
func TestGetMetadata(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(metadata))
_, err := w.Write([]byte(metadata))
require.NoError(t, err)
}))
settings, err := GetMetadata(ts.URL)
require.Nil(t, err)

View File

@ -82,7 +82,8 @@ func TestGithubClient(t *testing.T) {
if r.URL.Path == urlPath {
w.Header().Add("content-type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("some payload"))
_, err := w.Write([]byte("some payload"))
require.NoError(t, err)
}
}))
t.Cleanup(server.Close)

View File

@ -52,7 +52,7 @@ func TestMSRCClient(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/cvrf/v2.0/document/2021-Oct" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("some payload"))
w.Write([]byte("some payload")) //nolint:errcheck
}
}))
t.Cleanup(server.Close)

View File

@ -30,7 +30,7 @@ func TestSecurityBulletin(t *testing.T) {
a.Products["780"] = "Windows 10 C"
a.Products["980"] = "Windows 10 D"
a.Merge(b)
require.NoError(t, a.Merge(b))
require.Equal(t, a.Products["123"], NewProductFromFullName("Windows 10 A"))
require.Equal(t, a.Products["456"], NewProductFromFullName("Windows 10 B"))
@ -63,7 +63,7 @@ func TestSecurityBulletin(t *testing.T) {
b.Vulnerabities["cve-3"] = cve3
b.Vulnerabities["cve-4"] = cve4
a.Merge(b)
require.NoError(t, a.Merge(b))
require.Equal(t, *a.Vulnerabities["cve-1"].PublishedEpoch, int64(123))
require.Equal(t, *a.Vulnerabities["cve-2"].PublishedEpoch, int64(456))
@ -96,7 +96,7 @@ func TestSecurityBulletin(t *testing.T) {
b := NewSecurityBulletin("Windows 10")
b.VendorFixes[2] = vf2
a.Merge(b)
require.NoError(t, a.Merge(b))
require.Equal(t, *a.VendorFixes[1].Supersedes, uint(1))
require.Equal(t, *a.VendorFixes[2].Supersedes, uint(2))

View File

@ -98,7 +98,7 @@ func parseEPSSScoresFile(path string) ([]epssScore, error) {
r.FieldsPerRecord = 3
// skip the header
r.Read()
r.Read() //nolint:errcheck
var epssScores []epssScore
for {

View File

@ -173,7 +173,8 @@ func TestTriggerVulnerabilitiesWebhook(t *testing.T) {
b, err := ioutil.ReadAll(r.Body)
assert.NoError(t, err)
requests = append(requests, string(b))
w.Write(nil)
_, err = w.Write(nil)
assert.NoError(t, err)
}))
defer srv.Close()

View File

@ -52,11 +52,11 @@ func writeJSONMessage(t *testing.T, conn *websocket.Conn, typ string, data inter
require.Nil(t, err)
// Writes from the client to the server do not include the "a"
conn.WriteMessage(websocket.TextMessage, d)
require.NoError(t, conn.WriteMessage(websocket.TextMessage, d))
}
func TestWriteJSONMessage(t *testing.T) {
var cases = []struct {
cases := []struct {
typ string
data interface{}
}{
@ -114,7 +114,7 @@ func TestWriteJSONMessage(t *testing.T) {
}
func TestWriteJSONError(t *testing.T) {
var cases = []struct {
cases := []struct {
err interface{}
}{
{
@ -165,7 +165,7 @@ func TestWriteJSONError(t *testing.T) {
}
func TestReadJSONMessage(t *testing.T) {
var cases = []struct {
cases := []struct {
typ string
data interface{}
err error
@ -243,7 +243,7 @@ func TestReadJSONMessage(t *testing.T) {
}
func TestReadAuthToken(t *testing.T) {
var cases = []struct {
cases := []struct {
typ string
data authData
token string

View File

@ -31,7 +31,7 @@ func TestJiraFailer(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`
_, err := w.Write([]byte(`
{
"id": "10000",
"key": "ED-24",
@ -44,6 +44,7 @@ func TestJiraFailer(t *testing.T) {
}
}
}`))
require.NoError(t, err)
}))
defer srv.Close()
@ -101,7 +102,8 @@ func TestZendeskFailer(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"ticket": {"id": 987}}`))
_, err := w.Write([]byte(`{"ticket": {"id": 987}}`))
require.NoError(t, err)
}))
defer srv.Close()

View File

@ -80,7 +80,7 @@ func TestJiraRun(t *testing.T) {
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`
_, err = w.Write([]byte(`
{
"id": "10000",
"key": "ED-24",
@ -93,6 +93,7 @@ func TestJiraRun(t *testing.T) {
}
}
}`))
require.NoError(t, err)
}))
defer srv.Close()
@ -191,7 +192,6 @@ func TestJiraRun(t *testing.T) {
require.NoError(t, err)
})
}
}
func TestJiraQueueVulnJobs(t *testing.T) {

View File

@ -77,7 +77,8 @@ func TestZendeskRun(t *testing.T) {
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{}`))
_, err = w.Write([]byte(`{}`))
require.NoError(t, err)
}))
defer srv.Close()

View File

@ -27,7 +27,7 @@ import (
func main() {
app := createApp(os.Stdin, os.Stdout, exitErrHandler)
app.Run(os.Args)
app.Run(os.Args) //nolint:errcheck
}
// exitErrHandler implements cli.ExitErrHandlerFunc. If there is an error, prints it to stderr and exits with status 1.

View File

@ -131,7 +131,7 @@ func main() {
return nil
}
app.Run(os.Args)
app.Run(os.Args) //nolint:errcheck
}
func exitErrHandler(c *cli.Context, err error) {