Improve protocol tests, close handling

This commit is contained in:
Jakob Borg 2016-01-12 09:19:44 +01:00
parent 7427b9de35
commit 9595687bce
3 changed files with 25 additions and 21 deletions

View File

@ -8,20 +8,21 @@ import (
)
type TestModel struct {
data []byte
folder string
name string
offset int64
size int
hash []byte
flags uint32
options []Option
closedCh chan bool
data []byte
folder string
name string
offset int64
size int
hash []byte
flags uint32
options []Option
closedCh chan struct{}
closedErr error
}
func newTestModel() *TestModel {
return &TestModel{
closedCh: make(chan bool),
closedCh: make(chan struct{}),
}
}
@ -44,18 +45,19 @@ func (t *TestModel) Request(deviceID DeviceID, folder, name string, offset int64
}
func (t *TestModel) Close(deviceID DeviceID, err error) {
t.closedErr = err
close(t.closedCh)
}
func (t *TestModel) ClusterConfig(deviceID DeviceID, config ClusterConfigMessage) {
}
func (t *TestModel) isClosed() bool {
func (t *TestModel) closedError() error {
select {
case <-t.closedCh:
return true
return t.closedErr
case <-time.After(1 * time.Second):
return false // Timeout
return nil // Timeout
}
}

View File

@ -691,6 +691,7 @@ func (c *rawConnection) writerLoop() {
func (c *rawConnection) close(err error) {
c.once.Do(func() {
l.Debugln("close due to", err)
close(c.closed)
c.awaitingMut.Lock()

View File

@ -6,6 +6,7 @@ import (
"bytes"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
@ -107,14 +108,14 @@ func TestVersionErr(t *testing.T) {
w := xdr.NewWriter(c0.cw)
w.WriteUint32(encodeHeader(header{
version: 2,
version: 2, // higher than supported
msgID: 0,
msgType: 0,
msgType: messageTypeIndex,
}))
w.WriteUint32(0) // Avoids reader closing due to EOF
if !m1.isClosed() {
t.Error("Connection should close due to unknown version")
if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown protocol version") {
t.Error("Connection should close due to unknown version, not", err)
}
}
@ -140,8 +141,8 @@ func TestTypeErr(t *testing.T) {
}))
w.WriteUint32(0) // Avoids reader closing due to EOF
if !m1.isClosed() {
t.Error("Connection should close due to unknown message type")
if err := m1.closedError(); err == nil || !strings.Contains(err.Error(), "unknown message type") {
t.Error("Connection should close due to unknown message type, not", err)
}
}
@ -159,10 +160,10 @@ func TestClose(t *testing.T) {
c0.ClusterConfig(ClusterConfigMessage{})
c1.ClusterConfig(ClusterConfigMessage{})
c0.close(nil)
c0.close(errors.New("manual close"))
<-c0.closed
if !m0.isClosed() {
if err := m0.closedError(); err == nil || !strings.Contains(err.Error(), "manual close") {
t.Fatal("Connection should be closed")
}