github.com/metacubex/quic-go@v0.44.1-0.20240520163451-20b689a59136/http3/datagram_test.go (about)

     1  package http3
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"time"
     7  
     8  	. "github.com/onsi/ginkgo/v2"
     9  	. "github.com/onsi/gomega"
    10  )
    11  
    12  var _ = Describe("Datagrams", func() {
    13  	It("receives a datagram", func() {
    14  		dg := newDatagrammer(nil)
    15  		dg.enqueue([]byte("foobar"))
    16  		data, err := dg.Receive(context.Background())
    17  		Expect(err).ToNot(HaveOccurred())
    18  		Expect(data).To(Equal([]byte("foobar")))
    19  	})
    20  
    21  	It("queues up to 32 datagrams", func() {
    22  		dg := newDatagrammer(nil)
    23  		for i := 0; i < streamDatagramQueueLen+1; i++ {
    24  			dg.enqueue([]byte{uint8(i)})
    25  		}
    26  		for i := 0; i < streamDatagramQueueLen; i++ {
    27  			data, err := dg.Receive(context.Background())
    28  			Expect(err).ToNot(HaveOccurred())
    29  			Expect(data[0]).To(BeEquivalentTo(i))
    30  		}
    31  		ctx, cancel := context.WithCancel(context.Background())
    32  		cancel()
    33  		_, err := dg.Receive(ctx)
    34  		Expect(err).To(MatchError(context.Canceled))
    35  	})
    36  
    37  	It("blocks until a new datagram is received", func() {
    38  		dg := newDatagrammer(nil)
    39  		done := make(chan struct{})
    40  		go func() {
    41  			defer GinkgoRecover()
    42  			defer close(done)
    43  			data, err := dg.Receive(context.Background())
    44  			Expect(err).ToNot(HaveOccurred())
    45  			Expect(data).To(Equal([]byte("foobar")))
    46  		}()
    47  
    48  		Consistently(done, 50*time.Millisecond).ShouldNot(BeClosed())
    49  		dg.enqueue([]byte("foobar"))
    50  		Eventually(done).Should(BeClosed())
    51  	})
    52  
    53  	It("drops datagrams when the stream's receive side is closed", func() {
    54  		dg := newDatagrammer(nil)
    55  		dg.enqueue([]byte("foo"))
    56  		testErr := errors.New("test error")
    57  		dg.SetReceiveError(testErr)
    58  		dg.enqueue([]byte("bar"))
    59  		data, err := dg.Receive(context.Background())
    60  		Expect(err).ToNot(HaveOccurred())
    61  		Expect(data).To(Equal([]byte("foo")))
    62  		_, err = dg.Receive(context.Background())
    63  		Expect(err).To(MatchError(testErr))
    64  	})
    65  
    66  	It("sends datagrams", func() {
    67  		var sent []byte
    68  		testErr := errors.New("test error")
    69  		dg := newDatagrammer(func(b []byte) error {
    70  			sent = b
    71  			return testErr
    72  		})
    73  		Expect(dg.Send([]byte("foobar"))).To(MatchError(testErr))
    74  		Expect(sent).To(Equal([]byte("foobar")))
    75  	})
    76  })