diff --git a/.golangci.yml b/.golangci.yml index 57fd4e00b0d..1b750174c13 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -14,6 +14,8 @@ linters: - goheader - gocritic - forbidigo + - testifylint + - ginkgolinter linters-settings: misspell: @@ -56,6 +58,10 @@ linters-settings: - name: use-any - name: var-declaration - name: var-naming + testifylint: + enable-all: true + ginkgolinter: + forbid-focus-container: true issues: exclude-rules: diff --git a/apis/projectcontour/v1alpha1/accesslog_test.go b/apis/projectcontour/v1alpha1/accesslog_test.go index 26b40c661ab..6f02627e655 100644 --- a/apis/projectcontour/v1alpha1/accesslog_test.go +++ b/apis/projectcontour/v1alpha1/accesslog_test.go @@ -17,25 +17,25 @@ import ( "testing" "github.com/projectcontour/contour/apis/projectcontour/v1alpha1" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestValidateAccessLogType(t *testing.T) { - assert.Error(t, v1alpha1.AccessLogType("").Validate()) - assert.Error(t, v1alpha1.AccessLogType("foo").Validate()) + require.Error(t, v1alpha1.AccessLogType("").Validate()) + require.Error(t, v1alpha1.AccessLogType("foo").Validate()) - assert.NoError(t, v1alpha1.EnvoyAccessLog.Validate()) - assert.NoError(t, v1alpha1.JSONAccessLog.Validate()) + require.NoError(t, v1alpha1.EnvoyAccessLog.Validate()) + require.NoError(t, v1alpha1.JSONAccessLog.Validate()) } func TestValidateAccessLogLevel(t *testing.T) { - assert.Error(t, v1alpha1.AccessLogLevel("").Validate()) - assert.Error(t, v1alpha1.AccessLogLevel("foo").Validate()) + require.Error(t, v1alpha1.AccessLogLevel("").Validate()) + require.Error(t, v1alpha1.AccessLogLevel("foo").Validate()) - assert.NoError(t, v1alpha1.LogLevelInfo.Validate()) - assert.NoError(t, v1alpha1.LogLevelError.Validate()) - assert.NoError(t, v1alpha1.LogLevelCritical.Validate()) - assert.NoError(t, v1alpha1.LogLevelDisabled.Validate()) + require.NoError(t, v1alpha1.LogLevelInfo.Validate()) + require.NoError(t, v1alpha1.LogLevelError.Validate()) + require.NoError(t, v1alpha1.LogLevelCritical.Validate()) + require.NoError(t, v1alpha1.LogLevelDisabled.Validate()) } func TestValidateAccessLogJSONFields(t *testing.T) { @@ -59,7 +59,7 @@ func TestValidateAccessLogJSONFields(t *testing.T) { } for _, c := range errorCases { - assert.Error(t, v1alpha1.AccessLogJSONFields(c).Validate(), c) + require.Error(t, v1alpha1.AccessLogJSONFields(c).Validate(), c) } successCases := [][]string{ @@ -82,7 +82,7 @@ func TestValidateAccessLogJSONFields(t *testing.T) { } for _, c := range successCases { - assert.NoError(t, v1alpha1.AccessLogJSONFields(c).Validate(), c) + require.NoError(t, v1alpha1.AccessLogJSONFields(c).Validate(), c) } } @@ -103,7 +103,7 @@ func TestAccessLogFormatString(t *testing.T) { } for _, c := range errorCases { - assert.Error(t, v1alpha1.AccessLogFormatString(c).Validate(), c) + require.Error(t, v1alpha1.AccessLogFormatString(c).Validate(), c) } successCases := []string{ @@ -135,6 +135,6 @@ func TestAccessLogFormatString(t *testing.T) { } for _, c := range successCases { - assert.NoError(t, v1alpha1.AccessLogFormatString(c).Validate(), c) + require.NoError(t, v1alpha1.AccessLogFormatString(c).Validate(), c) } } diff --git a/cmd/contour/certgen_test.go b/cmd/contour/certgen_test.go index 87b6a0a52fe..b8d335631ba 100644 --- a/cmd/contour/certgen_test.go +++ b/cmd/contour/certgen_test.go @@ -27,6 +27,7 @@ import ( "github.com/projectcontour/contour/pkg/certs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" corev1 "k8s.io/api/core/v1" ) @@ -48,9 +49,7 @@ func TestGeneratedSecretsValid(t *testing.T) { Lifetime: conf.Lifetime, Namespace: conf.Namespace, }) - if err != nil { - t.Fatalf("failed to generate certificates: %s", err) - } + require.NoError(t, err, "failed to generate certificates") secrets, errs := certgen.AsSecrets(conf.Namespace, "", certificates) if len(errs) > 0 { @@ -93,7 +92,7 @@ func TestGeneratedSecretsValid(t *testing.T) { } pemBlock, _ := pem.Decode(s.Data[corev1.TLSCertKey]) - assert.Equal(t, pemBlock.Type, "CERTIFICATE") + assert.Equal(t, "CERTIFICATE", pemBlock.Type) cert, err := x509.ParseCertificate(pemBlock.Bytes) if err != nil { @@ -127,9 +126,7 @@ func TestSecretNamePrefix(t *testing.T) { Lifetime: conf.Lifetime, Namespace: conf.Namespace, }) - if err != nil { - t.Fatalf("failed to generate certificates: %s", err) - } + require.NoError(t, err, "failed to generate certificates") secrets, errs := certgen.AsSecrets(conf.Namespace, conf.NameSuffix, certificates) if len(errs) > 0 { @@ -172,18 +169,15 @@ func TestSecretNamePrefix(t *testing.T) { } pemBlock, _ := pem.Decode(s.Data[corev1.TLSCertKey]) - assert.Equal(t, pemBlock.Type, "CERTIFICATE") + assert.Equal(t, "CERTIFICATE", pemBlock.Type) cert, err := x509.ParseCertificate(pemBlock.Bytes) - if err != nil { - t.Errorf("failed to parse X509 certificate: %s", err) - } + require.NoError(t, err, "failed to parse X509 certificate") // Check that each certificate contains SAN entries for the right DNS names. sort.Strings(cert.DNSNames) sort.Strings(wantedNames[s.Name]) assert.Equal(t, cert.DNSNames, wantedNames[s.Name]) - } } @@ -206,9 +200,7 @@ func TestInvalidNamespaceAndName(t *testing.T) { Lifetime: conf.Lifetime, Namespace: conf.Namespace, }) - if err != nil { - t.Fatalf("failed to generate certificates: %s", err) - } + require.NoError(t, err, "failed to generate certificates") secrets, errs := certgen.AsSecrets(conf.Namespace, conf.NameSuffix, certificates) if len(errs) != 2 { @@ -263,14 +255,14 @@ func TestOutputFileMode(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { outputDir, err := os.MkdirTemp("", "") - assert.NoError(t, err) + require.NoError(t, err) defer os.RemoveAll(outputDir) tc.cc.OutputDir = outputDir // Write a file with insecure mode to ensure overwrite works as expected. if tc.cc.Overwrite { _, err = os.Create(filepath.Join(outputDir, tc.insecureFile)) - assert.NoError(t, err) + require.NoError(t, err) } generatedCerts, err := certs.GenerateCerts( @@ -278,9 +270,9 @@ func TestOutputFileMode(t *testing.T) { Lifetime: tc.cc.Lifetime, Namespace: tc.cc.Namespace, }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, OutputCerts(tc.cc, nil, generatedCerts)) + require.NoError(t, OutputCerts(tc.cc, nil, generatedCerts)) err = filepath.Walk(outputDir, func(path string, info os.FileInfo, err error) error { if !info.IsDir() { @@ -288,7 +280,7 @@ func TestOutputFileMode(t *testing.T) { } return nil }) - assert.NoError(t, err) + require.NoError(t, err) }) } } diff --git a/internal/annotation/annotations_test.go b/internal/annotation/annotations_test.go index 89fca235c11..8689f802d3b 100644 --- a/internal/annotation/annotations_test.go +++ b/internal/annotation/annotations_test.go @@ -483,8 +483,8 @@ func TestAnnotationKindValidation(t *testing.T) { for key := range annotationsByKind[kind] { t.Run(fmt.Sprintf("%s is known and valid for %s", key, kind), func(t *testing.T) { - assert.Equal(t, true, IsKnown(key)) - assert.Equal(t, true, ValidForKind(kind, key)) + assert.True(t, IsKnown(key)) + assert.True(t, ValidForKind(kind, key)) }) } } diff --git a/internal/contourconfig/contourconfiguration_test.go b/internal/contourconfig/contourconfiguration_test.go index ccc19d98915..38124d2752d 100644 --- a/internal/contourconfig/contourconfiguration_test.go +++ b/internal/contourconfig/contourconfiguration_test.go @@ -333,7 +333,7 @@ func TestParseTimeoutPolicy(t *testing.T) { require.Error(t, err, "expected error to be returned") require.Contains(t, err.Error(), tc.errorMsg) } else { - require.Nil(t, err) + require.NoError(t, err) require.Equal(t, tc.expected, parsed) } }) diff --git a/internal/dag/accessors_test.go b/internal/dag/accessors_test.go index b3a0af8d57c..ca9be59d39d 100644 --- a/internal/dag/accessors_test.go +++ b/internal/dag/accessors_test.go @@ -21,6 +21,7 @@ import ( "github.com/projectcontour/contour/internal/ref" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -254,11 +255,11 @@ func TestGetSingleListener(t *testing.T) { got, gotErr := d.GetSingleListener("http") assert.Equal(t, d.Listeners["http"], got) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) got, gotErr = d.GetSingleListener("https") assert.Equal(t, d.Listeners["https"], got) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) }) t.Run("one HTTP listener, no HTTPS listener", func(t *testing.T) { @@ -273,11 +274,11 @@ func TestGetSingleListener(t *testing.T) { got, gotErr := d.GetSingleListener("http") assert.Equal(t, d.Listeners["http"], got) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) got, gotErr = d.GetSingleListener("https") assert.Nil(t, got) - assert.EqualError(t, gotErr, "no HTTPS listener configured") + require.EqualError(t, gotErr, "no HTTPS listener configured") }) t.Run("many HTTP listeners, one HTTPS listener", func(t *testing.T) { @@ -304,11 +305,11 @@ func TestGetSingleListener(t *testing.T) { got, gotErr := d.GetSingleListener("http") assert.Nil(t, got) - assert.EqualError(t, gotErr, "more than one HTTP listener configured") + require.EqualError(t, gotErr, "more than one HTTP listener configured") got, gotErr = d.GetSingleListener("https") assert.Equal(t, d.Listeners["https-1"], got) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) }) } diff --git a/internal/dag/cache_test.go b/internal/dag/cache_test.go index f01fa4c680b..b29ac815756 100644 --- a/internal/dag/cache_test.go +++ b/internal/dag/cache_test.go @@ -1835,9 +1835,9 @@ func TestLookupService(t *testing.T) { switch { case tc.wantErr != nil: require.Error(t, gotErr) - assert.EqualError(t, tc.wantErr, gotErr.Error()) + require.EqualError(t, tc.wantErr, gotErr.Error()) default: - assert.Nil(t, gotErr) + require.NoError(t, gotErr) assert.Equal(t, tc.wantSvc, gotSvc) assert.Equal(t, tc.wantPort, gotPort) } @@ -2732,9 +2732,9 @@ func TestLookupUpstreamValidation(t *testing.T) { switch { case tc.wantErr != nil: require.Error(t, gotErr) - assert.EqualError(t, tc.wantErr, gotErr.Error()) + require.EqualError(t, tc.wantErr, gotErr.Error()) default: - assert.Nil(t, gotErr) + require.NoError(t, gotErr) assert.Equal(t, tc.wantPvc, gotPvc) } }) diff --git a/internal/dag/conditions_test.go b/internal/dag/conditions_test.go index 466331100cb..cc4a586349b 100644 --- a/internal/dag/conditions_test.go +++ b/internal/dag/conditions_test.go @@ -18,6 +18,7 @@ import ( contour_api_v1 "github.com/projectcontour/contour/apis/projectcontour/v1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPathMatchCondition(t *testing.T) { @@ -741,11 +742,11 @@ func TestValidateHeaderMatchConditions(t *testing.T) { gotErr := headerMatchConditionsValid(tc.matchconditions) if !tc.wantErr { - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } }) } @@ -871,11 +872,11 @@ func TestValidateQueryParameterMatchConditions(t *testing.T) { gotErr := queryParameterMatchConditionsValid(tc.matchconditions) if !tc.wantErr { - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } }) } diff --git a/internal/dag/dag_test.go b/internal/dag/dag_test.go index bb7e1ed5015..55f00e01773 100644 --- a/internal/dag/dag_test.go +++ b/internal/dag/dag_test.go @@ -17,6 +17,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/types" ) @@ -89,12 +90,12 @@ func TestPeerValidationContext(t *testing.T) { pvc2 := PeerValidationContext{} var pvc3 *PeerValidationContext - assert.Equal(t, pvc1.GetSubjectNames()[0], "subject") - assert.Equal(t, pvc1.GetCACertificate(), []byte("cacert")) - assert.Equal(t, pvc2.GetSubjectNames(), []string(nil)) - assert.Equal(t, pvc2.GetCACertificate(), []byte(nil)) - assert.Equal(t, pvc3.GetSubjectNames(), []string(nil)) - assert.Equal(t, pvc3.GetCACertificate(), []byte(nil)) + assert.Equal(t, "subject", pvc1.GetSubjectNames()[0]) + assert.Equal(t, []byte("cacert"), pvc1.GetCACertificate()) + assert.Equal(t, []string(nil), pvc2.GetSubjectNames()) + assert.Equal(t, []byte(nil), pvc2.GetCACertificate()) + assert.Equal(t, []string(nil), pvc3.GetSubjectNames()) + assert.Equal(t, []byte(nil), pvc3.GetCACertificate()) } func TestObserverFunc(t *testing.T) { @@ -104,7 +105,7 @@ func TestObserverFunc(t *testing.T) { // Ensure the given function gets called. result := false ObserverFunc(func(*DAG) { result = true }).OnChange(nil) - assert.Equal(t, true, result) + require.True(t, result) } func TestServiceClusterValid(t *testing.T) { @@ -117,7 +118,7 @@ func TestServiceClusterValid(t *testing.T) { } for _, c := range invalid { - assert.Errorf(t, c.Validate(), "invalid cluster %#v", c) + require.Errorf(t, c.Validate(), "invalid cluster %#v", c) } } diff --git a/internal/dag/policy_test.go b/internal/dag/policy_test.go index 018b386d8b2..f1c5992e097 100644 --- a/internal/dag/policy_test.go +++ b/internal/dag/policy_test.go @@ -25,6 +25,7 @@ import ( "github.com/projectcontour/contour/internal/timeout" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" networking_v1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -275,11 +276,11 @@ func TestTimeoutPolicy(t *testing.T) { t.Run(name, func(t *testing.T) { gotRouteTimeoutPolicy, gotClusterTimeoutPolicy, gotErr := timeoutPolicy(tc.tp, tc.clusterConnectTimeout) if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } else { assert.Equal(t, tc.wantRouteTimeoutPolicy, gotRouteTimeoutPolicy) assert.Equal(t, tc.wantClusterTimeoutPolicy, gotClusterTimeoutPolicy) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } }) @@ -648,10 +649,10 @@ func TestHeadersPolicy(t *testing.T) { tc := tc got, gotErr := headersPolicyService(&tc.dhp, tc.hp, true, dynamicHeaders) if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } else { assert.Equal(t, tc.want, *got) - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } }) } @@ -1000,7 +1001,7 @@ func TestRateLimitPolicy(t *testing.T) { rlp, err := rateLimitPolicy(tc.in) if tc.wantErr != "" { - assert.EqualError(t, err, tc.wantErr) + require.EqualError(t, err, tc.wantErr) } else { assert.Equal(t, tc.want, rlp) } diff --git a/internal/envoy/cluster_test.go b/internal/envoy/cluster_test.go index 33bfc89e5c5..e0adca8f9ab 100644 --- a/internal/envoy/cluster_test.go +++ b/internal/envoy/cluster_test.go @@ -46,11 +46,11 @@ func TestTruncate(t *testing.T) { } func TestAnyPositive(t *testing.T) { - assert.Equal(t, false, AnyPositive(0)) - assert.Equal(t, true, AnyPositive(1)) - assert.Equal(t, false, AnyPositive(0, 0)) - assert.Equal(t, true, AnyPositive(1, 0)) - assert.Equal(t, true, AnyPositive(0, 1)) + assert.False(t, AnyPositive(0)) + assert.True(t, AnyPositive(1)) + assert.False(t, AnyPositive(0, 0)) + assert.True(t, AnyPositive(1, 0)) + assert.True(t, AnyPositive(0, 1)) } func TestHashname(t *testing.T) { diff --git a/internal/envoy/v3/bootstrap_test.go b/internal/envoy/v3/bootstrap_test.go index d9dedc1ba55..1c5083df515 100644 --- a/internal/envoy/v3/bootstrap_test.go +++ b/internal/envoy/v3/bootstrap_test.go @@ -1988,7 +1988,7 @@ func TestBootstrap(t *testing.T) { t.Run(name, func(t *testing.T) { tc := tc steps, gotError := bootstrap(&tc.config) - assert.Equal(t, gotError != nil, tc.wantedError) + assert.Equal(t, tc.wantedError, gotError != nil) gotConfigs := map[string]proto.Message{} for _, step := range steps { diff --git a/internal/envoy/v3/cluster_test.go b/internal/envoy/v3/cluster_test.go index e8bb7eef649..d5986704fda 100644 --- a/internal/envoy/v3/cluster_test.go +++ b/internal/envoy/v3/cluster_test.go @@ -992,9 +992,9 @@ func TestDNSNameCluster(t *testing.T) { } func TestClusterLoadAssignmentName(t *testing.T) { - assert.Equal(t, xds.ClusterLoadAssignmentName(types.NamespacedName{Namespace: "ns", Name: "svc"}, "port"), "ns/svc/port") - assert.Equal(t, xds.ClusterLoadAssignmentName(types.NamespacedName{Namespace: "ns", Name: "svc"}, ""), "ns/svc") - assert.Equal(t, xds.ClusterLoadAssignmentName(types.NamespacedName{}, ""), "/") + assert.Equal(t, "ns/svc/port", xds.ClusterLoadAssignmentName(types.NamespacedName{Namespace: "ns", Name: "svc"}, "port")) + assert.Equal(t, "ns/svc", xds.ClusterLoadAssignmentName(types.NamespacedName{Namespace: "ns", Name: "svc"}, "")) + assert.Equal(t, "/", xds.ClusterLoadAssignmentName(types.NamespacedName{}, "")) } func TestClustername(t *testing.T) { diff --git a/internal/envoy/v3/listener_test.go b/internal/envoy/v3/listener_test.go index c8bfa83e28f..e6d97a5d01a 100644 --- a/internal/envoy/v3/listener_test.go +++ b/internal/envoy/v3/listener_test.go @@ -62,19 +62,19 @@ var compressorContentTypes = []string{ } func TestCodecForVersions(t *testing.T) { - assert.Equal(t, CodecForVersions(HTTPVersionAuto), HTTPVersionAuto) - assert.Equal(t, CodecForVersions(HTTPVersion1, HTTPVersion2), HTTPVersionAuto) - assert.Equal(t, CodecForVersions(HTTPVersion1), HTTPVersion1) - assert.Equal(t, CodecForVersions(HTTPVersion2), HTTPVersion2) + assert.Equal(t, HTTPVersionAuto, CodecForVersions(HTTPVersionAuto)) + assert.Equal(t, HTTPVersionAuto, CodecForVersions(HTTPVersion1, HTTPVersion2)) + assert.Equal(t, HTTPVersion1, CodecForVersions(HTTPVersion1)) + assert.Equal(t, HTTPVersion2, CodecForVersions(HTTPVersion2)) } func TestProtoNamesForVersions(t *testing.T) { - assert.Equal(t, ProtoNamesForVersions(), []string{"h2", "http/1.1"}) - assert.Equal(t, ProtoNamesForVersions(HTTPVersionAuto), []string{"h2", "http/1.1"}) - assert.Equal(t, ProtoNamesForVersions(HTTPVersion1), []string{"http/1.1"}) - assert.Equal(t, ProtoNamesForVersions(HTTPVersion2), []string{"h2"}) - assert.Equal(t, ProtoNamesForVersions(HTTPVersion3), []string(nil)) - assert.Equal(t, ProtoNamesForVersions(HTTPVersion1, HTTPVersion2), []string{"h2", "http/1.1"}) + assert.Equal(t, []string{"h2", "http/1.1"}, ProtoNamesForVersions()) + assert.Equal(t, []string{"h2", "http/1.1"}, ProtoNamesForVersions(HTTPVersionAuto)) + assert.Equal(t, []string{"http/1.1"}, ProtoNamesForVersions(HTTPVersion1)) + assert.Equal(t, []string{"h2"}, ProtoNamesForVersions(HTTPVersion2)) + assert.Equal(t, []string(nil), ProtoNamesForVersions(HTTPVersion3)) + assert.Equal(t, []string{"h2", "http/1.1"}, ProtoNamesForVersions(HTTPVersion1, HTTPVersion2)) } func TestListener(t *testing.T) { @@ -1710,10 +1710,10 @@ func TestFilterChainTLS_Match(t *testing.T) { // DefaultFilters adds the required HTTP connection manager filters. func TestBuilderValidation(t *testing.T) { - assert.Error(t, HTTPConnectionManagerBuilder().Validate(), + require.Error(t, HTTPConnectionManagerBuilder().Validate(), "ConnectionManager with no filters should not pass validation") - assert.Error(t, HTTPConnectionManagerBuilder().AddFilter(&http.HttpFilter{ + require.Error(t, HTTPConnectionManagerBuilder().AddFilter(&http.HttpFilter{ Name: "foo", ConfigType: &http.HttpFilter_TypedConfig{ TypedConfig: &anypb.Any{ @@ -1723,7 +1723,7 @@ func TestBuilderValidation(t *testing.T) { }).Validate(), "ConnectionManager with only non-router filter should not pass validation") - assert.NoError(t, HTTPConnectionManagerBuilder().DefaultFilters().Validate(), + require.NoError(t, HTTPConnectionManagerBuilder().DefaultFilters().Validate(), "ConnectionManager with default filters failed validation") badBuilder := HTTPConnectionManagerBuilder().DefaultFilters() @@ -1735,7 +1735,7 @@ func TestBuilderValidation(t *testing.T) { }, }, }) - assert.Errorf(t, badBuilder.Validate(), "Adding a filter after the Router filter should fail") + require.Errorf(t, badBuilder.Validate(), "Adding a filter after the Router filter should fail") } func TestAddFilter(t *testing.T) { diff --git a/internal/envoy/v3/socket_options_test.go b/internal/envoy/v3/socket_options_test.go index 689fe2af015..fc7a688b9c0 100644 --- a/internal/envoy/v3/socket_options_test.go +++ b/internal/envoy/v3/socket_options_test.go @@ -24,10 +24,10 @@ import ( func TestSocketOptions(t *testing.T) { // No options shall be set when value 0 is set. so := NewSocketOptions().TOS(0).TrafficClass(0) - assert.Equal(t, len(so.options), 0) + assert.Empty(t, so.options) so.TOS(64) - assert.Equal(t, so.Build(), + assert.Equal(t, []*envoy_core_v3.SocketOption{ { Description: "Set IPv4 TOS field", @@ -37,10 +37,11 @@ func TestSocketOptions(t *testing.T) { State: envoy_core_v3.SocketOption_STATE_LISTENING, }, }, + so.Build(), ) so.TrafficClass(64) - assert.Equal(t, so.Build(), + assert.Equal(t, []*envoy_core_v3.SocketOption{ { Description: "Set IPv4 TOS field", @@ -57,5 +58,6 @@ func TestSocketOptions(t *testing.T) { State: envoy_core_v3.SocketOption_STATE_LISTENING, }, }, + so.Build(), ) } diff --git a/internal/gatewayapi/listeners_test.go b/internal/gatewayapi/listeners_test.go index 365edaa5d9b..405248aed94 100644 --- a/internal/gatewayapi/listeners_test.go +++ b/internal/gatewayapi/listeners_test.go @@ -369,7 +369,7 @@ func TestValidateListeners(t *testing.T) { } res := ValidateListeners(listeners) - assert.Len(t, res.InvalidListenerConditions, 0) + assert.Empty(t, res.InvalidListenerConditions) assert.Len(t, res.Ports, 1) assert.Len(t, res.ListenerNames, 3) }) @@ -521,7 +521,7 @@ func TestValidateListeners(t *testing.T) { }, } res := ValidateListeners(listeners) - assert.Len(t, res.InvalidListenerConditions, 0) + assert.Empty(t, res.InvalidListenerConditions) assert.Len(t, res.Ports, 3) assert.Len(t, res.ListenerNames, 3) }) diff --git a/internal/httpsvc/http_test.go b/internal/httpsvc/http_test.go index ed42e56c271..c5b2c02795b 100644 --- a/internal/httpsvc/http_test.go +++ b/internal/httpsvc/http_test.go @@ -146,7 +146,7 @@ func TestHTTPSService(t *testing.T) { resp.Body.Close() expectedCert, _ := contourCertBeforeRotation.X509Certificate() assert.Equal(t, &expectedCert, resp.TLS.PeerCertificates[0]) - assert.True(t, uint16(tls.VersionTLS13) >= resp.TLS.Version) + assert.GreaterOrEqual(t, uint16(tls.VersionTLS13), resp.TLS.Version) assert.Equal(t, http.StatusOK, resp.StatusCode) return true }, 1*time.Second, 100*time.Millisecond) @@ -156,7 +156,7 @@ func TestHTTPSService(t *testing.T) { checkFatalErr(t, err) resp, err := tryGet("https://localhost:8001/test", trustedTLSClientCert, caCertPool) - assert.Nil(t, err) + require.NoError(t, err) resp.Body.Close() expectedCert, _ := contourCertAfterRotation.X509Certificate() assert.Equal(t, &expectedCert, resp.TLS.PeerCertificates[0]) @@ -164,7 +164,7 @@ func TestHTTPSService(t *testing.T) { // Connection should fail when trying to connect with untrusted client cert. untrustedTLSClientCert, _ := untrustedClientCert.TLSCertificate() _, err = tryGet("https://localhost:8001/test", untrustedTLSClientCert, caCertPool) // nolint // false positive: response body must be closed - assert.NotNil(t, err) + require.Error(t, err) // Gracefully shut down. cancel() diff --git a/internal/k8s/helpers_test.go b/internal/k8s/helpers_test.go index 362cfb097fd..420aaf43a40 100644 --- a/internal/k8s/helpers_test.go +++ b/internal/k8s/helpers_test.go @@ -21,6 +21,7 @@ import ( contour_api_v1 "github.com/projectcontour/contour/apis/projectcontour/v1" contour_api_v1alpha1 "github.com/projectcontour/contour/apis/projectcontour/v1alpha1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" v1 "k8s.io/api/core/v1" networking_v1 "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -89,20 +90,20 @@ func TestIsObjectEqual(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { buf, err := os.ReadFile(tc.filename) - assert.NoError(t, err) + require.NoError(t, err) // Each file contains two YAML records, which should be compared with each other. objects := strings.Split(string(buf), "---") - assert.Equal(t, 2, len(objects), "expected 2 objects in file") + assert.Len(t, objects, 2, "expected 2 objects in file") // Decode the objects. oldObj, _, err := deserializer.Decode([]byte(objects[0]), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) newObj, _, err := deserializer.Decode([]byte(objects[1]), nil, nil) - assert.NoError(t, err) + require.NoError(t, err) got, err := IsObjectEqual(oldObj.(client.Object), newObj.(client.Object)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.equals, got) }) } @@ -124,13 +125,13 @@ func TestIsEqualForResourceVersion(t *testing.T) { // Objects with equal ResourceVersion should evaluate to true. got, err := IsObjectEqual(oldS, newS) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, got) // Differences in data should be ignored. newS.Data["foo"] = []byte("baz") got, err = IsObjectEqual(oldS, newS) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, got) } @@ -151,13 +152,13 @@ func TestIsEqualFallback(t *testing.T) { // Any object (even unsupported types) with equal ResourceVersion should evaluate to true. got, err := IsObjectEqual(oldObj, newObj) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, got) // Unsupported types with unequal ResourceVersion should return an error. newObj.ResourceVersion = "456" got, err = IsObjectEqual(oldObj, newObj) - assert.Error(t, err) + require.Error(t, err) assert.False(t, got) } @@ -172,13 +173,13 @@ func TestIsEqualForGeneration(t *testing.T) { // Objects with equal Generation should evaluate to true. got, err := IsObjectEqual(oldObj, newObj) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, got) // Objects with unequal Generation should evaluate to false. newObj.SetGeneration(oldObj.GetGeneration() + 1) got, err = IsObjectEqual(oldObj, newObj) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, got) } diff --git a/internal/k8s/log_test.go b/internal/k8s/log_test.go index f86db16f0d5..1267f37b7b0 100644 --- a/internal/k8s/log_test.go +++ b/internal/k8s/log_test.go @@ -134,7 +134,7 @@ func TestControllerRuntimeLoggerLogsToLogrus(t *testing.T) { controller_runtime_log.Log.Info("some message") require.Eventually(t, func() bool { return len(logHook.AllEntries()) == 1 }, klogFlushWaitTime, klogFlushWaitInterval) - assert.Equal(t, logHook.AllEntries()[0].Message, "some message") + assert.Equal(t, "some message", logHook.AllEntries()[0].Message) } // Last LogWriterOption passed in should be used. diff --git a/internal/k8s/statusaddress_test.go b/internal/k8s/statusaddress_test.go index 7dbdf200cde..838bbbc5553 100644 --- a/internal/k8s/statusaddress_test.go +++ b/internal/k8s/statusaddress_test.go @@ -77,7 +77,7 @@ func TestServiceStatusLoadBalancerWatcherOnAdd(t *testing.T) { want := v1.LoadBalancerStatus{ Ingress: []v1.LoadBalancerIngress{{Hostname: "projectcontour.io"}}, } - assert.Equal(t, got, want) + assert.Equal(t, want, got) } func TestServiceStatusLoadBalancerWatcherOnUpdate(t *testing.T) { @@ -127,7 +127,7 @@ func TestServiceStatusLoadBalancerWatcherOnUpdate(t *testing.T) { want := v1.LoadBalancerStatus{ Ingress: []v1.LoadBalancerIngress{{Hostname: "projectcontour.io"}}, } - assert.Equal(t, got, want) + assert.Equal(t, want, got) } func TestServiceStatusLoadBalancerWatcherOnDelete(t *testing.T) { @@ -175,7 +175,7 @@ func TestServiceStatusLoadBalancerWatcherOnDelete(t *testing.T) { want := v1.LoadBalancerStatus{ Ingress: nil, } - assert.Equal(t, got, want) + assert.Equal(t, want, got) } func TestStatusAddressUpdater(t *testing.T) { diff --git a/internal/provisioner/controller/gatewayclass_test.go b/internal/provisioner/controller/gatewayclass_test.go index 9d53efe0b5a..ac302f1971c 100644 --- a/internal/provisioner/controller/gatewayclass_test.go +++ b/internal/provisioner/controller/gatewayclass_test.go @@ -47,7 +47,7 @@ func TestGatewayClassReconcile(t *testing.T) { NamespacedName: types.NamespacedName{Name: "nonexistent"}, }, assertions: func(t *testing.T, r *gatewayClassReconciler, gc *gatewayv1beta1.GatewayClass, reconcileErr error) { - assert.NoError(t, reconcileErr) + require.NoError(t, reconcileErr) gatewayClasses := &gatewayv1beta1.GatewayClassList{} require.NoError(t, r.client.List(context.Background(), gatewayClasses)) @@ -64,7 +64,7 @@ func TestGatewayClassReconcile(t *testing.T) { }, }, assertions: func(t *testing.T, r *gatewayClassReconciler, gc *gatewayv1beta1.GatewayClass, reconcileErr error) { - assert.NoError(t, reconcileErr) + require.NoError(t, reconcileErr) res := &gatewayv1beta1.GatewayClass{} require.NoError(t, r.client.Get(context.Background(), keyFor(gc), res)) diff --git a/internal/provisioner/objects/contourconfig/contourconfig_test.go b/internal/provisioner/objects/contourconfig/contourconfig_test.go index d02f41940f4..428d55323c9 100644 --- a/internal/provisioner/objects/contourconfig/contourconfig_test.go +++ b/internal/provisioner/objects/contourconfig/contourconfig_test.go @@ -332,9 +332,9 @@ func TestEnsureContourConfigDeleted(t *testing.T) { } err := client.Get(context.Background(), key, remaining) if tc.wantDelete { - assert.True(t, errors.IsNotFound(err)) + require.True(t, errors.IsNotFound(err)) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) diff --git a/internal/provisioner/objects/object_test.go b/internal/provisioner/objects/object_test.go index eb7c1aa7db7..a2af22ca69c 100644 --- a/internal/provisioner/objects/object_test.go +++ b/internal/provisioner/objects/object_test.go @@ -46,7 +46,7 @@ func TestEnsureObject_ErrorGettingObject(t *testing.T) { }, } - assert.ErrorContains(t, EnsureObject(context.Background(), client, want, nil, &corev1.Service{}), "failed to get resource obj-ns/obj-name") + require.ErrorContains(t, EnsureObject(context.Background(), client, want, nil, &corev1.Service{}), "failed to get resource obj-ns/obj-name") } func TestEnsureObject_NonExistentObjectIsCreated(t *testing.T) { @@ -161,7 +161,7 @@ func TestEnsureObject_ErrorUpdatingObject(t *testing.T) { return errors.New("update error") } - assert.ErrorContains(t, EnsureObject(context.Background(), client, desired, updater, &corev1.Service{}), "update error") + require.ErrorContains(t, EnsureObject(context.Background(), client, desired, updater, &corev1.Service{}), "update error") } func TestEnsureObjectDeleted_ObjectNotFound(t *testing.T) { diff --git a/internal/status/cache_test.go b/internal/status/cache_test.go index 70715007953..0105f469468 100644 --- a/internal/status/cache_test.go +++ b/internal/status/cache_test.go @@ -72,11 +72,11 @@ func TestCacheAcquisition(t *testing.T) { assert.Equal(t, &newEntry, cachedEntry) updates := cache.GetStatusUpdates() - assert.Equal(t, 3, len(updates)) + assert.Len(t, updates, 3) assert.Equal(t, newEntry.ID, updates[0].NamespacedName.Name) - assert.Equal(t, 3, len(cache.entries)) - assert.Equal(t, 1, len(cache.entries["HTTPProxy"])) - assert.Equal(t, 1, len(cache.entries["ExtensionService"])) - assert.Equal(t, 1, len(cache.entries["HTTPRoute"])) + assert.Len(t, cache.entries, 3) + assert.Len(t, cache.entries["HTTPProxy"], 1) + assert.Len(t, cache.entries["ExtensionService"], 1) + assert.Len(t, cache.entries["HTTPRoute"], 1) } diff --git a/internal/timeout/timeout_test.go b/internal/timeout/timeout_test.go index c077ca44133..e78ec8a2113 100644 --- a/internal/timeout/timeout_test.go +++ b/internal/timeout/timeout_test.go @@ -17,7 +17,7 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParse(t *testing.T) { @@ -60,11 +60,11 @@ func TestParse(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { got, gotErr := Parse(tc.duration) - assert.Equal(t, tc.want, got) + require.Equal(t, tc.want, got) if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } else { - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } }) } @@ -102,16 +102,16 @@ func TestParseMaxAge(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { got, gotErr := ParseMaxAge(tc.duration) - assert.Equal(t, tc.want, got) + require.Equal(t, tc.want, got) if tc.wantErr { - assert.Error(t, gotErr) + require.Error(t, gotErr) } else { - assert.NoError(t, gotErr) + require.NoError(t, gotErr) } }) } } func TestDurationSetting(t *testing.T) { - assert.Equal(t, 10*time.Second, DurationSetting(10*time.Second).Duration()) + require.Equal(t, 10*time.Second, DurationSetting(10*time.Second).Duration()) } diff --git a/internal/timeout/validation_test.go b/internal/timeout/validation_test.go index 2aa5c6b7f80..6ff4bad96f4 100644 --- a/internal/timeout/validation_test.go +++ b/internal/timeout/validation_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestKubebuilderValidation verifies that the regex used as a kubebuilder validation @@ -75,10 +76,10 @@ func TestKubebuilderValidation(t *testing.T) { if valid { assert.True(t, regexMatches, "input string %q: regex should match but does not", tc) - assert.NoError(t, parseErr, "input string %q: timeout.Parse should succeed but does not", tc) + require.NoError(t, parseErr, "input string %q", tc) } else { assert.False(t, regexMatches, "input string %q: regex should not match but does", tc) - assert.NotNil(t, parseErr, "input string %q: timeout.Parse should return an error but does not", tc) + require.Error(t, parseErr, "input string %q", tc) } } } diff --git a/internal/xds/v3/callbacks_test.go b/internal/xds/v3/callbacks_test.go index cfc0ccbf1a4..a3e66d36c3c 100644 --- a/internal/xds/v3/callbacks_test.go +++ b/internal/xds/v3/callbacks_test.go @@ -24,6 +24,7 @@ import ( "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/genproto/googleapis/rpc/code" "google.golang.org/genproto/googleapis/rpc/status" ) @@ -168,7 +169,7 @@ func TestLogDiscoveryRequestDetails(t *testing.T) { } } assert.NotNil(t, logEntry, fmt.Sprintf("no log line with expected message %q", tc.expectedLogMsg)) - assert.Equal(t, logEntry.Data, tc.expectedLogData) + assert.Equal(t, tc.expectedLogData, logEntry.Data) logHook.Reset() }) } @@ -181,7 +182,7 @@ func TestOnStreamRequestCallbackLogs(t *testing.T) { callbacks := NewRequestLoggingCallbacks(log) err := callbacks.OnStreamOpen(context.TODO(), 999, "a-type") - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, logHook.AllEntries()) logHook.Reset() @@ -195,7 +196,7 @@ func TestOnStreamRequestCallbackLogs(t *testing.T) { ResourceNames: []string{"some", "resources"}, TypeUrl: "some-type-url", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, logHook.AllEntries()) logHook.Reset() } diff --git a/internal/xds/v3/contour_test.go b/internal/xds/v3/contour_test.go index 99b07c93567..d7cd389761e 100644 --- a/internal/xds/v3/contour_test.go +++ b/internal/xds/v3/contour_test.go @@ -27,6 +27,7 @@ import ( "github.com/sirupsen/logrus" "github.com/sirupsen/logrus/hooks/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" @@ -198,7 +199,7 @@ func TestStreamLoggingConnectionClose(t *testing.T) { assert.Equal(t, tc.closeErr, err) assert.Equal(t, tc.closeErr, entry.Data["error"]) } else { - assert.Nil(t, err) + require.NoError(t, err) } logHook.Reset() diff --git a/pkg/certs/certgen_test.go b/pkg/certs/certgen_test.go index c2e244b0762..969e5410e30 100644 --- a/pkg/certs/certgen_test.go +++ b/pkg/certs/certgen_test.go @@ -20,7 +20,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -59,10 +58,10 @@ func TestGenerateCerts(t *testing.T) { require.Truef(t, ok, "Failed to set up CA cert for testing, maybe it's an invalid PEM") err = verifyCert(got.ContourCertificate, roots, tc.wantContourDNSName, currentTime) - assert.NoErrorf(t, err, "Validating %s failed", name) + require.NoErrorf(t, err, "Validating %s failed", name) err = verifyCert(got.EnvoyCertificate, roots, tc.wantEnvoyDNSName, currentTime) - assert.NoErrorf(t, err, "Validating %s failed", name) + require.NoErrorf(t, err, "Validating %s failed", name) }) } @@ -149,7 +148,7 @@ func TestGeneratedCertsValid(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { err := verifyCert(tc.cert, roots, tc.dnsname, now) - assert.NoErrorf(t, err, "Validating %s failed", name) + require.NoErrorf(t, err, "Validating %s failed", name) }) } diff --git a/pkg/config/parameters_test.go b/pkg/config/parameters_test.go index aee9291ef8d..1984091f568 100644 --- a/pkg/config/parameters_test.go +++ b/pkg/config/parameters_test.go @@ -122,48 +122,48 @@ policy: } func TestValidateClusterDNSFamilyType(t *testing.T) { - assert.Error(t, ClusterDNSFamilyType("").Validate()) - assert.Error(t, ClusterDNSFamilyType("foo").Validate()) + require.Error(t, ClusterDNSFamilyType("").Validate()) + require.Error(t, ClusterDNSFamilyType("foo").Validate()) - assert.NoError(t, AutoClusterDNSFamily.Validate()) - assert.NoError(t, IPv4ClusterDNSFamily.Validate()) - assert.NoError(t, IPv6ClusterDNSFamily.Validate()) - assert.NoError(t, AllClusterDNSFamily.Validate()) + require.NoError(t, AutoClusterDNSFamily.Validate()) + require.NoError(t, IPv4ClusterDNSFamily.Validate()) + require.NoError(t, IPv6ClusterDNSFamily.Validate()) + require.NoError(t, AllClusterDNSFamily.Validate()) } func TestValidateServerHeaderTranformationType(t *testing.T) { - assert.Error(t, ServerHeaderTransformationType("").Validate()) - assert.Error(t, ServerHeaderTransformationType("foo").Validate()) + require.Error(t, ServerHeaderTransformationType("").Validate()) + require.Error(t, ServerHeaderTransformationType("foo").Validate()) - assert.NoError(t, OverwriteServerHeader.Validate()) - assert.NoError(t, AppendIfAbsentServerHeader.Validate()) - assert.NoError(t, PassThroughServerHeader.Validate()) + require.NoError(t, OverwriteServerHeader.Validate()) + require.NoError(t, AppendIfAbsentServerHeader.Validate()) + require.NoError(t, PassThroughServerHeader.Validate()) } func TestValidateHeadersPolicy(t *testing.T) { - assert.Error(t, HeadersPolicy{ + require.Error(t, HeadersPolicy{ Set: map[string]string{ "inv@lid-header": "ook", }, }.Validate()) - assert.Error(t, HeadersPolicy{ + require.Error(t, HeadersPolicy{ Remove: []string{"inv@lid-header"}, }.Validate()) - assert.NoError(t, HeadersPolicy{ + require.NoError(t, HeadersPolicy{ Set: map[string]string{}, Remove: []string{}, }.Validate()) - assert.NoError(t, HeadersPolicy{ + require.NoError(t, HeadersPolicy{ Set: map[string]string{"X-Envoy-Host": "envoy-a12345"}, }.Validate()) - assert.NoError(t, HeadersPolicy{ + require.NoError(t, HeadersPolicy{ Set: map[string]string{ "X-Envoy-Host": "envoy-s12345", "l5d-dst-override": "kuard.default.svc.cluster.local:80", }, Remove: []string{"Sensitive-Header"}, }.Validate()) - assert.NoError(t, HeadersPolicy{ + require.NoError(t, HeadersPolicy{ Set: map[string]string{ "X-Envoy-Host": "%HOSTNAME%", "l5d-dst-override": "%CONTOUR_SERVICE_NAME%.%CONTOUR_NAMESPACE%.svc.cluster.local:%CONTOUR_SERVICE_PORT%", @@ -172,44 +172,44 @@ func TestValidateHeadersPolicy(t *testing.T) { } func TestValidateNamespacedName(t *testing.T) { - assert.NoErrorf(t, NamespacedName{}.Validate(), "empty name should be OK") - assert.NoError(t, NamespacedName{Name: "name", Namespace: "ns"}.Validate()) + require.NoErrorf(t, NamespacedName{}.Validate(), "empty name should be OK") + require.NoError(t, NamespacedName{Name: "name", Namespace: "ns"}.Validate()) - assert.Error(t, NamespacedName{Name: "name"}.Validate()) - assert.Error(t, NamespacedName{Namespace: "ns"}.Validate()) + require.Error(t, NamespacedName{Name: "name"}.Validate()) + require.Error(t, NamespacedName{Namespace: "ns"}.Validate()) } func TestValidateServerType(t *testing.T) { - assert.Error(t, ServerType("").Validate()) - assert.Error(t, ServerType("foo").Validate()) + require.Error(t, ServerType("").Validate()) + require.Error(t, ServerType("foo").Validate()) - assert.NoError(t, EnvoyServerType.Validate()) - assert.NoError(t, ContourServerType.Validate()) + require.NoError(t, EnvoyServerType.Validate()) + require.NoError(t, ContourServerType.Validate()) } func TestValidateGatewayParameters(t *testing.T) { // Not required if nothing is passed. var gw *GatewayParameters - assert.Equal(t, nil, gw.Validate()) + require.NoError(t, gw.Validate()) // ControllerName is required. gw = &GatewayParameters{ControllerName: "controller"} - assert.Equal(t, nil, gw.Validate()) + require.NoError(t, gw.Validate()) } func TestValidateHTTPVersionType(t *testing.T) { - assert.Error(t, HTTPVersionType("").Validate()) - assert.Error(t, HTTPVersionType("foo").Validate()) - assert.Error(t, HTTPVersionType("HTTP/1.1").Validate()) - assert.Error(t, HTTPVersionType("HTTP/2").Validate()) + require.Error(t, HTTPVersionType("").Validate()) + require.Error(t, HTTPVersionType("foo").Validate()) + require.Error(t, HTTPVersionType("HTTP/1.1").Validate()) + require.Error(t, HTTPVersionType("HTTP/2").Validate()) - assert.NoError(t, HTTPVersion1.Validate()) - assert.NoError(t, HTTPVersion2.Validate()) + require.NoError(t, HTTPVersion1.Validate()) + require.NoError(t, HTTPVersion2.Validate()) } func TestValidateTimeoutParams(t *testing.T) { - assert.NoError(t, TimeoutParameters{}.Validate()) - assert.NoError(t, TimeoutParameters{ + require.NoError(t, TimeoutParameters{}.Validate()) + require.NoError(t, TimeoutParameters{ RequestTimeout: "infinite", ConnectionIdleTimeout: "infinite", StreamIdleTimeout: "infinite", @@ -218,7 +218,7 @@ func TestValidateTimeoutParams(t *testing.T) { ConnectionShutdownGracePeriod: "infinite", ConnectTimeout: "2s", }.Validate()) - assert.NoError(t, TimeoutParameters{ + require.NoError(t, TimeoutParameters{ RequestTimeout: "infinity", ConnectionIdleTimeout: "infinity", StreamIdleTimeout: "infinity", @@ -228,25 +228,25 @@ func TestValidateTimeoutParams(t *testing.T) { ConnectTimeout: "2s", }.Validate()) - assert.Error(t, TimeoutParameters{RequestTimeout: "foo"}.Validate()) - assert.Error(t, TimeoutParameters{ConnectionIdleTimeout: "bar"}.Validate()) - assert.Error(t, TimeoutParameters{StreamIdleTimeout: "baz"}.Validate()) - assert.Error(t, TimeoutParameters{MaxConnectionDuration: "boop"}.Validate()) - assert.Error(t, TimeoutParameters{DelayedCloseTimeout: "bebop"}.Validate()) - assert.Error(t, TimeoutParameters{ConnectionShutdownGracePeriod: "bong"}.Validate()) - assert.Error(t, TimeoutParameters{ConnectTimeout: "infinite"}.Validate()) + require.Error(t, TimeoutParameters{RequestTimeout: "foo"}.Validate()) + require.Error(t, TimeoutParameters{ConnectionIdleTimeout: "bar"}.Validate()) + require.Error(t, TimeoutParameters{StreamIdleTimeout: "baz"}.Validate()) + require.Error(t, TimeoutParameters{MaxConnectionDuration: "boop"}.Validate()) + require.Error(t, TimeoutParameters{DelayedCloseTimeout: "bebop"}.Validate()) + require.Error(t, TimeoutParameters{ConnectionShutdownGracePeriod: "bong"}.Validate()) + require.Error(t, TimeoutParameters{ConnectTimeout: "infinite"}.Validate()) } func TestTLSParametersValidation(t *testing.T) { // Fallback certificate validation - assert.NoError(t, TLSParameters{ + require.NoError(t, TLSParameters{ FallbackCertificate: NamespacedName{ Name: " ", Namespace: " ", }, }.Validate()) - assert.Error(t, TLSParameters{ + require.Error(t, TLSParameters{ FallbackCertificate: NamespacedName{ Name: "somename", Namespace: " ", @@ -254,13 +254,13 @@ func TestTLSParametersValidation(t *testing.T) { }.Validate()) // Client certificate validation - assert.NoError(t, TLSParameters{ + require.NoError(t, TLSParameters{ ClientCertificate: NamespacedName{ Name: " ", Namespace: " ", }, }.Validate()) - assert.Error(t, TLSParameters{ + require.Error(t, TLSParameters{ ClientCertificate: NamespacedName{ Name: "", Namespace: "somenamespace ", @@ -268,51 +268,51 @@ func TestTLSParametersValidation(t *testing.T) { }.Validate()) // Cipher suites validation - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ CipherSuites: []string{}, }.Validate()) - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ CipherSuites: []string{ "[ECDHE-ECDSA-AES128-GCM-SHA256|ECDHE-ECDSA-CHACHA20-POLY1305]", "ECDHE-ECDSA-AES128-GCM-SHA256", }, }.Validate()) - assert.Error(t, ProtocolParameters{ + require.Error(t, ProtocolParameters{ CipherSuites: []string{ "NOTAVALIDCIPHER", }, }.Validate()) // TLS protocol version validation - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ MinimumProtocolVersion: "1.2", }.Validate()) - assert.Error(t, ProtocolParameters{ + require.Error(t, ProtocolParameters{ MinimumProtocolVersion: "1.1", }.Validate()) - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ MaximumProtocolVersion: "1.3", }.Validate()) - assert.Error(t, ProtocolParameters{ + require.Error(t, ProtocolParameters{ MaximumProtocolVersion: "invalid", }.Validate()) - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ MinimumProtocolVersion: "1.2", MaximumProtocolVersion: "1.3", }.Validate()) - assert.Error(t, ProtocolParameters{ + require.Error(t, ProtocolParameters{ MinimumProtocolVersion: "1.3", MaximumProtocolVersion: "1.2", }.Validate()) - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ MinimumProtocolVersion: "1.2", MaximumProtocolVersion: "1.2", }.Validate()) - assert.NoError(t, ProtocolParameters{ + require.NoError(t, ProtocolParameters{ MinimumProtocolVersion: "1.3", MaximumProtocolVersion: "1.3", }.Validate()) - assert.Error(t, ProtocolParameters{ + require.Error(t, ProtocolParameters{ MinimumProtocolVersion: "1.1", MaximumProtocolVersion: "1.3", }.Validate()) @@ -522,7 +522,7 @@ func TestMetricsParametersValidation(t *testing.T) { Port: 1234, }, } - assert.NoError(t, valid.Validate()) + require.NoError(t, valid.Validate()) tlsValid := MetricsParameters{ Contour: MetricsServerParameters{ @@ -536,7 +536,7 @@ func TestMetricsParametersValidation(t *testing.T) { Port: 1234, }, } - assert.NoError(t, valid.Validate()) + require.NoError(t, valid.Validate()) assert.True(t, tlsValid.Contour.HasTLS()) assert.False(t, tlsValid.Envoy.HasTLS()) @@ -551,7 +551,7 @@ func TestMetricsParametersValidation(t *testing.T) { Port: 1234, }, } - assert.Error(t, tlsKeyMissing.Validate()) + require.Error(t, tlsKeyMissing.Validate()) tlsCAWithoutServerCert := MetricsParameters{ Contour: MetricsServerParameters{ @@ -564,7 +564,7 @@ func TestMetricsParametersValidation(t *testing.T) { CABundle: "ca.pem", }, } - assert.Error(t, tlsCAWithoutServerCert.Validate()) + require.Error(t, tlsCAWithoutServerCert.Validate()) } diff --git a/test/e2e/gateway/response_header_modifier_test.go b/test/e2e/gateway/response_header_modifier_test.go index 9e025a90daf..d59501eec6c 100644 --- a/test/e2e/gateway/response_header_modifier_test.go +++ b/test/e2e/gateway/response_header_modifier_test.go @@ -113,22 +113,20 @@ func testResponseHeaderModifierBackendRef(namespace string, gateway types.Namesp switch body.Service { case "echo-header-filter": assert.Len(t, res.Headers["My-Header"], 1) - assert.Equal(t, res.Headers.Get("My-Header"), "Foo") + assert.Equal(t, "Foo", res.Headers.Get("My-Header")) assert.Len(t, res.Headers["Replace-Header"], 1) - assert.Equal(t, res.Headers.Get("Replace-Header"), "Bar") + assert.Equal(t, "Bar", res.Headers.Get("Replace-Header")) - assert.Len(t, res.Headers["Other-Header"], 0) - assert.Equal(t, res.Headers.Get("Other-Header"), "") + assert.Empty(t, res.Headers["Other-Header"]) case "echo-header-nofilter": - assert.Len(t, res.Headers["My-Header"], 0) - assert.Equal(t, res.Headers.Get("My-Header"), "") + assert.Empty(t, res.Headers["My-Header"]) assert.Len(t, res.Headers["Replace-Header"], 1) - assert.Equal(t, res.Headers.Get("Replace-Header"), "Tobe-Replaced") + assert.Equal(t, "Tobe-Replaced", res.Headers.Get("Replace-Header")) assert.Len(t, res.Headers["Other-Header"], 1) - assert.Equal(t, res.Headers.Get("Other-Header"), "Remove") + assert.Equal(t, "Remove", res.Headers.Get("Other-Header")) } } assert.Contains(t, seenBackends, "echo-header-filter") diff --git a/test/e2e/httpproxy/cookie_rewrite_test.go b/test/e2e/httpproxy/cookie_rewrite_test.go index 304f2e7bd59..d5cd40605ff 100644 --- a/test/e2e/httpproxy/cookie_rewrite_test.go +++ b/test/e2e/httpproxy/cookie_rewrite_test.go @@ -75,7 +75,7 @@ func testInvalidCookieRewriteFields(namespace string) { }, }, } - assert.Error(f.T(), f.Client.Create(context.TODO(), p), "expected char %d to be invalid in cookie name", c) + require.Error(f.T(), f.Client.Create(context.TODO(), p), "expected char %d to be invalid in cookie name", c) } // ;, DEL, and control chars. @@ -108,7 +108,7 @@ func testInvalidCookieRewriteFields(namespace string) { }, }, } - assert.Error(f.T(), f.Client.Create(context.TODO(), p), "expected char %d to be invalid in path rewrite", c) + require.Error(f.T(), f.Client.Create(context.TODO(), p), "expected char %d to be invalid in path rewrite", c) } invalidDomains := []string{ @@ -144,7 +144,7 @@ func testInvalidCookieRewriteFields(namespace string) { }, }, } - assert.Error(f.T(), f.Client.Create(context.TODO(), p), "expected domain rewrite %q to be invalid", d) + require.Error(f.T(), f.Client.Create(context.TODO(), p), "expected domain rewrite %q to be invalid", d) } p := &contourv1.HTTPProxy{ @@ -174,7 +174,7 @@ func testInvalidCookieRewriteFields(namespace string) { }, }, } - assert.Error(f.T(), f.Client.Create(context.TODO(), p), "expected invalid SameSite to be rejected") + require.Error(f.T(), f.Client.Create(context.TODO(), p), "expected invalid SameSite to be rejected") }) } diff --git a/test/e2e/httpproxy/fqdn_test.go b/test/e2e/httpproxy/fqdn_test.go index 7d732c41454..cb7b2a1fbed 100644 --- a/test/e2e/httpproxy/fqdn_test.go +++ b/test/e2e/httpproxy/fqdn_test.go @@ -52,7 +52,7 @@ func testWildcardFQDN(namespace string) { // Creation should fail the kubebuilder CRD validations. err := f.CreateHTTPProxy(p) - require.NotNil(t, err, "Expected invalid wildcard to be rejected.") + require.Error(t, err, "Expected invalid wildcard to be rejected.") }) } diff --git a/test/e2e/httpproxy/grpc_test.go b/test/e2e/httpproxy/grpc_test.go index 4e5f68acaeb..962e163f003 100644 --- a/test/e2e/httpproxy/grpc_test.go +++ b/test/e2e/httpproxy/grpc_test.go @@ -244,7 +244,7 @@ func parseGRPCWebResponse(body []byte) grpcWebResponse { currentPos += 4 if trailersLen > 0 { - require.Equal(t, len(body), currentPos+trailersLen) + require.Len(t, body, currentPos+trailersLen) trailersKV := strings.Split(strings.TrimSpace(string(body[currentPos:])), "\r\n") for _, kv := range trailersKV { diff --git a/test/e2e/httpproxy/internal_redirect_test.go b/test/e2e/httpproxy/internal_redirect_test.go index df5ec742141..32e5068ea79 100644 --- a/test/e2e/httpproxy/internal_redirect_test.go +++ b/test/e2e/httpproxy/internal_redirect_test.go @@ -57,7 +57,7 @@ func testInternalRedirectValidation(namespace string) { // Creation should fail the kubebuilder CRD validations. err := f.CreateHTTPProxy(p) - require.NotNil(t, err, "Expected invalid AllowCrossSchemeRedirect to be rejected.") + require.Error(t, err, "Expected invalid AllowCrossSchemeRedirect to be rejected.") }) Specify("invalid redirect code", func() { @@ -86,7 +86,7 @@ func testInternalRedirectValidation(namespace string) { // Creation should fail the kubebuilder CRD validations. err := f.CreateHTTPProxy(p) - require.NotNil(t, err, "Expected invalid RedirectResponseCodes to be rejected.") + require.Error(t, err, "Expected invalid RedirectResponseCodes to be rejected.") }) } diff --git a/test/e2e/httpproxy/namespaces_test.go b/test/e2e/httpproxy/namespaces_test.go index 721470fb45a..fed4d96669a 100644 --- a/test/e2e/httpproxy/namespaces_test.go +++ b/test/e2e/httpproxy/namespaces_test.go @@ -48,7 +48,7 @@ func testWatchNamespaces(namespaces []string) e2e.NamespacedTestBody { deployEchoServer(f.T(), f.Client, nonWatchedNS, "echo") p := newEchoProxy("proxy", nonWatchedNS) err := f.CreateHTTPProxy(p) - require.Nil(f.T(), err, "could not create httpproxy") + require.NoError(f.T(), err, "could not create httpproxy") require.Never(f.T(), func() bool { res := &contourv1.HTTPProxy{} if err := f.Client.Get(context.TODO(), client.ObjectKeyFromObject(p), res); err != nil { @@ -121,7 +121,7 @@ func testWatchAndRootNamespaces(rootNamespaces []string, nonRootNamespace string }, } err := f.CreateHTTPProxy(lp) - require.Nil(f.T(), err, "could not create leaf httpproxy") + require.NoError(f.T(), err, "could not create leaf httpproxy") f.CreateHTTPProxyAndWaitFor(p, e2e.HTTPProxyValid) res, ok := f.HTTP.RequestUntil(&e2e.HTTPRequestOpts{ Host: p.Spec.VirtualHost.Fqdn, @@ -134,7 +134,7 @@ func testWatchAndRootNamespaces(rootNamespaces []string, nonRootNamespace string deployEchoServer(f.T(), f.Client, nonWatchedNS, "echo") p = newEchoProxy("root-proxy", nonWatchedNS) err = f.CreateHTTPProxy(p) - require.Nil(f.T(), err, "could not create httpproxy") + require.NoError(f.T(), err, "could not create httpproxy") require.Never(f.T(), func() bool { res := &contourv1.HTTPProxy{} if err := f.Client.Get(context.TODO(), client.ObjectKeyFromObject(p), res); err != nil { diff --git a/test/e2e/httpproxy/request_redirect_test.go b/test/e2e/httpproxy/request_redirect_test.go index 5b530a85fd9..a90f63fbdfe 100644 --- a/test/e2e/httpproxy/request_redirect_test.go +++ b/test/e2e/httpproxy/request_redirect_test.go @@ -35,7 +35,7 @@ func testRequestRedirectRuleNoService(namespace string) { proxy := getRedirectHTTPProxy(namespace, true) for _, route := range proxy.Spec.Routes { - require.Equal(t, 0, len(route.Services)) + require.Empty(t, route.Services) } doRedirectTest(namespace, proxy, t) diff --git a/test/e2e/upgrade/upgrade_test.go b/test/e2e/upgrade/upgrade_test.go index ed519899930..49f794ac3c8 100644 --- a/test/e2e/upgrade/upgrade_test.go +++ b/test/e2e/upgrade/upgrade_test.go @@ -68,7 +68,7 @@ var _ = Describe("When upgrading", func() { // We should be running in a multi-node cluster with a proper load // balancer, so fetch load balancer ip to make requests to. require.NoError(f.T(), f.Client.Get(context.TODO(), client.ObjectKeyFromObject(f.Deployment.EnvoyService), f.Deployment.EnvoyService)) - require.Greater(f.T(), len(f.Deployment.EnvoyService.Status.LoadBalancer.Ingress), 0) + require.NotEmpty(f.T(), f.Deployment.EnvoyService.Status.LoadBalancer.Ingress) require.NotEmpty(f.T(), f.Deployment.EnvoyService.Status.LoadBalancer.Ingress[0].IP) f.HTTP.HTTPURLBase = "http://" + f.Deployment.EnvoyService.Status.LoadBalancer.Ingress[0].IP f.HTTP.HTTPSURLBase = "https://" + f.Deployment.EnvoyService.Status.LoadBalancer.Ingress[0].IP