From 4f3156b9865e7e70e5fafb772a9881acc3cd65fc Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Wed, 25 Feb 2026 15:15:44 +0100 Subject: [PATCH 01/11] feat(testify): Use require instead of assert when possible --- .../telemetryimpl/prom_counter_test.go | 13 +- .../telemetry/telemetryimpl/telemetry_test.go | 8 +- .../process/process_collector_test.go | 9 +- pkg/collector/check/stats/stats_test.go | 5 +- .../gpu/integrationtests/check_test.go | 4 +- pkg/compliance/dbconfig/loader_test.go | 13 +- pkg/dyninst/end_to_end_test.go | 4 +- .../missing_type_recompilation_test.go | 4 +- .../procscan/proc_stat_reader_test.go | 22 +--- .../installer/setup/config/write_test.go | 13 +- pkg/network/tracer/tracer_linux_test.go | 34 ++---- pkg/network/tracer/tracer_test.go | 48 ++------ pkg/trace/api/info_test.go | 5 +- pkg/util/executable/executable_test.go | 21 +--- pkg/util/log/log_test.go | 8 +- pkg/util/winutil/eventlog/example_test.go | 4 +- .../subscription/subscription_test.go | 12 +- .../agent-health/docker_permission_test.go | 4 +- .../file-tailing/file_tailing_test.go | 5 +- .../file-tailing/file_tailing_test.go | 4 +- .../tests/agent-runtimes/infra/utils_test.go | 6 +- test/new-e2e/tests/containers/base_test.go | 40 ++----- test/new-e2e/tests/containers/ecs_test.go | 22 +--- test/new-e2e/tests/containers/k8s_test.go | 113 ++++-------------- test/new-e2e/tests/cspm/cspm_test.go | 8 +- test/new-e2e/tests/cws/windows_test.go | 20 +--- .../discovery/process_autodiscovery_test.go | 45 ++----- .../fake_traceroute_test.go | 4 +- test/new-e2e/tests/npm/agentenv_npm_test.go | 5 +- .../tests/npm/cilium_lb_conntracker_test.go | 4 +- .../new-e2e/tests/remote-config/utils_test.go | 5 +- test/new-e2e/tests/sbom/k8s_test.go | 4 +- .../windows/install-test/install_test.go | 13 +- .../windows/install-test/upgrade_test.go | 4 +- 34 files changed, 133 insertions(+), 400 deletions(-) diff --git a/comp/core/telemetry/telemetryimpl/prom_counter_test.go b/comp/core/telemetry/telemetryimpl/prom_counter_test.go index acc37a706514..b2f23a42b9c0 100644 --- a/comp/core/telemetry/telemetryimpl/prom_counter_test.go +++ b/comp/core/telemetry/telemetryimpl/prom_counter_test.go @@ -10,6 +10,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPromCounterInitializer(t *testing.T) { @@ -41,18 +42,12 @@ func TestPromCounterInitializer(t *testing.T) { counter.InitializeToZero("mycheck", "mystate") endMetrics, err := promTelemetry.Gather() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - if !assert.Equal(t, len(endMetrics), 1) { - return - } + require.Equal(t, len(endMetrics), 1) metricFamily := endMetrics[0] - if !assert.Equal(t, len(metricFamily.GetMetric()), 1) { - return - } + require.Equal(t, len(metricFamily.GetMetric()), 1) assert.Equal(t, metricFamily.GetName(), "subsystem_test") diff --git a/comp/core/telemetry/telemetryimpl/telemetry_test.go b/comp/core/telemetry/telemetryimpl/telemetry_test.go index 0f552a7832a2..02969912e0ba 100644 --- a/comp/core/telemetry/telemetryimpl/telemetry_test.go +++ b/comp/core/telemetry/telemetryimpl/telemetry_test.go @@ -24,13 +24,9 @@ func TestCounterInitializer(t *testing.T) { counter.InitializeToZero("mycheck", "mystate") startMetrics, err := telemetry.GetRegistry().Gather() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - if !assert.Equal(t, len(startMetrics), 1) { - return - } + require.Equal(t, len(startMetrics), 1) metrics, err := telemetry.GetCountMetric("subsystem", "test") assert.NoError(t, err) diff --git a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go index 212e2f337180..232e2f061d54 100644 --- a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go +++ b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go @@ -17,6 +17,7 @@ import ( "github.com/benbjohnson/clock" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/mock" "go.uber.org/fx" @@ -692,9 +693,7 @@ func TestProcessDifferentCmdline(t *testing.T) { // Wait for first collection to complete assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { - return - } + require.NoError(cT, err) || !assert.NotNil(cT, actualProc) assert.Equal(cT, []string{"bash"}, actualProc.Cmdline) }, time.Second, time.Millisecond*100) @@ -704,9 +703,7 @@ func TestProcessDifferentCmdline(t *testing.T) { // After exec, the store should have htop, not bash assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { - return - } + require.NoError(cT, err) || !assert.NotNil(cT, actualProc) // Critical assertion: cmdline should be updated to htop after exec assert.Equal(cT, []string{"htop"}, actualProc.Cmdline, "Process cmdline should be updated after exec") assert.Equal(cT, "htop", actualProc.Name, "Process name should be updated after exec") diff --git a/pkg/collector/check/stats/stats_test.go b/pkg/collector/check/stats/stats_test.go index fd2fa4d0e15c..6d378ad736c3 100644 --- a/pkg/collector/check/stats/stats_test.go +++ b/pkg/collector/check/stats/stats_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/comp/core/telemetry/telemetryimpl" healthplatformmock "github.com/DataDog/datadog-agent/comp/healthplatform/mock" @@ -95,9 +96,7 @@ func TestNewStatsStateTelemetryInitialized(t *testing.T) { NewStats(newMockCheck(), healthplatformmock.Mock(t)) tlmData, err := getTelemetryData() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Contains( t, diff --git a/pkg/collector/corechecks/gpu/integrationtests/check_test.go b/pkg/collector/corechecks/gpu/integrationtests/check_test.go index 1ea4646350c3..06e1e3a5304e 100644 --- a/pkg/collector/corechecks/gpu/integrationtests/check_test.go +++ b/pkg/collector/corechecks/gpu/integrationtests/check_test.go @@ -82,9 +82,7 @@ func assertMetricCase(t *testing.T, metricsByName map[string][]mock.Call, tc met t.Helper() calls, ok := metricsByName[tc.name] - if !assert.True(t, ok, "%s metric should be present", tc.name) || !assert.NotEmpty(t, calls, "No calls found for metric %s", tc.name) { - return - } + require.True(t, ok, "%s metric should be present", tc.name) || !assert.NotEmpty(t, calls, "No calls found for metric %s", tc.name) for _, call := range calls { value := call.Arguments[1].(float64) diff --git a/pkg/compliance/dbconfig/loader_test.go b/pkg/compliance/dbconfig/loader_test.go index 40cef04fa794..7e34105767f7 100644 --- a/pkg/compliance/dbconfig/loader_test.go +++ b/pkg/compliance/dbconfig/loader_test.go @@ -20,6 +20,7 @@ import ( "github.com/DataDog/datadog-agent/pkg/compliance/types" "github.com/shirou/gopsutil/v4/process" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDBConfLoader(t *testing.T) { @@ -599,9 +600,7 @@ include_dir 'conf.d' defer stop() c, ok := LoadPostgreSQLConfig(context.Background(), hostroot, proc) - if !assert.True(t, ok) { - return - } + require.True(t, ok) configData := c.ConfigData.(map[string]string) assert.Equal(t, "100", configData["max_connections"]) @@ -665,9 +664,7 @@ work_mem = 16MB c, ok := LoadPostgreSQLConfig(context.Background(), hostroot, proc) assert.True(t, ok) - if !assert.NotNil(t, c) { - return - } + require.NotNil(t, c) configData := c.ConfigData.(map[string]string) assert.Equal(t, "200", configData["max_connections"]) @@ -698,9 +695,7 @@ include 'circular.conf' c, ok := LoadPostgreSQLConfig(context.Background(), hostroot, proc) assert.True(t, ok) - if !assert.NotNil(t, c) { - return - } + require.NotNil(t, c) // Should not crash, circular protection should kick in configData := c.ConfigData.(map[string]string) assert.Equal(t, "100", configData["max_connections"]) diff --git a/pkg/dyninst/end_to_end_test.go b/pkg/dyninst/end_to_end_test.go index a296ad903981..055af5609dc1 100644 --- a/pkg/dyninst/end_to_end_test.go +++ b/pkg/dyninst/end_to_end_test.go @@ -311,9 +311,7 @@ func runE2ETest(t *testing.T, cfg e2eTestConfig) { exp := expected.AsStats() gotKeys := slices.Sorted(maps.Keys(stats)) expectedKeys := slices.Sorted(maps.Keys(exp)) - if !assert.Equal(t, gotKeys, expectedKeys) { - return - } + require.Equal(t, gotKeys, expectedKeys) for _, key := range gotKeys { assert.Equal(t, exp[key], stats[key], "key %s", key) } diff --git a/pkg/dyninst/missing_type_recompilation_test.go b/pkg/dyninst/missing_type_recompilation_test.go index 69223d96ab1a..8203b9dae555 100644 --- a/pkg/dyninst/missing_type_recompilation_test.go +++ b/pkg/dyninst/missing_type_recompilation_test.go @@ -177,9 +177,7 @@ func TestMissingTypeRecompilation(t *testing.T) { require.EventuallyWithT(t, func(c *assert.CollectT) { stats := m.GetStats() actuatorStats, ok := stats["actuator"].(map[string]any) - if !assert.True(c, ok, "actuator stats missing") { - return - } + require.True(c, ok, "actuator stats missing") assert.Equal(c, uint64(0), actuatorStats["numPrograms"], "expected numPrograms == 0 after cleanup") assert.Equal(c, uint64(0), actuatorStats["numProcesses"], diff --git a/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go b/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go index 6ca45dde228f..21f50d9f6bd9 100644 --- a/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go +++ b/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go @@ -95,28 +95,18 @@ func testCases(t testing.TB) iter.Seq[testCase] { filename := filepath.Base(entry) name := strings.TrimSuffix(filename, ".txt") expected, ok := expectedValues[name] - if !assert.True(t, ok, - "test file %s found but no expected values defined", name, - ) { - return - } + require.True(t, ok, + "test file %s found but no expected values defined", name,) delete(expectedValues, name) data, err := testdataFS.ReadFile(entry) - if !assert.NoError(t, err, "failed to read test data") { - return - } + require.NoError(t, err, "failed to read test data") procRoot := filepath.Join(tempDir, name, "proc") pidDir := filepath.Join(procRoot, strconv.FormatInt(int64(expected.pid), 10)) - if !assert.NoError(t, os.MkdirAll(pidDir, 0o755)) { - return - } + require.NoError(t, os.MkdirAll(pidDir, 0o755)) statPath := filepath.Join(pidDir, "stat") - if !assert.NoError( + require.NoError( t, - os.WriteFile(statPath, data, 0o644), - ) { - return - } + os.WriteFile(statPath, data, 0o644),) if !yield(testCase{ name: name, expected: expected, diff --git a/pkg/fleet/installer/setup/config/write_test.go b/pkg/fleet/installer/setup/config/write_test.go index 320c48054baa..c3894e3ac4d2 100644 --- a/pkg/fleet/installer/setup/config/write_test.go +++ b/pkg/fleet/installer/setup/config/write_test.go @@ -13,6 +13,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "golang.org/x/text/encoding" "golang.org/x/text/encoding/unicode" ) @@ -362,9 +363,7 @@ api_key: newkey // The config file may be UTF-16 on Windows t.Run(tc.name+" (UTF-16)", func(t *testing.T) { encoded, err := unicode.UTF16(unicode.LittleEndian, unicode.ExpectBOM).NewEncoder().String(tc.initialYAML) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) tc.initialYAML = encoded runWriteConfigTestCase(t, tc) }) @@ -425,14 +424,10 @@ func TestEnsureUTF8(t *testing.T) { for _, e := range encodings { // encode input to new encoding encoded, err := e.NewEncoder().Bytes(input) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) // convert it back to UTF-8 output, err := ensureUTF8(encoded) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, input, output) // assert output does not contain BOM assert.False(t, bytes.HasPrefix(output, []byte{0xFF, 0xFE}), "output should not have UTF-16LE BOM") diff --git a/pkg/network/tracer/tracer_linux_test.go b/pkg/network/tracer/tracer_linux_test.go index ed5bc7f2182c..d0681fa5e9fb 100644 --- a/pkg/network/tracer/tracer_linux_test.go +++ b/pkg/network/tracer/tracer_linux_test.go @@ -122,9 +122,7 @@ func (s *TracerSuite) TestTCPRemoveEntries() { conns, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c2.LocalAddr(), c2.RemoteAddr(), conns) - if !assert.True(ct, ok) { - return - } + require.True(ct, ok) assert.Equal(ct, clientMessageSize, int(conn.Monotonic.SentBytes)) assert.Equal(ct, 0, int(conn.Monotonic.RecvBytes)) assert.Equal(ct, 0, int(conn.Monotonic.Retransmits)) @@ -324,9 +322,7 @@ func (s *TracerSuite) TestTCPRTT() { allConnections, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), allConnections) - if !assert.True(ct, ok) { - return - } + require.True(ct, ok) if cfg.EnableEbpfless { timeoutUs := uint32((10 * time.Second).Microseconds()) @@ -493,18 +489,14 @@ func (s *TracerSuite) TestConntrackExpiration() { var conn *network.ConnectionStats require.EventuallyWithT(t, func(collect *assert.CollectT) { _, err = c.Write([]byte("ping\n")) - if !assert.NoError(collect, err, "error sending data to server") { - return - } + require.NoError(collect, err, "error sending data to server") connections, cleanup := getConnections(collect, tr) defer cleanup() t.Log(connections) // for debugging failures var ok bool conn, ok = findConnection(c.LocalAddr(), c.RemoteAddr(), connections) - if !assert.True(collect, ok, "connection not found") { - return - } + require.True(collect, ok, "connection not found") assert.NotNil(collect, tr.conntracker.GetTranslationForConn(&conn.ConnectionTuple), "connection does not have NAT translation") }, 3*time.Second, 100*time.Millisecond, "failed to find connection translation") @@ -662,9 +654,7 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv6() { } return cs.DPort == uint16(remoteAddr.Port) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) @@ -2079,10 +2069,8 @@ func (s *TracerSuite) TestBlockingReadCounts() { return true }) - if !assert.NoError(collect, err, "error reading from connection") || - !assert.NoError(collect, readErr, "error from raw conn") { - return - } + require.NoError(collect, err, "error reading from connection") || + !assert.NoError(collect, readErr, "error from raw conn") read += n t.Logf("read %d", read) @@ -2150,9 +2138,7 @@ func (s *TracerSuite) TestPreexistingConnectionDirection() { require.NotNil(collect, outgoing) require.NotNil(collect, incoming) - if !assert.True(collect, incoming != nil && outgoing != nil) { - return - } + require.True(collect, incoming != nil && outgoing != nil) m := outgoing.Monotonic // skip byte counts in ebpfless: for ebpfless pre-existing connections, @@ -3328,9 +3314,7 @@ func (s *TracerSuite) TestTCPRetransmitSyncOnClose() { defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), conns) - if !assert.True(ct, ok, "connection not found") { - return - } + require.True(ct, ok, "connection not found") // We expect retransmits > 0 assert.Greater(ct, int(conn.Monotonic.Retransmits), 0, "should have retransmits") diff --git a/pkg/network/tracer/tracer_test.go b/pkg/network/tracer/tracer_test.go index 40b139fafea7..0d2cb3da4d50 100644 --- a/pkg/network/tracer/tracer_test.go +++ b/pkg/network/tracer/tracer_test.go @@ -1052,24 +1052,16 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim require.EventuallyWithT(t, func(c *assert.CollectT) { dnsClient := new(dns.Client) dnsConn, err := dnsClient.Dial(dnsServerAddr.String()) - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) dnsClientAddr := dnsConn.LocalAddr().(*net.UDPAddr) _, _, err = dnsClient.ExchangeWithConn(queryMsg, dnsConn) if timeout == 0 { - if !assert.NoError(c, err, "unexpected error making DNS request") { - return - } + require.NoError(c, err, "unexpected error making DNS request") } else { - if !assert.Error(c, err) { - return - } + require.Error(c, err) } _ = dnsConn.Close() - if !assert.NoError(c, tr.reverseDNS.WaitForDomain(domain)) { - return - } + require.NoError(c, tr.reverseDNS.WaitForDomain(domain)) // Iterate through active connections until we find connection created above, and confirm send + recv counts connections, cleanup := getConnections(c, tr) @@ -1079,17 +1071,11 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim return } - if !assert.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) { - return - } + require.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) if !tr.config.EnableEbpfless { - if !assert.Equal(c, os.Getpid(), int(conn.Pid)) { - return - } - } - if !assert.Equal(c, dnsServerAddr.Port, int(conn.DPort)) { - return + require.Equal(c, os.Getpid(), int(conn.Pid)) } + require.Equal(c, dnsServerAddr.Port, int(conn.DPort)) var total uint32 var successfulResponses uint32 @@ -1106,15 +1092,9 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim failedResponses := total - successfulResponses // DNS Stats - if !assert.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) { - return - } - if !assert.Equal(c, uint32(failure), failedResponses) { - return - } - if !assert.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) { - return - } + require.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) + require.Equal(c, uint32(failure), failedResponses) + require.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) }, 10*time.Second, 100*time.Millisecond, "Failed to get dns response or unexpected response") } @@ -1251,9 +1231,7 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv4() { return cs.DPort == uint16(remotePort) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) } @@ -1282,9 +1260,7 @@ func (s *TracerSuite) TestConnectedUDPSendIPv6() { outgoing = network.FilterConnections(connections, func(cs network.ConnectionStats) bool { return cs.DPort == uint16(remotePort) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) diff --git a/pkg/trace/api/info_test.go b/pkg/trace/api/info_test.go index daecb81e0ec8..0a3a05810675 100644 --- a/pkg/trace/api/info_test.go +++ b/pkg/trace/api/info_test.go @@ -18,6 +18,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/pkg/obfuscate" "github.com/DataDog/datadog-agent/pkg/trace/config" @@ -365,9 +366,7 @@ func TestInfoHandler(t *testing.T) { req.Header.Add("Datadog-Container-ID", "id1") h.ServeHTTP(rec, req) var m map[string]any - if !assert.NoError(t, json.NewDecoder(rec.Body).Decode(&m)) { - return - } + require.NoError(t, json.NewDecoder(rec.Body).Decode(&m)) assert.NoError(t, ensureKeys(expectedKeys, m, "")) expectedContainerHash := fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join([]string{"kube_cluster_name:clusterA", "kube_namespace:namespace1"}, ",")))) assert.Equal(t, expectedContainerHash, rec.Header().Get(containerTagsHashHeader)) diff --git a/pkg/util/executable/executable_test.go b/pkg/util/executable/executable_test.go index bfc6354c1550..312d40c2b48a 100644 --- a/pkg/util/executable/executable_test.go +++ b/pkg/util/executable/executable_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestResolvePath(t *testing.T) { @@ -23,13 +24,9 @@ func TestResolvePath(t *testing.T) { } actualPath, err := ResolvePath(testProgram) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) - if !assert.NotEmpty(t, actualPath) { - return - } + require.NotEmpty(t, actualPath) if _, err := os.Stat(actualPath); os.IsNotExist(err) { assert.FailNowf(t, "Resolved path '%s' does not exist!", actualPath) @@ -43,14 +40,10 @@ func TestResolvePathIsAbsolute(t *testing.T) { } actualPath, err := ResolvePath(testProgram) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) absPath, err := filepath.Abs(actualPath) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, absPath, actualPath) } @@ -59,7 +52,5 @@ func TestResolvePathFailure(t *testing.T) { testProgram := "badprogramname" _, err := ResolvePath(testProgram) - if !assert.NotNil(t, err) { - return - } + require.NotNil(t, err) } diff --git a/pkg/util/log/log_test.go b/pkg/util/log/log_test.go index e1eb8d525b19..d1dcefc31a07 100644 --- a/pkg/util/log/log_test.go +++ b/pkg/util/log/log_test.go @@ -541,14 +541,10 @@ func TestLoggerScrubbingCount(t *testing.T) { for _, fun := range tc.funcs { val := reflect.ValueOf(fun) funcName, err := getFuncName(val) - if !assert.NoError(t, err) { - continue - } + require.NoError(t, err) valTy := reflect.TypeOf(fun) - if !assert.Equalf(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) { - continue - } + require.Equalf(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) // create a slice of reflect.Value from the args reflArgs := make([]reflect.Value, 0, len(tc.args)) diff --git a/pkg/util/winutil/eventlog/example_test.go b/pkg/util/winutil/eventlog/example_test.go index a8dff42becb8..60d63eef52e7 100644 --- a/pkg/util/winutil/eventlog/example_test.go +++ b/pkg/util/winutil/eventlog/example_test.go @@ -45,9 +45,7 @@ func testSubscriptionExample(t testing.TB, ti eventlog_test.APITester, stop chan // Start the subscription err := sub.Start() - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) // Cleanup the subscription when done defer sub.Stop() diff --git a/pkg/util/winutil/eventlog/subscription/subscription_test.go b/pkg/util/winutil/eventlog/subscription/subscription_test.go index 01c651c43746..30940a757cb7 100644 --- a/pkg/util/winutil/eventlog/subscription/subscription_test.go +++ b/pkg/util/winutil/eventlog/subscription/subscription_test.go @@ -409,9 +409,7 @@ func (s *GetEventsTestSuite) TestStopWhileWaitingWithEventsAvailable() { // Read not all of the events _, err := ReadNumEvents(s.T(), s.ti, sub, batchCount) close(readyToStop) - if !assert.NoError(s.T(), err) { - return - } + require.NoError(s.T(), err) // Purposefully don't read the rest of the events. This leaves the signal event set. // Wait for Stop() to finish <-stopped @@ -443,9 +441,7 @@ func (s *GetEventsTestSuite) TestStopWhileWaitingWithNoMoreItemseNotFinalized() // Read all events _, err := getEventHandles(s.T(), s.ti, sub, s.numEvents) close(readyToStop) - if !assert.NoError(s.T(), err) { - return - } + require.NoError(s.T(), err) // Purposefully don't call EvtNext the final time when it would normally return ERROR_NO_MORE_ITEMS. // This leaves the signal event set. // Wait for Stop() to finish @@ -792,9 +788,7 @@ func (s *GetEventsTestSuite) TestReadWhenNoMoreEvents() { eventRecords, err := getEventHandles(s.T(), s.ti, sub, 2*s.numEvents) require.NoError(s.T(), err) count := uint(len(eventRecords)) - if !assert.Equal(s.T(), 2*s.numEvents, count, fmt.Sprintf("Missing events, collected %d/%d events", count, 2*s.numEvents)) { - return - } + require.Equal(s.T(), 2*s.numEvents, count, fmt.Sprintf("Missing events, collected %d/%d events", count, 2*s.numEvents)) err = assertNoMoreEvents(s.T(), sub) require.NoError(s.T(), err) diff --git a/test/new-e2e/tests/agent-health/docker_permission_test.go b/test/new-e2e/tests/agent-health/docker_permission_test.go index 9a6740ad479c..4a9d50e3391c 100644 --- a/test/new-e2e/tests/agent-health/docker_permission_test.go +++ b/test/new-e2e/tests/agent-health/docker_permission_test.go @@ -136,9 +136,7 @@ func (suite *dockerPermissionSuite) TestDockerPermissionIssueLifecycle() { var postRestartIssue *healthplatform.Issue require.EventuallyWithT(t, func(ct *assert.CollectT) { payloads, err := fakeIntake.GetAgentHealth() - if !assert.NoError(ct, err) || !assert.NotEmpty(ct, payloads, "Should receive health report after restart") { - return - } + require.NoError(ct, err) || !assert.NotEmpty(ct, payloads, "Should receive health report after restart") latest := payloads[len(payloads)-1] postRestartIssue = findIssue(t, latest, expectedIssueID) assert.NotNil(ct, postRestartIssue, "Docker permission issue should still be present after restart") diff --git a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go index fa5a89640bc3..d4a75ea55717 100644 --- a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go @@ -16,6 +16,7 @@ import ( "github.com/DataDog/datadog-agent/test/new-e2e/tests/agent-log-pipelines/utils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/components/datadog/agentparams" scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" @@ -61,9 +62,7 @@ func (s *LinuxFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { - return - } + require.NoError(c, err, "Unable to filter logs by the service 'hello'.") // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected.") { cat, _ := s.Env().RemoteHost.Execute(fmt.Sprintf("cat %s && cat %s/hello-world-2.log", logFilePath, utils.LinuxLogsFolderPath)) diff --git a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go index e966bc1e0827..2b6a9810ee48 100644 --- a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go @@ -61,9 +61,7 @@ func (s *WindowsFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { - return - } + require.NoError(c, err, "Unable to filter logs by the service 'hello'.") // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected") { cat, _ := s.Env().RemoteHost.Execute("type " + logFilePath) diff --git a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go index 64f2cfbb5ab4..e08f97ae253f 100644 --- a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go +++ b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/environments" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/testcommon/check" @@ -93,10 +94,7 @@ func verifyCheckRuns(t *testing.T, env *environments.Host, checkName string) boo // by querying the agent status API. This is a helper function meant to be called within EventuallyWithT. func verifyCheckSchedulingViaStatusAPI(t *testing.T, c *assert.CollectT, env *environments.Host, checks []string, shouldBeScheduled bool) { scheduledChecks, err := getScheduledChecks(env) - if !assert.NoError(c, err, "Failed to get scheduled checks") { - t.Logf("Failed to retrieve scheduled checks, will retry...") - return - } + require.NoError(c, err, "Failed to get scheduled checks") t.Logf("Found %d check types in agent status", len(scheduledChecks)) diff --git a/test/new-e2e/tests/containers/base_test.go b/test/new-e2e/tests/containers/base_test.go index 692f36111cbb..da39d8b28594 100644 --- a/test/new-e2e/tests/containers/base_test.go +++ b/test/new-e2e/tests/containers/base_test.go @@ -164,14 +164,8 @@ func (suite *baseSuite[Env]) testMetric(args *testMetricArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.MetricSeries](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) // Check tags if expectedTags != nil { @@ -293,14 +287,8 @@ func (suite *baseSuite[Env]) testLog(args *testLogArgs) { args.Filter.Service, fakeintake.WithMatchingTags[*aggregator.Log](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) // Check tags if expectedTags != nil { @@ -426,14 +414,8 @@ func (suite *baseSuite[Env]) testCheckRun(args *testCheckRunArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.CheckRun](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) // Check tags if expectedTags != nil { @@ -539,14 +521,8 @@ func (suite *baseSuite[Env]) testEvent(args *testEventArgs) { args.Filter.Source, fakeintake.WithMatchingTags[*aggregator.Event](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) // Check tags if expectedTags != nil { diff --git a/test/new-e2e/tests/containers/ecs_test.go b/test/new-e2e/tests/containers/ecs_test.go index e0f0bcacc10f..22b7bb4a9f37 100644 --- a/test/new-e2e/tests/containers/ecs_test.go +++ b/test/new-e2e/tests/containers/ecs_test.go @@ -118,10 +118,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(10)), // Because `DescribeServices` takes at most 10 services in input NextToken: nextToken, }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list ECS services") { - return - } + require.NoErrorf(c, err, "Failed to list ECS services") nextToken = servicesList.NextToken @@ -129,9 +126,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { Cluster: &suite.ecsClusterName, Services: servicesList.ServiceArns, }) - if !assert.NoErrorf(c, err, "Failed to describe ECS services %v", servicesList.ServiceArns) { - continue - } + require.NoErrorf(c, err, "Failed to describe ECS services %v", servicesList.ServiceArns) for _, serviceDescription := range servicesDescription.Services { assert.NotZerof(c, serviceDescription.DesiredCount, "ECS service %s has no task", *serviceDescription.ServiceName) @@ -148,9 +143,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(100)), // Because `DescribeTasks` takes at most 100 tasks in input NextToken: nextToken, }) - if !assert.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) { - break - } + require.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) nextToken = tasksList.NextToken @@ -158,9 +151,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { Cluster: &suite.ecsClusterName, Tasks: tasksList.TaskArns, }) - if !assert.NoErrorf(c, err, "Failed to describe ECS tasks %v", tasksList.TaskArns) { - continue - } + require.NoErrorf(c, err, "Failed to describe ECS tasks %v", tasksList.TaskArns) for _, taskDescription := range tasksDescription.Tasks { assert.Equalf(c, string(awsecstypes.DesiredStatusRunning), *taskDescription.LastStatus, @@ -614,10 +605,7 @@ func (suite *ecsSuite) TestTraceTCP() { func (suite *ecsSuite) testTrace(taskName string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { - return - } + require.NoErrorf(c, cerr, "Failed to query fake intake") var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/containers/k8s_test.go b/test/new-e2e/tests/containers/k8s_test.go index 4dd264f12c9b..acbafffc5ac5 100644 --- a/test/new-e2e/tests/containers/k8s_test.go +++ b/test/new-e2e/tests/containers/k8s_test.go @@ -128,58 +128,37 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { fields.OneTermNotEqualSelector("eks.amazonaws.com/compute-type", "fargate"), ).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list Linux nodes") { - return - } + require.NoErrorf(c, err, "Failed to list Linux nodes") windowsNodes, err := suite.Env().KubernetesCluster.Client().CoreV1().Nodes().List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("kubernetes.io/os", "windows").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list Windows nodes") { - return - } + require.NoErrorf(c, err, "Failed to list Windows nodes") linuxPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxNodeAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list Linux datadog agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list Linux datadog agent pods") windowsPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.WindowsNodeAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list Windows datadog agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list Windows datadog agent pods") clusterAgentPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list datadog cluster agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list datadog cluster agent pods") clusterChecksPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterChecks.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") { - return - } + require.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") dogstatsdPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("dogstatsd-standalone").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", "dogstatsd-standalone").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") { - return - } + require.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") assert.Len(c, linuxPods.Items, len(linuxNodes.Items)) assert.Len(c, windowsPods.Items, len(windowsNodes.Items)) @@ -348,10 +327,7 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"agent", "check", "-t", "3", "container", "--table", "--delay", "1000", "--pause", "5000"}) - // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) matched, err := regexp.MatchString(`container\.memory\.usage\s+gauge\s+\d+\s+\d+`, stdout) if assert.NoError(c, err) { assert.Truef(c, matched, "Output of `agent check -r container` doesn’t contain the expected metric") @@ -366,10 +342,7 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"env", "DD_LOG_LEVEL=off", "agent", "check", "-r", "container", "--table", "--delay", "1000", "--json"}) - // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if !assert.Truef(c, json.Valid([]byte(stdout)), "Output of `agent check -r container --json` isn’t valid JSON") { var blob interface{} err := json.Unmarshal([]byte(stdout), &blob) @@ -1644,14 +1617,8 @@ func (suite *k8sSuite) TestContainerImage() { }() images, err := suite.Fakeintake.FilterContainerImages("ghcr.io/datadog/apps-nginx-server") - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, images, "No container_image yet") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, images, "No container_image yet") expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), @@ -1714,19 +1681,13 @@ func (suite *k8sSuite) TestSBOM() { }() sbomIDs, err := suite.Fakeintake.GetSBOMIDs() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") sbomIDs = lo.Filter(sbomIDs, func(id string, _ int) bool { return strings.HasPrefix(id, "ghcr.io/datadog/apps-nginx-server") }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") { - return - } + require.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") images := lo.FlatMap(sbomIDs, func(id string, _ int) []*aggregator.SBOMPayload { images, err := suite.Fakeintake.FilterSBOMs(id) @@ -1734,19 +1695,13 @@ func (suite *k8sSuite) TestSBOM() { return images }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, images, "No SBOM payload yet") { - return - } + require.NotEmptyf(c, images, "No SBOM payload yet") images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { return image.Status == sbom.SBOMStatus_SUCCESS }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, images, "No successful SBOM yet") { - return - } + require.NotEmptyf(c, images, "No successful SBOM yet") images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { cyclonedx := image.GetCyclonedx() @@ -1755,15 +1710,10 @@ func (suite *k8sSuite) TestSBOM() { cyclonedx.Metadata.Component != nil }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NotEmptyf(c, images, "No SBOM with complete CycloneDX") { - return - } + require.NotEmptyf(c, images, "No SBOM with complete CycloneDX") for _, image := range images { - if !assert.NotNil(c, image.GetCyclonedx().Metadata.Component.Properties) { - continue - } + require.NotNil(c, image.GetCyclonedx().Metadata.Component.Properties) expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), @@ -1830,13 +1780,8 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { LabelSelector: fields.OneTermEqualSelector("app", "nginx").String(), FieldSelector: fields.OneTermEqualSelector("status.phase", "Running").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to list nginx pods") { - return - } - if !assert.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") { - return - } + require.NoErrorf(c, err, "Failed to list nginx pods") + require.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") // Choose the oldest pod. // If we choose a pod that is too recent, there is a risk that we delete a pod that hasn’t been seen by the agent yet. @@ -1866,10 +1811,7 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { }() events, err := suite.Fakeintake.GetContainerLifecycleEvents() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") foundPodEvent := false @@ -1925,14 +1867,8 @@ func (suite *k8sSuite) testHPA(namespace, deployment string) { "kube_deployment:" + deployment, }), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) { - sendEvent("warning", fmt.Sprintf("No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment), nil) - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) // Check HPA is properly scaling up or down // This indirectly tests the cluster-agent external metrics server @@ -1975,10 +1911,7 @@ func (suite *k8sSuite) TestTraceTCP() { func (suite *k8sSuite) testTrace(kubeDeployment string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { - return - } + require.NoErrorf(c, cerr, "Failed to query fake intake") var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/cspm/cspm_test.go b/test/new-e2e/tests/cspm/cspm_test.go index 91b2f7aa5a60..b49de90762b0 100644 --- a/test/new-e2e/tests/cspm/cspm_test.go +++ b/test/new-e2e/tests/cspm/cspm_test.go @@ -204,9 +204,7 @@ func (s *cspmTestSuite) TestMetrics() { assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.running") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.running") } @@ -215,9 +213,7 @@ func (s *cspmTestSuite) TestMetrics() { s.T().Log("Waiting for datadog.security_agent.compliance.containers_running metrics") assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.containers_running") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.containers_running") } diff --git a/test/new-e2e/tests/cws/windows_test.go b/test/new-e2e/tests/cws/windows_test.go index 22f400c5c8c1..9c1a5cd4de1b 100644 --- a/test/new-e2e/tests/cws/windows_test.go +++ b/test/new-e2e/tests/cws/windows_test.go @@ -202,24 +202,14 @@ func (a *agentSuiteWindows) Test03CreateFileSignal() { // Check app signal assert.EventuallyWithT(a.T(), func(c *assert.CollectT) { signal, err := a.apiClient.GetSignal(fmt.Sprintf("host:%s @workflow.rule.id:%s", a.Env().Agent.Client.Hostname(), signalRuleID)) - if !assert.NoError(c, err) { - return - } - if !assert.NotNil(c, signal) { - return - } + require.NoError(c, err) + require.NotNil(c, signal) assert.Contains(c, signal.Tags, "rule_id:"+strings.ToLower(agentRuleName), "unable to find rule_id tag") - if !assert.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") { - return - } + require.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") attributes := signal.AdditionalProperties["attributes"].(map[string]interface{}) - if !assert.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") { - return - } + require.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") agentContext := attributes["agent"].(map[string]interface{}) - if !assert.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") { - return - } + require.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") assert.Contains(c, agentContext["rule_id"], agentRuleName, "signal doesn't contain agent rule id") }, 4*time.Minute, 10*time.Second) } diff --git a/test/new-e2e/tests/discovery/process_autodiscovery_test.go b/test/new-e2e/tests/discovery/process_autodiscovery_test.go index b59f2923e077..d5c0a8678f71 100644 --- a/test/new-e2e/tests/discovery/process_autodiscovery_test.go +++ b/test/new-e2e/tests/discovery/process_autodiscovery_test.go @@ -110,38 +110,23 @@ func (s *processAutodiscoverySuite) verifyRedisCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - if !assert.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") // Verify the check has cel://process AD identifier - if !assert.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") // Verify host was resolved to localhost - if !assert.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - if !assert.NoError(c, err, "failed to parse agent status") { - t.Logf("Failed to parse status output: %s", statusOutput) - return - } + require.NoError(c, err, "failed to parse agent status") instances, exists := status.RunnerStats.Checks["redisdb"] - if !assert.True(c, exists, "redisdb check should be running") { - t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) - return - } + require.True(c, exists, "redisdb check should be running") // Verify the check has executed successfully for instanceName, checkStat := range instances { @@ -178,32 +163,20 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - if !assert.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") // Verify the check has cel://process AD identifier - if !assert.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - if !assert.NoError(c, err, "failed to parse agent status") { - t.Logf("Failed to parse status output: %s", statusOutput) - return - } + require.NoError(c, err, "failed to parse agent status") instances, exists := status.RunnerStats.Checks["nginx"] - if !assert.True(c, exists, "nginx check should be running") { - t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) - return - } + require.True(c, exists, "nginx check should be running") // Key assertion: exactly 1 nginx check instance despite multiple nginx processes assert.Equal(c, 1, len(instances), "expected exactly 1 nginx check instance, got %d", len(instances)) diff --git a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go index 7a787bc54dd9..283cd58c844f 100644 --- a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go +++ b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go @@ -116,9 +116,7 @@ func (s *fakeTracerouteTestSuite) TestFakeTraceroute() { assert.EventuallyWithT(t, func(c *assert.CollectT) { nps, err := s.Env().FakeIntake.Client().GetLatestNetpathEvents() assert.NoError(c, err, "GetLatestNetpathEvents() errors") - if !assert.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") { - return - } + require.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") udpPath := s.expectNetpath(c, func(np *aggregator.Netpath) bool { return np.Destination.Hostname == targetIP.String() && np.Protocol == "UDP" diff --git a/test/new-e2e/tests/npm/agentenv_npm_test.go b/test/new-e2e/tests/npm/agentenv_npm_test.go index 2c3b4ff2e960..5849903783d9 100644 --- a/test/new-e2e/tests/npm/agentenv_npm_test.go +++ b/test/new-e2e/tests/npm/agentenv_npm_test.go @@ -17,6 +17,7 @@ import ( scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type vmSuiteEx6 struct { @@ -41,9 +42,7 @@ func (v *vmSuiteEx6) Test1_FakeIntakeNPM() { v.Env().RemoteHost.MustExecute("curl http://www.datadoghq.com") hostnameNetID, err := v.Env().FakeIntake.Client().GetConnectionsNames() - if !assert.NoError(c, err, "fakeintake GetConnectionsNames() error") { - return - } + require.NoError(c, err, "fakeintake GetConnectionsNames() error") if assert.NotZero(c, len(hostnameNetID), "no connections yet") { t.Logf("hostname+networkID %v seen connections", hostnameNetID) diff --git a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go index 321dd4ac1a70..c08d55095982 100644 --- a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go +++ b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go @@ -137,9 +137,7 @@ func (suite *ciliumLBConntrackerTestSuite) TestCiliumConntracker() { return } - if !assert.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") { - return - } + require.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") svcConns = append(svcConns, c) } diff --git a/test/new-e2e/tests/remote-config/utils_test.go b/test/new-e2e/tests/remote-config/utils_test.go index 47b4d2bc226a..19f0a199f4ff 100644 --- a/test/new-e2e/tests/remote-config/utils_test.go +++ b/test/new-e2e/tests/remote-config/utils_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/components" ) @@ -32,9 +33,7 @@ func assertAgentLogsEventually(t *testing.T, rh *components.RemoteHost, agentNam assert.EventuallyWithTf(t, func(c *assert.CollectT) { // read agent logs agentLogs, err := rh.ReadFilePrivileged(remoteLogsPath) - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) logs := string(agentLogs) for _, log := range missingLogs { if strings.Contains(logs, log) { diff --git a/test/new-e2e/tests/sbom/k8s_test.go b/test/new-e2e/tests/sbom/k8s_test.go index 438c27183303..9a77f9d9ce53 100644 --- a/test/new-e2e/tests/sbom/k8s_test.go +++ b/test/new-e2e/tests/sbom/k8s_test.go @@ -312,9 +312,7 @@ func (suite *k8sSuite) TestSBOM() { for _, image := range images { cyclonedx := image.GetCyclonedx() - if !assert.NotNil(c, cyclonedx.Metadata.Component.Properties) { - continue - } + require.NotNil(c, cyclonedx.Metadata.Component.Properties) expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), diff --git a/test/new-e2e/tests/windows/install-test/install_test.go b/test/new-e2e/tests/windows/install-test/install_test.go index f41b2332da49..b3b61a07ca33 100644 --- a/test/new-e2e/tests/windows/install-test/install_test.go +++ b/test/new-e2e/tests/windows/install-test/install_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -423,16 +424,10 @@ func (s *testInstallOptsSuite) TestInstallOpts() { var boundPort boundport.BoundPort s.Require().EventuallyWithTf(func(c *assert.CollectT) { pid, err := windowsCommon.GetServicePID(vm, "DatadogAgent") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) boundPort, err = common.GetBoundPort(vm, "tcp", cmdPort) - if !assert.NoError(c, err) { - return - } - if !assert.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) { - return - } + require.NoError(c, err) + require.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) assert.Equalf(c, pid, boundPort.PID(), "port tcp/%d should be bound by the agent", cmdPort) }, 1*time.Minute, 500*time.Millisecond, "port tcp/%d should be bound by the agent", cmdPort) s.Require().EqualValues("127.0.0.1", boundPort.LocalAddress(), "agent should only be listening locally") diff --git a/test/new-e2e/tests/windows/install-test/upgrade_test.go b/test/new-e2e/tests/windows/install-test/upgrade_test.go index 3d056f1ee9f3..ab4748478c0a 100644 --- a/test/new-e2e/tests/windows/install-test/upgrade_test.go +++ b/test/new-e2e/tests/windows/install-test/upgrade_test.go @@ -403,9 +403,7 @@ func (s *testUpgradeFromV5Suite) installAgent5() { s.Assert().EventuallyWithT(func(t *assert.CollectT) { cmd := fmt.Sprintf(`& "%s\embedded\python.exe" "%s\agent\agent.py" info`, installPath, installPath) out, err := host.Execute(cmd) - if !assert.NoError(t, err, "should get agent info") { - return - } + require.NoError(t, err, "should get agent info") s.T().Logf("Agent 5 info:\n%s", out) assert.Contains(t, out, agentPackage.AgentVersion(), "info should have agent 5 version") }, 5*time.Minute, 5*time.Second, "should get agent 5 info") From 55b3c4bf686255c1eadf4302169e6f31dea3a808 Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Wed, 25 Feb 2026 17:35:22 +0100 Subject: [PATCH 02/11] fix(tests): Split combined assert||assert guards into separate require calls require functions don't return a value (unlike assert which returns bool), so they can't be used in || expressions. Split combined conditions into separate require calls. --- .../collectors/internal/process/process_collector_test.go | 6 ++++-- pkg/collector/corechecks/gpu/integrationtests/check_test.go | 3 ++- pkg/network/tracer/tracer_linux_test.go | 4 ++-- test/new-e2e/tests/agent-health/docker_permission_test.go | 3 ++- 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go index 232e2f061d54..90b77aceb0e3 100644 --- a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go +++ b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go @@ -693,7 +693,8 @@ func TestProcessDifferentCmdline(t *testing.T) { // Wait for first collection to complete assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - require.NoError(cT, err) || !assert.NotNil(cT, actualProc) + require.NoError(cT, err) + require.NotNil(cT, actualProc) assert.Equal(cT, []string{"bash"}, actualProc.Cmdline) }, time.Second, time.Millisecond*100) @@ -703,7 +704,8 @@ func TestProcessDifferentCmdline(t *testing.T) { // After exec, the store should have htop, not bash assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - require.NoError(cT, err) || !assert.NotNil(cT, actualProc) + require.NoError(cT, err) + require.NotNil(cT, actualProc) // Critical assertion: cmdline should be updated to htop after exec assert.Equal(cT, []string{"htop"}, actualProc.Cmdline, "Process cmdline should be updated after exec") assert.Equal(cT, "htop", actualProc.Name, "Process name should be updated after exec") diff --git a/pkg/collector/corechecks/gpu/integrationtests/check_test.go b/pkg/collector/corechecks/gpu/integrationtests/check_test.go index 06e1e3a5304e..65ca3018d064 100644 --- a/pkg/collector/corechecks/gpu/integrationtests/check_test.go +++ b/pkg/collector/corechecks/gpu/integrationtests/check_test.go @@ -82,7 +82,8 @@ func assertMetricCase(t *testing.T, metricsByName map[string][]mock.Call, tc met t.Helper() calls, ok := metricsByName[tc.name] - require.True(t, ok, "%s metric should be present", tc.name) || !assert.NotEmpty(t, calls, "No calls found for metric %s", tc.name) + require.True(t, ok, "%s metric should be present", tc.name) + require.NotEmpty(t, calls, "No calls found for metric %s", tc.name) for _, call := range calls { value := call.Arguments[1].(float64) diff --git a/pkg/network/tracer/tracer_linux_test.go b/pkg/network/tracer/tracer_linux_test.go index d0681fa5e9fb..deec3cdd61a0 100644 --- a/pkg/network/tracer/tracer_linux_test.go +++ b/pkg/network/tracer/tracer_linux_test.go @@ -2069,8 +2069,8 @@ func (s *TracerSuite) TestBlockingReadCounts() { return true }) - require.NoError(collect, err, "error reading from connection") || - !assert.NoError(collect, readErr, "error from raw conn") + require.NoError(collect, err, "error reading from connection") + require.NoError(collect, readErr, "error from raw conn") read += n t.Logf("read %d", read) diff --git a/test/new-e2e/tests/agent-health/docker_permission_test.go b/test/new-e2e/tests/agent-health/docker_permission_test.go index 4a9d50e3391c..bfd7bbed24b3 100644 --- a/test/new-e2e/tests/agent-health/docker_permission_test.go +++ b/test/new-e2e/tests/agent-health/docker_permission_test.go @@ -136,7 +136,8 @@ func (suite *dockerPermissionSuite) TestDockerPermissionIssueLifecycle() { var postRestartIssue *healthplatform.Issue require.EventuallyWithT(t, func(ct *assert.CollectT) { payloads, err := fakeIntake.GetAgentHealth() - require.NoError(ct, err) || !assert.NotEmpty(ct, payloads, "Should receive health report after restart") + require.NoError(ct, err) + require.NotEmpty(ct, payloads, "Should receive health report after restart") latest := payloads[len(payloads)-1] postRestartIssue = findIssue(t, latest, expectedIssueID) assert.NotNil(ct, postRestartIssue, "Docker permission issue should still be present after restart") From 199776088c5175a6868e036ad4cbb5f6cd2f42de Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Wed, 25 Feb 2026 18:41:45 +0100 Subject: [PATCH 03/11] fix(tests): Fix linter errors from assert-to-require migration - Fix gofmt import ordering in process_collector_test.go - Remove unused getCheckNames function in process_autodiscovery_test.go (was only used in debug logging lines that were removed) - Revert require.Equal back to assert.Equal in end_to_end_test.go where the variable t is assert.TestingT (which lacks FailNow required by require) --- .../internal/process/process_collector_test.go | 2 +- pkg/dyninst/end_to_end_test.go | 2 +- .../procsubscribe/procscan/proc_stat_reader_test.go | 5 ++--- .../tests/discovery/process_autodiscovery_test.go | 9 --------- 4 files changed, 4 insertions(+), 14 deletions(-) diff --git a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go index 90b77aceb0e3..6ce80fc3db65 100644 --- a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go +++ b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go @@ -17,8 +17,8 @@ import ( "github.com/benbjohnson/clock" "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "go.uber.org/fx" "github.com/DataDog/datadog-agent/comp/core/config" diff --git a/pkg/dyninst/end_to_end_test.go b/pkg/dyninst/end_to_end_test.go index 055af5609dc1..ac84b306fd01 100644 --- a/pkg/dyninst/end_to_end_test.go +++ b/pkg/dyninst/end_to_end_test.go @@ -311,7 +311,7 @@ func runE2ETest(t *testing.T, cfg e2eTestConfig) { exp := expected.AsStats() gotKeys := slices.Sorted(maps.Keys(stats)) expectedKeys := slices.Sorted(maps.Keys(exp)) - require.Equal(t, gotKeys, expectedKeys) + assert.Equal(t, gotKeys, expectedKeys) for _, key := range gotKeys { assert.Equal(t, exp[key], stats[key], "key %s", key) } diff --git a/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go b/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go index 21f50d9f6bd9..8bd7262cc92d 100644 --- a/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go +++ b/pkg/dyninst/procsubscribe/procscan/proc_stat_reader_test.go @@ -19,7 +19,6 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -96,7 +95,7 @@ func testCases(t testing.TB) iter.Seq[testCase] { name := strings.TrimSuffix(filename, ".txt") expected, ok := expectedValues[name] require.True(t, ok, - "test file %s found but no expected values defined", name,) + "test file %s found but no expected values defined", name) delete(expectedValues, name) data, err := testdataFS.ReadFile(entry) require.NoError(t, err, "failed to read test data") @@ -106,7 +105,7 @@ func testCases(t testing.TB) iter.Seq[testCase] { statPath := filepath.Join(pidDir, "stat") require.NoError( t, - os.WriteFile(statPath, data, 0o644),) + os.WriteFile(statPath, data, 0o644)) if !yield(testCase{ name: name, expected: expected, diff --git a/test/new-e2e/tests/discovery/process_autodiscovery_test.go b/test/new-e2e/tests/discovery/process_autodiscovery_test.go index d5c0a8678f71..562c012c5fdc 100644 --- a/test/new-e2e/tests/discovery/process_autodiscovery_test.go +++ b/test/new-e2e/tests/discovery/process_autodiscovery_test.go @@ -191,12 +191,3 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser assert.Fail(c, "Nginx check is configured but has not run yet") } - -// getCheckNames returns the names of all scheduled checks -func getCheckNames(checks map[checkName]map[instanceName]checkStatus) []string { - names := make([]string, 0, len(checks)) - for name := range checks { - names = append(names, name) - } - return names -} From 3d5a831b1f46a71c7f64ff7e8e1d16bc2c2c3277 Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 10:23:21 +0100 Subject: [PATCH 04/11] allow by-pass errors on macos --- tasks/gotest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tasks/gotest.py b/tasks/gotest.py index 55595f08508b..1fc43b647a14 100644 --- a/tasks/gotest.py +++ b/tasks/gotest.py @@ -483,11 +483,11 @@ def get_modified_packages(ctx, build_tags=None, lint=False) -> list[GoModule]: if not os.path.exists(os.path.dirname(modified_file)): continue - # If there are go file matching the build tags in the folder we do not try to run tests + # If there are no go files matching the build tags in the folder we do not try to run tests res = ctx.run( - f'go list -tags "{" ".join(build_tags)}" ./{os.path.dirname(modified_file)}/...', hide=True, warn=True + f'go list -tags "{" ".join(build_tags)}" ./{os.path.dirname(modified_file)}/', hide=True, warn=True ) - if res.stderr is not None and "matched no packages" in res.stderr: + if res is None or res.return_code != 0: continue relative_target = "./" + os.path.relpath(os.path.dirname(modified_file), best_module_path) From 9bf22280f87b2b2a5f22e43465da144d0696bbd4 Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 16:58:18 +0100 Subject: [PATCH 05/11] remove replacement when continue was called --- comp/core/telemetry/telemetryimpl/prom_counter_test.go | 4 ++-- pkg/util/log/log_test.go | 8 ++++++-- test/new-e2e/tests/containers/ecs_test.go | 8 ++++++-- test/new-e2e/tests/containers/k8s_test.go | 5 ++++- test/new-e2e/tests/sbom/k8s_test.go | 4 +++- 5 files changed, 21 insertions(+), 8 deletions(-) diff --git a/comp/core/telemetry/telemetryimpl/prom_counter_test.go b/comp/core/telemetry/telemetryimpl/prom_counter_test.go index b2f23a42b9c0..4dcbf0c0f227 100644 --- a/comp/core/telemetry/telemetryimpl/prom_counter_test.go +++ b/comp/core/telemetry/telemetryimpl/prom_counter_test.go @@ -44,10 +44,10 @@ func TestPromCounterInitializer(t *testing.T) { endMetrics, err := promTelemetry.Gather() require.NoError(t, err) - require.Equal(t, len(endMetrics), 1) + require.Len(t, endMetrics, 1) metricFamily := endMetrics[0] - require.Equal(t, len(metricFamily.GetMetric()), 1) + require.Len(t, metricFamily.GetMetric(), 1) assert.Equal(t, metricFamily.GetName(), "subsystem_test") diff --git a/pkg/util/log/log_test.go b/pkg/util/log/log_test.go index d1dcefc31a07..f5207fc443a7 100644 --- a/pkg/util/log/log_test.go +++ b/pkg/util/log/log_test.go @@ -541,10 +541,14 @@ func TestLoggerScrubbingCount(t *testing.T) { for _, fun := range tc.funcs { val := reflect.ValueOf(fun) funcName, err := getFuncName(val) - require.NoError(t, err) + if !assert.NoError(t, err) { + continue + } valTy := reflect.TypeOf(fun) - require.Equalf(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) + if !assert.Equal(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) { + continue + } // create a slice of reflect.Value from the args reflArgs := make([]reflect.Value, 0, len(tc.args)) diff --git a/test/new-e2e/tests/containers/ecs_test.go b/test/new-e2e/tests/containers/ecs_test.go index 22b7bb4a9f37..00a2ac6508a1 100644 --- a/test/new-e2e/tests/containers/ecs_test.go +++ b/test/new-e2e/tests/containers/ecs_test.go @@ -126,7 +126,9 @@ func (suite *ecsSuite) Test00UpAndRunning() { Cluster: &suite.ecsClusterName, Services: servicesList.ServiceArns, }) - require.NoErrorf(c, err, "Failed to describe ECS services %v", servicesList.ServiceArns) + if !assert.NoErrorf(c, err, "Failed to describe ECS services %v", servicesList.ServiceArns) { + continue + } for _, serviceDescription := range servicesDescription.Services { assert.NotZerof(c, serviceDescription.DesiredCount, "ECS service %s has no task", *serviceDescription.ServiceName) @@ -151,7 +153,9 @@ func (suite *ecsSuite) Test00UpAndRunning() { Cluster: &suite.ecsClusterName, Tasks: tasksList.TaskArns, }) - require.NoErrorf(c, err, "Failed to describe ECS tasks %v", tasksList.TaskArns) + if !assert.NoErrorf(c, err, "Failed to describe ECS tasks %v", tasksList.TaskArns) { + continue + } for _, taskDescription := range tasksDescription.Tasks { assert.Equalf(c, string(awsecstypes.DesiredStatusRunning), *taskDescription.LastStatus, diff --git a/test/new-e2e/tests/containers/k8s_test.go b/test/new-e2e/tests/containers/k8s_test.go index acbafffc5ac5..b6645ac32e16 100644 --- a/test/new-e2e/tests/containers/k8s_test.go +++ b/test/new-e2e/tests/containers/k8s_test.go @@ -1868,7 +1868,10 @@ func (suite *k8sSuite) testHPA(namespace, deployment string) { }), ) require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) + if !assert.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) { + sendEvent("warning", fmt.Sprintf("No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment), nil) + return + } // Check HPA is properly scaling up or down // This indirectly tests the cluster-agent external metrics server diff --git a/test/new-e2e/tests/sbom/k8s_test.go b/test/new-e2e/tests/sbom/k8s_test.go index 9a77f9d9ce53..438c27183303 100644 --- a/test/new-e2e/tests/sbom/k8s_test.go +++ b/test/new-e2e/tests/sbom/k8s_test.go @@ -312,7 +312,9 @@ func (suite *k8sSuite) TestSBOM() { for _, image := range images { cyclonedx := image.GetCyclonedx() - require.NotNil(c, cyclonedx.Metadata.Component.Properties) + if !assert.NotNil(c, cyclonedx.Metadata.Component.Properties) { + continue + } expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), From ad3f2b59cc112e248baefeb7046008b8b3e92606 Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 17:37:08 +0100 Subject: [PATCH 06/11] Remove replacement when called in a goroutine --- .../process/process_collector_test.go | 11 +- .../missing_type_recompilation_test.go | 4 +- pkg/network/tracer/tracer_linux_test.go | 34 ++++-- pkg/network/tracer/tracer_test.go | 48 ++++++-- pkg/util/winutil/eventlog/example_test.go | 4 +- .../subscription/subscription_test.go | 8 +- .../agent-health/docker_permission_test.go | 5 +- .../file-tailing/file_tailing_test.go | 5 +- .../file-tailing/file_tailing_test.go | 4 +- .../tests/agent-runtimes/infra/utils_test.go | 6 +- test/new-e2e/tests/containers/base_test.go | 40 +++++-- test/new-e2e/tests/containers/ecs_test.go | 14 ++- test/new-e2e/tests/containers/k8s_test.go | 108 ++++++++++++++---- test/new-e2e/tests/cspm/cspm_test.go | 8 +- test/new-e2e/tests/cws/windows_test.go | 20 +++- .../discovery/process_autodiscovery_test.go | 54 +++++++-- .../fake_traceroute_test.go | 4 +- test/new-e2e/tests/npm/agentenv_npm_test.go | 5 +- .../tests/npm/cilium_lb_conntracker_test.go | 4 +- .../new-e2e/tests/remote-config/utils_test.go | 5 +- .../windows/install-test/install_test.go | 13 ++- .../windows/install-test/upgrade_test.go | 4 +- 22 files changed, 311 insertions(+), 97 deletions(-) diff --git a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go index 6ce80fc3db65..212e2f337180 100644 --- a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go +++ b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go @@ -18,7 +18,6 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" "go.uber.org/fx" "github.com/DataDog/datadog-agent/comp/core/config" @@ -693,8 +692,9 @@ func TestProcessDifferentCmdline(t *testing.T) { // Wait for first collection to complete assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - require.NoError(cT, err) - require.NotNil(cT, actualProc) + if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { + return + } assert.Equal(cT, []string{"bash"}, actualProc.Cmdline) }, time.Second, time.Millisecond*100) @@ -704,8 +704,9 @@ func TestProcessDifferentCmdline(t *testing.T) { // After exec, the store should have htop, not bash assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - require.NoError(cT, err) - require.NotNil(cT, actualProc) + if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { + return + } // Critical assertion: cmdline should be updated to htop after exec assert.Equal(cT, []string{"htop"}, actualProc.Cmdline, "Process cmdline should be updated after exec") assert.Equal(cT, "htop", actualProc.Name, "Process name should be updated after exec") diff --git a/pkg/dyninst/missing_type_recompilation_test.go b/pkg/dyninst/missing_type_recompilation_test.go index 8203b9dae555..69223d96ab1a 100644 --- a/pkg/dyninst/missing_type_recompilation_test.go +++ b/pkg/dyninst/missing_type_recompilation_test.go @@ -177,7 +177,9 @@ func TestMissingTypeRecompilation(t *testing.T) { require.EventuallyWithT(t, func(c *assert.CollectT) { stats := m.GetStats() actuatorStats, ok := stats["actuator"].(map[string]any) - require.True(c, ok, "actuator stats missing") + if !assert.True(c, ok, "actuator stats missing") { + return + } assert.Equal(c, uint64(0), actuatorStats["numPrograms"], "expected numPrograms == 0 after cleanup") assert.Equal(c, uint64(0), actuatorStats["numProcesses"], diff --git a/pkg/network/tracer/tracer_linux_test.go b/pkg/network/tracer/tracer_linux_test.go index deec3cdd61a0..ed5bc7f2182c 100644 --- a/pkg/network/tracer/tracer_linux_test.go +++ b/pkg/network/tracer/tracer_linux_test.go @@ -122,7 +122,9 @@ func (s *TracerSuite) TestTCPRemoveEntries() { conns, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c2.LocalAddr(), c2.RemoteAddr(), conns) - require.True(ct, ok) + if !assert.True(ct, ok) { + return + } assert.Equal(ct, clientMessageSize, int(conn.Monotonic.SentBytes)) assert.Equal(ct, 0, int(conn.Monotonic.RecvBytes)) assert.Equal(ct, 0, int(conn.Monotonic.Retransmits)) @@ -322,7 +324,9 @@ func (s *TracerSuite) TestTCPRTT() { allConnections, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), allConnections) - require.True(ct, ok) + if !assert.True(ct, ok) { + return + } if cfg.EnableEbpfless { timeoutUs := uint32((10 * time.Second).Microseconds()) @@ -489,14 +493,18 @@ func (s *TracerSuite) TestConntrackExpiration() { var conn *network.ConnectionStats require.EventuallyWithT(t, func(collect *assert.CollectT) { _, err = c.Write([]byte("ping\n")) - require.NoError(collect, err, "error sending data to server") + if !assert.NoError(collect, err, "error sending data to server") { + return + } connections, cleanup := getConnections(collect, tr) defer cleanup() t.Log(connections) // for debugging failures var ok bool conn, ok = findConnection(c.LocalAddr(), c.RemoteAddr(), connections) - require.True(collect, ok, "connection not found") + if !assert.True(collect, ok, "connection not found") { + return + } assert.NotNil(collect, tr.conntracker.GetTranslationForConn(&conn.ConnectionTuple), "connection does not have NAT translation") }, 3*time.Second, 100*time.Millisecond, "failed to find connection translation") @@ -654,7 +662,9 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv6() { } return cs.DPort == uint16(remoteAddr.Port) }) - require.Len(ct, outgoing, 1) + if !assert.Len(ct, outgoing, 1) { + return + } assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) @@ -2069,8 +2079,10 @@ func (s *TracerSuite) TestBlockingReadCounts() { return true }) - require.NoError(collect, err, "error reading from connection") - require.NoError(collect, readErr, "error from raw conn") + if !assert.NoError(collect, err, "error reading from connection") || + !assert.NoError(collect, readErr, "error from raw conn") { + return + } read += n t.Logf("read %d", read) @@ -2138,7 +2150,9 @@ func (s *TracerSuite) TestPreexistingConnectionDirection() { require.NotNil(collect, outgoing) require.NotNil(collect, incoming) - require.True(collect, incoming != nil && outgoing != nil) + if !assert.True(collect, incoming != nil && outgoing != nil) { + return + } m := outgoing.Monotonic // skip byte counts in ebpfless: for ebpfless pre-existing connections, @@ -3314,7 +3328,9 @@ func (s *TracerSuite) TestTCPRetransmitSyncOnClose() { defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), conns) - require.True(ct, ok, "connection not found") + if !assert.True(ct, ok, "connection not found") { + return + } // We expect retransmits > 0 assert.Greater(ct, int(conn.Monotonic.Retransmits), 0, "should have retransmits") diff --git a/pkg/network/tracer/tracer_test.go b/pkg/network/tracer/tracer_test.go index 0d2cb3da4d50..40b139fafea7 100644 --- a/pkg/network/tracer/tracer_test.go +++ b/pkg/network/tracer/tracer_test.go @@ -1052,16 +1052,24 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim require.EventuallyWithT(t, func(c *assert.CollectT) { dnsClient := new(dns.Client) dnsConn, err := dnsClient.Dial(dnsServerAddr.String()) - require.NoError(c, err) + if !assert.NoError(c, err) { + return + } dnsClientAddr := dnsConn.LocalAddr().(*net.UDPAddr) _, _, err = dnsClient.ExchangeWithConn(queryMsg, dnsConn) if timeout == 0 { - require.NoError(c, err, "unexpected error making DNS request") + if !assert.NoError(c, err, "unexpected error making DNS request") { + return + } } else { - require.Error(c, err) + if !assert.Error(c, err) { + return + } } _ = dnsConn.Close() - require.NoError(c, tr.reverseDNS.WaitForDomain(domain)) + if !assert.NoError(c, tr.reverseDNS.WaitForDomain(domain)) { + return + } // Iterate through active connections until we find connection created above, and confirm send + recv counts connections, cleanup := getConnections(c, tr) @@ -1071,11 +1079,17 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim return } - require.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) + if !assert.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) { + return + } if !tr.config.EnableEbpfless { - require.Equal(c, os.Getpid(), int(conn.Pid)) + if !assert.Equal(c, os.Getpid(), int(conn.Pid)) { + return + } + } + if !assert.Equal(c, dnsServerAddr.Port, int(conn.DPort)) { + return } - require.Equal(c, dnsServerAddr.Port, int(conn.DPort)) var total uint32 var successfulResponses uint32 @@ -1092,9 +1106,15 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim failedResponses := total - successfulResponses // DNS Stats - require.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) - require.Equal(c, uint32(failure), failedResponses) - require.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) + if !assert.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) { + return + } + if !assert.Equal(c, uint32(failure), failedResponses) { + return + } + if !assert.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) { + return + } }, 10*time.Second, 100*time.Millisecond, "Failed to get dns response or unexpected response") } @@ -1231,7 +1251,9 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv4() { return cs.DPort == uint16(remotePort) }) - require.Len(ct, outgoing, 1) + if !assert.Len(ct, outgoing, 1) { + return + } assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) } @@ -1260,7 +1282,9 @@ func (s *TracerSuite) TestConnectedUDPSendIPv6() { outgoing = network.FilterConnections(connections, func(cs network.ConnectionStats) bool { return cs.DPort == uint16(remotePort) }) - require.Len(ct, outgoing, 1) + if !assert.Len(ct, outgoing, 1) { + return + } assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) diff --git a/pkg/util/winutil/eventlog/example_test.go b/pkg/util/winutil/eventlog/example_test.go index 60d63eef52e7..a8dff42becb8 100644 --- a/pkg/util/winutil/eventlog/example_test.go +++ b/pkg/util/winutil/eventlog/example_test.go @@ -45,7 +45,9 @@ func testSubscriptionExample(t testing.TB, ti eventlog_test.APITester, stop chan // Start the subscription err := sub.Start() - require.NoError(t, err) + if !assert.NoError(t, err) { + return + } // Cleanup the subscription when done defer sub.Stop() diff --git a/pkg/util/winutil/eventlog/subscription/subscription_test.go b/pkg/util/winutil/eventlog/subscription/subscription_test.go index 30940a757cb7..9035fcffb425 100644 --- a/pkg/util/winutil/eventlog/subscription/subscription_test.go +++ b/pkg/util/winutil/eventlog/subscription/subscription_test.go @@ -409,7 +409,9 @@ func (s *GetEventsTestSuite) TestStopWhileWaitingWithEventsAvailable() { // Read not all of the events _, err := ReadNumEvents(s.T(), s.ti, sub, batchCount) close(readyToStop) - require.NoError(s.T(), err) + if !assert.NoError(s.T(), err) { + return + } // Purposefully don't read the rest of the events. This leaves the signal event set. // Wait for Stop() to finish <-stopped @@ -441,7 +443,9 @@ func (s *GetEventsTestSuite) TestStopWhileWaitingWithNoMoreItemseNotFinalized() // Read all events _, err := getEventHandles(s.T(), s.ti, sub, s.numEvents) close(readyToStop) - require.NoError(s.T(), err) + if !assert.NoError(s.T(), err) { + return + } // Purposefully don't call EvtNext the final time when it would normally return ERROR_NO_MORE_ITEMS. // This leaves the signal event set. // Wait for Stop() to finish diff --git a/test/new-e2e/tests/agent-health/docker_permission_test.go b/test/new-e2e/tests/agent-health/docker_permission_test.go index bfd7bbed24b3..9a6740ad479c 100644 --- a/test/new-e2e/tests/agent-health/docker_permission_test.go +++ b/test/new-e2e/tests/agent-health/docker_permission_test.go @@ -136,8 +136,9 @@ func (suite *dockerPermissionSuite) TestDockerPermissionIssueLifecycle() { var postRestartIssue *healthplatform.Issue require.EventuallyWithT(t, func(ct *assert.CollectT) { payloads, err := fakeIntake.GetAgentHealth() - require.NoError(ct, err) - require.NotEmpty(ct, payloads, "Should receive health report after restart") + if !assert.NoError(ct, err) || !assert.NotEmpty(ct, payloads, "Should receive health report after restart") { + return + } latest := payloads[len(payloads)-1] postRestartIssue = findIssue(t, latest, expectedIssueID) assert.NotNil(ct, postRestartIssue, "Docker permission issue should still be present after restart") diff --git a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go index d4a75ea55717..fa5a89640bc3 100644 --- a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go @@ -16,7 +16,6 @@ import ( "github.com/DataDog/datadog-agent/test/new-e2e/tests/agent-log-pipelines/utils" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/components/datadog/agentparams" scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" @@ -62,7 +61,9 @@ func (s *LinuxFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - require.NoError(c, err, "Unable to filter logs by the service 'hello'.") + if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { + return + } // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected.") { cat, _ := s.Env().RemoteHost.Execute(fmt.Sprintf("cat %s && cat %s/hello-world-2.log", logFilePath, utils.LinuxLogsFolderPath)) diff --git a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go index 2b6a9810ee48..e966bc1e0827 100644 --- a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go @@ -61,7 +61,9 @@ func (s *WindowsFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - require.NoError(c, err, "Unable to filter logs by the service 'hello'.") + if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { + return + } // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected") { cat, _ := s.Env().RemoteHost.Execute("type " + logFilePath) diff --git a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go index e08f97ae253f..64f2cfbb5ab4 100644 --- a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go +++ b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go @@ -11,7 +11,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/environments" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/testcommon/check" @@ -94,7 +93,10 @@ func verifyCheckRuns(t *testing.T, env *environments.Host, checkName string) boo // by querying the agent status API. This is a helper function meant to be called within EventuallyWithT. func verifyCheckSchedulingViaStatusAPI(t *testing.T, c *assert.CollectT, env *environments.Host, checks []string, shouldBeScheduled bool) { scheduledChecks, err := getScheduledChecks(env) - require.NoError(c, err, "Failed to get scheduled checks") + if !assert.NoError(c, err, "Failed to get scheduled checks") { + t.Logf("Failed to retrieve scheduled checks, will retry...") + return + } t.Logf("Found %d check types in agent status", len(scheduledChecks)) diff --git a/test/new-e2e/tests/containers/base_test.go b/test/new-e2e/tests/containers/base_test.go index da39d8b28594..692f36111cbb 100644 --- a/test/new-e2e/tests/containers/base_test.go +++ b/test/new-e2e/tests/containers/base_test.go @@ -164,8 +164,14 @@ func (suite *baseSuite[Env]) testMetric(args *testMetricArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.MetricSeries](regexTags), ) - require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) { + return + } // Check tags if expectedTags != nil { @@ -287,8 +293,14 @@ func (suite *baseSuite[Env]) testLog(args *testLogArgs) { args.Filter.Service, fakeintake.WithMatchingTags[*aggregator.Log](regexTags), ) - require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) { + return + } // Check tags if expectedTags != nil { @@ -414,8 +426,14 @@ func (suite *baseSuite[Env]) testCheckRun(args *testCheckRunArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.CheckRun](regexTags), ) - require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) { + return + } // Check tags if expectedTags != nil { @@ -521,8 +539,14 @@ func (suite *baseSuite[Env]) testEvent(args *testEventArgs) { args.Filter.Source, fakeintake.WithMatchingTags[*aggregator.Event](regexTags), ) - require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) { + return + } // Check tags if expectedTags != nil { diff --git a/test/new-e2e/tests/containers/ecs_test.go b/test/new-e2e/tests/containers/ecs_test.go index 00a2ac6508a1..e0f0bcacc10f 100644 --- a/test/new-e2e/tests/containers/ecs_test.go +++ b/test/new-e2e/tests/containers/ecs_test.go @@ -118,7 +118,10 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(10)), // Because `DescribeServices` takes at most 10 services in input NextToken: nextToken, }) - require.NoErrorf(c, err, "Failed to list ECS services") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list ECS services") { + return + } nextToken = servicesList.NextToken @@ -145,7 +148,9 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(100)), // Because `DescribeTasks` takes at most 100 tasks in input NextToken: nextToken, }) - require.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) + if !assert.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) { + break + } nextToken = tasksList.NextToken @@ -609,7 +614,10 @@ func (suite *ecsSuite) TestTraceTCP() { func (suite *ecsSuite) testTrace(taskName string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - require.NoErrorf(c, cerr, "Failed to query fake intake") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { + return + } var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/containers/k8s_test.go b/test/new-e2e/tests/containers/k8s_test.go index b6645ac32e16..4dd264f12c9b 100644 --- a/test/new-e2e/tests/containers/k8s_test.go +++ b/test/new-e2e/tests/containers/k8s_test.go @@ -128,37 +128,58 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { fields.OneTermNotEqualSelector("eks.amazonaws.com/compute-type", "fargate"), ).String(), }) - require.NoErrorf(c, err, "Failed to list Linux nodes") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list Linux nodes") { + return + } windowsNodes, err := suite.Env().KubernetesCluster.Client().CoreV1().Nodes().List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("kubernetes.io/os", "windows").String(), }) - require.NoErrorf(c, err, "Failed to list Windows nodes") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list Windows nodes") { + return + } linuxPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxNodeAgent.LabelSelectors["app"]).String(), }) - require.NoErrorf(c, err, "Failed to list Linux datadog agent pods") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list Linux datadog agent pods") { + return + } windowsPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.WindowsNodeAgent.LabelSelectors["app"]).String(), }) - require.NoErrorf(c, err, "Failed to list Windows datadog agent pods") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list Windows datadog agent pods") { + return + } clusterAgentPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterAgent.LabelSelectors["app"]).String(), }) - require.NoErrorf(c, err, "Failed to list datadog cluster agent pods") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list datadog cluster agent pods") { + return + } clusterChecksPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterChecks.LabelSelectors["app"]).String(), }) - require.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") { + return + } dogstatsdPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("dogstatsd-standalone").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", "dogstatsd-standalone").String(), }) - require.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") { + return + } assert.Len(c, linuxPods.Items, len(linuxNodes.Items)) assert.Len(c, windowsPods.Items, len(windowsNodes.Items)) @@ -327,7 +348,10 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"agent", "check", "-t", "3", "container", "--table", "--delay", "1000", "--pause", "5000"}) - require.NoError(c, err) + // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoError(c, err) { + return + } matched, err := regexp.MatchString(`container\.memory\.usage\s+gauge\s+\d+\s+\d+`, stdout) if assert.NoError(c, err) { assert.Truef(c, matched, "Output of `agent check -r container` doesn’t contain the expected metric") @@ -342,7 +366,10 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"env", "DD_LOG_LEVEL=off", "agent", "check", "-r", "container", "--table", "--delay", "1000", "--json"}) - require.NoError(c, err) + // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoError(c, err) { + return + } if !assert.Truef(c, json.Valid([]byte(stdout)), "Output of `agent check -r container --json` isn’t valid JSON") { var blob interface{} err := json.Unmarshal([]byte(stdout), &blob) @@ -1617,8 +1644,14 @@ func (suite *k8sSuite) TestContainerImage() { }() images, err := suite.Fakeintake.FilterContainerImages("ghcr.io/datadog/apps-nginx-server") - require.NoErrorf(c, err, "Failed to query fake intake") - require.NotEmptyf(c, images, "No container_image yet") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, images, "No container_image yet") { + return + } expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), @@ -1681,13 +1714,19 @@ func (suite *k8sSuite) TestSBOM() { }() sbomIDs, err := suite.Fakeintake.GetSBOMIDs() - require.NoErrorf(c, err, "Failed to query fake intake") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } sbomIDs = lo.Filter(sbomIDs, func(id string, _ int) bool { return strings.HasPrefix(id, "ghcr.io/datadog/apps-nginx-server") }) - require.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") { + return + } images := lo.FlatMap(sbomIDs, func(id string, _ int) []*aggregator.SBOMPayload { images, err := suite.Fakeintake.FilterSBOMs(id) @@ -1695,13 +1734,19 @@ func (suite *k8sSuite) TestSBOM() { return images }) - require.NotEmptyf(c, images, "No SBOM payload yet") + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, images, "No SBOM payload yet") { + return + } images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { return image.Status == sbom.SBOMStatus_SUCCESS }) - require.NotEmptyf(c, images, "No successful SBOM yet") + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, images, "No successful SBOM yet") { + return + } images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { cyclonedx := image.GetCyclonedx() @@ -1710,10 +1755,15 @@ func (suite *k8sSuite) TestSBOM() { cyclonedx.Metadata.Component != nil }) - require.NotEmptyf(c, images, "No SBOM with complete CycloneDX") + // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NotEmptyf(c, images, "No SBOM with complete CycloneDX") { + return + } for _, image := range images { - require.NotNil(c, image.GetCyclonedx().Metadata.Component.Properties) + if !assert.NotNil(c, image.GetCyclonedx().Metadata.Component.Properties) { + continue + } expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), @@ -1780,8 +1830,13 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { LabelSelector: fields.OneTermEqualSelector("app", "nginx").String(), FieldSelector: fields.OneTermEqualSelector("status.phase", "Running").String(), }) - require.NoErrorf(c, err, "Failed to list nginx pods") - require.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to list nginx pods") { + return + } + if !assert.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") { + return + } // Choose the oldest pod. // If we choose a pod that is too recent, there is a risk that we delete a pod that hasn’t been seen by the agent yet. @@ -1811,7 +1866,10 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { }() events, err := suite.Fakeintake.GetContainerLifecycleEvents() - require.NoErrorf(c, err, "Failed to query fake intake") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } foundPodEvent := false @@ -1867,7 +1925,10 @@ func (suite *k8sSuite) testHPA(namespace, deployment string) { "kube_deployment:" + deployment, }), ) - require.NoErrorf(c, err, "Failed to query fake intake") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, err, "Failed to query fake intake") { + return + } if !assert.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) { sendEvent("warning", fmt.Sprintf("No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment), nil) return @@ -1914,7 +1975,10 @@ func (suite *k8sSuite) TestTraceTCP() { func (suite *k8sSuite) testTrace(kubeDeployment string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - require.NoErrorf(c, cerr, "Failed to query fake intake") + // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged + if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { + return + } var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/cspm/cspm_test.go b/test/new-e2e/tests/cspm/cspm_test.go index b49de90762b0..91b2f7aa5a60 100644 --- a/test/new-e2e/tests/cspm/cspm_test.go +++ b/test/new-e2e/tests/cspm/cspm_test.go @@ -204,7 +204,9 @@ func (s *cspmTestSuite) TestMetrics() { assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.running") - require.NoError(c, err) + if !assert.NoError(c, err) { + return + } if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.running") } @@ -213,7 +215,9 @@ func (s *cspmTestSuite) TestMetrics() { s.T().Log("Waiting for datadog.security_agent.compliance.containers_running metrics") assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.containers_running") - require.NoError(c, err) + if !assert.NoError(c, err) { + return + } if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.containers_running") } diff --git a/test/new-e2e/tests/cws/windows_test.go b/test/new-e2e/tests/cws/windows_test.go index 9c1a5cd4de1b..22f400c5c8c1 100644 --- a/test/new-e2e/tests/cws/windows_test.go +++ b/test/new-e2e/tests/cws/windows_test.go @@ -202,14 +202,24 @@ func (a *agentSuiteWindows) Test03CreateFileSignal() { // Check app signal assert.EventuallyWithT(a.T(), func(c *assert.CollectT) { signal, err := a.apiClient.GetSignal(fmt.Sprintf("host:%s @workflow.rule.id:%s", a.Env().Agent.Client.Hostname(), signalRuleID)) - require.NoError(c, err) - require.NotNil(c, signal) + if !assert.NoError(c, err) { + return + } + if !assert.NotNil(c, signal) { + return + } assert.Contains(c, signal.Tags, "rule_id:"+strings.ToLower(agentRuleName), "unable to find rule_id tag") - require.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") + if !assert.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") { + return + } attributes := signal.AdditionalProperties["attributes"].(map[string]interface{}) - require.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") + if !assert.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") { + return + } agentContext := attributes["agent"].(map[string]interface{}) - require.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") + if !assert.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") { + return + } assert.Contains(c, agentContext["rule_id"], agentRuleName, "signal doesn't contain agent rule id") }, 4*time.Minute, 10*time.Second) } diff --git a/test/new-e2e/tests/discovery/process_autodiscovery_test.go b/test/new-e2e/tests/discovery/process_autodiscovery_test.go index 562c012c5fdc..b59f2923e077 100644 --- a/test/new-e2e/tests/discovery/process_autodiscovery_test.go +++ b/test/new-e2e/tests/discovery/process_autodiscovery_test.go @@ -110,23 +110,38 @@ func (s *processAutodiscoverySuite) verifyRedisCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - require.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") + if !assert.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check has cel://process AD identifier - require.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") + if !assert.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify host was resolved to localhost - require.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") + if !assert.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - require.NoError(c, err, "failed to parse agent status") + if !assert.NoError(c, err, "failed to parse agent status") { + t.Logf("Failed to parse status output: %s", statusOutput) + return + } instances, exists := status.RunnerStats.Checks["redisdb"] - require.True(c, exists, "redisdb check should be running") + if !assert.True(c, exists, "redisdb check should be running") { + t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) + return + } // Verify the check has executed successfully for instanceName, checkStat := range instances { @@ -163,20 +178,32 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - require.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") + if !assert.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check has cel://process AD identifier - require.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") + if !assert.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - require.NoError(c, err, "failed to parse agent status") + if !assert.NoError(c, err, "failed to parse agent status") { + t.Logf("Failed to parse status output: %s", statusOutput) + return + } instances, exists := status.RunnerStats.Checks["nginx"] - require.True(c, exists, "nginx check should be running") + if !assert.True(c, exists, "nginx check should be running") { + t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) + return + } // Key assertion: exactly 1 nginx check instance despite multiple nginx processes assert.Equal(c, 1, len(instances), "expected exactly 1 nginx check instance, got %d", len(instances)) @@ -191,3 +218,12 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser assert.Fail(c, "Nginx check is configured but has not run yet") } + +// getCheckNames returns the names of all scheduled checks +func getCheckNames(checks map[checkName]map[instanceName]checkStatus) []string { + names := make([]string, 0, len(checks)) + for name := range checks { + names = append(names, name) + } + return names +} diff --git a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go index 283cd58c844f..7a787bc54dd9 100644 --- a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go +++ b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go @@ -116,7 +116,9 @@ func (s *fakeTracerouteTestSuite) TestFakeTraceroute() { assert.EventuallyWithT(t, func(c *assert.CollectT) { nps, err := s.Env().FakeIntake.Client().GetLatestNetpathEvents() assert.NoError(c, err, "GetLatestNetpathEvents() errors") - require.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") + if !assert.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") { + return + } udpPath := s.expectNetpath(c, func(np *aggregator.Netpath) bool { return np.Destination.Hostname == targetIP.String() && np.Protocol == "UDP" diff --git a/test/new-e2e/tests/npm/agentenv_npm_test.go b/test/new-e2e/tests/npm/agentenv_npm_test.go index 5849903783d9..2c3b4ff2e960 100644 --- a/test/new-e2e/tests/npm/agentenv_npm_test.go +++ b/test/new-e2e/tests/npm/agentenv_npm_test.go @@ -17,7 +17,6 @@ import ( scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) type vmSuiteEx6 struct { @@ -42,7 +41,9 @@ func (v *vmSuiteEx6) Test1_FakeIntakeNPM() { v.Env().RemoteHost.MustExecute("curl http://www.datadoghq.com") hostnameNetID, err := v.Env().FakeIntake.Client().GetConnectionsNames() - require.NoError(c, err, "fakeintake GetConnectionsNames() error") + if !assert.NoError(c, err, "fakeintake GetConnectionsNames() error") { + return + } if assert.NotZero(c, len(hostnameNetID), "no connections yet") { t.Logf("hostname+networkID %v seen connections", hostnameNetID) diff --git a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go index c08d55095982..321dd4ac1a70 100644 --- a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go +++ b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go @@ -137,7 +137,9 @@ func (suite *ciliumLBConntrackerTestSuite) TestCiliumConntracker() { return } - require.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") + if !assert.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") { + return + } svcConns = append(svcConns, c) } diff --git a/test/new-e2e/tests/remote-config/utils_test.go b/test/new-e2e/tests/remote-config/utils_test.go index 19f0a199f4ff..47b4d2bc226a 100644 --- a/test/new-e2e/tests/remote-config/utils_test.go +++ b/test/new-e2e/tests/remote-config/utils_test.go @@ -13,7 +13,6 @@ import ( "time" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/components" ) @@ -33,7 +32,9 @@ func assertAgentLogsEventually(t *testing.T, rh *components.RemoteHost, agentNam assert.EventuallyWithTf(t, func(c *assert.CollectT) { // read agent logs agentLogs, err := rh.ReadFilePrivileged(remoteLogsPath) - require.NoError(c, err) + if !assert.NoError(c, err) { + return + } logs := string(agentLogs) for _, log := range missingLogs { if strings.Contains(logs, log) { diff --git a/test/new-e2e/tests/windows/install-test/install_test.go b/test/new-e2e/tests/windows/install-test/install_test.go index b3b61a07ca33..f41b2332da49 100644 --- a/test/new-e2e/tests/windows/install-test/install_test.go +++ b/test/new-e2e/tests/windows/install-test/install_test.go @@ -22,7 +22,6 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -424,10 +423,16 @@ func (s *testInstallOptsSuite) TestInstallOpts() { var boundPort boundport.BoundPort s.Require().EventuallyWithTf(func(c *assert.CollectT) { pid, err := windowsCommon.GetServicePID(vm, "DatadogAgent") - require.NoError(c, err) + if !assert.NoError(c, err) { + return + } boundPort, err = common.GetBoundPort(vm, "tcp", cmdPort) - require.NoError(c, err) - require.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) + if !assert.NoError(c, err) { + return + } + if !assert.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) { + return + } assert.Equalf(c, pid, boundPort.PID(), "port tcp/%d should be bound by the agent", cmdPort) }, 1*time.Minute, 500*time.Millisecond, "port tcp/%d should be bound by the agent", cmdPort) s.Require().EqualValues("127.0.0.1", boundPort.LocalAddress(), "agent should only be listening locally") diff --git a/test/new-e2e/tests/windows/install-test/upgrade_test.go b/test/new-e2e/tests/windows/install-test/upgrade_test.go index ab4748478c0a..3d056f1ee9f3 100644 --- a/test/new-e2e/tests/windows/install-test/upgrade_test.go +++ b/test/new-e2e/tests/windows/install-test/upgrade_test.go @@ -403,7 +403,9 @@ func (s *testUpgradeFromV5Suite) installAgent5() { s.Assert().EventuallyWithT(func(t *assert.CollectT) { cmd := fmt.Sprintf(`& "%s\embedded\python.exe" "%s\agent\agent.py" info`, installPath, installPath) out, err := host.Execute(cmd) - require.NoError(t, err, "should get agent info") + if !assert.NoError(t, err, "should get agent info") { + return + } s.T().Logf("Agent 5 info:\n%s", out) assert.Contains(t, out, agentPackage.AgentVersion(), "info should have agent 5 version") }, 5*time.Minute, 5*time.Second, "should get agent 5 info") From 6dedfde3974b2c7ea1b97a5058b08e5e958063ee Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 18:08:29 +0100 Subject: [PATCH 07/11] Remove comments to replace assert by require when in a goroutine --- test/new-e2e/tests/containers/k8s_test.go | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/test/new-e2e/tests/containers/k8s_test.go b/test/new-e2e/tests/containers/k8s_test.go index 4dd264f12c9b..26688a8d2830 100644 --- a/test/new-e2e/tests/containers/k8s_test.go +++ b/test/new-e2e/tests/containers/k8s_test.go @@ -128,7 +128,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { fields.OneTermNotEqualSelector("eks.amazonaws.com/compute-type", "fargate"), ).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list Linux nodes") { return } @@ -136,7 +135,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { windowsNodes, err := suite.Env().KubernetesCluster.Client().CoreV1().Nodes().List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("kubernetes.io/os", "windows").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list Windows nodes") { return } @@ -144,7 +142,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { linuxPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxNodeAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list Linux datadog agent pods") { return } @@ -152,7 +149,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { windowsPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.WindowsNodeAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list Windows datadog agent pods") { return } @@ -160,7 +156,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { clusterAgentPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterAgent.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list datadog cluster agent pods") { return } @@ -168,7 +163,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { clusterChecksPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterChecks.LabelSelectors["app"]).String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") { return } @@ -176,7 +170,6 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { dogstatsdPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("dogstatsd-standalone").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", "dogstatsd-standalone").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") { return } @@ -1644,11 +1637,9 @@ func (suite *k8sSuite) TestContainerImage() { }() images, err := suite.Fakeintake.FilterContainerImages("ghcr.io/datadog/apps-nginx-server") - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, images, "No container_image yet") { return } @@ -1714,7 +1705,6 @@ func (suite *k8sSuite) TestSBOM() { }() sbomIDs, err := suite.Fakeintake.GetSBOMIDs() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } @@ -1723,7 +1713,6 @@ func (suite *k8sSuite) TestSBOM() { return strings.HasPrefix(id, "ghcr.io/datadog/apps-nginx-server") }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") { return } @@ -1734,7 +1723,6 @@ func (suite *k8sSuite) TestSBOM() { return images }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, images, "No SBOM payload yet") { return } @@ -1743,7 +1731,6 @@ func (suite *k8sSuite) TestSBOM() { return image.Status == sbom.SBOMStatus_SUCCESS }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, images, "No successful SBOM yet") { return } @@ -1755,7 +1742,6 @@ func (suite *k8sSuite) TestSBOM() { cyclonedx.Metadata.Component != nil }) - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, images, "No SBOM with complete CycloneDX") { return } @@ -1830,7 +1816,6 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { LabelSelector: fields.OneTermEqualSelector("app", "nginx").String(), FieldSelector: fields.OneTermEqualSelector("status.phase", "Running").String(), }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list nginx pods") { return } @@ -1866,7 +1851,6 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { }() events, err := suite.Fakeintake.GetContainerLifecycleEvents() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } @@ -1925,7 +1909,6 @@ func (suite *k8sSuite) testHPA(namespace, deployment string) { "kube_deployment:" + deployment, }), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } @@ -1975,7 +1958,6 @@ func (suite *k8sSuite) TestTraceTCP() { func (suite *k8sSuite) testTrace(kubeDeployment string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { return } From acef10fd24390505dd4ca46be07a8b9830d2632c Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 18:10:30 +0100 Subject: [PATCH 08/11] revert change on gotest --- tasks/gotest.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tasks/gotest.py b/tasks/gotest.py index 1fc43b647a14..55595f08508b 100644 --- a/tasks/gotest.py +++ b/tasks/gotest.py @@ -483,11 +483,11 @@ def get_modified_packages(ctx, build_tags=None, lint=False) -> list[GoModule]: if not os.path.exists(os.path.dirname(modified_file)): continue - # If there are no go files matching the build tags in the folder we do not try to run tests + # If there are go file matching the build tags in the folder we do not try to run tests res = ctx.run( - f'go list -tags "{" ".join(build_tags)}" ./{os.path.dirname(modified_file)}/', hide=True, warn=True + f'go list -tags "{" ".join(build_tags)}" ./{os.path.dirname(modified_file)}/...', hide=True, warn=True ) - if res is None or res.return_code != 0: + if res.stderr is not None and "matched no packages" in res.stderr: continue relative_target = "./" + os.path.relpath(os.path.dirname(modified_file), best_module_path) From 9cb394095423f4da8fae1c5ffe1d0d95d31ffa8b Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Thu, 26 Feb 2026 18:18:22 +0100 Subject: [PATCH 09/11] last updates --- pkg/dyninst/end_to_end_test.go | 4 ++-- pkg/util/log/log_test.go | 2 +- test/new-e2e/tests/containers/base_test.go | 8 -------- test/new-e2e/tests/containers/ecs_test.go | 2 -- 4 files changed, 3 insertions(+), 13 deletions(-) diff --git a/pkg/dyninst/end_to_end_test.go b/pkg/dyninst/end_to_end_test.go index ac84b306fd01..0860f9f3d4a4 100644 --- a/pkg/dyninst/end_to_end_test.go +++ b/pkg/dyninst/end_to_end_test.go @@ -306,12 +306,12 @@ func runE2ETest(t *testing.T, cfg e2eTestConfig) { makeTargetStatus(uploader.StatusEmitting, expectedProbeIDs...), ) - assertModuleStats := func(t assert.TestingT, expected actuator.Metrics) { + assertModuleStats := func(t require.TestingT, expected actuator.Metrics) { stats := ts.module.GetStats()["actuator"].(map[string]any) exp := expected.AsStats() gotKeys := slices.Sorted(maps.Keys(stats)) expectedKeys := slices.Sorted(maps.Keys(exp)) - assert.Equal(t, gotKeys, expectedKeys) + require.Equal(t, gotKeys, expectedKeys) for _, key := range gotKeys { assert.Equal(t, exp[key], stats[key], "key %s", key) } diff --git a/pkg/util/log/log_test.go b/pkg/util/log/log_test.go index f5207fc443a7..e1eb8d525b19 100644 --- a/pkg/util/log/log_test.go +++ b/pkg/util/log/log_test.go @@ -546,7 +546,7 @@ func TestLoggerScrubbingCount(t *testing.T) { } valTy := reflect.TypeOf(fun) - if !assert.Equal(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) { + if !assert.Equalf(t, valTy.Kind(), reflect.Func, "expected %s to be a function", funcName) { continue } diff --git a/test/new-e2e/tests/containers/base_test.go b/test/new-e2e/tests/containers/base_test.go index 692f36111cbb..f0029d5143df 100644 --- a/test/new-e2e/tests/containers/base_test.go +++ b/test/new-e2e/tests/containers/base_test.go @@ -164,11 +164,9 @@ func (suite *baseSuite[Env]) testMetric(args *testMetricArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.MetricSeries](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) { return } @@ -293,11 +291,9 @@ func (suite *baseSuite[Env]) testLog(args *testLogArgs) { args.Filter.Service, fakeintake.WithMatchingTags[*aggregator.Log](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) { return } @@ -426,11 +422,9 @@ func (suite *baseSuite[Env]) testCheckRun(args *testCheckRunArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.CheckRun](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) { return } @@ -539,11 +533,9 @@ func (suite *baseSuite[Env]) testEvent(args *testEventArgs) { args.Filter.Source, fakeintake.WithMatchingTags[*aggregator.Event](regexTags), ) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to query fake intake") { return } - // Can be replaced by require.NoEmptyf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) { return } diff --git a/test/new-e2e/tests/containers/ecs_test.go b/test/new-e2e/tests/containers/ecs_test.go index e0f0bcacc10f..a66c0910ed3e 100644 --- a/test/new-e2e/tests/containers/ecs_test.go +++ b/test/new-e2e/tests/containers/ecs_test.go @@ -118,7 +118,6 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(10)), // Because `DescribeServices` takes at most 10 services in input NextToken: nextToken, }) - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, err, "Failed to list ECS services") { return } @@ -614,7 +613,6 @@ func (suite *ecsSuite) TestTraceTCP() { func (suite *ecsSuite) testTrace(taskName string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - // Can be replaced by require.NoErrorf(…) once https://github.com/stretchr/testify/pull/1481 is merged if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { return } From 8dfe6d59eb168785fd56aac25abc894ec1b35036 Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Fri, 27 Feb 2026 15:59:25 +0100 Subject: [PATCH 10/11] reapply require in eventually --- .../process/process_collector_test.go | 11 ++- .../missing_type_recompilation_test.go | 4 +- pkg/network/tracer/tracer_linux_test.go | 34 ++------ pkg/network/tracer/tracer_test.go | 48 +++-------- .../agent-health/docker_permission_test.go | 5 +- .../file-tailing/file_tailing_test.go | 5 +- .../file-tailing/file_tailing_test.go | 4 +- .../tests/agent-runtimes/infra/utils_test.go | 6 +- test/new-e2e/tests/containers/base_test.go | 32 ++----- test/new-e2e/tests/containers/ecs_test.go | 12 +-- test/new-e2e/tests/containers/k8s_test.go | 86 +++++-------------- test/new-e2e/tests/cspm/cspm_test.go | 8 +- test/new-e2e/tests/cws/windows_test.go | 20 ++--- .../discovery/process_autodiscovery_test.go | 54 ++---------- .../fake_traceroute_test.go | 4 +- test/new-e2e/tests/npm/agentenv_npm_test.go | 5 +- .../tests/npm/cilium_lb_conntracker_test.go | 4 +- .../new-e2e/tests/remote-config/utils_test.go | 5 +- .../windows/install-test/install_test.go | 13 +-- .../windows/install-test/upgrade_test.go | 4 +- 20 files changed, 93 insertions(+), 271 deletions(-) diff --git a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go index 212e2f337180..6ce80fc3db65 100644 --- a/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go +++ b/comp/core/workloadmeta/collectors/internal/process/process_collector_test.go @@ -18,6 +18,7 @@ import ( "github.com/golang/mock/gomock" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" "go.uber.org/fx" "github.com/DataDog/datadog-agent/comp/core/config" @@ -692,9 +693,8 @@ func TestProcessDifferentCmdline(t *testing.T) { // Wait for first collection to complete assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { - return - } + require.NoError(cT, err) + require.NotNil(cT, actualProc) assert.Equal(cT, []string{"bash"}, actualProc.Cmdline) }, time.Second, time.Millisecond*100) @@ -704,9 +704,8 @@ func TestProcessDifferentCmdline(t *testing.T) { // After exec, the store should have htop, not bash assert.EventuallyWithT(t, func(cT *assert.CollectT) { actualProc, err := c.mockStore.GetProcess(pid) - if !assert.NoError(cT, err) || !assert.NotNil(cT, actualProc) { - return - } + require.NoError(cT, err) + require.NotNil(cT, actualProc) // Critical assertion: cmdline should be updated to htop after exec assert.Equal(cT, []string{"htop"}, actualProc.Cmdline, "Process cmdline should be updated after exec") assert.Equal(cT, "htop", actualProc.Name, "Process name should be updated after exec") diff --git a/pkg/dyninst/missing_type_recompilation_test.go b/pkg/dyninst/missing_type_recompilation_test.go index 69223d96ab1a..8203b9dae555 100644 --- a/pkg/dyninst/missing_type_recompilation_test.go +++ b/pkg/dyninst/missing_type_recompilation_test.go @@ -177,9 +177,7 @@ func TestMissingTypeRecompilation(t *testing.T) { require.EventuallyWithT(t, func(c *assert.CollectT) { stats := m.GetStats() actuatorStats, ok := stats["actuator"].(map[string]any) - if !assert.True(c, ok, "actuator stats missing") { - return - } + require.True(c, ok, "actuator stats missing") assert.Equal(c, uint64(0), actuatorStats["numPrograms"], "expected numPrograms == 0 after cleanup") assert.Equal(c, uint64(0), actuatorStats["numProcesses"], diff --git a/pkg/network/tracer/tracer_linux_test.go b/pkg/network/tracer/tracer_linux_test.go index ed5bc7f2182c..deec3cdd61a0 100644 --- a/pkg/network/tracer/tracer_linux_test.go +++ b/pkg/network/tracer/tracer_linux_test.go @@ -122,9 +122,7 @@ func (s *TracerSuite) TestTCPRemoveEntries() { conns, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c2.LocalAddr(), c2.RemoteAddr(), conns) - if !assert.True(ct, ok) { - return - } + require.True(ct, ok) assert.Equal(ct, clientMessageSize, int(conn.Monotonic.SentBytes)) assert.Equal(ct, 0, int(conn.Monotonic.RecvBytes)) assert.Equal(ct, 0, int(conn.Monotonic.Retransmits)) @@ -324,9 +322,7 @@ func (s *TracerSuite) TestTCPRTT() { allConnections, cleanup := getConnections(ct, tr) defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), allConnections) - if !assert.True(ct, ok) { - return - } + require.True(ct, ok) if cfg.EnableEbpfless { timeoutUs := uint32((10 * time.Second).Microseconds()) @@ -493,18 +489,14 @@ func (s *TracerSuite) TestConntrackExpiration() { var conn *network.ConnectionStats require.EventuallyWithT(t, func(collect *assert.CollectT) { _, err = c.Write([]byte("ping\n")) - if !assert.NoError(collect, err, "error sending data to server") { - return - } + require.NoError(collect, err, "error sending data to server") connections, cleanup := getConnections(collect, tr) defer cleanup() t.Log(connections) // for debugging failures var ok bool conn, ok = findConnection(c.LocalAddr(), c.RemoteAddr(), connections) - if !assert.True(collect, ok, "connection not found") { - return - } + require.True(collect, ok, "connection not found") assert.NotNil(collect, tr.conntracker.GetTranslationForConn(&conn.ConnectionTuple), "connection does not have NAT translation") }, 3*time.Second, 100*time.Millisecond, "failed to find connection translation") @@ -662,9 +654,7 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv6() { } return cs.DPort == uint16(remoteAddr.Port) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) @@ -2079,10 +2069,8 @@ func (s *TracerSuite) TestBlockingReadCounts() { return true }) - if !assert.NoError(collect, err, "error reading from connection") || - !assert.NoError(collect, readErr, "error from raw conn") { - return - } + require.NoError(collect, err, "error reading from connection") + require.NoError(collect, readErr, "error from raw conn") read += n t.Logf("read %d", read) @@ -2150,9 +2138,7 @@ func (s *TracerSuite) TestPreexistingConnectionDirection() { require.NotNil(collect, outgoing) require.NotNil(collect, incoming) - if !assert.True(collect, incoming != nil && outgoing != nil) { - return - } + require.True(collect, incoming != nil && outgoing != nil) m := outgoing.Monotonic // skip byte counts in ebpfless: for ebpfless pre-existing connections, @@ -3328,9 +3314,7 @@ func (s *TracerSuite) TestTCPRetransmitSyncOnClose() { defer cleanup() conn, ok := findConnection(c.LocalAddr(), c.RemoteAddr(), conns) - if !assert.True(ct, ok, "connection not found") { - return - } + require.True(ct, ok, "connection not found") // We expect retransmits > 0 assert.Greater(ct, int(conn.Monotonic.Retransmits), 0, "should have retransmits") diff --git a/pkg/network/tracer/tracer_test.go b/pkg/network/tracer/tracer_test.go index 40b139fafea7..0d2cb3da4d50 100644 --- a/pkg/network/tracer/tracer_test.go +++ b/pkg/network/tracer/tracer_test.go @@ -1052,24 +1052,16 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim require.EventuallyWithT(t, func(c *assert.CollectT) { dnsClient := new(dns.Client) dnsConn, err := dnsClient.Dial(dnsServerAddr.String()) - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) dnsClientAddr := dnsConn.LocalAddr().(*net.UDPAddr) _, _, err = dnsClient.ExchangeWithConn(queryMsg, dnsConn) if timeout == 0 { - if !assert.NoError(c, err, "unexpected error making DNS request") { - return - } + require.NoError(c, err, "unexpected error making DNS request") } else { - if !assert.Error(c, err) { - return - } + require.Error(c, err) } _ = dnsConn.Close() - if !assert.NoError(c, tr.reverseDNS.WaitForDomain(domain)) { - return - } + require.NoError(c, tr.reverseDNS.WaitForDomain(domain)) // Iterate through active connections until we find connection created above, and confirm send + recv counts connections, cleanup := getConnections(c, tr) @@ -1079,17 +1071,11 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim return } - if !assert.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) { - return - } + require.Equal(c, queryMsg.Len(), int(conn.Monotonic.SentBytes)) if !tr.config.EnableEbpfless { - if !assert.Equal(c, os.Getpid(), int(conn.Pid)) { - return - } - } - if !assert.Equal(c, dnsServerAddr.Port, int(conn.DPort)) { - return + require.Equal(c, os.Getpid(), int(conn.Pid)) } + require.Equal(c, dnsServerAddr.Port, int(conn.DPort)) var total uint32 var successfulResponses uint32 @@ -1106,15 +1092,9 @@ func testDNSStats(t *testing.T, tr *Tracer, domain string, success, failure, tim failedResponses := total - successfulResponses // DNS Stats - if !assert.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) { - return - } - if !assert.Equal(c, uint32(failure), failedResponses) { - return - } - if !assert.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) { - return - } + require.Equal(c, uint32(success), successfulResponses, "expected %d successful responses but got %d", success, successfulResponses) + require.Equal(c, uint32(failure), failedResponses) + require.Equal(c, uint32(timeout), timeouts, "expected %d timeouts but got %d", timeout, timeouts) }, 10*time.Second, 100*time.Millisecond, "Failed to get dns response or unexpected response") } @@ -1251,9 +1231,7 @@ func (s *TracerSuite) TestUnconnectedUDPSendIPv4() { return cs.DPort == uint16(remotePort) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) }, 3*time.Second, 100*time.Millisecond) } @@ -1282,9 +1260,7 @@ func (s *TracerSuite) TestConnectedUDPSendIPv6() { outgoing = network.FilterConnections(connections, func(cs network.ConnectionStats) bool { return cs.DPort == uint16(remotePort) }) - if !assert.Len(ct, outgoing, 1) { - return - } + require.Len(ct, outgoing, 1) assert.Equal(ct, remoteAddr.IP.String(), outgoing[0].Dest.String()) assert.Equal(ct, bytesSent, int(outgoing[0].Monotonic.SentBytes)) diff --git a/test/new-e2e/tests/agent-health/docker_permission_test.go b/test/new-e2e/tests/agent-health/docker_permission_test.go index 9a6740ad479c..bfd7bbed24b3 100644 --- a/test/new-e2e/tests/agent-health/docker_permission_test.go +++ b/test/new-e2e/tests/agent-health/docker_permission_test.go @@ -136,9 +136,8 @@ func (suite *dockerPermissionSuite) TestDockerPermissionIssueLifecycle() { var postRestartIssue *healthplatform.Issue require.EventuallyWithT(t, func(ct *assert.CollectT) { payloads, err := fakeIntake.GetAgentHealth() - if !assert.NoError(ct, err) || !assert.NotEmpty(ct, payloads, "Should receive health report after restart") { - return - } + require.NoError(ct, err) + require.NotEmpty(ct, payloads, "Should receive health report after restart") latest := payloads[len(payloads)-1] postRestartIssue = findIssue(t, latest, expectedIssueID) assert.NotNil(ct, postRestartIssue, "Docker permission issue should still be present after restart") diff --git a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go index fa5a89640bc3..d4a75ea55717 100644 --- a/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/linux-log/file-tailing/file_tailing_test.go @@ -16,6 +16,7 @@ import ( "github.com/DataDog/datadog-agent/test/new-e2e/tests/agent-log-pipelines/utils" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/components/datadog/agentparams" scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" @@ -61,9 +62,7 @@ func (s *LinuxFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { - return - } + require.NoError(c, err, "Unable to filter logs by the service 'hello'.") // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected.") { cat, _ := s.Env().RemoteHost.Execute(fmt.Sprintf("cat %s && cat %s/hello-world-2.log", logFilePath, utils.LinuxLogsFolderPath)) diff --git a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go index e966bc1e0827..2b6a9810ee48 100644 --- a/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go +++ b/test/new-e2e/tests/agent-log-pipelines/windows-log/file-tailing/file_tailing_test.go @@ -61,9 +61,7 @@ func (s *WindowsFakeintakeSuite) BeforeTest(suiteName, testName string) { // Ensure no logs are present in fakeintake before testing starts s.EventuallyWithT(func(c *assert.CollectT) { logs, err := s.Env().FakeIntake.Client().FilterLogs("hello") - if !assert.NoError(c, err, "Unable to filter logs by the service 'hello'.") { - return - } + require.NoError(c, err, "Unable to filter logs by the service 'hello'.") // If logs are found, print their content for debugging if !assert.Empty(c, logs, "Logs were found when none were expected") { cat, _ := s.Env().RemoteHost.Execute("type " + logFilePath) diff --git a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go index 64f2cfbb5ab4..e08f97ae253f 100644 --- a/test/new-e2e/tests/agent-runtimes/infra/utils_test.go +++ b/test/new-e2e/tests/agent-runtimes/infra/utils_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/environments" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/testcommon/check" @@ -93,10 +94,7 @@ func verifyCheckRuns(t *testing.T, env *environments.Host, checkName string) boo // by querying the agent status API. This is a helper function meant to be called within EventuallyWithT. func verifyCheckSchedulingViaStatusAPI(t *testing.T, c *assert.CollectT, env *environments.Host, checks []string, shouldBeScheduled bool) { scheduledChecks, err := getScheduledChecks(env) - if !assert.NoError(c, err, "Failed to get scheduled checks") { - t.Logf("Failed to retrieve scheduled checks, will retry...") - return - } + require.NoError(c, err, "Failed to get scheduled checks") t.Logf("Found %d check types in agent status", len(scheduledChecks)) diff --git a/test/new-e2e/tests/containers/base_test.go b/test/new-e2e/tests/containers/base_test.go index f0029d5143df..da39d8b28594 100644 --- a/test/new-e2e/tests/containers/base_test.go +++ b/test/new-e2e/tests/containers/base_test.go @@ -164,12 +164,8 @@ func (suite *baseSuite[Env]) testMetric(args *testMetricArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.MetricSeries](regexTags), ) - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, metrics, "No `%s` metrics yet", prettyMetricQuery) // Check tags if expectedTags != nil { @@ -291,12 +287,8 @@ func (suite *baseSuite[Env]) testLog(args *testLogArgs) { args.Filter.Service, fakeintake.WithMatchingTags[*aggregator.Log](regexTags), ) - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, logs, "No `%s` logs yet", prettyLogQuery) // Check tags if expectedTags != nil { @@ -422,12 +414,8 @@ func (suite *baseSuite[Env]) testCheckRun(args *testCheckRunArgs) { args.Filter.Name, fakeintake.WithMatchingTags[*aggregator.CheckRun](regexTags), ) - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, checkRuns, "No `%s` checkRun yet", prettyCheckRunQuery) // Check tags if expectedTags != nil { @@ -533,12 +521,8 @@ func (suite *baseSuite[Env]) testEvent(args *testEventArgs) { args.Filter.Source, fakeintake.WithMatchingTags[*aggregator.Event](regexTags), ) - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, events, "No `%s` events yet", prettyEventQuery) // Check tags if expectedTags != nil { diff --git a/test/new-e2e/tests/containers/ecs_test.go b/test/new-e2e/tests/containers/ecs_test.go index a66c0910ed3e..00a2ac6508a1 100644 --- a/test/new-e2e/tests/containers/ecs_test.go +++ b/test/new-e2e/tests/containers/ecs_test.go @@ -118,9 +118,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(10)), // Because `DescribeServices` takes at most 10 services in input NextToken: nextToken, }) - if !assert.NoErrorf(c, err, "Failed to list ECS services") { - return - } + require.NoErrorf(c, err, "Failed to list ECS services") nextToken = servicesList.NextToken @@ -147,9 +145,7 @@ func (suite *ecsSuite) Test00UpAndRunning() { MaxResults: pointer.Ptr(int32(100)), // Because `DescribeTasks` takes at most 100 tasks in input NextToken: nextToken, }) - if !assert.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) { - break - } + require.NoErrorf(c, err, "Failed to list ECS tasks for service %s", *serviceDescription.ServiceName) nextToken = tasksList.NextToken @@ -613,9 +609,7 @@ func (suite *ecsSuite) TestTraceTCP() { func (suite *ecsSuite) testTrace(taskName string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { - return - } + require.NoErrorf(c, cerr, "Failed to query fake intake") var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/containers/k8s_test.go b/test/new-e2e/tests/containers/k8s_test.go index 26688a8d2830..be69ddc58c21 100644 --- a/test/new-e2e/tests/containers/k8s_test.go +++ b/test/new-e2e/tests/containers/k8s_test.go @@ -128,51 +128,37 @@ func (suite *k8sSuite) testUpAndRunning(waitFor time.Duration) { fields.OneTermNotEqualSelector("eks.amazonaws.com/compute-type", "fargate"), ).String(), }) - if !assert.NoErrorf(c, err, "Failed to list Linux nodes") { - return - } + require.NoErrorf(c, err, "Failed to list Linux nodes") windowsNodes, err := suite.Env().KubernetesCluster.Client().CoreV1().Nodes().List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("kubernetes.io/os", "windows").String(), }) - if !assert.NoErrorf(c, err, "Failed to list Windows nodes") { - return - } + require.NoErrorf(c, err, "Failed to list Windows nodes") linuxPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxNodeAgent.LabelSelectors["app"]).String(), }) - if !assert.NoErrorf(c, err, "Failed to list Linux datadog agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list Linux datadog agent pods") windowsPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.WindowsNodeAgent.LabelSelectors["app"]).String(), }) - if !assert.NoErrorf(c, err, "Failed to list Windows datadog agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list Windows datadog agent pods") clusterAgentPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterAgent.LabelSelectors["app"]).String(), }) - if !assert.NoErrorf(c, err, "Failed to list datadog cluster agent pods") { - return - } + require.NoErrorf(c, err, "Failed to list datadog cluster agent pods") clusterChecksPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("datadog").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", suite.Env().Agent.LinuxClusterChecks.LabelSelectors["app"]).String(), }) - if !assert.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") { - return - } + require.NoErrorf(c, err, "Failed to list datadog cluster checks runner pods") dogstatsdPods, err := suite.Env().KubernetesCluster.Client().CoreV1().Pods("dogstatsd-standalone").List(ctx, metav1.ListOptions{ LabelSelector: fields.OneTermEqualSelector("app", "dogstatsd-standalone").String(), }) - if !assert.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") { - return - } + require.NoErrorf(c, err, "Failed to list dogstatsd standalone pods") assert.Len(c, linuxPods.Items, len(linuxNodes.Items)) assert.Len(c, windowsPods.Items, len(windowsNodes.Items)) @@ -341,10 +327,7 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"agent", "check", "-t", "3", "container", "--table", "--delay", "1000", "--pause", "5000"}) - // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) matched, err := regexp.MatchString(`container\.memory\.usage\s+gauge\s+\d+\s+\d+`, stdout) if assert.NoError(c, err) { assert.Truef(c, matched, "Output of `agent check -r container` doesn’t contain the expected metric") @@ -359,10 +342,7 @@ func (suite *k8sSuite) testAgentCLI() { var stdout string suite.EventuallyWithT(func(c *assert.CollectT) { stdout, _, err = suite.Env().KubernetesCluster.KubernetesClient.PodExec("datadog", pod.Items[0].Name, "agent", []string{"env", "DD_LOG_LEVEL=off", "agent", "check", "-r", "container", "--table", "--delay", "1000", "--json"}) - // Can be replaced by require.NoError(…) once https://github.com/stretchr/testify/pull/1481 is merged - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if !assert.Truef(c, json.Valid([]byte(stdout)), "Output of `agent check -r container --json` isn’t valid JSON") { var blob interface{} err := json.Unmarshal([]byte(stdout), &blob) @@ -1637,12 +1617,8 @@ func (suite *k8sSuite) TestContainerImage() { }() images, err := suite.Fakeintake.FilterContainerImages("ghcr.io/datadog/apps-nginx-server") - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } - if !assert.NotEmptyf(c, images, "No container_image yet") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") + require.NotEmptyf(c, images, "No container_image yet") expectedTags := []*regexp.Regexp{ regexp.MustCompile(`^architecture:(amd|arm)64$`), @@ -1705,17 +1681,13 @@ func (suite *k8sSuite) TestSBOM() { }() sbomIDs, err := suite.Fakeintake.GetSBOMIDs() - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") sbomIDs = lo.Filter(sbomIDs, func(id string, _ int) bool { return strings.HasPrefix(id, "ghcr.io/datadog/apps-nginx-server") }) - if !assert.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") { - return - } + require.NotEmptyf(c, sbomIDs, "No SBOM for ghcr.io/datadog/apps-nginx-server yet") images := lo.FlatMap(sbomIDs, func(id string, _ int) []*aggregator.SBOMPayload { images, err := suite.Fakeintake.FilterSBOMs(id) @@ -1723,17 +1695,13 @@ func (suite *k8sSuite) TestSBOM() { return images }) - if !assert.NotEmptyf(c, images, "No SBOM payload yet") { - return - } + require.NotEmptyf(c, images, "No SBOM payload yet") images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { return image.Status == sbom.SBOMStatus_SUCCESS }) - if !assert.NotEmptyf(c, images, "No successful SBOM yet") { - return - } + require.NotEmptyf(c, images, "No successful SBOM yet") images = lo.Filter(images, func(image *aggregator.SBOMPayload, _ int) bool { cyclonedx := image.GetCyclonedx() @@ -1742,9 +1710,7 @@ func (suite *k8sSuite) TestSBOM() { cyclonedx.Metadata.Component != nil }) - if !assert.NotEmptyf(c, images, "No SBOM with complete CycloneDX") { - return - } + require.NotEmptyf(c, images, "No SBOM with complete CycloneDX") for _, image := range images { if !assert.NotNil(c, image.GetCyclonedx().Metadata.Component.Properties) { @@ -1816,12 +1782,8 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { LabelSelector: fields.OneTermEqualSelector("app", "nginx").String(), FieldSelector: fields.OneTermEqualSelector("status.phase", "Running").String(), }) - if !assert.NoErrorf(c, err, "Failed to list nginx pods") { - return - } - if !assert.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") { - return - } + require.NoErrorf(c, err, "Failed to list nginx pods") + require.NotEmptyf(c, pods.Items, "Failed to find an nginx pod") // Choose the oldest pod. // If we choose a pod that is too recent, there is a risk that we delete a pod that hasn’t been seen by the agent yet. @@ -1851,9 +1813,7 @@ func (suite *k8sSuite) TestContainerLifecycleEvents() { }() events, err := suite.Fakeintake.GetContainerLifecycleEvents() - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") foundPodEvent := false @@ -1909,9 +1869,7 @@ func (suite *k8sSuite) testHPA(namespace, deployment string) { "kube_deployment:" + deployment, }), ) - if !assert.NoErrorf(c, err, "Failed to query fake intake") { - return - } + require.NoErrorf(c, err, "Failed to query fake intake") if !assert.NotEmptyf(c, metrics, "No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment) { sendEvent("warning", fmt.Sprintf("No `kubernetes_state.deployment.replicas_available{kube_namespace:%s,kube_deployment:%s}` metrics yet", namespace, deployment), nil) return @@ -1958,9 +1916,7 @@ func (suite *k8sSuite) TestTraceTCP() { func (suite *k8sSuite) testTrace(kubeDeployment string) { suite.EventuallyWithTf(func(c *assert.CollectT) { traces, cerr := suite.Fakeintake.GetTraces() - if !assert.NoErrorf(c, cerr, "Failed to query fake intake") { - return - } + require.NoErrorf(c, cerr, "Failed to query fake intake") var err error // Iterate starting from the most recent traces diff --git a/test/new-e2e/tests/cspm/cspm_test.go b/test/new-e2e/tests/cspm/cspm_test.go index 91b2f7aa5a60..b49de90762b0 100644 --- a/test/new-e2e/tests/cspm/cspm_test.go +++ b/test/new-e2e/tests/cspm/cspm_test.go @@ -204,9 +204,7 @@ func (s *cspmTestSuite) TestMetrics() { assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.running") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.running") } @@ -215,9 +213,7 @@ func (s *cspmTestSuite) TestMetrics() { s.T().Log("Waiting for datadog.security_agent.compliance.containers_running metrics") assert.EventuallyWithT(s.T(), func(c *assert.CollectT) { metrics, err := s.Env().FakeIntake.Client().FilterMetrics("datadog.security_agent.compliance.containers_running") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) if assert.NotEmpty(c, metrics) { s.T().Log("Metrics found: datadog.security_agent.compliance.containers_running") } diff --git a/test/new-e2e/tests/cws/windows_test.go b/test/new-e2e/tests/cws/windows_test.go index 22f400c5c8c1..9c1a5cd4de1b 100644 --- a/test/new-e2e/tests/cws/windows_test.go +++ b/test/new-e2e/tests/cws/windows_test.go @@ -202,24 +202,14 @@ func (a *agentSuiteWindows) Test03CreateFileSignal() { // Check app signal assert.EventuallyWithT(a.T(), func(c *assert.CollectT) { signal, err := a.apiClient.GetSignal(fmt.Sprintf("host:%s @workflow.rule.id:%s", a.Env().Agent.Client.Hostname(), signalRuleID)) - if !assert.NoError(c, err) { - return - } - if !assert.NotNil(c, signal) { - return - } + require.NoError(c, err) + require.NotNil(c, signal) assert.Contains(c, signal.Tags, "rule_id:"+strings.ToLower(agentRuleName), "unable to find rule_id tag") - if !assert.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") { - return - } + require.Contains(c, signal.AdditionalProperties, "attributes", "unable to find 'attributes' field in signal") attributes := signal.AdditionalProperties["attributes"].(map[string]interface{}) - if !assert.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") { - return - } + require.Contains(c, attributes, "agent", "unable to find 'agent' field in signal's attributes") agentContext := attributes["agent"].(map[string]interface{}) - if !assert.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") { - return - } + require.Contains(c, agentContext, "rule_id", "unable to find 'rule_id' in signal's agent context") assert.Contains(c, agentContext["rule_id"], agentRuleName, "signal doesn't contain agent rule id") }, 4*time.Minute, 10*time.Second) } diff --git a/test/new-e2e/tests/discovery/process_autodiscovery_test.go b/test/new-e2e/tests/discovery/process_autodiscovery_test.go index b59f2923e077..562c012c5fdc 100644 --- a/test/new-e2e/tests/discovery/process_autodiscovery_test.go +++ b/test/new-e2e/tests/discovery/process_autodiscovery_test.go @@ -110,38 +110,23 @@ func (s *processAutodiscoverySuite) verifyRedisCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - if !assert.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") // Verify the check has cel://process AD identifier - if !assert.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") // Verify host was resolved to localhost - if !assert.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - if !assert.NoError(c, err, "failed to parse agent status") { - t.Logf("Failed to parse status output: %s", statusOutput) - return - } + require.NoError(c, err, "failed to parse agent status") instances, exists := status.RunnerStats.Checks["redisdb"] - if !assert.True(c, exists, "redisdb check should be running") { - t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) - return - } + require.True(c, exists, "redisdb check should be running") // Verify the check has executed successfully for instanceName, checkStat := range instances { @@ -178,32 +163,20 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - if !assert.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") // Verify the check has cel://process AD identifier - if !assert.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") { - t.Logf("config-check output: %s", configCheckOutput) - return - } + require.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - if !assert.NoError(c, err, "failed to parse agent status") { - t.Logf("Failed to parse status output: %s", statusOutput) - return - } + require.NoError(c, err, "failed to parse agent status") instances, exists := status.RunnerStats.Checks["nginx"] - if !assert.True(c, exists, "nginx check should be running") { - t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) - return - } + require.True(c, exists, "nginx check should be running") // Key assertion: exactly 1 nginx check instance despite multiple nginx processes assert.Equal(c, 1, len(instances), "expected exactly 1 nginx check instance, got %d", len(instances)) @@ -218,12 +191,3 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser assert.Fail(c, "Nginx check is configured but has not run yet") } - -// getCheckNames returns the names of all scheduled checks -func getCheckNames(checks map[checkName]map[instanceName]checkStatus) []string { - names := make([]string, 0, len(checks)) - for name := range checks { - names = append(names, name) - } - return names -} diff --git a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go index 7a787bc54dd9..283cd58c844f 100644 --- a/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go +++ b/test/new-e2e/tests/netpath/network-path-integration/fake_traceroute_test.go @@ -116,9 +116,7 @@ func (s *fakeTracerouteTestSuite) TestFakeTraceroute() { assert.EventuallyWithT(t, func(c *assert.CollectT) { nps, err := s.Env().FakeIntake.Client().GetLatestNetpathEvents() assert.NoError(c, err, "GetLatestNetpathEvents() errors") - if !assert.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") { - return - } + require.NotNil(c, nps, "GetLatestNetpathEvents() returned nil netpaths") udpPath := s.expectNetpath(c, func(np *aggregator.Netpath) bool { return np.Destination.Hostname == targetIP.String() && np.Protocol == "UDP" diff --git a/test/new-e2e/tests/npm/agentenv_npm_test.go b/test/new-e2e/tests/npm/agentenv_npm_test.go index 2c3b4ff2e960..5849903783d9 100644 --- a/test/new-e2e/tests/npm/agentenv_npm_test.go +++ b/test/new-e2e/tests/npm/agentenv_npm_test.go @@ -17,6 +17,7 @@ import ( scenec2 "github.com/DataDog/datadog-agent/test/e2e-framework/scenarios/aws/ec2" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type vmSuiteEx6 struct { @@ -41,9 +42,7 @@ func (v *vmSuiteEx6) Test1_FakeIntakeNPM() { v.Env().RemoteHost.MustExecute("curl http://www.datadoghq.com") hostnameNetID, err := v.Env().FakeIntake.Client().GetConnectionsNames() - if !assert.NoError(c, err, "fakeintake GetConnectionsNames() error") { - return - } + require.NoError(c, err, "fakeintake GetConnectionsNames() error") if assert.NotZero(c, len(hostnameNetID), "no connections yet") { t.Logf("hostname+networkID %v seen connections", hostnameNetID) diff --git a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go index 321dd4ac1a70..c08d55095982 100644 --- a/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go +++ b/test/new-e2e/tests/npm/cilium_lb_conntracker_test.go @@ -137,9 +137,7 @@ func (suite *ciliumLBConntrackerTestSuite) TestCiliumConntracker() { return } - if !assert.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") { - return - } + require.NotNil(collect, c.IpTranslation, "ip translation is nil for service connection") svcConns = append(svcConns, c) } diff --git a/test/new-e2e/tests/remote-config/utils_test.go b/test/new-e2e/tests/remote-config/utils_test.go index 47b4d2bc226a..19f0a199f4ff 100644 --- a/test/new-e2e/tests/remote-config/utils_test.go +++ b/test/new-e2e/tests/remote-config/utils_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/DataDog/datadog-agent/test/e2e-framework/testing/components" ) @@ -32,9 +33,7 @@ func assertAgentLogsEventually(t *testing.T, rh *components.RemoteHost, agentNam assert.EventuallyWithTf(t, func(c *assert.CollectT) { // read agent logs agentLogs, err := rh.ReadFilePrivileged(remoteLogsPath) - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) logs := string(agentLogs) for _, log := range missingLogs { if strings.Contains(logs, log) { diff --git a/test/new-e2e/tests/windows/install-test/install_test.go b/test/new-e2e/tests/windows/install-test/install_test.go index f41b2332da49..b3b61a07ca33 100644 --- a/test/new-e2e/tests/windows/install-test/install_test.go +++ b/test/new-e2e/tests/windows/install-test/install_test.go @@ -22,6 +22,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -423,16 +424,10 @@ func (s *testInstallOptsSuite) TestInstallOpts() { var boundPort boundport.BoundPort s.Require().EventuallyWithTf(func(c *assert.CollectT) { pid, err := windowsCommon.GetServicePID(vm, "DatadogAgent") - if !assert.NoError(c, err) { - return - } + require.NoError(c, err) boundPort, err = common.GetBoundPort(vm, "tcp", cmdPort) - if !assert.NoError(c, err) { - return - } - if !assert.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) { - return - } + require.NoError(c, err) + require.NotNil(c, boundPort, "port tcp/%d should be bound", cmdPort) assert.Equalf(c, pid, boundPort.PID(), "port tcp/%d should be bound by the agent", cmdPort) }, 1*time.Minute, 500*time.Millisecond, "port tcp/%d should be bound by the agent", cmdPort) s.Require().EqualValues("127.0.0.1", boundPort.LocalAddress(), "agent should only be listening locally") diff --git a/test/new-e2e/tests/windows/install-test/upgrade_test.go b/test/new-e2e/tests/windows/install-test/upgrade_test.go index 3d056f1ee9f3..ab4748478c0a 100644 --- a/test/new-e2e/tests/windows/install-test/upgrade_test.go +++ b/test/new-e2e/tests/windows/install-test/upgrade_test.go @@ -403,9 +403,7 @@ func (s *testUpgradeFromV5Suite) installAgent5() { s.Assert().EventuallyWithT(func(t *assert.CollectT) { cmd := fmt.Sprintf(`& "%s\embedded\python.exe" "%s\agent\agent.py" info`, installPath, installPath) out, err := host.Execute(cmd) - if !assert.NoError(t, err, "should get agent info") { - return - } + require.NoError(t, err, "should get agent info") s.T().Logf("Agent 5 info:\n%s", out) assert.Contains(t, out, agentPackage.AgentVersion(), "info should have agent 5 version") }, 5*time.Minute, 5*time.Second, "should get agent 5 info") From 172c742fcf7e3eae724f560fea40d19a735fd60a Mon Sep 17 00:00:00 2001 From: Nicolas Schweitzer Date: Fri, 27 Feb 2026 16:21:05 +0100 Subject: [PATCH 11/11] revert test/new-e2e/tests/discovery/process_autodiscovery_test.go which calls logs in their loops --- .../discovery/process_autodiscovery_test.go | 54 +++++++++++++++---- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/test/new-e2e/tests/discovery/process_autodiscovery_test.go b/test/new-e2e/tests/discovery/process_autodiscovery_test.go index 562c012c5fdc..b59f2923e077 100644 --- a/test/new-e2e/tests/discovery/process_autodiscovery_test.go +++ b/test/new-e2e/tests/discovery/process_autodiscovery_test.go @@ -110,23 +110,38 @@ func (s *processAutodiscoverySuite) verifyRedisCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - require.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") + if !assert.Contains(c, configCheckOutput, "=== redisdb check ===", "redisdb check should be configured") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check has cel://process AD identifier - require.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") + if !assert.Contains(c, configCheckOutput, "cel://process", "redisdb check should have cel://process AD identifier") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify host was resolved to localhost - require.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") + if !assert.Contains(c, configCheckOutput, "host: 127.0.0.1", "redisdb check should have host resolved to 127.0.0.1") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - require.NoError(c, err, "failed to parse agent status") + if !assert.NoError(c, err, "failed to parse agent status") { + t.Logf("Failed to parse status output: %s", statusOutput) + return + } instances, exists := status.RunnerStats.Checks["redisdb"] - require.True(c, exists, "redisdb check should be running") + if !assert.True(c, exists, "redisdb check should be running") { + t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) + return + } // Verify the check has executed successfully for instanceName, checkStat := range instances { @@ -163,20 +178,32 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser // Verify check configuration via config-check configCheckOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent configcheck") - require.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") + if !assert.Contains(c, configCheckOutput, "=== nginx check ===", "nginx check should be configured") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check has cel://process AD identifier - require.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") + if !assert.Contains(c, configCheckOutput, "cel://process", "nginx check should have cel://process AD identifier") { + t.Logf("config-check output: %s", configCheckOutput) + return + } // Verify the check is running via collector status statusOutput := s.Env().RemoteHost.MustExecute("sudo datadog-agent status collector --json") var status collectorStatus err := json.Unmarshal([]byte(statusOutput), &status) - require.NoError(c, err, "failed to parse agent status") + if !assert.NoError(c, err, "failed to parse agent status") { + t.Logf("Failed to parse status output: %s", statusOutput) + return + } instances, exists := status.RunnerStats.Checks["nginx"] - require.True(c, exists, "nginx check should be running") + if !assert.True(c, exists, "nginx check should be running") { + t.Logf("Available checks: %v", getCheckNames(status.RunnerStats.Checks)) + return + } // Key assertion: exactly 1 nginx check instance despite multiple nginx processes assert.Equal(c, 1, len(instances), "expected exactly 1 nginx check instance, got %d", len(instances)) @@ -191,3 +218,12 @@ func (s *processAutodiscoverySuite) verifyNginxCheckScheduledViaProcess(c *asser assert.Fail(c, "Nginx check is configured but has not run yet") } + +// getCheckNames returns the names of all scheduled checks +func getCheckNames(checks map[checkName]map[instanceName]checkStatus) []string { + names := make([]string, 0, len(checks)) + for name := range checks { + names = append(names, name) + } + return names +}