【发布时间】:2019-01-11 11:15:36
【问题描述】:
我正在用测试覆盖项目,为此我需要虚拟 TCP 服务器,它可以接受连接、向/从它写入/读取数据、关闭它等...我发现了 this 关于堆栈溢出的问题,涵盖了模拟连接,但没有涵盖我实际需要测试的内容。
我的想法依赖于article 作为起点,但是当我开始实现通道以让服务器将一些数据写入新打开的连接时,我在写入通道时遇到了不可调试的死锁。
我想要实现的是向服务器的通道写入一些数据,比如sendingQueue chan *[]byte,所以稍后将对应的[]byte发送到新建立的连接。
在这些小研究中,我尝试在向通道发送数据之前/之后调试和打印消息,并尝试在程序的不同位置从通道发送/读取数据。
我发现了什么:
-
如果我使用
直接在handleConnection中添加数据,我的想法会奏效go func() { f := []byte("test.") t.sendingQueue <- &f }() -
如果我以任何形式将数据从
TestUtils_TestingTCPServer_WritesRequest推送到频道,无论是使用func (t *TCPServer) Put(data *[]byte) (err error)还是直接使用:go func(queue chan *[]byte, data *[]byte) { queue <- data }(t.sendingQueue, &payload) - 通道是否被缓冲并不重要。
所以,很明显,我调试代码的方式有问题(我没有深入研究 cli dlv,只使用 IDE 调试器),或者我完全怀念使用 go 通道、goroutine 或网络的方式.Conn 模块。
为方便起见,public gist 提供完整代码。注意 — TestUtils_TestingTCPServer_WritesRequest 中有 // INIT 部分,这是运行/调试单个测试所必需的。在目录中运行go test 时应将其注释掉。
utils.go:
// NewServer creates a new Server using given protocol
// and addr.
func NewTestingTCPServer(protocol, addr string) (*TCPServer, error) {
switch strings.ToLower(protocol) {
case "tcp":
return &TCPServer{
addr: addr,
sendingQueue: make(chan *[]byte, 10),
}, nil
case "udp":
}
return nil, errors.New("invalid protocol given")
}
// TCPServer holds the structure of our TCP
// implementation.
type TCPServer struct {
addr string
server net.Listener
sendingQueue chan *[]byte
}
func (t *TCPServer) Run() (err error) {}
func (t *TCPServer) Close() (err error) {}
func (t *TCPServer) Put(data *[]byte) (err error) {}
func (t *TCPServer) handleConnection(conn net.Conn){
// <...>
// Putting data here successfully sends it via freshly established
// Connection:
// go func() {
// f := []byte("test.")
// t.sendingQueue <- &f
// }()
for {
fmt.Printf("Started for loop\n")
select {
case data := <-readerChannel:
fmt.Printf("Read written data\n")
writeBuffer.Write(*data)
writeBuffer.Flush()
case data := <-t.sendingQueue:
fmt.Printf("Read pushed data\n")
writeBuffer.Write(*data)
writeBuffer.Flush()
case <-ticker:
fmt.Printf("Tick\n")
return
}
fmt.Printf("Finished for loop\n")
}
}
utils_test.go
func TestUtils_TestingTCPServer_WritesRequest(t *testing.T) {
payload := []byte("hello world\n")
// <...> In gist here is placed INIT piece, which
// is required to debug single test
fmt.Printf("Putting payload into queue\n")
// This doesn't affect channel
err = utilTestingSrv.Put(&payload)
assert.Nil(t, err)
// This doesn't work either
//go func(queue chan *[]byte, data *[]byte) {
// queue <- data
//}(utilTestingSrv.sendingQueue, &payload)
conn, err := net.Dial("tcp", ":41123")
if !assert.Nil(t, err) {
t.Error("could not connect to server: ", err)
}
defer conn.Close()
out := make([]byte, 1024)
if _, err := conn.Read(out); assert.Nil(t, err) {
// Need to remove trailing byte 0xa from bytes array to make sure bytes array are equal.
if out[len(payload)] == 0xa {
out[len(payload)] = 0x0
}
assert.Equal(t, payload, bytes.Trim(out, "\x00"))
} else {
t.Error("could not read from connection")
}
}
【问题讨论】:
-
如果您使通道缓冲并且不在单独的 goroutine 中发送数据,您的 #2 解决方案应该可以工作。也应该可能连接到服务器之前你写数据。
-
我也这么认为,但事实并非如此。在 goroutine 中发送数据有什么问题?频道写入应该是 goroutine 安全的。
-
因为无法保证 goroutine 何时启动。没有数据竞赛,但有逻辑竞赛。
-
不幸的是,它没有帮助,感谢您的尝试。我测试了有/没有 goroutine 和有/没有额外功能 f.e.只是在
TestUtils_TestingTCPServer_WritesRequest中与客户端建立连接之前向通道发送数据。 -
您的 gist 代码在 TestUtils_TestingTCPServer_WritesRequest() 和 init() 中使用相同的端口调用 NewTestingTCPServer,这会导致某些东西无法正常工作。
标签: unit-testing go networking concurrency deadlock