test: normalize require.New and assert.New syntax

This commit is contained in:
R.B. Boyer 2022-01-20 10:45:56 -06:00
parent d8b9eb7756
commit c12b0ee3d2
11 changed files with 111 additions and 119 deletions

View File

@ -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)
})
}

View File

@ -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")
}
}

View File

@ -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)
})
}
}

View File

@ -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)
}
}

View File

@ -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)
}
}
}

View File

@ -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,

View File

@ -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")
}

View File

@ -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"))
})
})
}

View File

@ -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

View File

@ -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)

View File

@ -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)
})
}
}