From 31f6f55bbe4177e3d39ed1c6023d15ccc8fa6bfb Mon Sep 17 00:00:00 2001 From: "R.B. Boyer" Date: Thu, 20 Jan 2022 10:45:56 -0600 Subject: [PATCH] test: normalize require.New and assert.New syntax --- acl/policy_test.go | 38 +++++------ agent/cache-types/connect_ca_leaf_test.go | 3 +- agent/connect/generate_test.go | 45 ++++++------- agent/connect_ca_endpoint_test.go | 12 ++-- agent/consul/connect_ca_endpoint_test.go | 5 +- agent/consul/logging_test.go | 9 ++- agent/consul/state/catalog_test.go | 5 +- agent/event_endpoint_test.go | 37 +++++------ command/acl/token/clone/token_clone_test.go | 64 +++++++++---------- command/acl/token/update/token_update_test.go | 6 +- command/services/config_test.go | 6 +- 11 files changed, 111 insertions(+), 119 deletions(-) diff --git a/acl/policy_test.go b/acl/policy_test.go index fd0e9dba50..90854449a7 100644 --- a/acl/policy_test.go +++ b/acl/policy_test.go @@ -1516,30 +1516,30 @@ func TestMergePolicies(t *testing.T) { }, } - req := require.New(t) + require := require.New(t) for _, tcase := range tests { t.Run(tcase.name, func(t *testing.T) { act := MergePolicies(tcase.input) exp := tcase.expected - req.Equal(exp.ACL, act.ACL) - req.Equal(exp.Keyring, act.Keyring) - req.Equal(exp.Operator, act.Operator) - req.Equal(exp.Mesh, act.Mesh) - req.ElementsMatch(exp.Agents, act.Agents) - req.ElementsMatch(exp.AgentPrefixes, act.AgentPrefixes) - req.ElementsMatch(exp.Events, act.Events) - req.ElementsMatch(exp.EventPrefixes, act.EventPrefixes) - req.ElementsMatch(exp.Keys, act.Keys) - req.ElementsMatch(exp.KeyPrefixes, act.KeyPrefixes) - req.ElementsMatch(exp.Nodes, act.Nodes) - req.ElementsMatch(exp.NodePrefixes, act.NodePrefixes) - req.ElementsMatch(exp.PreparedQueries, act.PreparedQueries) - req.ElementsMatch(exp.PreparedQueryPrefixes, act.PreparedQueryPrefixes) - req.ElementsMatch(exp.Services, act.Services) - req.ElementsMatch(exp.ServicePrefixes, act.ServicePrefixes) - req.ElementsMatch(exp.Sessions, act.Sessions) - req.ElementsMatch(exp.SessionPrefixes, act.SessionPrefixes) + require.Equal(exp.ACL, act.ACL) + require.Equal(exp.Keyring, act.Keyring) + require.Equal(exp.Operator, act.Operator) + require.Equal(exp.Mesh, act.Mesh) + require.ElementsMatch(exp.Agents, act.Agents) + require.ElementsMatch(exp.AgentPrefixes, act.AgentPrefixes) + require.ElementsMatch(exp.Events, act.Events) + require.ElementsMatch(exp.EventPrefixes, act.EventPrefixes) + require.ElementsMatch(exp.Keys, act.Keys) + require.ElementsMatch(exp.KeyPrefixes, act.KeyPrefixes) + require.ElementsMatch(exp.Nodes, act.Nodes) + require.ElementsMatch(exp.NodePrefixes, act.NodePrefixes) + require.ElementsMatch(exp.PreparedQueries, act.PreparedQueries) + require.ElementsMatch(exp.PreparedQueryPrefixes, act.PreparedQueryPrefixes) + require.ElementsMatch(exp.Services, act.Services) + require.ElementsMatch(exp.ServicePrefixes, act.ServicePrefixes) + require.ElementsMatch(exp.Sessions, act.Sessions) + require.ElementsMatch(exp.SessionPrefixes, act.SessionPrefixes) }) } diff --git a/agent/cache-types/connect_ca_leaf_test.go b/agent/cache-types/connect_ca_leaf_test.go index 10ec02b10a..c2fccf9839 100644 --- a/agent/cache-types/connect_ca_leaf_test.go +++ b/agent/cache-types/connect_ca_leaf_test.go @@ -406,8 +406,7 @@ func TestConnectCALeaf_changingRootsJitterBetweenCalls(t *testing.T) { // Sanity check that we've not gone way beyond the deadline without a // new cert. We give some leeway to make it less brittle. - require.Falsef( - time.Now().After(shouldExpireAfter.Add(100*time.Millisecond)), + require.Falsef(time.Now().After(shouldExpireAfter.Add(100*time.Millisecond)), "waited extra 100ms and delayed CA rotate renew didn't happen") } } diff --git a/agent/connect/generate_test.go b/agent/connect/generate_test.go index bd328f69f6..21e2f72e97 100644 --- a/agent/connect/generate_test.go +++ b/agent/connect/generate_test.go @@ -8,8 +8,9 @@ import ( "crypto/x509" "encoding/pem" - "github.com/hashicorp/consul/agent/structs" "github.com/stretchr/testify/require" + + "github.com/hashicorp/consul/agent/structs" ) type KeyConfig struct { @@ -47,32 +48,32 @@ func makeConfig(kc KeyConfig) structs.CommonCAProviderConfig { } func testGenerateRSAKey(t *testing.T, bits int) { - r := require.New(t) + require := require.New(t) _, rsaBlock, err := GeneratePrivateKeyWithConfig("rsa", bits) - r.NoError(err) - r.Contains(rsaBlock, "RSA PRIVATE KEY") + require.NoError(err) + require.Contains(rsaBlock, "RSA PRIVATE KEY") rsaBytes, _ := pem.Decode([]byte(rsaBlock)) - r.NotNil(rsaBytes) + require.NotNil(rsaBytes) rsaKey, err := x509.ParsePKCS1PrivateKey(rsaBytes.Bytes) - r.NoError(err) - r.NoError(rsaKey.Validate()) - r.Equal(bits/8, rsaKey.Size()) // note: returned size is in bytes. 2048/8==256 + require.NoError(err) + require.NoError(rsaKey.Validate()) + require.Equal(bits/8, rsaKey.Size()) // note: returned size is in bytes. 2048/8==256 } func testGenerateECDSAKey(t *testing.T, bits int) { - r := require.New(t) + require := require.New(t) _, pemBlock, err := GeneratePrivateKeyWithConfig("ec", bits) - r.NoError(err) - r.Contains(pemBlock, "EC PRIVATE KEY") + require.NoError(err) + require.Contains(pemBlock, "EC PRIVATE KEY") block, _ := pem.Decode([]byte(pemBlock)) - r.NotNil(block) + require.NotNil(block) pk, err := x509.ParseECPrivateKey(block.Bytes) - r.NoError(err) - r.Equal(bits, pk.Curve.Params().BitSize) + require.NoError(err) + require.Equal(bits, pk.Curve.Params().BitSize) } // Tests to make sure we are able to generate every type of private key supported by the x509 lib. @@ -104,7 +105,7 @@ func TestValidateGoodConfigs(t *testing.T) { config := makeConfig(params) t.Run(fmt.Sprintf("TestValidateGoodConfigs-%s-%d", params.keyType, params.keyBits), func(t *testing.T) { - require.New(t).NoError(config.Validate(), "unexpected error: type=%s bits=%d", + require.NoError(t, config.Validate(), "unexpected error: type=%s bits=%d", params.keyType, params.keyBits) }) @@ -117,7 +118,7 @@ func TestValidateBadConfigs(t *testing.T) { for _, params := range badParams { config := makeConfig(params) t.Run(fmt.Sprintf("TestValidateBadConfigs-%s-%d", params.keyType, params.keyBits), func(t *testing.T) { - require.New(t).Error(config.Validate(), "expected error: type=%s bits=%d", + require.Error(t, config.Validate(), "expected error: type=%s bits=%d", params.keyType, params.keyBits) }) } @@ -131,7 +132,7 @@ func TestSignatureMismatches(t *testing.T) { } t.Parallel() - r := require.New(t) + require := require.New(t) for _, p1 := range goodParams { for _, p2 := range goodParams { if p1 == p2 { @@ -139,14 +140,14 @@ func TestSignatureMismatches(t *testing.T) { } t.Run(fmt.Sprintf("TestMismatches-%s%d-%s%d", p1.keyType, p1.keyBits, p2.keyType, p2.keyBits), func(t *testing.T) { ca := TestCAWithKeyType(t, nil, p1.keyType, p1.keyBits) - r.Equal(p1.keyType, ca.PrivateKeyType) - r.Equal(p1.keyBits, ca.PrivateKeyBits) + require.Equal(p1.keyType, ca.PrivateKeyType) + require.Equal(p1.keyBits, ca.PrivateKeyBits) certPEM, keyPEM, err := testLeaf(t, "foobar.service.consul", "default", ca, p2.keyType, p2.keyBits) - r.NoError(err) + require.NoError(err) _, err = ParseCert(certPEM) - r.NoError(err) + require.NoError(err) _, err = ParseSigner(keyPEM) - r.NoError(err) + require.NoError(err) }) } } diff --git a/agent/connect_ca_endpoint_test.go b/agent/connect_ca_endpoint_test.go index 44dfc0acb8..0256151f89 100644 --- a/agent/connect_ca_endpoint_test.go +++ b/agent/connect_ca_endpoint_test.go @@ -43,7 +43,7 @@ func TestConnectCARoots_list(t *testing.T) { t.Parallel() - assertion := assert.New(t) + assert := assert.New(t) a := NewTestAgent(t, "") defer a.Shutdown() testrpc.WaitForTestAgent(t, a.RPC, "dc1") @@ -56,16 +56,16 @@ func TestConnectCARoots_list(t *testing.T) { req, _ := http.NewRequest("GET", "/v1/connect/ca/roots", nil) resp := httptest.NewRecorder() obj, err := a.srv.ConnectCARoots(resp, req) - assertion.NoError(err) + assert.NoError(err) value := obj.(structs.IndexedCARoots) - assertion.Equal(value.ActiveRootID, ca2.ID) - assertion.Len(value.Roots, 2) + assert.Equal(value.ActiveRootID, ca2.ID) + assert.Len(value.Roots, 2) // We should never have the secret information for _, r := range value.Roots { - assertion.Equal("", r.SigningCert) - assertion.Equal("", r.SigningKey) + assert.Equal("", r.SigningCert) + assert.Equal("", r.SigningKey) } } diff --git a/agent/consul/connect_ca_endpoint_test.go b/agent/consul/connect_ca_endpoint_test.go index 84ea9f69a8..89c4b2a05e 100644 --- a/agent/consul/connect_ca_endpoint_test.go +++ b/agent/consul/connect_ca_endpoint_test.go @@ -899,7 +899,6 @@ func TestConnectCASign(t *testing.T) { func BenchmarkConnectCASign(b *testing.B) { t := &testing.T{} - require := require.New(b) dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() @@ -919,7 +918,9 @@ func BenchmarkConnectCASign(b *testing.B) { b.ResetTimer() for n := 0; n < b.N; n++ { - require.NoError(msgpackrpc.CallWithCodec(codec, "ConnectCA.Sign", args, &reply)) + if err := msgpackrpc.CallWithCodec(codec, "ConnectCA.Sign", args, &reply); err != nil { + b.Fatalf("err: %v", err) + } } } diff --git a/agent/consul/logging_test.go b/agent/consul/logging_test.go index 720f229f8b..4933600379 100644 --- a/agent/consul/logging_test.go +++ b/agent/consul/logging_test.go @@ -3,8 +3,9 @@ package consul import ( "testing" - "github.com/hashicorp/consul/sdk/testutil" "github.com/stretchr/testify/require" + + "github.com/hashicorp/consul/sdk/testutil" ) func TestLoggerStore_Named(t *testing.T) { @@ -17,8 +18,7 @@ func TestLoggerStore_Named(t *testing.T) { l1 := store.Named("test1") l2 := store.Named("test2") - require.Truef( - l1 != l2, + require.Truef(l1 != l2, "expected %p and %p to have a different memory address", l1, l2, @@ -35,8 +35,7 @@ func TestLoggerStore_NamedCache(t *testing.T) { l1 := store.Named("test") l2 := store.Named("test") - require.Truef( - l1 == l2, + require.Truef(l1 == l2, "expected %p and %p to have the same memory address", l1, l2, diff --git a/agent/consul/state/catalog_test.go b/agent/consul/state/catalog_test.go index b3a41855ab..295176a177 100644 --- a/agent/consul/state/catalog_test.go +++ b/agent/consul/state/catalog_test.go @@ -2389,9 +2389,8 @@ func TestStateStore_ConnectServiceNodes(t *testing.T) { assert.Len(nodes, 3) for _, n := range nodes { - assert.True( - n.ServiceKind == structs.ServiceKindConnectProxy || - n.ServiceConnect.Native, + assert.True(n.ServiceKind == structs.ServiceKindConnectProxy || + n.ServiceConnect.Native, "either proxy or connect native") } diff --git a/agent/event_endpoint_test.go b/agent/event_endpoint_test.go index d3ca95077b..d430c15ddb 100644 --- a/agent/event_endpoint_test.go +++ b/agent/event_endpoint_test.go @@ -9,10 +9,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/hashicorp/consul/acl" "github.com/hashicorp/consul/sdk/testutil/retry" "github.com/hashicorp/consul/testrpc" - "github.com/stretchr/testify/require" ) func TestEventFire(t *testing.T) { @@ -212,25 +213,21 @@ func TestEventList_ACLFilter(t *testing.T) { t.Run("no token", func(t *testing.T) { retry.Run(t, func(r *retry.R) { - require := require.New(r) - req := httptest.NewRequest("GET", "/v1/event/list", nil) resp := httptest.NewRecorder() obj, err := a.srv.EventList(resp, req) - require.NoError(err) + require.NoError(r, err) list, ok := obj.([]*UserEvent) - require.True(ok) - require.Empty(list) - require.Empty(resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) + require.True(r, ok) + require.Empty(r, list) + require.Empty(r, resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) }) }) t.Run("token with access to one event type", func(t *testing.T) { retry.Run(t, func(r *retry.R) { - require := require.New(r) - token := testCreateToken(t, a, ` event "foo" { policy = "read" @@ -241,37 +238,35 @@ func TestEventList_ACLFilter(t *testing.T) { resp := httptest.NewRecorder() obj, err := a.srv.EventList(resp, req) - require.NoError(err) + require.NoError(r, err) list, ok := obj.([]*UserEvent) - require.True(ok) - require.Len(list, 1) - require.Equal("foo", list[0].Name) - require.NotEmpty(resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) + require.True(r, ok) + require.Len(r, list, 1) + require.Equal(r, "foo", list[0].Name) + require.NotEmpty(r, resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) }) }) t.Run("root token", func(t *testing.T) { retry.Run(t, func(r *retry.R) { - require := require.New(r) - req := httptest.NewRequest("GET", "/v1/event/list?token=root", nil) resp := httptest.NewRecorder() obj, err := a.srv.EventList(resp, req) - require.NoError(err) + require.NoError(r, err) list, ok := obj.([]*UserEvent) - require.True(ok) - require.Len(list, 2) + require.True(r, ok) + require.Len(r, list, 2) var names []string for _, e := range list { names = append(names, e.Name) } - require.ElementsMatch([]string{"foo", "bar"}, names) + require.ElementsMatch(r, []string{"foo", "bar"}, names) - require.Empty(resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) + require.Empty(r, resp.Header().Get("X-Consul-Results-Filtered-By-ACLs")) }) }) } diff --git a/command/acl/token/clone/token_clone_test.go b/command/acl/token/clone/token_clone_test.go index ec7c4ebcc5..0c6b56c206 100644 --- a/command/acl/token/clone/token_clone_test.go +++ b/command/acl/token/clone/token_clone_test.go @@ -65,7 +65,7 @@ func TestTokenCloneCommand_Pretty(t *testing.T) { } t.Parallel() - req := require.New(t) + require := require.New(t) a := agent.NewTestAgent(t, ` primary_datacenter = "dc1" @@ -86,14 +86,14 @@ func TestTokenCloneCommand_Pretty(t *testing.T) { &api.ACLPolicy{Name: "test-policy"}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(err) // create a token token, _, err := client.ACL().TokenCreate( &api.ACLToken{Description: "test", Policies: []*api.ACLTokenPolicyLink{{Name: "test-policy"}}}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(err) // clone with description t.Run("Description", func(t *testing.T) { @@ -108,27 +108,27 @@ func TestTokenCloneCommand_Pretty(t *testing.T) { } code := cmd.Run(args) - req.Empty(ui.ErrorWriter.String()) - req.Equal(code, 0) + require.Empty(ui.ErrorWriter.String()) + require.Equal(code, 0) cloned := parseCloneOutput(t, ui.OutputWriter.String()) - req.Equal("test cloned", cloned.Description) - req.Len(cloned.Policies, 1) + require.Equal("test cloned", cloned.Description) + require.Len(cloned.Policies, 1) apiToken, _, err := client.ACL().TokenRead( cloned.AccessorID, &api.QueryOptions{Token: "root"}, ) - req.NoError(err) - req.NotNil(apiToken) + require.NoError(err) + require.NotNil(apiToken) - req.Equal(cloned.AccessorID, apiToken.AccessorID) - req.Equal(cloned.SecretID, apiToken.SecretID) - req.Equal(cloned.Description, apiToken.Description) - req.Equal(cloned.Local, apiToken.Local) - req.Equal(cloned.Policies, apiToken.Policies) + require.Equal(cloned.AccessorID, apiToken.AccessorID) + require.Equal(cloned.SecretID, apiToken.SecretID) + require.Equal(cloned.Description, apiToken.Description) + require.Equal(cloned.Local, apiToken.Local) + require.Equal(cloned.Policies, apiToken.Policies) }) // clone without description @@ -143,27 +143,27 @@ func TestTokenCloneCommand_Pretty(t *testing.T) { } code := cmd.Run(args) - req.Equal(code, 0) - req.Empty(ui.ErrorWriter.String()) + require.Equal(code, 0) + require.Empty(ui.ErrorWriter.String()) cloned := parseCloneOutput(t, ui.OutputWriter.String()) - req.Equal("test", cloned.Description) - req.Len(cloned.Policies, 1) + require.Equal("test", cloned.Description) + require.Len(cloned.Policies, 1) apiToken, _, err := client.ACL().TokenRead( cloned.AccessorID, &api.QueryOptions{Token: "root"}, ) - req.NoError(err) - req.NotNil(apiToken) + require.NoError(err) + require.NotNil(apiToken) - req.Equal(cloned.AccessorID, apiToken.AccessorID) - req.Equal(cloned.SecretID, apiToken.SecretID) - req.Equal(cloned.Description, apiToken.Description) - req.Equal(cloned.Local, apiToken.Local) - req.Equal(cloned.Policies, apiToken.Policies) + require.Equal(cloned.AccessorID, apiToken.AccessorID) + require.Equal(cloned.SecretID, apiToken.SecretID) + require.Equal(cloned.Description, apiToken.Description) + require.Equal(cloned.Local, apiToken.Local) + require.Equal(cloned.Policies, apiToken.Policies) }) } @@ -173,7 +173,7 @@ func TestTokenCloneCommand_JSON(t *testing.T) { } t.Parallel() - req := require.New(t) + require := require.New(t) a := agent.NewTestAgent(t, ` primary_datacenter = "dc1" @@ -194,14 +194,14 @@ func TestTokenCloneCommand_JSON(t *testing.T) { &api.ACLPolicy{Name: "test-policy"}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(err) // create a token token, _, err := client.ACL().TokenCreate( &api.ACLToken{Description: "test", Policies: []*api.ACLTokenPolicyLink{{Name: "test-policy"}}}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(err) // clone with description t.Run("Description", func(t *testing.T) { @@ -217,8 +217,8 @@ func TestTokenCloneCommand_JSON(t *testing.T) { } code := cmd.Run(args) - req.Empty(ui.ErrorWriter.String()) - req.Equal(code, 0) + require.Empty(ui.ErrorWriter.String()) + require.Equal(code, 0) output := ui.OutputWriter.String() var jsonOutput json.RawMessage @@ -239,8 +239,8 @@ func TestTokenCloneCommand_JSON(t *testing.T) { } code := cmd.Run(args) - req.Empty(ui.ErrorWriter.String()) - req.Equal(code, 0) + require.Empty(ui.ErrorWriter.String()) + require.Equal(code, 0) output := ui.OutputWriter.String() var jsonOutput json.RawMessage diff --git a/command/acl/token/update/token_update_test.go b/command/acl/token/update/token_update_test.go index 924e6052c0..17fca2e816 100644 --- a/command/acl/token/update/token_update_test.go +++ b/command/acl/token/update/token_update_test.go @@ -158,8 +158,6 @@ func TestTokenUpdateCommand_JSON(t *testing.T) { t.Parallel() assert := assert.New(t) - // Alias because we need to access require package in Retry below - req := require.New(t) a := agent.NewTestAgent(t, ` primary_datacenter = "dc1" @@ -182,14 +180,14 @@ func TestTokenUpdateCommand_JSON(t *testing.T) { &api.ACLPolicy{Name: "test-policy"}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(t, err) // create a token token, _, err := client.ACL().TokenCreate( &api.ACLToken{Description: "test"}, &api.WriteOptions{Token: "root"}, ) - req.NoError(err) + require.NoError(t, err) t.Run("update with policy by name", func(t *testing.T) { cmd := New(ui) diff --git a/command/services/config_test.go b/command/services/config_test.go index a90701da2b..daf05c6cb3 100644 --- a/command/services/config_test.go +++ b/command/services/config_test.go @@ -176,10 +176,10 @@ func TestStructsToAgentService(t *testing.T) { tc := tt t.Run(tc.Name, func(t *testing.T) { t.Parallel() - r := require.New(t) + require := require.New(t) actual, err := serviceToAgentService(tc.Input) - r.NoError(err) - r.Equal(tc.Output, actual) + require.NoError(err) + require.Equal(tc.Output, actual) }) } }