-
Notifications
You must be signed in to change notification settings - Fork 8
/
testing.go
43 lines (38 loc) · 1.02 KB
/
testing.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
* Copyright (C) 2020-2022 Arm Limited or its affiliates and Contributors. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package httptest
import (
"context"
"fmt"
"net"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/ARM-software/golang-utils/utils/parallelisation"
)
// NewTestServer creates a test server
func NewTestServer(t *testing.T, ctx context.Context, handler http.Handler, port string) {
list, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
require.Nil(t, err)
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: time.Minute,
ReadTimeout: time.Minute,
}
err = parallelisation.DetermineContextError(ctx)
if err != nil {
return
}
// Goroutine in charge of closing the server when requested.
go func(ctx context.Context, server *http.Server) {
<-ctx.Done()
_ = server.Close()
}(ctx, srv)
go func(server *http.Server, listen net.Listener) {
defer func() { _ = listen.Close() }()
err = srv.Serve(listen)
}(srv, list)
}