♻️ Improved TestServe util with custom TLS-certificates and timeout

This commit is contained in:
Maxim Lebedev 2021-10-05 00:44:12 +05:00
parent 5e2cda1817
commit 77004187d9
Signed by: toby3d
GPG Key ID: 1F14E25B7C119FC5

View File

@ -1,11 +1,13 @@
//go:generate go run "$GOROOT/src/crypto/tls/generate_cert.go" --host 127.0.0.1,::1,localhost --start-date "Jan 1 00:00:00 1970" --duration=1000000h --ca --rsa-bits 1024 --ecdsa-curve P256
package util package util
import ( import (
"crypto/tls"
"net" "net"
"path/filepath"
"testing" "testing"
"time"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
http "github.com/valyala/fasthttp" http "github.com/valyala/fasthttp"
httputil "github.com/valyala/fasthttp/fasthttputil" httputil "github.com/valyala/fasthttp/fasthttputil"
) )
@ -14,29 +16,29 @@ import (
func TestServe(tb testing.TB, handler http.RequestHandler) (*http.Client, *http.Server, func()) { func TestServe(tb testing.TB, handler http.RequestHandler) (*http.Client, *http.Server, func()) {
tb.Helper() tb.Helper()
ln := httputil.NewInmemoryListener()
server := &http.Server{ server := &http.Server{
Handler: handler,
DisableKeepalive: true,
CloseOnShutdown: true, CloseOnShutdown: true,
DisableKeepalive: true,
Handler: http.TimeoutHandler(handler, 1*time.Minute, "handler performance is too slow"),
ReduceMemoryUsage: true,
} }
go func() { ln := httputil.NewInmemoryListener()
assert.NoError(tb, server.Serve(ln))
}() //nolint: errcheck
go server.ServeTLS(ln, filepath.Join("..", "..", "..", "util", "cert.pem"),
filepath.Join("..", "..", "..", "util", "key.pem"))
client := &http.Client{ client := &http.Client{
Dial: func(_ string) (net.Conn, error) { TLSConfig: &tls.Config{
conn, err := ln.Dial() InsecureSkipVerify: true,
if err != nil { },
return nil, errors.Wrap(err, "cannot dial to address") Dial: func(addr string) (net.Conn, error) {
} return ln.Dial()
return conn, nil
}, },
} }
return client, server, func() { return client, server, func() {
assert.NoError(tb, server.Shutdown()) server.Shutdown() //nolint: errcheck
} }
} }