| 1 | package tap |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "net" |
| 6 | "sync" |
| 7 | "testing" |
| 8 | |
| 9 | "github.com/containers/gvisor-tap-vsock/pkg/types" |
| 10 | "github.com/stretchr/testify/require" |
| 11 | ) |
| 12 | |
| 13 | |
| 14 | type readingConn struct { |
| 15 | net.Conn |
| 16 | reading chan struct{} |
| 17 | once sync.Once |
| 18 | } |
| 19 | |
| 20 | func (c *readingConn) Read(b []byte) (int, error) { |
| 21 | c.once.Do(func() { close(c.reading) }) |
| 22 | return c.Conn.Read(b) |
| 23 | } |
| 24 | |
| 25 | |
| 26 | |
| 27 | func TestAcceptEndedByContext(t *testing.T) { |
| 28 | for _, cancelled := range []bool{true, false} { |
| 29 | s := NewSwitch(false) |
| 30 | ours, theirs := net.Pipe() |
| 31 | conn := &readingConn{Conn: ours, reading: make(chan struct{})} |
| 32 | ctx, cancel := context.WithCancel(context.Background()) |
| 33 | done := make(chan error, 1) |
| 34 | go func() { done <- s.Accept(ctx, conn, types.VfkitProtocol) }() |
| 35 | <-conn.reading |
| 36 | if cancelled { |
| 37 | cancel() |
| 38 | } |
| 39 | theirs.Close() |
| 40 | err := <-done |
| 41 | cancel() |
| 42 | if cancelled { |
| 43 | require.NoError(t, err) |
| 44 | } else { |
| 45 | require.Error(t, err) |
| 46 | } |
| 47 | } |
| 48 | } |