mercredi 26 août 2020

How to defer a test server closure when doing parallel table test cases?

I’m having a trouble deferring the closure of a test http server when doing parallel table test funcs. I’m trying waiting using a sync.WaitGroup but the wg.Done() is either closing too early, or never happening.

ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    _, _ = w.Write([]byte(`hello`))
}))
defer ts.Close()

var wg sync.WaitGroup
for _, tc := range testCases {
    wg.Add(1)
    func(tc testCase) {
        // `Done` here doesn't wait for the test to run, so closes the test server early
        // defer wg.Done()
        t.Run(tc.name, func(t *testing.T) {
            // `Done` here is never called, so causes a timeout
            // defer wg.Done()
            t.Parallel()
            _, err := http.Get(ts.URL)
            if err != nil {
                t.Fatal(err.Error())
            }
        })
    }(tc)
}
wg.Wait()

For runnable example please see https://play.golang.org/p/1GvWRwlrsjA

Aucun commentaire:

Enregistrer un commentaire