github.com/gdamore/mangos@v1.4.0/test/simple_test.go (about) 1 // Copyright 2018 The Mangos Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use file except in compliance with the License. 5 // You may obtain a copy of the license at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package test 16 17 import ( 18 "fmt" 19 "math/rand" 20 "sync" 21 "testing" 22 23 "nanomsg.org/go-mangos" 24 "nanomsg.org/go-mangos/protocol/pair" 25 "nanomsg.org/go-mangos/transport/tcp" 26 27 . "github.com/smartystreets/goconvey/convey" 28 ) 29 30 // This test case just tests that the simple Send/Recv (suboptimal) interfaces 31 // work as advertised. This covers verification that was reported in GitHub 32 // issue 139: Race condition in simple Send()/Recv() code 33 34 func TestSimpleCorrect(t *testing.T) { 35 36 Convey("We can use the simple Send/Recv API", t, func() { 37 tx, e := pair.NewSocket() 38 So(e, ShouldBeNil) 39 So(tx, ShouldNotBeNil) 40 41 rx, e := pair.NewSocket() 42 So(e, ShouldBeNil) 43 So(rx, ShouldNotBeNil) 44 45 tx.AddTransport(tcp.NewTransport()) 46 rx.AddTransport(tcp.NewTransport()) 47 48 Convey("When a simple TCP pair is created", func() { 49 e = rx.Listen(AddrTestTCP) 50 So(e, ShouldBeNil) 51 52 e = tx.Dial(AddrTestTCP) 53 So(e, ShouldBeNil) 54 55 iter := 100000 56 Convey(fmt.Sprintf("We can send/recv %d msgs async", iter), func() { 57 wg := &sync.WaitGroup{} 58 wg.Add(2) 59 goodtx := true 60 goodrx := true 61 go simpleSend(tx, wg, iter, &goodtx) 62 go simpleRecv(rx, wg, iter, &goodrx) 63 wg.Wait() 64 So(goodtx, ShouldBeTrue) 65 So(goodrx, ShouldBeTrue) 66 e = tx.Close() 67 So(e, ShouldBeNil) 68 e = rx.Close() 69 So(e, ShouldBeNil) 70 }) 71 }) 72 }) 73 } 74 75 func simpleSend(tx mangos.Socket, wg *sync.WaitGroup, iter int, pass *bool) { 76 defer wg.Done() 77 var buf [256]byte 78 good := true 79 for i := 0; i < iter; i++ { 80 l := rand.Intn(255) + 1 81 buf[0] = uint8(l) 82 if e := tx.Send(buf[:l]); e != nil { 83 good = false 84 break 85 } 86 } 87 *pass = good 88 } 89 90 func simpleRecv(rx mangos.Socket, wg *sync.WaitGroup, iter int, pass *bool) { 91 defer wg.Done() 92 good := true 93 for i := 0; i < iter; i++ { 94 buf, e := rx.Recv() 95 if buf == nil || e != nil || len(buf) < 1 || len(buf) != int(buf[0]) { 96 good = false 97 break 98 } 99 } 100 *pass = good 101 }