如何创建两个连接的 io.ReadWriteClosers 用于测试目的

问题描述 投票:0回答:1

我正在尝试在我的网络应用程序上运行一些测试。我想避免为每个测试创建一个套接字,所以我想我应该使用标准库中的 io.Pipe 。然而它只提供了 io.PipeReader, io.PipeWriter 对。我需要两个连接的 io.ReadWriteClosers

func TestEndpoints() {
    // Create pipeEndpoint1 and pipeEndpoint2. Both should implement  
    // io.ReadWriteCloser

    e1 := makeEndpoint(pipeEndpoint1)
    e2 := makeEndpoint(pipeEndpoint2)

    // Run some test
}
 
func makeEndpoint(rwc io.ReadWriteCloser) *Endpoint {
    // 
}

有没有办法创建两个连接的 io.ReadWriteClosers?

go testing
1个回答
0
投票

标准库中似乎没有办法做到这一点,所以这就是我所做的:

type PipeBidirectional struct {
    r *io.PipeReader
    w *io.PipeWriter
}

func NewPipes() (*PipeBidirectional, *PipeBidirectional) {
    r1, w1 := io.Pipe()
    r2, w2 := io.Pipe()

    return &PipeBidirectional{r1, w2}, &PipeBidirectional{r2, w1}
}

func (p *PipeBidirectional) Read(b []byte) (int, error) {
    return p.r.Read(b)
}

func (p *PipeBidirectional) Write(b []byte) (int, error) {
    return p.w.Write(b)
}

func (p *PipeBidirectional) Close() error {
    e1 := p.r.Close()
    e2 := p.w.Close()
    if e1 != nil || e2 != nil {
        return fmt.Errorf("e1: %w e2: %w", e1, e2)
    }
    return nil
}
© www.soinside.com 2019 - 2024. All rights reserved.