diff options
author | Felix Lange <fjl@twurst.com> | 2014-12-12 18:39:07 +0800 |
---|---|---|
committer | Felix Lange <fjl@twurst.com> | 2014-12-15 07:28:20 +0800 |
commit | 65e39bf20eecf7f3296fba531efb72ac28dc0124 (patch) | |
tree | 6a7f4116bcb1eea1a85176b1542366bccc80222b /p2p/message_test.go | |
parent | e28c60caf9a31669451124a9add2b9036bec1e73 (diff) | |
download | dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar.gz dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar.bz2 dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar.lz dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar.xz dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.tar.zst dexon-65e39bf20eecf7f3296fba531efb72ac28dc0124.zip |
p2p: add MsgPipe for protocol testing
Diffstat (limited to 'p2p/message_test.go')
-rw-r--r-- | p2p/message_test.go | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/p2p/message_test.go b/p2p/message_test.go index 7b39b061d..0fbcfeef0 100644 --- a/p2p/message_test.go +++ b/p2p/message_test.go @@ -2,8 +2,11 @@ package p2p import ( "bytes" + "fmt" "io/ioutil" + "runtime" "testing" + "time" "github.com/ethereum/go-ethereum/ethutil" ) @@ -68,3 +71,63 @@ func TestDecodeRealMsg(t *testing.T) { t.Errorf("incorrect code %d, want %d", msg.Code, 0) } } + +func ExampleMsgPipe() { + rw1, rw2 := MsgPipe() + go func() { + rw1.EncodeMsg(8, []byte{0, 0}) + rw1.EncodeMsg(5, []byte{1, 1}) + rw1.Close() + }() + + for { + msg, err := rw2.ReadMsg() + if err != nil { + break + } + var data [1][]byte + msg.Decode(&data) + fmt.Printf("msg: %d, %x\n", msg.Code, data[0]) + } + // Output: + // msg: 8, 0000 + // msg: 5, 0101 +} + +func TestMsgPipeUnblockWrite(t *testing.T) { +loop: + for i := 0; i < 100; i++ { + rw1, rw2 := MsgPipe() + done := make(chan struct{}) + go func() { + if err := rw1.EncodeMsg(1); err == nil { + t.Error("EncodeMsg returned nil error") + } else if err != ErrPipeClosed { + t.Error("EncodeMsg returned wrong error: got %v, want %v", err, ErrPipeClosed) + } + close(done) + }() + + // this call should ensure that EncodeMsg is waiting to + // deliver sometimes. if this isn't done, Close is likely to + // be executed before EncodeMsg starts and then we won't test + // all the cases. + runtime.Gosched() + + rw2.Close() + select { + case <-done: + case <-time.After(200 * time.Millisecond): + t.Errorf("write didn't unblock") + break loop + } + } +} + +// This test should panic if concurrent close isn't implemented correctly. +func TestMsgPipeConcurrentClose(t *testing.T) { + rw1, _ := MsgPipe() + for i := 0; i < 10; i++ { + go rw1.Close() + } +} |