-
Notifications
You must be signed in to change notification settings - Fork 31
/
gcd_test.go
544 lines (464 loc) · 14.2 KB
/
gcd_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
package gcd
import (
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"runtime"
"testing"
"time"
"github.com/wirepair/gcd/gcdapi"
)
var (
debugger *Gcd
testListener net.Listener
testSkipNetworkIntercept bool
testPath string
testDir string
testPort string
testServerAddr string
)
func init() {
switch runtime.GOOS {
case "windows":
flag.StringVar(&testPath, "chrome", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "path to chrome")
flag.StringVar(&testDir, "dir", "C:\\temp\\gcd\\", "user directory")
case "darwin":
flag.StringVar(&testPath, "chrome", "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "path to chrome")
flag.StringVar(&testDir, "dir", "/tmp/gcd/", "user directory")
case "linux":
flag.StringVar(&testPath, "chrome", "/usr/bin/chromium-browser", "path to chrome")
flag.StringVar(&testDir, "dir", "/tmp/gcd/", "user directory")
}
flag.StringVar(&testPort, "port", "9222", "Debugger port")
// TODO: remove this once mainline chrome supports it.
flag.BoolVar(&testSkipNetworkIntercept, "intercept", true, "set to false to test network intercept, will fail if browser does not support yet.")
}
func TestMain(m *testing.M) {
flag.Parse()
testServer()
os.MkdirAll(testDir, 0755)
ret := m.Run()
testCleanUp()
os.Exit(ret)
}
func testCleanUp() {
testListener.Close()
os.RemoveAll(testDir)
}
func TestDeleteProfileOnExit(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("windows will hold on to the process handle too long")
}
debugger := NewChromeDebugger()
debugger.DeleteProfileOnExit()
profileDir := testRandomTempDir(t)
err := debugger.StartProcess(testPath, profileDir, testRandomPort(t))
if err != nil {
t.Fatalf("error starting chrome")
}
debugger.ExitProcess()
if stat, err := os.Stat(profileDir); err == nil {
t.Fatalf("error temporary profileDir still exists: %s\n", stat.Name())
}
}
func TestGetPages(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
targets, err := debugger.GetTargets()
if err != nil {
t.Fatalf("error getting targets: %s\n", err)
}
if len(targets) <= 0 {
t.Fatalf("invalid number of targets, got: %d\n", len(targets))
}
t.Logf("page: %s\n", targets[0].Target.Url)
}
func TestEnv(t *testing.T) {
var ok bool
debugger = NewChromeDebugger()
debugger.AddEnvironmentVars([]string{"hello=youze", "zoinks=scoob"})
debugger.StartProcess(testPath, testRandomTempDir(t), testRandomPort(t))
defer debugger.ExitProcess()
t.Logf("%#v\n", debugger.chromeCmd.Env)
for _, v := range debugger.chromeCmd.Env {
if v == "hello=youze" {
ok = true
}
}
if !ok {
t.Fatalf("error finding our environment vars in chrome process")
}
}
func TestProcessKilled(t *testing.T) {
testDefaultStartup(t)
doneCh := make(chan struct{})
shutdown := time.NewTimer(time.Second * 4)
timeout := time.NewTimer(time.Second * 10)
terminatedHandler := func(reason string) {
t.Logf("reason: %s\n", reason)
doneCh <- struct{}{}
}
debugger.SetTerminationHandler(terminatedHandler)
for {
select {
case <-doneCh:
goto DONE
case <-shutdown.C:
debugger.ExitProcess()
case <-timeout.C:
t.Fatalf("timed out waiting for termination")
}
}
DONE:
}
func TestTargetCrashed(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
doneCh := make(chan struct{})
go testTimeoutListener(t, doneCh, 5, "timed out waiting for crashed to be handled")
targetCrashedFn := func(targ *ChromeTarget, payload []byte) {
t.Logf("reason: %s\n", string(payload))
close(doneCh)
}
tab, err := debugger.NewTab()
if err != nil {
t.Fatalf("error creating new tab")
}
tab.Inspector.Enable()
tab.Subscribe("Inspector.targetCrashed", targetCrashedFn)
navParams := &gcdapi.PageNavigateParams{Url: "chrome://crash", TransitionType: "typed"}
tab.Page.NavigateWithParams(navParams)
<-doneCh
}
func TestEvents(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
console := target.Console
doneCh := make(chan struct{}, 1)
target.Subscribe("Console.messageAdded", func(target *ChromeTarget, v []byte) {
target.Unsubscribe("Console.messageAdded")
msg := &gcdapi.ConsoleMessageAddedEvent{}
err := json.Unmarshal(v, msg)
if err != nil {
t.Fatalf("error unmarshalling event data: %v\n", err)
}
t.Logf("METHOD: %s\n", msg.Method)
eventData := msg.Params.Message
t.Logf("Got event: %v\n", eventData)
close(doneCh)
})
_, err = console.Enable()
if err != nil {
t.Fatalf("error sending enable: %s\n", err)
}
navParams := &gcdapi.PageNavigateParams{Url: testServerAddr + "console_log.html", TransitionType: "typed"}
if _, _, _, err := target.Page.NavigateWithParams(navParams); err != nil {
t.Fatalf("error attempting to navigate: %s\n", err)
}
go testTimeoutListener(t, doneCh, 5, "console message")
<-doneCh
}
func TestEvaluate(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
doneCh := make(chan struct{}, 1)
target.Subscribe("Runtime.executionContextCreated", func(target *ChromeTarget, v []byte) {
//target.Unsubscribe("Console.messageAdded")
msg := &gcdapi.RuntimeExecutionContextCreatedEvent{}
err := json.Unmarshal(v, msg)
if err != nil {
t.Fatalf("error unmarshalling event data: %v\n", err)
}
if msg.Params.Context.Origin != testServerAddr[:len(testServerAddr)-1] {
return
}
scriptSource := "document.location.href"
objectGroup := "gcdtest"
awaitPromise := false
includeCommandLineAPI := true
contextId := msg.Params.Context.Id
silent := true
returnByValue := false
generatePreview := true
userGestures := true
evalParams := &gcdapi.RuntimeEvaluateParams{Expression: scriptSource, ObjectGroup: objectGroup, IncludeCommandLineAPI: includeCommandLineAPI, Silent: silent, ContextId: contextId, ReturnByValue: returnByValue, GeneratePreview: generatePreview, UserGesture: userGestures, AwaitPromise: awaitPromise}
rro, exception, err := target.Runtime.EvaluateWithParams(evalParams)
if err != nil {
t.Fatalf("error evaluating: %s %#v\n", err, exception)
}
if val, ok := rro.Value.(string); ok {
if val != testServerAddr {
t.Fatalf("invalid location returned expected %s got %s\n", testServerAddr, val)
}
} else {
t.Fatalf("error rro.Value was not a string")
}
close(doneCh)
})
target.Runtime.Enable()
navParams := &gcdapi.PageNavigateParams{Url: testServerAddr, TransitionType: "typed"}
target.Page.NavigateWithParams(navParams)
<-doneCh
}
func TestSimpleReturn(t *testing.T) {
var ret bool
testDefaultStartup(t)
defer debugger.ExitProcess()
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
network := target.Network
if _, err := network.Enable(-1, -1, -1); err != nil {
t.Fatalf("error enabling network")
}
ret, err = network.CanClearBrowserCache()
if err != nil {
t.Fatalf("error getting response to clearing browser cache: %s\n", err)
}
if !ret {
t.Fatalf("we should have got true for can clear browser cache\n")
}
}
func TestSimpleReturnWithParams(t *testing.T) {
var ret bool
testDefaultStartup(t)
defer debugger.ExitProcess()
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
network := target.Network
networkParams := &gcdapi.NetworkEnableParams{
MaxTotalBufferSize: -1,
MaxResourceBufferSize: -1,
}
if _, err := network.EnableWithParams(networkParams); err != nil {
t.Fatalf("error enabling network")
}
ret, err = network.CanClearBrowserCache()
if err != nil {
t.Fatalf("error getting response to clearing browser cache: %s\n", err)
}
if !ret {
t.Fatalf("we should have got true for can clear browser cache\n")
}
}
// tests getting a complex object back from inside a fired event that we subscribed to.
func TestComplexReturn(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
doneCh := make(chan struct{}, 1)
go testTimeoutListener(t, doneCh, 7, "waiting for page load to get cookies")
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
if _, err := target.Network.Enable(-1, -1, -1); err != nil {
t.Fatalf("error enabling network %s\n", err)
}
if _, err := target.Page.Enable(); err != nil {
t.Fatalf("error enabling page: %s\n", err)
}
target.Subscribe("Page.loadEventFired", func(target *ChromeTarget, payload []byte) {
var ok bool
t.Logf("page load event fired\n")
cookies, err := target.Network.GetCookies([]string{testServerAddr})
if err != nil {
t.Fatalf("error getting cookies!")
}
for _, v := range cookies {
t.Logf("got cookies: %#v\n", v)
if v.Name == "HEYA" {
ok = true
break
}
}
if !ok {
t.Fatalf("error finding our cookie value!")
}
close(doneCh)
})
navParams := &gcdapi.PageNavigateParams{Url: testServerAddr + "cookie.html", TransitionType: "typed"}
_, _, _, err = target.Page.NavigateWithParams(navParams)
if err != nil {
t.Fatalf("error navigating to cookie page: %s\n", err)
}
t.Logf("waiting for loadEventFired")
<-doneCh
}
func TestConnectToInstance(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
doneCh := make(chan struct{})
go testTimeoutListener(t, doneCh, 15, "timed out waiting for remote connection")
go func() {
remoteDebugger := NewChromeDebugger()
remoteDebugger.ConnectToInstance(debugger.host, debugger.port)
_, err := remoteDebugger.NewTab()
if err != nil {
t.Fatalf("error creating new tab")
}
targets, error := remoteDebugger.GetTargets()
if error != nil {
t.Fatalf("cannot get targets: %s \n", error)
}
if len(targets) <= 0 {
t.Fatalf("invalid number of targets, got: %d\n", len(targets))
}
for _, target := range targets {
t.Logf("page: %s\n", target.Target.Url)
}
close(doneCh)
}()
<-doneCh
}
func TestLocalExtension(t *testing.T) {
testExtensionStartup(t)
debugger.ConnectToInstance(debugger.host, debugger.port)
defer debugger.ExitProcess()
doneCh := make(chan struct{})
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error creating new tab")
}
if _, err := target.Page.Enable(); err != nil {
t.Fatalf("error enabling page: %s\n", err)
}
target.Subscribe("Page.loadEventFired", func(target *ChromeTarget, payload []byte) {
t.Logf("page load event fired\n")
close(doneCh)
})
if _, err := target.Network.Enable(-1, -1, -1); err != nil {
t.Fatalf("error enabling network: %s\n", err)
}
params := &gcdapi.PageNavigateParams{Url: "http://www.google.com"}
_, _, _, err = target.Page.NavigateWithParams(params)
if err != nil {
t.Fatalf("error navigating: %s\n", err)
}
go testTimeoutListener(t, doneCh, 15, "timed out waiting for remote connection")
<-doneCh
}
func TestNetworkIntercept(t *testing.T) {
if testSkipNetworkIntercept {
return
}
testDefaultStartup(t)
defer debugger.ExitProcess()
doneCh := make(chan struct{})
target, err := debugger.NewTab()
if err != nil {
t.Fatalf("error getting new tab: %s\n", err)
}
go testTimeoutListener(t, doneCh, 5, "timed out waiting for requestIntercepted")
network := target.Network
networkParams := &gcdapi.NetworkEnableParams{
MaxTotalBufferSize: -1,
MaxResourceBufferSize: -1,
}
if _, err := network.EnableWithParams(networkParams); err != nil {
t.Fatalf("error enabling network")
}
patterns := make([]*gcdapi.NetworkRequestPattern, 1)
patterns[0] = &gcdapi.NetworkRequestPattern{UrlPattern: "*", ResourceType: "Document"}
interceptParams := &gcdapi.NetworkSetRequestInterceptionParams{Patterns: patterns}
if _, err := network.SetRequestInterceptionWithParams(interceptParams); err != nil {
t.Fatalf("unable to set interception enabled: %s\n", err)
}
target.Subscribe("Network.requestIntercepted", func(target *ChromeTarget, payload []byte) {
fmt.Printf("requestIntercepted event fired %s\n", string(payload))
t.Logf("requestIntercepted event fired %s\n", string(payload))
close(doneCh)
})
params := &gcdapi.PageNavigateParams{Url: "http://www.example.com"}
_, _, _, err = target.Page.NavigateWithParams(params)
if err != nil {
t.Fatalf("error navigating: %s\n", err)
}
<-doneCh
}
func TestGetFirstTab(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
_, err := debugger.GetFirstTab()
if err != nil {
t.Fatalf("error getting first tab: %v\n", err)
}
}
func TestCloseTab(t *testing.T) {
testDefaultStartup(t)
defer debugger.ExitProcess()
target, err := debugger.GetFirstTab()
if err != nil {
t.Fatalf("error getting first tab: %v\n", err)
}
if err := debugger.CloseTab(target); err != nil {
t.Fatalf("error closing tab")
}
}
// UTILITY FUNCTIONS
func testExtensionStartup(t *testing.T) {
debugger = NewChromeDebugger()
sep := string(os.PathSeparator)
path, err := os.Getwd()
if err != nil {
t.Fatalf("error getting working directory: %s\n", err)
}
extensionPath := "--load-extension=" + path + sep + "testdata" + sep + "extension" + sep
debugger.AddFlags([]string{extensionPath})
debugger.StartProcess(testPath, testRandomTempDir(t), testRandomPort(t))
}
func testDefaultStartup(t *testing.T) {
debugger = NewChromeDebugger()
debugger.DeleteProfileOnExit()
debugger.AddFlags([]string{"--headless"})
debugger.StartProcess(testPath, testRandomTempDir(t), testRandomPort(t))
}
func testServer() {
testListener, _ = net.Listen("tcp", ":0")
_, testServerPort, _ := net.SplitHostPort(testListener.Addr().String())
testServerAddr = fmt.Sprintf("http://localhost:%s/", testServerPort)
go http.Serve(testListener, http.FileServer(http.Dir("testdata/")))
}
func testTimeoutListener(t *testing.T, closeCh chan struct{}, seconds time.Duration, message string) {
timeout := time.NewTimer(seconds * time.Second)
for {
select {
case <-closeCh:
timeout.Stop()
return
case <-timeout.C:
close(closeCh)
t.Fatalf("timed out waiting for %s", message)
return
}
}
}
func testRandomPort(t *testing.T) string {
l, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
_, randPort, _ := net.SplitHostPort(l.Addr().String())
l.Close()
return randPort
}
func testRandomTempDir(t *testing.T) string {
dir, err := ioutil.TempDir(testDir, "gcd")
if err != nil {
t.Errorf("error creating temp dir: %s\n", err)
}
return dir
}