117274bc5d
This vastly speeds up 'go test' on my laptop from ~10s to ~3s, as we save a lot of time spinning up new Chrome browser processes. In practice, each tab is a separate process anyway, but there's a lot of added overhead if we're firing up the entire browser, particularly with an empty user data dir. This makes 'go test' racy now, as Browser doesn't support creating tabs concurrently right now. Follow-up commits will fix that, with the help of 'go test -race' after this commit.
80 lines
1.9 KiB
Go
80 lines
1.9 KiB
Go
package chromedp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path"
|
|
"testing"
|
|
)
|
|
|
|
var (
|
|
testdataDir string
|
|
|
|
browserCtx context.Context
|
|
|
|
allocOpts = []ExecAllocatorOption{
|
|
NoFirstRun,
|
|
NoDefaultBrowserCheck,
|
|
Headless,
|
|
DisableGPU,
|
|
}
|
|
)
|
|
|
|
func testAllocate(t *testing.T, path string) (_ context.Context, cancel func()) {
|
|
// Same browser, new tab; not needing to start new chrome browsers for
|
|
// each test gives a huge speed-up.
|
|
ctx, cancel := NewContext(browserCtx)
|
|
|
|
// Only navigate if we want a path, otherwise leave the blank page.
|
|
if path != "" {
|
|
if err := Run(ctx, Navigate(testdataDir+"/"+path)); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
//if err := WithLogf(t.Logf)(c.c); err != nil {
|
|
// t.Fatalf("could not set logf: %v", err)
|
|
//}
|
|
//if err := WithDebugf(t.Logf)(c.c); err != nil {
|
|
// t.Fatalf("could not set debugf: %v", err)
|
|
//}
|
|
//if err := WithErrorf(t.Errorf)(c.c); err != nil {
|
|
// t.Fatalf("could not set errorf: %v", err)
|
|
//}
|
|
|
|
return ctx, cancel
|
|
}
|
|
|
|
func TestMain(m *testing.M) {
|
|
wd, err := os.Getwd()
|
|
if err != nil {
|
|
panic(fmt.Sprintf("could not get working directory: %v", err))
|
|
}
|
|
testdataDir = "file://" + path.Join(wd, "testdata")
|
|
|
|
// it's worth noting that newer versions of chrome (64+) run much faster
|
|
// than older ones -- same for headless_shell ...
|
|
if execPath := os.Getenv("CHROMEDP_TEST_RUNNER"); execPath != "" {
|
|
allocOpts = append(allocOpts, ExecPath(execPath))
|
|
}
|
|
// not explicitly needed to be set, as this vastly speeds up unit tests
|
|
if noSandbox := os.Getenv("CHROMEDP_NO_SANDBOX"); noSandbox != "false" {
|
|
allocOpts = append(allocOpts, NoSandbox)
|
|
}
|
|
|
|
allocCtx, cancel := NewAllocator(context.Background(), WithExecAllocator(allocOpts...))
|
|
|
|
// start the browser
|
|
browserCtx, _ = NewContext(allocCtx)
|
|
if err := Run(browserCtx, Tasks{}); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
code := m.Run()
|
|
|
|
cancel()
|
|
FromContext(allocCtx).Allocator.Wait()
|
|
os.Exit(code)
|
|
}
|