tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/duplex/mux/proxy_test.go (about) 1 package mux 2 3 import ( 4 "context" 5 "errors" 6 "io" 7 "io/ioutil" 8 "net" 9 "syscall" 10 "testing" 11 ) 12 13 func setupProxy(t *testing.T) (func(), chan error, Session, Session) { 14 la, err := net.Listen("tcp", "127.0.0.1:0") 15 fatal(err, t) 16 lb, err := net.Listen("tcp", "127.0.0.1:0") 17 fatal(err, t) 18 cleanup := func() { 19 la.Close() 20 lb.Close() 21 } 22 23 proxyErr := make(chan error, 1) 24 go func() { 25 a, err := la.Accept() 26 fatal(err, t) 27 defer a.Close() 28 29 b, err := lb.Accept() 30 fatal(err, t) 31 defer b.Close() 32 33 proxyErr <- Proxy(New(b), New(a)) 34 }() 35 36 cb, err := net.Dial("tcp", lb.Addr().String()) 37 fatal(err, t) 38 39 ca, err := net.Dial("tcp", la.Addr().String()) 40 fatal(err, t) 41 42 return cleanup, proxyErr, New(ca), New(cb) 43 } 44 45 func TestProxyDuplex(t *testing.T) { 46 cleanup, _, sessA, sessB := setupProxy(t) 47 defer cleanup() 48 49 ctx := context.Background() 50 chA, err := sessA.Open(ctx) 51 fatal(err, t) 52 53 chB, err := sessB.Accept() 54 fatal(err, t) 55 56 msgA := "A -> a <-> b -> B" 57 msgB := "B -> b <-> a -> A" 58 _, err = io.WriteString(chA, msgA) 59 fatal(err, t) 60 fatal(chA.CloseWrite(), t) 61 62 _, err = io.WriteString(chB, msgB) 63 fatal(err, t) 64 fatal(chB.CloseWrite(), t) 65 66 gotA, err := ioutil.ReadAll(chA) 67 fatal(err, t) 68 gotB, err := ioutil.ReadAll(chB) 69 fatal(err, t) 70 71 if string(gotA) != msgB { 72 t.Fatalf("unexpected bytes read from chA: %#v", gotA) 73 } 74 75 if string(gotB) != msgA { 76 t.Fatalf("unexpected bytes read from chB: %#v", gotB) 77 } 78 } 79 80 func TestProxyCloseDst(t *testing.T) { 81 cleanup, proxyErr, sessA, sessB := setupProxy(t) 82 defer cleanup() 83 84 fatal(sessB.Close(), t) 85 86 ctx := context.Background() 87 chA, err := sessA.Open(ctx) 88 fatal(err, t) 89 90 _, err = io.WriteString(chA, "hello") 91 if err != nil && 92 !errors.Is(err, net.ErrClosed) && 93 !errors.Is(err, io.EOF) && 94 !errors.Is(err, syscall.EPIPE) { //&& 95 //!errors.Is(err, syscall.ECONNRESET) { 96 t.Fatal("unexpected channel error:", err) 97 } 98 99 err = <-proxyErr 100 if !errors.Is(err, net.ErrClosed) { 101 t.Fatal("unexpected proxy error:", err) 102 } 103 }