First, let me tell that I've seen other questions that are similar to this one, but I don't think any question really answers it in enough detail (How does one test net.Conn in unit tests in Golang? and How does one test net.Conn in unit tests in Golang?).
What I want to test is function that in some way responds to a TCP request.
In the simplest scenario:
func HandleMessage(c net.Conn) {
s, err := bufio.NewReader(c).ReadString('\n')
s = strings.Trim(s, "\n")
c.Write([]byte(s + " whatever"))
}
How would I unit test such a function, ideally using net.Pipe()
to not open actual connections. I've been trying things like this:
func TestHandleMessage(t *testing.T) {
server, client := net.Pipe()
go func(){
server.Write([]byte("test"))
server.Close()
}()
s, err := bufio.NewReader(c).ReadString('\n')
assert.Nil(t, err)
assert.Equal(t, "test whatever", s)
}
However I can't seem to understand where to put the HandleMessage(client)
(or HandleMessage(server)?
in the test to actually get the response I want. I can get it to the point that it either blocks and won't finish at all, or that it will return the exact same string that I wrote in the server.
Could someone help me out and point out where I'm making a mistake? Or maybe point in a correct direction when it comes to testing TCP functions.