diff --git a/.golangci.yml b/.golangci.yml index 88cb4fb..120faf2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -19,12 +19,16 @@ linters-settings: recommendations: - errors forbidigo: + analyze-types: true forbid: - ^fmt.Print(f|ln)?$ - ^log.(Panic|Fatal|Print)(f|ln)?$ - ^os.Exit$ - ^panic$ - ^print(ln)?$ + - p: ^testing.T.(Error|Errorf|Fatal|Fatalf|Fail|FailNow)$ + pkg: ^testing$ + msg: "use testify/assert instead" varnamelen: max-distance: 12 min-name-length: 2 @@ -127,9 +131,12 @@ issues: exclude-dirs-use-default: false exclude-rules: # Allow complex tests and examples, better to be self contained - - path: (examples|main\.go|_test\.go) + - path: (examples|main\.go) linters: + - gocognit - forbidigo + - path: _test\.go + linters: - gocognit # Allow forbidden identifiers in CLI commands diff --git a/active_tcp_test.go b/active_tcp_test.go index 796292b..b47ff6a 100644 --- a/active_tcp_test.go +++ b/active_tcp_test.go @@ -147,7 +147,7 @@ func TestActiveTCP(t *testing.T) { req.NoError(err) req.NotNil(activeAgent) - passiveAgentConn, activeAgenConn := connect(passiveAgent, activeAgent) + passiveAgentConn, activeAgenConn := connect(t, passiveAgent, activeAgent) req.NotNil(passiveAgentConn) req.NotNil(activeAgenConn) @@ -220,7 +220,7 @@ func TestActiveTCP_NonBlocking(t *testing.T) { require.NoError(t, aAgent.AddRemoteCandidate(invalidCandidate)) require.NoError(t, bAgent.AddRemoteCandidate(invalidCandidate)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isConnected } @@ -284,7 +284,7 @@ func TestActiveTCP_Respect_NetworkTypes(t *testing.T) { require.NoError(t, aAgent.AddRemoteCandidate(invalidCandidate)) require.NoError(t, bAgent.AddRemoteCandidate(invalidCandidate)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isConnected require.NoError(t, tcpListener.Close()) diff --git a/agent_handlers_test.go b/agent_handlers_test.go index 5518f26..0c980f6 100644 --- a/agent_handlers_test.go +++ b/agent_handlers_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/pion/transport/v3/test" + "github.com/stretchr/testify/assert" ) func TestConnectionStateNotifier(t *testing.T) { @@ -33,7 +34,7 @@ func TestConnectionStateNotifier(t *testing.T) { } select { case <-updates: - t.Errorf("received more updates than expected") + t.Errorf("received more updates than expected") // nolint case <-time.After(1 * time.Second): } close(done) @@ -53,14 +54,11 @@ func TestConnectionStateNotifier(t *testing.T) { done := make(chan struct{}) go func() { for i := 0; i < 10000; i++ { - x := <-updates - if x != ConnectionState(i) { - t.Errorf("expected %d got %d", x, i) - } + assert.Equal(t, ConnectionState(i), <-updates) } select { case <-updates: - t.Errorf("received more updates than expected") + t.Errorf("received more updates than expected") // nolint case <-time.After(1 * time.Second): } close(done) diff --git a/agent_test.go b/agent_test.go index 1ec75c1..0d97ea6 100644 --- a/agent_test.go +++ b/agent_test.go @@ -8,7 +8,6 @@ package ice import ( "context" - "errors" "net" "strconv" "sync" @@ -57,9 +56,7 @@ func TestHandlePeerReflexive(t *testing.T) { //nolint:cyclop } local, err := NewCandidateHost(&hostConfig) local.conn = &fakenet.MockPacketConn{} - if err != nil { - t.Fatalf("failed to create a new candidate: %v", err) - } + require.NoError(t, err) remote := &net.UDPAddr{IP: net.ParseIP("172.17.0.3"), Port: 999} @@ -77,29 +74,17 @@ func TestHandlePeerReflexive(t *testing.T) { //nolint:cyclop agent.handleInbound(msg, local, remote) // Length of remote candidate list must be one now - if len(agent.remoteCandidates) != 1 { - t.Fatal("failed to add a network type to the remote candidate list") - } + require.Len(t, agent.remoteCandidates, 1) // Length of remote candidate list for a network type must be 1 set := agent.remoteCandidates[local.NetworkType()] - if len(set) != 1 { - t.Fatal("failed to add prflx candidate to remote candidate list") - } + require.Len(t, set, 1) c := set[0] - if c.Type() != CandidateTypePeerReflexive { - t.Fatal("candidate type must be prflx") - } - - if c.Address() != "172.17.0.3" { - t.Fatal("IP address mismatch") - } - - if c.Port() != 999 { - t.Fatal("Port number mismatch") - } + require.Equal(t, CandidateTypePeerReflexive, c.Type()) + require.Equal(t, "172.17.0.3", c.Address()) + require.Equal(t, 999, c.Port()) })) }) @@ -120,18 +105,13 @@ func TestHandlePeerReflexive(t *testing.T) { //nolint:cyclop Component: 1, } local, err := NewCandidateHost(&hostConfig) - if err != nil { - t.Fatalf("failed to create a new candidate: %v", err) - } + require.NoError(t, err) remote := &BadAddr{} // nolint: contextcheck agent.handleInbound(nil, local, remote) - - if len(agent.remoteCandidates) != 0 { - t.Fatal("bad address should not be added to the remote candidate list") - } + require.Len(t, agent.remoteCandidates, 0) })) }) @@ -158,9 +138,7 @@ func TestHandlePeerReflexive(t *testing.T) { //nolint:cyclop } local, err := NewCandidateHost(&hostConfig) local.conn = &fakenet.MockPacketConn{} - if err != nil { - t.Fatalf("failed to create a new candidate: %v", err) - } + require.NoError(t, err) remote := &net.UDPAddr{IP: net.ParseIP("172.17.0.3"), Port: 999} msg, err := stun.Build(stun.BindingSuccess, stun.NewTransactionIDSetter(tID), @@ -171,9 +149,7 @@ func TestHandlePeerReflexive(t *testing.T) { //nolint:cyclop // nolint: contextcheck agent.handleInbound(msg, local, remote) - if len(agent.remoteCandidates) != 0 { - t.Fatal("unknown remote was able to create a candidate") - } + require.Len(t, agent.remoteCandidates, 0) })) }) } @@ -248,7 +224,7 @@ func TestConnectivityOnStartup(t *testing.T) { bUfrag, bPwd, err := bAgent.GetLocalUserCredentials() require.NoError(t, err) - gatherAndExchangeCandidates(aAgent, bAgent) + gatherAndExchangeCandidates(t, aAgent, bAgent) accepted := make(chan struct{}) accepting := make(chan struct{}) @@ -256,9 +232,9 @@ func TestConnectivityOnStartup(t *testing.T) { origHdlr := aAgent.onConnectionStateChangeHdlr.Load() if origHdlr != nil { - defer check(aAgent.OnConnectionStateChange(origHdlr.(func(ConnectionState)))) //nolint:forcetypeassert + defer require.NoError(t, aAgent.OnConnectionStateChange(origHdlr.(func(ConnectionState)))) //nolint:forcetypeassert } - check(aAgent.OnConnectionStateChange(func(s ConnectionState) { + require.NoError(t, aAgent.OnConnectionStateChange(func(s ConnectionState) { if s == ConnectionStateChecking { close(accepting) } @@ -270,14 +246,14 @@ func TestConnectivityOnStartup(t *testing.T) { go func() { var acceptErr error aConn, acceptErr = aAgent.Accept(context.TODO(), bUfrag, bPwd) - check(acceptErr) + require.NoError(t, acceptErr) close(accepted) }() <-accepting bConn, err := bAgent.Dial(context.TODO(), aUfrag, aPwd) - check(err) + require.NoError(t, err) // Ensure accepted <-accepted @@ -346,7 +322,7 @@ func TestConnectivityLite(t *testing.T) { }() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connectWithVNet(aAgent, bAgent) + connectWithVNet(t, aAgent, bAgent) // Ensure pair selected // Note: this assumes ConnectionStateConnected is thrown after selecting the final pair @@ -377,65 +353,47 @@ func TestInboundValidity(t *testing.T) { //nolint:cyclop } local, err := NewCandidateHost(&hostConfig) local.conn = &fakenet.MockPacketConn{} - if err != nil { - t.Fatalf("failed to create a new candidate: %v", err) - } + require.NoError(t, err) t.Run("Invalid Binding requests should be discarded", func(t *testing.T) { agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() agent.handleInbound(buildMsg(stun.ClassRequest, "invalid", agent.localPwd), local, remote) - if len(agent.remoteCandidates) == 1 { - t.Fatal("Binding with invalid Username was able to create prflx candidate") - } + require.Len(t, agent.remoteCandidates, 0) agent.handleInbound(buildMsg(stun.ClassRequest, agent.localUfrag+":"+agent.remoteUfrag, "Invalid"), local, remote) - if len(agent.remoteCandidates) == 1 { - t.Fatal("Binding with invalid MessageIntegrity was able to create prflx candidate") - } + require.Len(t, agent.remoteCandidates, 0) }) t.Run("Invalid Binding success responses should be discarded", func(t *testing.T) { a, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, a.Close()) }() a.handleInbound(buildMsg(stun.ClassSuccessResponse, a.localUfrag+":"+a.remoteUfrag, "Invalid"), local, remote) - if len(a.remoteCandidates) == 1 { - t.Fatal("Binding with invalid MessageIntegrity was able to create prflx candidate") - } + require.Len(t, a.remoteCandidates, 0) }) t.Run("Discard non-binding messages", func(t *testing.T) { a, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, a.Close()) }() a.handleInbound(buildMsg(stun.ClassErrorResponse, a.localUfrag+":"+a.remoteUfrag, "Invalid"), local, remote) - if len(a.remoteCandidates) == 1 { - t.Fatal("non-binding message was able to create prflxRemote") - } + require.Len(t, a.remoteCandidates, 0) }) t.Run("Valid bind request", func(t *testing.T) { a, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, a.Close()) }() @@ -444,9 +402,7 @@ func TestInboundValidity(t *testing.T) { //nolint:cyclop a.selector = &controllingSelector{agent: a, log: a.log} // nolint: contextcheck a.handleInbound(buildMsg(stun.ClassRequest, a.localUfrag+":"+a.remoteUfrag, a.localPwd), local, remote) - if len(a.remoteCandidates) != 1 { - t.Fatal("Binding with valid values was unable to create prflx candidate") - } + require.Len(t, a.remoteCandidates, 1) }) require.NoError(t, err) @@ -469,17 +425,13 @@ func TestInboundValidity(t *testing.T) { //nolint:cyclop // nolint: contextcheck agent.handleInbound(msg, local, remote) - if len(agent.remoteCandidates) != 1 { - t.Fatal("Binding with valid values (but no fingerprint) was unable to create prflx candidate") - } + require.Len(t, agent.remoteCandidates, 1) })) }) t.Run("Success with invalid TransactionID", func(t *testing.T) { agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -492,9 +444,7 @@ func TestInboundValidity(t *testing.T) { //nolint:cyclop } local, err := NewCandidateHost(&hostConfig) local.conn = &fakenet.MockPacketConn{} - if err != nil { - t.Fatalf("failed to create a new candidate: %v", err) - } + require.NoError(t, err) remote := &net.UDPAddr{IP: net.ParseIP("172.17.0.3"), Port: 999} tID := [stun.TransactionIDSize]byte{} @@ -506,9 +456,7 @@ func TestInboundValidity(t *testing.T) { //nolint:cyclop require.NoError(t, err) agent.handleInbound(msg, local, remote) - if len(agent.remoteCandidates) != 0 { - t.Fatal("unknown remote was able to create a candidate") - } + require.Len(t, agent.remoteCandidates, 0) }) } @@ -525,21 +473,17 @@ func TestInvalidAgentStarts(t *testing.T) { ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) defer cancel() - if _, err = agent.Dial(ctx, "", "bar"); err != nil && !errors.Is(err, ErrRemoteUfragEmpty) { - t.Fatal(err) - } + _, err = agent.Dial(ctx, "", "bar") + require.ErrorIs(t, ErrRemoteUfragEmpty, err) - if _, err = agent.Dial(ctx, "foo", ""); err != nil && !errors.Is(err, ErrRemotePwdEmpty) { - t.Fatal(err) - } + _, err = agent.Dial(ctx, "foo", "") + require.ErrorIs(t, ErrRemotePwdEmpty, err) - if _, err = agent.Dial(ctx, "foo", "bar"); err != nil && !errors.Is(err, ErrCanceledByCaller) { - t.Fatal(err) - } + _, err = agent.Dial(ctx, "foo", "bar") + require.ErrorIs(t, ErrCanceledByCaller, err) - if _, err = agent.Dial(context.TODO(), "foo", "bar"); err != nil && !errors.Is(err, ErrMultipleStart) { - t.Fatal(err) - } + _, err = agent.Dial(ctx, "foo", "bar") + require.ErrorIs(t, ErrMultipleStart, err) } // Assert that Agent emits Connecting/Connected/Disconnected/Failed/Closed messages. @@ -606,7 +550,7 @@ func TestConnectionStateCallback(t *testing.T) { //nolint:cyclop }) require.NoError(t, err) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isChecking <-isConnected @@ -622,17 +566,13 @@ func TestConnectionStateCallback(t *testing.T) { //nolint:cyclop func TestInvalidGather(t *testing.T) { t.Run("Gather with no OnCandidate should error", func(t *testing.T) { a, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Error constructing ice.Agent") - } + require.NoError(t, err) defer func() { require.NoError(t, a.Close()) }() err = a.GatherCandidates() - if !errors.Is(err, ErrNoOnCandidateHandler) { - t.Fatal("trickle GatherCandidates succeeded without OnCandidate") - } + require.ErrorIs(t, ErrNoOnCandidateHandler, err) }) } @@ -643,9 +583,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo defer test.TimeOut(1 * time.Second).Stop() agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -657,9 +595,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo Component: 1, } hostLocal, err := NewCandidateHost(hostConfig) - if err != nil { - t.Fatalf("Failed to construct local host candidate: %s", err) - } + require.NoError(t, err) relayConfig := &CandidateRelayConfig{ Network: "udp", @@ -670,9 +606,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo RelPort: 43210, } relayRemote, err := NewCandidateRelay(relayConfig) - if err != nil { - t.Fatalf("Failed to construct remote relay candidate: %s", err) - } + require.NoError(t, err) srflxConfig := &CandidateServerReflexiveConfig{ Network: "udp", @@ -683,9 +617,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo RelPort: 43212, } srflxRemote, err := NewCandidateServerReflexive(srflxConfig) - if err != nil { - t.Fatalf("Failed to construct remote srflx candidate: %s", err) - } + require.NoError(t, err) prflxConfig := &CandidatePeerReflexiveConfig{ Network: "udp", @@ -696,9 +628,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo RelPort: 43211, } prflxRemote, err := NewCandidatePeerReflexive(prflxConfig) - if err != nil { - t.Fatalf("Failed to construct remote prflx candidate: %s", err) - } + require.NoError(t, err) hostConfig = &CandidateHostConfig{ Network: "udp", @@ -707,9 +637,7 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo Component: 1, } hostRemote, err := NewCandidateHost(hostConfig) - if err != nil { - t.Fatalf("Failed to construct remote host candidate: %s", err) - } + require.NoError(t, err) for _, remote := range []Candidate{relayRemote, srflxRemote, prflxRemote, hostRemote} { p := agent.findPair(hostLocal, remote) @@ -731,16 +659,12 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo } stats := agent.GetCandidatePairsStats() - if len(stats) != 4 { - t.Fatal("expected 4 candidate pairs stats") - } + require.Len(t, stats, 4) var relayPairStat, srflxPairStat, prflxPairStat, hostPairStat CandidatePairStats for _, cps := range stats { - if cps.LocalCandidateID != hostLocal.ID() { - t.Fatal("invalid local candidate id") - } + require.Equal(t, cps.LocalCandidateID, hostLocal.ID()) switch cps.RemoteCandidateID { case relayRemote.ID(): relayPairStat = cps @@ -751,54 +675,30 @@ func TestCandidatePairsStats(t *testing.T) { //nolint:cyclop,gocyclo case hostRemote.ID(): hostPairStat = cps default: - t.Fatal("invalid remote candidate ID") + t.Fatal("invalid remote candidate ID") //nolint } - if cps.FirstRequestTimestamp.IsZero() || cps.LastRequestTimestamp.IsZero() || - cps.FirstResponseTimestamp.IsZero() || cps.LastResponseTimestamp.IsZero() || - cps.FirstRequestReceivedTimestamp.IsZero() || cps.LastRequestReceivedTimestamp.IsZero() || - cps.RequestsReceived == 0 || cps.RequestsSent == 0 || cps.ResponsesSent == 0 || cps.ResponsesReceived == 0 { - t.Fatal("failed to verify pair stats counter and timestamps", cps) - } + require.False(t, cps.FirstRequestTimestamp.IsZero()) + require.False(t, cps.LastRequestTimestamp.IsZero()) + require.False(t, cps.FirstResponseTimestamp.IsZero()) + require.False(t, cps.LastResponseTimestamp.IsZero()) + require.False(t, cps.FirstRequestReceivedTimestamp.IsZero()) + require.False(t, cps.LastRequestReceivedTimestamp.IsZero()) + require.NotZero(t, cps.RequestsReceived) + require.NotZero(t, cps.RequestsSent) + require.NotZero(t, cps.ResponsesSent) + require.NotZero(t, cps.ResponsesReceived) } - if relayPairStat.RemoteCandidateID != relayRemote.ID() { - t.Fatal("missing host-relay pair stat") - } + require.Equal(t, relayPairStat.RemoteCandidateID, relayRemote.ID()) + require.Equal(t, srflxPairStat.RemoteCandidateID, srflxRemote.ID()) + require.Equal(t, prflxPairStat.RemoteCandidateID, prflxRemote.ID()) + require.Equal(t, hostPairStat.RemoteCandidateID, hostRemote.ID()) + require.Equal(t, prflxPairStat.State, CandidatePairStateFailed) - if srflxPairStat.RemoteCandidateID != srflxRemote.ID() { - t.Fatal("missing host-srflx pair stat") - } - - if prflxPairStat.RemoteCandidateID != prflxRemote.ID() { - t.Fatal("missing host-prflx pair stat") - } - - if hostPairStat.RemoteCandidateID != hostRemote.ID() { - t.Fatal("missing host-host pair stat") - } - - if prflxPairStat.State != CandidatePairStateFailed { - t.Fatalf("expected host-prflx pair to have state failed, it has state %s instead", - prflxPairStat.State.String()) - } - - expectedCurrentRoundTripTime := time.Duration(10) * time.Second - if prflxPairStat.CurrentRoundTripTime != expectedCurrentRoundTripTime.Seconds() { - t.Fatalf("expected current round trip time to be %f, it is %f instead", - expectedCurrentRoundTripTime.Seconds(), prflxPairStat.CurrentRoundTripTime) - } - - expectedTotalRoundTripTime := time.Duration(55) * time.Second - if prflxPairStat.TotalRoundTripTime != expectedTotalRoundTripTime.Seconds() { - t.Fatalf("expected total round trip time to be %f, it is %f instead", - expectedTotalRoundTripTime.Seconds(), prflxPairStat.TotalRoundTripTime) - } - - if prflxPairStat.ResponsesReceived != 10 { - t.Fatalf("expected responses received to be 10, it is %d instead", - prflxPairStat.ResponsesReceived) - } + require.Equal(t, float64(10), prflxPairStat.CurrentRoundTripTime) + require.Equal(t, float64(55), prflxPairStat.TotalRoundTripTime) + require.Equal(t, uint64(10), prflxPairStat.ResponsesReceived) } func TestSelectedCandidatePairStats(t *testing.T) { //nolint:cyclop @@ -808,9 +708,7 @@ func TestSelectedCandidatePairStats(t *testing.T) { //nolint:cyclop defer test.TimeOut(1 * time.Second).Stop() agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -822,9 +720,7 @@ func TestSelectedCandidatePairStats(t *testing.T) { //nolint:cyclop Component: 1, } hostLocal, err := NewCandidateHost(hostConfig) - if err != nil { - t.Fatalf("Failed to construct local host candidate: %s", err) - } + require.NoError(t, err) srflxConfig := &CandidateServerReflexiveConfig{ Network: "udp", @@ -835,9 +731,7 @@ func TestSelectedCandidatePairStats(t *testing.T) { //nolint:cyclop RelPort: 43212, } srflxRemote, err := NewCandidateServerReflexive(srflxConfig) - if err != nil { - t.Fatalf("Failed to construct remote srflx candidate: %s", err) - } + require.NoError(t, err) // no selected pair, should return not available _, ok := agent.GetSelectedCandidatePairStats() @@ -859,29 +753,11 @@ func TestSelectedCandidatePairStats(t *testing.T) { //nolint:cyclop stats, ok := agent.GetSelectedCandidatePairStats() require.True(t, ok) - if stats.LocalCandidateID != hostLocal.ID() { - t.Fatal("invalid local candidate id") - } - if stats.RemoteCandidateID != srflxRemote.ID() { - t.Fatal("invalid remote candidate id") - } - - expectedCurrentRoundTripTime := time.Duration(10) * time.Second - if stats.CurrentRoundTripTime != expectedCurrentRoundTripTime.Seconds() { - t.Fatalf("expected current round trip time to be %f, it is %f instead", - expectedCurrentRoundTripTime.Seconds(), stats.CurrentRoundTripTime) - } - - expectedTotalRoundTripTime := time.Duration(55) * time.Second - if stats.TotalRoundTripTime != expectedTotalRoundTripTime.Seconds() { - t.Fatalf("expected total round trip time to be %f, it is %f instead", - expectedTotalRoundTripTime.Seconds(), stats.TotalRoundTripTime) - } - - if stats.ResponsesReceived != 10 { - t.Fatalf("expected responses received to be 10, it is %d instead", - stats.ResponsesReceived) - } + require.Equal(t, stats.LocalCandidateID, hostLocal.ID()) + require.Equal(t, stats.RemoteCandidateID, srflxRemote.ID()) + require.Equal(t, float64(10), stats.CurrentRoundTripTime) + require.Equal(t, float64(55), stats.TotalRoundTripTime) + require.Equal(t, uint64(10), stats.ResponsesReceived) } func TestLocalCandidateStats(t *testing.T) { //nolint:cyclop @@ -891,9 +767,7 @@ func TestLocalCandidateStats(t *testing.T) { //nolint:cyclop defer test.TimeOut(1 * time.Second).Stop() agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -905,9 +779,7 @@ func TestLocalCandidateStats(t *testing.T) { //nolint:cyclop Component: 1, } hostLocal, err := NewCandidateHost(hostConfig) - if err != nil { - t.Fatalf("Failed to construct local host candidate: %s", err) - } + require.NoError(t, err) srflxConfig := &CandidateServerReflexiveConfig{ Network: "udp", @@ -918,16 +790,12 @@ func TestLocalCandidateStats(t *testing.T) { //nolint:cyclop RelPort: 43212, } srflxLocal, err := NewCandidateServerReflexive(srflxConfig) - if err != nil { - t.Fatalf("Failed to construct local srflx candidate: %s", err) - } + require.NoError(t, err) agent.localCandidates[NetworkTypeUDP4] = []Candidate{hostLocal, srflxLocal} localStats := agent.GetLocalCandidatesStats() - if len(localStats) != 2 { - t.Fatalf("expected 2 local candidates stats, got %d instead", len(localStats)) - } + require.Len(t, localStats, 2) var hostLocalStat, srflxLocalStat CandidateStats for _, stats := range localStats { @@ -940,29 +808,16 @@ func TestLocalCandidateStats(t *testing.T) { //nolint:cyclop srflxLocalStat = stats candidate = srflxLocal default: - t.Fatal("invalid local candidate ID") + t.Fatal("invalid local candidate ID") // nolint } - if stats.CandidateType != candidate.Type() { - t.Fatal("invalid stats CandidateType") - } - - if stats.Priority != candidate.Priority() { - t.Fatal("invalid stats CandidateType") - } - - if stats.IP != candidate.Address() { - t.Fatal("invalid stats IP") - } + require.Equal(t, stats.CandidateType, candidate.Type()) + require.Equal(t, stats.Priority, candidate.Priority()) + require.Equal(t, stats.IP, candidate.Address()) } - if hostLocalStat.ID != hostLocal.ID() { - t.Fatal("missing host local stat") - } - - if srflxLocalStat.ID != srflxLocal.ID() { - t.Fatal("missing srflx local stat") - } + require.Equal(t, hostLocalStat.ID, hostLocal.ID()) + require.Equal(t, srflxLocalStat.ID, srflxLocal.ID()) } func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop @@ -972,9 +827,7 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop defer test.TimeOut(1 * time.Second).Stop() agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -988,9 +841,7 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop RelPort: 43210, } relayRemote, err := NewCandidateRelay(relayConfig) - if err != nil { - t.Fatalf("Failed to construct remote relay candidate: %s", err) - } + require.NoError(t, err) srflxConfig := &CandidateServerReflexiveConfig{ Network: "udp", @@ -1001,9 +852,7 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop RelPort: 43212, } srflxRemote, err := NewCandidateServerReflexive(srflxConfig) - if err != nil { - t.Fatalf("Failed to construct remote srflx candidate: %s", err) - } + require.NoError(t, err) prflxConfig := &CandidatePeerReflexiveConfig{ Network: "udp", @@ -1014,9 +863,7 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop RelPort: 43211, } prflxRemote, err := NewCandidatePeerReflexive(prflxConfig) - if err != nil { - t.Fatalf("Failed to construct remote prflx candidate: %s", err) - } + require.NoError(t, err) hostConfig := &CandidateHostConfig{ Network: "udp", @@ -1025,16 +872,12 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop Component: 1, } hostRemote, err := NewCandidateHost(hostConfig) - if err != nil { - t.Fatalf("Failed to construct remote host candidate: %s", err) - } + require.NoError(t, err) agent.remoteCandidates[NetworkTypeUDP4] = []Candidate{relayRemote, srflxRemote, prflxRemote, hostRemote} remoteStats := agent.GetRemoteCandidatesStats() - if len(remoteStats) != 4 { - t.Fatalf("expected 4 remote candidates stats, got %d instead", len(remoteStats)) - } + require.Len(t, remoteStats, 4) var relayRemoteStat, srflxRemoteStat, prflxRemoteStat, hostRemoteStat CandidateStats for _, stats := range remoteStats { var candidate Candidate @@ -1052,37 +895,18 @@ func TestRemoteCandidateStats(t *testing.T) { //nolint:cyclop hostRemoteStat = stats candidate = hostRemote default: - t.Fatal("invalid remote candidate ID") + t.Fatal("invalid remote candidate ID") // nolint } - if stats.CandidateType != candidate.Type() { - t.Fatal("invalid stats CandidateType") - } - - if stats.Priority != candidate.Priority() { - t.Fatal("invalid stats CandidateType") - } - - if stats.IP != candidate.Address() { - t.Fatal("invalid stats IP") - } + require.Equal(t, stats.CandidateType, candidate.Type()) + require.Equal(t, stats.Priority, candidate.Priority()) + require.Equal(t, stats.IP, candidate.Address()) } - if relayRemoteStat.ID != relayRemote.ID() { - t.Fatal("missing relay remote stat") - } - - if srflxRemoteStat.ID != srflxRemote.ID() { - t.Fatal("missing srflx remote stat") - } - - if prflxRemoteStat.ID != prflxRemote.ID() { - t.Fatal("missing prflx remote stat") - } - - if hostRemoteStat.ID != hostRemote.ID() { - t.Fatal("missing host remote stat") - } + require.Equal(t, relayRemoteStat.ID, relayRemote.ID()) + require.Equal(t, srflxRemoteStat.ID, srflxRemote.ID()) + require.Equal(t, prflxRemoteStat.ID, prflxRemote.ID()) + require.Equal(t, hostRemoteStat.ID, hostRemote.ID()) } func TestInitExtIPMapping(t *testing.T) { @@ -1090,13 +914,8 @@ func TestInitExtIPMapping(t *testing.T) { // agent.extIPMapper should be nil by default agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %v", err) - } - if agent.extIPMapper != nil { - require.NoError(t, agent.Close()) - t.Fatal("a.extIPMapper should be nil by default") - } + require.NoError(t, err) + require.Nil(t, agent.extIPMapper) require.NoError(t, agent.Close()) // a.extIPMapper should be nil when NAT1To1IPs is a non-nil empty array @@ -1104,14 +923,8 @@ func TestInitExtIPMapping(t *testing.T) { NAT1To1IPs: []string{}, NAT1To1IPCandidateType: CandidateTypeHost, }) - if err != nil { - require.NoError(t, agent.Close()) - t.Fatalf("Failed to create agent: %v", err) - } - if agent.extIPMapper != nil { - require.NoError(t, agent.Close()) - t.Fatal("a.extIPMapper should be nil by default") - } + require.NoError(t, err) + require.Nil(t, agent.extIPMapper) require.NoError(t, agent.Close()) // NewAgent should return an error when 1:1 NAT for host candidate is enabled @@ -1121,9 +934,7 @@ func TestInitExtIPMapping(t *testing.T) { NAT1To1IPCandidateType: CandidateTypeHost, CandidateTypes: []CandidateType{CandidateTypeRelay}, }) - if !errors.Is(err, ErrIneffectiveNAT1To1IPMappingHost) { - t.Fatalf("Unexpected error: %v", err) - } + require.ErrorIs(t, ErrIneffectiveNAT1To1IPMappingHost, err) // NewAgent should return an error when 1:1 NAT for srflx candidate is enabled // but the candidate type does not appear in the CandidateTypes. @@ -1132,9 +943,7 @@ func TestInitExtIPMapping(t *testing.T) { NAT1To1IPCandidateType: CandidateTypeServerReflexive, CandidateTypes: []CandidateType{CandidateTypeRelay}, }) - if !errors.Is(err, ErrIneffectiveNAT1To1IPMappingSrflx) { - t.Fatalf("Unexpected error: %v", err) - } + require.ErrorIs(t, ErrIneffectiveNAT1To1IPMappingSrflx, err) // NewAgent should return an error when 1:1 NAT for host candidate is enabled // along with mDNS with MulticastDNSModeQueryAndGather @@ -1143,18 +952,14 @@ func TestInitExtIPMapping(t *testing.T) { NAT1To1IPCandidateType: CandidateTypeHost, MulticastDNSMode: MulticastDNSModeQueryAndGather, }) - if !errors.Is(err, ErrMulticastDNSWithNAT1To1IPMapping) { - t.Fatalf("Unexpected error: %v", err) - } + require.ErrorIs(t, ErrMulticastDNSWithNAT1To1IPMapping, err) // NewAgent should return if newExternalIPMapper() returns an error. _, err = NewAgent(&AgentConfig{ NAT1To1IPs: []string{"bad.2.3.4"}, // Bad IP NAT1To1IPCandidateType: CandidateTypeHost, }) - if !errors.Is(err, ErrInvalidNAT1To1IPMapping) { - t.Fatalf("Unexpected error: %v", err) - } + require.ErrorIs(t, ErrInvalidNAT1To1IPMapping, err) } func TestBindingRequestTimeout(t *testing.T) { @@ -1260,7 +1065,7 @@ func TestConnectionStateFailedDeleteAllCandidates(t *testing.T) { } })) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isFailed done := make(chan struct{}) @@ -1312,7 +1117,7 @@ func TestConnectionStateConnectingToFailed(t *testing.T) { case ConnectionStateChecking: isChecking.Done() case ConnectionStateCompleted: - t.Errorf("Unexpected ConnectionState: %v", c) + t.Errorf("Unexpected ConnectionState: %v", c) //nolint default: } } @@ -1342,7 +1147,7 @@ func TestAgentRestart(t *testing.T) { oneSecond := time.Second t.Run("Restart During Gather", func(t *testing.T) { - connA, connB := pipe(&AgentConfig{ + connA, connB := pipe(t, &AgentConfig{ DisconnectedTimeout: &oneSecond, FailedTimeout: &oneSecond, }) @@ -1370,7 +1175,7 @@ func TestAgentRestart(t *testing.T) { }) t.Run("Restart One Side", func(t *testing.T) { - connA, connB := pipe(&AgentConfig{ + connA, connB := pipe(t, &AgentConfig{ DisconnectedTimeout: &oneSecond, FailedTimeout: &oneSecond, }) @@ -1401,7 +1206,7 @@ func TestAgentRestart(t *testing.T) { } // Store the original candidates, confirm that after we reconnect we have new pairs - connA, connB := pipe(&AgentConfig{ + connA, connB := pipe(t, &AgentConfig{ DisconnectedTimeout: &oneSecond, FailedTimeout: &oneSecond, }) @@ -1428,7 +1233,7 @@ func TestAgentRestart(t *testing.T) { require.NoError(t, err) require.NoError(t, connB.agent.SetRemoteCredentials(ufrag, pwd)) - gatherAndExchangeCandidates(connA.agent, connB.agent) + gatherAndExchangeCandidates(t, connA.agent, connB.agent) // Wait until both have gone back to connected <-aConnected @@ -1443,9 +1248,7 @@ func TestAgentRestart(t *testing.T) { func TestGetRemoteCredentials(t *testing.T) { var config AgentConfig agent, err := NewAgent(&config) - if err != nil { - t.Fatalf("Error constructing ice.Agent: %v", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -1464,9 +1267,7 @@ func TestGetRemoteCandidates(t *testing.T) { var config AgentConfig agent, err := NewAgent(&config) - if err != nil { - t.Fatalf("Error constructing ice.Agent: %v", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -1498,9 +1299,7 @@ func TestGetLocalCandidates(t *testing.T) { var config AgentConfig agent, err := NewAgent(&config) - if err != nil { - t.Fatalf("Error constructing ice.Agent: %v", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -1580,7 +1379,7 @@ func TestCloseInConnectionStateCallback(t *testing.T) { }) require.NoError(t, err) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) close(isConnected) <-isClosed @@ -1605,12 +1404,12 @@ func TestRunTaskInConnectionStateCallback(t *testing.T) { } aAgent, err := NewAgent(cfg) - check(err) + require.NoError(t, err) defer func() { require.NoError(t, aAgent.Close()) }() bAgent, err := NewAgent(cfg) - check(err) + require.NoError(t, err) defer func() { require.NoError(t, bAgent.Close()) }() @@ -1626,7 +1425,7 @@ func TestRunTaskInConnectionStateCallback(t *testing.T) { }) require.NoError(t, err) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isComplete } @@ -1650,36 +1449,35 @@ func TestRunTaskInSelectedCandidatePairChangeCallback(t *testing.T) { } aAgent, err := NewAgent(cfg) - check(err) + require.NoError(t, err) defer func() { require.NoError(t, aAgent.Close()) }() bAgent, err := NewAgent(cfg) - check(err) + require.NoError(t, err) defer func() { require.NoError(t, bAgent.Close()) }() isComplete := make(chan interface{}) isTested := make(chan interface{}) - if err = aAgent.OnSelectedCandidatePairChange(func(Candidate, Candidate) { + err = aAgent.OnSelectedCandidatePairChange(func(Candidate, Candidate) { go func() { _, _, errCred := aAgent.GetLocalUserCredentials() require.NoError(t, errCred) close(isTested) }() - }); err != nil { - t.Error(err) - } - if err = aAgent.OnConnectionStateChange(func(c ConnectionState) { + }) + require.NoError(t, err) + + err = aAgent.OnConnectionStateChange(func(c ConnectionState) { if c == ConnectionStateConnected { close(isComplete) } - }); err != nil { - t.Error(err) - } + }) + require.NoError(t, err) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-isComplete <-isTested @@ -1746,7 +1544,7 @@ func TestLiteLifecycle(t *testing.T) { } })) - connectWithVNet(bAgent, aAgent) + connectWithVNet(t, bAgent, aAgent) <-aConnected <-bConnected @@ -1821,7 +1619,7 @@ func TestGetSelectedCandidatePair(t *testing.T) { require.NoError(t, err) require.Nil(t, bAgentPair) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) aAgentPair, err = aAgent.GetSelectedCandidatePair() require.NoError(t, err) @@ -1920,7 +1718,7 @@ func TestAcceptAggressiveNomination(t *testing.T) { //nolint:cyclop }() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) // Ensure pair selected // Note: this assumes ConnectionStateConnected is thrown after selecting the final pair @@ -2008,11 +1806,8 @@ func TestAcceptAggressiveNomination(t *testing.T) { //nolint:cyclop case selected := <-selectedCh: require.True(t, selected.Equal(expectNewSelectedCandidate)) default: - if !tc.isExpectedToSwitch { - require.True(t, aAgent.getSelectedPair().Remote.Equal(expectNewSelectedCandidate)) - } else { - t.Fatal("No selected candidate pair") - } + require.False(t, tc.isExpectedToSwitch) + require.True(t, aAgent.getSelectedPair().Remote.Equal(expectNewSelectedCandidate)) } }) } @@ -2053,15 +1848,13 @@ func TestAgentGracefulCloseDeadlock(t *testing.T) { closeNow.Add(1) closed.Add(2) closeHdlr := func(agent *Agent, agentClosed *bool) { - check(agent.OnConnectionStateChange(func(cs ConnectionState) { + require.NoError(t, agent.OnConnectionStateChange(func(cs ConnectionState) { if cs == ConnectionStateConnected { connected.Done() closeNow.Wait() go func() { - if err := agent.GracefulClose(); err != nil { - require.NoError(t, err) - } + require.NoError(t, agent.GracefulClose()) *agentClosed = true closed.Done() }() @@ -2073,7 +1866,7 @@ func TestAgentGracefulCloseDeadlock(t *testing.T) { closeHdlr(bAgent, &bAgentClosed) t.Log("connecting agents") - _, _ = connect(aAgent, bAgent) + _, _ = connect(t, aAgent, bAgent) t.Log("waiting for them to confirm connection in callback") connected.Wait() @@ -2087,9 +1880,7 @@ func TestSetCandidatesUfrag(t *testing.T) { var config AgentConfig agent, err := NewAgent(&config) - if err != nil { - t.Fatalf("Error constructing ice.Agent: %v", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -2129,9 +1920,7 @@ func TestAlwaysSentKeepAlive(t *testing.T) { //nolint:cyclop defer test.TimeOut(1 * time.Second).Stop() agent, err := NewAgent(&AgentConfig{}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -2139,11 +1928,9 @@ func TestAlwaysSentKeepAlive(t *testing.T) { //nolint:cyclop log := logging.NewDefaultLoggerFactory().NewLogger("agent") agent.selector = &controllingSelector{agent: agent, log: log} pair := makeCandidatePair(t) - if s, ok := pair.Local.(*CandidateHost); ok { - s.conn = &fakenet.MockPacketConn{} - } else { - t.Fatalf("Invalid local candidate") - } + s, ok := pair.Local.(*CandidateHost) + require.True(t, ok) + s.conn = &fakenet.MockPacketConn{} agent.setSelectedPair(pair) pair.Remote.seen(false) diff --git a/agent_udpmux_test.go b/agent_udpmux_test.go index 1dd70c7..ec71bee 100644 --- a/agent_udpmux_test.go +++ b/agent_udpmux_test.go @@ -71,7 +71,7 @@ func TestMuxAgent(t *testing.T) { require.NoError(t, agent.Close()) }() - conn, muxedConn := connect(agent, muxedA) + conn, muxedConn := connect(t, agent, muxedA) pair := muxedA.getSelectedPair() require.NotNil(t, pair) diff --git a/candidate_relay_test.go b/candidate_relay_test.go index f22af07..1a04506 100644 --- a/candidate_relay_test.go +++ b/candidate_relay_test.go @@ -80,7 +80,7 @@ func TestRelayOnlyConnection(t *testing.T) { bNotifier, bConnected := onConnected() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-aConnected <-bConnected } diff --git a/candidate_server_reflexive_test.go b/candidate_server_reflexive_test.go index 77d344a..c3e91aa 100644 --- a/candidate_server_reflexive_test.go +++ b/candidate_server_reflexive_test.go @@ -73,7 +73,7 @@ func TestServerReflexiveOnlyConnection(t *testing.T) { bNotifier, bConnected := onConnected() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-aConnected <-bConnected } diff --git a/candidate_test.go b/candidate_test.go index ac7b642..a89632f 100644 --- a/candidate_test.go +++ b/candidate_test.go @@ -176,9 +176,7 @@ func TestCandidatePriority(t *testing.T) { WantPriority: 16777215, }, } { - if got, want := test.Candidate.Priority(), test.WantPriority; got != want { - t.Fatalf("Candidate(%v).Priority() = %d, want %d", test.Candidate, got, want) - } + require.Equal(t, test.Candidate.Priority(), test.WantPriority) } } @@ -271,9 +269,7 @@ func mustCandidateHost(t *testing.T, conf *CandidateHostConfig) Candidate { t.Helper() cand, err := NewCandidateHost(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) return cand } @@ -286,9 +282,7 @@ func mustCandidateHostWithExtensions( t.Helper() cand, err := NewCandidateHost(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) cand.setExtensions(extensions) @@ -299,9 +293,7 @@ func mustCandidateRelay(t *testing.T, conf *CandidateRelayConfig) Candidate { t.Helper() cand, err := NewCandidateRelay(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) return cand } @@ -314,9 +306,7 @@ func mustCandidateRelayWithExtensions( t.Helper() cand, err := NewCandidateRelay(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) cand.setExtensions(extensions) @@ -327,9 +317,7 @@ func mustCandidateServerReflexive(t *testing.T, conf *CandidateServerReflexiveCo t.Helper() cand, err := NewCandidateServerReflexive(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) return cand } @@ -342,9 +330,7 @@ func mustCandidateServerReflexiveWithExtensions( t.Helper() cand, err := NewCandidateServerReflexive(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) cand.setExtensions(extensions) @@ -359,9 +345,7 @@ func mustCandidatePeerReflexiveWithExtensions( t.Helper() cand, err := NewCandidatePeerReflexive(conf) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) cand.setExtensions(extensions) @@ -603,7 +587,7 @@ func TestCandidateWriteTo(t *testing.T) { }) require.NoError(t, err, "error creating test TCP listener") - conn, err := net.DialTCP("tcp", nil, listener.Addr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, listener.Addr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") loggerFactory := logging.NewDefaultLoggerFactory() @@ -1049,9 +1033,7 @@ func TestCandidateGetExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) candidate.setExtensions(extensions) @@ -1086,9 +1068,7 @@ func TestCandidateGetExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) candidate.setExtensions(extensions) @@ -1111,9 +1091,7 @@ func TestCandidateGetExtension(t *testing.T) { Foundation: "750", TCPType: TCPTypeActive, }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) tcpType, ok := candidate.GetExtension("tcptype") @@ -1136,9 +1114,7 @@ func TestCandidateGetExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) tcpType, ok = candidate2.GetExtension("tcptype") @@ -1163,9 +1139,7 @@ func TestBaseCandidateMarshalExtensions(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) candidate.setExtensions(extensions) @@ -1181,9 +1155,7 @@ func TestBaseCandidateMarshalExtensions(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) value := candidate.marshalExtensions() require.Equal(t, "", value) @@ -1198,9 +1170,7 @@ func TestBaseCandidateMarshalExtensions(t *testing.T) { Foundation: "750", TCPType: TCPTypeActive, }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) value := candidate.marshalExtensions() require.Equal(t, "tcptype active", value) @@ -1296,9 +1266,7 @@ func TestBaseCandidateExtensionsEqual(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) cand.setExtensions(testCase.extensions1) @@ -1316,9 +1284,7 @@ func TestCandidateAddExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.NoError(t, candidate.AddExtension(CandidateExtension{"a", "b"})) require.NoError(t, candidate.AddExtension(CandidateExtension{"c", "d"})) @@ -1335,9 +1301,7 @@ func TestCandidateAddExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.NoError(t, candidate.AddExtension(CandidateExtension{"a", "b"})) require.NoError(t, candidate.AddExtension(CandidateExtension{"a", "d"})) @@ -1355,9 +1319,7 @@ func TestCandidateAddExtension(t *testing.T) { Foundation: "750", TCPType: TCPTypeActive, }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) ext, ok := candidate.GetExtension("tcptype") require.True(t, ok) @@ -1380,9 +1342,7 @@ func TestCandidateAddExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.NoError(t, candidate.AddExtension(CandidateExtension{"tcptype", "active"})) @@ -1401,9 +1361,7 @@ func TestCandidateAddExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.Error(t, candidate.AddExtension(CandidateExtension{"", ""})) @@ -1424,9 +1382,7 @@ func TestCandidateRemoveExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.NoError(t, candidate.AddExtension(CandidateExtension{"a", "b"})) require.NoError(t, candidate.AddExtension(CandidateExtension{"c", "d"})) @@ -1445,9 +1401,7 @@ func TestCandidateRemoveExtension(t *testing.T) { Priority: 500, Foundation: "750", }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) require.NoError(t, candidate.AddExtension(CandidateExtension{"a", "b"})) require.NoError(t, candidate.AddExtension(CandidateExtension{"c", "d"})) @@ -1467,9 +1421,7 @@ func TestCandidateRemoveExtension(t *testing.T) { Foundation: "750", TCPType: TCPTypeActive, }) - if err != nil { - t.Error(err) - } + require.NoError(t, err) // tcptype extension should be removed, even if it's not in the extensions list (Not Parsed) require.True(t, candidate.RemoveExtension("tcptype")) diff --git a/candidatepair_test.go b/candidatepair_test.go index a338a69..f6e8284 100644 --- a/candidatepair_test.go +++ b/candidatepair_test.go @@ -115,9 +115,7 @@ func TestCandidatePairPriority(t *testing.T) { WantPriority: 72057593987596287, }, } { - if got, want := test.Pair.priority(), test.WantPriority; got != want { - t.Fatalf("CandidatePair(%v).Priority() = %d, want %d", test.Pair, got, want) - } + require.Equal(t, test.Pair.priority(), test.WantPriority) } } @@ -125,9 +123,7 @@ func TestCandidatePairEquality(t *testing.T) { pairA := newCandidatePair(hostCandidate(), srflxCandidate(), true) pairB := newCandidatePair(hostCandidate(), srflxCandidate(), false) - if !pairA.equal(pairB) { - t.Fatalf("Expected %v to equal %v", pairA, pairB) - } + require.True(t, pairA.equal(pairB)) } func TestNilCandidatePairString(t *testing.T) { diff --git a/connectivity_vnet_test.go b/connectivity_vnet_test.go index 5ab5b56..2064c46 100644 --- a/connectivity_vnet_test.go +++ b/connectivity_vnet_test.go @@ -200,15 +200,16 @@ func addVNetSTUN(wanNet *vnet.Net, loggerFactory logging.LoggerFactory) (*turn.S return server, err } -func connectWithVNet(aAgent, bAgent *Agent) (*Conn, *Conn) { +func connectWithVNet(t *testing.T, aAgent, bAgent *Agent) (*Conn, *Conn) { + t.Helper() // Manual signaling aUfrag, aPwd, err := aAgent.GetLocalUserCredentials() - check(err) + require.NoError(t, err) bUfrag, bPwd, err := bAgent.GetLocalUserCredentials() - check(err) + require.NoError(t, err) - gatherAndExchangeCandidates(aAgent, bAgent) + gatherAndExchangeCandidates(t, aAgent, bAgent) accepted := make(chan struct{}) var aConn *Conn @@ -216,12 +217,12 @@ func connectWithVNet(aAgent, bAgent *Agent) (*Conn, *Conn) { go func() { var acceptErr error aConn, acceptErr = aAgent.Accept(context.TODO(), bUfrag, bPwd) - check(acceptErr) + require.NoError(t, acceptErr) close(accepted) }() bConn, err := bAgent.Dial(context.TODO(), aUfrag, aPwd) - check(err) + require.NoError(t, err) // Ensure accepted <-accepted @@ -234,7 +235,8 @@ type agentTestConfig struct { nat1To1IPCandidateType CandidateType } -func pipeWithVNet(vnet *virtualNet, a0TestConfig, a1TestConfig *agentTestConfig) (*Conn, *Conn) { +func pipeWithVNet(t *testing.T, vnet *virtualNet, a0TestConfig, a1TestConfig *agentTestConfig) (*Conn, *Conn) { + t.Helper() aNotifier, aConnected := onConnected() bNotifier, bConnected := onConnected() @@ -255,13 +257,8 @@ func pipeWithVNet(vnet *virtualNet, a0TestConfig, a1TestConfig *agentTestConfig) } aAgent, err := NewAgent(cfg0) - if err != nil { - panic(err) - } - err = aAgent.OnConnectionStateChange(aNotifier) - if err != nil { - panic(err) - } + require.NoError(t, err) + require.NoError(t, aAgent.OnConnectionStateChange(aNotifier)) if a1TestConfig.nat1To1IPCandidateType != CandidateTypeUnspecified { nat1To1IPs = []string{ @@ -278,15 +275,10 @@ func pipeWithVNet(vnet *virtualNet, a0TestConfig, a1TestConfig *agentTestConfig) } bAgent, err := NewAgent(cfg1) - if err != nil { - panic(err) - } - err = bAgent.OnConnectionStateChange(bNotifier) - if err != nil { - panic(err) - } + require.NoError(t, err) + require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - aConn, bConn := connectWithVNet(aAgent, bAgent) + aConn, bConn := connectWithVNet(t, aAgent, bAgent) // Ensure pair selected // Note: this assumes ConnectionStateConnected is thrown after selecting the final pair @@ -347,7 +339,7 @@ func TestConnectivityVNet(t *testing.T) { stunServerURL, }, } - ca, cb := pipeWithVNet(vnet, a0TestConfig, a1TestConfig) + ca, cb := pipeWithVNet(t, vnet, a0TestConfig, a1TestConfig) time.Sleep(1 * time.Second) @@ -381,7 +373,7 @@ func TestConnectivityVNet(t *testing.T) { stunServerURL, }, } - ca, cb := pipeWithVNet(vnet, a0TestConfig, a1TestConfig) + ca, cb := pipeWithVNet(t, vnet, a0TestConfig, a1TestConfig) log.Debug("Closing...") closePipe(t, ca, cb) @@ -413,7 +405,7 @@ func TestConnectivityVNet(t *testing.T) { a1TestConfig := &agentTestConfig{ urls: []*stun.URI{}, } - ca, cb := pipeWithVNet(vnet, a0TestConfig, a1TestConfig) + ca, cb := pipeWithVNet(t, vnet, a0TestConfig, a1TestConfig) log.Debug("Closing...") closePipe(t, ca, cb) @@ -445,7 +437,7 @@ func TestConnectivityVNet(t *testing.T) { a1TestConfig := &agentTestConfig{ urls: []*stun.URI{}, } - ca, cb := pipeWithVNet(vnet, a0TestConfig, a1TestConfig) + ca, cb := pipeWithVNet(t, vnet, a0TestConfig, a1TestConfig) log.Debug("Closing...") closePipe(t, ca, cb) @@ -527,7 +519,7 @@ func TestDisconnectedToConnected(t *testing.T) { controlledStateChanges <- c })) - connectWithVNet(controllingAgent, controlledAgent) + connectWithVNet(t, controllingAgent, controlledAgent) blockUntilStateSeen := func(expectedState ConnectionState, stateQueue chan ConnectionState) { for s := range stateQueue { if s == expectedState { @@ -618,7 +610,7 @@ func TestWriteUseValidPair(t *testing.T) { require.NoError(t, controlledAgent.Close()) }() - gatherAndExchangeCandidates(controllingAgent, controlledAgent) + gatherAndExchangeCandidates(t, controllingAgent, controlledAgent) controllingUfrag, controllingPwd, err := controllingAgent.GetLocalUserCredentials() require.NoError(t, err) diff --git a/errors.go b/errors.go index 39b22e5..a803665 100644 --- a/errors.go +++ b/errors.go @@ -136,7 +136,6 @@ var ( errParseRelatedAddr = errors.New("failed to parse related addresses") errParseExtension = errors.New("failed to parse extension") errParseTCPType = errors.New("failed to parse TCP type") - errRead = errors.New("failed to read") errUDPMuxDisabled = errors.New("UDPMux is not enabled") errUnknownRole = errors.New("unknown role") errWrite = errors.New("failed to write") diff --git a/gather_test.go b/gather_test.go index d450187..6ef39e1 100644 --- a/gather_test.go +++ b/gather_test.go @@ -12,7 +12,6 @@ import ( "io" "net" "net/url" - "reflect" "sort" "strconv" "sync" @@ -78,19 +77,13 @@ func TestListenUDP(t *testing.T) { require.NoError(t, err) p, _ := strconv.Atoi(port) - if p < portMin || p > portMax { - t.Fatalf("listenUDP with port restriction [%d, %d] listened on incorrect port (%s)", portMin, portMax, port) - } + require.False(t, p < portMin || p > portMax) result = append(result, p) portRange = append(portRange, portMin+i) } - if sort.IntsAreSorted(result) { - t.Fatalf("listenUDP with port restriction [%d, %d], ports result should be random", portMin, portMax) - } + require.False(t, sort.IntsAreSorted(result)) sort.Ints(result) - if !reflect.DeepEqual(result, portRange) { - t.Fatalf("listenUDP with port restriction [%d, %d], got:%v, want:%v", portMin, portMax, result, portRange) - } + require.Equal(t, result, portRange) _, err = listenUDPInPortRange(agent.net, agent.log, portMax, portMin, udp, &net.UDPAddr{IP: ip, Port: 0}) require.Equal(t, err, ErrPort, "listenUDP with port restriction [%d, %d], did not return ErrPort", portMin, portMax) } diff --git a/gather_vnet_test.go b/gather_vnet_test.go index c5a3f1d..3020367 100644 --- a/gather_vnet_test.go +++ b/gather_vnet_test.go @@ -8,7 +8,6 @@ package ice import ( "context" - "errors" "fmt" "net" "testing" @@ -38,36 +37,25 @@ func TestVNetGather(t *testing.T) { //nolint:cyclop }() _, localIPs, err := localInterfaces(a.net, a.interfaceFilter, a.ipFilter, []NetworkType{NetworkTypeUDP4}, false) - if len(localIPs) > 0 { - t.Fatal("should return no local IP") - } + require.Len(t, localIPs, 0) require.NoError(t, err) }) t.Run("Gather a dynamic IP address", func(t *testing.T) { cider := "1.2.3.0/24" _, ipNet, err := net.ParseCIDR(cider) - if err != nil { - t.Fatalf("Failed to parse CIDR: %s", err) - } + require.NoError(t, err) router, err := vnet.NewRouter(&vnet.RouterConfig{ CIDR: cider, LoggerFactory: loggerFactory, }) - if err != nil { - t.Fatalf("Failed to create a router: %s", err) - } + require.NoError(t, err) nw, err := vnet.NewNet(&vnet.NetConfig{}) - if err != nil { - t.Fatalf("Failed to create a Net: %s", err) - } + require.NoError(t, err) - err = router.AddNet(nw) - if err != nil { - t.Fatalf("Failed to add a Net to the router: %s", err) - } + require.NoError(t, router.AddNet(nw)) a, err := NewAgent(&AgentConfig{ Net: nw, @@ -78,18 +66,12 @@ func TestVNetGather(t *testing.T) { //nolint:cyclop }() _, localAddrs, err := localInterfaces(a.net, a.interfaceFilter, a.ipFilter, []NetworkType{NetworkTypeUDP4}, false) - if len(localAddrs) == 0 { - t.Fatal("should have one local IP") - } + require.Len(t, localAddrs, 1) require.NoError(t, err) for _, addr := range localAddrs { - if addr.IsLoopback() { - t.Fatal("should not return loopback IP") - } - if !ipNet.Contains(addr.AsSlice()) { - t.Fatal("should be contained in the CIDR") - } + require.False(t, addr.IsLoopback()) + require.True(t, ipNet.Contains(addr.AsSlice())) } }) @@ -98,24 +80,15 @@ func TestVNetGather(t *testing.T) { //nolint:cyclop CIDR: "1.2.3.0/24", LoggerFactory: loggerFactory, }) - if err != nil { - t.Fatalf("Failed to create a router: %s", err) - } + require.NoError(t, err) nw, err := vnet.NewNet(&vnet.NetConfig{}) - if err != nil { - t.Fatalf("Failed to create a Net: %s", err) - } + require.NoError(t, err) - err = router.AddNet(nw) - if err != nil { - t.Fatalf("Failed to add a Net to the router: %s", err) - } + require.NoError(t, router.AddNet(nw)) agent, err := NewAgent(&AgentConfig{Net: nw}) - if err != nil { - t.Fatalf("Failed to create agent: %s", err) - } + require.NoError(t, err) defer func() { require.NoError(t, agent.Close()) }() @@ -127,35 +100,22 @@ func TestVNetGather(t *testing.T) { //nolint:cyclop []NetworkType{NetworkTypeUDP4}, false, ) - if len(localAddrs) == 0 { - t.Fatal("localInterfaces found no interfaces, unable to test") - } + require.NotEqual(t, 0, len(localAddrs)) require.NoError(t, err) ip := localAddrs[0].AsSlice() conn, err := listenUDPInPortRange(agent.net, agent.log, 0, 0, udp, &net.UDPAddr{IP: ip, Port: 0}) - if err != nil { - t.Fatalf("listenUDP error with no port restriction %v", err) - } else if conn == nil { - t.Fatalf("listenUDP error with no port restriction return a nil conn") - } - err = conn.Close() - if err != nil { - t.Fatalf("failed to close conn") - } + require.NoError(t, err) + require.NotNil(t, conn) + require.NoError(t, conn.Close()) _, err = listenUDPInPortRange(agent.net, agent.log, 4999, 5000, udp, &net.UDPAddr{IP: ip, Port: 0}) - if !errors.Is(err, ErrPort) { - t.Fatal("listenUDP with invalid port range did not return ErrPort") - } + require.ErrorIs(t, ErrPort, err) conn, err = listenUDPInPortRange(agent.net, agent.log, 5000, 5000, udp, &net.UDPAddr{IP: ip, Port: 0}) - if err != nil { - t.Fatalf("listenUDP error with no port restriction %v", err) - } else if conn == nil { - t.Fatalf("listenUDP error with no port restriction return a nil conn") - } + require.NoError(t, err) + require.NotNil(t, conn) defer func() { require.NoError(t, conn.Close()) }() @@ -163,9 +123,7 @@ func TestVNetGather(t *testing.T) { //nolint:cyclop _, port, err := net.SplitHostPort(conn.LocalAddr().String()) require.NoError(t, err) - if port != "5000" { - t.Fatalf("listenUDP with port restriction of 5000 listened on incorrect port (%s)", port) - } + require.Equal(t, "5000", port) }) } @@ -205,9 +163,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { //nolint:cyclop nw, err := vnet.NewNet(&vnet.NetConfig{ StaticIPs: []string{localIP0, localIP1}, }) - if err != nil { - t.Fatalf("Failed to create a Net: %s", err) - } + require.NoError(t, err) err = lan.AddNet(nw) require.NoError(t, err, "should succeed") @@ -242,38 +198,22 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { //nolint:cyclop candidates, err := agent.GetLocalCandidates() require.NoError(t, err, "should succeed") - if len(candidates) != 2 { - t.Fatal("There must be two candidates") - } + require.Len(t, candidates, 2) lAddr := [2]*net.UDPAddr{nil, nil} for i, candi := range candidates { lAddr[i] = candi.(*CandidateHost).conn.LocalAddr().(*net.UDPAddr) //nolint:forcetypeassert - if candi.Port() != lAddr[i].Port { - t.Fatalf("Unexpected candidate port: %d", candi.Port()) - } + require.Equal(t, candi.Port(), lAddr[i].Port) } if candidates[0].Address() == externalIP0 { //nolint:nestif - if candidates[1].Address() != externalIP1 { - t.Fatalf("Unexpected candidate IP: %s", candidates[1].Address()) - } - if lAddr[0].IP.String() != localIP0 { - t.Fatalf("Unexpected listen IP: %s", lAddr[0].IP.String()) - } - if lAddr[1].IP.String() != localIP1 { - t.Fatalf("Unexpected listen IP: %s", lAddr[1].IP.String()) - } + require.Equal(t, candidates[1].Address(), externalIP1) + require.Equal(t, lAddr[0].IP.String(), localIP0) + require.Equal(t, lAddr[1].IP.String(), localIP1) } else if candidates[0].Address() == externalIP1 { - if candidates[1].Address() != externalIP0 { - t.Fatalf("Unexpected candidate IP: %s", candidates[1].Address()) - } - if lAddr[0].IP.String() != localIP1 { - t.Fatalf("Unexpected listen IP: %s", lAddr[0].IP.String()) - } - if lAddr[1].IP.String() != localIP0 { - t.Fatalf("Unexpected listen IP: %s", lAddr[1].IP.String()) - } + require.Equal(t, candidates[1].Address(), externalIP0) + require.Equal(t, lAddr[0].IP.String(), localIP1) + require.Equal(t, lAddr[1].IP.String(), localIP0) } }) @@ -304,9 +244,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { //nolint:cyclop "10.0.0.1", }, }) - if err != nil { - t.Fatalf("Failed to create a Net: %s", err) - } + require.NoError(t, err) err = lan.AddNet(nw) require.NoError(t, err, "should succeed") @@ -344,9 +282,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { //nolint:cyclop candidates, err := agent.GetLocalCandidates() require.NoError(t, err, "should succeed") - if len(candidates) != 2 { - t.Fatalf("Expected two candidates. actually %d", len(candidates)) - } + require.Len(t, candidates, 2) var candiHost *CandidateHost var candiSrflx *CandidateServerReflexive @@ -358,7 +294,7 @@ func TestVNetGatherWithNAT1To1(t *testing.T) { //nolint:cyclop case *CandidateServerReflexive: candiSrflx = candi default: - t.Fatal("Unexpected candidate type") + t.Fatal("Unexpected candidate type") // nolint } } @@ -377,18 +313,11 @@ func TestVNetGatherWithInterfaceFilter(t *testing.T) { CIDR: "1.2.3.0/24", LoggerFactory: loggerFactory, }) - if err != nil { - t.Fatalf("Failed to create a router: %s", err) - } + require.NoError(t, err) nw, err := vnet.NewNet(&vnet.NetConfig{}) - if err != nil { - t.Fatalf("Failed to create a Net: %s", err) - } - - if err = router.AddNet(nw); err != nil { - t.Fatalf("Failed to add a Net to the router: %s", err) - } + require.NoError(t, err) + require.NoError(t, router.AddNet(nw)) t.Run("InterfaceFilter should exclude the interface", func(t *testing.T) { agent, err := NewAgent(&AgentConfig{ @@ -412,10 +341,7 @@ func TestVNetGatherWithInterfaceFilter(t *testing.T) { false, ) require.NoError(t, err) - - if len(localIPs) != 0 { - t.Fatal("InterfaceFilter should have excluded everything") - } + require.Len(t, localIPs, 0) }) t.Run("IPFilter should exclude the IP", func(t *testing.T) { @@ -440,10 +366,7 @@ func TestVNetGatherWithInterfaceFilter(t *testing.T) { false, ) require.NoError(t, err) - - if len(localIPs) != 0 { - t.Fatal("IPFilter should have excluded everything") - } + require.Len(t, localIPs, 0) }) t.Run("InterfaceFilter should not exclude the interface", func(t *testing.T) { @@ -468,10 +391,7 @@ func TestVNetGatherWithInterfaceFilter(t *testing.T) { false, ) require.NoError(t, err) - - if len(localIPs) == 0 { - t.Fatal("InterfaceFilter should not have excluded anything") - } + require.Len(t, localIPs, 1) }) } diff --git a/icecontrol_test.go b/icecontrol_test.go index 8d710d9..1ea25a4 100644 --- a/icecontrol_test.go +++ b/icecontrol_test.go @@ -4,69 +4,52 @@ package ice import ( - "errors" "testing" "github.com/pion/stun/v3" + "github.com/stretchr/testify/require" ) func TestControlled_GetFrom(t *testing.T) { //nolint:dupl m := new(stun.Message) var attrCtr AttrControlled - if err := attrCtr.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } - if err := m.Build(stun.BindingRequest, &attrCtr); err != nil { - t.Error(err) - } + require.ErrorIs(t, stun.ErrAttributeNotFound, attrCtr.GetFrom(m)) + require.NoError(t, m.Build(stun.BindingRequest, &attrCtr)) + m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) + var c1 AttrControlled - if err := c1.GetFrom(m1); err != nil { - t.Error(err) - } - if c1 != attrCtr { - t.Error("not equal") - } + require.NoError(t, c1.GetFrom(m1)) + require.Equal(t, c1, attrCtr) + t.Run("IncorrectSize", func(t *testing.T) { m3 := new(stun.Message) m3.Add(stun.AttrICEControlled, make([]byte, 100)) var c2 AttrControlled - if err := c2.GetFrom(m3); !stun.IsAttrSizeInvalid(err) { - t.Error("should error") - } + require.True(t, stun.IsAttrSizeInvalid(c2.GetFrom(m3))) }) } func TestControlling_GetFrom(t *testing.T) { //nolint:dupl m := new(stun.Message) var attrCtr AttrControlling - if err := attrCtr.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } - if err := m.Build(stun.BindingRequest, &attrCtr); err != nil { - t.Error(err) - } + require.ErrorIs(t, stun.ErrAttributeNotFound, attrCtr.GetFrom(m)) + require.NoError(t, m.Build(stun.BindingRequest, &attrCtr)) + m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) + var c1 AttrControlling - if err := c1.GetFrom(m1); err != nil { - t.Error(err) - } - if c1 != attrCtr { - t.Error("not equal") - } + require.NoError(t, c1.GetFrom(m1)) + require.Equal(t, c1, attrCtr) t.Run("IncorrectSize", func(t *testing.T) { m3 := new(stun.Message) m3.Add(stun.AttrICEControlling, make([]byte, 100)) var c2 AttrControlling - if err := c2.GetFrom(m3); !stun.IsAttrSizeInvalid(err) { - t.Error("should error") - } + require.True(t, stun.IsAttrSizeInvalid(c2.GetFrom(m3))) }) } @@ -74,70 +57,49 @@ func TestControl_GetFrom(t *testing.T) { //nolint:cyclop t.Run("Blank", func(t *testing.T) { m := new(stun.Message) var c AttrControl - if err := c.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } + require.ErrorIs(t, stun.ErrAttributeNotFound, c.GetFrom(m)) }) t.Run("Controlling", func(t *testing.T) { //nolint:dupl m := new(stun.Message) var attCtr AttrControl - if err := attCtr.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } + require.ErrorIs(t, stun.ErrAttributeNotFound, attCtr.GetFrom(m)) attCtr.Role = Controlling attCtr.Tiebreaker = 4321 - if err := m.Build(stun.BindingRequest, &attCtr); err != nil { - t.Error(err) - } + require.NoError(t, m.Build(stun.BindingRequest, &attCtr)) m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) var c1 AttrControl - if err := c1.GetFrom(m1); err != nil { - t.Error(err) - } - if c1 != attCtr { - t.Error("not equal") - } + require.NoError(t, c1.GetFrom(m1)) + require.Equal(t, c1, attCtr) t.Run("IncorrectSize", func(t *testing.T) { m3 := new(stun.Message) m3.Add(stun.AttrICEControlling, make([]byte, 100)) var c2 AttrControl - if err := c2.GetFrom(m3); !stun.IsAttrSizeInvalid(err) { - t.Error("should error") - } + err := c2.GetFrom(m3) + require.True(t, stun.IsAttrSizeInvalid(err)) }) }) t.Run("Controlled", func(t *testing.T) { //nolint:dupl m := new(stun.Message) var attrCtrl AttrControl - if err := attrCtrl.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } + require.ErrorIs(t, stun.ErrAttributeNotFound, attrCtrl.GetFrom(m)) attrCtrl.Role = Controlled attrCtrl.Tiebreaker = 1234 - if err := m.Build(stun.BindingRequest, &attrCtrl); err != nil { - t.Error(err) - } + require.NoError(t, m.Build(stun.BindingRequest, &attrCtrl)) m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) + var c1 AttrControl - if err := c1.GetFrom(m1); err != nil { - t.Error(err) - } - if c1 != attrCtrl { - t.Error("not equal") - } + require.NoError(t, c1.GetFrom(m1)) + require.Equal(t, c1, attrCtrl) t.Run("IncorrectSize", func(t *testing.T) { m3 := new(stun.Message) m3.Add(stun.AttrICEControlling, make([]byte, 100)) var c2 AttrControl - if err := c2.GetFrom(m3); !stun.IsAttrSizeInvalid(err) { - t.Error("should error") - } + err := c2.GetFrom(m3) + require.True(t, stun.IsAttrSizeInvalid(err)) }) }) } diff --git a/mdns_test.go b/mdns_test.go index a65d836..3dea4e4 100644 --- a/mdns_test.go +++ b/mdns_test.go @@ -65,7 +65,7 @@ func TestMulticastDNSOnlyConnection(t *testing.T) { bNotifier, bConnected := onConnected() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-aConnected <-bConnected }) @@ -124,7 +124,7 @@ func TestMulticastDNSMixedConnection(t *testing.T) { bNotifier, bConnected := onConnected() require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - connect(aAgent, bAgent) + connect(t, aAgent, bAgent) <-aConnected <-bConnected }) @@ -195,7 +195,5 @@ func TestGenerateMulticastDNSName(t *testing.T) { `^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}.local+$`, ).MatchString - if !isMDNSName(name) { - t.Fatalf("mDNS name must be UUID v4 + \".local\" suffix, got %s", name) - } + require.True(t, isMDNSName(name)) } diff --git a/net_test.go b/net_test.go index 8b7692e..8ebdf1f 100644 --- a/net_test.go +++ b/net_test.go @@ -13,25 +13,11 @@ import ( ) func TestIsSupportedIPv6Partial(t *testing.T) { - if isSupportedIPv6Partial(net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1}) { - t.Errorf("isSupportedIPv6Partial returned true with IPv4-compatible IPv6 address") - } - - if isSupportedIPv6Partial(net.ParseIP("fec0::2333")) { - t.Errorf("isSupportedIPv6Partial returned true with IPv6 site-local unicast address") - } - - if !isSupportedIPv6Partial(net.ParseIP("fe80::2333")) { - t.Errorf("isSupportedIPv6Partial returned false with IPv6 link-local address") - } - - if !isSupportedIPv6Partial(net.ParseIP("ff02::2333")) { - t.Errorf("isSupportedIPv6Partial returned false with IPv6 link-local multicast address") - } - - if !isSupportedIPv6Partial(net.ParseIP("2001::1")) { - t.Errorf("isSupportedIPv6Partial returned false with IPv6 global unicast address") - } + require.False(t, isSupportedIPv6Partial(net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1})) + require.False(t, isSupportedIPv6Partial(net.ParseIP("fec0::2333"))) + require.True(t, isSupportedIPv6Partial(net.ParseIP("fe80::2333"))) + require.True(t, isSupportedIPv6Partial(net.ParseIP("ff02::2333"))) + require.True(t, isSupportedIPv6Partial(net.ParseIP("2001::1"))) } func TestCreateAddr(t *testing.T) { @@ -67,7 +53,7 @@ func mustAddr(t *testing.T, ip net.IP) netip.Addr { t.Helper() addr, ok := netip.AddrFromSlice(ip) if !ok { - t.Fatal(ipConvertError{ip}) + t.Fatal(ipConvertError{ip}) // nolint } return addr diff --git a/networktype_test.go b/networktype_test.go index d327af6..31aba30 100644 --- a/networktype_test.go +++ b/networktype_test.go @@ -46,13 +46,8 @@ func TestNetworkTypeParsing_Success(t *testing.T) { }, } { actual, err := determineNetworkType(test.inNetwork, mustAddr(t, test.inIP)) - if err != nil { - t.Errorf("NetworkTypeParsing failed: %v", err) - } - if actual != test.expected { - t.Errorf("NetworkTypeParsing: '%s' -- input:%s expected:%s actual:%s", - test.name, test.inNetwork, test.expected, actual) - } + require.NoError(t, err) + require.Equal(t, test.expected, actual) } } @@ -70,11 +65,8 @@ func TestNetworkTypeParsing_Failure(t *testing.T) { ipv6, }, } { - actual, err := determineNetworkType(test.inNetwork, mustAddr(t, test.inIP)) - if err == nil { - t.Errorf("NetworkTypeParsing should fail: '%s' -- input:%s actual:%s", - test.name, test.inNetwork, actual) - } + _, err := determineNetworkType(test.inNetwork, mustAddr(t, test.inIP)) + require.Error(t, err) } } diff --git a/priority_test.go b/priority_test.go index b6b2c5d..eee418d 100644 --- a/priority_test.go +++ b/priority_test.go @@ -4,38 +4,29 @@ package ice import ( - "errors" "testing" "github.com/pion/stun/v3" + "github.com/stretchr/testify/require" ) func TestPriority_GetFrom(t *testing.T) { //nolint:dupl m := new(stun.Message) var priority PriorityAttr - if err := priority.GetFrom(m); !errors.Is(err, stun.ErrAttributeNotFound) { - t.Error("unexpected error") - } - if err := m.Build(stun.BindingRequest, &priority); err != nil { - t.Error(err) - } + require.ErrorIs(t, stun.ErrAttributeNotFound, priority.GetFrom(m)) + require.NoError(t, m.Build(stun.BindingRequest, &priority)) + m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) + var p1 PriorityAttr - if err := p1.GetFrom(m1); err != nil { - t.Error(err) - } - if p1 != priority { - t.Error("not equal") - } + require.NoError(t, p1.GetFrom(m1)) + require.Equal(t, p1, priority) t.Run("IncorrectSize", func(t *testing.T) { m3 := new(stun.Message) m3.Add(stun.AttrPriority, make([]byte, 100)) var p2 PriorityAttr - if err := p2.GetFrom(m3); !stun.IsAttrSizeInvalid(err) { - t.Error("should error") - } + require.True(t, stun.IsAttrSizeInvalid(p2.GetFrom(m3))) }) } diff --git a/rand_test.go b/rand_test.go index 9dd1187..420858c 100644 --- a/rand_test.go +++ b/rand_test.go @@ -67,15 +67,10 @@ func TestRandomGeneratorCollision(t *testing.T) { } wg.Wait() - if len(rands) != num { - t.Fatal("Failed to generate randoms") - } - + require.Len(t, rands, num) for i := 0; i < num; i++ { for j := i + 1; j < num; j++ { - if rands[i] == rands[j] { - t.Fatalf("generateRandString caused collision: %s == %s", rands[i], rands[j]) - } + require.NotEqual(t, rands[i], rands[j]) } } } diff --git a/selection_test.go b/selection_test.go index 7f4e5f3..810df8e 100644 --- a/selection_test.go +++ b/selection_test.go @@ -97,7 +97,7 @@ func TestBindingRequestHandler(t *testing.T) { require.NoError(t, err) require.NoError(t, controlledAgent.OnConnectionStateChange(bNotifier)) - controlledConn, controllingConn := connect(controlledAgent, controllingAgent) + controlledConn, controllingConn := connect(t, controlledAgent, controllingAgent) <-aConnected <-bConnected diff --git a/tcp_mux_multi_test.go b/tcp_mux_multi_test.go index 619b857..a73252c 100644 --- a/tcp_mux_multi_test.go +++ b/tcp_mux_multi_test.go @@ -61,7 +61,7 @@ func TestMultiTCPMux_Recv(t *testing.T) { defer func() { _ = pktConn.Close() }() - conn, err := net.DialTCP("tcp", nil, pktConn.LocalAddr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, pktConn.LocalAddr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") msg := stun.New() diff --git a/tcp_mux_test.go b/tcp_mux_test.go index 53fa9ee..b33e399 100644 --- a/tcp_mux_test.go +++ b/tcp_mux_test.go @@ -51,7 +51,7 @@ func TestTCPMux_Recv(t *testing.T) { require.NotNil(t, tcpMux.LocalAddr(), "tcpMux.LocalAddr() is nil") - conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") msg := stun.New() @@ -150,7 +150,7 @@ func TestTCPMux_FirstPacketTimeout(t *testing.T) { require.NotNil(t, tcpMux.LocalAddr(), "tcpMux.LocalAddr() is nil") - conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") defer func() { _ = conn.Close() @@ -192,7 +192,7 @@ func TestTCPMux_NoLeakForConnectionFromStun(t *testing.T) { require.NotNil(t, tcpMux.LocalAddr(), "tcpMux.LocalAddr() is nil") t.Run("close connection from stun msg after timeout", func(t *testing.T) { - conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") defer func() { _ = conn.Close() @@ -217,7 +217,7 @@ func TestTCPMux_NoLeakForConnectionFromStun(t *testing.T) { }) t.Run("connection keep alive if access by user", func(t *testing.T) { - conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) + conn, err := net.DialTCP("tcp", nil, tcpMux.LocalAddr().(*net.TCPAddr)) // nolint require.NoError(t, err, "error dialing test TCP connection") defer func() { _ = conn.Close() diff --git a/transport_test.go b/transport_test.go index 0581c93..0377f81 100644 --- a/transport_test.go +++ b/transport_test.go @@ -38,10 +38,7 @@ func testTimeout(t *testing.T, conn *Conn, timeout time.Duration) { ticker := time.NewTicker(pollRate) defer func() { ticker.Stop() - err := conn.Close() - if err != nil { - t.Error(err) - } + require.NoError(t, conn.Close()) }() startedAt := time.Now() @@ -51,26 +48,18 @@ func testTimeout(t *testing.T, conn *Conn, timeout time.Duration) { var cs ConnectionState - err := conn.agent.loop.Run(context.Background(), func(_ context.Context) { + require.NoError(t, conn.agent.loop.Run(context.Background(), func(_ context.Context) { cs = conn.agent.connectionState - }) - if err != nil { - // We should never get here. - panic(err) - } + })) if cs != ConnectionStateConnected { elapsed := time.Since(startedAt) - if elapsed+margin < timeout { - t.Fatalf("Connection timed out %f msec early", elapsed.Seconds()*1000) - } else { - t.Logf("Connection timed out in %f msec", elapsed.Seconds()*1000) + require.Less(t, timeout, elapsed+margin) - return - } + return } } - t.Fatalf("Connection failed to time out in time. (expected timeout: %v)", timeout) + t.Fatalf("Connection failed to time out in time. (expected timeout: %v)", timeout) //nolint } func TestTimeout(t *testing.T) { @@ -85,24 +74,14 @@ func TestTimeout(t *testing.T) { defer test.TimeOut(time.Second * 20).Stop() t.Run("WithoutDisconnectTimeout", func(t *testing.T) { - ca, cb := pipe(nil) - err := cb.Close() - if err != nil { - // We should never get here. - panic(err) - } - + ca, cb := pipe(t, nil) + require.NoError(t, cb.Close()) testTimeout(t, ca, defaultDisconnectedTimeout) }) t.Run("WithDisconnectTimeout", func(t *testing.T) { - ca, cb := pipeWithTimeout(5*time.Second, 3*time.Second) - err := cb.Close() - if err != nil { - // We should never get here. - panic(err) - } - + ca, cb := pipeWithTimeout(t, 5*time.Second, 3*time.Second) + require.NoError(t, cb.Close()) testTimeout(t, ca, 5*time.Second) }) } @@ -114,31 +93,19 @@ func TestReadClosed(t *testing.T) { // Limit runtime in case of deadlocks defer test.TimeOut(time.Second * 20).Stop() - ca, cb := pipe(nil) - - err := ca.Close() - if err != nil { - // We should never get here. - panic(err) - } - - err = cb.Close() - if err != nil { - // We should never get here. - panic(err) - } + ca, cb := pipe(t, nil) + require.NoError(t, ca.Close()) + require.NoError(t, cb.Close()) empty := make([]byte, 10) - _, err = ca.Read(empty) - if err == nil { - t.Fatalf("Reading from a closed channel should return an error") - } + _, err := ca.Read(empty) + require.Error(t, err) } func stressDuplex(t *testing.T) { t.Helper() - ca, cb := pipe(nil) + ca, cb := pipe(t, nil) defer func() { require.NoError(t, ca.Close()) @@ -153,58 +120,52 @@ func stressDuplex(t *testing.T) { require.NoError(t, test.StressDuplex(ca, cb, opt)) } -func check(err error) { - if err != nil { - panic(err) - } -} - -func gatherAndExchangeCandidates(aAgent, bAgent *Agent) { +func gatherAndExchangeCandidates(t *testing.T, aAgent, bAgent *Agent) { + t.Helper() var wg sync.WaitGroup wg.Add(2) - check(aAgent.OnCandidate(func(candidate Candidate) { + require.NoError(t, aAgent.OnCandidate(func(candidate Candidate) { if candidate == nil { wg.Done() } })) - check(aAgent.GatherCandidates()) + require.NoError(t, aAgent.GatherCandidates()) - check(bAgent.OnCandidate(func(candidate Candidate) { + require.NoError(t, bAgent.OnCandidate(func(candidate Candidate) { if candidate == nil { wg.Done() } })) - check(bAgent.GatherCandidates()) + require.NoError(t, bAgent.GatherCandidates()) wg.Wait() candidates, err := aAgent.GetLocalCandidates() - check(err) + require.NoError(t, err) for _, c := range candidates { if addr, parseErr := netip.ParseAddr(c.Address()); parseErr == nil { - if shouldFilterLocationTrackedIP(addr) { - panic(addr) - } + require.False(t, shouldFilterLocationTrackedIP(addr)) } candidateCopy, copyErr := c.copy() - check(copyErr) - check(bAgent.AddRemoteCandidate(candidateCopy)) + require.NoError(t, copyErr) + require.NoError(t, bAgent.AddRemoteCandidate(candidateCopy)) } candidates, err = bAgent.GetLocalCandidates() - check(err) + require.NoError(t, err) for _, c := range candidates { candidateCopy, copyErr := c.copy() - check(copyErr) - check(aAgent.AddRemoteCandidate(candidateCopy)) + require.NoError(t, copyErr) + require.NoError(t, aAgent.AddRemoteCandidate(candidateCopy)) } } -func connect(aAgent, bAgent *Agent) (*Conn, *Conn) { - gatherAndExchangeCandidates(aAgent, bAgent) +func connect(t *testing.T, aAgent, bAgent *Agent) (*Conn, *Conn) { + t.Helper() + gatherAndExchangeCandidates(t, aAgent, bAgent) accepted := make(chan struct{}) var aConn *Conn @@ -212,15 +173,15 @@ func connect(aAgent, bAgent *Agent) (*Conn, *Conn) { go func() { var acceptErr error bUfrag, bPwd, acceptErr := bAgent.GetLocalUserCredentials() - check(acceptErr) + require.NoError(t, acceptErr) aConn, acceptErr = aAgent.Accept(context.TODO(), bUfrag, bPwd) - check(acceptErr) + require.NoError(t, acceptErr) close(accepted) }() aUfrag, aPwd, err := aAgent.GetLocalUserCredentials() - check(err) + require.NoError(t, err) bConn, err := bAgent.Dial(context.TODO(), aUfrag, aPwd) - check(err) + require.NoError(t, err) // Ensure accepted <-accepted @@ -228,7 +189,8 @@ func connect(aAgent, bAgent *Agent) (*Conn, *Conn) { return aConn, bConn } -func pipe(defaultConfig *AgentConfig) (*Conn, *Conn) { +func pipe(t *testing.T, defaultConfig *AgentConfig) (*Conn, *Conn) { + t.Helper() var urls []*stun.URI aNotifier, aConnected := onConnected() @@ -243,15 +205,15 @@ func pipe(defaultConfig *AgentConfig) (*Conn, *Conn) { cfg.NetworkTypes = supportedNetworkTypes() aAgent, err := NewAgent(cfg) - check(err) - check(aAgent.OnConnectionStateChange(aNotifier)) + require.NoError(t, err) + require.NoError(t, aAgent.OnConnectionStateChange(aNotifier)) bAgent, err := NewAgent(cfg) - check(err) + require.NoError(t, err) - check(bAgent.OnConnectionStateChange(bNotifier)) + require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - aConn, bConn := connect(aAgent, bAgent) + aConn, bConn := connect(t, aAgent, bAgent) // Ensure pair selected // Note: this assumes ConnectionStateConnected is thrown after selecting the final pair @@ -261,7 +223,8 @@ func pipe(defaultConfig *AgentConfig) (*Conn, *Conn) { return aConn, bConn } -func pipeWithTimeout(disconnectTimeout time.Duration, iceKeepalive time.Duration) (*Conn, *Conn) { +func pipeWithTimeout(t *testing.T, disconnectTimeout time.Duration, iceKeepalive time.Duration) (*Conn, *Conn) { + t.Helper() var urls []*stun.URI aNotifier, aConnected := onConnected() @@ -275,14 +238,14 @@ func pipeWithTimeout(disconnectTimeout time.Duration, iceKeepalive time.Duration } aAgent, err := NewAgent(cfg) - check(err) - check(aAgent.OnConnectionStateChange(aNotifier)) + require.NoError(t, err) + require.NoError(t, aAgent.OnConnectionStateChange(aNotifier)) bAgent, err := NewAgent(cfg) - check(err) - check(bAgent.OnConnectionStateChange(bNotifier)) + require.NoError(t, err) + require.NoError(t, bAgent.OnConnectionStateChange(bNotifier)) - aConn, bConn := connect(aAgent, bAgent) + aConn, bConn := connect(t, aAgent, bAgent) // Ensure pair selected // Note: this assumes ConnectionStateConnected is thrown after selecting the final pair @@ -328,29 +291,22 @@ func TestConnStats(t *testing.T) { // Limit runtime in case of deadlocks defer test.TimeOut(time.Second * 20).Stop() - ca, cb := pipe(nil) - if _, err := ca.Write(make([]byte, 10)); err != nil { - t.Fatal("unexpected error trying to write") - } + ca, cb := pipe(t, nil) + _, err := ca.Write(make([]byte, 10)) + require.NoError(t, err) defer closePipe(t, ca, cb) var wg sync.WaitGroup wg.Add(1) go func() { buf := make([]byte, 10) - if _, err := cb.Read(buf); err != nil { - panic(errRead) - } + _, err := cb.Read(buf) + require.NoError(t, err) wg.Done() }() wg.Wait() - if ca.BytesSent() != 10 { - t.Fatal("bytes sent don't match") - } - - if cb.BytesReceived() != 10 { - t.Fatal("bytes received don't match") - } + require.Equal(t, uint64(10), ca.BytesSent()) + require.Equal(t, uint64(10), cb.BytesReceived()) } diff --git a/transport_vnet_test.go b/transport_vnet_test.go index 8eb2b6d..07e5940 100644 --- a/transport_vnet_test.go +++ b/transport_vnet_test.go @@ -53,7 +53,7 @@ func TestRemoteLocalAddr(t *testing.T) { }) t.Run("Remote/Local Pair Match between Agents", func(t *testing.T) { - ca, cb := pipeWithVNet(builtVnet, + ca, cb := pipeWithVNet(t, builtVnet, &agentTestConfig{ urls: []*stun.URI{stunServerURL}, }, diff --git a/udp_mux_multi_test.go b/udp_mux_multi_test.go index 0986fc1..4fc64de 100644 --- a/udp_mux_multi_test.go +++ b/udp_mux_multi_test.go @@ -103,7 +103,7 @@ func testMultiUDPMuxConnections(t *testing.T, udpMuxMulti *MultiUDPMuxDefault, u // Try talking with each PacketConn for _, pktConn := range pktConns { - remoteConn, err := net.DialUDP(network, nil, pktConn.LocalAddr().(*net.UDPAddr)) + remoteConn, err := net.DialUDP(network, nil, pktConn.LocalAddr().(*net.UDPAddr)) // nolint require.NoError(t, err, "error dialing test UDP connection") testMuxConnectionPair(t, pktConn, remoteConn, ufrag) } diff --git a/udp_mux_test.go b/udp_mux_test.go index 3a293ff..0aa7344 100644 --- a/udp_mux_test.go +++ b/udp_mux_test.go @@ -252,7 +252,7 @@ func verifyPacket(t *testing.T, b []byte, nextSeq uint32) { func TestUDPMux_Agent_Restart(t *testing.T) { oneSecond := time.Second - connA, connB := pipe(&AgentConfig{ + connA, connB := pipe(t, &AgentConfig{ DisconnectedTimeout: &oneSecond, FailedTimeout: &oneSecond, }) @@ -279,7 +279,7 @@ func TestUDPMux_Agent_Restart(t *testing.T) { require.NoError(t, connA.agent.SetRemoteCredentials(ufragB, pwdB)) require.NoError(t, connB.agent.SetRemoteCredentials(ufragA, pwdA)) - gatherAndExchangeCandidates(connA.agent, connB.agent) + gatherAndExchangeCandidates(t, connA.agent, connB.agent) // Wait until both have gone back to connected <-aConnected diff --git a/udp_mux_universal_test.go b/udp_mux_universal_test.go index 46f927a..1f648e6 100644 --- a/udp_mux_universal_test.go +++ b/udp_mux_universal_test.go @@ -51,7 +51,7 @@ func testMuxSrflxConnection(t *testing.T, udpMux *UniversalUDPMuxDefault, ufrag _ = pktConn.Close() }() - remoteConn, err := net.DialUDP(network, nil, &net.UDPAddr{ + remoteConn, err := net.DialUDP(network, nil, &net.UDPAddr{ // nolint Port: udpMux.LocalAddr().(*net.UDPAddr).Port, }) require.NoError(t, err, "error dialing test UDP connection") diff --git a/usecandidate_test.go b/usecandidate_test.go index c44409c..d50315a 100644 --- a/usecandidate_test.go +++ b/usecandidate_test.go @@ -7,21 +7,16 @@ import ( "testing" "github.com/pion/stun/v3" + "github.com/stretchr/testify/require" ) func TestUseCandidateAttr_AddTo(t *testing.T) { m := new(stun.Message) - if UseCandidate().IsSet(m) { - t.Error("should not be set") - } - if err := m.Build(stun.BindingRequest, UseCandidate()); err != nil { - t.Error(err) - } + require.False(t, UseCandidate().IsSet(m)) + require.NoError(t, m.Build(stun.BindingRequest, UseCandidate())) + m1 := new(stun.Message) - if _, err := m1.Write(m.Raw); err != nil { - t.Error(err) - } - if !UseCandidate().IsSet(m1) { - t.Error("should be set") - } + _, err := m1.Write(m.Raw) + require.NoError(t, err) + require.True(t, UseCandidate().IsSet(m1)) }