Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

github.com/gbbr/mocks

Package Overview
Dependencies
Alerts
File Explorer
Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

github.com/gbbr/mocks

  • v0.0.0-20141202184823-95d029e0de82
  • Source
  • Go
  • Socket score

Version published
Created
Source

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.

FAQs

Package last updated on 02 Dec 2014

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc