tests: Run select statement in separate goroutine (#4499)

Instead of after the wg.Wait() so as to make sure that the 'earliest'
of the two select case that becomes active is selected..
This commit is contained in:
Frank Wessels 2017-06-08 07:39:50 -07:00 committed by Harshavardhana
parent 45a568dd85
commit 145328ac9f

View File

@ -309,34 +309,36 @@ func TestServerListenAndServePlain(t *testing.T) {
// ListenAndServe in a goroutine, but we don't know when it's ready // ListenAndServe in a goroutine, but we don't know when it's ready
go func() { errc <- m.ListenAndServe("", "") }() go func() { errc <- m.ListenAndServe("", "") }()
wg := &sync.WaitGroup{}
wg.Add(1)
// Keep trying the server until it's accepting connections // Keep trying the server until it's accepting connections
go func() { go func() {
client := http.Client{Timeout: time.Millisecond * 10} client := http.Client{Timeout: time.Millisecond * 10}
ok := false for {
for !ok {
res, _ := client.Get("http://" + addr) res, _ := client.Get("http://" + addr)
if res != nil && res.StatusCode == http.StatusOK { if res != nil && res.StatusCode == http.StatusOK {
ok = true break
} }
} }
wg.Done()
}() }()
wg.Wait() wg := &sync.WaitGroup{}
wg.Add(1)
// Block until we get an error or wait closed go func() {
defer wg.Done()
select { select {
case err := <-errc: case err := <-errc:
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
case <-wait: case <-wait:
m.Close() // Shutdown the ServerMux
return return
} }
}()
// Wait until we get an error or wait closed
wg.Wait()
// Shutdown the ServerMux
m.Close()
} }
func TestServerListenAndServeTLS(t *testing.T) { func TestServerListenAndServeTLS(t *testing.T) {
@ -389,12 +391,11 @@ func TestServerListenAndServeTLS(t *testing.T) {
Timeout: time.Millisecond * 10, Timeout: time.Millisecond * 10,
Transport: tr, Transport: tr,
} }
okTLS := false
// Keep trying the server until it's accepting connections // Keep trying the server until it's accepting connections
for !okTLS { for {
res, _ := client.Get("https://" + addr) res, _ := client.Get("https://" + addr)
if res != nil && res.StatusCode == http.StatusOK { if res != nil && res.StatusCode == http.StatusOK {
okTLS = true break
} }
} }
@ -423,9 +424,9 @@ func TestServerListenAndServeTLS(t *testing.T) {
wg.Done() wg.Done()
}() }()
wg.Wait() wg.Add(1)
go func() {
// Block until we get an error or wait closed defer wg.Done()
select { select {
case err := <-errc: case err := <-errc:
if err != nil { if err != nil {
@ -433,9 +434,15 @@ func TestServerListenAndServeTLS(t *testing.T) {
return return
} }
case <-wait: case <-wait:
m.Close() // Shutdown the ServerMux
return return
} }
}()
// Wait until we get an error or wait closed
wg.Wait()
// Shutdown the ServerMux
m.Close()
} }
// generateTestCert creates a cert and a key used for testing only // generateTestCert creates a cert and a key used for testing only