Tests update: use require assertion (#1257)

* use require in filter package


fix

* use require in rpc package

* use require in tools/certgen package

* use require in mmf package

* use require in telemetry and logging


fix

Co-authored-by: Scott Redig <sredig@google.com>
This commit is contained in:
Alexey
2020-09-10 00:24:18 +03:00
committed by GitHub
parent a6fc4724bc
commit 10b36705f0
13 changed files with 176 additions and 170 deletions

View File

@ -19,11 +19,11 @@ import (
"open-match.dev/open-match/pkg/pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMakeMatchesDeduplicate(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
poolNameToTickets := map[string][]*pb.Ticket{
"pool1": {{Id: "1"}},
@ -31,12 +31,12 @@ func TestMakeMatchesDeduplicate(t *testing.T) {
}
matches, err := makeMatches(poolNameToTickets)
assert.Nil(err)
assert.Equal(len(matches), 0)
require.Nil(err)
require.Equal(len(matches), 0)
}
func TestMakeMatches(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
poolNameToTickets := map[string][]*pb.Ticket{
"pool1": {{Id: "1"}, {Id: "2"}, {Id: "3"}},
@ -45,11 +45,11 @@ func TestMakeMatches(t *testing.T) {
}
matches, err := makeMatches(poolNameToTickets)
assert.Nil(err)
assert.Equal(len(matches), 3)
require.Nil(err)
require.Equal(len(matches), 3)
for _, match := range matches {
assert.Equal(2, len(match.Tickets))
assert.Equal(matchName, match.MatchFunction)
require.Equal(2, len(match.Tickets))
require.Equal(matchName, match.MatchFunction)
}
}

View File

@ -19,7 +19,7 @@ import (
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"open-match.dev/open-match/internal/filter/testcases"
@ -31,9 +31,10 @@ func TestMeetsCriteria(t *testing.T) {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
pf, err := NewPoolFilter(tc.Pool)
if err != nil {
t.Error("pool should be valid")
}
require.NoError(t, err)
require.NotNil(t, pf)
tc.Ticket.CreateTime = ptypes.TimestampNow()
if !pf.In(tc.Ticket) {
t.Error("ticket should be included in the pool")
@ -45,9 +46,10 @@ func TestMeetsCriteria(t *testing.T) {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
pf, err := NewPoolFilter(tc.Pool)
if err != nil {
t.Error("pool should be valid")
}
require.NoError(t, err)
require.NotNil(t, pf)
tc.Ticket.CreateTime = ptypes.TimestampNow()
if pf.In(tc.Ticket) {
t.Error("ticket should be excluded from the pool")
@ -83,10 +85,13 @@ func TestValidPoolFilter(t *testing.T) {
tc := tc
t.Run(tc.name, func(t *testing.T) {
pf, err := NewPoolFilter(tc.pool)
assert.Nil(t, pf)
require.Error(t, err)
require.Nil(t, pf)
s := status.Convert(err)
assert.Equal(t, tc.code, s.Code())
assert.Equal(t, tc.msg, s.Message())
require.Equal(t, tc.code, s.Code())
require.Equal(t, tc.msg, s.Message())
})
}
}

View File

@ -21,7 +21,7 @@ import (
stackdriver "github.com/TV4/logrus-stackdriver-formatter"
"github.com/sirupsen/logrus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewFormatter(t *testing.T) {
@ -37,9 +37,9 @@ func TestNewFormatter(t *testing.T) {
for _, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("newFormatter(%s) => %s", tc.in, tc.expected), func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
actual := newFormatter(tc.in)
assert.Equal(reflect.TypeOf(tc.expected), reflect.TypeOf(actual))
require.Equal(reflect.TypeOf(tc.expected), reflect.TypeOf(actual))
})
}
}
@ -60,9 +60,9 @@ func TestIsDebugLevel(t *testing.T) {
for _, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("isDebugLevel(%s) => %t", tc.in, tc.expected), func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
actual := isDebugLevel(tc.in)
assert.Equal(tc.expected, actual)
require.Equal(tc.expected, actual)
})
}
}
@ -87,9 +87,9 @@ func TestToLevel(t *testing.T) {
for _, tc := range testCases {
tc := tc
t.Run(fmt.Sprintf("toLevel(%s) => %s", tc.in, tc.expected), func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
actual := toLevel(tc.in)
assert.Equal(tc.expected, actual)
require.Equal(tc.expected, actual)
})
}
}

View File

@ -18,7 +18,7 @@ import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
@ -27,31 +27,31 @@ const (
)
func TestGetGRPC(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cc := NewClientCache(viper.New())
client, err := cc.GetGRPC(fakeGRPCAddress)
assert.Nil(err)
require.Nil(err)
cachedClient, err := cc.GetGRPC(fakeGRPCAddress)
assert.Nil(err)
require.Nil(err)
// Test caching by comparing pointer value
assert.EqualValues(client, cachedClient)
require.EqualValues(client, cachedClient)
}
func TestGetHTTP(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cc := NewClientCache(viper.New())
client, address, err := cc.GetHTTP(fakeHTTPAddress)
assert.Nil(err)
assert.Equal(fakeHTTPAddress, address)
require.Nil(err)
require.Equal(fakeHTTPAddress, address)
cachedClient, address, err := cc.GetHTTP(fakeHTTPAddress)
assert.Nil(err)
assert.Equal(fakeHTTPAddress, address)
require.Nil(err)
require.Equal(fakeHTTPAddress, address)
// Test caching by comparing pointer value
assert.EqualValues(client, cachedClient)
require.EqualValues(client, cachedClient)
}

View File

@ -23,7 +23,7 @@ import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"open-match.dev/open-match/internal/config"
"open-match.dev/open-match/internal/telemetry"
@ -34,39 +34,39 @@ import (
)
func TestSecureGRPCFromConfig(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(assert, true)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(t, require, true)
defer closer()
runGrpcClientTests(t, assert, cfg, rpcParams)
runGrpcClientTests(t, require, cfg, rpcParams)
}
func TestInsecureGRPCFromConfig(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(assert, false)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(t, require, false)
defer closer()
runGrpcClientTests(t, assert, cfg, rpcParams)
runGrpcClientTests(t, require, cfg, rpcParams)
}
func TestHTTPSFromConfig(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(assert, true)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(t, require, true)
defer closer()
runHTTPClientTests(assert, cfg, rpcParams)
runHTTPClientTests(require, cfg, rpcParams)
}
func TestInsecureHTTPFromConfig(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(assert, false)
cfg, rpcParams, closer := configureConfigAndKeysForTesting(t, require, false)
defer closer()
runHTTPClientTests(assert, cfg, rpcParams)
runHTTPClientTests(require, cfg, rpcParams)
}
func TestSanitizeHTTPAddress(t *testing.T) {
@ -88,15 +88,15 @@ func TestSanitizeHTTPAddress(t *testing.T) {
tc := testCase
description := fmt.Sprintf("sanitizeHTTPAddress(%s, %t) => (%s, %v)", tc.address, tc.preferHTTPS, tc.expected, tc.err)
t.Run(description, func(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
actual, err := sanitizeHTTPAddress(tc.address, tc.preferHTTPS)
assert.Equal(tc.expected, actual)
assert.Equal(tc.err, err)
require.Equal(tc.expected, actual)
require.Equal(tc.err, err)
})
}
}
func runGrpcClientTests(t *testing.T, assert *assert.Assertions, cfg config.View, rpcParams *ServerParams) {
func runGrpcClientTests(t *testing.T, require *require.Assertions, cfg config.View, rpcParams *ServerParams) {
// Serve a fake frontend server and wait for its full start up
ff := &shellTesting.FakeFrontend{}
rpcParams.AddHandleFunc(func(s *grpc.Server) {
@ -106,22 +106,22 @@ func runGrpcClientTests(t *testing.T, assert *assert.Assertions, cfg config.View
s := &Server{}
defer s.Stop()
err := s.Start(rpcParams)
assert.Nil(err)
require.Nil(err)
// Acquire grpc client
grpcConn, err := GRPCClientFromConfig(cfg, "test")
assert.Nil(err)
assert.NotNil(grpcConn)
require.Nil(err)
require.NotNil(grpcConn)
// Confirm the client works as expected
ctx := utilTesting.NewContext(t)
feClient := pb.NewFrontendServiceClient(grpcConn)
grpcResp, err := feClient.CreateTicket(ctx, &pb.CreateTicketRequest{})
assert.Nil(err)
assert.NotNil(grpcResp)
require.Nil(err)
require.NotNil(grpcResp)
}
func runHTTPClientTests(assert *assert.Assertions, cfg config.View, rpcParams *ServerParams) {
func runHTTPClientTests(require *require.Assertions, cfg config.View, rpcParams *ServerParams) {
// Serve a fake frontend server and wait for its full start up
ff := &shellTesting.FakeFrontend{}
rpcParams.AddHandleFunc(func(s *grpc.Server) {
@ -130,20 +130,20 @@ func runHTTPClientTests(assert *assert.Assertions, cfg config.View, rpcParams *S
s := &Server{}
defer s.Stop()
err := s.Start(rpcParams)
assert.Nil(err)
require.Nil(err)
// Acquire http client
httpClient, baseURL, err := HTTPClientFromConfig(cfg, "test")
assert.Nil(err)
require.Nil(err)
// Confirm the client works as expected
httpReq, err := http.NewRequest(http.MethodGet, baseURL+telemetry.HealthCheckEndpoint, nil)
assert.Nil(err)
assert.NotNil(httpReq)
require.Nil(err)
require.NotNil(httpReq)
httpResp, err := httpClient.Do(httpReq)
assert.Nil(err)
assert.NotNil(httpResp)
require.Nil(err)
require.NotNil(httpResp)
defer func() {
if httpResp != nil {
httpResp.Body.Close()
@ -151,13 +151,13 @@ func runHTTPClientTests(assert *assert.Assertions, cfg config.View, rpcParams *S
}()
body, err := ioutil.ReadAll(httpResp.Body)
assert.Nil(err)
assert.Equal(200, httpResp.StatusCode)
assert.Equal("ok", string(body))
require.Nil(err)
require.Equal(200, httpResp.StatusCode)
require.Equal("ok", string(body))
}
// Generate a config view and optional TLS key manifests (optional) for testing
func configureConfigAndKeysForTesting(assert *assert.Assertions, tlsEnabled bool) (config.View, *ServerParams, func()) {
func configureConfigAndKeysForTesting(t *testing.T, require *require.Assertions, tlsEnabled bool) (config.View, *ServerParams, func()) {
// Create netlisteners on random ports used for rpc serving
grpcL := MustListen()
httpL := MustListen()
@ -171,7 +171,7 @@ func configureConfigAndKeysForTesting(assert *assert.Assertions, tlsEnabled bool
// Create temporary TLS key files for testing
pubFile, err := ioutil.TempFile("", "pub*")
assert.Nil(err)
require.Nil(err)
if tlsEnabled {
// Generate public and private key bytes
@ -179,11 +179,11 @@ func configureConfigAndKeysForTesting(assert *assert.Assertions, tlsEnabled bool
fmt.Sprintf("localhost:%s", MustGetPortNumber(grpcL)),
fmt.Sprintf("localhost:%s", MustGetPortNumber(httpL)),
})
assert.Nil(err)
require.Nil(err)
// Write certgen key bytes to the temp files
err = ioutil.WriteFile(pubFile.Name(), pubBytes, 0400)
assert.Nil(err)
require.Nil(err)
// Generate a config view with paths to the manifests
cfg.Set(configNameClientTrustedCertificatePath, pubFile.Name())
@ -191,7 +191,7 @@ func configureConfigAndKeysForTesting(assert *assert.Assertions, tlsEnabled bool
rpcParams.SetTLSConfiguration(pubBytes, pubBytes, priBytes)
}
return cfg, rpcParams, func() { removeTempFile(assert, pubFile.Name()) }
return cfg, rpcParams, func() { removeTempFile(t, pubFile.Name()) }
}
func MustListen() net.Listener {
@ -210,9 +210,11 @@ func MustGetPortNumber(l net.Listener) string {
return port
}
func removeTempFile(assert *assert.Assertions, paths ...string) {
func removeTempFile(t *testing.T, paths ...string) {
for _, path := range paths {
err := os.Remove(path)
assert.Nil(err)
if err != nil {
t.Errorf("Can not remove the temporary file: %s, err: %s", path, err.Error())
}
}
}

View File

@ -22,13 +22,13 @@ import (
"open-match.dev/open-match/pkg/pb"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
shellTesting "open-match.dev/open-match/internal/testing"
)
func TestInsecureStartStop(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
grpcL := MustListen()
httpL := MustListen()
ff := &shellTesting.FakeFrontend{}
@ -40,15 +40,15 @@ func TestInsecureStartStop(t *testing.T) {
s := newInsecureServer(grpcL, httpL)
defer s.stop()
err := s.start(params)
assert.Nil(err)
require.Nil(err)
conn, err := grpc.Dial(fmt.Sprintf(":%s", MustGetPortNumber(grpcL)), grpc.WithInsecure())
assert.Nil(err)
require.Nil(err)
defer conn.Close()
endpoint := fmt.Sprintf("http://localhost:%s", MustGetPortNumber(httpL))
httpClient := &http.Client{
Timeout: time.Second,
}
runGrpcWithProxyTests(t, assert, s, conn, httpClient, endpoint)
runGrpcWithProxyTests(t, require, s, conn, httpClient, endpoint)
}

View File

@ -22,7 +22,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"open-match.dev/open-match/internal/telemetry"
shellTesting "open-match.dev/open-match/internal/testing"
@ -31,7 +31,7 @@ import (
)
func TestStartStopServer(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
grpcL := MustListen()
httpL := MustListen()
ff := &shellTesting.FakeFrontend{}
@ -44,57 +44,57 @@ func TestStartStopServer(t *testing.T) {
defer s.Stop()
err := s.Start(params)
assert.Nil(err)
require.Nil(err)
conn, err := grpc.Dial(fmt.Sprintf(":%s", MustGetPortNumber(grpcL)), grpc.WithInsecure())
assert.Nil(err)
require.Nil(err)
endpoint := fmt.Sprintf("http://localhost:%s", MustGetPortNumber(httpL))
httpClient := &http.Client{
Timeout: time.Second,
}
runGrpcWithProxyTests(t, assert, s.serverWithProxy, conn, httpClient, endpoint)
runGrpcWithProxyTests(t, require, s.serverWithProxy, conn, httpClient, endpoint)
}
func runGrpcWithProxyTests(t *testing.T, assert *assert.Assertions, s grpcServerWithProxy, conn *grpc.ClientConn, httpClient *http.Client, endpoint string) {
func runGrpcWithProxyTests(t *testing.T, require *require.Assertions, s grpcServerWithProxy, conn *grpc.ClientConn, httpClient *http.Client, endpoint string) {
ctx := utilTesting.NewContext(t)
feClient := pb.NewFrontendServiceClient(conn)
grpcResp, err := feClient.CreateTicket(ctx, &pb.CreateTicketRequest{})
assert.Nil(err)
assert.NotNil(grpcResp)
require.Nil(err)
require.NotNil(grpcResp)
httpReq, err := http.NewRequest(http.MethodPost, endpoint+"/v1/frontendservice/tickets", strings.NewReader("{}"))
assert.Nil(err)
assert.NotNil(httpReq)
require.Nil(err)
require.NotNil(httpReq)
httpResp, err := httpClient.Do(httpReq)
assert.Nil(err)
assert.NotNil(httpResp)
require.Nil(err)
require.NotNil(httpResp)
defer func() {
if httpResp != nil {
httpResp.Body.Close()
}
}()
body, err := ioutil.ReadAll(httpResp.Body)
assert.Nil(err)
assert.Equal(200, httpResp.StatusCode)
assert.Equal("{}", string(body))
require.Nil(err)
require.Equal(200, httpResp.StatusCode)
require.Equal("{}", string(body))
httpReq, err = http.NewRequest(http.MethodGet, endpoint+telemetry.HealthCheckEndpoint, nil)
assert.Nil(err)
require.Nil(err)
httpResp, err = httpClient.Do(httpReq)
assert.Nil(err)
assert.NotNil(httpResp)
require.Nil(err)
require.NotNil(httpResp)
defer func() {
if httpResp != nil {
httpResp.Body.Close()
}
}()
body, err = ioutil.ReadAll(httpResp.Body)
assert.Nil(err)
assert.Equal(200, httpResp.StatusCode)
assert.Equal("ok", string(body))
require.Nil(err)
require.Equal(200, httpResp.StatusCode)
require.Equal("ok", string(body))
s.stop()
}

View File

@ -22,7 +22,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
shellTesting "open-match.dev/open-match/internal/testing"
@ -32,14 +32,14 @@ import (
// TestStartStopTlsServerWithCARootedCertificate verifies that we can have a gRPC+TLS+HTTPS server/client work with a single self-signed certificate.
func TestStartStopTlsServerWithSingleCertificate(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
grpcL := MustListen()
proxyL := MustListen()
grpcAddress := fmt.Sprintf("localhost:%s", MustGetPortNumber(grpcL))
proxyAddress := fmt.Sprintf("localhost:%s", MustGetPortNumber(proxyL))
allHostnames := []string{grpcAddress, proxyAddress}
pub, priv, err := certgenTesting.CreateCertificateAndPrivateKeyForTesting(allHostnames)
assert.Nil(err)
require.Nil(err)
runTestStartStopTLSServer(t, &tlsServerTestParams{
rootPublicCertificateFileData: pub,
rootPrivateKeyFileData: priv,
@ -54,17 +54,17 @@ func TestStartStopTlsServerWithSingleCertificate(t *testing.T) {
// TestStartStopTlsServerWithCARootedCertificate verifies that we can have a gRPC+TLS+HTTPS server/client work with a self-signed CA-rooted certificate.
func TestStartStopTlsServerWithCARootedCertificate(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
grpcL := MustListen()
proxyL := MustListen()
grpcAddress := fmt.Sprintf("localhost:%s", MustGetPortNumber(grpcL))
proxyAddress := fmt.Sprintf("localhost:%s", MustGetPortNumber(proxyL))
allHostnames := []string{grpcAddress, proxyAddress}
rootPub, rootPriv, err := certgenTesting.CreateRootCertificateAndPrivateKeyForTesting(allHostnames)
assert.Nil(err)
require.Nil(err)
pub, priv, err := certgenTesting.CreateDerivedCertificateAndPrivateKeyForTesting(rootPub, rootPriv, allHostnames)
assert.Nil(err)
require.Nil(err)
runTestStartStopTLSServer(t, &tlsServerTestParams{
rootPublicCertificateFileData: rootPub,
@ -90,7 +90,7 @@ type tlsServerTestParams struct {
}
func runTestStartStopTLSServer(t *testing.T, tp *tlsServerTestParams) {
assert := assert.New(t)
require := require.New(t)
ff := &shellTesting.FakeFrontend{}
@ -104,16 +104,16 @@ func runTestStartStopTLSServer(t *testing.T, tp *tlsServerTestParams) {
defer s.stop()
err := s.start(serverParams)
assert.Nil(err)
require.Nil(err)
pool, err := trustedCertificateFromFileData(tp.rootPublicCertificateFileData)
assert.Nil(err)
require.Nil(err)
conn, err := grpc.Dial(tp.grpcAddress, grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(pool, tp.grpcAddress)))
assert.Nil(err)
require.Nil(err)
tlsCert, err := certificateFromFileData(tp.publicCertificateFileData, tp.privateKeyFileData)
assert.Nil(err)
require.Nil(err)
tlsTransport := &http.Transport{
TLSClientConfig: &tls.Config{
ServerName: tp.proxyAddress,
@ -126,5 +126,5 @@ func runTestStartStopTLSServer(t *testing.T, tp *tlsServerTestParams) {
Timeout: time.Second * 10,
Transport: tlsTransport,
}
runGrpcWithProxyTests(t, assert, s, conn, httpClient, httpsEndpoint)
runGrpcWithProxyTests(t, require, s, conn, httpClient, httpsEndpoint)
}

View File

@ -20,11 +20,11 @@ import (
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConfigz(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
cfg := viper.New()
cfg.Set("char-val", "b")
cfg.Set("int-val", 1)
@ -33,8 +33,8 @@ func TestConfigz(t *testing.T) {
czFunc := func(w http.ResponseWriter, r *http.Request) {
cz.ServeHTTP(w, r)
}
assert.HTTPSuccess(czFunc, http.MethodGet, "/", url.Values{}, "")
assert.HTTPBodyContains(czFunc, http.MethodGet, "/", url.Values{}, `<!DOCTYPE html>
require.HTTPSuccess(czFunc, http.MethodGet, "/", url.Values{}, "")
require.HTTPBodyContains(czFunc, http.MethodGet, "/", url.Values{}, `<!DOCTYPE html>
<head>
<title>Open Match Configuration</title>
</head>

View File

@ -19,12 +19,12 @@ import (
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHelp(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
h := newHelp()
assert.HTTPSuccess(h, http.MethodGet, "/", url.Values{}, "")
assert.HTTPBodyContains(h, http.MethodGet, "/", url.Values{}, `Open Match Server Help`)
require.HTTPSuccess(h, http.MethodGet, "/", url.Values{}, "")
require.HTTPBodyContains(h, http.MethodGet, "/", url.Values{}, `Open Match Server Help`)
}

View File

@ -22,7 +22,7 @@ import (
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func angryHealthCheck(context.Context) error {
@ -56,22 +56,22 @@ func TestHealthCheck(t *testing.T) {
}
func assertHealthCheck(t *testing.T, hc http.Handler, errorString string) {
assert := assert.New(t)
require := require.New(t)
sp, ok := hc.(*statefulProbe)
assert.True(ok)
assert.Equal(healthStateFirstProbe, atomic.LoadInt32(sp.healthState))
require.True(ok)
require.Equal(healthStateFirstProbe, atomic.LoadInt32(sp.healthState))
hcFunc := func(w http.ResponseWriter, r *http.Request) {
hc.ServeHTTP(w, r)
}
assert.HTTPSuccess(hcFunc, http.MethodGet, "/", url.Values{}, "ok")
require.HTTPSuccess(hcFunc, http.MethodGet, "/", url.Values{}, "ok")
// A readiness probe has not happened yet so it's still in "first state"
assert.Equal(healthStateFirstProbe, atomic.LoadInt32(sp.healthState))
require.Equal(healthStateFirstProbe, atomic.LoadInt32(sp.healthState))
if errorString == "" {
assert.HTTPSuccess(hcFunc, http.MethodGet, "/", url.Values{"readiness": []string{"true"}}, "ok")
assert.Equal(healthStateHealthy, atomic.LoadInt32(sp.healthState))
require.HTTPSuccess(hcFunc, http.MethodGet, "/", url.Values{"readiness": []string{"true"}}, "ok")
require.Equal(healthStateHealthy, atomic.LoadInt32(sp.healthState))
} else {
assert.HTTPError(hcFunc, http.MethodGet, "/", url.Values{"readiness": []string{"true"}}, errorString)
assert.Equal(healthStateUnhealthy, atomic.LoadInt32(sp.healthState))
require.HTTPError(hcFunc, http.MethodGet, "/", url.Values{"readiness": []string{"true"}}, errorString)
require.Equal(healthStateUnhealthy, atomic.LoadInt32(sp.healthState))
}
}

View File

@ -25,7 +25,7 @@ import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
@ -33,13 +33,13 @@ const (
)
func TestCreateCertificate(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
tmpDir, err := ioutil.TempDir("", "certtest")
defer func() {
assert.Nil(os.RemoveAll(tmpDir))
require.Nil(os.RemoveAll(tmpDir))
}()
assert.Nil(err)
require.Nil(err)
publicCertPath := filepath.Join(tmpDir, "public.cert")
privateKeyPath := filepath.Join(tmpDir, "private.key")
err = CreateCertificateAndPrivateKeyFiles(
@ -50,31 +50,31 @@ func TestCreateCertificate(t *testing.T) {
Hostnames: []string{"a.com", "b.com", "127.0.0.1"},
RSAKeyLength: 2048,
})
assert.Nil(err)
require.Nil(err)
assert.FileExists(publicCertPath)
assert.FileExists(privateKeyPath)
require.FileExists(publicCertPath)
require.FileExists(privateKeyPath)
publicCertFileData, err := ioutil.ReadFile(publicCertPath)
assert.Nil(err)
require.Nil(err)
privateKeyFileData, err := ioutil.ReadFile(privateKeyPath)
assert.Nil(err)
require.Nil(err)
// Verify that we can load the public/private key pair.
pub, pk, err := ReadKeyPair(publicCertFileData, privateKeyFileData)
assert.Nil(err)
assert.NotNil(pub)
assert.NotNil(pk)
require.Nil(err)
require.NotNil(pub)
require.NotNil(pk)
// Verify that the public/private key pair can RSA encrypt/decrypt.
pubKey, ok := pub.PublicKey.(*rsa.PublicKey)
assert.True(ok, "pub.PublicKey is not of type, *rsa.PublicKey, %v", pub.PublicKey)
require.True(ok, "pub.PublicKey is not of type, *rsa.PublicKey, %v", pub.PublicKey)
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, pubKey, []byte(secretMessage), []byte{})
assert.Nil(err)
assert.NotEqual(string(ciphertext), secretMessage)
require.Nil(err)
require.NotEqual(string(ciphertext), secretMessage)
cleartext, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, pk, ciphertext, []byte{})
assert.Nil(err)
assert.Equal(string(cleartext), string(secretMessage))
require.Nil(err)
require.Equal(string(cleartext), string(secretMessage))
}
func TestBadValues(t *testing.T) {
@ -132,9 +132,8 @@ func TestExpandHostnames(t *testing.T) {
for _, testCase := range testCases {
testCase := testCase
t.Run(fmt.Sprintf("expandHostnames(%s) => %s", testCase.input, testCase.expected), func(t *testing.T) {
assert := assert.New(t)
actual := expandHostnames(testCase.input)
assert.Equal(testCase.expected, actual)
require.Equal(t, testCase.expected, actual)
})
}
}

View File

@ -17,7 +17,7 @@ package testing
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
certgenInternal "open-match.dev/open-match/tools/certgen/internal"
)
@ -26,44 +26,44 @@ const (
)
func TestCreateCertificateAndPrivateKeyForTestingAreValid(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
pubData, privData, err := CreateCertificateAndPrivateKeyForTesting([]string{fakeAddress})
assert.Nil(err)
require.Nil(err)
// Verify that we can load the public/private key pair.
pub, pk, err := certgenInternal.ReadKeyPair(pubData, privData)
assert.Nil(err)
assert.NotNil(pub)
assert.NotNil(pk)
require.Nil(err)
require.NotNil(pub)
require.NotNil(pk)
}
func TestCreateRootedCertificateAndPrivateKeyForTestingAreValid(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
rootPubData, rootPrivData, err := CreateRootCertificateAndPrivateKeyForTesting([]string{fakeAddress})
assert.Nil(err)
require.Nil(err)
pubData, privData, err := CreateDerivedCertificateAndPrivateKeyForTesting(rootPubData, rootPrivData, []string{fakeAddress})
assert.Nil(err)
require.Nil(err)
rootPub, rootPk, err := certgenInternal.ReadKeyPair(rootPubData, rootPrivData)
assert.Nil(err)
assert.NotNil(rootPk)
require.Nil(err)
require.NotNil(rootPk)
pub, pk, err := certgenInternal.ReadKeyPair(pubData, privData)
assert.Nil(err)
assert.NotNil(pk)
require.Nil(err)
require.NotNil(pk)
assert.Nil(pub.CheckSignatureFrom(rootPub))
require.Nil(pub.CheckSignatureFrom(rootPub))
}
func TestCreateCertificateAndPrivateKeyForTestingAreDifferent(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
pubData1, privData1, err := CreateCertificateAndPrivateKeyForTesting([]string{fakeAddress})
assert.Nil(err)
require.Nil(err)
pubData2, privData2, err := CreateCertificateAndPrivateKeyForTesting([]string{fakeAddress})
assert.Nil(err)
require.Nil(err)
assert.NotEqual(string(pubData1), string(pubData2))
assert.NotEqual(string(privData1), string(privData2))
require.NotEqual(string(pubData1), string(pubData2))
require.NotEqual(string(privData1), string(privData2))
}