@@ -18,10 +18,12 @@ package configconverter
18
18
import (
19
19
"context"
20
20
"io"
21
+ "net"
21
22
"net/http"
22
23
"os"
23
24
"strconv"
24
25
"testing"
26
+ "time"
25
27
26
28
"github.com/stretchr/testify/assert"
27
29
"github.com/stretchr/testify/require"
@@ -39,7 +41,9 @@ func TestConfigServer_RequireEnvVar(t *testing.T) {
39
41
cs := NewConfigServer ()
40
42
require .NotNil (t , cs )
41
43
cs .OnNew ()
42
- t .Cleanup (cs .OnShutdown )
44
+ t .Cleanup (func () {
45
+ shutdownAndWaitForPort (t , cs , defaultConfigServerPort )
46
+ })
43
47
require .NoError (t , cs .Convert (context .Background (), confmap .NewFromStringMap (initial )))
44
48
45
49
client := & http.Client {}
@@ -90,18 +94,16 @@ func TestConfigServer_EnvVar(t *testing.T) {
90
94
}()
91
95
}
92
96
97
+ actualServerPort := defaultConfigServerPort
98
+ if tt .portEnvVar != "" {
99
+ actualServerPort = tt .portEnvVar
100
+ }
93
101
cs := NewConfigServer ()
94
102
require .NotNil (t , cs )
95
103
cs .OnNew ()
96
104
97
105
require .NoError (t , cs .Convert (context .Background (), confmap .NewFromStringMap (initial )))
98
- defer func () {
99
- cs .OnShutdown () // Call shutdown even if the server is not up.
100
- if ! tt .serverDown {
101
- // Wait for the server to shutdown. Otherwise the port might be still in use.
102
- <- cs .doneCh
103
- }
104
- }()
106
+ defer shutdownAndWaitForPort (t , cs , actualServerPort )
105
107
106
108
endpoint := tt .endpoint
107
109
if endpoint == "" {
@@ -154,7 +156,9 @@ func TestConfigServer_Serve(t *testing.T) {
154
156
cs := NewConfigServer ()
155
157
require .NotNil (t , cs )
156
158
cs .OnNew ()
157
- t .Cleanup (cs .OnShutdown )
159
+ t .Cleanup (func () {
160
+ shutdownAndWaitForPort (t , cs , defaultConfigServerPort )
161
+ })
158
162
159
163
cs .OnRetrieve ("scheme" , initial )
160
164
require .NoError (t , cs .Convert (context .Background (), confmap .NewFromStringMap (initial )))
@@ -225,3 +229,15 @@ func TestSimpleRedact(t *testing.T) {
225
229
"X-SF-Token" : "<redacted>" ,
226
230
}, result )
227
231
}
232
+
233
+ func shutdownAndWaitForPort (t * testing.T , cs * ConfigServer , port string ) {
234
+ cs .OnShutdown ()
235
+ require .Eventually (t , func () bool {
236
+ ln , err := net .Listen ("tcp" , "localhost:" + port )
237
+ if err == nil {
238
+ ln .Close ()
239
+ return true
240
+ }
241
+ return false
242
+ }, 5 * time .Second , 200 * time .Millisecond )
243
+ }
0 commit comments