In Go, a TCP connection (net.Conn) is a io.ReadWriteCloser. I'd like to test my network code by simulating a TCP connection. There are two requirements that I have:
- the data to be read is stored in a string
- whenever data is written, I'd like it to be stored in some kind of buffer which I can access later
Is there a data structure for this, or an easy way to make one?
EDIT: I've rolled this answer into a package which makes things a bit simpler - see here: https://github.com/jordwest/mock-conn
While Ivan's solution will work for simple cases, keep in mind that a real TCP connection is actually two buffers, or rather pipes. For example:
If you use a single buffer that the server both reads from and writes to, you could end up with the server talking to itself.
Here's a solution that allows you to pass a
MockConn
type as aReadWriteCloser
to the server. TheRead
,Write
andClose
functions simply proxy through to the functions on the server's end of the pipes.When mocking a 'server' connection, simply pass the MockConn in place of where you would use the
net.Conn
(this obviously implements theReadWriteCloser
interface only, you could easily add dummy methods forLocalAddr()
etc if you need to support the fullnet.Conn
interface)In your tests you can act as the client by reading and writing to the
ClientReader
andClientWriter
fields as needed:No idea if this existed when the question was asked, but you probably want
net.Pipe()
which provides you with two full duplexnet.Conn
instances which are linked to each otherWhy not using
bytes.Buffer
? It's anio.ReadWriter
and has aString
method to get the stored data. If you need to make it anio.ReadWriteCloser
, you could define you own type:and define a
Close
method: