Refactor network to a top-level module

This commit is contained in:
9seconds
2021-03-14 21:43:30 +03:00
parent 37a78bd1c3
commit f8ad90c845
25 changed files with 231 additions and 192 deletions
+42
View File
@@ -0,0 +1,42 @@
package testlib
import (
"bytes"
"io"
"os"
"strings"
)
func CaptureStdout(callback func()) string {
return captureOutput(&os.Stdout, callback)
}
func CaptureStderr(callback func()) string {
return captureOutput(&os.Stderr, callback)
}
func captureOutput(filefp **os.File, callback func()) string {
oldFp := *filefp
defer func() {
*filefp = oldFp
}()
reader, writer, _ := os.Pipe()
buf := &bytes.Buffer{}
closeChan := make(chan bool)
go func() {
io.Copy(buf, reader) // nolint: errcheck
close(closeChan)
}()
*filefp = writer
callback()
writer.Close()
<-closeChan
return strings.TrimSpace(buf.String())
}
+48
View File
@@ -0,0 +1,48 @@
package testlib
import (
"net"
"time"
"github.com/stretchr/testify/mock"
)
type NetConnMock struct {
mock.Mock
}
func (n *NetConnMock) Read(b []byte) (int, error) {
args := n.Called(b)
return args.Int(0), args.Error(1)
}
func (n *NetConnMock) Write(b []byte) (int, error) {
args := n.Called(b)
return args.Int(0), args.Error(1)
}
func (n *NetConnMock) Close() error {
return n.Called().Error(0)
}
func (n *NetConnMock) LocalAddr() net.Addr {
return n.Called().Get(0).(net.Addr)
}
func (n *NetConnMock) RemoteAddr() net.Addr {
return n.Called().Get(0).(net.Addr)
}
func (n *NetConnMock) SetDeadline(t time.Time) error {
return n.Called(t).Error(0)
}
func (n *NetConnMock) SetReadDeadline(t time.Time) error {
return n.Called(t).Error(0)
}
func (n *NetConnMock) SetWriteDeadline(t time.Time) error {
return n.Called(t).Error(0)
}
+35
View File
@@ -0,0 +1,35 @@
package testlib
import (
"context"
"net"
"net/http"
"time"
"github.com/stretchr/testify/mock"
)
type NetworkMock struct {
mock.Mock
}
func (n *NetworkMock) Dial(network, address string) (net.Conn, error) {
args := n.Called(network, address)
return args.Get(0).(net.Conn), args.Error(1)
}
func (n *NetworkMock) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
args := n.Called(ctx, network, address)
return args.Get(0).(net.Conn), args.Error(1)
}
func (n *NetworkMock) MakeHTTPClient(dialFunc func(ctx context.Context,
network, address string) (net.Conn, error)) *http.Client {
return n.Called(dialFunc).Get(0).(*http.Client)
}
func (n *NetworkMock) IdleTimeout() time.Duration {
return n.Called().Get(0).(time.Duration)
}