github.com/pion/dtls/v2@v2.2.12/bench_test.go (about) 1 // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly> 2 // SPDX-License-Identifier: MIT 3 4 package dtls 5 6 import ( 7 "context" 8 "crypto/tls" 9 "fmt" 10 "testing" 11 "time" 12 13 "github.com/pion/dtls/v2/pkg/crypto/selfsign" 14 "github.com/pion/logging" 15 "github.com/pion/transport/v2/dpipe" 16 "github.com/pion/transport/v2/test" 17 ) 18 19 func TestSimpleReadWrite(t *testing.T) { 20 report := test.CheckRoutines(t) 21 defer report() 22 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 23 defer cancel() 24 25 ca, cb := dpipe.Pipe() 26 certificate, err := selfsign.GenerateSelfSigned() 27 if err != nil { 28 t.Fatal(err) 29 } 30 gotHello := make(chan struct{}) 31 32 go func() { 33 server, sErr := testServer(ctx, cb, &Config{ 34 Certificates: []tls.Certificate{certificate}, 35 LoggerFactory: logging.NewDefaultLoggerFactory(), 36 }, false) 37 if sErr != nil { 38 t.Error(sErr) 39 return 40 } 41 buf := make([]byte, 1024) 42 if _, sErr = server.Read(buf); sErr != nil { 43 t.Error(sErr) 44 } 45 gotHello <- struct{}{} 46 if sErr = server.Close(); sErr != nil { //nolint:contextcheck 47 t.Error(sErr) 48 } 49 }() 50 51 client, err := testClient(ctx, ca, &Config{ 52 LoggerFactory: logging.NewDefaultLoggerFactory(), 53 InsecureSkipVerify: true, 54 }, false) 55 if err != nil { 56 t.Fatal(err) 57 } 58 if _, err = client.Write([]byte("hello")); err != nil { 59 t.Error(err) 60 } 61 select { 62 case <-gotHello: 63 // OK 64 case <-time.After(time.Second * 5): 65 t.Error("timeout") 66 } 67 68 if err = client.Close(); err != nil { 69 t.Error(err) 70 } 71 } 72 73 func benchmarkConn(b *testing.B, n int64) { 74 b.Run(fmt.Sprintf("%d", n), func(b *testing.B) { 75 ctx := context.Background() 76 77 ca, cb := dpipe.Pipe() 78 certificate, err := selfsign.GenerateSelfSigned() 79 server := make(chan *Conn) 80 go func() { 81 s, sErr := testServer(ctx, cb, &Config{ 82 Certificates: []tls.Certificate{certificate}, 83 }, false) 84 if err != nil { 85 b.Error(sErr) 86 return 87 } 88 server <- s 89 }() 90 if err != nil { 91 b.Fatal(err) 92 } 93 hw := make([]byte, n) 94 b.ReportAllocs() 95 b.SetBytes(int64(len(hw))) 96 go func() { 97 client, cErr := testClient(ctx, ca, &Config{InsecureSkipVerify: true}, false) 98 if cErr != nil { 99 b.Error(err) 100 } 101 for { 102 if _, cErr = client.Write(hw); cErr != nil { //nolint:contextcheck 103 b.Error(err) 104 } 105 } 106 }() 107 s := <-server 108 buf := make([]byte, 2048) 109 for i := 0; i < b.N; i++ { 110 if _, err = s.Read(buf); err != nil { 111 b.Error(err) 112 } 113 } 114 }) 115 } 116 117 func BenchmarkConnReadWrite(b *testing.B) { 118 for _, n := range []int64{16, 128, 512, 1024, 2048} { 119 benchmarkConn(b, n) 120 } 121 }