Mocks Save

Tiny collection of mocks for faking a network connection in Go

Project README

Mocks

Mocks is a small package that helps with testing network applications.

Mocking a network connection

To mock the net.Conn interface, import github.com/gbbr/mocks into your package and use a configured Conn structure, such as:

var mockConn net.Conn

mockConn = &mocks.Conn{
	// Local address
	LAddr: "127.0.0.1:888",
	LNet:  "tcp",

	// Remote address
	RAddr: "10.18.20.21:123",
	RNet: "udp",
}

fmt.Println(mockConn.LocalAddr().String()) // prints "127.0.0.1:888"
fmt.Println(mockConn.RemoteAddr().String()) // prints "10.18.20.21:123"

The view data that was sent to the mock connection, configure the In io.Writer interface of mocks.Conn, like:

var buf bytes.Buffer
mockConn.In = &buf
fmt.Fprintf(mockConn, "Message")

fmt.Println(buf.String()) // prints "Message"

To set a data source for the network connection the Out io.Reader may be used as follows:

mockConn.Out = bytes.NewBuffer([]byte("Test\n"))

var msg string
fmt.Scanln(mockConn, &msg)

fmt.Println(msg) // outputs "Test"

Obtaining a full communication channel

Pipe returns a full duplex network connection that receives data on either end and outputs it on the other one.

c1, c2 := Pipe(
	&Conn{RAddr: "1.1.1.1:123"},
	&Conn{LAddr: "127.0.0.1:12", RAddr: "2.2.2.2:456"},
)

// Go routine writes to connection 1
go c1.Write([]byte("Hello"))

// Read 5 bytes
b := make([]byte, 5)

// Connection 2 receives message
n, err := c2.Read(b)
if err != nil {
	t.Errorf("Could not read c2: %s", err)
}

fmt.Println(string(b)) // outputs "Hello"

Refer to the tests for a complete example.

Considerations

If you do not wish to to create the above examples (ie. you do not need to fake the remote/local address), you may also consider using the pipe provided in the net package, which returns two ends of a network stream. Careful though, when using net.Pipe() and requesting LocalAddr() or RemoteAddr() nil pointer panic will happen.

Open Source Agenda is not affiliated with "Mocks" Project. README Source: gbbr/mocks
Stars
44
Open Issues
0
Last Commit
9 years ago
Repository

Open Source Agenda Badge

Open Source Agenda Rating