Use httptest to serve wasm test files.

This picks a port automatically, so avoids any conflicts that might
arise from running the tests in parallel.
This commit is contained in:
Elliott Sales de Andrade
2020-12-22 17:56:53 -05:00
committed by Ron Evans
parent 5bae55d755
commit f3bdebe2a6
6 changed files with 40 additions and 34 deletions
+20 -29
View File
@@ -3,11 +3,11 @@ package wasm
import (
"context"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"regexp"
@@ -20,29 +20,6 @@ import (
"github.com/chromedp/chromedp"
)
var addr = flag.String("addr", ":8826", "Host:port to listen on for wasm test server")
var wasmTmpDir string // set in TestMain to a temp directory for build output
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(func() int {
var err error
wasmTmpDir, err = ioutil.TempDir("", "wasm_test")
if err != nil {
log.Fatalf("unable to create temp dir: %v", err)
}
defer os.RemoveAll(wasmTmpDir) // cleanup even on panic and before os.Exit
startServer(wasmTmpDir)
return m.Run()
}())
}
func run(cmdline string) error {
args := strings.Fields(cmdline)
return runargs(args...)
@@ -70,7 +47,12 @@ func chromectx(timeout time.Duration) (context.Context, context.CancelFunc) {
return ctx, cancel
}
func startServer(tmpDir string) {
func startServer(t *testing.T) (string, *httptest.Server, func()) {
// In Go 1.15, all this can be replaced by t.TempDir()
tmpDir, err := ioutil.TempDir("", "wasm_test")
if err != nil {
t.Fatalf("unable to create temp dir: %v", err)
}
fsh := http.FileServer(http.Dir(tmpDir))
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -140,11 +122,20 @@ if (wasmSupported) {
fsh.ServeHTTP(w, r)
})
log.Printf("Starting server at %q for dir: %s", *addr, tmpDir)
go func() {
log.Fatal(http.ListenAndServe(*addr, h))
}()
server := httptest.NewServer(h)
t.Logf("Started server at %q for dir: %s", server.URL, tmpDir)
// In Go 1.14+, this can be replaced by t.Cleanup()
cleanup := func() {
err := os.RemoveAll(tmpDir)
if err != nil {
t.Error(err)
}
server.Close()
}
return tmpDir, server, cleanup
}
// waitLog blocks until the log output equals the text provided (ignoring whitespace before and after)