fix(filtering): avoid the if err == nil pattern (#567)
1. in normal code is better to always do if err != nil so that the ifs only contain error code (this is ~coding policy) 2. in tests we want to ensure we narrow down the error to the real error that happened, to have greater confidence Written while working on https://github.com/ooni/probe/issues/1803#issuecomment-957323297
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package mocks
|
||||
|
||||
import "net"
|
||||
|
||||
// Listener allows mocking a net.Listener.
|
||||
type Listener struct {
|
||||
// Accept allows mocking Accept.
|
||||
MockAccept func() (net.Conn, error)
|
||||
|
||||
// Close allows mocking Close.
|
||||
MockClose func() error
|
||||
|
||||
// Addr allows mocking Addr.
|
||||
MockAddr func() net.Addr
|
||||
}
|
||||
|
||||
var _ net.Listener = &Listener{}
|
||||
|
||||
// Accept implements net.Listener.Accept
|
||||
func (li *Listener) Accept() (net.Conn, error) {
|
||||
return li.MockAccept()
|
||||
}
|
||||
|
||||
// Close implements net.Listener.Closer.
|
||||
func (li *Listener) Close() error {
|
||||
return li.MockClose()
|
||||
}
|
||||
|
||||
// Addr implements net.Listener.Addr
|
||||
func (li *Listener) Addr() net.Addr {
|
||||
return li.MockAddr()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
func TestListener(t *testing.T) {
|
||||
t.Run("Accept", func(t *testing.T) {
|
||||
expected := errors.New("mocked error")
|
||||
li := &Listener{
|
||||
MockAccept: func() (net.Conn, error) {
|
||||
return nil, expected
|
||||
},
|
||||
}
|
||||
conn, err := li.Accept()
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatal("unexpected err", err)
|
||||
}
|
||||
if conn != nil {
|
||||
t.Fatal("expected nil conn")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Close", func(t *testing.T) {
|
||||
expected := errors.New("mocked error")
|
||||
li := &Listener{
|
||||
MockClose: func() error {
|
||||
return expected
|
||||
},
|
||||
}
|
||||
err := li.Close()
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatal("unexpected err", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Addr", func(t *testing.T) {
|
||||
addr := &net.TCPAddr{
|
||||
IP: net.IPv4(127, 0, 0, 1),
|
||||
Port: 1234,
|
||||
}
|
||||
li := &Listener{
|
||||
MockAddr: func() net.Addr {
|
||||
return addr
|
||||
},
|
||||
}
|
||||
outAddr := li.Addr()
|
||||
if diff := cmp.Diff(addr, outAddr); diff != "" {
|
||||
t.Fatal(diff)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user