-
Notifications
You must be signed in to change notification settings - Fork 544
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ensure CloseAndExhaust never blocks forever.
- Loading branch information
1 parent
973d04f
commit 2635d15
Showing
2 changed files
with
99 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// SPDX-License-Identifier: AGPL-3.0-only | ||
|
||
package util | ||
|
||
import ( | ||
"errors" | ||
"io" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestCloseAndExhaust(t *testing.T) { | ||
t.Run("CloseSend returns an error", func(t *testing.T) { | ||
expectedErr := errors.New("something went wrong") | ||
stream := &mockStream{closeSendError: expectedErr} | ||
|
||
actualErr := CloseAndExhaust[string](stream) | ||
require.Equal(t, expectedErr, actualErr) | ||
}) | ||
|
||
t.Run("Recv returns error immediately", func(t *testing.T) { | ||
stream := &mockStream{recvErrors: []error{io.EOF}} | ||
err := CloseAndExhaust[string](stream) | ||
require.NoError(t, err, "CloseAndExhaust should ignore errors from Recv()") | ||
}) | ||
|
||
t.Run("Recv returns error after multiple calls", func(t *testing.T) { | ||
stream := &mockStream{recvErrors: []error{nil, nil, io.EOF}} | ||
err := CloseAndExhaust[string](stream) | ||
require.NoError(t, err, "CloseAndExhaust should ignore errors from Recv()") | ||
}) | ||
|
||
t.Run("Recv blocks forever", func(t *testing.T) { | ||
stream := &mockStream{} | ||
returned := make(chan error) | ||
|
||
go func() { | ||
returned <- CloseAndExhaust[string](stream) | ||
}() | ||
|
||
select { | ||
case err := <-returned: | ||
require.Equal(t, ErrCloseAndExhaustTimedOut, err) | ||
case <-time.After(5 * time.Second): | ||
require.FailNow(t, "expected CloseAndExhaust to time out waiting for Recv() to return, but it did not") | ||
} | ||
}) | ||
} | ||
|
||
type mockStream struct { | ||
closeSendError error | ||
recvErrors []error | ||
} | ||
|
||
func (m *mockStream) CloseSend() error { | ||
return m.closeSendError | ||
} | ||
|
||
func (m *mockStream) Recv() (string, error) { | ||
if len(m.recvErrors) == 0 { | ||
// Block forever. | ||
<-make(chan struct{}) | ||
} | ||
|
||
err := m.recvErrors[0] | ||
m.recvErrors = m.recvErrors[1:] | ||
|
||
return "", err | ||
} |