Skip to content

Commit

Permalink
fix: improved listener coverage, also added dial function
Browse files Browse the repository at this point in the history
  • Loading branch information
shoriwe committed May 22, 2023
1 parent c3cd6db commit 70c2519
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 7 deletions.
18 changes: 12 additions & 6 deletions config/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,23 @@ type Listener struct {
}

func (l *Listener) Listen() (net.Listener, error) {
ls, lErr := net.Listen(l.Network, l.Address)
if lErr != nil {
return nil, lErr
if l.TLS == nil {
return net.Listen(l.Network, l.Address)
}
config, cErr := l.TLS.Config()
if cErr != nil {
return nil, cErr
}
return tls.Listen(l.Network, l.Address, config)
}

func (l *Listener) Dial() (net.Conn, error) {
if l.TLS == nil {
return ls, nil
return net.Dial(l.Network, l.Address)
}
config, cErr := l.TLS.Config()
if cErr != nil {
ls.Close()
return nil, cErr
}
return tls.NewListener(ls, config), nil
return tls.Dial(l.Network, l.Address, config)
}
68 changes: 67 additions & 1 deletion config/listener_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
)

func TestListener(t *testing.T) {
func TestListener_Listen(t *testing.T) {
t.Run("No TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Expand Down Expand Up @@ -48,3 +48,69 @@ func TestListener(t *testing.T) {
assert.NotNil(tt, lErr)
})
}

func TestListener_Dial(t *testing.T) {
t.Run("No TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:0",
}
l, lErr := c.Listen()
assert.Nil(tt, lErr)
defer l.Close()
doneCh := make(chan struct{}, 1)
msg := []byte("TEST")
go func() {
c2 := Listener{
Network: l.Addr().Network(),
Address: l.Addr().String(),
}
conn, cErr := c2.Dial()
assert.Nil(tt, cErr)
defer conn.Close()
_, wErr := conn.Write(msg)
assert.Nil(tt, wErr)
<-doneCh
}()
conn, aErr := l.Accept()
assert.Nil(tt, aErr)
buffer := make([]byte, len(msg))
_, rErr := conn.Read(buffer)
assert.Nil(tt, rErr)
assert.Equal(tt, msg, buffer)
doneCh <- struct{}{}
})
t.Run("With TLS", func(tt *testing.T) {
c := Listener{
Network: "tcp",
Address: "localhost:0",
TLS: &TLS{},
}
l, lErr := c.Listen()
assert.Nil(tt, lErr)
defer l.Close()
doneCh := make(chan struct{}, 1)
msg := []byte("TEST")
go func() {
c2 := Listener{
Network: l.Addr().Network(),
Address: l.Addr().String(),
TLS: &TLS{},
}
conn, cErr := c2.Dial()
assert.Nil(tt, cErr)
defer conn.Close()
_, wErr := conn.Write(msg)
assert.Nil(tt, wErr)
<-doneCh
}()
conn, aErr := l.Accept()
assert.Nil(tt, aErr)
buffer := make([]byte, len(msg))
_, rErr := conn.Read(buffer)
assert.Nil(tt, rErr)
assert.Equal(tt, msg, buffer)
doneCh <- struct{}{}
})

}

0 comments on commit 70c2519

Please sign in to comment.