gpt4 book ai didi

unit-testing - 在 go 中测试连接的正确方法

转载 作者:IT王子 更新时间:2023-10-29 01:14:24 24 4
gpt4 key购买 nike

我正在用测试覆盖项目,为此我需要虚拟 TCP 服务器,它可以接受连接、向其中写入/读取数据、关闭它等...我找到了 this关于堆栈溢出的问题,涵盖了模拟连接,但并未涵盖我实际需要测试的内容。

我的想法依赖于这个article作为起点,但是当我开始实现 channel 让服务器将一些数据写入新打开的连接时,我在写入 channel 时遇到了不可调试的死锁。

我要实现的是写一些数据到服务器的 channel ,比如sendingQueue chan *[]byte,所以后面对应[]byte 将被发送到新建立的连接。

在这些小研究中,我尝试在向 channel 发送数据之前/之后调试和打印消息,并尝试在程序的不同位置从 channel 发送/读取数据。

我发现了什么:

  1. 如果我使用

    直接在 handleConnection 中添加数据,我的想法就会成功
    go func() {
    f := []byte("test.")
    t.sendingQueue <- &f
    }()
  2. 如果我以任何形式将数据从 TestUtils_TestingTCPServer_WritesRequest 推送到 channel ,无论是使用 func (t *TCPServer) Put(data *[]byte),我的想法都行不通(错误错误) 或直接使用:

    go func(queue chan *[]byte, data *[]byte) {
    queue <- data
    }(t.sendingQueue, &payload)
  3. channel 是否缓冲并不重要。

所以,很明显,我调试代码的方式有问题(我没有深入研究 cli dlv,只使用 IDE 调试器),或者我完全怀念使用 go channels、goroutines 或 net 的方式.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")
}
}

最佳答案

在同事的帮助下阅读 article关于 init 的工作原理,我发现了一个问题。

它在 init 函数中,由于使用了 := 赋值,它正在重新创建额外的服务器。我还更新了代码以确保服务器在 net.Dialconn.Read 之前运行。

关于unit-testing - 在 go 中测试连接的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54145430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com