diff --git a/.travis.entrypoint.sh b/.travis.entrypoint.sh deleted file mode 100755 index 21d6276..0000000 --- a/.travis.entrypoint.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/sh -set -e -echo "" > coverage.txt - -# the alpine image doesn't come with git -apk update && apk add git - -go get -v github.com/golang/lint/golint -[ "0" = "$?" ] || exit 1 - -go get -u github.com/golang/dep/cmd/dep -[ "0" = "$?" ] || exit 2 - -cd /go/src/github.com/mkenney/go-chrome -[ "0" = "$?" ] || exit 3 - -dep ensure -[ "0" = "$?" ] || exit 4 - -for dir in $(go list ./... | grep -v vendor); do - go test -timeout 30s -coverprofile=profile.out $dir - exit_code=$? - if [ "0" != "$exit_code" ]; then - exit $exit_code - fi - if [ -f profile.out ]; then - cat profile.out >> coverage.txt - rm profile.out - fi -done - -exit_code=0 -for dir in $(go list ./... | grep -v vendor); do - echo "golint $dir" - result=$(golint $dir) - if [ "" != "$result" ]; then - echo $result - exit_code=5 - fi -done - -exit $exit_code diff --git a/.travis.sh b/.travis.sh index 0fd3a00..a81b856 100755 --- a/.travis.sh +++ b/.travis.sh @@ -1,8 +1,40 @@ #!/bin/sh set -e -docker pull golang:1.10-alpine -docker run \ - --rm \ - -v $(pwd):/go/src/github.com/mkenney/go-chrome \ - --entrypoint="/go/src/github.com/mkenney/go-chrome/.travis.entrypoint.sh" \ - golang:1.10-alpine \ No newline at end of file + +exit_code=0 + +go get -v github.com/golang/lint/golint +[ "0" = "$?" ] || exit 1 + +go get -u github.com/golang/dep/cmd/dep +[ "0" = "$?" ] || exit 2 + +dep ensure +[ "0" = "$?" ] || exit 3 + +for dir in $(go list ./... | grep -v vendor); do + echo "golint $dir" + result=$(golint $dir) + if [ "" != "$result" ]; then + echo $result + exit_code=5 + fi + if [ "0" != "$exit_code" ]; then + exit $exit_code + fi +done + +rm -f coverage.txt +for dir in $(go list ./... | grep -v vendor); do + GOCACHE=off go test -race -timeout 300s -coverprofile=profile.out $dir + exit_code=$? + if [ "0" != "$exit_code" ]; then + exit $exit_code + fi + if [ -f profile.out ]; then + cat profile.out >> coverage.txt + rm profile.out + fi +done + +exit $exit_code diff --git a/.travis.yml b/.travis.yml index db93ed9..3dc76b3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,14 +11,12 @@ branches: only: - master -services: - - docker - language: go go_import_path: github.com/mkenney/go-chrome go: - 1.9.x - 1.10.x + - 1.11.x - tip diff --git a/Gopkg.lock b/Gopkg.lock index 43960a5..4ff9092 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -2,26 +2,29 @@ [[projects]] - digest = "1:f254314a58767f8b34862fa09b0a3206e26a38f624d33a66fc0e442403feb94f" + digest = "1:26a8cd2b5c205710c74dca6c6fa5e8944985d7dfb8435ab2d299d9d57c7ff176" name = "github.com/bdlm/errors" packages = ["."] pruneopts = "" - revision = "4261cfedec68315454b163ae305cd34ecfc8b059" - version = "v0.1.0" + revision = "1e47c06d58b39d53be1b8f4e9bc353422a14aaa0" + version = "v0.1.2" [[projects]] - digest = "1:dad84a5b80c9cc6b9ee62236482b3e800eef019794f55a311f362977ca7580f6" + digest = "1:aa0ea6789f494e72359ee8da88e82c96a084960cc7ca2f594d04192e34c6e78c" name = "github.com/bdlm/log" packages = ["."] pruneopts = "" - revision = "09ffec84c7dadbb7dbe314e5bc27ac7a86ce5245" - version = "v0.1.10" + revision = "a880e500b91a3325f66bd576f8129074e7d613bf" + version = "v0.1.13" [[projects]] branch = "master" digest = "1:229dccc6286f2dd642f3c217c56fa340bb8dbe0c7ca05512ad49102dfbab1840" name = "github.com/bdlm/std" - packages = ["logger"] + packages = [ + "error", + "logger", + ] pruneopts = "" revision = "ba3aa8890134f4246631d714d79a75f53fca0c53" diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f231307 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,12 @@ +version: '3.5' +services: + chrome: + container_name: chrome + hostname: chrome + image: mkenney/chromium-headless:latest + ports: + - 9222:9222 + entrypoint: sh + command: + - "-cexu" + - "/usr/bin/google-chrome --addr=localhost --port=9222 --remote-debugging-port=9222 --remote-debugging-address=0.0.0.0 --disable-extensions --disable-gpu --headless --hide-scrollbars --no-first-run --no-sandbox" diff --git a/tot/chrome.chromium.go b/tot/chrome.chromium.go index ec27858..635c0e4 100644 --- a/tot/chrome.chromium.go +++ b/tot/chrome.chromium.go @@ -299,7 +299,7 @@ func (chrome *Chrome) Query( log.WithFields(log.Fields{ "path": path, "status": resp.Status, - }).Debug("querying chrome:/%s %s", path, resp.Status) + }).Debug("querying chrome") if 200 != resp.StatusCode { return nil, errs.New(0, resp.Status) } diff --git a/tot/mock.chromium_test.go b/tot/mock.chromium_test.go index 7a9a0d5..fd74893 100644 --- a/tot/mock.chromium_test.go +++ b/tot/mock.chromium_test.go @@ -233,7 +233,7 @@ func (chrome *MockChrome) Query( if len(params) > 0 { path += fmt.Sprintf("?%s", params.Encode()) } - log.Debugf("chrome:/%s %s", path) + log.Debugf("chrome:/%s", path) return msg, nil } diff --git a/tot/socket/cdtp.accessibility_test.go b/tot/socket/cdtp.accessibility_test.go index cbf63ef..e5c548d 100644 --- a/tot/socket/cdtp.accessibility_test.go +++ b/tot/socket/cdtp.accessibility_test.go @@ -2,7 +2,6 @@ package socket import ( "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/accessibility" @@ -10,24 +9,20 @@ import ( ) func TestAccessibilityGetPartialAXTree(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAccessibilityGetPartialAXTree") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() params := &accessibility.PartialAXTreeParams{ NodeID: dom.NodeID(1), FetchRelatives: true, } - resultChan := mockSocket.Accessibility().GetPartialAXTree(params) - mockResult := accessibility.PartialAXTreeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + mockResult := &accessibility.PartialAXTreeResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Accessibility().GetPartialAXTree(params) if nil != result.Err { t.Errorf("Expected success, got error: %s", result.Err) } @@ -36,8 +31,7 @@ func TestAccessibilityGetPartialAXTree(t *testing.T) { t.Errorf("Expected empty set, got '%s'", tmp) } - resultChan = mockSocket.Accessibility().GetPartialAXTree(params) - mockResult = accessibility.PartialAXTreeResult{ + mockResult = &accessibility.PartialAXTreeResult{ Nodes: []*accessibility.AXNode{{ NodeID: accessibility.AXNodeID("NodeID"), Ignored: false, @@ -73,13 +67,8 @@ func TestAccessibilityGetPartialAXTree(t *testing.T) { BackendDOMNodeID: dom.BackendNodeID(1), }}, } - mockResultBytes, _ = json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result = <-resultChan + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result = <-soc.Accessibility().GetPartialAXTree(params) if nil != result.Err { t.Errorf("Expected success, got error: %s", result.Err) } @@ -88,16 +77,8 @@ func TestAccessibilityGetPartialAXTree(t *testing.T) { t.Errorf("Expected dataset, got '%s'", tmp) } - resultChan = mockSocket.Accessibility().GetPartialAXTree(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Accessibility().GetPartialAXTree(params) if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.animation_test.go b/tot/socket/cdtp.animation_test.go index d792881..b0aeb81 100644 --- a/tot/socket/cdtp.animation_test.go +++ b/tot/socket/cdtp.animation_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -12,86 +10,73 @@ import ( ) func TestAnimationDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - - resultChan := mockSocket.Animation().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - - resultChan := mockSocket.Animation().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationGetCurrentTime(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationGetCurrentTime") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.GetCurrentTimeParams{ ID: "animation-id", } - resultChan := mockSocket.Animation().GetCurrentTime(params) - mockResultBytes, _ := json.Marshal(animation.GetCurrentTimeResult{}) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + mockResult := &animation.GetCurrentTimeResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().GetCurrentTime(params) if nil != result.Err { t.Errorf("Expected success, got error: '%s'", result.Err.Error()) } @@ -99,19 +84,13 @@ func TestAnimationGetCurrentTime(t *testing.T) { t.Errorf("Expected 0, got %d", result.CurrentTime) } - resultChan = mockSocket.Animation().GetCurrentTime(&animation.GetCurrentTimeParams{ - ID: "animation-id", - }) - mockResult := &animation.GetCurrentTimeResult{ + mockResult = &animation.GetCurrentTimeResult{ CurrentTime: time.Now().Unix(), } - mockResultBytes, _ = json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result = <-soc.Animation().GetCurrentTime(&animation.GetCurrentTimeParams{ + ID: "animation-id", }) - result = <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -123,38 +102,26 @@ func TestAnimationGetCurrentTime(t *testing.T) { ) } - resultChan = mockSocket.Animation().GetCurrentTime(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().GetCurrentTime(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationGetPlaybackRate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationGetPlaybackRate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Animation().GetPlaybackRate() mockResult := &animation.GetPlaybackRateResult{ PlaybackRate: 1.0, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().GetPlaybackRate() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -166,66 +133,55 @@ func TestAnimationGetPlaybackRate(t *testing.T) { ) } - resultChan = mockSocket.Animation().GetPlaybackRate() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().GetPlaybackRate() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationReleaseAnimations(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationReleaseAnimations") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.ReleaseAnimationsParams{ Animations: []string{"animation1", "animation2"}, } - resultChan := mockSocket.Animation().ReleaseAnimations(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().ReleaseAnimations(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().ReleaseAnimations(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().ReleaseAnimations(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationResolveAnimation(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationResolveAnimation") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.ResolveAnimationParams{ AnimationID: "animation-id", } - resultChan := mockSocket.Animation().ResolveAnimation(params) + mockResult := &animation.ResolveAnimationResult{ RemoteObject: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -251,13 +207,9 @@ func TestAnimationResolveAnimation(t *testing.T) { }, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().ResolveAnimation(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -269,185 +221,161 @@ func TestAnimationResolveAnimation(t *testing.T) { ) } - resultChan = mockSocket.Animation().ResolveAnimation(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().ResolveAnimation(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationSeekAnimations(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationSeekAnimations") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.SeekAnimationsParams{ Animations: []string{"animation1", "animation2"}, CurrentTime: 1, } - resultChan := mockSocket.Animation().SeekAnimations(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().SeekAnimations(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().SeekAnimations(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().SeekAnimations(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationSetPaused(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationSetPaused") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.SetPausedParams{ Animations: []string{"animation1", "animation2"}, Paused: true, } - resultChan := mockSocket.Animation().SetPaused(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().SetPaused(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().SetPaused(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().SetPaused(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationSetPlaybackRate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationSetPlaybackRate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.SetPlaybackRateParams{ PlaybackRate: 1, } - resultChan := mockSocket.Animation().SetPlaybackRate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().SetPlaybackRate(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().SetPlaybackRate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().SetPlaybackRate(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationSetTiming(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationSetTiming") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &animation.SetTimingParams{ AnimationID: "animation-id", Duration: 1, Delay: 1, } - resultChan := mockSocket.Animation().SetTiming(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Animation().SetTiming(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Animation().SetTiming(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Animation().SetTiming(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestAnimationOnAnimationCanceled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationOnAnimationCanceled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *animation.CanceledEvent) - mockSocket.Animation().OnAnimationCanceled(func(eventData *animation.CanceledEvent) { + soc.Animation().OnAnimationCanceled(func(eventData *animation.CanceledEvent) { resultChan <- eventData }) mockResult := &animation.CanceledEvent{ ID: "event-id", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, - Method: "Animation.animationCanceled", - Params: mockResultBytes, + chrome.AddData(MockData{0, + &Error{}, + mockResult, + "Animation.animationCanceled", }) result := <-resultChan if result.ID != mockResult.ID { @@ -458,18 +386,10 @@ func TestAnimationOnAnimationCanceled(t *testing.T) { ) } - resultChan = make(chan *animation.CanceledEvent) - mockSocket.Animation().OnAnimationCanceled(func(eventData *animation.CanceledEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - Method: "Animation.animationCanceled", + chrome.AddData(MockData{0, + genericError, + nil, + "Animation.animationCanceled", }) result = <-resultChan if nil == result.Err { @@ -478,25 +398,25 @@ func TestAnimationOnAnimationCanceled(t *testing.T) { } func TestAnimationOnAnimationCreated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationOnAnimationCreated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *animation.CreatedEvent) - mockSocket.Animation().OnAnimationCreated(func(eventData *animation.CreatedEvent) { + soc.Animation().OnAnimationCreated(func(eventData *animation.CreatedEvent) { resultChan <- eventData }) mockResult := &animation.CreatedEvent{ ID: "event-id", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, - Method: "Animation.animationCreated", - Params: mockResultBytes, + chrome.AddData(MockData{0, + &Error{}, + mockResult, + "Animation.animationCreated", }) result := <-resultChan if result.ID != mockResult.ID { @@ -507,18 +427,10 @@ func TestAnimationOnAnimationCreated(t *testing.T) { ) } - resultChan = make(chan *animation.CreatedEvent) - mockSocket.Animation().OnAnimationCreated(func(eventData *animation.CreatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - Method: "Animation.animationCreated", + chrome.AddData(MockData{0, + genericError, + nil, + "Animation.animationCreated", }) result = <-resultChan if nil == result.Err { @@ -527,15 +439,18 @@ func TestAnimationOnAnimationCreated(t *testing.T) { } func TestAnimationOnAnimationStarted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAnimationOnAnimationStarted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *animation.StartedEvent) - mockSocket.Animation().OnAnimationStarted(func(eventData *animation.StartedEvent) { + soc.Animation().OnAnimationStarted(func(eventData *animation.StartedEvent) { resultChan <- eventData }) + mockResult := &animation.StartedEvent{ Animation: &animation.Animation{ ID: "animation-id", @@ -564,12 +479,10 @@ func TestAnimationOnAnimationStarted(t *testing.T) { CSSID: "css-id", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, - Method: "Animation.animationStarted", - Params: mockResultBytes, + chrome.AddData(MockData{0, + &Error{}, + mockResult, + "Animation.animationStarted", }) result := <-resultChan if result.Animation.ID != mockResult.Animation.ID { @@ -580,18 +493,10 @@ func TestAnimationOnAnimationStarted(t *testing.T) { ) } - resultChan = make(chan *animation.StartedEvent) - mockSocket.Animation().OnAnimationStarted(func(eventData *animation.StartedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - Method: "Animation.animationStarted", + chrome.AddData(MockData{0, + genericError, + nil, + "Animation.animationStarted", }) result = <-resultChan if nil == result.Err { diff --git a/tot/socket/cdtp.application.cache_test.go b/tot/socket/cdtp.application.cache_test.go index 269fdc9..bfcd378 100644 --- a/tot/socket/cdtp.application.cache_test.go +++ b/tot/socket/cdtp.application.cache_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -11,44 +9,39 @@ import ( ) func TestApplicationCacheEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ApplicationCache().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: nil, - }) - result := <-resultChan + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ApplicationCache().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ApplicationCache().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ApplicationCache().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestApplicationCacheGetForFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheGetForFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() mockParams := &application_cache.GetForFrameParams{FrameID: page.FrameID("mock-frame-id")} - resultChan := mockSocket.ApplicationCache().GetForFrame(mockParams) mockResult := &application_cache.GetForFrameResult{ ApplicationCache: &application_cache.ApplicationCache{ ManifestURL: "http://example.com/manifest", @@ -62,16 +55,9 @@ func TestApplicationCacheGetForFrame(t *testing.T) { }}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockParamsBytes, _ := json.Marshal(mockParams) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Params: mockParamsBytes, - Result: mockResultBytes, - }) - result := <-resultChan + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ApplicationCache().GetForFrame(mockParams) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -83,28 +69,20 @@ func TestApplicationCacheGetForFrame(t *testing.T) { ) } - resultChan = mockSocket.ApplicationCache().GetForFrame(mockParams) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ApplicationCache().GetForFrame(mockParams) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestApplicationCacheGetFramesWithManifests(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheGetFramesWithManifests") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ApplicationCache().GetFramesWithManifests() mockResult := &application_cache.GetFramesWithManifestsResult{ FrameIDs: []*application_cache.FrameWithManifest{{ FrameID: page.FrameID(1), @@ -112,13 +90,9 @@ func TestApplicationCacheGetFramesWithManifests(t *testing.T) { Status: 1, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ApplicationCache().GetFramesWithManifests() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -130,40 +104,28 @@ func TestApplicationCacheGetFramesWithManifests(t *testing.T) { ) } - resultChan = mockSocket.ApplicationCache().GetFramesWithManifests() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ApplicationCache().GetFramesWithManifests() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestApplicationCacheGetManifestForFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheGetManifestForFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ApplicationCache().GetManifestForFrame(&application_cache.GetManifestForFrameParams{ - FrameID: page.FrameID("mock-frame-id"), - }) mockResult := &application_cache.GetManifestForFrameResult{ ManifestURL: "http://example.com/manifest", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ApplicationCache().GetManifestForFrame(&application_cache.GetManifestForFrameParams{ + FrameID: page.FrameID("mock-frame-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -175,44 +137,38 @@ func TestApplicationCacheGetManifestForFrame(t *testing.T) { ) } - resultChan = mockSocket.ApplicationCache().GetManifestForFrame(&application_cache.GetManifestForFrameParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ApplicationCache().GetManifestForFrame(&application_cache.GetManifestForFrameParams{ FrameID: page.FrameID("mock-frame-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestApplicationCacheOnApplicationCacheStatusUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheOnApplicationCacheStatusUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *application_cache.StatusUpdatedEvent) - mockSocket.ApplicationCache().OnApplicationCacheStatusUpdated(func(eventData *application_cache.StatusUpdatedEvent) { + soc.ApplicationCache().OnApplicationCacheStatusUpdated(func(eventData *application_cache.StatusUpdatedEvent) { resultChan <- eventData }) + mockResult := &application_cache.StatusUpdatedEvent{ FrameID: page.FrameID("mock-frame-id"), ManifestURL: "http://example.com/manifest", Status: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, - Method: "ApplicationCache.applicationCacheStatusUpdated", - Params: mockResultBytes, + chrome.AddData(MockData{ + 0, + &Error{}, + mockResult, + "ApplicationCache.applicationCacheStatusUpdated", }) result := <-resultChan if result.ManifestURL != mockResult.ManifestURL { @@ -223,18 +179,11 @@ func TestApplicationCacheOnApplicationCacheStatusUpdated(t *testing.T) { ) } - resultChan = make(chan *application_cache.StatusUpdatedEvent) - mockSocket.ApplicationCache().OnApplicationCacheStatusUpdated(func(eventData *application_cache.StatusUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - Method: "ApplicationCache.applicationCacheStatusUpdated", + chrome.AddData(MockData{ + 0, + genericError, + nil, + "ApplicationCache.applicationCacheStatusUpdated", }) result = <-resultChan if nil == result.Err { @@ -243,24 +192,25 @@ func TestApplicationCacheOnApplicationCacheStatusUpdated(t *testing.T) { } func TestApplicationCacheOnNetworkStateUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestApplicationCacheOnNetworkStateUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *application_cache.NetworkStateUpdatedEvent) - mockSocket.ApplicationCache().OnNetworkStateUpdated(func(eventData *application_cache.NetworkStateUpdatedEvent) { + soc.ApplicationCache().OnNetworkStateUpdated(func(eventData *application_cache.NetworkStateUpdatedEvent) { resultChan <- eventData }) + mockResult := &application_cache.NetworkStateUpdatedEvent{ IsNowOnline: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "ApplicationCache.networkStateUpdated", - Params: mockResultBytes, }) result := <-resultChan if result.IsNowOnline != mockResult.IsNowOnline { @@ -271,17 +221,9 @@ func TestApplicationCacheOnNetworkStateUpdated(t *testing.T) { ) } - resultChan = make(chan *application_cache.NetworkStateUpdatedEvent) - mockSocket.ApplicationCache().OnNetworkStateUpdated(func(eventData *application_cache.NetworkStateUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "ApplicationCache.networkStateUpdated", }) result = <-resultChan diff --git a/tot/socket/cdtp.audits_test.go b/tot/socket/cdtp.audits_test.go index 679fa4b..a97b825 100644 --- a/tot/socket/cdtp.audits_test.go +++ b/tot/socket/cdtp.audits_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" audits "github.com/mkenney/go-chrome/tot/audits" @@ -10,29 +8,25 @@ import ( ) func TestAuditsGetEncodedResponse(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestAuditsGetEncodedResponse") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Audits().GetEncodedResponse(&audits.GetEncodedResponseParams{ - RequestID: network.RequestID("audit-id"), - Encoding: audits.Encoding.Webp, - Quality: 1, - SizeOnly: true, - }) mockResult := &audits.GetEncodedResponseResult{ Body: "Response body", OriginalSize: 1, EncodedSize: 2, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Audits().GetEncodedResponse(&audits.GetEncodedResponseParams{ + RequestID: network.RequestID("audit-id"), + Encoding: audits.Encoding.Webp, + Quality: 1, + SizeOnly: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -44,21 +38,13 @@ func TestAuditsGetEncodedResponse(t *testing.T) { ) } - resultChan = mockSocket.Audits().GetEncodedResponse(&audits.GetEncodedResponseParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Audits().GetEncodedResponse(&audits.GetEncodedResponseParams{ RequestID: network.RequestID("audit-id"), Encoding: audits.Encoding.Webp, Quality: 1, SizeOnly: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.browser_test.go b/tot/socket/cdtp.browser_test.go index c0f547d..b751da1 100644 --- a/tot/socket/cdtp.browser_test.go +++ b/tot/socket/cdtp.browser_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" browser "github.com/mkenney/go-chrome/tot/browser" @@ -10,43 +8,39 @@ import ( ) func TestBrowserClose(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestBrowserClose") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Browser().Close() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - }) - result := <-resultChan + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Browser().Close() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Browser().Close() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Browser().Close() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestBrowserGetVersion(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestBrowserGetVersion") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Browser().GetVersion() mockResult := &browser.GetVersionResult{ ProtocolVersion: "1.2", Product: "product", @@ -54,13 +48,9 @@ func TestBrowserGetVersion(t *testing.T) { UserAgent: "user-agent", JSVersion: "V8 version", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Browser().GetVersion() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -72,30 +62,20 @@ func TestBrowserGetVersion(t *testing.T) { ) } - resultChan = mockSocket.Browser().GetVersion() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Browser().GetVersion() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestBrowserGetWindowBounds(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestBrowserGetWindowBounds") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Browser().GetWindowBounds(&browser.GetWindowBoundsParams{ - WindowID: browser.WindowID(1), - }) mockResult := &browser.GetWindowBoundsResult{ Bounds: &browser.Bounds{ Height: 100, @@ -105,13 +85,11 @@ func TestBrowserGetWindowBounds(t *testing.T) { WindowState: browser.WindowState("window-state"), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Browser().GetWindowBounds(&browser.GetWindowBoundsParams{ + WindowID: browser.WindowID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -123,32 +101,22 @@ func TestBrowserGetWindowBounds(t *testing.T) { ) } - resultChan = mockSocket.Browser().GetWindowBounds(&browser.GetWindowBoundsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Browser().GetWindowBounds(&browser.GetWindowBoundsParams{ WindowID: browser.WindowID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestBrowserGetWindowForTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestBrowserGetWindowForTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Browser().GetWindowForTarget(&browser.GetWindowForTargetParams{ - TargetID: target.ID("target-id"), - }) mockResult := &browser.GetWindowForTargetResult{ WindowID: browser.WindowID(1), Bounds: &browser.Bounds{ @@ -159,13 +127,11 @@ func TestBrowserGetWindowForTarget(t *testing.T) { WindowState: browser.WindowState("window-state"), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Browser().GetWindowForTarget(&browser.GetWindowForTargetParams{ + TargetID: target.ID("target-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -184,30 +150,23 @@ func TestBrowserGetWindowForTarget(t *testing.T) { ) } - resultChan = mockSocket.Browser().GetWindowForTarget(&browser.GetWindowForTargetParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Browser().GetWindowForTarget(&browser.GetWindowForTargetParams{ TargetID: target.ID("target-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestBrowserSetWindowBounds(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestBrowserSetWindowBounds") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Browser().SetWindowBounds(&browser.SetWindowBoundsParams{ + mockResult := &browser.SetWindowBoundsResult{ WindowID: browser.WindowID(1), Bounds: &browser.Bounds{ Height: 100, @@ -216,8 +175,10 @@ func TestBrowserSetWindowBounds(t *testing.T) { Width: 100, WindowState: browser.WindowState("window-state"), }, - }) - mockResult := &browser.SetWindowBoundsResult{ + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Browser().SetWindowBounds(&browser.SetWindowBoundsParams{ WindowID: browser.WindowID(1), Bounds: &browser.Bounds{ Height: 100, @@ -226,14 +187,7 @@ func TestBrowserSetWindowBounds(t *testing.T) { Width: 100, WindowState: browser.WindowState("window-state"), }, - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -252,7 +206,8 @@ func TestBrowserSetWindowBounds(t *testing.T) { ) } - resultChan = mockSocket.Browser().SetWindowBounds(&browser.SetWindowBoundsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Browser().SetWindowBounds(&browser.SetWindowBoundsParams{ WindowID: browser.WindowID(1), Bounds: &browser.Bounds{ Height: 100, @@ -262,15 +217,6 @@ func TestBrowserSetWindowBounds(t *testing.T) { WindowState: browser.WindowState("window-state"), }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.cache.storage_test.go b/tot/socket/cdtp.cache.storage_test.go index cccb725..f3c6a78 100644 --- a/tot/socket/cdtp.cache.storage_test.go +++ b/tot/socket/cdtp.cache.storage_test.go @@ -1,102 +1,81 @@ package socket import ( - "encoding/json" - "net/url" "testing" - "github.com/bdlm/log" cacheStorage "github.com/mkenney/go-chrome/tot/cache/storage" ) -func init() { - level, err := log.ParseLevel("debug") - if nil == err { - log.SetLevel(level) - } -} - func TestCacheStorageDeleteCache(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCacheStorageDeleteCache") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } - resultChan := mockSocket.CacheStorage().DeleteCache(&cacheStorage.DeleteCacheParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CacheStorage().DeleteCache(&cacheStorage.DeleteCacheParams{ CacheID: cacheStorage.CacheID("cache-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CacheStorage().DeleteCache(&cacheStorage.DeleteCacheParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CacheStorage().DeleteCache(&cacheStorage.DeleteCacheParams{ CacheID: cacheStorage.CacheID("cache-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCacheStorageDeleteEntry(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCacheStorageDeleteEntry") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - - resultChan := mockSocket.CacheStorage().DeleteEntry(&cacheStorage.DeleteEntryParams{ + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := MockData{ + 0, + &Error{}, + nil, + "", + } + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CacheStorage().DeleteEntry(&cacheStorage.DeleteEntryParams{ CacheID: cacheStorage.CacheID("cache-id"), Request: "request", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CacheStorage().DeleteEntry(&cacheStorage.DeleteEntryParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CacheStorage().DeleteEntry(&cacheStorage.DeleteEntryParams{ CacheID: cacheStorage.CacheID("cache-id"), Request: "request", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCacheStorageRequestCacheNames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCacheStorageRequestCacheNames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CacheStorage().RequestCacheNames(&cacheStorage.RequestCacheNamesParams{ - SecurityOrigin: "security-origin", - }) mockResult := &cacheStorage.RequestCacheNamesResult{ Caches: []*cacheStorage.Cache{{ CacheID: cacheStorage.CacheID("cache-id"), @@ -104,13 +83,16 @@ func TestCacheStorageRequestCacheNames(t *testing.T) { CacheName: "cache-name", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{ + 0, + &Error{}, + mockResult, + "", + }) + result := <-soc.CacheStorage().RequestCacheNames(&cacheStorage.RequestCacheNamesParams{ + SecurityOrigin: "security-origin", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -122,45 +104,38 @@ func TestCacheStorageRequestCacheNames(t *testing.T) { ) } - resultChan = mockSocket.CacheStorage().RequestCacheNames(&cacheStorage.RequestCacheNamesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CacheStorage().RequestCacheNames(&cacheStorage.RequestCacheNamesParams{ SecurityOrigin: "security-origin", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCacheStorageRequestCachedResponse(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCacheStorageRequestCachedResponse") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CacheStorage().RequestCachedResponse(&cacheStorage.RequestCachedResponseParams{ - CacheID: cacheStorage.CacheID("security-origin"), - RequestURL: mockSocket.URL().String(), - }) mockResult := &cacheStorage.RequestCachedResponseResult{ Response: &cacheStorage.CachedResponse{ Body: "body", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{ + 0, + &Error{}, + mockResult, + "", + }) + result := <-soc.CacheStorage().RequestCachedResponse(&cacheStorage.RequestCachedResponseParams{ + CacheID: cacheStorage.CacheID("security-origin"), + RequestURL: soc.URL().String(), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -172,38 +147,26 @@ func TestCacheStorageRequestCachedResponse(t *testing.T) { ) } - resultChan = mockSocket.CacheStorage().RequestCachedResponse(&cacheStorage.RequestCachedResponseParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CacheStorage().RequestCachedResponse(&cacheStorage.RequestCachedResponseParams{ CacheID: cacheStorage.CacheID("security-origin"), - RequestURL: mockSocket.URL().String(), + RequestURL: soc.URL().String(), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCacheStorageRequestEntries(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCacheStorageRequestEntries") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CacheStorage().RequestEntries(&cacheStorage.RequestEntriesParams{ - CacheID: cacheStorage.CacheID("security-origin"), - SkipCount: 1, - PageSize: 1, - }) mockResult := &cacheStorage.RequestEntriesResult{ CacheDataEntries: []*cacheStorage.DataEntry{{ - RequestURL: mockSocket.URL().String(), + RequestURL: soc.URL().String(), RequestMethod: "POST", RequestHeaders: []*cacheStorage.Header{{ Name: "Header", @@ -219,13 +182,18 @@ func TestCacheStorageRequestEntries(t *testing.T) { }}, HasMore: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{ + 0, + &Error{}, + mockResult, + "", + }) + result := <-soc.CacheStorage().RequestEntries(&cacheStorage.RequestEntriesParams{ + CacheID: cacheStorage.CacheID("security-origin"), + SkipCount: 1, + PageSize: 1, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -237,20 +205,12 @@ func TestCacheStorageRequestEntries(t *testing.T) { ) } - resultChan = mockSocket.CacheStorage().RequestEntries(&cacheStorage.RequestEntriesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CacheStorage().RequestEntries(&cacheStorage.RequestEntriesParams{ CacheID: cacheStorage.CacheID("security-origin"), SkipCount: 1, PageSize: 1, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.console_test.go b/tot/socket/cdtp.console_test.go index 40f86e2..15ae76c 100644 --- a/tot/socket/cdtp.console_test.go +++ b/tot/socket/cdtp.console_test.go @@ -1,125 +1,85 @@ package socket import ( - "encoding/json" - "net/url" "testing" console "github.com/mkenney/go-chrome/tot/console" ) func TestConsoleClearMessages(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestConsoleClearMessages") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Console().ClearMessages() mockResult := &console.ClearMessagesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Console().ClearMessages() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Console().ClearMessages() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Console().ClearMessages() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestConsoleDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestConsoleDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Console().Disable() mockResult := &console.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Console().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Console().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Console().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestConsoleEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestConsoleEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Console().Enable() mockResult := &console.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Console().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Console().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Console().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestConsoleOnMessageAdded(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestConsoleOnMessageAdded") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := make(chan *console.MessageAddedEvent) - mockSocket.Console().OnMessageAdded(func(eventData *console.MessageAddedEvent) { - resultChan <- eventData - }) mockResult := &console.MessageAddedEvent{ Message: &console.Message{ Source: console.MessageSource.XML, @@ -130,12 +90,16 @@ func TestConsoleOnMessageAdded(t *testing.T) { Column: 10, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + + resultChan := make(chan *console.MessageAddedEvent) + soc.Console().OnMessageAdded(func(eventData *console.MessageAddedEvent) { + resultChan <- eventData + }) + + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Console.messageAdded", - Params: mockResultBytes, }) result := <-resultChan if result.Message.Source != mockResult.Message.Source { @@ -146,17 +110,9 @@ func TestConsoleOnMessageAdded(t *testing.T) { ) } - resultChan = make(chan *console.MessageAddedEvent) - mockSocket.Console().OnMessageAdded(func(eventData *console.MessageAddedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Console.messageAdded", }) result = <-resultChan diff --git a/tot/socket/cdtp.css_test.go b/tot/socket/cdtp.css_test.go index 546ffba..16748fd 100644 --- a/tot/socket/cdtp.css_test.go +++ b/tot/socket/cdtp.css_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/css" @@ -11,21 +9,12 @@ import ( ) func TestCSSAddRule(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSAddRule") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().AddRule(&css.AddRuleParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - RuleText: "rule text", - Location: &css.SourceRange{ - StartLine: 10, - StartColumn: 10, - EndLine: 10, - EndColumn: 10, - }, - }) mockResult := &css.AddRuleResult{Rule: &css.Rule{ StyleSheetID: css.StyleSheetID("stylesheet-id"), SelectorList: &css.SelectorList{ @@ -98,13 +87,18 @@ func TestCSSAddRule(t *testing.T) { }}, }}, }} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().AddRule(&css.AddRuleParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + RuleText: "rule text", + Location: &css.SourceRange{ + StartLine: 10, + StartColumn: 10, + EndLine: 10, + EndColumn: 10, + }, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -112,7 +106,8 @@ func TestCSSAddRule(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Rule.StyleSheetID, result.Rule.StyleSheetID) } - resultChan = mockSocket.CSS().AddRule(&css.AddRuleParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().AddRule(&css.AddRuleParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), RuleText: "rule text", Location: &css.SourceRange{ @@ -122,39 +117,26 @@ func TestCSSAddRule(t *testing.T) { EndColumn: 10, }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSCollectClassNames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSCollectClassNames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().CollectClassNames(&css.CollectClassNamesParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - }) mockResult := &css.CollectClassNamesResult{ClassNames: []string{ "class1", "class2", }} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().CollectClassNames(&css.CollectClassNamesParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -162,42 +144,30 @@ func TestCSSCollectClassNames(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.ClassNames[0], result.ClassNames[0]) } - resultChan = mockSocket.CSS().CollectClassNames(&css.CollectClassNamesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().CollectClassNames(&css.CollectClassNamesParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSCreateStyleSheet(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSCreateStyleSheet") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().CreateStyleSheet(&css.CreateStyleSheetParams{ - FrameID: page.FrameID("frame-id"), - }) mockResult := &css.CreateStyleSheetResult{ StyleSheetID: css.StyleSheetID("stylesheet-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().CreateStyleSheet(&css.CreateStyleSheetParams{ + FrameID: page.FrameID("frame-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -205,153 +175,105 @@ func TestCSSCreateStyleSheet(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.StyleSheetID, result.StyleSheetID) } - resultChan = mockSocket.CSS().CreateStyleSheet(&css.CreateStyleSheetParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().CreateStyleSheet(&css.CreateStyleSheetParams{ FrameID: page.FrameID("frame-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().Disable() mockResult := &css.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CSS().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().Enable() mockResult := &css.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CSS().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSForcePseudoState(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSForcePseudoState") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &css.ForcePseudoStateResult{} - resultChan := mockSocket.CSS().ForcePseudoState(&css.ForcePseudoStateParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().ForcePseudoState(&css.ForcePseudoStateParams{ NodeID: dom.NodeID(1), ForcedPseudoClasses: []css.ForcedPseudoClassesEnum{css.ForcedPseudoClasses.Active}, }) - mockResult := &css.ForcePseudoStateResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CSS().ForcePseudoState(&css.ForcePseudoStateParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().ForcePseudoState(&css.ForcePseudoStateParams{ NodeID: dom.NodeID(1), ForcedPseudoClasses: []css.ForcedPseudoClassesEnum{css.ForcedPseudoClasses.Active}, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetBackgroundColors(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetBackgroundColors") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetBackgroundColors(&css.GetBackgroundColorsParams{ - NodeID: dom.NodeID(1), - }) mockResult := &css.GetBackgroundColorsResult{ BackgroundColors: []string{"blue"}, ComputedFontSize: "10pt", ComputedFontWeight: "normal", ComputedBodyFontSize: "10pt", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetBackgroundColors(&css.GetBackgroundColorsParams{ + NodeID: dom.NodeID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -359,45 +281,33 @@ func TestCSSGetBackgroundColors(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.BackgroundColors[0], result.BackgroundColors[0]) } - resultChan = mockSocket.CSS().GetBackgroundColors(&css.GetBackgroundColorsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetBackgroundColors(&css.GetBackgroundColorsParams{ NodeID: dom.NodeID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetComputedStyleForNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetComputedStyleForNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetComputedStyleForNode(&css.GetComputedStyleForNodeParams{ - NodeID: dom.NodeID(1), - }) mockResult := &css.GetComputedStyleForNodeResult{ ComputedStyle: []*css.ComputedStyleProperty{{ Name: "style-name", Value: "style-value", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetComputedStyleForNode(&css.GetComputedStyleForNodeParams{ + NodeID: dom.NodeID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -405,32 +315,22 @@ func TestCSSGetComputedStyleForNode(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.ComputedStyle[0].Name, result.ComputedStyle[0].Name) } - resultChan = mockSocket.CSS().GetComputedStyleForNode(&css.GetComputedStyleForNodeParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetComputedStyleForNode(&css.GetComputedStyleForNodeParams{ NodeID: dom.NodeID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetInlineStylesForNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetInlineStylesForNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetInlineStylesForNode(&css.GetInlineStylesForNodeParams{ - NodeID: dom.NodeID(1), - }) mockResult := &css.GetInlineStylesForNodeResult{ InlineStyle: &css.Style{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -469,13 +369,11 @@ func TestCSSGetInlineStylesForNode(t *testing.T) { }}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetInlineStylesForNode(&css.GetInlineStylesForNodeParams{ + NodeID: dom.NodeID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -483,32 +381,22 @@ func TestCSSGetInlineStylesForNode(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.InlineStyle.StyleSheetID, result.InlineStyle.StyleSheetID) } - resultChan = mockSocket.CSS().GetInlineStylesForNode(&css.GetInlineStylesForNodeParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetInlineStylesForNode(&css.GetInlineStylesForNodeParams{ NodeID: dom.NodeID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetMatchedStylesForNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetMatchedStylesForNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetMatchedStylesForNode(&css.GetMatchedStylesForNodeParams{ - NodeID: dom.NodeID(1), - }) mockResult := &css.GetMatchedStylesForNodeResult{ InlineStyle: &css.Style{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -565,13 +453,11 @@ func TestCSSGetMatchedStylesForNode(t *testing.T) { }, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetMatchedStylesForNode(&css.GetMatchedStylesForNodeParams{ + NodeID: dom.NodeID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -579,30 +465,22 @@ func TestCSSGetMatchedStylesForNode(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.InlineStyle.StyleSheetID, result.InlineStyle.StyleSheetID) } - resultChan = mockSocket.CSS().GetMatchedStylesForNode(&css.GetMatchedStylesForNodeParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetMatchedStylesForNode(&css.GetMatchedStylesForNodeParams{ NodeID: dom.NodeID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetMediaQueries(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetMediaQueries") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetMediaQueries() mockResult := &css.GetMediaQueriesResult{ Medias: []*css.Media{{ Text: "media text", @@ -631,13 +509,9 @@ func TestCSSGetMediaQueries(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetMediaQueries() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -645,30 +519,20 @@ func TestCSSGetMediaQueries(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Medias[0].Text, result.Medias[0].Text) } - resultChan = mockSocket.CSS().GetMediaQueries() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetMediaQueries() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetPlatformFontsForNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetPlatformFontsForNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetPlatformFontsForNode(&css.GetPlatformFontsForNodeParams{ - NodeID: dom.NodeID(1), - }) mockResult := &css.GetPlatformFontsForNodeResult{ Fonts: []*css.PlatformFontUsage{{ FamilyName: "courier", @@ -676,13 +540,11 @@ func TestCSSGetPlatformFontsForNode(t *testing.T) { GlyphCount: 1, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetPlatformFontsForNode(&css.GetPlatformFontsForNodeParams{ + NodeID: dom.NodeID(1), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -690,42 +552,30 @@ func TestCSSGetPlatformFontsForNode(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Fonts[0].FamilyName, result.Fonts[0].FamilyName) } - resultChan = mockSocket.CSS().GetPlatformFontsForNode(&css.GetPlatformFontsForNodeParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetPlatformFontsForNode(&css.GetPlatformFontsForNodeParams{ NodeID: dom.NodeID(1), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSGetStyleSheetText(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSGetStyleSheetText") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().GetStyleSheetText(&css.GetStyleSheetTextParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - }) mockResult := &css.GetStyleSheetTextResult{ Text: "some text", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().GetStyleSheetText(&css.GetStyleSheetTextParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -733,81 +583,52 @@ func TestCSSGetStyleSheetText(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Text, result.Text) } - resultChan = mockSocket.CSS().GetStyleSheetText(&css.GetStyleSheetTextParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().GetStyleSheetText(&css.GetStyleSheetTextParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetEffectivePropertyValueForNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetEffectivePropertyValueForNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &css.SetEffectivePropertyValueForNodeResult{} - resultChan := mockSocket.CSS().SetEffectivePropertyValueForNode(&css.SetEffectivePropertyValueForNodeParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetEffectivePropertyValueForNode(&css.SetEffectivePropertyValueForNodeParams{ NodeID: dom.NodeID(1), PropertyName: "property-name", Value: "property-value", }) - mockResult := &css.SetEffectivePropertyValueForNodeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CSS().SetEffectivePropertyValueForNode(&css.SetEffectivePropertyValueForNodeParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetEffectivePropertyValueForNode(&css.SetEffectivePropertyValueForNodeParams{ NodeID: dom.NodeID(1), PropertyName: "property-name", Value: "property-value", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetKeyframeKey(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetKeyframeKey") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().SetKeyframeKey(&css.SetKeyframeKeyParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - Range: &css.SourceRange{ - StartLine: 10, - StartColumn: 10, - EndLine: 10, - EndColumn: 10, - }, - Selector: "selector", - }) mockResult := &css.SetKeyframeKeyResult{ KeyText: &css.Value{ Text: "some text", @@ -819,13 +640,18 @@ func TestCSSSetKeyframeKey(t *testing.T) { }, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetKeyframeKey(&css.SetKeyframeKeyParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + Range: &css.SourceRange{ + StartLine: 10, + StartColumn: 10, + EndLine: 10, + EndColumn: 10, + }, + Selector: "selector", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -833,7 +659,8 @@ func TestCSSSetKeyframeKey(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.KeyText.Text, result.KeyText.Text) } - resultChan = mockSocket.CSS().SetKeyframeKey(&css.SetKeyframeKeyParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetKeyframeKey(&css.SetKeyframeKeyParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), Range: &css.SourceRange{ StartLine: 10, @@ -843,36 +670,18 @@ func TestCSSSetKeyframeKey(t *testing.T) { }, Selector: "selector", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetMediaText(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetMediaText") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().SetMediaText(&css.SetMediaTextParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - Range: &css.SourceRange{ - StartLine: 10, - StartColumn: 10, - EndLine: 10, - EndColumn: 10, - }, - Text: "some text", - }) mockResult := &css.SetMediaTextResult{ Media: &css.Media{ Text: "some text", @@ -901,13 +710,18 @@ func TestCSSSetMediaText(t *testing.T) { }}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetMediaText(&css.SetMediaTextParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + Range: &css.SourceRange{ + StartLine: 10, + StartColumn: 10, + EndLine: 10, + EndColumn: 10, + }, + Text: "some text", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -915,7 +729,8 @@ func TestCSSSetMediaText(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Media.Text, result.Media.Text) } - resultChan = mockSocket.CSS().SetMediaText(&css.SetMediaTextParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetMediaText(&css.SetMediaTextParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), Range: &css.SourceRange{ StartLine: 10, @@ -925,36 +740,18 @@ func TestCSSSetMediaText(t *testing.T) { }, Text: "some text", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetRuleSelector(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetRuleSelector") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().SetRuleSelector(&css.SetRuleSelectorParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - Range: &css.SourceRange{ - StartLine: 10, - StartColumn: 10, - EndLine: 10, - EndColumn: 10, - }, - Selector: "selector", - }) mockResult := &css.SetRuleSelectorResult{ SelectorList: &css.SelectorList{ Selectors: []*css.Value{{ @@ -968,13 +765,18 @@ func TestCSSSetRuleSelector(t *testing.T) { }}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetRuleSelector(&css.SetRuleSelectorParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + Range: &css.SourceRange{ + StartLine: 10, + StartColumn: 10, + EndLine: 10, + EndColumn: 10, + }, + Selector: "selector", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -982,7 +784,8 @@ func TestCSSSetRuleSelector(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.SelectorList.Selectors[0].Text, result.SelectorList.Selectors[0].Text) } - resultChan = mockSocket.CSS().SetRuleSelector(&css.SetRuleSelectorParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetRuleSelector(&css.SetRuleSelectorParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), Range: &css.SourceRange{ StartLine: 10, @@ -992,40 +795,27 @@ func TestCSSSetRuleSelector(t *testing.T) { }, Selector: "selector", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetStyleSheetText(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetStyleSheetText") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().SetStyleSheetText(&css.SetStyleSheetTextParams{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - Text: "some text", - }) mockResult := &css.SetStyleSheetTextResult{ SourceMapURL: "http://sourcemap-url", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetStyleSheetText(&css.SetStyleSheetTextParams{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + Text: "some text", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1033,42 +823,23 @@ func TestCSSSetStyleSheetText(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.SourceMapURL, result.SourceMapURL) } - resultChan = mockSocket.CSS().SetStyleSheetText(&css.SetStyleSheetTextParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetStyleSheetText(&css.SetStyleSheetTextParams{ StyleSheetID: css.StyleSheetID("stylesheet-id"), Text: "some text", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSSetStyleTexts(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSSetStyleTexts") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().SetStyleTexts(&css.SetStyleTextsParams{ - Edits: []*css.StyleDeclarationEdit{{ - StyleSheetID: css.StyleSheetID("stylesheet-id"), - Range: &css.SourceRange{ - StartLine: 10, - StartColumn: 10, - EndLine: 10, - EndColumn: 10, - }, - Text: "some text", - }}, - }) mockResult := &css.SetStyleTextsResult{ Styles: []*css.Style{{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -1089,13 +860,20 @@ func TestCSSSetStyleTexts(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().SetStyleTexts(&css.SetStyleTextsParams{ + Edits: []*css.StyleDeclarationEdit{{ + StyleSheetID: css.StyleSheetID("stylesheet-id"), + Range: &css.SourceRange{ + StartLine: 10, + StartColumn: 10, + EndLine: 10, + EndColumn: 10, + }, + Text: "some text", + }}, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1103,7 +881,8 @@ func TestCSSSetStyleTexts(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Styles[0].StyleSheetID, result.Styles[0].StyleSheetID) } - resultChan = mockSocket.CSS().SetStyleTexts(&css.SetStyleTextsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().SetStyleTexts(&css.SetStyleTextsParams{ Edits: []*css.StyleDeclarationEdit{{ StyleSheetID: css.StyleSheetID("stylesheet-id"), Range: &css.SourceRange{ @@ -1115,61 +894,40 @@ func TestCSSSetStyleTexts(t *testing.T) { Text: "some text", }}, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSStartRuleUsageTracking(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSStartRuleUsageTracking") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().StartRuleUsageTracking() mockResult := &css.StartRuleUsageTrackingResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().StartRuleUsageTracking() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.CSS().StartRuleUsageTracking() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().StartRuleUsageTracking() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSStopRuleUsageTracking(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSStopRuleUsageTracking") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().StopRuleUsageTracking() mockResult := &css.StopRuleUsageTrackingResult{ RuleUsage: []*css.RuleUsage{{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -1178,13 +936,9 @@ func TestCSSStopRuleUsageTracking(t *testing.T) { Used: true, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().StopRuleUsageTracking() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1192,28 +946,20 @@ func TestCSSStopRuleUsageTracking(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.RuleUsage[0].StyleSheetID, result.RuleUsage[0].StyleSheetID) } - resultChan = mockSocket.CSS().StopRuleUsageTracking() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().StopRuleUsageTracking() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSTakeCoverageDelta(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSTakeCoverageDelta") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.CSS().TakeCoverageDelta() mockResult := &css.TakeCoverageDeltaResult{ Coverage: []*css.RuleUsage{{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -1222,13 +968,9 @@ func TestCSSTakeCoverageDelta(t *testing.T) { Used: true, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.CSS().TakeCoverageDelta() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1236,55 +978,40 @@ func TestCSSTakeCoverageDelta(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Coverage[0].StyleSheetID, result.Coverage[0].StyleSheetID) } - resultChan = mockSocket.CSS().TakeCoverageDelta() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.CSS().TakeCoverageDelta() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestCSSOnFontsUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSOnFontsUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *css.FontsUpdatedEvent) - mockSocket.CSS().OnFontsUpdated(func(eventData *css.FontsUpdatedEvent) { + soc.CSS().OnFontsUpdated(func(eventData *css.FontsUpdatedEvent) { resultChan <- eventData }) + mockResult := &css.FontsUpdatedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "CSS.fontsUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *css.FontsUpdatedEvent) - mockSocket.CSS().OnFontsUpdated(func(eventData *css.FontsUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "CSS.fontsUpdated", }) result = <-resultChan @@ -1294,39 +1021,32 @@ func TestCSSOnFontsUpdated(t *testing.T) { } func TestCSSOnMediaQueryResultChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSOnMediaQueryResultChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *css.MediaQueryResultChangedEvent) - mockSocket.CSS().OnMediaQueryResultChanged(func(eventData *css.MediaQueryResultChangedEvent) { + soc.CSS().OnMediaQueryResultChanged(func(eventData *css.MediaQueryResultChangedEvent) { resultChan <- eventData }) + mockResult := &css.MediaQueryResultChangedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "CSS.mediaQueryResultChanged", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *css.MediaQueryResultChangedEvent) - mockSocket.CSS().OnMediaQueryResultChanged(func(eventData *css.MediaQueryResultChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "CSS.mediaQueryResultChanged", }) result = <-resultChan @@ -1336,15 +1056,18 @@ func TestCSSOnMediaQueryResultChanged(t *testing.T) { } func TestCSSOnStyleSheetAdded(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSOnStyleSheetAdded") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *css.StyleSheetAddedEvent) - mockSocket.CSS().OnStyleSheetAdded(func(eventData *css.StyleSheetAddedEvent) { + soc.CSS().OnStyleSheetAdded(func(eventData *css.StyleSheetAddedEvent) { resultChan <- eventData }) + mockResult := &css.StyleSheetAddedEvent{ Header: &css.StyleSheetHeader{ StyleSheetID: css.StyleSheetID("stylesheet-id"), @@ -1361,12 +1084,10 @@ func TestCSSOnStyleSheetAdded(t *testing.T) { Length: 1, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "CSS.styleSheetAdded", - Params: mockResultBytes, }) result := <-resultChan if nil != result.Err { @@ -1376,17 +1097,9 @@ func TestCSSOnStyleSheetAdded(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Header.StyleSheetID, result.Header.StyleSheetID) } - resultChan = make(chan *css.StyleSheetAddedEvent) - mockSocket.CSS().OnStyleSheetAdded(func(eventData *css.StyleSheetAddedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "CSS.styleSheetAdded", }) result = <-resultChan @@ -1396,24 +1109,25 @@ func TestCSSOnStyleSheetAdded(t *testing.T) { } func TestCSSOnStyleSheetChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSOnStyleSheetChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *css.StyleSheetChangedEvent) - mockSocket.CSS().OnStyleSheetChanged(func(eventData *css.StyleSheetChangedEvent) { + soc.CSS().OnStyleSheetChanged(func(eventData *css.StyleSheetChangedEvent) { resultChan <- eventData }) + mockResult := &css.StyleSheetChangedEvent{ StyleSheetID: css.StyleSheetID("stylesheet-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "CSS.styleSheetChanged", - Params: mockResultBytes, }) result := <-resultChan if nil != result.Err { @@ -1423,17 +1137,9 @@ func TestCSSOnStyleSheetChanged(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.StyleSheetID, result.StyleSheetID) } - resultChan = make(chan *css.StyleSheetChangedEvent) - mockSocket.CSS().OnStyleSheetChanged(func(eventData *css.StyleSheetChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "CSS.styleSheetChanged", }) result = <-resultChan @@ -1443,24 +1149,25 @@ func TestCSSOnStyleSheetChanged(t *testing.T) { } func TestCSSOnStyleSheetRemoved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCSSOnStyleSheetRemoved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *css.StyleSheetRemovedEvent) - mockSocket.CSS().OnStyleSheetRemoved(func(eventData *css.StyleSheetRemovedEvent) { + soc.CSS().OnStyleSheetRemoved(func(eventData *css.StyleSheetRemovedEvent) { resultChan <- eventData }) + mockResult := &css.StyleSheetRemovedEvent{ StyleSheetID: css.StyleSheetID("stylesheet-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "CSS.styleSheetRemoved", - Params: mockResultBytes, }) result := <-resultChan if nil != result.Err { @@ -1470,17 +1177,9 @@ func TestCSSOnStyleSheetRemoved(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.StyleSheetID, result.StyleSheetID) } - resultChan = make(chan *css.StyleSheetRemovedEvent) - mockSocket.CSS().OnStyleSheetRemoved(func(eventData *css.StyleSheetRemovedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "CSS.styleSheetRemoved", }) result = <-resultChan diff --git a/tot/socket/cdtp.database_test.go b/tot/socket/cdtp.database_test.go index cbaa42c..d7f0efc 100644 --- a/tot/socket/cdtp.database_test.go +++ b/tot/socket/cdtp.database_test.go @@ -1,91 +1,62 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/database" ) func TestDatabaseDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDatabaseDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Database().Disable() mockResult := &database.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Database().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Database().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Database().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDatabaseEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDatabaseEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Database().Enable() mockResult := &database.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Database().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Database().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Database().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDatabaseExecuteSQL(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDatabaseExecuteSQL") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Database().ExecuteSQL(&database.ExecuteSQLParams{ - ID: database.ID("db-id"), - Query: "SELECT * FROM table_name", - }) mockResult := &database.ExecuteSQLResult{ ColumnNames: []string{"column1", "column2"}, Values: []interface{}{"value1", 2}, @@ -94,13 +65,12 @@ func TestDatabaseExecuteSQL(t *testing.T) { Message: "error message", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Database().ExecuteSQL(&database.ExecuteSQLParams{ + ID: database.ID("db-id"), + Query: "SELECT * FROM table_name", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -108,43 +78,31 @@ func TestDatabaseExecuteSQL(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.ColumnNames[0], result.ColumnNames[0]) } - resultChan = mockSocket.Database().ExecuteSQL(&database.ExecuteSQLParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Database().ExecuteSQL(&database.ExecuteSQLParams{ ID: database.ID("db-id"), Query: "SELECT * FROM table_name", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDatabaseGetTableNames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDatabaseGetTableNames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Database().GetTableNames(&database.GetTableNamesParams{ - ID: database.ID("db-id"), - }) mockResult := &database.GetTableNamesResult{ TableNames: []string{"table1", "table2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Database().GetTableNames(&database.GetTableNamesParams{ + ID: database.ID("db-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -152,33 +110,28 @@ func TestDatabaseGetTableNames(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.TableNames[0], result.TableNames[0]) } - resultChan = mockSocket.Database().GetTableNames(&database.GetTableNamesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Database().GetTableNames(&database.GetTableNamesParams{ ID: database.ID("db-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDatabaseOnAdd(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDatabaseOnAdd") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *database.AddEvent) - mockSocket.Database().OnAdd(func(eventData *database.AddEvent) { + soc.Database().OnAdd(func(eventData *database.AddEvent) { resultChan <- eventData }) + mockResult := &database.AddEvent{ Database: &database.Database{ ID: database.ID("db-id"), @@ -187,29 +140,19 @@ func TestDatabaseOnAdd(t *testing.T) { Version: "v1.0", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Database.addDatabase", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *database.AddEvent) - mockSocket.Database().OnAdd(func(eventData *database.AddEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Database.addDatabase", }) result = <-resultChan diff --git a/tot/socket/cdtp.debugger_test.go b/tot/socket/cdtp.debugger_test.go index 12d622c..d65951e 100644 --- a/tot/socket/cdtp.debugger_test.go +++ b/tot/socket/cdtp.debugger_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/debugger" @@ -10,12 +8,16 @@ import ( ) func TestDebuggerContinueToLocation(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerContinueToLocation") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().ContinueToLocation(&debugger.ContinueToLocationParams{ + mockResult := &debugger.ContinueToLocationResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().ContinueToLocation(&debugger.ContinueToLocationParams{ Location: &debugger.Location{ ScriptID: runtime.ScriptID("script-id"), LineNumber: 1, @@ -23,19 +25,12 @@ func TestDebuggerContinueToLocation(t *testing.T) { }, TargetCallFrames: debugger.TargetCallFrames.Any, }) - mockResult := &debugger.ContinueToLocationResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().ContinueToLocation(&debugger.ContinueToLocationParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().ContinueToLocation(&debugger.ContinueToLocationParams{ Location: &debugger.Location{ ScriptID: runtime.ScriptID("script-id"), LineNumber: 1, @@ -43,104 +38,62 @@ func TestDebuggerContinueToLocation(t *testing.T) { }, TargetCallFrames: debugger.TargetCallFrames.Any, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().Disable() mockResult := &debugger.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().Enable() mockResult := &debugger.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerEvaluateOnCallFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerEvaluateOnCallFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().EvaluateOnCallFrame(&debugger.EvaluateOnCallFrameParams{ - CallFrameID: debugger.CallFrameID("call-frame-id"), - Expression: "expression", - ObjectGroup: "object-group", - IncludeCommandLineAPI: true, - Silent: true, - ReturnByValue: true, - GeneratePreview: true, - ThrowOnSideEffect: true, - }) mockResult := &debugger.EvaluateOnCallFrameResult{ Result: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -174,13 +127,18 @@ func TestDebuggerEvaluateOnCallFrame(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().EvaluateOnCallFrame(&debugger.EvaluateOnCallFrameParams{ + CallFrameID: debugger.CallFrameID("call-frame-id"), + Expression: "expression", + ObjectGroup: "object-group", + IncludeCommandLineAPI: true, + Silent: true, + ReturnByValue: true, + GeneratePreview: true, + ThrowOnSideEffect: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -188,7 +146,8 @@ func TestDebuggerEvaluateOnCallFrame(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Result.Type, result.Result.Type) } - resultChan = mockSocket.Debugger().EvaluateOnCallFrame(&debugger.EvaluateOnCallFrameParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().EvaluateOnCallFrame(&debugger.EvaluateOnCallFrameParams{ CallFrameID: debugger.CallFrameID("call-frame-id"), Expression: "expression", ObjectGroup: "object-group", @@ -198,27 +157,29 @@ func TestDebuggerEvaluateOnCallFrame(t *testing.T) { GeneratePreview: true, ThrowOnSideEffect: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerGetPossibleBreakpoints(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerGetPossibleBreakpoints") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().GetPossibleBreakpoints(&debugger.GetPossibleBreakpointsParams{ + mockResult := &debugger.GetPossibleBreakpointsResult{ + Locations: []*debugger.BreakLocation{{ + ScriptID: runtime.ScriptID("script-id"), + LineNumber: 1, + ColumnNumber: 1, + Type: debugger.BreakLocationType.DebuggerStatement, + }}, + } + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().GetPossibleBreakpoints(&debugger.GetPossibleBreakpointsParams{ Start: &debugger.Location{ ScriptID: runtime.ScriptID("script-id"), LineNumber: 1, @@ -231,21 +192,6 @@ func TestDebuggerGetPossibleBreakpoints(t *testing.T) { }, RestrictToFunction: true, }) - mockResult := &debugger.GetPossibleBreakpointsResult{ - Locations: []*debugger.BreakLocation{{ - ScriptID: runtime.ScriptID("script-id"), - LineNumber: 1, - ColumnNumber: 1, - Type: debugger.BreakLocationType.DebuggerStatement, - }}, - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -253,7 +199,8 @@ func TestDebuggerGetPossibleBreakpoints(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Locations[0].ScriptID, result.Locations[0].ScriptID) } - resultChan = mockSocket.Debugger().GetPossibleBreakpoints(&debugger.GetPossibleBreakpointsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().GetPossibleBreakpoints(&debugger.GetPossibleBreakpointsParams{ Start: &debugger.Location{ ScriptID: runtime.ScriptID("script-id"), LineNumber: 1, @@ -266,39 +213,26 @@ func TestDebuggerGetPossibleBreakpoints(t *testing.T) { }, RestrictToFunction: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerGetScriptSource(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerGetScriptSource") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().GetScriptSource(&debugger.GetScriptSourceParams{ - ScriptID: runtime.ScriptID("script-id"), - }) mockResult := &debugger.GetScriptSourceResult{ ScriptSource: "script-source", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().GetScriptSource(&debugger.GetScriptSourceParams{ + ScriptID: runtime.ScriptID("script-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -306,35 +240,22 @@ func TestDebuggerGetScriptSource(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.ScriptSource, result.ScriptSource) } - resultChan = mockSocket.Debugger().GetScriptSource(&debugger.GetScriptSourceParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().GetScriptSource(&debugger.GetScriptSourceParams{ ScriptID: runtime.ScriptID("script-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerGetStackTrace(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerGetStackTrace") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().GetStackTrace(&debugger.GetStackTraceParams{ - StackTraceID: runtime.StackTraceID{ - ID: "stack-trace-id", - DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), - }, - }) mockResult := &debugger.GetStackTraceResult{ StackTrace: &runtime.StackTrace{ Description: "description", @@ -346,13 +267,14 @@ func TestDebuggerGetStackTrace(t *testing.T) { }, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().GetStackTrace(&debugger.GetStackTraceParams{ + StackTraceID: runtime.StackTraceID{ + ID: "stack-trace-id", + DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), + }, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -360,151 +282,105 @@ func TestDebuggerGetStackTrace(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.StackTrace.Description, result.StackTrace.Description) } - resultChan = mockSocket.Debugger().GetStackTrace(&debugger.GetStackTraceParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().GetStackTrace(&debugger.GetStackTraceParams{ StackTraceID: runtime.StackTraceID{ ID: "stack-trace-id", DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerPause(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerPause") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().Pause() mockResult := &debugger.PauseResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().Pause() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().Pause() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().Pause() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerPauseOnAsyncCall(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerPauseOnAsyncCall") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().PauseOnAsyncCall(&debugger.PauseOnAsyncCallParams{ + mockResult := &debugger.PauseOnAsyncCallResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().PauseOnAsyncCall(&debugger.PauseOnAsyncCallParams{ ParentStackTraceID: runtime.StackTraceID{ ID: "stack-trace-id", DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), }, }) - mockResult := &debugger.PauseOnAsyncCallResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().PauseOnAsyncCall(&debugger.PauseOnAsyncCallParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().PauseOnAsyncCall(&debugger.PauseOnAsyncCallParams{ ParentStackTraceID: runtime.StackTraceID{ ID: "stack-trace-id", DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerRemoveBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerRemoveBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().RemoveBreakpoint(&debugger.RemoveBreakpointParams{ - BreakpointID: debugger.BreakpointID("breakpoint-id"), - }) mockResult := &debugger.RemoveBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().RemoveBreakpoint(&debugger.RemoveBreakpointParams{ + BreakpointID: debugger.BreakpointID("breakpoint-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().RemoveBreakpoint(&debugger.RemoveBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().RemoveBreakpoint(&debugger.RemoveBreakpointParams{ BreakpointID: debugger.BreakpointID("breakpoint-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerRestartFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerRestartFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().RestartFrame(&debugger.RestartFrameParams{ - CallFrameID: debugger.CallFrameID("call-frame-id"), - }) mockResult := &debugger.RestartFrameResult{ CallFrames: []*debugger.CallFrame{{ CallFrameID: debugger.CallFrameID("call-frame-id"), @@ -550,13 +426,11 @@ func TestDebuggerRestartFrame(t *testing.T) { DebuggerID: runtime.UniqueDebuggerID("unique-debugger-id"), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().RestartFrame(&debugger.RestartFrameParams{ + CallFrameID: debugger.CallFrameID("call-frame-id"), }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -564,116 +438,80 @@ func TestDebuggerRestartFrame(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.CallFrames[0].CallFrameID, result.CallFrames[0].CallFrameID) } - resultChan = mockSocket.Debugger().RestartFrame(&debugger.RestartFrameParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().RestartFrame(&debugger.RestartFrameParams{ CallFrameID: debugger.CallFrameID("call-frame-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerResume(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerResume") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().Resume() mockResult := &debugger.ResumeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().Resume() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().Resume() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().Resume() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerScheduleStepIntoAsync(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerScheduleStepIntoAsync") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().ScheduleStepIntoAsync() mockResult := &debugger.ScheduleStepIntoAsyncResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().ScheduleStepIntoAsync() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().ScheduleStepIntoAsync() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().ScheduleStepIntoAsync() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSearchInContent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSearchInContent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SearchInContent(&debugger.SearchInContentParams{ - ScriptID: runtime.ScriptID("script-id"), - Query: "search string", - CaseSensitive: true, - IsRegex: true, - }) mockResult := &debugger.SearchInContentResult{ Result: []*debugger.SearchMatch{{ LineNumber: 1, LineContent: "line with search string in it", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SearchInContent(&debugger.SearchInContentParams{ + ScriptID: runtime.ScriptID("script-id"), + Query: "search string", + CaseSensitive: true, + IsRegex: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -681,162 +519,111 @@ func TestDebuggerSearchInContent(t *testing.T) { t.Errorf("Expected '%d', got '%d'", mockResult.Result[0].LineNumber, result.Result[0].LineNumber) } - resultChan = mockSocket.Debugger().SearchInContent(&debugger.SearchInContentParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SearchInContent(&debugger.SearchInContentParams{ ScriptID: runtime.ScriptID("script-id"), Query: "search string", CaseSensitive: true, IsRegex: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetAsyncCallStackDepth(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetAsyncCallStackDepth") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetAsyncCallStackDepth(&debugger.SetAsyncCallStackDepthParams{ - MaxDepth: 1, - }) mockResult := &debugger.SetAsyncCallStackDepthResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetAsyncCallStackDepth(&debugger.SetAsyncCallStackDepthParams{ + MaxDepth: 1, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetAsyncCallStackDepth(&debugger.SetAsyncCallStackDepthParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetAsyncCallStackDepth(&debugger.SetAsyncCallStackDepthParams{ MaxDepth: 1, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetBlackboxPatterns(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetBlackboxPatterns") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetBlackboxPatterns(&debugger.SetBlackboxPatternsParams{ - Patterns: []string{"pattern 1", "pattern 2"}, - }) mockResult := &debugger.SetBlackboxPatternsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetBlackboxPatterns(&debugger.SetBlackboxPatternsParams{ + Patterns: []string{"pattern 1", "pattern 2"}, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetBlackboxPatterns(&debugger.SetBlackboxPatternsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetBlackboxPatterns(&debugger.SetBlackboxPatternsParams{ Patterns: []string{"pattern 1", "pattern 2"}, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetBlackboxedRanges(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetBlackboxedRanges") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.SetBlackboxedRangesResult{} - resultChan := mockSocket.Debugger().SetBlackboxedRanges(&debugger.SetBlackboxedRangesParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetBlackboxedRanges(&debugger.SetBlackboxedRangesParams{ ScriptID: runtime.ScriptID("script-id"), Positions: []*debugger.ScriptPosition{{ LineNumber: 1, ColumnNumber: 1, }}, }) - mockResult := &debugger.SetBlackboxedRangesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetBlackboxedRanges(&debugger.SetBlackboxedRangesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetBlackboxedRanges(&debugger.SetBlackboxedRangesParams{ ScriptID: runtime.ScriptID("script-id"), Positions: []*debugger.ScriptPosition{{ LineNumber: 1, ColumnNumber: 1, }}, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetBreakpoint(&debugger.SetBreakpointParams{ - Location: &debugger.Location{ - ScriptID: runtime.ScriptID("script-id"), - LineNumber: 1, - ColumnNumber: 1, - }, - Condition: "breakpoint-condition", - }) mockResult := &debugger.SetBreakpointResult{ BreakpointID: debugger.BreakpointID("breakpoint-id"), ActualLocation: &debugger.Location{ @@ -845,13 +632,16 @@ func TestDebuggerSetBreakpoint(t *testing.T) { ColumnNumber: 4, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetBreakpoint(&debugger.SetBreakpointParams{ + Location: &debugger.Location{ + ScriptID: runtime.ScriptID("script-id"), + LineNumber: 1, + ColumnNumber: 1, + }, + Condition: "breakpoint-condition", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -859,7 +649,8 @@ func TestDebuggerSetBreakpoint(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.BreakpointID, result.BreakpointID) } - resultChan = mockSocket.Debugger().SetBreakpoint(&debugger.SetBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetBreakpoint(&debugger.SetBreakpointParams{ Location: &debugger.Location{ ScriptID: runtime.ScriptID("script-id"), LineNumber: 1, @@ -867,34 +658,18 @@ func TestDebuggerSetBreakpoint(t *testing.T) { }, Condition: "breakpoint-condition", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetBreakpointByURL(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetBreakpointByURL") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetBreakpointByURL(&debugger.SetBreakpointByURLParams{ - LineNumber: 1, - URL: "http://some.url", - URLRegex: "some regex", - ScriptHash: "some hash", - ColumnNumber: 1, - Condition: "some condition", - }) mockResult := &debugger.SetBreakpointByURLResult{ BreakpointID: debugger.BreakpointID("breakpoint-id"), Locations: []*debugger.Location{{ @@ -903,13 +678,16 @@ func TestDebuggerSetBreakpointByURL(t *testing.T) { ColumnNumber: 4, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetBreakpointByURL(&debugger.SetBreakpointByURLParams{ + LineNumber: 1, + URL: "http://some.url", + URLRegex: "some regex", + ScriptHash: "some hash", + ColumnNumber: 1, + Condition: "some condition", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -917,7 +695,8 @@ func TestDebuggerSetBreakpointByURL(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.BreakpointID, result.BreakpointID) } - resultChan = mockSocket.Debugger().SetBreakpointByURL(&debugger.SetBreakpointByURLParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetBreakpointByURL(&debugger.SetBreakpointByURLParams{ LineNumber: 1, URL: "http://some.url", URLRegex: "some regex", @@ -925,153 +704,104 @@ func TestDebuggerSetBreakpointByURL(t *testing.T) { ColumnNumber: 1, Condition: "some condition", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetBreakpointsActive(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetBreakpointsActive") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetBreakpointsActive(&debugger.SetBreakpointsActiveParams{ - Active: true, - }) mockResult := &debugger.SetBreakpointsActiveResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetBreakpointsActive(&debugger.SetBreakpointsActiveParams{ + Active: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetBreakpointsActive(&debugger.SetBreakpointsActiveParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetBreakpointsActive(&debugger.SetBreakpointsActiveParams{ Active: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetPauseOnExceptions(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetPauseOnExceptions") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetPauseOnExceptions(&debugger.SetPauseOnExceptionsParams{ - State: debugger.State.None, - }) mockResult := &debugger.SetPauseOnExceptionsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetPauseOnExceptions(&debugger.SetPauseOnExceptionsParams{ + State: debugger.State.None, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetPauseOnExceptions(&debugger.SetPauseOnExceptionsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetPauseOnExceptions(&debugger.SetPauseOnExceptionsParams{ State: debugger.State.None, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetReturnValue(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetReturnValue") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.SetReturnValueResult{} - resultChan := mockSocket.Debugger().SetReturnValue(&debugger.SetReturnValueParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetReturnValue(&debugger.SetReturnValueParams{ NewValue: &runtime.CallArgument{ Value: "some-value", UnserializableValue: runtime.UnserializableValue.Infinity, ObjectID: runtime.RemoteObjectID("remote-object-id"), }, }) - mockResult := &debugger.SetReturnValueResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetReturnValue(&debugger.SetReturnValueParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetReturnValue(&debugger.SetReturnValueParams{ NewValue: &runtime.CallArgument{ Value: "some-value", UnserializableValue: runtime.UnserializableValue.Infinity, ObjectID: runtime.RemoteObjectID("remote-object-id"), }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetScriptSource(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetScriptSource") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetScriptSource(&debugger.SetScriptSourceParams{ - ScriptID: runtime.ScriptID("script-id"), - ScriptSource: "http://script.source", - DryRun: true, - }) mockResult := &debugger.SetScriptSourceResult{ CallFrames: []*debugger.CallFrame{{ CallFrameID: debugger.CallFrameID("call-frame-id"), @@ -1139,13 +869,13 @@ func TestDebuggerSetScriptSource(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetScriptSource(&debugger.SetScriptSourceParams{ + ScriptID: runtime.ScriptID("script-id"), + ScriptSource: "http://script.source", + DryRun: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1153,70 +883,54 @@ func TestDebuggerSetScriptSource(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.CallFrames[0].CallFrameID, result.CallFrames[0].CallFrameID) } - resultChan = mockSocket.Debugger().SetScriptSource(&debugger.SetScriptSourceParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetScriptSource(&debugger.SetScriptSourceParams{ ScriptID: runtime.ScriptID("script-id"), ScriptSource: "http://script.source", DryRun: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetSkipAllPauses(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetSkipAllPauses") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().SetSkipAllPauses(&debugger.SetSkipAllPausesParams{ - Skip: true, - }) mockResult := &debugger.SetSkipAllPausesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetSkipAllPauses(&debugger.SetSkipAllPausesParams{ + Skip: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetSkipAllPauses(&debugger.SetSkipAllPausesParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetSkipAllPauses(&debugger.SetSkipAllPausesParams{ Skip: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerSetVariableValue(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerSetVariableValue") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.SetVariableValueResult{} - resultChan := mockSocket.Debugger().SetVariableValue(&debugger.SetVariableValueParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().SetVariableValue(&debugger.SetVariableValueParams{ ScopeNumber: 1, VariableName: "varname", NewValue: &runtime.CallArgument{ @@ -1226,19 +940,12 @@ func TestDebuggerSetVariableValue(t *testing.T) { }, CallFrameID: debugger.CallFrameID("call-frame-id"), }) - mockResult := &debugger.SetVariableValueResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().SetVariableValue(&debugger.SetVariableValueParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().SetVariableValue(&debugger.SetVariableValueParams{ ScopeNumber: 1, VariableName: "varname", NewValue: &runtime.CallArgument{ @@ -1248,136 +955,94 @@ func TestDebuggerSetVariableValue(t *testing.T) { }, CallFrameID: debugger.CallFrameID("call-frame-id"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerStepInto(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerStepInto") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().StepInto(&debugger.StepIntoParams{ - BreakOnAsyncCall: true, - }) mockResult := &debugger.StepIntoResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().StepInto(&debugger.StepIntoParams{ + BreakOnAsyncCall: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().StepInto(&debugger.StepIntoParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().StepInto(&debugger.StepIntoParams{ BreakOnAsyncCall: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerStepOut(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerStepOut") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().StepOut() mockResult := &debugger.StepOutResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().StepOut() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().StepOut() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().StepOut() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerStepOver(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerStepOver") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Debugger().StepOver() mockResult := &debugger.StepOverResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Debugger().StepOver() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Debugger().StepOver() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Debugger().StepOver() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDebuggerOnBreakpointResolved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerOnBreakpointResolved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *debugger.BreakpointResolvedEvent) - mockSocket.Debugger().OnBreakpointResolved(func(eventData *debugger.BreakpointResolvedEvent) { + soc.Debugger().OnBreakpointResolved(func(eventData *debugger.BreakpointResolvedEvent) { resultChan <- eventData }) + mockResult := &debugger.BreakpointResolvedEvent{ BreakpointID: debugger.BreakpointID("breakpoint-id"), Location: &debugger.Location{ @@ -1386,29 +1051,19 @@ func TestDebuggerOnBreakpointResolved(t *testing.T) { ColumnNumber: 1, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Debugger.breakpointResolved", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *debugger.BreakpointResolvedEvent) - mockSocket.Debugger().OnBreakpointResolved(func(eventData *debugger.BreakpointResolvedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Debugger.breakpointResolved", }) result = <-resultChan @@ -1418,15 +1073,18 @@ func TestDebuggerOnBreakpointResolved(t *testing.T) { } func TestDebuggerOnPaused(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerOnPaused") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *debugger.PausedEvent) - mockSocket.Debugger().OnPaused(func(eventData *debugger.PausedEvent) { + soc.Debugger().OnPaused(func(eventData *debugger.PausedEvent) { resultChan <- eventData }) + mockResult := &debugger.PausedEvent{ CallFrames: []*debugger.CallFrame{{ CallFrameID: debugger.CallFrameID("call-frame-id"), @@ -1438,29 +1096,19 @@ func TestDebuggerOnPaused(t *testing.T) { AsyncStackTraceID: &runtime.StackTraceID{}, AsyncCallStackTraceID: &runtime.StackTraceID{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Debugger.paused", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *debugger.PausedEvent) - mockSocket.Debugger().OnPaused(func(eventData *debugger.PausedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Debugger.paused", }) result = <-resultChan @@ -1470,39 +1118,32 @@ func TestDebuggerOnPaused(t *testing.T) { } func TestDebuggerOnResumed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerOnResumed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *debugger.ResumedEvent) - mockSocket.Debugger().OnResumed(func(eventData *debugger.ResumedEvent) { + soc.Debugger().OnResumed(func(eventData *debugger.ResumedEvent) { resultChan <- eventData }) + mockResult := &debugger.ResumedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Debugger.resumed", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *debugger.ResumedEvent) - mockSocket.Debugger().OnResumed(func(eventData *debugger.ResumedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Debugger.resumed", }) result = <-resultChan @@ -1512,24 +1153,27 @@ func TestDebuggerOnResumed(t *testing.T) { } func TestDebuggerOnScriptFailedToParse(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerOnScriptFailedToParse") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *debugger.ScriptFailedToParseEvent) - mockSocket.Debugger().OnScriptFailedToParse(func(eventData *debugger.ScriptFailedToParseEvent) { + soc.Debugger().OnScriptFailedToParse(func(eventData *debugger.ScriptFailedToParseEvent) { resultChan <- eventData }) + mockResult := &debugger.ScriptFailedToParseEvent{ - ScriptID: runtime.ScriptID("script-id"), - URL: "http://script.url", - StartLine: 1, - StartColumn: 1, - EndLine: 2, - EndColumn: 10, - ExecutionContextID: runtime.ExecutionContextID(1), - Hash: "some hash", + ScriptID: runtime.ScriptID("script-id"), + URL: "http://script.url", + StartLine: 1, + StartColumn: 1, + EndLine: 2, + EndColumn: 10, + ExecutionContextID: runtime.ExecutionContextID(1), + Hash: "some hash", ExecutionContextAuxData: map[string]string{"key": "value"}, SourceMapURL: "http://source-map.url", HasSourceURL: true, @@ -1537,29 +1181,19 @@ func TestDebuggerOnScriptFailedToParse(t *testing.T) { Length: 1, StackTrace: &runtime.StackTrace{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Debugger.scriptFailedToParse", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *debugger.ScriptFailedToParseEvent) - mockSocket.Debugger().OnScriptFailedToParse(func(eventData *debugger.ScriptFailedToParseEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Debugger.scriptFailedToParse", }) result = <-resultChan @@ -1569,24 +1203,27 @@ func TestDebuggerOnScriptFailedToParse(t *testing.T) { } func TestDebuggerOnScriptParsed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDebuggerOnScriptParsed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *debugger.ScriptParsedEvent) - mockSocket.Debugger().OnScriptParsed(func(eventData *debugger.ScriptParsedEvent) { + soc.Debugger().OnScriptParsed(func(eventData *debugger.ScriptParsedEvent) { resultChan <- eventData }) + mockResult := &debugger.ScriptParsedEvent{ - ScriptID: runtime.ScriptID("script-id"), - URL: "http://script.url", - StartLine: 1, - StartColumn: 1, - EndLine: 2, - EndColumn: 10, - ExecutionContextID: runtime.ExecutionContextID(1), - Hash: "some hash", + ScriptID: runtime.ScriptID("script-id"), + URL: "http://script.url", + StartLine: 1, + StartColumn: 1, + EndLine: 2, + EndColumn: 10, + ExecutionContextID: runtime.ExecutionContextID(1), + Hash: "some hash", ExecutionContextAuxData: map[string]string{"key": "value"}, IsLiveEdit: true, SourceMapURL: "http://source-map.url", @@ -1595,29 +1232,19 @@ func TestDebuggerOnScriptParsed(t *testing.T) { Length: 1, StackTrace: &runtime.StackTrace{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Debugger.scriptParsed", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *debugger.ScriptParsedEvent) - mockSocket.Debugger().OnScriptParsed(func(eventData *debugger.ScriptParsedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Debugger.scriptParsed", }) result = <-resultChan diff --git a/tot/socket/cdtp.device.orientation_test.go b/tot/socket/cdtp.device.orientation_test.go index 40ba0cd..ba53435 100644 --- a/tot/socket/cdtp.device.orientation_test.go +++ b/tot/socket/cdtp.device.orientation_test.go @@ -1,84 +1,58 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/device/orientation" ) func TestDeviceOrientationClearOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDeviceOrientationClearOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DeviceOrientation().ClearOverride() mockResult := &orientation.ClearOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DeviceOrientation().ClearOverride() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DeviceOrientation().ClearOverride() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DeviceOrientation().ClearOverride() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDeviceOrientationSetOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDeviceOrientationSetOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &orientation.SetOverrideResult{} - resultChan := mockSocket.DeviceOrientation().SetOverride(&orientation.SetOverrideParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DeviceOrientation().SetOverride(&orientation.SetOverrideParams{ Alpha: 1, Beta: 1, Gamma: 1, }) - mockResult := &orientation.SetOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DeviceOrientation().SetOverride(&orientation.SetOverrideParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DeviceOrientation().SetOverride(&orientation.SetOverrideParams{ Alpha: 1, Beta: 1, Gamma: 1, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.dom.debugger_test.go b/tot/socket/cdtp.dom.debugger_test.go index efe187f..89ee6b2 100644 --- a/tot/socket/cdtp.dom.debugger_test.go +++ b/tot/socket/cdtp.dom.debugger_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom" @@ -11,16 +9,12 @@ import ( ) func TestDOMDebuggerGetEventListeners(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerGetEventListeners") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().GetEventListeners(&debugger.GetEventListenersParams{ - ObjectID: runtime.RemoteObjectID("remote-object-id"), - Depth: 1, - Pierce: true, - }) mockResult := &debugger.GetEventListenersResult{ Listeners: []*debugger.EventListener{{ Type: "listener-type", @@ -39,13 +33,13 @@ func TestDOMDebuggerGetEventListeners(t *testing.T) { BackendNodeID: dom.BackendNodeID(1), }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().GetEventListeners(&debugger.GetEventListenersParams{ + ObjectID: runtime.RemoteObjectID("remote-object-id"), + Depth: 1, + Pierce: true, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -53,332 +47,228 @@ func TestDOMDebuggerGetEventListeners(t *testing.T) { t.Errorf("Expected '%d', got '%d'", mockResult.Listeners[0].BackendNodeID, result.Listeners[0].BackendNodeID) } - resultChan = mockSocket.DOMDebugger().GetEventListeners(&debugger.GetEventListenersParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().GetEventListeners(&debugger.GetEventListenersParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), Depth: 1, Pierce: true, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerRemoveDOMBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerRemoveDOMBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.RemoveDOMBreakpointResult{} - resultChan := mockSocket.DOMDebugger().RemoveDOMBreakpoint(&debugger.RemoveDOMBreakpointParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().RemoveDOMBreakpoint(&debugger.RemoveDOMBreakpointParams{ NodeID: dom.NodeID(1), Type: debugger.DOMBreakpointType("breakpoint type"), }) - mockResult := &debugger.RemoveDOMBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().RemoveDOMBreakpoint(&debugger.RemoveDOMBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().RemoveDOMBreakpoint(&debugger.RemoveDOMBreakpointParams{ NodeID: dom.NodeID(1), Type: debugger.DOMBreakpointType("breakpoint type"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerRemoveEventListenerBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerRemoveEventListenerBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.RemoveEventListenerBreakpointResult{} - resultChan := mockSocket.DOMDebugger().RemoveEventListenerBreakpoint(&debugger.RemoveEventListenerBreakpointParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().RemoveEventListenerBreakpoint(&debugger.RemoveEventListenerBreakpointParams{ EventName: "event name", TargetName: "target name", }) - mockResult := &debugger.RemoveEventListenerBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().RemoveEventListenerBreakpoint(&debugger.RemoveEventListenerBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().RemoveEventListenerBreakpoint(&debugger.RemoveEventListenerBreakpointParams{ EventName: "event name", TargetName: "target name", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerRemoveInstrumentationBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerRemoveInstrumentationBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().RemoveInstrumentationBreakpoint(&debugger.RemoveInstrumentationBreakpointParams{ - EventName: "event name", - }) mockResult := &debugger.RemoveInstrumentationBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().RemoveInstrumentationBreakpoint(&debugger.RemoveInstrumentationBreakpointParams{ + EventName: "event name", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().RemoveInstrumentationBreakpoint(&debugger.RemoveInstrumentationBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().RemoveInstrumentationBreakpoint(&debugger.RemoveInstrumentationBreakpointParams{ EventName: "event name", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerRemoveXHRBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerRemoveXHRBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().RemoveXHRBreakpoint(&debugger.RemoveXHRBreakpointParams{ - URL: "http://xhr.url", - }) mockResult := &debugger.RemoveXHRBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().RemoveXHRBreakpoint(&debugger.RemoveXHRBreakpointParams{ + URL: "http://xhr.url", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().RemoveXHRBreakpoint(&debugger.RemoveXHRBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().RemoveXHRBreakpoint(&debugger.RemoveXHRBreakpointParams{ URL: "http://xhr.url", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerSetDOMBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerSetDOMBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &debugger.SetDOMBreakpointResult{} - resultChan := mockSocket.DOMDebugger().SetDOMBreakpoint(&debugger.SetDOMBreakpointParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().SetDOMBreakpoint(&debugger.SetDOMBreakpointParams{ NodeID: dom.NodeID(1), Type: debugger.DOMBreakpointType("breakpoint type"), }) - mockResult := &debugger.SetDOMBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().SetDOMBreakpoint(&debugger.SetDOMBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().SetDOMBreakpoint(&debugger.SetDOMBreakpointParams{ NodeID: dom.NodeID(1), Type: debugger.DOMBreakpointType("breakpoint type"), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerSetEventListenerBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerSetEventListenerBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().SetEventListenerBreakpoint(&debugger.SetEventListenerBreakpointParams{ + mockResult := &debugger.SetEventListenerBreakpointResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().SetEventListenerBreakpoint(&debugger.SetEventListenerBreakpointParams{ EventName: "event name", TargetName: "target name", }) - mockResult := &debugger.SetEventListenerBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().SetEventListenerBreakpoint(&debugger.SetEventListenerBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().SetEventListenerBreakpoint(&debugger.SetEventListenerBreakpointParams{ EventName: "event name", TargetName: "target name", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerSetInstrumentationBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerSetInstrumentationBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().SetInstrumentationBreakpoint(&debugger.SetInstrumentationBreakpointParams{ - EventName: "event name", - }) mockResult := &debugger.SetInstrumentationBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().SetInstrumentationBreakpoint(&debugger.SetInstrumentationBreakpointParams{ + EventName: "event name", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().SetInstrumentationBreakpoint(&debugger.SetInstrumentationBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().SetInstrumentationBreakpoint(&debugger.SetInstrumentationBreakpointParams{ EventName: "event name", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDebuggerSetXHRBreakpoint(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDebuggerSetXHRBreakpoint") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMDebugger().SetXHRBreakpoint(&debugger.SetXHRBreakpointParams{ - URL: "http://xhr.url", - }) mockResult := &debugger.SetXHRBreakpointResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMDebugger().SetXHRBreakpoint(&debugger.SetXHRBreakpointParams{ + URL: "http://xhr.url", }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMDebugger().SetXHRBreakpoint(&debugger.SetXHRBreakpointParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMDebugger().SetXHRBreakpoint(&debugger.SetXHRBreakpointParams{ URL: "http://xhr.url", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.dom.snapshot_test.go b/tot/socket/cdtp.dom.snapshot_test.go index 21c4a93..8ec3a89 100644 --- a/tot/socket/cdtp.dom.snapshot_test.go +++ b/tot/socket/cdtp.dom.snapshot_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom" @@ -11,82 +9,56 @@ import ( ) func TestDOMSnapshotDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSnapshotDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMSnapshot().Disable() mockResult := &snapshot.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMSnapshot().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMSnapshot().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMSnapshot().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSnapshotEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSnapshotEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMSnapshot().Enable() mockResult := &snapshot.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMSnapshot().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMSnapshot().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMSnapshot().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSnapshotGet(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSnapshotGet") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMSnapshot().Get(&snapshot.GetParams{ - ComputedStyleWhitelist: []string{"one", "two"}, - }) mockResult := &snapshot.GetResult{ DOMNodes: []*snapshot.DOMNode{{ NodeType: 1, @@ -142,13 +114,11 @@ func TestDOMSnapshotGet(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMSnapshot().Get(&snapshot.GetParams{ + ComputedStyleWhitelist: []string{"one", "two"}, }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -156,18 +126,10 @@ func TestDOMSnapshotGet(t *testing.T) { t.Errorf("Expected '%d', got '%d'", mockResult.DOMNodes[0].NodeType, result.DOMNodes[0].NodeType) } - resultChan = mockSocket.DOMSnapshot().Get(&snapshot.GetParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMSnapshot().Get(&snapshot.GetParams{ ComputedStyleWhitelist: []string{"one", "two"}, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.dom.storage_test.go b/tot/socket/cdtp.dom.storage_test.go index 4296c51..baf8848 100644 --- a/tot/socket/cdtp.dom.storage_test.go +++ b/tot/socket/cdtp.dom.storage_test.go @@ -1,147 +1,105 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom/storage" ) func TestDOMStorageClear(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageClear") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMStorage().Clear(&storage.ClearParams{ + mockResult := &storage.ClearResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().Clear(&storage.ClearParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, }) - mockResult := &storage.ClearResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMStorage().Clear(&storage.ClearParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().Clear(&storage.ClearParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMStorage().Disable() mockResult := &storage.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMStorage().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMStorage().Enable() mockResult := &storage.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMStorage().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageGetItems(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageGetItems") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &storage.GetItemsResult{ + Entries: []storage.Item{{float64(1), "two"}}, + } - resultChan := mockSocket.DOMStorage().GetItems(&storage.GetItemsParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().GetItems(&storage.GetItemsParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, }) - mockResult := &storage.GetItemsResult{ - Entries: []storage.Item{{float64(1), "two"}}, - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -152,79 +110,63 @@ func TestDOMStorageGetItems(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Entries[0][0], result.Entries[0][0]) } - resultChan = mockSocket.DOMStorage().GetItems(&storage.GetItemsParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().GetItems(&storage.GetItemsParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageRemoveItem(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageRemoveItem") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOMStorage().RemoveItem(&storage.RemoveItemParams{ + mockResult := &storage.RemoveItemResult{} + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().RemoveItem(&storage.RemoveItemParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, Key: "item-key", }) - mockResult := &storage.RemoveItemResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMStorage().RemoveItem(&storage.RemoveItemParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().RemoveItem(&storage.RemoveItemParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, Key: "item-key", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageSetItem(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageSetItem") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + mockResult := &storage.SetItemResult{} - resultChan := mockSocket.DOMStorage().SetItem(&storage.SetItemParams{ + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOMStorage().SetItem(&storage.SetItemParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, @@ -232,49 +174,37 @@ func TestDOMStorageSetItem(t *testing.T) { Key: "item-key", Value: "item value", }) - mockResult := &storage.SetItemResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOMStorage().SetItem(&storage.SetItemParams{ + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOMStorage().SetItem(&storage.SetItemParams{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, Key: "item-key", }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMStorageOnItemAdded(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageOnItemAdded") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.ItemAddedEvent) - mockSocket.DOMStorage().OnItemAdded(func(eventData *storage.ItemAddedEvent) { + soc.DOMStorage().OnItemAdded(func(eventData *storage.ItemAddedEvent) { resultChan <- eventData }) + mockResult := &storage.ItemAddedEvent{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", @@ -283,29 +213,19 @@ func TestDOMStorageOnItemAdded(t *testing.T) { Key: "item-key", NewValue: "item value", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOMStorage.domStorageItemAdded", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *storage.ItemAddedEvent) - mockSocket.DOMStorage().OnItemAdded(func(eventData *storage.ItemAddedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOMStorage.domStorageItemAdded", }) result = <-resultChan @@ -315,15 +235,18 @@ func TestDOMStorageOnItemAdded(t *testing.T) { } func TestDOMStorageOnItemRemoved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageOnItemRemoved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.ItemRemovedEvent) - mockSocket.DOMStorage().OnItemRemoved(func(eventData *storage.ItemRemovedEvent) { + soc.DOMStorage().OnItemRemoved(func(eventData *storage.ItemRemovedEvent) { resultChan <- eventData }) + mockResult := &storage.ItemRemovedEvent{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", @@ -331,29 +254,19 @@ func TestDOMStorageOnItemRemoved(t *testing.T) { }, Key: "item-key", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOMStorage.domStorageItemRemoved", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *storage.ItemRemovedEvent) - mockSocket.DOMStorage().OnItemRemoved(func(eventData *storage.ItemRemovedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOMStorage.domStorageItemRemoved", }) result = <-resultChan @@ -363,15 +276,18 @@ func TestDOMStorageOnItemRemoved(t *testing.T) { } func TestDOMStorageOnItemUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageOnItemUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.ItemUpdatedEvent) - mockSocket.DOMStorage().OnItemUpdated(func(eventData *storage.ItemUpdatedEvent) { + soc.DOMStorage().OnItemUpdated(func(eventData *storage.ItemUpdatedEvent) { resultChan <- eventData }) + mockResult := &storage.ItemUpdatedEvent{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", @@ -381,29 +297,19 @@ func TestDOMStorageOnItemUpdated(t *testing.T) { OldValue: "old-value", NewValue: "new-value", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOMStorage.domStorageItemUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *storage.ItemUpdatedEvent) - mockSocket.DOMStorage().OnItemUpdated(func(eventData *storage.ItemUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOMStorage.domStorageItemUpdated", }) result = <-resultChan @@ -413,44 +319,37 @@ func TestDOMStorageOnItemUpdated(t *testing.T) { } func TestDOMStorageOnItemsCleared(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMStorageOnItemsCleared") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.ItemsClearedEvent) - mockSocket.DOMStorage().OnItemsCleared(func(eventData *storage.ItemsClearedEvent) { + soc.DOMStorage().OnItemsCleared(func(eventData *storage.ItemsClearedEvent) { resultChan <- eventData }) + mockResult := &storage.ItemsClearedEvent{ StorageID: &storage.ID{ SecurityOrigin: "security-origin", IsLocalStorage: true, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOMStorage.domStorageItemsCleared", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *storage.ItemsClearedEvent) - mockSocket.DOMStorage().OnItemsCleared(func(eventData *storage.ItemsClearedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOMStorage.domStorageItemsCleared", }) result = <-resultChan diff --git a/tot/socket/cdtp.dom_test.go b/tot/socket/cdtp.dom_test.go index fd509c6..88a89fd 100644 --- a/tot/socket/cdtp.dom_test.go +++ b/tot/socket/cdtp.dom_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom" @@ -11,25 +9,21 @@ import ( ) func TestDOMCollectClassNamesFromSubtree(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMCollectClassNamesFromSubtree") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.CollectClassNamesFromSubtreeParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().CollectClassNamesFromSubtree(params) mockResult := &dom.CollectClassNamesFromSubtreeResult{ ClassNames: []string{"class1", "class2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().CollectClassNamesFromSubtree(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -37,43 +31,31 @@ func TestDOMCollectClassNamesFromSubtree(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.ClassNames[0], result.ClassNames[0]) } - resultChan = mockSocket.DOM().CollectClassNamesFromSubtree(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().CollectClassNamesFromSubtree(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMCopyTo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMCopyTo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.CopyToParams{ NodeID: dom.NodeID(1), TargetNodeID: dom.NodeID(1), InsertBeforeNodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().CopyTo(params) mockResult := &dom.CopyToResult{ NodeID: dom.NodeID(2), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().CopyTo(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -81,26 +63,19 @@ func TestDOMCopyTo(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().CopyTo(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().CopyTo(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDescribeNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDescribeNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.DescribeNodeParams{ NodeID: dom.NodeID(1), @@ -109,17 +84,12 @@ func TestDOMDescribeNode(t *testing.T) { Depth: 1, Pierce: true, } - resultChan := mockSocket.DOM().DescribeNode(params) mockResult := &dom.DescribeNodeResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().DescribeNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -127,60 +97,41 @@ func TestDOMDescribeNode(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().DescribeNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().DescribeNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOM().Disable() mockResult := &dom.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMDiscardSearchResults(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMDiscardSearchResults") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.DiscardSearchResultsParams{ Node: &dom.Node{ @@ -218,127 +169,86 @@ func TestDOMDiscardSearchResults(t *testing.T) { IsSVG: true, }, } - resultChan := mockSocket.DOM().DiscardSearchResults(params) mockResult := &dom.DiscardSearchResultsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().DiscardSearchResults(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().DiscardSearchResults(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().DiscardSearchResults(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOM().Enable() mockResult := &dom.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMFocus(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMFocus") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.FocusParams{ NodeID: dom.NodeID(1), BackendNodeID: dom.BackendNodeID(1), ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.DOM().Focus(params) mockResult := &dom.FocusResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().Focus(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().Focus(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().Focus(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetAttributes(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetAttributes") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetAttributesParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().GetAttributes(params) mockResult := &dom.GetAttributesResult{ Attributes: []string{"attr1", "attr2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetAttributes(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -346,33 +256,25 @@ func TestDOMGetAttributes(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Attributes[0], result.Attributes[0]) } - resultChan = mockSocket.DOM().GetAttributes(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetAttributes(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetBoxModel(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetBoxModel") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetBoxModelParams{ NodeID: dom.NodeID(1), BackendNodeID: dom.BackendNodeID(1), ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.DOM().GetBoxModel(params) mockResult := &dom.GetBoxModelResult{ Model: &dom.BoxModel{ Content: dom.Quad{1, 2}, @@ -388,13 +290,9 @@ func TestDOMGetBoxModel(t *testing.T) { }, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetBoxModel(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -402,32 +300,24 @@ func TestDOMGetBoxModel(t *testing.T) { t.Errorf("Expected '%v', got '%v'", mockResult.Model.Content, result.Model.Content) } - resultChan = mockSocket.DOM().GetBoxModel(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetBoxModel(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetDocument(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetDocument") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetDocumentParams{ Depth: 1, Pierce: true, } - resultChan := mockSocket.DOM().GetDocument(params) mockResult := &dom.GetDocumentResult{ Root: &dom.Node{ NodeID: dom.NodeID(1), @@ -464,13 +354,9 @@ func TestDOMGetDocument(t *testing.T) { IsSVG: true, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetDocument(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -478,32 +364,24 @@ func TestDOMGetDocument(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Root.NodeID, result.Root.NodeID) } - resultChan = mockSocket.DOM().GetDocument(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetDocument(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetFlattenedDocument(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetFlattenedDocument") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetFlattenedDocumentParams{ Depth: 1, Pierce: true, } - resultChan := mockSocket.DOM().GetFlattenedDocument(params) mockResult := &dom.GetFlattenedDocumentResult{ Nodes: []*dom.Node{{ NodeID: dom.NodeID(1), @@ -540,13 +418,9 @@ func TestDOMGetFlattenedDocument(t *testing.T) { IsSVG: true, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetFlattenedDocument(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -554,43 +428,31 @@ func TestDOMGetFlattenedDocument(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Nodes[0].NodeID, result.Nodes[0].NodeID) } - resultChan = mockSocket.DOM().GetFlattenedDocument(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetFlattenedDocument(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetNodeForLocation(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetNodeForLocation") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetNodeForLocationParams{ - X: 1, - Y: 1, + X: 1, + Y: 1, IncludeUserAgentShadowDOM: true, } - resultChan := mockSocket.DOM().GetNodeForLocation(params) mockResult := &dom.GetNodeForLocationResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetNodeForLocation(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -598,43 +460,31 @@ func TestDOMGetNodeForLocation(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().GetNodeForLocation(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetNodeForLocation(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetOuterHTML(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetOuterHTML") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetOuterHTMLParams{ NodeID: dom.NodeID(1), BackendNodeID: dom.BackendNodeID(1), ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.DOM().GetOuterHTML(params) mockResult := &dom.GetOuterHTMLResult{ OuterHTML: "", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetOuterHTML(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -642,41 +492,29 @@ func TestDOMGetOuterHTML(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.OuterHTML, result.OuterHTML) } - resultChan = mockSocket.DOM().GetOuterHTML(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetOuterHTML(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetRelayoutBoundary(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetRelayoutBoundary") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetRelayoutBoundaryParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().GetRelayoutBoundary(params) mockResult := &dom.GetRelayoutBoundaryResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetRelayoutBoundary(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -684,43 +522,31 @@ func TestDOMGetRelayoutBoundary(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().GetRelayoutBoundary(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetRelayoutBoundary(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMGetSearchResults(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMGetSearchResults") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.GetSearchResultsParams{ SearchID: "search-id", FromIndex: 1, ToIndex: 2, } - resultChan := mockSocket.DOM().GetSearchResults(params) mockResult := &dom.GetSearchResultsResult{ NodeIDs: []dom.NodeID{1, 2}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().GetSearchResults(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -728,77 +554,53 @@ func TestDOMGetSearchResults(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeIDs[0], result.NodeIDs[0]) } - resultChan = mockSocket.DOM().GetSearchResults(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().GetSearchResults(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMMarkUndoableState(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMMarkUndoableState") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOM().MarkUndoableState() mockResult := &dom.MarkUndoableStateResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().MarkUndoableState() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().MarkUndoableState() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().MarkUndoableState() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMMoveTo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMMoveTo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.MoveToParams{ NodeID: dom.NodeID(1), TargetNodeID: dom.NodeID(2), InsertBeforeNodeID: dom.NodeID(3), } - resultChan := mockSocket.DOM().MoveTo(params) mockResult := &dom.MoveToResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().MoveTo(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -806,43 +608,31 @@ func TestDOMMoveTo(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().MoveTo(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().MoveTo(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMPerformSearch(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMPerformSearch") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.PerformSearchParams{ - Query: "search query", + Query: "search query", IncludeUserAgentShadowDOM: true, } - resultChan := mockSocket.DOM().PerformSearch(params) mockResult := &dom.PerformSearchResult{ SearchID: "search-id", ResultCount: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().PerformSearch(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -850,41 +640,29 @@ func TestDOMPerformSearch(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.SearchID, result.SearchID) } - resultChan = mockSocket.DOM().PerformSearch(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().PerformSearch(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMPushNodeByPathToFrontend(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMPushNodeByPathToFrontend") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.PushNodeByPathToFrontendParams{ Path: "/node/path", } - resultChan := mockSocket.DOM().PushNodeByPathToFrontend(params) mockResult := &dom.PushNodeByPathToFrontendResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().PushNodeByPathToFrontend(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -892,41 +670,29 @@ func TestDOMPushNodeByPathToFrontend(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().PushNodeByPathToFrontend(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().PushNodeByPathToFrontend(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMPushNodesByBackendIDsToFrontend(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMPushNodesByBackendIDsToFrontend") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.PushNodesByBackendIDsToFrontendParams{ BackendNodeIDs: []dom.BackendNodeID{1, 2}, } - resultChan := mockSocket.DOM().PushNodesByBackendIDsToFrontend(params) mockResult := &dom.PushNodesByBackendIDsToFrontendResult{ NodeIDs: []dom.NodeID{1, 2}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().PushNodesByBackendIDsToFrontend(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -934,42 +700,30 @@ func TestDOMPushNodesByBackendIDsToFrontend(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeIDs[0], result.NodeIDs[0]) } - resultChan = mockSocket.DOM().PushNodesByBackendIDsToFrontend(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().PushNodesByBackendIDsToFrontend(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMQuerySelector(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMQuerySelector") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.QuerySelectorParams{ NodeID: dom.NodeID(1), Selector: "selector", } - resultChan := mockSocket.DOM().QuerySelector(params) mockResult := &dom.QuerySelectorResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().QuerySelector(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -977,42 +731,30 @@ func TestDOMQuerySelector(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().QuerySelector(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().QuerySelector(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMQuerySelectorAll(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMQuerySelectorAll") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.QuerySelectorAllParams{ NodeID: dom.NodeID(1), Selector: "selector", } - resultChan := mockSocket.DOM().QuerySelectorAll(params) mockResult := &dom.QuerySelectorAllResult{ NodeIDs: []dom.NodeID{1, 2}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().QuerySelectorAll(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1020,189 +762,129 @@ func TestDOMQuerySelectorAll(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeIDs[0], result.NodeIDs[0]) } - resultChan = mockSocket.DOM().QuerySelectorAll(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().QuerySelectorAll(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMRedo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMRedo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOM().Redo() mockResult := &dom.RedoResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().Redo() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().Redo() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().Redo() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMRemoveAttribute(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMRemoveAttribute") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.RemoveAttributeParams{ NodeID: dom.NodeID(1), Name: "attribute-name", } - resultChan := mockSocket.DOM().RemoveAttribute(params) mockResult := &dom.RemoveAttributeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().RemoveAttribute(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().RemoveAttribute(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().RemoveAttribute(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMRemoveNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMRemoveNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.RemoveNodeParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().RemoveNode(params) mockResult := &dom.RemoveNodeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().RemoveNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().RemoveNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().RemoveNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMRequestChildNodes(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMRequestChildNodes") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.RequestChildNodesParams{ NodeID: dom.NodeID(1), Depth: 1, Pierce: true, } - resultChan := mockSocket.DOM().RequestChildNodes(params) mockResult := &dom.RequestChildNodesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().RequestChildNodes(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().RequestChildNodes(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().RequestChildNodes(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMRequestNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMRequestNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.RequestNodeParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.DOM().RequestNode(params) mockResult := &dom.RequestNodeResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().RequestNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1210,33 +892,25 @@ func TestDOMRequestNode(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().RequestNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().RequestNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMResolveNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMResolveNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.ResolveNodeParams{ NodeID: dom.NodeID(1), BackendNodeID: dom.BackendNodeID(1), ObjectGroup: "object-group", } - resultChan := mockSocket.DOM().ResolveNode(params) mockResult := &dom.ResolveNodeResult{ Object: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -1263,13 +937,9 @@ func TestDOMResolveNode(t *testing.T) { }, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().ResolveNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1277,104 +947,73 @@ func TestDOMResolveNode(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Object.Type, result.Object.Type) } - resultChan = mockSocket.DOM().ResolveNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().ResolveNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetAttributeValue(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetAttributeValue") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetAttributeValueParams{ NodeID: dom.NodeID(1), Name: "name", Value: "value", } - resultChan := mockSocket.DOM().SetAttributeValue(params) mockResult := &dom.SetAttributeValueResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetAttributeValue(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetAttributeValue(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetAttributeValue(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetAttributesAsText(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetAttributesAsText") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetAttributesAsTextParams{ NodeID: dom.NodeID(1), Text: "some text", Name: "name", } - resultChan := mockSocket.DOM().SetAttributesAsText(params) mockResult := &dom.SetAttributesAsTextResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetAttributesAsText(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetAttributesAsText(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetAttributesAsText(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetFileInputFiles(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetFileInputFiles") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetFileInputFilesParams{ Files: []string{"file1", "file2"}, @@ -1382,92 +1021,63 @@ func TestDOMSetFileInputFiles(t *testing.T) { BackendNodeID: dom.BackendNodeID(1), ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.DOM().SetFileInputFiles(params) mockResult := &dom.SetFileInputFilesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetFileInputFiles(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetFileInputFiles(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetFileInputFiles(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetInspectedNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetInspectedNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetInspectedNodeParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.DOM().SetInspectedNode(params) mockResult := &dom.SetInspectedNodeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetInspectedNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetInspectedNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetInspectedNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetNodeName(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetNodeName") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetNodeNameParams{ NodeID: dom.NodeID(1), Name: "new-name", } - resultChan := mockSocket.DOM().SetNodeName(params) mockResult := &dom.SetNodeNameResult{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetNodeName(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -1475,169 +1085,118 @@ func TestDOMSetNodeName(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = mockSocket.DOM().SetNodeName(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetNodeName(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetNodeValue(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetNodeValue") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetNodeValueParams{ NodeID: dom.NodeID(1), Value: "new-value", } - resultChan := mockSocket.DOM().SetNodeValue(params) mockResult := &dom.SetNodeValueResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetNodeValue(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetNodeValue(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetNodeValue(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMSetOuterHTML(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMSetOuterHTML") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &dom.SetOuterHTMLParams{ NodeID: dom.NodeID(1), OuterHTML: "", } - resultChan := mockSocket.DOM().SetOuterHTML(params) mockResult := &dom.SetOuterHTMLResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().SetOuterHTML(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().SetOuterHTML(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().SetOuterHTML(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMUndo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMUndo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.DOM().Undo() mockResult := &dom.UndoResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.DOM().Undo() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.DOM().Undo() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.DOM().Undo() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestDOMOnAttributeModified(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnAttributeModified") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.AttributeModifiedEvent) - mockSocket.DOM().OnAttributeModified(func(eventData *dom.AttributeModifiedEvent) { + soc.DOM().OnAttributeModified(func(eventData *dom.AttributeModifiedEvent) { resultChan <- eventData }) + mockResult := &dom.AttributeModifiedEvent{ NodeID: dom.NodeID(1), Name: "attribute-name", Value: "attribute-value", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.attributeModified", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.AttributeModifiedEvent) - mockSocket.DOM().OnAttributeModified(func(eventData *dom.AttributeModifiedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.attributeModified", }) result = <-resultChan @@ -1647,42 +1206,35 @@ func TestDOMOnAttributeModified(t *testing.T) { } func TestDOMOnAttributeRemoved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnAttributeRemoved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.AttributeRemovedEvent) - mockSocket.DOM().OnAttributeRemoved(func(eventData *dom.AttributeRemovedEvent) { + soc.DOM().OnAttributeRemoved(func(eventData *dom.AttributeRemovedEvent) { resultChan <- eventData }) + mockResult := &dom.AttributeRemovedEvent{ NodeID: dom.NodeID(1), Name: "attribute-name", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.attributeRemoved", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.AttributeRemovedEvent) - mockSocket.DOM().OnAttributeRemoved(func(eventData *dom.AttributeRemovedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.attributeRemoved", }) result = <-resultChan @@ -1692,42 +1244,35 @@ func TestDOMOnAttributeRemoved(t *testing.T) { } func TestDOMOnCharacterDataModified(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnCharacterDataModified") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.CharacterDataModifiedEvent) - mockSocket.DOM().OnCharacterDataModified(func(eventData *dom.CharacterDataModifiedEvent) { + soc.DOM().OnCharacterDataModified(func(eventData *dom.CharacterDataModifiedEvent) { resultChan <- eventData }) + mockResult := &dom.CharacterDataModifiedEvent{ NodeID: dom.NodeID(1), CharacterData: "char-data", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.characterDataModified", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.CharacterDataModifiedEvent) - mockSocket.DOM().OnCharacterDataModified(func(eventData *dom.CharacterDataModifiedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.characterDataModified", }) result = <-resultChan @@ -1737,43 +1282,36 @@ func TestDOMOnCharacterDataModified(t *testing.T) { } func TestDOMOnChildNodeCountUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnChildNodeCountUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.ChildNodeCountUpdatedEvent) - mockSocket.DOM().OnChildNodeCountUpdated(func(eventData *dom.ChildNodeCountUpdatedEvent) { + soc.DOM().OnChildNodeCountUpdated(func(eventData *dom.ChildNodeCountUpdatedEvent) { resultChan <- eventData }) + mockResult := &dom.ChildNodeCountUpdatedEvent{ ParentNodeID: dom.NodeID(2), PreviousNodeID: dom.NodeID(1), Node: &dom.Node{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.childNodeCountUpdated", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.ChildNodeCountUpdatedEvent) - mockSocket.DOM().OnChildNodeCountUpdated(func(eventData *dom.ChildNodeCountUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.childNodeCountUpdated", }) result = <-resultChan @@ -1783,43 +1321,36 @@ func TestDOMOnChildNodeCountUpdated(t *testing.T) { } func TestDOMOnChildNodeInserted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnChildNodeInserted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.ChildNodeInsertedEvent) - mockSocket.DOM().OnChildNodeInserted(func(eventData *dom.ChildNodeInsertedEvent) { + soc.DOM().OnChildNodeInserted(func(eventData *dom.ChildNodeInsertedEvent) { resultChan <- eventData }) + mockResult := &dom.ChildNodeInsertedEvent{ ParentNodeID: dom.NodeID(1), PreviousNodeID: dom.NodeID(1), Node: &dom.Node{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.childNodeInserted", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.ChildNodeInsertedEvent) - mockSocket.DOM().OnChildNodeInserted(func(eventData *dom.ChildNodeInsertedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.childNodeInserted", }) result = <-resultChan @@ -1829,42 +1360,35 @@ func TestDOMOnChildNodeInserted(t *testing.T) { } func TestDOMOnChildNodeRemoved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnChildNodeRemoved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.ChildNodeRemovedEvent) - mockSocket.DOM().OnChildNodeRemoved(func(eventData *dom.ChildNodeRemovedEvent) { + soc.DOM().OnChildNodeRemoved(func(eventData *dom.ChildNodeRemovedEvent) { resultChan <- eventData }) + mockResult := &dom.ChildNodeRemovedEvent{ ParentNodeID: dom.NodeID(1), NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.childNodeRemoved", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.ChildNodeRemovedEvent) - mockSocket.DOM().OnChildNodeRemoved(func(eventData *dom.ChildNodeRemovedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.childNodeRemoved", }) result = <-resultChan @@ -1874,42 +1398,35 @@ func TestDOMOnChildNodeRemoved(t *testing.T) { } func TestDOMOnDistributedNodesUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnDistributedNodesUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.DistributedNodesUpdatedEvent) - mockSocket.DOM().OnDistributedNodesUpdated(func(eventData *dom.DistributedNodesUpdatedEvent) { + soc.DOM().OnDistributedNodesUpdated(func(eventData *dom.DistributedNodesUpdatedEvent) { resultChan <- eventData }) + mockResult := &dom.DistributedNodesUpdatedEvent{ InsertionPointID: dom.NodeID(1), DistributedNodes: []*dom.BackendNode{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.distributedNodesUpdated", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.DistributedNodesUpdatedEvent) - mockSocket.DOM().OnDistributedNodesUpdated(func(eventData *dom.DistributedNodesUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.distributedNodesUpdated", }) result = <-resultChan @@ -1919,39 +1436,32 @@ func TestDOMOnDistributedNodesUpdated(t *testing.T) { } func TestDOMOnDocumentUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnDocumentUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.DocumentUpdatedEvent) - mockSocket.DOM().OnDocumentUpdated(func(eventData *dom.DocumentUpdatedEvent) { + soc.DOM().OnDocumentUpdated(func(eventData *dom.DocumentUpdatedEvent) { resultChan <- eventData }) + mockResult := &dom.DocumentUpdatedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.documentUpdated", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.DocumentUpdatedEvent) - mockSocket.DOM().OnDocumentUpdated(func(eventData *dom.DocumentUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.documentUpdated", }) result = <-resultChan @@ -1961,41 +1471,34 @@ func TestDOMOnDocumentUpdated(t *testing.T) { } func TestDOMOnInlineStyleInvalidated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnInlineStyleInvalidated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.InlineStyleInvalidatedEvent) - mockSocket.DOM().OnInlineStyleInvalidated(func(eventData *dom.InlineStyleInvalidatedEvent) { + soc.DOM().OnInlineStyleInvalidated(func(eventData *dom.InlineStyleInvalidatedEvent) { resultChan <- eventData }) + mockResult := &dom.InlineStyleInvalidatedEvent{ NodeIDs: []dom.NodeID{1, 2}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.inlineStyleInvalidated", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.InlineStyleInvalidatedEvent) - mockSocket.DOM().OnInlineStyleInvalidated(func(eventData *dom.InlineStyleInvalidatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.inlineStyleInvalidated", }) result = <-resultChan @@ -2005,42 +1508,35 @@ func TestDOMOnInlineStyleInvalidated(t *testing.T) { } func TestDOMOnPseudoElementAdded(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnPseudoElementAdded") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.PseudoElementAddedEvent) - mockSocket.DOM().OnPseudoElementAdded(func(eventData *dom.PseudoElementAddedEvent) { + soc.DOM().OnPseudoElementAdded(func(eventData *dom.PseudoElementAddedEvent) { resultChan <- eventData }) + mockResult := &dom.PseudoElementAddedEvent{ ParentID: dom.NodeID(1), PseudoElement: &dom.Node{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.pseudoElementAdded", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.PseudoElementAddedEvent) - mockSocket.DOM().OnPseudoElementAdded(func(eventData *dom.PseudoElementAddedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.pseudoElementAdded", }) result = <-resultChan @@ -2050,42 +1546,35 @@ func TestDOMOnPseudoElementAdded(t *testing.T) { } func TestDOMOnPseudoElementRemoved(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnPseudoElementRemoved") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.PseudoElementRemovedEvent) - mockSocket.DOM().OnPseudoElementRemoved(func(eventData *dom.PseudoElementRemovedEvent) { + soc.DOM().OnPseudoElementRemoved(func(eventData *dom.PseudoElementRemovedEvent) { resultChan <- eventData }) + mockResult := &dom.PseudoElementRemovedEvent{ ParentID: dom.NodeID(1), PseudoElementID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.pseudoElementRemoved", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.PseudoElementRemovedEvent) - mockSocket.DOM().OnPseudoElementRemoved(func(eventData *dom.PseudoElementRemovedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.pseudoElementRemoved", }) result = <-resultChan @@ -2095,42 +1584,35 @@ func TestDOMOnPseudoElementRemoved(t *testing.T) { } func TestDOMOnSetChildNodes(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnSetChildNodes") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.SetChildNodesEvent) - mockSocket.DOM().OnSetChildNodes(func(eventData *dom.SetChildNodesEvent) { + soc.DOM().OnSetChildNodes(func(eventData *dom.SetChildNodesEvent) { resultChan <- eventData }) + mockResult := &dom.SetChildNodesEvent{ ParentID: dom.NodeID(1), Nodes: []*dom.Node{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.setChildNodes", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.SetChildNodesEvent) - mockSocket.DOM().OnSetChildNodes(func(eventData *dom.SetChildNodesEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.setChildNodes", }) result = <-resultChan @@ -2140,42 +1622,35 @@ func TestDOMOnSetChildNodes(t *testing.T) { } func TestDOMOnShadowRootPopped(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnShadowRootPopped") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.ShadowRootPoppedEvent) - mockSocket.DOM().OnShadowRootPopped(func(eventData *dom.ShadowRootPoppedEvent) { + soc.DOM().OnShadowRootPopped(func(eventData *dom.ShadowRootPoppedEvent) { resultChan <- eventData }) + mockResult := &dom.ShadowRootPoppedEvent{ HostID: dom.NodeID(1), RootID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.shadowRootPopped", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.ShadowRootPoppedEvent) - mockSocket.DOM().OnShadowRootPopped(func(eventData *dom.ShadowRootPoppedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.shadowRootPopped", }) result = <-resultChan @@ -2185,42 +1660,35 @@ func TestDOMOnShadowRootPopped(t *testing.T) { } func TestDOMOnShadowRootPushed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestDOMOnShadowRootPushed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *dom.ShadowRootPushedEvent) - mockSocket.DOM().OnShadowRootPushed(func(eventData *dom.ShadowRootPushedEvent) { + soc.DOM().OnShadowRootPushed(func(eventData *dom.ShadowRootPushedEvent) { resultChan <- eventData }) + mockResult := &dom.ShadowRootPushedEvent{ HostID: dom.NodeID(1), Root: &dom.Node{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "DOM.shadowRootPushed", - Result: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *dom.ShadowRootPushedEvent) - mockSocket.DOM().OnShadowRootPushed(func(eventData *dom.ShadowRootPushedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "DOM.shadowRootPushed", }) result = <-resultChan diff --git a/tot/socket/cdtp.emulation_test.go b/tot/socket/cdtp.emulation_test.go index c87d413..3faf8f1 100644 --- a/tot/socket/cdtp.emulation_test.go +++ b/tot/socket/cdtp.emulation_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -13,22 +11,18 @@ import ( ) func TestEmulationCanEmulate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationCanEmulate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Emulation().CanEmulate() mockResult := &emulation.CanEmulateResult{ Result: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().CanEmulate() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -36,165 +30,110 @@ func TestEmulationCanEmulate(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Result, result.Result) } - resultChan = mockSocket.Emulation().CanEmulate() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().CanEmulate() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationClearDeviceMetricsOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationClearDeviceMetricsOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Emulation().ClearDeviceMetricsOverride() mockResult := &emulation.ClearDeviceMetricsOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().ClearDeviceMetricsOverride() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().ClearDeviceMetricsOverride() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().ClearDeviceMetricsOverride() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationClearGeolocationOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationClearGeolocationOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Emulation().ClearGeolocationOverride() mockResult := &emulation.ClearGeolocationOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().ClearGeolocationOverride() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().ClearGeolocationOverride() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().ClearGeolocationOverride() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationResetPageScaleFactor(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationResetPageScaleFactor") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Emulation().ResetPageScaleFactor() mockResult := &emulation.ResetPageScaleFactorResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().ResetPageScaleFactor() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().ResetPageScaleFactor() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().ResetPageScaleFactor() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetCPUThrottlingRate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetCPUThrottlingRate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetCPUThrottlingRateParams{ Rate: 1, } - resultChan := mockSocket.Emulation().SetCPUThrottlingRate(params) mockResult := &emulation.SetCPUThrottlingRateResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetCPUThrottlingRate(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetCPUThrottlingRate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetCPUThrottlingRate(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetDefaultBackgroundColorOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetDefaultBackgroundColorOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetDefaultBackgroundColorOverrideParams{ Color: &dom.RGBA{ @@ -204,39 +143,27 @@ func TestEmulationSetDefaultBackgroundColorOverride(t *testing.T) { A: 1, }, } - resultChan := mockSocket.Emulation().SetDefaultBackgroundColorOverride(params) mockResult := &emulation.SetDefaultBackgroundColorOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetDefaultBackgroundColorOverride(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetDefaultBackgroundColorOverride(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetDefaultBackgroundColorOverride(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetDeviceMetricsOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetDeviceMetricsOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetDeviceMetricsOverrideParams{ Width: 1, @@ -261,319 +188,218 @@ func TestEmulationSetDeviceMetricsOverride(t *testing.T) { Scale: 1, }, } - resultChan := mockSocket.Emulation().SetDeviceMetricsOverride(params) mockResult := &emulation.SetDeviceMetricsOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetDeviceMetricsOverride(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetDeviceMetricsOverride(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetDeviceMetricsOverride(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetEmitTouchEventsForMouse(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetEmitTouchEventsForMouse") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetEmitTouchEventsForMouseParams{ Enabled: true, Configuration: emulation.Configuration.Mobile, } - resultChan := mockSocket.Emulation().SetEmitTouchEventsForMouse(params) mockResult := &emulation.SetEmitTouchEventsForMouseResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetEmitTouchEventsForMouse(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetEmitTouchEventsForMouse(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetEmitTouchEventsForMouse(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetEmulatedMedia(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetEmulatedMedia") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetEmulatedMediaParams{ Media: "media", } - resultChan := mockSocket.Emulation().SetEmulatedMedia(params) mockResult := &emulation.SetEmulatedMediaResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetEmulatedMedia(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetEmulatedMedia(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetEmulatedMedia(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetGeolocationOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetGeolocationOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetGeolocationOverrideParams{ Latitude: 1, Longitude: 1, Accuracy: 1, } - resultChan := mockSocket.Emulation().SetGeolocationOverride(params) mockResult := &emulation.SetGeolocationOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetGeolocationOverride(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetGeolocationOverride(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetGeolocationOverride(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetNavigatorOverrides(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetNavigatorOverrides") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetNavigatorOverridesParams{ Platform: "platform", } - resultChan := mockSocket.Emulation().SetNavigatorOverrides(params) mockResult := &emulation.SetNavigatorOverridesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetNavigatorOverrides(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetNavigatorOverrides(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetNavigatorOverrides(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetPageScaleFactor(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetPageScaleFactor") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetPageScaleFactorParams{ PageScaleFactor: 1, } - resultChan := mockSocket.Emulation().SetPageScaleFactor(params) mockResult := &emulation.SetPageScaleFactorResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetPageScaleFactor(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetPageScaleFactor(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetPageScaleFactor(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetScriptExecutionDisabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetScriptExecutionDisabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetScriptExecutionDisabledParams{ Value: true, } - resultChan := mockSocket.Emulation().SetScriptExecutionDisabled(params) mockResult := &emulation.SetScriptExecutionDisabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetScriptExecutionDisabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetScriptExecutionDisabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetScriptExecutionDisabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetTouchEmulationEnabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetTouchEmulationEnabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetTouchEmulationEnabledParams{ Enabled: true, MaxTouchPoints: 1, } - resultChan := mockSocket.Emulation().SetTouchEmulationEnabled(params) mockResult := &emulation.SetTouchEmulationEnabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetTouchEmulationEnabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetTouchEmulationEnabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetTouchEmulationEnabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetVirtualTimePolicy(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetVirtualTimePolicy") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetVirtualTimePolicyParams{ - Policy: emulation.VirtualTimePolicy("policy"), - Budget: 1, + Policy: emulation.VirtualTimePolicy("policy"), + Budget: 1, MaxVirtualTimeTaskStarvationCount: 1, } - resultChan := mockSocket.Emulation().SetVirtualTimePolicy(params) mockResult := &emulation.SetVirtualTimePolicyResult{ VirtualTimeBase: runtime.Timestamp(time.Now().Unix()), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetVirtualTimePolicy(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -581,95 +407,68 @@ func TestEmulationSetVirtualTimePolicy(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.VirtualTimeBase, result.VirtualTimeBase) } - resultChan = mockSocket.Emulation().SetVirtualTimePolicy(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetVirtualTimePolicy(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationSetVisibleSize(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationSetVisibleSize") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &emulation.SetVisibleSizeParams{ Width: 1, Height: 1, } - resultChan := mockSocket.Emulation().SetVisibleSize(params) mockResult := &emulation.SetVisibleSizeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Emulation().SetVisibleSize(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Emulation().SetVisibleSize(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Emulation().SetVisibleSize(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestEmulationOnVirtualTimeAdvanced(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationOnVirtualTimeAdvanced") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *emulation.VirtualTimeAdvancedEvent) - mockSocket.Emulation().OnVirtualTimeAdvanced(func(eventData *emulation.VirtualTimeAdvancedEvent) { + soc.Emulation().OnVirtualTimeAdvanced(func(eventData *emulation.VirtualTimeAdvancedEvent) { resultChan <- eventData }) + mockResult := &emulation.VirtualTimeAdvancedEvent{ VirtualTimeElapsed: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Emulation.virtualTimeAdvanced", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *emulation.VirtualTimeAdvancedEvent) - mockSocket.Emulation().OnVirtualTimeAdvanced(func(eventData *emulation.VirtualTimeAdvancedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Emulation.virtualTimeAdvanced", }) result = <-resultChan @@ -679,39 +478,32 @@ func TestEmulationOnVirtualTimeAdvanced(t *testing.T) { } func TestEmulationOnVirtualTimeBudgetExpired(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationOnVirtualTimeBudgetExpired") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *emulation.VirtualTimeBudgetExpiredEvent) - mockSocket.Emulation().OnVirtualTimeBudgetExpired(func(eventData *emulation.VirtualTimeBudgetExpiredEvent) { + soc.Emulation().OnVirtualTimeBudgetExpired(func(eventData *emulation.VirtualTimeBudgetExpiredEvent) { resultChan <- eventData }) + mockResult := &emulation.VirtualTimeBudgetExpiredEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Emulation.virtualTimeBudgetExpired", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *emulation.VirtualTimeBudgetExpiredEvent) - mockSocket.Emulation().OnVirtualTimeBudgetExpired(func(eventData *emulation.VirtualTimeBudgetExpiredEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Emulation.virtualTimeBudgetExpired", }) result = <-resultChan @@ -721,41 +513,34 @@ func TestEmulationOnVirtualTimeBudgetExpired(t *testing.T) { } func TestEmulationOnVirtualTimePaused(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestEmulationOnVirtualTimePaused") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *emulation.VirtualTimePausedEvent) - mockSocket.Emulation().OnVirtualTimePaused(func(eventData *emulation.VirtualTimePausedEvent) { + soc.Emulation().OnVirtualTimePaused(func(eventData *emulation.VirtualTimePausedEvent) { resultChan <- eventData }) + mockResult := &emulation.VirtualTimePausedEvent{ VirtualTimeElapsed: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Emulation.virtualTimePaused", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *emulation.VirtualTimePausedEvent) - mockSocket.Emulation().OnVirtualTimePaused(func(eventData *emulation.VirtualTimePausedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Emulation.virtualTimePaused", }) result = <-resultChan diff --git a/tot/socket/cdtp.headless.experimental_test.go b/tot/socket/cdtp.headless.experimental_test.go index 76d1219..a633c82 100644 --- a/tot/socket/cdtp.headless.experimental_test.go +++ b/tot/socket/cdtp.headless.experimental_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -11,10 +9,11 @@ import ( ) func TestHeadlessExperimentalBeginFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeadlessExperimentalBeginFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &experimental.BeginFrameParams{ FrameTime: runtime.Timestamp(time.Now().Unix()), @@ -25,19 +24,14 @@ func TestHeadlessExperimentalBeginFrame(t *testing.T) { Quality: 100, }, } - resultChan := mockSocket.HeadlessExperimental().BeginFrame(params) mockResult := &experimental.BeginFrameResult{ HasDamage: true, MainFrameContentUpdated: true, ScreenshotData: "data", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeadlessExperimental().BeginFrame(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -45,123 +39,84 @@ func TestHeadlessExperimentalBeginFrame(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.HasDamage, result.HasDamage) } - resultChan = mockSocket.HeadlessExperimental().BeginFrame(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeadlessExperimental().BeginFrame(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeadlessExperimentalDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeadlessExperimentalDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.HeadlessExperimental().Disable() mockResult := &experimental.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeadlessExperimental().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeadlessExperimental().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeadlessExperimental().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeadlessExperimentalEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeadlessExperimentalEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.HeadlessExperimental().Enable() mockResult := &experimental.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeadlessExperimental().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeadlessExperimental().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeadlessExperimental().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeadlessExperimentalOnMainFrameReadyForScreenshots(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeadlessExperimentalOnMainFrameReadyForScreenshots") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *experimental.MainFrameReadyForScreenshotsEvent) - mockSocket.HeadlessExperimental().OnMainFrameReadyForScreenshots(func(eventData *experimental.MainFrameReadyForScreenshotsEvent) { + soc.HeadlessExperimental().OnMainFrameReadyForScreenshots(func(eventData *experimental.MainFrameReadyForScreenshotsEvent) { resultChan <- eventData }) + mockResult := &experimental.MainFrameReadyForScreenshotsEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeadlessExperimental.mainFrameReadyForScreenshots", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *experimental.MainFrameReadyForScreenshotsEvent) - mockSocket.HeadlessExperimental().OnMainFrameReadyForScreenshots(func(eventData *experimental.MainFrameReadyForScreenshotsEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeadlessExperimental.mainFrameReadyForScreenshots", }) result = <-resultChan @@ -171,41 +126,34 @@ func TestHeadlessExperimentalOnMainFrameReadyForScreenshots(t *testing.T) { } func TestHeadlessExperimentalOnNeedsBeginFramesChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeadlessExperimentalOnNeedsBeginFramesChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *experimental.NeedsBeginFramesChangedEvent) - mockSocket.HeadlessExperimental().OnNeedsBeginFramesChanged(func(eventData *experimental.NeedsBeginFramesChangedEvent) { + soc.HeadlessExperimental().OnNeedsBeginFramesChanged(func(eventData *experimental.NeedsBeginFramesChangedEvent) { resultChan <- eventData }) + mockResult := &experimental.NeedsBeginFramesChangedEvent{ NeedsBeginFrames: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeadlessExperimental.needsBeginFramesChanged", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *experimental.NeedsBeginFramesChangedEvent) - mockSocket.HeadlessExperimental().OnNeedsBeginFramesChanged(func(eventData *experimental.NeedsBeginFramesChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeadlessExperimental.needsBeginFramesChanged", }) result = <-resultChan diff --git a/tot/socket/cdtp.heap.profiler_test.go b/tot/socket/cdtp.heap.profiler_test.go index 4f18683..6a76407 100644 --- a/tot/socket/cdtp.heap.profiler_test.go +++ b/tot/socket/cdtp.heap.profiler_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/heap/profiler" @@ -10,164 +8,112 @@ import ( ) func TestHeapProfilerAddInspectedHeapObject(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerAddInspectedHeapObject") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.AddInspectedHeapObjectParams{ HeapObjectID: profiler.HeapSnapshotObjectID("snapshot-id"), } - resultChan := mockSocket.HeapProfiler().AddInspectedHeapObject(params) mockResult := &profiler.AddInspectedHeapObjectResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().AddInspectedHeapObject(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().AddInspectedHeapObject(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().AddInspectedHeapObject(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerCollectGarbage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerCollectGarbage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.HeapProfiler().CollectGarbage() mockResult := &profiler.CollectGarbageResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().CollectGarbage() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().CollectGarbage() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().CollectGarbage() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.HeapProfiler().Disable() mockResult := &profiler.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.HeapProfiler().Enable() mockResult := &profiler.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerGetHeapObjectID(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerGetHeapObjectID") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.GetHeapObjectIDParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.HeapProfiler().GetHeapObjectID(params) mockResult := &profiler.GetHeapObjectIDResult{ HeapSnapshotObjectID: profiler.HeapSnapshotObjectID("heap-snapshot-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().GetHeapObjectID(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -175,31 +121,23 @@ func TestHeapProfilerGetHeapObjectID(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.HeapSnapshotObjectID, result.HeapSnapshotObjectID) } - resultChan = mockSocket.HeapProfiler().GetHeapObjectID(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().GetHeapObjectID(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerGetObjectByHeapObjectID(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerGetObjectByHeapObjectID") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.GetObjectByHeapObjectIDParams{ ObjectID: profiler.HeapSnapshotObjectID("heap-snapshot-id"), } - resultChan := mockSocket.HeapProfiler().GetObjectByHeapObjectID(params) mockResult := &profiler.GetObjectByHeapObjectIDResult{ Result: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -215,13 +153,9 @@ func TestHeapProfilerGetObjectByHeapObjectID(t *testing.T) { CustomPreview: &runtime.CustomPreview{}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().GetObjectByHeapObjectID(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -229,26 +163,19 @@ func TestHeapProfilerGetObjectByHeapObjectID(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.Result.Type, result.Result.Type) } - resultChan = mockSocket.HeapProfiler().GetObjectByHeapObjectID(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().GetObjectByHeapObjectID(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerGetSamplingProfile(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerGetSamplingProfile") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.GetSamplingProfileParams{ Profile: &profiler.SamplingHeapProfile{ @@ -265,112 +192,76 @@ func TestHeapProfilerGetSamplingProfile(t *testing.T) { }, }, } - resultChan := mockSocket.HeapProfiler().GetSamplingProfile(params) mockResult := &profiler.GetSamplingProfileResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().GetSamplingProfile(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().GetSamplingProfile(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().GetSamplingProfile(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerStartSampling(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerStartSampling") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.StartSamplingParams{ SamplingInterval: 1, } - resultChan := mockSocket.HeapProfiler().StartSampling(params) mockResult := &profiler.StartSamplingResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().StartSampling(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().StartSampling(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().StartSampling(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerStartTrackingHeapObjects(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerStartTrackingHeapObjects") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.StartTrackingHeapObjectsParams{ TrackAllocations: true, } - resultChan := mockSocket.HeapProfiler().StartTrackingHeapObjects(params) mockResult := &profiler.StartTrackingHeapObjectsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().StartTrackingHeapObjects(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().StartTrackingHeapObjects(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().StartTrackingHeapObjects(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerStopSampling(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerStopSampling") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.StopSamplingParams{ Profile: &profiler.SamplingHeapProfile{ @@ -387,144 +278,100 @@ func TestHeapProfilerStopSampling(t *testing.T) { }, }, } - resultChan := mockSocket.HeapProfiler().StopSampling(params) mockResult := &profiler.StopSamplingResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().StopSampling(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().StopSampling(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().StopSampling(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerStopTrackingHeapObjects(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerStopTrackingHeapObjects") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.StopTrackingHeapObjectsParams{ ReportProgress: true, } - resultChan := mockSocket.HeapProfiler().StopTrackingHeapObjects(params) mockResult := &profiler.StopTrackingHeapObjectsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().StopTrackingHeapObjects(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().StopTrackingHeapObjects(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().StopTrackingHeapObjects(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerTakeHeapSnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerTakeHeapSnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.TakeHeapSnapshotParams{ ReportProgress: true, } - resultChan := mockSocket.HeapProfiler().TakeHeapSnapshot(params) mockResult := &profiler.TakeHeapSnapshotResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.HeapProfiler().TakeHeapSnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.HeapProfiler().TakeHeapSnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.HeapProfiler().TakeHeapSnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestHeapProfilerOnAddHeapSnapshotChunk(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerOnAddHeapSnapshotChunk") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.AddHeapSnapshotChunkEvent) - mockSocket.HeapProfiler().OnAddHeapSnapshotChunk(func(eventData *profiler.AddHeapSnapshotChunkEvent) { + soc.HeapProfiler().OnAddHeapSnapshotChunk(func(eventData *profiler.AddHeapSnapshotChunkEvent) { resultChan <- eventData }) + mockResult := &profiler.AddHeapSnapshotChunkEvent{ Chunk: "chunk", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeapProfiler.addHeapSnapshotChunk", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *profiler.AddHeapSnapshotChunkEvent) - mockSocket.HeapProfiler().OnAddHeapSnapshotChunk(func(eventData *profiler.AddHeapSnapshotChunkEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeapProfiler.addHeapSnapshotChunk", }) result = <-resultChan @@ -534,41 +381,34 @@ func TestHeapProfilerOnAddHeapSnapshotChunk(t *testing.T) { } func TestHeapProfilerOnHeapStatsUpdate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerOnHeapStatsUpdate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.HeapStatsUpdateEvent) - mockSocket.HeapProfiler().OnHeapStatsUpdate(func(eventData *profiler.HeapStatsUpdateEvent) { + soc.HeapProfiler().OnHeapStatsUpdate(func(eventData *profiler.HeapStatsUpdateEvent) { resultChan <- eventData }) + mockResult := &profiler.HeapStatsUpdateEvent{ StatsUpdate: []int{1, 2}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeapProfiler.heapStatsUpdate", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *profiler.HeapStatsUpdateEvent) - mockSocket.HeapProfiler().OnHeapStatsUpdate(func(eventData *profiler.HeapStatsUpdateEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeapProfiler.heapStatsUpdate", }) result = <-resultChan @@ -578,42 +418,35 @@ func TestHeapProfilerOnHeapStatsUpdate(t *testing.T) { } func TestHeapProfilerOnLastSeenObjectID(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerOnLastSeenObjectID") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.LastSeenObjectIDEvent) - mockSocket.HeapProfiler().OnLastSeenObjectID(func(eventData *profiler.LastSeenObjectIDEvent) { + soc.HeapProfiler().OnLastSeenObjectID(func(eventData *profiler.LastSeenObjectIDEvent) { resultChan <- eventData }) + mockResult := &profiler.LastSeenObjectIDEvent{ LastSeenObjectID: 1, Timestamp: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeapProfiler.lastSeenObjectID", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *profiler.LastSeenObjectIDEvent) - mockSocket.HeapProfiler().OnLastSeenObjectID(func(eventData *profiler.LastSeenObjectIDEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeapProfiler.lastSeenObjectID", }) result = <-resultChan @@ -623,43 +456,36 @@ func TestHeapProfilerOnLastSeenObjectID(t *testing.T) { } func TestHeapProfilerOnReportHeapSnapshotProgress(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerOnReportHeapSnapshotProgress") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.ReportHeapSnapshotProgressEvent) - mockSocket.HeapProfiler().OnReportHeapSnapshotProgress(func(eventData *profiler.ReportHeapSnapshotProgressEvent) { + soc.HeapProfiler().OnReportHeapSnapshotProgress(func(eventData *profiler.ReportHeapSnapshotProgressEvent) { resultChan <- eventData }) + mockResult := &profiler.ReportHeapSnapshotProgressEvent{ Done: 1, Total: 1, Finished: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeapProfiler.reportHeapSnapshotProgress", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *profiler.ReportHeapSnapshotProgressEvent) - mockSocket.HeapProfiler().OnReportHeapSnapshotProgress(func(eventData *profiler.ReportHeapSnapshotProgressEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeapProfiler.reportHeapSnapshotProgress", }) result = <-resultChan @@ -669,39 +495,32 @@ func TestHeapProfilerOnReportHeapSnapshotProgress(t *testing.T) { } func TestHeapProfilerOnResetProfiles(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHeapProfilerOnResetProfiles") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.ResetProfilesEvent) - mockSocket.HeapProfiler().OnResetProfiles(func(eventData *profiler.ResetProfilesEvent) { + soc.HeapProfiler().OnResetProfiles(func(eventData *profiler.ResetProfilesEvent) { resultChan <- eventData }) + mockResult := &profiler.ResetProfilesEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "HeapProfiler.resetProfiles", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *profiler.ResetProfilesEvent) - mockSocket.HeapProfiler().OnResetProfiles(func(eventData *profiler.ResetProfilesEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "HeapProfiler.resetProfiles", }) result = <-resultChan diff --git a/tot/socket/cdtp.indexed.db_test.go b/tot/socket/cdtp.indexed.db_test.go index 12fb401..3eef0cd 100644 --- a/tot/socket/cdtp.indexed.db_test.go +++ b/tot/socket/cdtp.indexed.db_test.go @@ -1,202 +1,141 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/indexed/db" ) func TestIndexedDBClearObjectStore(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBClearObjectStore") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.ClearObjectStoreParams{ SecurityOrigin: "security-origin", DatabaseName: "database-name", ObjectStoreName: "object-store-name", } - resultChan := mockSocket.IndexedDB().ClearObjectStore(params) mockResult := &db.ClearObjectStoreResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().ClearObjectStore(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IndexedDB().ClearObjectStore(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().ClearObjectStore(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBDeleteDatabase(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBDeleteDatabase") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.DeleteDatabaseParams{ SecurityOrigin: "security-origin", DatabaseName: "database-name", ObjectStoreName: "object-store-name", } - resultChan := mockSocket.IndexedDB().DeleteDatabase(params) mockResult := &db.DeleteDatabaseResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().DeleteDatabase(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IndexedDB().DeleteDatabase(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().DeleteDatabase(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBDeleteObjectStoreEntries(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBDeleteObjectStoreEntries") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.DeleteObjectStoreEntriesParams{ SecurityOrigin: "security-origin", DatabaseName: "database-name", } - resultChan := mockSocket.IndexedDB().DeleteObjectStoreEntries(params) mockResult := &db.DeleteObjectStoreEntriesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().DeleteObjectStoreEntries(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IndexedDB().DeleteObjectStoreEntries(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().DeleteObjectStoreEntries(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.IndexedDB().Disable() mockResult := &db.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IndexedDB().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.IndexedDB().Enable() mockResult := &db.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IndexedDB().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBRequestData(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBRequestData") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.RequestDataParams{ SecurityOrigin: "security-origin", @@ -224,7 +163,6 @@ func TestIndexedDBRequestData(t *testing.T) { UpperOpen: true, }, } - resultChan := mockSocket.IndexedDB().RequestData(params) mockResult := &db.RequestDataResult{ ObjectStoreDataEntries: []*db.DataEntry{{ Key: nil, @@ -233,13 +171,9 @@ func TestIndexedDBRequestData(t *testing.T) { }}, HasMore: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().RequestData(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -247,32 +181,24 @@ func TestIndexedDBRequestData(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.ObjectStoreDataEntries[0].Key, result.ObjectStoreDataEntries[0].Key) } - resultChan = mockSocket.IndexedDB().RequestData(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().RequestData(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBRequestDatabase(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBRequestDatabase") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.RequestDatabaseParams{ SecurityOrigin: "security-origin", DatabaseName: "database-name", } - resultChan := mockSocket.IndexedDB().RequestDatabase(params) mockResult := &db.RequestDatabaseResult{ DatabaseWithObjectStores: &db.DatabaseWithObjectStores{ Name: "name", @@ -298,13 +224,9 @@ func TestIndexedDBRequestDatabase(t *testing.T) { }}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().RequestDatabase(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -312,41 +234,29 @@ func TestIndexedDBRequestDatabase(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.DatabaseWithObjectStores.ObjectStores[0].KeyPath.Type, result.DatabaseWithObjectStores.ObjectStores[0].KeyPath.Type) } - resultChan = mockSocket.IndexedDB().RequestDatabase(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().RequestDatabase(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIndexedDBRequestDatabaseNames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIndexedDBRequestDatabaseNames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &db.RequestDatabaseNamesParams{ SecurityOrigin: "security-origin", } - resultChan := mockSocket.IndexedDB().RequestDatabaseNames(params) mockResult := &db.RequestDatabaseNamesResult{ DatabaseNames: []string{"db1", "db2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IndexedDB().RequestDatabaseNames(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -354,16 +264,8 @@ func TestIndexedDBRequestDatabaseNames(t *testing.T) { t.Errorf("Expected '%s', got '%s'", mockResult.DatabaseNames[0], result.DatabaseNames[0]) } - resultChan = mockSocket.IndexedDB().RequestDatabaseNames(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IndexedDB().RequestDatabaseNames(params) if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.input_test.go b/tot/socket/cdtp.input_test.go index c7ca703..12014d6 100644 --- a/tot/socket/cdtp.input_test.go +++ b/tot/socket/cdtp.input_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -10,20 +8,21 @@ import ( ) func TestInputDispatchKeyEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputDispatchKeyEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.DispatchKeyEventParams{ - Type: input.KeyEvent.KeyDown, - Modifiers: 1, - Timestamp: input.TimeSinceEpoch(time.Now().Unix()), - Text: "text", - UnmodifiedText: "unmodified text", - KeyIdentifier: "key-id", - Code: "code", - Key: "key", + Type: input.KeyEvent.KeyDown, + Modifiers: 1, + Timestamp: input.TimeSinceEpoch(time.Now().Unix()), + Text: "text", + UnmodifiedText: "unmodified text", + KeyIdentifier: "key-id", + Code: "code", + Key: "key", WindowsVirtualKeyCode: 1, NativeVirtualKeyCode: 1, AutoRepeat: true, @@ -31,39 +30,27 @@ func TestInputDispatchKeyEvent(t *testing.T) { IsSystemKey: true, Location: 1, } - resultChan := mockSocket.Input().DispatchKeyEvent(params) mockResult := &input.DispatchKeyEventResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().DispatchKeyEvent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().DispatchKeyEvent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().DispatchKeyEvent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputDispatchMouseEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputDispatchMouseEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.DispatchMouseEventParams{ Type: input.MouseEvent.MousePressed, @@ -76,39 +63,27 @@ func TestInputDispatchMouseEvent(t *testing.T) { DeltaX: 1, DeltaY: 1, } - resultChan := mockSocket.Input().DispatchMouseEvent(params) mockResult := &input.DispatchMouseEventResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().DispatchMouseEvent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().DispatchMouseEvent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().DispatchMouseEvent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputDispatchTouchEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputDispatchTouchEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.DispatchTouchEventParams{ Type: input.TouchEvent.TouchStart, @@ -124,39 +99,27 @@ func TestInputDispatchTouchEvent(t *testing.T) { Modifiers: 1, Timestamp: input.TimeSinceEpoch(time.Now().Unix()), } - resultChan := mockSocket.Input().DispatchTouchEvent(params) mockResult := &input.DispatchTouchEventResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().DispatchTouchEvent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().DispatchTouchEvent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().DispatchTouchEvent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputEmulateTouchFromMouseEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputEmulateTouchFromMouseEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.EmulateTouchFromMouseEventParams{ Type: input.MouseEvent.MousePressed, @@ -169,76 +132,52 @@ func TestInputEmulateTouchFromMouseEvent(t *testing.T) { Modifiers: 1, ClickCount: 1, } - resultChan := mockSocket.Input().EmulateTouchFromMouseEvent(params) mockResult := &input.EmulateTouchFromMouseEventResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().EmulateTouchFromMouseEvent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().EmulateTouchFromMouseEvent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().EmulateTouchFromMouseEvent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputSetIgnoreEvents(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputSetIgnoreEvents") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.SetIgnoreEventsParams{ Ignore: true, } - resultChan := mockSocket.Input().SetIgnoreEvents(params) mockResult := &input.SetIgnoreEventsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().SetIgnoreEvents(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().SetIgnoreEvents(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().SetIgnoreEvents(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputSynthesizePinchGesture(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputSynthesizePinchGesture") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.SynthesizePinchGestureParams{ X: 1, @@ -247,39 +186,27 @@ func TestInputSynthesizePinchGesture(t *testing.T) { RelativeSpeed: 1, GestureSourceType: input.GestureSourceType("gesture-source-type"), } - resultChan := mockSocket.Input().SynthesizePinchGesture(params) mockResult := &input.SynthesizePinchGestureResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().SynthesizePinchGesture(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().SynthesizePinchGesture(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().SynthesizePinchGesture(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputSynthesizeScrollGesture(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputSynthesizeScrollGesture") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.SynthesizeScrollGestureParams{ X: 1, @@ -295,39 +222,27 @@ func TestInputSynthesizeScrollGesture(t *testing.T) { RepeatDelayMs: 1, InteractionMarkerName: "marker-name", } - resultChan := mockSocket.Input().SynthesizeScrollGesture(params) mockResult := &input.SynthesizeScrollGestureResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().SynthesizeScrollGesture(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().SynthesizeScrollGesture(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().SynthesizeScrollGesture(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestInputSynthesizeTapGesture(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestInputSynthesizeTapGesture") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &input.SynthesizeTapGestureParams{ X: 1, @@ -336,29 +251,16 @@ func TestInputSynthesizeTapGesture(t *testing.T) { TapCount: 1, GestureSourceType: input.GestureSourceType("gesture-source-type"), } - resultChan := mockSocket.Input().SynthesizeTapGesture(params) mockResult := &input.SynthesizeTapGestureResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Input().SynthesizeTapGesture(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Input().SynthesizeTapGesture(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Input().SynthesizeTapGesture(params) if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.io_test.go b/tot/socket/cdtp.io_test.go index dce53b9..e03dc28 100644 --- a/tot/socket/cdtp.io_test.go +++ b/tot/socket/cdtp.io_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/io" @@ -10,66 +8,50 @@ import ( ) func TestIOClose(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIOClose") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &io.CloseParams{ Handle: io.StreamHandle("stream-handle"), } - resultChan := mockSocket.IO().Close(params) mockResult := &io.CloseResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IO().Close(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.IO().Close(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IO().Close(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIORead(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIORead") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &io.ReadParams{ Handle: io.StreamHandle("stream-handle"), Offset: 1, Size: 1, } - resultChan := mockSocket.IO().Read(params) mockResult := &io.ReadResult{ Base64Encoded: true, Data: "data", EOF: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IO().Read(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -77,41 +59,29 @@ func TestIORead(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Base64Encoded, result.Base64Encoded) } - resultChan = mockSocket.IO().Read(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IO().Read(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestIOResolveBlob(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestIOResolveBlob") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &io.ResolveBlobParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.IO().ResolveBlob(params) mockResult := &io.ResolveBlobResult{ UUID: "uuid", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.IO().ResolveBlob(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -119,16 +89,8 @@ func TestIOResolveBlob(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.UUID, result.UUID) } - resultChan = mockSocket.IO().ResolveBlob(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.IO().ResolveBlob(params) if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.layer.tree_test.go b/tot/socket/cdtp.layer.tree_test.go index fe7daee..049ca1f 100644 --- a/tot/socket/cdtp.layer.tree_test.go +++ b/tot/socket/cdtp.layer.tree_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom" @@ -10,25 +8,21 @@ import ( ) func TestLayerTreeCompositingReasons(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeCompositingReasons") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.CompositingReasonsParams{ LayerID: tree.LayerID("layer-id"), } - resultChan := mockSocket.LayerTree().CompositingReasons(params) mockResult := &tree.CompositingReasonsResult{ CompositingReasons: []string{"reason1", "reason2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().CompositingReasons(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -36,94 +30,63 @@ func TestLayerTreeCompositingReasons(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.CompositingReasons[0], result.CompositingReasons[0]) } - resultChan = mockSocket.LayerTree().CompositingReasons(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().CompositingReasons(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.LayerTree().Disable() mockResult := &tree.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.LayerTree().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.LayerTree().Enable() mockResult := &tree.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.LayerTree().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeLoadSnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeLoadSnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.LoadSnapshotParams{ Tiles: []*tree.PictureTile{{ @@ -132,17 +95,12 @@ func TestLayerTreeLoadSnapshot(t *testing.T) { Picture: "picture data", }}, } - resultChan := mockSocket.LayerTree().LoadSnapshot(params) mockResult := &tree.LoadSnapshotResult{ SnapshotID: tree.SnapshotID("snapshot-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().LoadSnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -150,41 +108,29 @@ func TestLayerTreeLoadSnapshot(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SnapshotID, result.SnapshotID) } - resultChan = mockSocket.LayerTree().LoadSnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().LoadSnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeMakeSnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeMakeSnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.MakeSnapshotParams{ LayerID: tree.LayerID("layer-id"), } - resultChan := mockSocket.LayerTree().MakeSnapshot(params) mockResult := &tree.MakeSnapshotResult{ SnapshotID: tree.SnapshotID("snapshot-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().MakeSnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -192,26 +138,19 @@ func TestLayerTreeMakeSnapshot(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SnapshotID, result.SnapshotID) } - resultChan = mockSocket.LayerTree().MakeSnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().MakeSnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeProfileSnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeProfileSnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.ProfileSnapshotParams{ SnapshotID: tree.SnapshotID("snapshot-id"), @@ -224,78 +163,54 @@ func TestLayerTreeProfileSnapshot(t *testing.T) { Height: 1, }, } - resultChan := mockSocket.LayerTree().ProfileSnapshot(params) mockResult := &tree.ProfileSnapshotResult{ Timings: []*tree.PaintProfile{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().ProfileSnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.LayerTree().ProfileSnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().ProfileSnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeReleaseSnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeReleaseSnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.ReleaseSnapshotParams{ SnapshotID: tree.SnapshotID("snapshot-id"), } - resultChan := mockSocket.LayerTree().ReleaseSnapshot(params) mockResult := &tree.ReleaseSnapshotResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().ReleaseSnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.LayerTree().ReleaseSnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().ReleaseSnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeReplaySnapshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeReplaySnapshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.ReplaySnapshotParams{ SnapshotID: tree.SnapshotID("snapshot-id"), @@ -303,17 +218,12 @@ func TestLayerTreeReplaySnapshot(t *testing.T) { ToStep: 2, Scale: 1, } - resultChan := mockSocket.LayerTree().ReplaySnapshot(params) mockResult := &tree.ReplaySnapshotResult{ DataURL: "data:urldata", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().ReplaySnapshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -321,41 +231,29 @@ func TestLayerTreeReplaySnapshot(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.DataURL, result.DataURL) } - resultChan = mockSocket.LayerTree().ReplaySnapshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().ReplaySnapshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeSnapshotCommandLog(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeSnapshotCommandLog") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tree.SnapshotCommandLogParams{ SnapshotID: tree.SnapshotID("snapshot-id"), } - resultChan := mockSocket.LayerTree().SnapshotCommandLog(params) mockResult := &tree.SnapshotCommandLogResult{ CommandLog: []map[string]string{{"command1": "log1"}}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.LayerTree().SnapshotCommandLog(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -363,31 +261,26 @@ func TestLayerTreeSnapshotCommandLog(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.CommandLog[0]["command1"], result.CommandLog[0]["command1"]) } - resultChan = mockSocket.LayerTree().SnapshotCommandLog(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.LayerTree().SnapshotCommandLog(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLayerTreeOnLayerPainted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeOnLayerPainted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *tree.LayerPaintedEvent) - mockSocket.LayerTree().OnLayerPainted(func(eventData *tree.LayerPaintedEvent) { + soc.LayerTree().OnLayerPainted(func(eventData *tree.LayerPaintedEvent) { resultChan <- eventData }) + mockResult := &tree.LayerPaintedEvent{ LayerID: tree.LayerID("layer-id"), Clip: &dom.Rect{ @@ -397,12 +290,10 @@ func TestLayerTreeOnLayerPainted(t *testing.T) { Height: 1, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "LayerTree.layerPainted", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -412,17 +303,9 @@ func TestLayerTreeOnLayerPainted(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.LayerID, result.LayerID) } - resultChan = make(chan *tree.LayerPaintedEvent) - mockSocket.LayerTree().OnLayerPainted(func(eventData *tree.LayerPaintedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "LayerTree.layerPainted", }) result = <-resultChan @@ -432,15 +315,18 @@ func TestLayerTreeOnLayerPainted(t *testing.T) { } func TestLayerTreeOnLayerTreeDidChange(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLayerTreeOnLayerTreeDidChange") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *tree.DidChangeEvent) - mockSocket.LayerTree().OnLayerTreeDidChange(func(eventData *tree.DidChangeEvent) { + soc.LayerTree().OnLayerTreeDidChange(func(eventData *tree.DidChangeEvent) { resultChan <- eventData }) + mockResult := &tree.DidChangeEvent{ Layers: []*tree.Layer{{ LayerID: tree.LayerID("layer-id"), @@ -469,12 +355,10 @@ func TestLayerTreeOnLayerTreeDidChange(t *testing.T) { }, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "LayerTree.layerTreeDidChange", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -484,17 +368,9 @@ func TestLayerTreeOnLayerTreeDidChange(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Layers[0].LayerID, result.Layers[0].LayerID) } - resultChan = make(chan *tree.DidChangeEvent) - mockSocket.LayerTree().OnLayerTreeDidChange(func(eventData *tree.DidChangeEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "LayerTree.layerTreeDidChange", }) result = <-resultChan diff --git a/tot/socket/cdtp.log_test.go b/tot/socket/cdtp.log_test.go index fd68b04..35c2b43 100644 --- a/tot/socket/cdtp.log_test.go +++ b/tot/socket/cdtp.log_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -12,112 +10,77 @@ import ( ) func TestLogClear(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogClear") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Log().Clear() mockResult := &log.ClearResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Log().Clear() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Log().Clear() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Log().Clear() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLogDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Log().Disable() mockResult := &log.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Log().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Log().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Log().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLogEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Log().Enable() mockResult := &log.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Log().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Log().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Log().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLogStartViolationsReport(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogStartViolationsReport") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &log.StartViolationsReportParams{ Config: []*log.ViolationSetting{{ @@ -125,78 +88,56 @@ func TestLogStartViolationsReport(t *testing.T) { Threshold: 1, }}, } - resultChan := mockSocket.Log().StartViolationsReport(params) mockResult := &log.StartViolationsReportResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Log().StartViolationsReport(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Log().StartViolationsReport(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Log().StartViolationsReport(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLogStopViolationsReport(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogStopViolationsReport") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Log().StopViolationsReport() mockResult := &log.StopViolationsReportResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Log().StopViolationsReport() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Log().StopViolationsReport() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Log().StopViolationsReport() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestLogOnEntryAdded(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestLogOnEntryAdded") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *log.EntryAddedEvent) - mockSocket.Log().OnEntryAdded(func(eventData *log.EntryAddedEvent) { + soc.Log().OnEntryAdded(func(eventData *log.EntryAddedEvent) { resultChan <- eventData }) + mockResult := &log.EntryAddedEvent{ Entry: &log.Entry{ Source: log.Source.XML, @@ -211,12 +152,10 @@ func TestLogOnEntryAdded(t *testing.T) { Args: []*runtime.RemoteObject{{}}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Log.entryAdded", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -226,17 +165,9 @@ func TestLogOnEntryAdded(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Entry.Source, result.Entry.Source) } - resultChan = make(chan *log.EntryAddedEvent) - mockSocket.Log().OnEntryAdded(func(eventData *log.EntryAddedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Log.entryAdded", }) result = <-resultChan diff --git a/tot/socket/cdtp.memory_test.go b/tot/socket/cdtp.memory_test.go index b117eab..9036722 100644 --- a/tot/socket/cdtp.memory_test.go +++ b/tot/socket/cdtp.memory_test.go @@ -1,155 +1,105 @@ package socket import ( - "encoding/json" - "net/url" "testing" memory "github.com/mkenney/go-chrome/tot/memory" ) func TestMemoryGetDOMCounters(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestMemoryGetDOMCounters") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &memory.GetDOMCountersParams{ Documents: 1, Nodes: 1, JsEventListeners: 1, } - resultChan := mockSocket.Memory().GetDOMCounters(params) mockResult := &memory.GetDOMCountersResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Memory().GetDOMCounters(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Memory().GetDOMCounters(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Memory().GetDOMCounters(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestMemoryPrepareForLeakDetection(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestMemoryPrepareForLeakDetection") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Memory().PrepareForLeakDetection() mockResult := &memory.PrepareForLeakDetectionResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Memory().PrepareForLeakDetection() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Memory().PrepareForLeakDetection() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Memory().PrepareForLeakDetection() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestMemorySetPressureNotificationsSuppressed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestMemorySetPressureNotificationsSuppressed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &memory.SetPressureNotificationsSuppressedParams{ Suppressed: true, } - resultChan := mockSocket.Memory().SetPressureNotificationsSuppressed(params) mockResult := &memory.SetPressureNotificationsSuppressedResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Memory().SetPressureNotificationsSuppressed(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Memory().SetPressureNotificationsSuppressed(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Memory().SetPressureNotificationsSuppressed(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestMemorySimulatePressureNotification(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestMemorySimulatePressureNotification") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &memory.SimulatePressureNotificationParams{ Level: memory.PressureLevel("pressure-level"), } - resultChan := mockSocket.Memory().SimulatePressureNotification(params) mockResult := &memory.SimulatePressureNotificationResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Memory().SimulatePressureNotification(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Memory().SimulatePressureNotification(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Memory().SimulatePressureNotification(params) if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.network_test.go b/tot/socket/cdtp.network_test.go index 01b8989..99ca1a3 100644 --- a/tot/socket/cdtp.network_test.go +++ b/tot/socket/cdtp.network_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -14,22 +12,18 @@ import ( ) func TestNetworkCanClearBrowserCache(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkCanClearBrowserCache") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().CanClearBrowserCache() mockResult := &network.CanClearBrowserCacheResult{ Result: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().CanClearBrowserCache() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -37,38 +31,26 @@ func TestNetworkCanClearBrowserCache(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Result, result.Result) } - resultChan = mockSocket.Network().CanClearBrowserCache() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().CanClearBrowserCache() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkCanClearBrowserCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkCanClearBrowserCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().CanClearBrowserCookies() mockResult := &network.CanClearBrowserCookiesResult{ Result: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().CanClearBrowserCookies() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -76,38 +58,26 @@ func TestNetworkCanClearBrowserCookies(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Result, result.Result) } - resultChan = mockSocket.Network().CanClearBrowserCookies() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().CanClearBrowserCookies() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkCanEmulateConditions(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkCanEmulateConditions") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().CanEmulateConditions() mockResult := &network.CanEmulateConditionsResult{ Result: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().CanEmulateConditions() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -115,94 +85,63 @@ func TestNetworkCanEmulateConditions(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Result, result.Result) } - resultChan = mockSocket.Network().CanEmulateConditions() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().CanEmulateConditions() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkClearBrowserCache(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkClearBrowserCache") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().ClearBrowserCache() mockResult := &network.ClearBrowserCacheResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().ClearBrowserCache() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().ClearBrowserCache() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().ClearBrowserCache() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkClearBrowserCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkClearBrowserCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().ClearBrowserCookies() mockResult := &network.ClearBrowserCookiesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().ClearBrowserCookies() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().ClearBrowserCookies() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().ClearBrowserCookies() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkContinueInterceptedRequest(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkContinueInterceptedRequest") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.ContinueInterceptedRequestParams{ InterceptionID: network.InterceptionID("interception-id"), @@ -218,39 +157,27 @@ func TestNetworkContinueInterceptedRequest(t *testing.T) { Password: "password", }, } - resultChan := mockSocket.Network().ContinueInterceptedRequest(params) mockResult := &network.ContinueInterceptedRequestResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().ContinueInterceptedRequest(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().ContinueInterceptedRequest(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().ContinueInterceptedRequest(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkDeleteCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkDeleteCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.DeleteCookiesParams{ Name: "name", @@ -258,73 +185,49 @@ func TestNetworkDeleteCookies(t *testing.T) { Domain: "some.url", Path: "/", } - resultChan := mockSocket.Network().DeleteCookies(params) mockResult := &network.DeleteCookiesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().DeleteCookies(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().DeleteCookies(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().DeleteCookies(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().Disable() mockResult := &network.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkEmulateConditions(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkEmulateConditions") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.EmulateConditionsParams{ Offline: true, @@ -333,78 +236,53 @@ func TestNetworkEmulateConditions(t *testing.T) { UploadThroughput: 1, ConnectionType: network.ConnectionType.None, } - resultChan := mockSocket.Network().EmulateConditions(params) mockResult := &network.EmulateConditionsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().EmulateConditions(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().EmulateConditions(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().EmulateConditions(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.EnableParams{ MaxTotalBufferSize: 1, MaxResourceBufferSize: 1, } - resultChan := mockSocket.Network().Enable(params) mockResult := &network.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().Enable(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().Enable(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().Enable(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkGetAllCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkGetAllCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Network().GetAllCookies() mockResult := &network.GetAllCookiesResult{ Cookies: []*network.Cookie{{ Name: "name", @@ -419,13 +297,9 @@ func TestNetworkGetAllCookies(t *testing.T) { SameSite: network.CookieSameSite.Strict, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().GetAllCookies() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -433,41 +307,29 @@ func TestNetworkGetAllCookies(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Cookies[0].Name, result.Cookies[0].Name) } - resultChan = mockSocket.Network().GetAllCookies() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().GetAllCookies() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkGetCertificate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkGetCertificate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.GetCertificateParams{ Origin: "origin", } - resultChan := mockSocket.Network().GetCertificate(params) mockResult := &network.GetCertificateResult{ TableNames: []string{"name1", "name2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().GetCertificate(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -475,31 +337,23 @@ func TestNetworkGetCertificate(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.TableNames[0], result.TableNames[0]) } - resultChan = mockSocket.Network().GetCertificate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().GetCertificate(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkGetCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkGetCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.GetCookiesParams{ URLs: []string{"url1", "url2"}, } - resultChan := mockSocket.Network().GetCookies(params) mockResult := &network.GetCookiesResult{ Cookies: []*network.Cookie{{ Name: "name", @@ -514,13 +368,9 @@ func TestNetworkGetCookies(t *testing.T) { SameSite: network.CookieSameSite.Strict, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().GetCookies(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -528,42 +378,30 @@ func TestNetworkGetCookies(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Cookies[0].Name, result.Cookies[0].Name) } - resultChan = mockSocket.Network().GetCookies(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().GetCookies(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkGetResponseBody(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkGetResponseBody") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.GetResponseBodyParams{ RequestID: network.RequestID("request-id"), } - resultChan := mockSocket.Network().GetResponseBody(params) mockResult := &network.GetResponseBodyResult{ Body: "body data", Base64Encoded: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().GetResponseBody(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -571,42 +409,30 @@ func TestNetworkGetResponseBody(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Body, result.Body) } - resultChan = mockSocket.Network().GetResponseBody(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().GetResponseBody(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkGetResponseBodyForInterception(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkGetResponseBodyForInterception") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.GetResponseBodyForInterceptionParams{ InterceptionID: network.InterceptionID("interception-id"), } - resultChan := mockSocket.Network().GetResponseBodyForInterception(params) mockResult := &network.GetResponseBodyForInterceptionResult{ Body: "body data", Base64Encoded: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().GetResponseBodyForInterception(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -614,63 +440,44 @@ func TestNetworkGetResponseBodyForInterception(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Body, result.Body) } - resultChan = mockSocket.Network().GetResponseBodyForInterception(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().GetResponseBodyForInterception(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkReplayXHR(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkReplayXHR") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.ReplayXHRParams{ RequestID: network.RequestID("request-id"), } - resultChan := mockSocket.Network().ReplayXHR(params) mockResult := &network.ReplayXHRResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().ReplayXHR(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().ReplayXHR(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().ReplayXHR(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSearchInResponseBody(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSearchInResponseBody") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SearchInResponseBodyParams{ RequestID: network.RequestID("request-id"), @@ -678,20 +485,15 @@ func TestNetworkSearchInResponseBody(t *testing.T) { CaseSensitive: true, IsRegex: true, } - resultChan := mockSocket.Network().SearchInResponseBody(params) mockResult := &network.SearchInResponseBodyResult{ Result: []*debugger.SearchMatch{{ LineNumber: 1, LineContent: "content", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SearchInResponseBody(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -699,137 +501,94 @@ func TestNetworkSearchInResponseBody(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Result[0].LineNumber, result.Result[0].LineNumber) } - resultChan = mockSocket.Network().SearchInResponseBody(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SearchInResponseBody(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetBlockedURLs(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetBlockedURLs") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetBlockedURLsParams{ URLs: []string{"http://url.1", "http://url.2"}, } - resultChan := mockSocket.Network().SetBlockedURLs(params) mockResult := &network.SetBlockedURLsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetBlockedURLs(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetBlockedURLs(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetBlockedURLs(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetBypassServiceWorker(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetBypassServiceWorker") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetBypassServiceWorkerParams{ Bypass: true, } - resultChan := mockSocket.Network().SetBypassServiceWorker(params) mockResult := &network.SetBypassServiceWorkerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetBypassServiceWorker(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetBypassServiceWorker(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetBypassServiceWorker(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetCacheDisabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetCacheDisabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetCacheDisabledParams{ CacheDisabled: true, } - resultChan := mockSocket.Network().SetCacheDisabled(params) mockResult := &network.SetCacheDisabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetCacheDisabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetCacheDisabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetCacheDisabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetCookie(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetCookie") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetCookieParams{ Name: "name", @@ -842,17 +601,12 @@ func TestNetworkSetCookie(t *testing.T) { SameSite: network.CookieSameSite.Strict, Expires: network.TimeSinceEpoch(time.Now().Unix()), } - resultChan := mockSocket.Network().SetCookie(params) mockResult := &network.SetCookieResult{ Success: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetCookie(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -860,26 +614,19 @@ func TestNetworkSetCookie(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Success, result.Success) } - resultChan = mockSocket.Network().SetCookie(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetCookie(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetCookies(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetCookies") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetCookiesParams{ Cookies: []*network.SetCookieParams{{ @@ -894,114 +641,78 @@ func TestNetworkSetCookies(t *testing.T) { Expires: network.TimeSinceEpoch(time.Now().Unix()), }}, } - resultChan := mockSocket.Network().SetCookies(params) mockResult := &network.SetCookiesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetCookies(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetCookies(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetCookies(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetDataSizeLimitsForTest(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetDataSizeLimitsForTest") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetDataSizeLimitsForTestParams{ MaxTotalSize: 1, MaxResourceSize: 1, } - resultChan := mockSocket.Network().SetDataSizeLimitsForTest(params) mockResult := &network.SetDataSizeLimitsForTestResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetDataSizeLimitsForTest(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetDataSizeLimitsForTest(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetDataSizeLimitsForTest(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetExtraHTTPHeaders(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetExtraHTTPHeaders") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetExtraHTTPHeadersParams{ Headers: network.Headers{"header1": "value1", "header2": "value2"}, } - resultChan := mockSocket.Network().SetExtraHTTPHeaders(params) mockResult := &network.SetExtraHTTPHeadersResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetExtraHTTPHeaders(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetExtraHTTPHeaders(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetExtraHTTPHeaders(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetRequestInterception(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetRequestInterception") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetRequestInterceptionParams{ Patterns: []*network.RequestPattern{{ @@ -1010,93 +721,70 @@ func TestNetworkSetRequestInterception(t *testing.T) { InterceptionStage: network.InterceptionStage.Request, }}, } - resultChan := mockSocket.Network().SetRequestInterception(params) mockResult := &network.SetRequestInterceptionResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetRequestInterception(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetRequestInterception(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetRequestInterception(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkSetUserAgentOverride(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkSetUserAgentOverride") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &network.SetUserAgentOverrideParams{ UserAgent: "user-agent", } - resultChan := mockSocket.Network().SetUserAgentOverride(params) mockResult := &network.SetUserAgentOverrideResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Network().SetUserAgentOverride(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Network().SetUserAgentOverride(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Network().SetUserAgentOverride(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestNetworkOnDataReceived(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnDataReceived") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.DataReceivedEvent) - mockSocket.Network().OnDataReceived(func(eventData *network.DataReceivedEvent) { + soc.Network().OnDataReceived(func(eventData *network.DataReceivedEvent) { resultChan <- eventData }) + mockResult := &network.DataReceivedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), DataLength: 1, EncodedDataLength: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.dataReceived", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1106,17 +794,9 @@ func TestNetworkOnDataReceived(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.DataReceivedEvent) - mockSocket.Network().OnDataReceived(func(eventData *network.DataReceivedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.dataReceived", }) result = <-resultChan @@ -1126,15 +806,18 @@ func TestNetworkOnDataReceived(t *testing.T) { } func TestNetworkOnEventSourceMessageReceived(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnEventSourceMessageReceived") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.EventSourceMessageReceivedEvent) - mockSocket.Network().OnEventSourceMessageReceived(func(eventData *network.EventSourceMessageReceivedEvent) { + soc.Network().OnEventSourceMessageReceived(func(eventData *network.EventSourceMessageReceivedEvent) { resultChan <- eventData }) + mockResult := &network.EventSourceMessageReceivedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1142,12 +825,10 @@ func TestNetworkOnEventSourceMessageReceived(t *testing.T) { EventID: "event-id", Data: "some data", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.eventSourceMessageReceived", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1157,17 +838,9 @@ func TestNetworkOnEventSourceMessageReceived(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.EventSourceMessageReceivedEvent) - mockSocket.Network().OnEventSourceMessageReceived(func(eventData *network.EventSourceMessageReceivedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.eventSourceMessageReceived", }) result = <-resultChan @@ -1177,15 +850,18 @@ func TestNetworkOnEventSourceMessageReceived(t *testing.T) { } func TestNetworkOnLoadingFailed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnLoadingFailed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.LoadingFailedEvent) - mockSocket.Network().OnLoadingFailed(func(eventData *network.LoadingFailedEvent) { + soc.Network().OnLoadingFailed(func(eventData *network.LoadingFailedEvent) { resultChan <- eventData }) + mockResult := &network.LoadingFailedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1194,12 +870,10 @@ func TestNetworkOnLoadingFailed(t *testing.T) { Canceled: true, BlockedReason: network.BlockedReason.Csp, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.loadingFailed", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1209,17 +883,9 @@ func TestNetworkOnLoadingFailed(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.LoadingFailedEvent) - mockSocket.Network().OnLoadingFailed(func(eventData *network.LoadingFailedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.loadingFailed", }) result = <-resultChan @@ -1229,26 +895,27 @@ func TestNetworkOnLoadingFailed(t *testing.T) { } func TestNetworkOnLoadingFinished(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnLoadingFinished") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.LoadingFinishedEvent) - mockSocket.Network().OnLoadingFinished(func(eventData *network.LoadingFinishedEvent) { + soc.Network().OnLoadingFinished(func(eventData *network.LoadingFinishedEvent) { resultChan <- eventData }) + mockResult := &network.LoadingFinishedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), EncodedDataLength: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.loadingFinished", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1258,17 +925,9 @@ func TestNetworkOnLoadingFinished(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.LoadingFinishedEvent) - mockSocket.Network().OnLoadingFinished(func(eventData *network.LoadingFinishedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.loadingFinished", }) result = <-resultChan @@ -1278,15 +937,18 @@ func TestNetworkOnLoadingFinished(t *testing.T) { } func TestNetworkOnRequestIntercepted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnRequestIntercepted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.RequestInterceptedEvent) - mockSocket.Network().OnRequestIntercepted(func(eventData *network.RequestInterceptedEvent) { + soc.Network().OnRequestIntercepted(func(eventData *network.RequestInterceptedEvent) { resultChan <- eventData }) + mockResult := &network.RequestInterceptedEvent{ InterceptionID: network.InterceptionID("interception-id"), Request: &network.Request{ @@ -1313,12 +975,10 @@ func TestNetworkOnRequestIntercepted(t *testing.T) { ResponseStatusCode: 400, ResponseHeaders: network.Headers{"header1": "value1"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.requestIntercepted", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1328,17 +988,9 @@ func TestNetworkOnRequestIntercepted(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.InterceptionID, result.InterceptionID) } - resultChan = make(chan *network.RequestInterceptedEvent) - mockSocket.Network().OnRequestIntercepted(func(eventData *network.RequestInterceptedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.requestIntercepted", }) result = <-resultChan @@ -1348,24 +1000,25 @@ func TestNetworkOnRequestIntercepted(t *testing.T) { } func TestNetworkOnRequestServedFromCache(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnRequestServedFromCache") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.RequestServedFromCacheEvent) - mockSocket.Network().OnRequestServedFromCache(func(eventData *network.RequestServedFromCacheEvent) { + soc.Network().OnRequestServedFromCache(func(eventData *network.RequestServedFromCacheEvent) { resultChan <- eventData }) + mockResult := &network.RequestServedFromCacheEvent{ RequestID: network.RequestID("request-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.requestServedFromCache", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1375,17 +1028,9 @@ func TestNetworkOnRequestServedFromCache(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.RequestServedFromCacheEvent) - mockSocket.Network().OnRequestServedFromCache(func(eventData *network.RequestServedFromCacheEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.requestServedFromCache", }) result = <-resultChan @@ -1395,15 +1040,18 @@ func TestNetworkOnRequestServedFromCache(t *testing.T) { } func TestNetworkOnRequestWillBeSent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnRequestWillBeSent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.RequestWillBeSentEvent) - mockSocket.Network().OnRequestWillBeSent(func(eventData *network.RequestWillBeSentEvent) { + soc.Network().OnRequestWillBeSent(func(eventData *network.RequestWillBeSentEvent) { resultChan <- eventData }) + mockResult := &network.RequestWillBeSentEvent{ RequestID: network.RequestID("request-id"), LoaderID: network.LoaderID("loader-id"), @@ -1489,12 +1137,10 @@ func TestNetworkOnRequestWillBeSent(t *testing.T) { Type: page.ResourceType.Document, FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.requestWillBeSent", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1504,17 +1150,9 @@ func TestNetworkOnRequestWillBeSent(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.RequestWillBeSentEvent) - mockSocket.Network().OnRequestWillBeSent(func(eventData *network.RequestWillBeSentEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.requestWillBeSent", }) result = <-resultChan @@ -1524,26 +1162,27 @@ func TestNetworkOnRequestWillBeSent(t *testing.T) { } func TestNetworkOnResourceChangedPriority(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnResourceChangedPriority") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.ResourceChangedPriorityEvent) - mockSocket.Network().OnResourceChangedPriority(func(eventData *network.ResourceChangedPriorityEvent) { + soc.Network().OnResourceChangedPriority(func(eventData *network.ResourceChangedPriorityEvent) { resultChan <- eventData }) + mockResult := &network.ResourceChangedPriorityEvent{ RequestID: network.RequestID("request-id"), NewPriority: network.ResourcePriority.VeryLow, Timestamp: network.MonotonicTime(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.resourceChangedPriority", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1553,17 +1192,9 @@ func TestNetworkOnResourceChangedPriority(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.ResourceChangedPriorityEvent) - mockSocket.Network().OnResourceChangedPriority(func(eventData *network.ResourceChangedPriorityEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.resourceChangedPriority", }) result = <-resultChan @@ -1573,15 +1204,18 @@ func TestNetworkOnResourceChangedPriority(t *testing.T) { } func TestNetworkOnResponseReceived(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnResponseReceived") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.ResponseReceivedEvent) - mockSocket.Network().OnResponseReceived(func(eventData *network.ResponseReceivedEvent) { + soc.Network().OnResponseReceived(func(eventData *network.ResponseReceivedEvent) { resultChan <- eventData }) + mockResult := &network.ResponseReceivedEvent{ RequestID: network.RequestID("request-id"), LoaderID: network.LoaderID("loader-id"), @@ -1590,12 +1224,10 @@ func TestNetworkOnResponseReceived(t *testing.T) { Response: &network.Response{}, FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.responseReceived", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1605,17 +1237,9 @@ func TestNetworkOnResponseReceived(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.ResponseReceivedEvent) - mockSocket.Network().OnResponseReceived(func(eventData *network.ResponseReceivedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.responseReceived", }) result = <-resultChan @@ -1625,25 +1249,26 @@ func TestNetworkOnResponseReceived(t *testing.T) { } func TestNetworkOnWebSocketClosed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketClosed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketClosedEvent) - mockSocket.Network().OnWebSocketClosed(func(eventData *network.WebSocketClosedEvent) { + soc.Network().OnWebSocketClosed(func(eventData *network.WebSocketClosedEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketClosedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketClosed", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1653,17 +1278,9 @@ func TestNetworkOnWebSocketClosed(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketClosedEvent) - mockSocket.Network().OnWebSocketClosed(func(eventData *network.WebSocketClosedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketClosed", }) result = <-resultChan @@ -1673,26 +1290,27 @@ func TestNetworkOnWebSocketClosed(t *testing.T) { } func TestNetworkOnWebSocketCreated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketCreated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketCreatedEvent) - mockSocket.Network().OnWebSocketCreated(func(eventData *network.WebSocketCreatedEvent) { + soc.Network().OnWebSocketCreated(func(eventData *network.WebSocketCreatedEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketCreatedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), ErrorMessage: "error message", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketCreated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1702,17 +1320,9 @@ func TestNetworkOnWebSocketCreated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketCreatedEvent) - mockSocket.Network().OnWebSocketCreated(func(eventData *network.WebSocketCreatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketCreated", }) result = <-resultChan @@ -1722,26 +1332,27 @@ func TestNetworkOnWebSocketCreated(t *testing.T) { } func TestNetworkOnWebSocketFrameError(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketFrameError") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketFrameErrorEvent) - mockSocket.Network().OnWebSocketFrameError(func(eventData *network.WebSocketFrameErrorEvent) { + soc.Network().OnWebSocketFrameError(func(eventData *network.WebSocketFrameErrorEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketFrameErrorEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), ErrorMessage: "error message", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketFrameError", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1751,17 +1362,9 @@ func TestNetworkOnWebSocketFrameError(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketFrameErrorEvent) - mockSocket.Network().OnWebSocketFrameError(func(eventData *network.WebSocketFrameErrorEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketFrameError", }) result = <-resultChan @@ -1771,15 +1374,18 @@ func TestNetworkOnWebSocketFrameError(t *testing.T) { } func TestNetworkOnWebSocketFrameReceived(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketFrameReceived") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketFrameReceivedEvent) - mockSocket.Network().OnWebSocketFrameReceived(func(eventData *network.WebSocketFrameReceivedEvent) { + soc.Network().OnWebSocketFrameReceived(func(eventData *network.WebSocketFrameReceivedEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketFrameReceivedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1789,12 +1395,10 @@ func TestNetworkOnWebSocketFrameReceived(t *testing.T) { PayloadData: "payload", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketFrameReceived", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1804,17 +1408,9 @@ func TestNetworkOnWebSocketFrameReceived(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketFrameReceivedEvent) - mockSocket.Network().OnWebSocketFrameReceived(func(eventData *network.WebSocketFrameReceivedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketFrameReceived", }) result = <-resultChan @@ -1824,15 +1420,18 @@ func TestNetworkOnWebSocketFrameReceived(t *testing.T) { } func TestNetworkOnWebSocketFrameSent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketFrameSent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketFrameSentEvent) - mockSocket.Network().OnWebSocketFrameSent(func(eventData *network.WebSocketFrameSentEvent) { + soc.Network().OnWebSocketFrameSent(func(eventData *network.WebSocketFrameSentEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketFrameSentEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1842,12 +1441,10 @@ func TestNetworkOnWebSocketFrameSent(t *testing.T) { PayloadData: "payload", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketFrameSent", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1857,17 +1454,9 @@ func TestNetworkOnWebSocketFrameSent(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketFrameSentEvent) - mockSocket.Network().OnWebSocketFrameSent(func(eventData *network.WebSocketFrameSentEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketFrameSent", }) result = <-resultChan @@ -1877,15 +1466,18 @@ func TestNetworkOnWebSocketFrameSent(t *testing.T) { } func TestNetworkOnWebSocketHandshakeResponseReceived(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketHandshakeResponseReceived") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketHandshakeResponseReceivedEvent) - mockSocket.Network().OnWebSocketHandshakeResponseReceived(func(eventData *network.WebSocketHandshakeResponseReceivedEvent) { + soc.Network().OnWebSocketHandshakeResponseReceived(func(eventData *network.WebSocketHandshakeResponseReceivedEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketHandshakeResponseReceivedEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1895,12 +1487,10 @@ func TestNetworkOnWebSocketHandshakeResponseReceived(t *testing.T) { PayloadData: "payload", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketHandshakeResponseReceived", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1910,17 +1500,9 @@ func TestNetworkOnWebSocketHandshakeResponseReceived(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketHandshakeResponseReceivedEvent) - mockSocket.Network().OnWebSocketHandshakeResponseReceived(func(eventData *network.WebSocketHandshakeResponseReceivedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketHandshakeResponseReceived", }) result = <-resultChan @@ -1930,15 +1512,18 @@ func TestNetworkOnWebSocketHandshakeResponseReceived(t *testing.T) { } func TestNetworkOnWebSocketWillSendHandshakeRequest(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNetworkOnWebSocketWillSendHandshakeRequest") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *network.WebSocketWillSendHandshakeRequestEvent) - mockSocket.Network().OnWebSocketWillSendHandshakeRequest(func(eventData *network.WebSocketWillSendHandshakeRequestEvent) { + soc.Network().OnWebSocketWillSendHandshakeRequest(func(eventData *network.WebSocketWillSendHandshakeRequestEvent) { resultChan <- eventData }) + mockResult := &network.WebSocketWillSendHandshakeRequestEvent{ RequestID: network.RequestID("request-id"), Timestamp: network.MonotonicTime(1), @@ -1947,12 +1532,10 @@ func TestNetworkOnWebSocketWillSendHandshakeRequest(t *testing.T) { Headers: network.Headers{"header1": "value1"}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Network.webSocketWillSendHandshakeRequest", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1962,17 +1545,9 @@ func TestNetworkOnWebSocketWillSendHandshakeRequest(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.RequestID, result.RequestID) } - resultChan = make(chan *network.WebSocketWillSendHandshakeRequestEvent) - mockSocket.Network().OnWebSocketWillSendHandshakeRequest(func(eventData *network.WebSocketWillSendHandshakeRequestEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Network.webSocketWillSendHandshakeRequest", }) result = <-resultChan diff --git a/tot/socket/cdtp.overlay_test.go b/tot/socket/cdtp.overlay_test.go index dc7a673..f0f38ad 100644 --- a/tot/socket/cdtp.overlay_test.go +++ b/tot/socket/cdtp.overlay_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/dom" @@ -12,93 +10,65 @@ import ( ) func TestOverlayDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Overlay().Disable() mockResult := &overlay.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Overlay().Enable() mockResult := &overlay.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayGetHighlightObjectForTest(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayGetHighlightObjectForTest") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.GetHighlightObjectForTestParams{ NodeID: dom.NodeID(1), } - resultChan := mockSocket.Overlay().GetHighlightObjectForTest(params) mockResult := &overlay.GetHighlightObjectForTestResult{ Highlight: map[string]string{"key": "data"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().GetHighlightObjectForTest(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -106,99 +76,68 @@ func TestOverlayGetHighlightObjectForTest(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Highlight["key"], result.Highlight["key"]) } - resultChan = mockSocket.Overlay().GetHighlightObjectForTest(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().GetHighlightObjectForTest(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayHideHighlight(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayHideHighlight") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Overlay().HideHighlight() mockResult := &overlay.HideHighlightResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().HideHighlight() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().HideHighlight() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().HideHighlight() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayHighlightFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayHighlightFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.HighlightFrameParams{ FrameID: page.FrameID("frame-id"), ContentColor: &dom.RGBA{}, ContentOutlineColor: &dom.RGBA{}, } - resultChan := mockSocket.Overlay().HighlightFrame(params) mockResult := &overlay.HighlightFrameResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().HighlightFrame(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().HighlightFrame(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().HighlightFrame(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayHighlightNode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayHighlightNode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.HighlightNodeParams{ HighlightConfig: &overlay.HighlightConfig{}, @@ -206,78 +145,54 @@ func TestOverlayHighlightNode(t *testing.T) { BackendNodeID: dom.BackendNodeID(1), ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.Overlay().HighlightNode(params) mockResult := &overlay.HighlightNodeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().HighlightNode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().HighlightNode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().HighlightNode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayHighlightQuad(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayHighlightQuad") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.HighlightQuadParams{ Quad: dom.Quad{1, 2}, Color: &dom.RGBA{}, OutlineColor: &dom.RGBA{}, } - resultChan := mockSocket.Overlay().HighlightQuad(params) mockResult := &overlay.HighlightQuadResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().HighlightQuad(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().HighlightQuad(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().HighlightQuad(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayHighlightRect(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayHighlightRect") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.HighlightRectParams{ X: 1, @@ -287,349 +202,241 @@ func TestOverlayHighlightRect(t *testing.T) { Color: &dom.RGBA{}, OutlineColor: &dom.RGBA{}, } - resultChan := mockSocket.Overlay().HighlightRect(params) mockResult := &overlay.HighlightRectResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().HighlightRect(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().HighlightRect(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().HighlightRect(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetInspectMode(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetInspectMode") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetInspectModeParams{ Mode: overlay.InspectMode.SearchForNode, } - resultChan := mockSocket.Overlay().SetInspectMode(params) mockResult := &overlay.SetInspectModeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetInspectMode(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetInspectMode(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetInspectMode(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetPausedInDebuggerMessage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetPausedInDebuggerMessage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetPausedInDebuggerMessageParams{ Message: "message", } - resultChan := mockSocket.Overlay().SetPausedInDebuggerMessage(params) mockResult := &overlay.SetPausedInDebuggerMessageResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetPausedInDebuggerMessage(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetPausedInDebuggerMessage(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetPausedInDebuggerMessage(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetShowDebugBorders(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetShowDebugBorders") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetShowDebugBordersParams{ Show: true, } - resultChan := mockSocket.Overlay().SetShowDebugBorders(params) mockResult := &overlay.SetShowDebugBordersResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetShowDebugBorders(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetShowDebugBorders(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetShowDebugBorders(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetShowFPSCounter(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetShowFPSCounter") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetShowFPSCounterParams{ Show: true, } - resultChan := mockSocket.Overlay().SetShowFPSCounter(params) mockResult := &overlay.SetShowFPSCounterResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetShowFPSCounter(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetShowFPSCounter(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetShowFPSCounter(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetShowPaintRects(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetShowPaintRects") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetShowPaintRectsParams{ Result: true, } - resultChan := mockSocket.Overlay().SetShowPaintRects(params) mockResult := &overlay.SetShowPaintRectsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetShowPaintRects(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetShowPaintRects(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetShowPaintRects(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetShowScrollBottleneckRects(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetShowScrollBottleneckRects") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetShowScrollBottleneckRectsParams{ Show: true, } - resultChan := mockSocket.Overlay().SetShowScrollBottleneckRects(params) mockResult := &overlay.SetShowScrollBottleneckRectsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetShowScrollBottleneckRects(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetShowScrollBottleneckRects(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetShowScrollBottleneckRects(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetShowViewportSizeOnResize(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetShowViewportSizeOnResize") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetShowViewportSizeOnResizeParams{ Show: true, } - resultChan := mockSocket.Overlay().SetShowViewportSizeOnResize(params) mockResult := &overlay.SetShowViewportSizeOnResizeResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetShowViewportSizeOnResize(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetShowViewportSizeOnResize(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetShowViewportSizeOnResize(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlaySetSuspended(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlaySetSuspended") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &overlay.SetSuspendedParams{ Suspended: true, } - resultChan := mockSocket.Overlay().SetSuspended(params) mockResult := &overlay.SetSuspendedResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Overlay().SetSuspended(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Overlay().SetSuspended(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Overlay().SetSuspended(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestOverlayOnInspectNodeRequested(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayOnInspectNodeRequested") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *overlay.InspectNodeRequestedEvent) - mockSocket.Overlay().OnInspectNodeRequested(func(eventData *overlay.InspectNodeRequestedEvent) { + soc.Overlay().OnInspectNodeRequested(func(eventData *overlay.InspectNodeRequestedEvent) { resultChan <- eventData }) + mockResult := &overlay.InspectNodeRequestedEvent{ BackendNodeID: dom.BackendNodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Overlay.inspectNodeRequested", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -639,17 +446,9 @@ func TestOverlayOnInspectNodeRequested(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.BackendNodeID, result.BackendNodeID) } - resultChan = make(chan *overlay.InspectNodeRequestedEvent) - mockSocket.Overlay().OnInspectNodeRequested(func(eventData *overlay.InspectNodeRequestedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Overlay.inspectNodeRequested", }) result = <-resultChan @@ -659,24 +458,25 @@ func TestOverlayOnInspectNodeRequested(t *testing.T) { } func TestOverlayOnNodeHighlightRequested(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayOnNodeHighlightRequested") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *overlay.NodeHighlightRequestedEvent) - mockSocket.Overlay().OnNodeHighlightRequested(func(eventData *overlay.NodeHighlightRequestedEvent) { + soc.Overlay().OnNodeHighlightRequested(func(eventData *overlay.NodeHighlightRequestedEvent) { resultChan <- eventData }) + mockResult := &overlay.NodeHighlightRequestedEvent{ NodeID: dom.NodeID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Overlay.nodeHighlightRequested", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -686,17 +486,9 @@ func TestOverlayOnNodeHighlightRequested(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.NodeID, result.NodeID) } - resultChan = make(chan *overlay.NodeHighlightRequestedEvent) - mockSocket.Overlay().OnNodeHighlightRequested(func(eventData *overlay.NodeHighlightRequestedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Overlay.nodeHighlightRequested", }) result = <-resultChan @@ -706,15 +498,18 @@ func TestOverlayOnNodeHighlightRequested(t *testing.T) { } func TestOverlayOnScreenshotRequested(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestOverlayOnScreenshotRequested") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *overlay.ScreenshotRequestedEvent) - mockSocket.Overlay().OnScreenshotRequested(func(eventData *overlay.ScreenshotRequestedEvent) { + soc.Overlay().OnScreenshotRequested(func(eventData *overlay.ScreenshotRequestedEvent) { resultChan <- eventData }) + mockResult := &overlay.ScreenshotRequestedEvent{ Viewport: &page.Viewport{ X: 1, @@ -724,12 +519,10 @@ func TestOverlayOnScreenshotRequested(t *testing.T) { Scale: 5, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Overlay.screenshotRequested", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -739,17 +532,9 @@ func TestOverlayOnScreenshotRequested(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Viewport.X, result.Viewport.X) } - resultChan = make(chan *overlay.ScreenshotRequestedEvent) - mockSocket.Overlay().OnScreenshotRequested(func(eventData *overlay.ScreenshotRequestedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Overlay.screenshotRequested", }) result = <-resultChan diff --git a/tot/socket/cdtp.page_test.go b/tot/socket/cdtp.page_test.go index 41f95b2..dbb196e 100644 --- a/tot/socket/cdtp.page_test.go +++ b/tot/socket/cdtp.page_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -12,25 +10,21 @@ import ( ) func TestPageAddScriptToEvaluateOnLoad(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageAddScriptToEvaluateOnLoad") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.AddScriptToEvaluateOnLoadParams{ ScriptSource: "some-source", } - resultChan := mockSocket.Page().AddScriptToEvaluateOnLoad(params) mockResult := &page.AddScriptToEvaluateOnLoadResult{ Identifier: page.ScriptIdentifier("script-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().AddScriptToEvaluateOnLoad(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -38,41 +32,29 @@ func TestPageAddScriptToEvaluateOnLoad(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Identifier, result.Identifier) } - resultChan = mockSocket.Page().AddScriptToEvaluateOnLoad(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().AddScriptToEvaluateOnLoad(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageAddScriptToEvaluateOnNewDocument(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageAddScriptToEvaluateOnNewDocument") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.AddScriptToEvaluateOnNewDocumentParams{ Source: "some-source", } - resultChan := mockSocket.Page().AddScriptToEvaluateOnNewDocument(params) mockResult := &page.AddScriptToEvaluateOnNewDocumentResult{ Identifier: page.ScriptIdentifier("script-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().AddScriptToEvaluateOnNewDocument(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -80,60 +62,41 @@ func TestPageAddScriptToEvaluateOnNewDocument(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Identifier, result.Identifier) } - resultChan = mockSocket.Page().AddScriptToEvaluateOnNewDocument(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().AddScriptToEvaluateOnNewDocument(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageBringToFront(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageBringToFront") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().BringToFront() mockResult := &page.BringToFrontResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().BringToFront() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().BringToFront() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().BringToFront() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageCaptureScreenshot(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageCaptureScreenshot") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.CaptureScreenshotParams{ Format: page.Format.Jpeg, @@ -147,17 +110,12 @@ func TestPageCaptureScreenshot(t *testing.T) { }, FromSurface: true, } - resultChan := mockSocket.Page().CaptureScreenshot(params) mockResult := &page.CaptureScreenshotResult{ Data: "screenshot data", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().CaptureScreenshot(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -165,43 +123,31 @@ func TestPageCaptureScreenshot(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Data, result.Data) } - resultChan = mockSocket.Page().CaptureScreenshot(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().CaptureScreenshot(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageCreateIsolatedWorld(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageCreateIsolatedWorld") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.CreateIsolatedWorldParams{ FrameID: page.FrameID("frame-id"), WorldName: "world-name", GrantUniveralAccess: true, } - resultChan := mockSocket.Page().CreateIsolatedWorld(params) mockResult := &page.CreateIsolatedWorldResult{ ExecutionContextID: runtime.ExecutionContextID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().CreateIsolatedWorld(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -209,94 +155,63 @@ func TestPageCreateIsolatedWorld(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.ExecutionContextID, result.ExecutionContextID) } - resultChan = mockSocket.Page().CreateIsolatedWorld(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().CreateIsolatedWorld(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().Disable() mockResult := &page.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().Enable() mockResult := &page.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetAppManifest(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetAppManifest") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.GetAppManifestParams{ URL: "http://some.url", @@ -308,41 +223,28 @@ func TestPageGetAppManifest(t *testing.T) { }}, Data: "some data", } - resultChan := mockSocket.Page().GetAppManifest(params) mockResult := &page.GetAppManifestResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetAppManifest(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().GetAppManifest(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetAppManifest(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetFrameTree(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetFrameTree") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().GetFrameTree() mockResult := &page.GetFrameTreeResult{ FrameTree: &page.FrameTree{ Frame: &page.Frame{ @@ -358,13 +260,9 @@ func TestPageGetFrameTree(t *testing.T) { ChildFrames: []*page.FrameTree{}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetFrameTree() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -372,28 +270,20 @@ func TestPageGetFrameTree(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameTree.Frame.ID, result.FrameTree.Frame.ID) } - resultChan = mockSocket.Page().GetFrameTree() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetFrameTree() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetLayoutMetrics(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetLayoutMetrics") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().GetLayoutMetrics() mockResult := &page.GetLayoutMetricsResult{ LayoutViewport: &page.LayoutViewport{ PageX: 1, @@ -417,13 +307,9 @@ func TestPageGetLayoutMetrics(t *testing.T) { Height: 1, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetLayoutMetrics() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -431,28 +317,20 @@ func TestPageGetLayoutMetrics(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.LayoutViewport.PageX, result.LayoutViewport.PageX) } - resultChan = mockSocket.Page().GetLayoutMetrics() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetLayoutMetrics() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetNavigationHistory(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetNavigationHistory") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().GetNavigationHistory() mockResult := &page.GetNavigationHistoryResult{ CurrentIndex: 1, Entries: []*page.NavigationEntry{{ @@ -463,13 +341,9 @@ func TestPageGetNavigationHistory(t *testing.T) { TransitionType: page.TransitionType("type"), }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetNavigationHistory() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -477,42 +351,30 @@ func TestPageGetNavigationHistory(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.CurrentIndex, result.CurrentIndex) } - resultChan = mockSocket.Page().GetNavigationHistory() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetNavigationHistory() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetResourceContent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetResourceContent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.GetResourceContentParams{ FrameID: page.FrameID("frame-id"), } - resultChan := mockSocket.Page().GetResourceContent(params) mockResult := &page.GetResourceContentResult{ Content: "content", Base64Encoded: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetResourceContent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -520,28 +382,20 @@ func TestPageGetResourceContent(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Content, result.Content) } - resultChan = mockSocket.Page().GetResourceContent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetResourceContent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageGetResourceTree(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageGetResourceTree") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().GetResourceTree() mockResult := &page.GetResourceTreeResult{ FrameTree: &page.FrameResourceTree{ Frame: &page.Frame{ @@ -558,13 +412,9 @@ func TestPageGetResourceTree(t *testing.T) { Resources: []*page.FrameResource{}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().GetResourceTree() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -572,83 +422,59 @@ func TestPageGetResourceTree(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameTree.Frame.ID, result.FrameTree.Frame.ID) } - resultChan = mockSocket.Page().GetResourceTree() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().GetResourceTree() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageHandleJavaScriptDialog(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageHandleJavaScriptDialog") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.HandleJavaScriptDialogParams{ Accept: true, PromptText: "prompt text", } - resultChan := mockSocket.Page().HandleJavaScriptDialog(params) mockResult := &page.HandleJavaScriptDialogResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().HandleJavaScriptDialog(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().HandleJavaScriptDialog(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().HandleJavaScriptDialog(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageNavigate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageNavigate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.NavigateParams{ URL: "http://some.url", Referrer: "http://referrer.url", TransitionType: page.TransitionType("transition-type"), } - resultChan := mockSocket.Page().Navigate(params) mockResult := &page.NavigateResult{ FrameID: page.FrameID("frame-id"), LoaderID: page.LoaderID("loader-id"), ErrorText: "error text", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().Navigate(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -656,63 +482,44 @@ func TestPageNavigate(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = mockSocket.Page().Navigate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().Navigate(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageNavigateToHistoryEntry(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageNavigateToHistoryEntry") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.NavigateToHistoryEntryParams{ EntryID: 1, } - resultChan := mockSocket.Page().NavigateToHistoryEntry(params) mockResult := &page.NavigateToHistoryEntryResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().NavigateToHistoryEntry(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().NavigateToHistoryEntry(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().NavigateToHistoryEntry(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPagePrintToPDF(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPagePrintToPDF") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.PrintToPDFParams{ Landscape: true, @@ -728,17 +535,12 @@ func TestPagePrintToPDF(t *testing.T) { PageRanges: "1-2", IgnoreInvalidPageRanges: true, } - resultChan := mockSocket.Page().PrintToPDF(params) mockResult := &page.PrintToPDFResult{ Data: "result data", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().PrintToPDF(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -746,209 +548,142 @@ func TestPagePrintToPDF(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Data, result.Data) } - resultChan = mockSocket.Page().PrintToPDF(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().PrintToPDF(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageReload(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageReload") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.ReloadParams{ IgnoreCache: true, ScriptToEvaluateOnLoad: "some-script", } - resultChan := mockSocket.Page().Reload(params) mockResult := &page.ReloadResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().Reload(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().Reload(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().Reload(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageRemoveScriptToEvaluateOnLoad(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageRemoveScriptToEvaluateOnLoad") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.RemoveScriptToEvaluateOnLoadParams{ Identifier: page.ScriptIdentifier("script-id"), } - resultChan := mockSocket.Page().RemoveScriptToEvaluateOnLoad(params) mockResult := &page.RemoveScriptToEvaluateOnLoadResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().RemoveScriptToEvaluateOnLoad(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().RemoveScriptToEvaluateOnLoad(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().RemoveScriptToEvaluateOnLoad(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageRemoveScriptToEvaluateOnNewDocument(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageRemoveScriptToEvaluateOnNewDocument") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.RemoveScriptToEvaluateOnNewDocumentParams{ Identifier: page.ScriptIdentifier("script-id"), } - resultChan := mockSocket.Page().RemoveScriptToEvaluateOnNewDocument(params) mockResult := &page.RemoveScriptToEvaluateOnNewDocumentResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().RemoveScriptToEvaluateOnNewDocument(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().RemoveScriptToEvaluateOnNewDocument(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().RemoveScriptToEvaluateOnNewDocument(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageRequestAppBanner(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageRequestAppBanner") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().RequestAppBanner() mockResult := &page.RequestAppBannerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().RequestAppBanner() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().RequestAppBanner() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().RequestAppBanner() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageScreencastFrameAck(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageScreencastFrameAck") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.ScreencastFrameAckParams{ SessionID: 1, } - resultChan := mockSocket.Page().ScreencastFrameAck(params) mockResult := &page.ScreencastFrameAckResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().ScreencastFrameAck(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().ScreencastFrameAck(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().ScreencastFrameAck(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSearchInResource(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSearchInResource") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SearchInResourceParams{ FrameID: page.FrameID("frame-id"), @@ -957,20 +692,15 @@ func TestPageSearchInResource(t *testing.T) { CaseSensitive: true, IsRegex: true, } - resultChan := mockSocket.Page().SearchInResource(params) mockResult := &page.SearchInResourceResult{ Result: []*debugger.SearchMatch{{ LineNumber: 1, LineContent: "some content", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SearchInResource(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -978,213 +708,146 @@ func TestPageSearchInResource(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Result[0].LineNumber, result.Result[0].LineNumber) } - resultChan = mockSocket.Page().SearchInResource(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SearchInResource(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSetAdBlockingEnabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSetAdBlockingEnabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SetAdBlockingEnabledParams{ Enabled: true, } - resultChan := mockSocket.Page().SetAdBlockingEnabled(params) mockResult := &page.SetAdBlockingEnabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SetAdBlockingEnabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().SetAdBlockingEnabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SetAdBlockingEnabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSetAutoAttachToCreatedPages(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSetAutoAttachToCreatedPages") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SetAutoAttachToCreatedPagesParams{ AutoAttach: true, } - resultChan := mockSocket.Page().SetAutoAttachToCreatedPages(params) mockResult := &page.SetAutoAttachToCreatedPagesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SetAutoAttachToCreatedPages(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().SetAutoAttachToCreatedPages(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SetAutoAttachToCreatedPages(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSetDocumentContent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSetDocumentContent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SetDocumentContentParams{ FrameID: page.FrameID("frame-id"), HTML: "html", } - resultChan := mockSocket.Page().SetDocumentContent(params) mockResult := &page.SetDocumentContentResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SetDocumentContent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().SetDocumentContent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SetDocumentContent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSetDownloadBehavior(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSetDownloadBehavior") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SetDownloadBehaviorParams{ Behavior: page.Behavior.Allow, DownloadPath: "/some/path", } - resultChan := mockSocket.Page().SetDownloadBehavior(params) mockResult := &page.SetDownloadBehaviorResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SetDownloadBehavior(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().SetDownloadBehavior(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SetDownloadBehavior(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageSetLifecycleEventsEnabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageSetLifecycleEventsEnabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.SetLifecycleEventsEnabledParams{ Enabled: true, } - resultChan := mockSocket.Page().SetLifecycleEventsEnabled(params) mockResult := &page.SetLifecycleEventsEnabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().SetLifecycleEventsEnabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().SetLifecycleEventsEnabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().SetLifecycleEventsEnabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageStartScreencast(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageStartScreencast") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &page.StartScreencastParams{ Format: page.Format.Jpeg, @@ -1193,121 +856,85 @@ func TestPageStartScreencast(t *testing.T) { MaxHeight: 1, EveryNthFrame: 1, } - resultChan := mockSocket.Page().StartScreencast(params) mockResult := &page.StartScreencastResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().StartScreencast(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().StartScreencast(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().StartScreencast(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageStopLoading(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageStopLoading") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().StopLoading() mockResult := &page.StopLoadingResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().StopLoading() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().StopLoading() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().StopLoading() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageStopScreencast(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageStopScreencast") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Page().StopScreencast() mockResult := &page.StopScreencastResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Page().StopScreencast() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Page().StopScreencast() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Page().StopScreencast() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPageOnDOMContentEventFired(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnDOMContentEventFired") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.DOMContentEventFiredEvent) - mockSocket.Page().OnDOMContentEventFired(func(eventData *page.DOMContentEventFiredEvent) { + soc.Page().OnDOMContentEventFired(func(eventData *page.DOMContentEventFiredEvent) { resultChan <- eventData }) + mockResult := &page.DOMContentEventFiredEvent{ Timestamp: page.MonotonicTime(time.Now().Unix()), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.domContentEventFired", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1317,17 +944,9 @@ func TestPageOnDOMContentEventFired(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Timestamp, result.Timestamp) } - resultChan = make(chan *page.DOMContentEventFiredEvent) - mockSocket.Page().OnDOMContentEventFired(func(eventData *page.DOMContentEventFiredEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.domContentEventFired", }) result = <-resultChan @@ -1337,26 +956,27 @@ func TestPageOnDOMContentEventFired(t *testing.T) { } func TestPageOnFrameAttached(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameAttached") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameAttachedEvent) - mockSocket.Page().OnFrameAttached(func(eventData *page.FrameAttachedEvent) { + soc.Page().OnFrameAttached(func(eventData *page.FrameAttachedEvent) { resultChan <- eventData }) + mockResult := &page.FrameAttachedEvent{ FrameID: page.FrameID("frame-id"), ParentFrameID: page.FrameID("parent-id"), Stack: &runtime.StackTrace{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameAttached", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1366,17 +986,9 @@ func TestPageOnFrameAttached(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameAttachedEvent) - mockSocket.Page().OnFrameAttached(func(eventData *page.FrameAttachedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameAttached", }) result = <-resultChan @@ -1386,24 +998,25 @@ func TestPageOnFrameAttached(t *testing.T) { } func TestPageOnFrameClearedScheduledNavigation(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameClearedScheduledNavigation") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameClearedScheduledNavigationEvent) - mockSocket.Page().OnFrameClearedScheduledNavigation(func(eventData *page.FrameClearedScheduledNavigationEvent) { + soc.Page().OnFrameClearedScheduledNavigation(func(eventData *page.FrameClearedScheduledNavigationEvent) { resultChan <- eventData }) + mockResult := &page.FrameClearedScheduledNavigationEvent{ FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameClearedScheduledNavigation", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1413,17 +1026,9 @@ func TestPageOnFrameClearedScheduledNavigation(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameClearedScheduledNavigationEvent) - mockSocket.Page().OnFrameClearedScheduledNavigation(func(eventData *page.FrameClearedScheduledNavigationEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameClearedScheduledNavigation", }) result = <-resultChan @@ -1433,24 +1038,24 @@ func TestPageOnFrameClearedScheduledNavigation(t *testing.T) { } func TestPageOnFrameDetached(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameDetached") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := make(chan *page.FrameDetachedEvent) - mockSocket.Page().OnFrameDetached(func(eventData *page.FrameDetachedEvent) { - resultChan <- eventData - }) mockResult := &page.FrameDetachedEvent{ FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameDetached", - Params: mockResultBytes, + }) + resultChan := make(chan *page.FrameDetachedEvent) + soc.Page().OnFrameDetached(func(eventData *page.FrameDetachedEvent) { + resultChan <- eventData }) result := <-resultChan if mockResult.Err != result.Err { @@ -1460,17 +1065,9 @@ func TestPageOnFrameDetached(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameDetachedEvent) - mockSocket.Page().OnFrameDetached(func(eventData *page.FrameDetachedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameDetached", }) result = <-resultChan @@ -1480,15 +1077,18 @@ func TestPageOnFrameDetached(t *testing.T) { } func TestPageOnFrameNavigated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameNavigated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameNavigatedEvent) - mockSocket.Page().OnFrameNavigated(func(eventData *page.FrameNavigatedEvent) { + soc.Page().OnFrameNavigated(func(eventData *page.FrameNavigatedEvent) { resultChan <- eventData }) + mockResult := &page.FrameNavigatedEvent{ Frame: &page.Frame{ ID: "frame-id", @@ -1501,12 +1101,10 @@ func TestPageOnFrameNavigated(t *testing.T) { UnreachableURL: "http://someother.url", }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameNavigated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1516,17 +1114,9 @@ func TestPageOnFrameNavigated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Frame.ID, result.Frame.ID) } - resultChan = make(chan *page.FrameNavigatedEvent) - mockSocket.Page().OnFrameNavigated(func(eventData *page.FrameNavigatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameNavigated", }) result = <-resultChan @@ -1536,39 +1126,32 @@ func TestPageOnFrameNavigated(t *testing.T) { } func TestPageOnFrameResized(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameResized") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameResizedEvent) - mockSocket.Page().OnFrameResized(func(eventData *page.FrameResizedEvent) { + soc.Page().OnFrameResized(func(eventData *page.FrameResizedEvent) { resultChan <- eventData }) + mockResult := &page.FrameResizedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameResized", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *page.FrameResizedEvent) - mockSocket.Page().OnFrameResized(func(eventData *page.FrameResizedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameResized", }) result = <-resultChan @@ -1578,27 +1161,28 @@ func TestPageOnFrameResized(t *testing.T) { } func TestPageOnFrameScheduledNavigation(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameScheduledNavigation") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameScheduledNavigationEvent) - mockSocket.Page().OnFrameScheduledNavigation(func(eventData *page.FrameScheduledNavigationEvent) { + soc.Page().OnFrameScheduledNavigation(func(eventData *page.FrameScheduledNavigationEvent) { resultChan <- eventData }) + mockResult := &page.FrameScheduledNavigationEvent{ FrameID: page.FrameID("frame-id"), Delay: 1, Reason: page.Reason.FormSubmissionGet, URL: "http://some.url", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameScheduledNavigation", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1608,17 +1192,9 @@ func TestPageOnFrameScheduledNavigation(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameScheduledNavigationEvent) - mockSocket.Page().OnFrameScheduledNavigation(func(eventData *page.FrameScheduledNavigationEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameScheduledNavigation", }) result = <-resultChan @@ -1628,24 +1204,25 @@ func TestPageOnFrameScheduledNavigation(t *testing.T) { } func TestPageOnFrameStartedLoading(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameStartedLoading") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameStartedLoadingEvent) - mockSocket.Page().OnFrameStartedLoading(func(eventData *page.FrameStartedLoadingEvent) { + soc.Page().OnFrameStartedLoading(func(eventData *page.FrameStartedLoadingEvent) { resultChan <- eventData }) + mockResult := &page.FrameStartedLoadingEvent{ FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameStartedLoading", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1655,17 +1232,9 @@ func TestPageOnFrameStartedLoading(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameStartedLoadingEvent) - mockSocket.Page().OnFrameStartedLoading(func(eventData *page.FrameStartedLoadingEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameStartedLoading", }) result = <-resultChan @@ -1675,24 +1244,25 @@ func TestPageOnFrameStartedLoading(t *testing.T) { } func TestPageOnFrameStoppedLoading(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnFrameStoppedLoading") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.FrameStoppedLoadingEvent) - mockSocket.Page().OnFrameStoppedLoading(func(eventData *page.FrameStoppedLoadingEvent) { + soc.Page().OnFrameStoppedLoading(func(eventData *page.FrameStoppedLoadingEvent) { resultChan <- eventData }) + mockResult := &page.FrameStoppedLoadingEvent{ FrameID: page.FrameID("frame-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.frameStoppedLoading", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1702,17 +1272,9 @@ func TestPageOnFrameStoppedLoading(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.FrameStoppedLoadingEvent) - mockSocket.Page().OnFrameStoppedLoading(func(eventData *page.FrameStoppedLoadingEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.frameStoppedLoading", }) result = <-resultChan @@ -1722,39 +1284,32 @@ func TestPageOnFrameStoppedLoading(t *testing.T) { } func TestPageOnInterstitialHidden(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnInterstitialHidden") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.InterstitialHiddenEvent) - mockSocket.Page().OnInterstitialHidden(func(eventData *page.InterstitialHiddenEvent) { + soc.Page().OnInterstitialHidden(func(eventData *page.InterstitialHiddenEvent) { resultChan <- eventData }) + mockResult := &page.InterstitialHiddenEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.interstitialHidden", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *page.InterstitialHiddenEvent) - mockSocket.Page().OnInterstitialHidden(func(eventData *page.InterstitialHiddenEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.interstitialHidden", }) result = <-resultChan @@ -1764,39 +1319,32 @@ func TestPageOnInterstitialHidden(t *testing.T) { } func TestPageOnInterstitialShown(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnInterstitialShown") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.InterstitialShownEvent) - mockSocket.Page().OnInterstitialShown(func(eventData *page.InterstitialShownEvent) { + soc.Page().OnInterstitialShown(func(eventData *page.InterstitialShownEvent) { resultChan <- eventData }) + mockResult := &page.InterstitialShownEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.interstitialShown", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *page.InterstitialShownEvent) - mockSocket.Page().OnInterstitialShown(func(eventData *page.InterstitialShownEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.interstitialShown", }) result = <-resultChan @@ -1806,25 +1354,26 @@ func TestPageOnInterstitialShown(t *testing.T) { } func TestPageOnJavascriptDialogClosed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnJavascriptDialogClosed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.JavascriptDialogClosedEvent) - mockSocket.Page().OnJavascriptDialogClosed(func(eventData *page.JavascriptDialogClosedEvent) { + soc.Page().OnJavascriptDialogClosed(func(eventData *page.JavascriptDialogClosedEvent) { resultChan <- eventData }) + mockResult := &page.JavascriptDialogClosedEvent{ Result: true, UserInput: "user input", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.javascriptDialogClosed", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1834,17 +1383,9 @@ func TestPageOnJavascriptDialogClosed(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Result, result.Result) } - resultChan = make(chan *page.JavascriptDialogClosedEvent) - mockSocket.Page().OnJavascriptDialogClosed(func(eventData *page.JavascriptDialogClosedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.javascriptDialogClosed", }) result = <-resultChan @@ -1854,27 +1395,28 @@ func TestPageOnJavascriptDialogClosed(t *testing.T) { } func TestPageOnJavascriptDialogOpening(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnJavascriptDialogOpening") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.JavascriptDialogOpeningEvent) - mockSocket.Page().OnJavascriptDialogOpening(func(eventData *page.JavascriptDialogOpeningEvent) { + soc.Page().OnJavascriptDialogOpening(func(eventData *page.JavascriptDialogOpeningEvent) { resultChan <- eventData }) + mockResult := &page.JavascriptDialogOpeningEvent{ URL: "http://some.url", Message: "some message", Type: page.DialogType.Alert, DefaultPrompt: "some prompt", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.javascriptDialogOpening", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1884,17 +1426,9 @@ func TestPageOnJavascriptDialogOpening(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.URL, result.URL) } - resultChan = make(chan *page.JavascriptDialogOpeningEvent) - mockSocket.Page().OnJavascriptDialogOpening(func(eventData *page.JavascriptDialogOpeningEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.javascriptDialogOpening", }) result = <-resultChan @@ -1904,27 +1438,28 @@ func TestPageOnJavascriptDialogOpening(t *testing.T) { } func TestPageOnLifecycleEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnLifecycleEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.LifecycleEventEvent) - mockSocket.Page().OnLifecycleEvent(func(eventData *page.LifecycleEventEvent) { + soc.Page().OnLifecycleEvent(func(eventData *page.LifecycleEventEvent) { resultChan <- eventData }) + mockResult := &page.LifecycleEventEvent{ FrameID: page.FrameID("frame-id"), LoaderID: page.LoaderID("loader-id"), Name: "name", Timestamp: page.MonotonicTime(time.Now().Unix()), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.lifecycleEvent", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1934,17 +1469,9 @@ func TestPageOnLifecycleEvent(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.FrameID, result.FrameID) } - resultChan = make(chan *page.LifecycleEventEvent) - mockSocket.Page().OnLifecycleEvent(func(eventData *page.LifecycleEventEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.lifecycleEvent", }) result = <-resultChan @@ -1954,24 +1481,25 @@ func TestPageOnLifecycleEvent(t *testing.T) { } func TestPageOnLoadEventFired(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnLoadEventFired") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.LoadEventFiredEvent) - mockSocket.Page().OnLoadEventFired(func(eventData *page.LoadEventFiredEvent) { + soc.Page().OnLoadEventFired(func(eventData *page.LoadEventFiredEvent) { resultChan <- eventData }) + mockResult := &page.LoadEventFiredEvent{ Timestamp: page.MonotonicTime(time.Now().Unix()), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.loadEventFired", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1981,17 +1509,9 @@ func TestPageOnLoadEventFired(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Timestamp, result.Timestamp) } - resultChan = make(chan *page.LoadEventFiredEvent) - mockSocket.Page().OnLoadEventFired(func(eventData *page.LoadEventFiredEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.loadEventFired", }) result = <-resultChan @@ -2001,15 +1521,18 @@ func TestPageOnLoadEventFired(t *testing.T) { } func TestPageOnScreencastFrame(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnScreencastFrame") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.ScreencastFrameEvent) - mockSocket.Page().OnScreencastFrame(func(eventData *page.ScreencastFrameEvent) { + soc.Page().OnScreencastFrame(func(eventData *page.ScreencastFrameEvent) { resultChan <- eventData }) + mockResult := &page.ScreencastFrameEvent{ Data: "data", Metadata: &page.ScreencastFrameMetadata{ @@ -2023,12 +1546,10 @@ func TestPageOnScreencastFrame(t *testing.T) { }, SessionID: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.screencastFrame", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -2038,17 +1559,9 @@ func TestPageOnScreencastFrame(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Data, result.Data) } - resultChan = make(chan *page.ScreencastFrameEvent) - mockSocket.Page().OnScreencastFrame(func(eventData *page.ScreencastFrameEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.screencastFrame", }) result = <-resultChan @@ -2058,24 +1571,25 @@ func TestPageOnScreencastFrame(t *testing.T) { } func TestPageOnScreencastVisibilityChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnScreencastVisibilityChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.ScreencastVisibilityChangedEvent) - mockSocket.Page().OnScreencastVisibilityChanged(func(eventData *page.ScreencastVisibilityChangedEvent) { + soc.Page().OnScreencastVisibilityChanged(func(eventData *page.ScreencastVisibilityChangedEvent) { resultChan <- eventData }) + mockResult := &page.ScreencastVisibilityChangedEvent{ Visible: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.screencastVisibilityChanged", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -2085,17 +1599,9 @@ func TestPageOnScreencastVisibilityChanged(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Visible, result.Visible) } - resultChan = make(chan *page.ScreencastVisibilityChangedEvent) - mockSocket.Page().OnScreencastVisibilityChanged(func(eventData *page.ScreencastVisibilityChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.screencastVisibilityChanged", }) result = <-resultChan @@ -2105,27 +1611,28 @@ func TestPageOnScreencastVisibilityChanged(t *testing.T) { } func TestPageOnWindowOpen(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPageOnWindowOpen") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *page.WindowOpenEvent) - mockSocket.Page().OnWindowOpen(func(eventData *page.WindowOpenEvent) { + soc.Page().OnWindowOpen(func(eventData *page.WindowOpenEvent) { resultChan <- eventData }) + mockResult := &page.WindowOpenEvent{ URL: "http://some.url", WindowName: "window-name", WindowFeatures: []string{"feature1", "feature2"}, UserGesture: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Page.windowOpen", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -2135,17 +1642,9 @@ func TestPageOnWindowOpen(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.URL, result.URL) } - resultChan = make(chan *page.WindowOpenEvent) - mockSocket.Page().OnWindowOpen(func(eventData *page.WindowOpenEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Page.windowOpen", }) result = <-resultChan diff --git a/tot/socket/cdtp.performance_test.go b/tot/socket/cdtp.performance_test.go index 00ecfa9..e375534 100644 --- a/tot/socket/cdtp.performance_test.go +++ b/tot/socket/cdtp.performance_test.go @@ -1,101 +1,71 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/performance" ) func TestPerformanceDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPerformanceDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Performance().Disable() mockResult := &performance.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Performance().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Performance().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Performance().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPerformanceEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPerformanceEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Performance().Enable() mockResult := &performance.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Performance().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Performance().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Performance().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPerformanceGetMetrics(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPerformanceGetMetrics") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Performance().GetMetrics() mockResult := &performance.GetMetricsResult{ Metrics: []*performance.Metric{{ Name: "metric name", Value: 1, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Performance().GetMetrics() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -103,31 +73,26 @@ func TestPerformanceGetMetrics(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Metrics[0].Name, result.Metrics[0].Name) } - resultChan = mockSocket.Performance().GetMetrics() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Performance().GetMetrics() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestPerformanceOnMetrics(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestPerformanceOnMetrics") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *performance.MetricsEvent) - mockSocket.Performance().OnMetrics(func(eventData *performance.MetricsEvent) { + soc.Performance().OnMetrics(func(eventData *performance.MetricsEvent) { resultChan <- eventData }) + mockResult := &performance.MetricsEvent{ Metrics: []*performance.Metric{{ Name: "metric name", @@ -135,12 +100,10 @@ func TestPerformanceOnMetrics(t *testing.T) { }}, Title: "event title", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Performance.metrics", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -150,17 +113,9 @@ func TestPerformanceOnMetrics(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Metrics[0].Name, result.Metrics[0].Name) } - resultChan = make(chan *performance.MetricsEvent) - mockSocket.Performance().OnMetrics(func(eventData *performance.MetricsEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Performance.metrics", }) result = <-resultChan diff --git a/tot/socket/cdtp.profiler_test.go b/tot/socket/cdtp.profiler_test.go index e09733e..0605654 100644 --- a/tot/socket/cdtp.profiler_test.go +++ b/tot/socket/cdtp.profiler_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/debugger" @@ -11,80 +9,56 @@ import ( ) func TestProfilerDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().Disable() mockResult := &profiler.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().Enable() mockResult := &profiler.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerGetBestEffortCoverage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerGetBestEffortCoverage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().GetBestEffortCoverage() mockResult := &profiler.GetBestEffortCoverageResult{ Result: []*profiler.ScriptCoverage{{ ScriptID: runtime.ScriptID("script-id"), @@ -100,13 +74,9 @@ func TestProfilerGetBestEffortCoverage(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().GetBestEffortCoverage() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -114,171 +84,115 @@ func TestProfilerGetBestEffortCoverage(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result[0].ScriptID, result.Result[0].ScriptID) } - resultChan = mockSocket.Profiler().GetBestEffortCoverage() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().GetBestEffortCoverage() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerSetSamplingInterval(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerSetSamplingInterval") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.SetSamplingIntervalParams{ Interval: 1, } - resultChan := mockSocket.Profiler().SetSamplingInterval(params) mockResult := &profiler.SetSamplingIntervalResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().SetSamplingInterval(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().SetSamplingInterval(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().SetSamplingInterval(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStart(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStart") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().Start() mockResult := &profiler.StartResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().Start() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().Start() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().Start() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStartPreciseCoverage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStartPreciseCoverage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &profiler.StartPreciseCoverageParams{ CallCount: true, Detailed: true, } - resultChan := mockSocket.Profiler().StartPreciseCoverage(params) mockResult := &profiler.StartPreciseCoverageResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().StartPreciseCoverage(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().StartPreciseCoverage(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().StartPreciseCoverage(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStartTypeProfile(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStartTypeProfile") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().StartTypeProfile() mockResult := &profiler.StartTypeProfileResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().StartTypeProfile() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().StartTypeProfile() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().StartTypeProfile() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStop(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStop") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().Stop() mockResult := &profiler.StopResult{ Profile: &profiler.Profile{ Nodes: []*profiler.ProfileNode{{ @@ -298,13 +212,9 @@ func TestProfilerStop(t *testing.T) { TimeDeltas: []int{1, 2}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().Stop() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -312,96 +222,64 @@ func TestProfilerStop(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Profile.Nodes[0].ID, result.Profile.Nodes[0].ID) } - resultChan = mockSocket.Profiler().Stop() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().Stop() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStopPreciseCoverage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStopPreciseCoverage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().StopPreciseCoverage() mockResult := &profiler.StopPreciseCoverageResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().StopPreciseCoverage() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().StopPreciseCoverage() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().StopPreciseCoverage() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerStopTypeProfile(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerStopTypeProfile") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().StopTypeProfile() mockResult := &profiler.StopTypeProfileResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().StopTypeProfile() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Profiler().StopTypeProfile() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().StopTypeProfile() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerTakePreciseCoverage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerTakePreciseCoverage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().TakePreciseCoverage() mockResult := &profiler.TakePreciseCoverageResult{ Result: []*profiler.ScriptCoverage{{ ScriptID: runtime.ScriptID("script-id"), @@ -417,13 +295,9 @@ func TestProfilerTakePreciseCoverage(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().TakePreciseCoverage() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -431,28 +305,20 @@ func TestProfilerTakePreciseCoverage(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result[0].ScriptID, result.Result[0].ScriptID) } - resultChan = mockSocket.Profiler().TakePreciseCoverage() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().TakePreciseCoverage() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerTakeTypeProfile(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerTakeTypeProfile") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Profiler().TakeTypeProfile() mockResult := &profiler.TakeTypeProfileResult{ Result: []*profiler.ScriptTypeProfile{{ ScriptID: runtime.ScriptID("script-id"), @@ -465,13 +331,9 @@ func TestProfilerTakeTypeProfile(t *testing.T) { }}, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Profiler().TakeTypeProfile() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -479,31 +341,26 @@ func TestProfilerTakeTypeProfile(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result[0].ScriptID, result.Result[0].ScriptID) } - resultChan = mockSocket.Profiler().TakeTypeProfile() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Profiler().TakeTypeProfile() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestProfilerOnConsoleProfileFinished(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerOnConsoleProfileFinished") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.ConsoleProfileFinishedEvent) - mockSocket.Profiler().OnConsoleProfileFinished(func(eventData *profiler.ConsoleProfileFinishedEvent) { + soc.Profiler().OnConsoleProfileFinished(func(eventData *profiler.ConsoleProfileFinishedEvent) { resultChan <- eventData }) + mockResult := &profiler.ConsoleProfileFinishedEvent{ ID: "finished-id", Location: &debugger.Location{}, @@ -526,12 +383,10 @@ func TestProfilerOnConsoleProfileFinished(t *testing.T) { }, Title: "title", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Profiler.consoleProfileFinished", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -541,17 +396,9 @@ func TestProfilerOnConsoleProfileFinished(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ID, result.ID) } - resultChan = make(chan *profiler.ConsoleProfileFinishedEvent) - mockSocket.Profiler().OnConsoleProfileFinished(func(eventData *profiler.ConsoleProfileFinishedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Profiler.consoleProfileFinished", }) result = <-resultChan @@ -561,26 +408,27 @@ func TestProfilerOnConsoleProfileFinished(t *testing.T) { } func TestProfilerOnConsoleProfileStarted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestProfilerOnConsoleProfileStarted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *profiler.ConsoleProfileStartedEvent) - mockSocket.Profiler().OnConsoleProfileStarted(func(eventData *profiler.ConsoleProfileStartedEvent) { + soc.Profiler().OnConsoleProfileStarted(func(eventData *profiler.ConsoleProfileStartedEvent) { resultChan <- eventData }) + mockResult := &profiler.ConsoleProfileStartedEvent{ ID: "event-id", Location: &debugger.Location{}, Title: "title", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Profiler.consoleProfileStarted", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -590,17 +438,9 @@ func TestProfilerOnConsoleProfileStarted(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ID, result.ID) } - resultChan = make(chan *profiler.ConsoleProfileStartedEvent) - mockSocket.Profiler().OnConsoleProfileStarted(func(eventData *profiler.ConsoleProfileStartedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Profiler.consoleProfileStarted", }) result = <-resultChan diff --git a/tot/socket/cdtp.runtime_test.go b/tot/socket/cdtp.runtime_test.go index f84569d..b11fd23 100644 --- a/tot/socket/cdtp.runtime_test.go +++ b/tot/socket/cdtp.runtime_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -10,17 +8,17 @@ import ( ) func TestRuntimeAwaitPromise(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeAwaitPromise") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.AwaitPromiseParams{ PromiseObjectID: runtime.RemoteObjectID("remote-object-id"), ReturnByValue: true, GeneratePreview: true, } - resultChan := mockSocket.Runtime().AwaitPromise(params) mockResult := &runtime.AwaitPromiseResult{ Result: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -89,13 +87,9 @@ func TestRuntimeAwaitPromise(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().AwaitPromise(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -103,26 +97,19 @@ func TestRuntimeAwaitPromise(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result.Type, result.Result.Type) } - resultChan = mockSocket.Runtime().AwaitPromise(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().AwaitPromise(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeCallFunctionOn(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeCallFunctionOn") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.CallFunctionOnParams{ FunctionDeclaration: "function(){}", @@ -140,7 +127,6 @@ func TestRuntimeCallFunctionOn(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), ObjectGroup: "object group", } - resultChan := mockSocket.Runtime().CallFunctionOn(params) mockResult := &runtime.CallFunctionOnResult{ Result: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -209,13 +195,9 @@ func TestRuntimeCallFunctionOn(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().CallFunctionOn(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -223,26 +205,19 @@ func TestRuntimeCallFunctionOn(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result.Type, result.Result.Type) } - resultChan = mockSocket.Runtime().CallFunctionOn(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().CallFunctionOn(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeCompileScript(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeCompileScript") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.CompileScriptParams{ Expression: "expression", @@ -250,7 +225,6 @@ func TestRuntimeCompileScript(t *testing.T) { PersistScript: true, ExecutionContextID: runtime.ExecutionContextID(1), } - resultChan := mockSocket.Runtime().CompileScript(params) mockResult := &runtime.CompileScriptResult{ ScriptID: runtime.ScriptID("script-id"), ExceptionDetails: &runtime.ExceptionDetails{ @@ -281,13 +255,9 @@ func TestRuntimeCompileScript(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().CompileScript(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -295,128 +265,85 @@ func TestRuntimeCompileScript(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ScriptID, result.ScriptID) } - resultChan = mockSocket.Runtime().CompileScript(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().CompileScript(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Runtime().Disable() mockResult := &runtime.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeDiscardConsoleEntries(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeDiscardConsoleEntries") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Runtime().DiscardConsoleEntries() mockResult := &runtime.DiscardConsoleEntriesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().DiscardConsoleEntries() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().DiscardConsoleEntries() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().DiscardConsoleEntries() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Runtime().Enable() mockResult := &runtime.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeEvaluate(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeEvaluate") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.EvaluateParams{ Expression: "expression", @@ -429,7 +356,6 @@ func TestRuntimeEvaluate(t *testing.T) { UserGesture: true, AwaitPromise: true, } - resultChan := mockSocket.Runtime().Evaluate(params) mockResult := &runtime.EvaluateResult{ Result: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -498,13 +424,9 @@ func TestRuntimeEvaluate(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().Evaluate(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -512,26 +434,19 @@ func TestRuntimeEvaluate(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result.Type, result.Result.Type) } - resultChan = mockSocket.Runtime().Evaluate(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().Evaluate(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeGetProperties(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeGetProperties") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.GetPropertiesParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), @@ -539,7 +454,6 @@ func TestRuntimeGetProperties(t *testing.T) { AccessorPropertiesOnly: true, GeneratePreview: true, } - resultChan := mockSocket.Runtime().GetProperties(params) mockResult := &runtime.GetPropertiesResult{ Result: []*runtime.PropertyDescriptor{{ Name: "name", @@ -595,13 +509,9 @@ func TestRuntimeGetProperties(t *testing.T) { ExecutionContextID: runtime.ExecutionContextID(1), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().GetProperties(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -609,41 +519,29 @@ func TestRuntimeGetProperties(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Result[0].Name, result.Result[0].Name) } - resultChan = mockSocket.Runtime().GetProperties(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().GetProperties(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeGlobalLexicalScopeNames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeGlobalLexicalScopeNames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.GlobalLexicalScopeNamesParams{ ExecutionContextID: runtime.ExecutionContextID(1), } - resultChan := mockSocket.Runtime().GlobalLexicalScopeNames(params) mockResult := &runtime.GlobalLexicalScopeNamesResult{ Names: []string{"name1", "name2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().GlobalLexicalScopeNames(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -651,41 +549,29 @@ func TestRuntimeGlobalLexicalScopeNames(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Names[0], result.Names[0]) } - resultChan = mockSocket.Runtime().GlobalLexicalScopeNames(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().GlobalLexicalScopeNames(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeQueryObjects(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeQueryObjects") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.QueryObjectsParams{ PrototypeObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.Runtime().QueryObjects(params) mockResult := &runtime.QueryObjectsResult{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().QueryObjects(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -693,134 +579,91 @@ func TestRuntimeQueryObjects(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ObjectID, result.ObjectID) } - resultChan = mockSocket.Runtime().QueryObjects(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().QueryObjects(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeReleaseObject(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeReleaseObject") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.ReleaseObjectParams{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - resultChan := mockSocket.Runtime().ReleaseObject(params) mockResult := &runtime.ReleaseObjectResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().ReleaseObject(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().ReleaseObject(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().ReleaseObject(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeReleaseObjectGroup(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeReleaseObjectGroup") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.ReleaseObjectGroupParams{ ObjectGroup: "object-group", } - resultChan := mockSocket.Runtime().ReleaseObjectGroup(params) mockResult := &runtime.ReleaseObjectGroupResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().ReleaseObjectGroup(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().ReleaseObjectGroup(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().ReleaseObjectGroup(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeRunIfWaitingForDebugger(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeRunIfWaitingForDebugger") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Runtime().RunIfWaitingForDebugger() mockResult := &runtime.RunIfWaitingForDebuggerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().RunIfWaitingForDebugger() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().RunIfWaitingForDebugger() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().RunIfWaitingForDebugger() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeRunScript(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeRunScript") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.RunScriptParams{ ScriptID: runtime.ScriptID("script-id"), @@ -832,17 +675,12 @@ func TestRuntimeRunScript(t *testing.T) { GeneratePreview: true, AwaitPromise: true, } - resultChan := mockSocket.Runtime().RunScript(params) mockResult := &runtime.RunScriptResult{ ObjectID: runtime.RemoteObjectID("remote-object-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().RunScript(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -850,26 +688,19 @@ func TestRuntimeRunScript(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ObjectID, result.ObjectID) } - resultChan = mockSocket.Runtime().RunScript(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().RunScript(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeSetCustomObjectFormatterEnabled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeSetCustomObjectFormatterEnabled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &runtime.SetCustomObjectFormatterEnabledParams{ Result: &runtime.RemoteObject{ @@ -877,44 +708,34 @@ func TestRuntimeSetCustomObjectFormatterEnabled(t *testing.T) { }, ExceptionDetails: &runtime.ExceptionDetails{}, } - resultChan := mockSocket.Runtime().SetCustomObjectFormatterEnabled(params) mockResult := &runtime.SetCustomObjectFormatterEnabledResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Runtime().SetCustomObjectFormatterEnabled(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Runtime().SetCustomObjectFormatterEnabled(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Runtime().SetCustomObjectFormatterEnabled(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestRuntimeOnConsoleAPICalled(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnConsoleAPICalled") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ConsoleAPICalledEvent) - mockSocket.Runtime().OnConsoleAPICalled(func(eventData *runtime.ConsoleAPICalledEvent) { + soc.Runtime().OnConsoleAPICalled(func(eventData *runtime.ConsoleAPICalledEvent) { resultChan <- eventData }) + mockResult := &runtime.ConsoleAPICalledEvent{ Type: runtime.CallType.Assert, Args: []*runtime.RemoteObject{{}}, @@ -923,12 +744,10 @@ func TestRuntimeOnConsoleAPICalled(t *testing.T) { StackTrace: &runtime.StackTrace{}, Context: "context", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.consoleAPICalled", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -938,17 +757,9 @@ func TestRuntimeOnConsoleAPICalled(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Type, result.Type) } - resultChan = make(chan *runtime.ConsoleAPICalledEvent) - mockSocket.Runtime().OnConsoleAPICalled(func(eventData *runtime.ConsoleAPICalledEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.consoleAPICalled", }) result = <-resultChan @@ -958,25 +769,26 @@ func TestRuntimeOnConsoleAPICalled(t *testing.T) { } func TestRuntimeOnExceptionRevoked(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnExceptionRevoked") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ExceptionRevokedEvent) - mockSocket.Runtime().OnExceptionRevoked(func(eventData *runtime.ExceptionRevokedEvent) { + soc.Runtime().OnExceptionRevoked(func(eventData *runtime.ExceptionRevokedEvent) { resultChan <- eventData }) + mockResult := &runtime.ExceptionRevokedEvent{ Reason: "reason", ExceptionID: 1, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.exceptionRevoked", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -986,17 +798,9 @@ func TestRuntimeOnExceptionRevoked(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Reason, result.Reason) } - resultChan = make(chan *runtime.ExceptionRevokedEvent) - mockSocket.Runtime().OnExceptionRevoked(func(eventData *runtime.ExceptionRevokedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.exceptionRevoked", }) result = <-resultChan @@ -1006,25 +810,26 @@ func TestRuntimeOnExceptionRevoked(t *testing.T) { } func TestRuntimeOnExceptionThrown(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnExceptionThrown") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ExceptionThrownEvent) - mockSocket.Runtime().OnExceptionThrown(func(eventData *runtime.ExceptionThrownEvent) { + soc.Runtime().OnExceptionThrown(func(eventData *runtime.ExceptionThrownEvent) { resultChan <- eventData }) + mockResult := &runtime.ExceptionThrownEvent{ Timestamp: runtime.Timestamp(time.Now().Unix()), ExceptionDetails: &runtime.ExceptionDetails{}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.exceptionThrown", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1034,17 +839,9 @@ func TestRuntimeOnExceptionThrown(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Timestamp, result.Timestamp) } - resultChan = make(chan *runtime.ExceptionThrownEvent) - mockSocket.Runtime().OnExceptionThrown(func(eventData *runtime.ExceptionThrownEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.exceptionThrown", }) result = <-resultChan @@ -1054,15 +851,18 @@ func TestRuntimeOnExceptionThrown(t *testing.T) { } func TestRuntimeOnExecutionContextCreated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnExecutionContextCreated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ExecutionContextCreatedEvent) - mockSocket.Runtime().OnExecutionContextCreated(func(eventData *runtime.ExecutionContextCreatedEvent) { + soc.Runtime().OnExecutionContextCreated(func(eventData *runtime.ExecutionContextCreatedEvent) { resultChan <- eventData }) + mockResult := &runtime.ExecutionContextCreatedEvent{ Context: &runtime.ExecutionContextDescription{ ID: runtime.ExecutionContextID(1), @@ -1071,12 +871,10 @@ func TestRuntimeOnExecutionContextCreated(t *testing.T) { AuxData: map[string]string{"key": "value"}, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.executionContextCreated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1086,17 +884,9 @@ func TestRuntimeOnExecutionContextCreated(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Context.ID, result.Context.ID) } - resultChan = make(chan *runtime.ExecutionContextCreatedEvent) - mockSocket.Runtime().OnExecutionContextCreated(func(eventData *runtime.ExecutionContextCreatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.executionContextCreated", }) result = <-resultChan @@ -1106,24 +896,25 @@ func TestRuntimeOnExecutionContextCreated(t *testing.T) { } func TestRuntimeOnExecutionContextDestroyed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnExecutionContextDestroyed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ExecutionContextDestroyedEvent) - mockSocket.Runtime().OnExecutionContextDestroyed(func(eventData *runtime.ExecutionContextDestroyedEvent) { + soc.Runtime().OnExecutionContextDestroyed(func(eventData *runtime.ExecutionContextDestroyedEvent) { resultChan <- eventData }) + mockResult := &runtime.ExecutionContextDestroyedEvent{ ExecutionContextID: runtime.ExecutionContextID(1), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.executionContextDestroyed", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1133,17 +924,9 @@ func TestRuntimeOnExecutionContextDestroyed(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.ExecutionContextID, result.ExecutionContextID) } - resultChan = make(chan *runtime.ExecutionContextDestroyedEvent) - mockSocket.Runtime().OnExecutionContextDestroyed(func(eventData *runtime.ExecutionContextDestroyedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.executionContextDestroyed", }) result = <-resultChan @@ -1153,39 +936,32 @@ func TestRuntimeOnExecutionContextDestroyed(t *testing.T) { } func TestRuntimeOnExecutionContextsCleared(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnExecutionContextsCleared") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.ExecutionContextsClearedEvent) - mockSocket.Runtime().OnExecutionContextsCleared(func(eventData *runtime.ExecutionContextsClearedEvent) { + soc.Runtime().OnExecutionContextsCleared(func(eventData *runtime.ExecutionContextsClearedEvent) { resultChan <- eventData }) + mockResult := &runtime.ExecutionContextsClearedEvent{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.executionContextsCleared", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { t.Errorf("Expected '%v', got: '%v'", mockResult, result) } - resultChan = make(chan *runtime.ExecutionContextsClearedEvent) - mockSocket.Runtime().OnExecutionContextsCleared(func(eventData *runtime.ExecutionContextsClearedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.executionContextsCleared", }) result = <-resultChan @@ -1195,15 +971,18 @@ func TestRuntimeOnExecutionContextsCleared(t *testing.T) { } func TestRuntimeOnInspectRequested(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestRuntimeOnInspectRequested") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *runtime.InspectRequestedEvent) - mockSocket.Runtime().OnInspectRequested(func(eventData *runtime.InspectRequestedEvent) { + soc.Runtime().OnInspectRequested(func(eventData *runtime.InspectRequestedEvent) { resultChan <- eventData }) + mockResult := &runtime.InspectRequestedEvent{ Object: &runtime.RemoteObject{ Type: runtime.ObjectType.Object, @@ -1246,12 +1025,10 @@ func TestRuntimeOnInspectRequested(t *testing.T) { }, Hints: map[string]string{"key": "value"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Runtime.inspectRequested", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -1261,17 +1038,9 @@ func TestRuntimeOnInspectRequested(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Object.Type, result.Object.Type) } - resultChan = make(chan *runtime.InspectRequestedEvent) - mockSocket.Runtime().OnInspectRequested(func(eventData *runtime.InspectRequestedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Runtime.inspectRequested", }) result = <-resultChan diff --git a/tot/socket/cdtp.schema_test.go b/tot/socket/cdtp.schema_test.go index 634bd1b..e571ce6 100644 --- a/tot/socket/cdtp.schema_test.go +++ b/tot/socket/cdtp.schema_test.go @@ -1,33 +1,27 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/schema" ) func TestSchemaGetDomains(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSchemaGetDomains") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Schema().GetDomains() mockResult := &schema.GetDomainsResult{ Domains: []*schema.Domain{{ Name: "name", Version: "version", }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Schema().GetDomains() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -35,16 +29,8 @@ func TestSchemaGetDomains(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Domains[0].Name, result.Domains[0].Name) } - resultChan = mockSocket.Schema().GetDomains() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Schema().GetDomains() if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.security_test.go b/tot/socket/cdtp.security_test.go index 7ff8002..fc51635 100644 --- a/tot/socket/cdtp.security_test.go +++ b/tot/socket/cdtp.security_test.go @@ -1,214 +1,153 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/security" ) func TestSecurityDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecurityDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Security().Disable() mockResult := &security.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Security().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Security().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Security().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestSecurityEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecurityEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Security().Enable() mockResult := &security.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Security().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Security().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Security().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestSecurityHandleCertificateError(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecurityHandleCertificateError") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &security.HandleCertificateErrorParams{ EventID: 1, Action: security.CertificateErrorAction.Continue, } - resultChan := mockSocket.Security().HandleCertificateError(params) mockResult := &security.HandleCertificateErrorResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Security().HandleCertificateError(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Security().HandleCertificateError(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Security().HandleCertificateError(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestSecuritySetIgnoreCertificateErrors(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecuritySetIgnoreCertificateErrors") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &security.SetIgnoreCertificateErrorsParams{ Ignore: true, } - resultChan := mockSocket.Security().SetIgnoreCertificateErrors(params) mockResult := &security.SetIgnoreCertificateErrorsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Security().SetIgnoreCertificateErrors(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Security().SetIgnoreCertificateErrors(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Security().SetIgnoreCertificateErrors(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestSecuritySetOverrideCertificateErrors(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecuritySetOverrideCertificateErrors") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &security.SetOverrideCertificateErrorsParams{ Override: true, } - resultChan := mockSocket.Security().SetOverrideCertificateErrors(params) mockResult := &security.SetOverrideCertificateErrorsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Security().SetOverrideCertificateErrors(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Security().SetOverrideCertificateErrors(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Security().SetOverrideCertificateErrors(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestSecurityOnCertificateError(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecurityOnCertificateError") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *security.CertificateErrorEvent) - mockSocket.Security().OnCertificateError(func(eventData *security.CertificateErrorEvent) { + soc.Security().OnCertificateError(func(eventData *security.CertificateErrorEvent) { resultChan <- eventData }) + mockResult := &security.CertificateErrorEvent{ EventID: 1, ErrorType: "error-type", RequestURL: "http://some.url", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Security.certificateError", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -218,17 +157,9 @@ func TestSecurityOnCertificateError(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.EventID, result.EventID) } - resultChan = make(chan *security.CertificateErrorEvent) - mockSocket.Security().OnCertificateError(func(eventData *security.CertificateErrorEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Security.certificateError", }) result = <-resultChan @@ -238,17 +169,20 @@ func TestSecurityOnCertificateError(t *testing.T) { } func TestSecurityOnSecurityStateChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSecurityOnSecurityStateChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *security.StateChangedEvent) - mockSocket.Security().OnSecurityStateChanged(func(eventData *security.StateChangedEvent) { + soc.Security().OnSecurityStateChanged(func(eventData *security.StateChangedEvent) { resultChan <- eventData }) + mockResult := &security.StateChangedEvent{ - State: security.State.Unknown, + State: security.State.Unknown, SchemeIsCryptographic: true, Explanations: []*security.StateExplanation{{ State: security.State.Unknown, @@ -268,12 +202,10 @@ func TestSecurityOnSecurityStateChanged(t *testing.T) { }, Summary: "summary", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Security.securityStateChanged", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -283,17 +215,9 @@ func TestSecurityOnSecurityStateChanged(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.State, result.State) } - resultChan = make(chan *security.StateChangedEvent) - mockSocket.Security().OnSecurityStateChanged(func(eventData *security.StateChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Security.securityStateChanged", }) result = <-resultChan diff --git a/tot/socket/cdtp.service.worker_test.go b/tot/socket/cdtp.service.worker_test.go index f211cc3..02f8ab6 100644 --- a/tot/socket/cdtp.service.worker_test.go +++ b/tot/socket/cdtp.service.worker_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "time" @@ -11,83 +9,60 @@ import ( ) func TestServiceWorkerDeliverPushMessage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerDeliverPushMessage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.DeliverPushMessageParams{ Origin: "origin", RegistrationID: "registration-id", Data: "data", } - resultChan := mockSocket.ServiceWorker().DeliverPushMessage(params) mockResult := &worker.DeliverPushMessageResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().DeliverPushMessage(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().DeliverPushMessage(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().DeliverPushMessage(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerDisable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerDisable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ServiceWorker().Disable() mockResult := &worker.DisableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().Disable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().Disable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().Disable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerDispatchSyncEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerDispatchSyncEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.DispatchSyncEventParams{ Origin: "origin", @@ -95,371 +70,253 @@ func TestServiceWorkerDispatchSyncEvent(t *testing.T) { Tag: "tag", LastChance: true, } - resultChan := mockSocket.ServiceWorker().DispatchSyncEvent(params) mockResult := &worker.DispatchSyncEventResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().DispatchSyncEvent(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().DispatchSyncEvent(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().DispatchSyncEvent(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerEnable(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerEnable") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ServiceWorker().Enable() mockResult := &worker.EnableResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().Enable() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().Enable() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().Enable() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerInspectWorker(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerInspectWorker") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.InspectWorkerParams{ VersionID: "version-id", } - resultChan := mockSocket.ServiceWorker().InspectWorker(params) mockResult := &worker.InspectWorkerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().InspectWorker(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().InspectWorker(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().InspectWorker(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerSetForceUpdateOnPageLoad(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerSetForceUpdateOnPageLoad") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.SetForceUpdateOnPageLoadParams{ ForceUpdateOnPageLoad: true, } - resultChan := mockSocket.ServiceWorker().SetForceUpdateOnPageLoad(params) mockResult := &worker.SetForceUpdateOnPageLoadResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().SetForceUpdateOnPageLoad(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().SetForceUpdateOnPageLoad(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().SetForceUpdateOnPageLoad(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerSkipWaiting(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerSkipWaiting") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.SkipWaitingParams{ ScopeURL: "http://some.url", } - resultChan := mockSocket.ServiceWorker().SkipWaiting(params) mockResult := &worker.SkipWaitingResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().SkipWaiting(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().SkipWaiting(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().SkipWaiting(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerStartWorker(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerStartWorker") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.StartWorkerParams{ ScopeURL: "http://some.url", } - resultChan := mockSocket.ServiceWorker().StartWorker(params) mockResult := &worker.StartWorkerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().StartWorker(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().StartWorker(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().StartWorker(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerStopAllWorkers(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerStopAllWorkers") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.ServiceWorker().StopAllWorkers() mockResult := &worker.StopAllWorkersResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().StopAllWorkers() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().StopAllWorkers() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().StopAllWorkers() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerStopWorker(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerStopWorker") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.StopWorkerParams{ VersionID: "version-id", } - resultChan := mockSocket.ServiceWorker().StopWorker(params) mockResult := &worker.StopWorkerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().StopWorker(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().StopWorker(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().StopWorker(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerUnregister(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerUnregister") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.UnregisterParams{ ScopeURL: "http://some.url", } - resultChan := mockSocket.ServiceWorker().Unregister(params) mockResult := &worker.UnregisterResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().Unregister(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().Unregister(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().Unregister(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerUpdateRegistration(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerUpdateRegistration") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &worker.UpdateRegistrationParams{ ScopeURL: "http://some.url", } - resultChan := mockSocket.ServiceWorker().UpdateRegistration(params) mockResult := &worker.UpdateRegistrationResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.ServiceWorker().UpdateRegistration(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.ServiceWorker().UpdateRegistration(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.ServiceWorker().UpdateRegistration(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestServiceWorkerOnWorkerErrorReported(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerOnWorkerErrorReported") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *worker.ErrorReportedEvent) - mockSocket.ServiceWorker().OnWorkerErrorReported(func(eventData *worker.ErrorReportedEvent) { + soc.ServiceWorker().OnWorkerErrorReported(func(eventData *worker.ErrorReportedEvent) { resultChan <- eventData }) + mockResult := &worker.ErrorReportedEvent{ ErrorMessage: &worker.ErrorMessage{ ErrorMessage: "error message", @@ -470,12 +327,10 @@ func TestServiceWorkerOnWorkerErrorReported(t *testing.T) { ColumnNumber: 1, }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "ServiceWorker.workerErrorReported", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -485,17 +340,9 @@ func TestServiceWorkerOnWorkerErrorReported(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ErrorMessage.ErrorMessage, result.ErrorMessage.ErrorMessage) } - resultChan = make(chan *worker.ErrorReportedEvent) - mockSocket.ServiceWorker().OnWorkerErrorReported(func(eventData *worker.ErrorReportedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "ServiceWorker.workerErrorReported", }) result = <-resultChan @@ -505,15 +352,18 @@ func TestServiceWorkerOnWorkerErrorReported(t *testing.T) { } func TestServiceWorkerOnWorkerRegistrationUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerOnWorkerRegistrationUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *worker.RegistrationUpdatedEvent) - mockSocket.ServiceWorker().OnWorkerRegistrationUpdated(func(eventData *worker.RegistrationUpdatedEvent) { + soc.ServiceWorker().OnWorkerRegistrationUpdated(func(eventData *worker.RegistrationUpdatedEvent) { resultChan <- eventData }) + mockResult := &worker.RegistrationUpdatedEvent{ Registrations: []*worker.Registration{{ RegistrationID: "registration-id", @@ -521,12 +371,10 @@ func TestServiceWorkerOnWorkerRegistrationUpdated(t *testing.T) { IsDeleted: true, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "ServiceWorker.workerRegistrationUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -536,17 +384,9 @@ func TestServiceWorkerOnWorkerRegistrationUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Registrations[0].RegistrationID, result.Registrations[0].RegistrationID) } - resultChan = make(chan *worker.RegistrationUpdatedEvent) - mockSocket.ServiceWorker().OnWorkerRegistrationUpdated(func(eventData *worker.RegistrationUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "ServiceWorker.workerRegistrationUpdated", }) result = <-resultChan @@ -556,15 +396,18 @@ func TestServiceWorkerOnWorkerRegistrationUpdated(t *testing.T) { } func TestServiceWorkerOnWorkerVersionUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestServiceWorkerOnWorkerVersionUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *worker.VersionUpdatedEvent) - mockSocket.ServiceWorker().OnWorkerVersionUpdated(func(eventData *worker.VersionUpdatedEvent) { + soc.ServiceWorker().OnWorkerVersionUpdated(func(eventData *worker.VersionUpdatedEvent) { resultChan <- eventData }) + mockResult := &worker.VersionUpdatedEvent{ Versions: []*worker.Version{{ VersionID: "version-id", @@ -578,12 +421,10 @@ func TestServiceWorkerOnWorkerVersionUpdated(t *testing.T) { TargetID: target.ID("target-id"), }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "ServiceWorker.workerVersionUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -593,17 +434,9 @@ func TestServiceWorkerOnWorkerVersionUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Versions[0].VersionID, result.Versions[0].VersionID) } - resultChan = make(chan *worker.VersionUpdatedEvent) - mockSocket.ServiceWorker().OnWorkerVersionUpdated(func(eventData *worker.VersionUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "ServiceWorker.workerVersionUpdated", }) result = <-resultChan diff --git a/tot/socket/cdtp.storage_test.go b/tot/socket/cdtp.storage_test.go index b4472dd..3766f33 100644 --- a/tot/socket/cdtp.storage_test.go +++ b/tot/socket/cdtp.storage_test.go @@ -1,61 +1,47 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/storage" ) func TestStorageClearDataForOrigin(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageClearDataForOrigin") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.ClearDataForOriginParams{ Origin: "origin", Types: "type1,type2", } - resultChan := mockSocket.Storage().ClearDataForOrigin(params) mockResult := &storage.ClearDataForOriginResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().ClearDataForOrigin(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Storage().ClearDataForOrigin(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().ClearDataForOrigin(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageGetUsageAndQuota(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageGetUsageAndQuota") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.GetUsageAndQuotaParams{ Origin: "origin", } - resultChan := mockSocket.Storage().GetUsageAndQuota(params) mockResult := &storage.GetUsageAndQuotaResult{ Usage: 1, Quota: 1, @@ -64,13 +50,9 @@ func TestStorageGetUsageAndQuota(t *testing.T) { Usage: 1, }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().GetUsageAndQuota(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -78,189 +60,134 @@ func TestStorageGetUsageAndQuota(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Usage, result.Usage) } - resultChan = mockSocket.Storage().GetUsageAndQuota(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().GetUsageAndQuota(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageTrackCacheStorageForOrigin(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageTrackCacheStorageForOrigin") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.TrackCacheStorageForOriginParams{ Origin: "origin", } - resultChan := mockSocket.Storage().TrackCacheStorageForOrigin(params) mockResult := &storage.TrackCacheStorageForOriginResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().TrackCacheStorageForOrigin(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Storage().TrackCacheStorageForOrigin(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().TrackCacheStorageForOrigin(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageTrackIndexedDBForOrigin(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageTrackIndexedDBForOrigin") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.TrackIndexedDBForOriginParams{ Origin: "origin", } - resultChan := mockSocket.Storage().TrackIndexedDBForOrigin(params) mockResult := &storage.TrackIndexedDBForOriginResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().TrackIndexedDBForOrigin(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Storage().TrackIndexedDBForOrigin(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().TrackIndexedDBForOrigin(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageUntrackCacheStorageForOrigin(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageUntrackCacheStorageForOrigin") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.UntrackCacheStorageForOriginParams{ Origin: "origin", } - resultChan := mockSocket.Storage().UntrackCacheStorageForOrigin(params) mockResult := &storage.UntrackCacheStorageForOriginResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().UntrackCacheStorageForOrigin(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Storage().UntrackCacheStorageForOrigin(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().UntrackCacheStorageForOrigin(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageUntrackIndexedDBForOrigin(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageUntrackIndexedDBForOrigin") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &storage.UntrackIndexedDBForOriginParams{ Origin: "origin", } - resultChan := mockSocket.Storage().UntrackIndexedDBForOrigin(params) mockResult := &storage.UntrackIndexedDBForOriginResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Storage().UntrackIndexedDBForOrigin(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Storage().UntrackIndexedDBForOrigin(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Storage().UntrackIndexedDBForOrigin(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestStorageOnCacheStorageContentUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageOnCacheStorageContentUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.CacheStorageContentUpdatedEvent) - mockSocket.Storage().OnCacheStorageContentUpdated(func(eventData *storage.CacheStorageContentUpdatedEvent) { + soc.Storage().OnCacheStorageContentUpdated(func(eventData *storage.CacheStorageContentUpdatedEvent) { resultChan <- eventData }) + mockResult := &storage.CacheStorageContentUpdatedEvent{ Origin: "origin", CacheName: "cache-name", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Storage.cacheStorageContentUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -270,17 +197,9 @@ func TestStorageOnCacheStorageContentUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Origin, result.Origin) } - resultChan = make(chan *storage.CacheStorageContentUpdatedEvent) - mockSocket.Storage().OnCacheStorageContentUpdated(func(eventData *storage.CacheStorageContentUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Storage.cacheStorageContentUpdated", }) result = <-resultChan @@ -290,24 +209,25 @@ func TestStorageOnCacheStorageContentUpdated(t *testing.T) { } func TestStorageOnCacheStorageListUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageOnCacheStorageListUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.CacheStorageListUpdatedEvent) - mockSocket.Storage().OnCacheStorageListUpdated(func(eventData *storage.CacheStorageListUpdatedEvent) { + soc.Storage().OnCacheStorageListUpdated(func(eventData *storage.CacheStorageListUpdatedEvent) { resultChan <- eventData }) + mockResult := &storage.CacheStorageListUpdatedEvent{ Origin: "origin", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Storage.cacheStorageListUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -317,17 +237,9 @@ func TestStorageOnCacheStorageListUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Origin, result.Origin) } - resultChan = make(chan *storage.CacheStorageListUpdatedEvent) - mockSocket.Storage().OnCacheStorageListUpdated(func(eventData *storage.CacheStorageListUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Storage.cacheStorageListUpdated", }) result = <-resultChan @@ -337,26 +249,27 @@ func TestStorageOnCacheStorageListUpdated(t *testing.T) { } func TestStorageOnIndexedDBContentUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageOnIndexedDBContentUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.IndexedDBContentUpdatedEvent) - mockSocket.Storage().OnIndexedDBContentUpdated(func(eventData *storage.IndexedDBContentUpdatedEvent) { + soc.Storage().OnIndexedDBContentUpdated(func(eventData *storage.IndexedDBContentUpdatedEvent) { resultChan <- eventData }) + mockResult := &storage.IndexedDBContentUpdatedEvent{ Origin: "origin", DatabaseName: "dbname", ObjectStoreName: "storename", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Storage.indexedDBContentUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -366,17 +279,9 @@ func TestStorageOnIndexedDBContentUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Origin, result.Origin) } - resultChan = make(chan *storage.IndexedDBContentUpdatedEvent) - mockSocket.Storage().OnIndexedDBContentUpdated(func(eventData *storage.IndexedDBContentUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Storage.indexedDBContentUpdated", }) result = <-resultChan @@ -386,24 +291,25 @@ func TestStorageOnIndexedDBContentUpdated(t *testing.T) { } func TestStorageOnIndexedDBListUpdated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestStorageOnIndexedDBListUpdated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *storage.IndexedDBListUpdatedEvent) - mockSocket.Storage().OnIndexedDBListUpdated(func(eventData *storage.IndexedDBListUpdatedEvent) { + soc.Storage().OnIndexedDBListUpdated(func(eventData *storage.IndexedDBListUpdatedEvent) { resultChan <- eventData }) + mockResult := &storage.IndexedDBListUpdatedEvent{ Origin: "origin", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Storage.indexedDBListUpdated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -413,17 +319,9 @@ func TestStorageOnIndexedDBListUpdated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Origin, result.Origin) } - resultChan = make(chan *storage.IndexedDBListUpdatedEvent) - mockSocket.Storage().OnIndexedDBListUpdated(func(eventData *storage.IndexedDBListUpdatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Storage.indexedDBListUpdated", }) result = <-resultChan diff --git a/tot/socket/cdtp.system.info_test.go b/tot/socket/cdtp.system.info_test.go index cf702a6..e1540e3 100644 --- a/tot/socket/cdtp.system.info_test.go +++ b/tot/socket/cdtp.system.info_test.go @@ -1,20 +1,18 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/system/info" ) func TestSystemInfoGetInfo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSystemInfoGetInfo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.SystemInfo().GetInfo() mockResult := &info.GetInfoResult{ GPU: &info.GPUInfo{ Devices: []*info.GPUDevice{{ @@ -31,13 +29,9 @@ func TestSystemInfoGetInfo(t *testing.T) { ModelVersion: "ModelVersion", CommandLine: "CommandLine", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.SystemInfo().GetInfo() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -45,16 +39,8 @@ func TestSystemInfoGetInfo(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.GPU.Devices[0].VendorID, result.GPU.Devices[0].VendorID) } - resultChan = mockSocket.SystemInfo().GetInfo() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.SystemInfo().GetInfo() if nil == result.Err { t.Errorf("Expected error, got success") } diff --git a/tot/socket/cdtp.target_test.go b/tot/socket/cdtp.target_test.go index fa30bb3..96b0f69 100644 --- a/tot/socket/cdtp.target_test.go +++ b/tot/socket/cdtp.target_test.go @@ -1,70 +1,52 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/target" ) func TestTargetActivateTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetActivateTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.ActivateTargetParams{ ID: target.ID("target-id"), } - resultChan := mockSocket.Target().ActivateTarget(params) mockResult := &target.ActivateTargetResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().ActivateTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().ActivateTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().ActivateTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetAttachToTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetAttachToTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.AttachToTargetParams{ ID: target.ID("target-id"), } - resultChan := mockSocket.Target().AttachToTarget(params) mockResult := &target.AttachToTargetResult{ SessionID: target.SessionID("session-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().AttachToTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -72,41 +54,29 @@ func TestTargetAttachToTarget(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SessionID, result.SessionID) } - resultChan = mockSocket.Target().AttachToTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().AttachToTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetCloseTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetCloseTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.CloseTargetParams{ ID: target.ID("target-id"), } - resultChan := mockSocket.Target().CloseTarget(params) mockResult := &target.CloseTargetResult{ Success: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().CloseTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -114,38 +84,26 @@ func TestTargetCloseTarget(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Success, result.Success) } - resultChan = mockSocket.Target().CloseTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().CloseTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetCreateBrowserContext(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetCreateBrowserContext") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - resultChan := mockSocket.Target().CreateBrowserContext() mockResult := &target.CreateBrowserContextResult{ BrowserContextID: target.BrowserContextID("BrowserContextID"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().CreateBrowserContext() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -153,26 +111,19 @@ func TestTargetCreateBrowserContext(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.BrowserContextID, result.BrowserContextID) } - resultChan = mockSocket.Target().CreateBrowserContext() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().CreateBrowserContext() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetCreateTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetCreateTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.CreateTargetParams{ URL: "http://some.url", @@ -181,17 +132,12 @@ func TestTargetCreateTarget(t *testing.T) { BrowserContextID: target.BrowserContextID("BrowserContextID"), EnableBeginFrameControl: true, } - resultChan := mockSocket.Target().CreateTarget(params) mockResult := &target.CreateTargetResult{ ID: target.ID("target-id"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().CreateTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -199,79 +145,55 @@ func TestTargetCreateTarget(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ID, result.ID) } - resultChan = mockSocket.Target().CreateTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().CreateTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetDetachFromTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetDetachFromTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.DetachFromTargetParams{ SessionID: target.SessionID("SessionID"), ID: target.ID("ID"), } - resultChan := mockSocket.Target().DetachFromTarget(params) mockResult := &target.DetachFromTargetResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().DetachFromTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().DetachFromTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().DetachFromTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetDisposeBrowserContext(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetDisposeBrowserContext") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.DisposeBrowserContextParams{ ID: target.ID("ID"), } - resultChan := mockSocket.Target().DisposeBrowserContext(params) mockResult := &target.DisposeBrowserContextResult{ Success: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().DisposeBrowserContext(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -279,31 +201,23 @@ func TestTargetDisposeBrowserContext(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Success, result.Success) } - resultChan = mockSocket.Target().DisposeBrowserContext(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().DisposeBrowserContext(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetGetTargetInfo(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetGetTargetInfo") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.GetTargetInfoParams{ ID: target.ID("ID"), } - resultChan := mockSocket.Target().GetTargetInfo(params) mockResult := &target.GetTargetInfoResult{ Infos: []*target.Info{{ ID: target.ID("ID"), @@ -314,13 +228,9 @@ func TestTargetGetTargetInfo(t *testing.T) { OpenerID: target.ID("ID"), }}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().GetTargetInfo(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } @@ -328,26 +238,19 @@ func TestTargetGetTargetInfo(t *testing.T) { t.Errorf("Expected %v, got %v", mockResult.Infos[0].ID, result.Infos[0].ID) } - resultChan = mockSocket.Target().GetTargetInfo(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().GetTargetInfo(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetGetTargets(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetGetTargets") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.GetTargetsParams{ Infos: []*target.Info{{ @@ -359,190 +262,130 @@ func TestTargetGetTargets(t *testing.T) { OpenerID: target.ID("ID"), }}, } - resultChan := mockSocket.Target().GetTargets(params) mockResult := &target.GetTargetsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().GetTargets(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().GetTargets(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().GetTargets(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetSendMessageToTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetSendMessageToTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.SendMessageToTargetParams{ Message: "message", SessionID: target.SessionID("SessionID"), ID: target.ID("ID"), } - resultChan := mockSocket.Target().SendMessageToTarget(params) mockResult := &target.SendMessageToTargetResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().SendMessageToTarget(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().SendMessageToTarget(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().SendMessageToTarget(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetSetAttachToFrames(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetSetAttachToFrames") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.SetAttachToFramesParams{ Value: true, } - resultChan := mockSocket.Target().SetAttachToFrames(params) mockResult := &target.SetAttachToFramesResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().SetAttachToFrames(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().SetAttachToFrames(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().SetAttachToFrames(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetSetAutoAttach(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetSetAutoAttach") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.SetAutoAttachParams{ AutoAttach: true, WaitForDebuggerOnStart: true, } - resultChan := mockSocket.Target().SetAutoAttach(params) mockResult := &target.SetAutoAttachResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().SetAutoAttach(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().SetAutoAttach(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().SetAutoAttach(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetSetDiscoverTargets(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetSetDiscoverTargets") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.SetDiscoverTargetsParams{ Discover: true, } - resultChan := mockSocket.Target().SetDiscoverTargets(params) mockResult := &target.SetDiscoverTargetsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().SetDiscoverTargets(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().SetDiscoverTargets(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().SetDiscoverTargets(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetSetRemoteLocations(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetSetRemoteLocations") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &target.SetRemoteLocationsParams{ Locations: []*target.RemoteLocation{{ @@ -550,44 +393,34 @@ func TestTargetSetRemoteLocations(t *testing.T) { Port: 1, }}, } - resultChan := mockSocket.Target().SetRemoteLocations(params) mockResult := &target.SetRemoteLocationsResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Target().SetRemoteLocations(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Target().SetRemoteLocations(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Target().SetRemoteLocations(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTargetOnAttachedToTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnAttachedToTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.AttachedToTargetEvent) - mockSocket.Target().OnAttachedToTarget(func(eventData *target.AttachedToTargetEvent) { + soc.Target().OnAttachedToTarget(func(eventData *target.AttachedToTargetEvent) { resultChan <- eventData }) + mockResult := &target.AttachedToTargetEvent{ SessionID: target.SessionID("SessionID"), Info: &target.Info{ @@ -600,12 +433,10 @@ func TestTargetOnAttachedToTarget(t *testing.T) { }, WaitingForDebugger: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.attachedToTarget", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -615,17 +446,9 @@ func TestTargetOnAttachedToTarget(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SessionID, result.SessionID) } - resultChan = make(chan *target.AttachedToTargetEvent) - mockSocket.Target().OnAttachedToTarget(func(eventData *target.AttachedToTargetEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.attachedToTarget", }) result = <-resultChan @@ -635,24 +458,25 @@ func TestTargetOnAttachedToTarget(t *testing.T) { } func TestTargetOnDetachedFromTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnDetachedFromTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.DetachedFromTargetEvent) - mockSocket.Target().OnDetachedFromTarget(func(eventData *target.DetachedFromTargetEvent) { + soc.Target().OnDetachedFromTarget(func(eventData *target.DetachedFromTargetEvent) { resultChan <- eventData }) + mockResult := &target.DetachedFromTargetEvent{ SessionID: target.SessionID("SessionID"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.detachedFromTarget", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -662,17 +486,9 @@ func TestTargetOnDetachedFromTarget(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SessionID, result.SessionID) } - resultChan = make(chan *target.DetachedFromTargetEvent) - mockSocket.Target().OnDetachedFromTarget(func(eventData *target.DetachedFromTargetEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.detachedFromTarget", }) result = <-resultChan @@ -682,25 +498,26 @@ func TestTargetOnDetachedFromTarget(t *testing.T) { } func TestTargetOnReceivedMessageFromTarget(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnReceivedMessageFromTarget") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.ReceivedMessageFromTargetEvent) - mockSocket.Target().OnReceivedMessageFromTarget(func(eventData *target.ReceivedMessageFromTargetEvent) { + soc.Target().OnReceivedMessageFromTarget(func(eventData *target.ReceivedMessageFromTargetEvent) { resultChan <- eventData }) + mockResult := &target.ReceivedMessageFromTargetEvent{ SessionID: target.SessionID("SessionID"), Message: "message", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.receivedMessageFromTarget", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -710,17 +527,9 @@ func TestTargetOnReceivedMessageFromTarget(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.SessionID, result.SessionID) } - resultChan = make(chan *target.ReceivedMessageFromTargetEvent) - mockSocket.Target().OnReceivedMessageFromTarget(func(eventData *target.ReceivedMessageFromTargetEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.receivedMessageFromTarget", }) result = <-resultChan @@ -730,15 +539,18 @@ func TestTargetOnReceivedMessageFromTarget(t *testing.T) { } func TestTargetOnTargetCreated(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnTargetCreated") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.CreatedEvent) - mockSocket.Target().OnTargetCreated(func(eventData *target.CreatedEvent) { + soc.Target().OnTargetCreated(func(eventData *target.CreatedEvent) { resultChan <- eventData }) + mockResult := &target.CreatedEvent{ Info: &target.Info{ ID: target.ID("ID"), @@ -749,12 +561,10 @@ func TestTargetOnTargetCreated(t *testing.T) { OpenerID: target.ID("ID"), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.targetCreated", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -764,17 +574,9 @@ func TestTargetOnTargetCreated(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Info.ID, result.Info.ID) } - resultChan = make(chan *target.CreatedEvent) - mockSocket.Target().OnTargetCreated(func(eventData *target.CreatedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.targetCreated", }) result = <-resultChan @@ -784,24 +586,25 @@ func TestTargetOnTargetCreated(t *testing.T) { } func TestTargetOnTargetDestroyed(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnTargetDestroyed") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.DestroyedEvent) - mockSocket.Target().OnTargetDestroyed(func(eventData *target.DestroyedEvent) { + soc.Target().OnTargetDestroyed(func(eventData *target.DestroyedEvent) { resultChan <- eventData }) + mockResult := &target.DestroyedEvent{ ID: target.ID("ID"), } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.targetDestroyed", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -811,17 +614,9 @@ func TestTargetOnTargetDestroyed(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.ID, result.ID) } - resultChan = make(chan *target.DestroyedEvent) - mockSocket.Target().OnTargetDestroyed(func(eventData *target.DestroyedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.targetDestroyed", }) result = <-resultChan @@ -831,15 +626,18 @@ func TestTargetOnTargetDestroyed(t *testing.T) { } func TestTargetOnTargetInfoChanged(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTargetOnTargetInfoChanged") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *target.InfoChangedEvent) - mockSocket.Target().OnTargetInfoChanged(func(eventData *target.InfoChangedEvent) { + soc.Target().OnTargetInfoChanged(func(eventData *target.InfoChangedEvent) { resultChan <- eventData }) + mockResult := &target.InfoChangedEvent{ Info: &target.Info{ ID: target.ID("ID"), @@ -850,12 +648,10 @@ func TestTargetOnTargetInfoChanged(t *testing.T) { OpenerID: target.ID("ID"), }, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Target.targetInfoChanged", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -865,17 +661,9 @@ func TestTargetOnTargetInfoChanged(t *testing.T) { t.Errorf("Expected %s, got %s", mockResult.Info.ID, result.Info.ID) } - resultChan = make(chan *target.InfoChangedEvent) - mockSocket.Target().OnTargetInfoChanged(func(eventData *target.InfoChangedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Target.targetInfoChanged", }) result = <-resultChan diff --git a/tot/socket/cdtp.tethering_test.go b/tot/socket/cdtp.tethering_test.go index 6b979da..2d736dc 100644 --- a/tot/socket/cdtp.tethering_test.go +++ b/tot/socket/cdtp.tethering_test.go @@ -1,107 +1,82 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/tethering" ) func TestTetheringBind(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTetheringBind") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tethering.BindParams{ Port: 1, } - resultChan := mockSocket.Tethering().Bind(params) mockResult := &tethering.BindResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Tethering().Bind(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Tethering().Bind(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Tethering().Bind(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTetheringUnbind(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTetheringUnbind") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() params := &tethering.UnbindParams{ Port: 1, } - resultChan := mockSocket.Tethering().Unbind(params) mockResult := &tethering.UnbindResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, ""}) + result := <-soc.Tethering().Unbind(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Tethering().Unbind(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, ""}) + result = <-soc.Tethering().Unbind(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTetheringOnAccepted(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTetheringOnAccepted") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() resultChan := make(chan *tethering.AcceptedEvent) - mockSocket.Tethering().OnAccepted(func(eventData *tethering.AcceptedEvent) { + soc.Tethering().OnAccepted(func(eventData *tethering.AcceptedEvent) { resultChan <- eventData }) + mockResult := &tethering.AcceptedEvent{ Port: 1, ConnectionID: "ConnectionID", } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: mockResult, Method: "Tethering.accepted", - Params: mockResultBytes, }) result := <-resultChan if mockResult.Err != result.Err { @@ -111,17 +86,9 @@ func TestTetheringOnAccepted(t *testing.T) { t.Errorf("Expected %d, got %d", mockResult.Port, result.Port) } - resultChan = make(chan *tethering.AcceptedEvent) - mockSocket.Tethering().OnAccepted(func(eventData *tethering.AcceptedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Tethering.accepted", }) result = <-resultChan diff --git a/tot/socket/cdtp.tracing_test.go b/tot/socket/cdtp.tracing_test.go index b1c12aa..1140127 100644 --- a/tot/socket/cdtp.tracing_test.go +++ b/tot/socket/cdtp.tracing_test.go @@ -1,8 +1,6 @@ package socket import ( - "encoding/json" - "net/url" "testing" "github.com/mkenney/go-chrome/tot/io" @@ -10,164 +8,117 @@ import ( ) func TestTracingEnd(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingEnd") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() - resultChan := mockSocket.Tracing().End() mockResult := &tracing.EndResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, "Tracing.end"}) + result := <-soc.Tracing().End() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Tracing().End() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, "Tracing.end"}) + result = <-soc.Tracing().End() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTracingGetCategories(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingGetCategories") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() - resultChan := mockSocket.Tracing().GetCategories() mockResult := &tracing.GetCategoriesResult{ Categories: []string{"cat1", "cat2"}, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, "Tracing.getCategories"}) + result := <-soc.Tracing().GetCategories() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - if mockResult.Categories[0] != result.Categories[0] { - t.Errorf("Expected %s, got %s", mockResult.Categories[0], result.Categories[0]) + if "cat1" != result.Categories[0] { + t.Errorf("Expected %s, got %s", "cat1", result.Categories[0]) } - resultChan = mockSocket.Tracing().GetCategories() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, "Tracing.getCategories"}) + result = <-soc.Tracing().GetCategories() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTracingRecordClockSyncMarker(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingRecordClockSyncMarker") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() params := &tracing.RecordClockSyncMarkerParams{ SyncID: "SyncID", } - resultChan := mockSocket.Tracing().RecordClockSyncMarker(params) mockResult := &tracing.RecordClockSyncMarkerResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, "Tracing.recordClockSyncMarker"}) + result := <-soc.Tracing().RecordClockSyncMarker(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Tracing().RecordClockSyncMarker(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, "Tracing.recordClockSyncMarker"}) + result = <-soc.Tracing().RecordClockSyncMarker(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTracingRequestMemoryDump(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingRequestMemoryDump") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() - resultChan := mockSocket.Tracing().RequestMemoryDump() mockResult := &tracing.RequestMemoryDumpResult{ DumpGUID: "DumpGUID", Success: true, } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, "Tracing.requestMemoryDump"}) + result := <-soc.Tracing().RequestMemoryDump() if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - if mockResult.DumpGUID != result.DumpGUID { - t.Errorf("Expected %s, got %s", mockResult.DumpGUID, result.DumpGUID) + if "DumpGUID" != result.DumpGUID { + t.Errorf("Expected %s, got %s", "DumpGUID", result.DumpGUID) } - resultChan = mockSocket.Tracing().RequestMemoryDump() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, "Tracing.requestMemoryDump"}) + result = <-soc.Tracing().RequestMemoryDump() if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTracingStart(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingStart") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() params := &tracing.StartParams{ - Categories: "Categories", - Options: "Options", + Categories: "Categories", + Options: "Options", BufferUsageReportingInterval: 1, TransferMode: tracing.TransferMode.ReportEvents, TraceConfig: &tracing.TraceConfig{ @@ -181,75 +132,54 @@ func TestTracingStart(t *testing.T) { MemoryDumpConfig: tracing.MemoryDumpConfig{"key": "value"}, }, } - resultChan := mockSocket.Tracing().Start(params) mockResult := &tracing.StartResult{} - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{}, - Result: mockResultBytes, - }) - result := <-resultChan + + chrome.AddData(MockData{0, &Error{}, mockResult, "Tracing.start"}) + result := <-soc.Tracing().Start(params) if nil != result.Err { t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) } - resultChan = mockSocket.Tracing().Start(params) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: mockSocket.CurCommandID(), - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, - }) - result = <-resultChan + chrome.AddData(MockData{0, genericError, nil, "Tracing.start"}) + result = <-soc.Tracing().Start(params) if nil == result.Err { t.Errorf("Expected error, got success") } } func TestTracingOnBufferUsage(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingOnBufferUsage") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() resultChan := make(chan *tracing.BufferUsageEvent) - mockSocket.Tracing().OnBufferUsage(func(eventData *tracing.BufferUsageEvent) { + soc.Tracing().OnBufferUsage(func(eventData *tracing.BufferUsageEvent) { resultChan <- eventData }) - mockResult := &tracing.BufferUsageEvent{ - PercentFull: 1, - EventCount: 1, - Value: 1, - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + + chrome.AddData(MockData{ + Err: &Error{}, + Result: &tracing.BufferUsageEvent{ + PercentFull: 1, + EventCount: 1, + Value: 1, + }, Method: "Tracing.bufferUsage", - Params: mockResultBytes, }) result := <-resultChan - if mockResult.Err != result.Err { - t.Errorf("Expected '%v', got: '%v'", mockResult, result) + if nil != result.Err { + t.Errorf("Expected '%v', got: '%v'", nil, result) } - if mockResult.PercentFull != result.PercentFull { - t.Errorf("Expected %f, got %f", mockResult.PercentFull, result.PercentFull) + if float64(1) != result.PercentFull { + t.Errorf("Expected %f, got %f", float64(1), result.PercentFull) } - resultChan = make(chan *tracing.BufferUsageEvent) - mockSocket.Tracing().OnBufferUsage(func(eventData *tracing.BufferUsageEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Tracing.bufferUsage", }) result = <-resultChan @@ -259,44 +189,36 @@ func TestTracingOnBufferUsage(t *testing.T) { } func TestTracingOnDataCollected(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingOnDataCollected") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() resultChan := make(chan *tracing.DataCollectedEvent) - mockSocket.Tracing().OnDataCollected(func(eventData *tracing.DataCollectedEvent) { + soc.Tracing().OnDataCollected(func(eventData *tracing.DataCollectedEvent) { resultChan <- eventData }) - mockResult := &tracing.DataCollectedEvent{ - Value: []map[string]string{{"key": "value"}}, - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + + chrome.AddData(MockData{ + Err: &Error{}, + Result: &tracing.DataCollectedEvent{ + Value: []map[string]string{{"key": "value"}}, + }, Method: "Tracing.dataCollected", - Params: mockResultBytes, }) result := <-resultChan - if mockResult.Err != result.Err { - t.Errorf("Expected '%v', got: '%v'", mockResult, result) + if nil != result.Err { + t.Errorf("Expected '%v', got: '%v'", nil, result) } - if mockResult.Value[0]["key"] != result.Value[0]["key"] { - t.Errorf("Expected %s, got %s", mockResult.Value[0]["key"], result.Value[0]["key"]) + if "value" != result.Value[0]["key"] { + t.Errorf("Expected %s, got %s", "value", result.Value[0]["key"]) } - resultChan = make(chan *tracing.DataCollectedEvent) - mockSocket.Tracing().OnDataCollected(func(eventData *tracing.DataCollectedEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Tracing.dataCollected", }) result = <-resultChan @@ -306,44 +228,36 @@ func TestTracingOnDataCollected(t *testing.T) { } func TestTracingOnTracingComplete(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestTracingOnTracingComplete") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer func() { chrome.Close() }() + soc := New(chrome.URL) + defer func() { soc.Stop() }() resultChan := make(chan *tracing.CompleteEvent) - mockSocket.Tracing().OnTracingComplete(func(eventData *tracing.CompleteEvent) { + soc.Tracing().OnTracingComplete(func(eventData *tracing.CompleteEvent) { resultChan <- eventData }) - mockResult := &tracing.CompleteEvent{ - Stream: io.StreamHandle("StreamHandle"), - } - mockResultBytes, _ := json.Marshal(mockResult) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + + chrome.AddData(MockData{ + Err: &Error{}, + Result: &tracing.CompleteEvent{ + Stream: io.StreamHandle("StreamHandle"), + }, Method: "Tracing.tracingComplete", - Params: mockResultBytes, }) result := <-resultChan - if mockResult.Err != result.Err { - t.Errorf("Expected '%v', got: '%v'", mockResult, result) + if nil != result.Err { + t.Errorf("Expected '%v', got: '%v'", nil, result.Err) } - if mockResult.Stream != result.Stream { - t.Errorf("Expected %s, got %s", mockResult.Stream, result.Stream) + if io.StreamHandle("StreamHandle") != result.Stream { + t.Errorf("Expected %v, got %v", io.StreamHandle("StreamHandle"), result.Stream) } - resultChan = make(chan *tracing.CompleteEvent) - mockSocket.Tracing().OnTracingComplete(func(eventData *tracing.CompleteEvent) { - resultChan <- eventData - }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{ - Code: 1, - Data: []byte(`"error data"`), - Message: "error message", - }, + chrome.AddData(MockData{ + Err: genericError, + Result: nil, Method: "Tracing.tracingComplete", }) result = <-resultChan diff --git a/tot/socket/mock.chrome_test.go b/tot/socket/mock.chrome_test.go new file mode 100644 index 0000000..fce934a --- /dev/null +++ b/tot/socket/mock.chrome_test.go @@ -0,0 +1,327 @@ +package socket + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/bdlm/log" + "github.com/gorilla/websocket" + "github.com/mkenney/go-chrome/tot/tracing" +) + +func init() { + log.SetFormatter(&log.TextFormatter{ + ForceTTY: true, + //EnableTrace: true, + }) + level, err := log.ParseLevel("debug") + if nil == err { + log.SetLevel(level) + } +} + +func NewMockChrome() *MockChrome { + return &MockChrome{ + mux: &sync.Mutex{}, + logger: log.WithFields(log.Fields{ + "mock": "chrome", + }), + } +} + +var upgrader = websocket.Upgrader{} + +var genericError = &Error{ + Code: 1, + Data: []byte(`"error data"`), + Message: "error message", +} + +type MockChrome struct { + breaker chan bool + logger *log.Entry + sleep time.Duration + + IgnoreInput bool + Server *httptest.Server + URL *url.URL + + mux *sync.Mutex + Data []MockData +} + +var socketMux = &sync.Mutex{} + +type MockData struct { + ID int + Err *Error + Result interface{} + Method string +} + +func (chrome *MockChrome) AddData(data MockData) { + chrome.mux.Lock() + chrome.Data = append(chrome.Data, data) + chrome.mux.Unlock() +} + +func (chrome *MockChrome) Close() { + chrome.Server.Close() +} + +func (chrome *MockChrome) popMockData(socket *websocket.Conn) MockData { + data := MockData{} + for { + chrome.mux.Lock() + + // no data, break + if 0 == len(chrome.Data) { + chrome.mux.Unlock() + time.Sleep(1 * time.Millisecond) + continue + } + + data = chrome.Data[0] + chrome.Data = chrome.Data[1:] + chrome.mux.Unlock() + + break + } + chrome.logger.WithFields(log.Fields{"data": data}). + Info("fetching mock chrome socket response data") + return data +} + +type ReadLoopData struct { + Err error + Payload Payload +} + +// launchListener starts the websocket input read loop. +func (chrome *MockChrome) launchListener( + websoc *websocket.Conn, + breaker chan bool, + dataChan chan ReadLoopData, +) { + + if chrome.IgnoreInput { + <-breaker + breaker <- true + return + } + + dataFeed := make(chan ReadLoopData) + dataFeedBreaker := make(chan bool) + go func() { + for { + select { + case <-dataFeedBreaker: + dataFeedBreaker <- true + return + default: + var data ReadLoopData + err := websoc.ReadJSON(&data.Payload) + if nil != err { + data.Err = err + // If the websocket closes kill the loop + if strings.Contains(data.Err.Error(), "abnormal closure") { + chrome.logger.WithFields(log.Fields{"data": data}). + Debug("websocket closed, ending read loop") + dataFeed <- data + return + } + } + chrome.logger.WithFields(log.Fields{"data": data}). + Debug("returning websocket input") + dataFeed <- data + } + } + }() + + for { + select { + case <-breaker: + chrome.logger.Debug("shutting down mock chrome websocket input read loop") + dataFeedBreaker <- true + breaker <- <-dataFeedBreaker + return + case dataChan <- <-dataFeed: + } + } +} + +// launchMockDataFeed starts the mock input data feeder. +func (chrome *MockChrome) launchMockDataFeed( + websoc *websocket.Conn, + breaker chan bool, + dataChan chan MockData, +) { + if !chrome.IgnoreInput { + <-breaker + breaker <- true + return + } + for { + if chrome.sleep > 0 { + time.Sleep(chrome.sleep) + } + select { + case <-breaker: + chrome.logger.Debug("shutting down mock chrome websocket write loop") + breaker <- true + return + case dataChan <- chrome.popMockData(websoc): + chrome.logger.Debug("mock data written to mock chrome websocket") + } + } +} + +// handle is the request data handler. +func (chrome *MockChrome) handle(writer http.ResponseWriter, request *http.Request) { + var err error + var response *Response + readLoopBreaker := make(chan bool, 1) + readLoopChan := make(chan ReadLoopData, 3) + writeLoopBreaker := make(chan bool, 1) + writeLoopChan := make(chan MockData, 3) + + // upgrade connection to a websocket + websoc, err := upgrader.Upgrade(writer, request, nil) + if err != nil { + return + } + + // websocket handler cleanup + defer func() { + chrome.logger.Debug("shutting down mock chrome") + readLoopBreaker <- true + writeLoopBreaker <- true + <-readLoopBreaker + <-writeLoopBreaker + websoc.Close() + }() + + // launch the websocket input read loop for this connection. + go chrome.launchListener(websoc, readLoopBreaker, readLoopChan) + + // launch the mock data loop for this connection. + go chrome.launchMockDataFeed(websoc, writeLoopBreaker, writeLoopChan) + + // main event loop + errCnt := 0 + for { + response = nil + + select { + case <-chrome.breaker: + chrome.logger.Debug("shutting down mock chrome event loop") + return + + // Manage any data input. + case data := <-readLoopChan: + if nil != data.Err { + errCnt++ + chrome.logger.WithField("error", data.Err).Warn("mock chrome read loop returned an error, shutting down") + if errCnt > 10 { + chrome.breaker <- true + } + } else { + errCnt = 0 + } + + mockData := chrome.popMockData(websoc) + mockData.ID = data.Payload.ID + mockData.Method = data.Payload.Method + if mockData.ID == 0 { + mockData.Result = data.Payload.Params + } + chrome.logger.WithField("data", mockData).Info("handling mock chrome websocket input") + writeLoopChan <- mockData + + // Return responses. + case data := <-writeLoopChan: + chrome.logger.WithField("data", data).Info("building mock chrome websocket response") + + response = &Response{} + response.Error = data.Err + response.Method = data.Method + response.ID = data.ID + + var mockResultBytes []byte + if nil != data.Result { + mockResultBytes, _ = json.Marshal(data.Result) + } + if response.ID > 0 { + response.Result = mockResultBytes + } else { + response.Params = mockResultBytes + } + + chrome.logger.WithFields(log.Fields{"data": data, "response": response}). + Info("writing response to mock chrome websocket connection") + + socketMux.Lock() + err = websoc.WriteJSON(response) + socketMux.Unlock() + + if nil != err { + chrome.logger.Errorf("%-v", err) + break + } + } + } +} + +func (chrome *MockChrome) ListenAndServe() { + chrome.Server = httptest.NewServer(http.HandlerFunc(chrome.handle)) + chrome.URL, _ = url.Parse("ws" + strings.TrimPrefix(chrome.Server.URL, "http")) +} + +func (chrome *MockChrome) Sleep(duration time.Duration) { + chrome.sleep = duration +} + +func TestMockSocket(t *testing.T) { + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + chrome.AddData(MockData{ + Err: &Error{}, + Result: &tracing.GetCategoriesResult{ + Categories: []string{"cat1", "cat2"}, + }, + Method: "Tracing.getCategories", + }) + resultChan := soc.Tracing().GetCategories() + result := <-resultChan + if nil != result.Err { + t.Errorf("Expected nil, got error: '%s'", result.Err.Error()) + } + if "cat1" != result.Categories[0] { + t.Errorf("Expected %s, got %s", "cat1", result.Categories[0]) + } + + chrome.AddData(MockData{ + Err: &Error{ + Code: 1, + Data: []byte(`"error data"`), + Message: "error message", + }, + Result: nil, + Method: "Tracing.getCategories", + }) + resultChan = soc.Tracing().GetCategories() + result = <-resultChan + if nil == result.Err { + t.Errorf("Expected error, got success") + } +} diff --git a/tot/socket/socket.conner.go b/tot/socket/socket.conner.go index 3bf4d4d..f58f72e 100644 --- a/tot/socket/socket.conner.go +++ b/tot/socket/socket.conner.go @@ -1,16 +1,13 @@ package socket import ( - "fmt" - errs "github.com/bdlm/errors" "github.com/bdlm/log" ) /* -Conn returns the current web socket pointer. - -Conn is a Conner implementation. +Conn returns the current web socket pointer. Conn is a Conner +implementation. */ func (socket *Socket) Conn() WebSocketer { socket.Connect() @@ -18,85 +15,93 @@ func (socket *Socket) Conn() WebSocketer { } /* -Connect establishes a websocket connection. - -Connect is a Conner implementation. +Connect establishes a websocket connection. Connect is a Conner +implementation. */ func (socket *Socket) Connect() error { socket.mux.Lock() - defer socket.mux.Unlock() - - if socket.connected { + if nil != socket.conn { + socket.mux.Unlock() return nil } + socket.mux.Lock() - log.WithFields(log.Fields{ - "socketID": socket.socketID, - "url": socket.url.String(), - }).Debug("connecting") + socket.logger.Debug("connecting") websocket, err := socket.newSocket(socket.url) if nil != err { - log.WithFields(log.Fields{ - "error": err.Error(), - "socketID": socket.socketID, - }).Debug("received error") - socket.connected = false + socket.logger.WithFields(log.Fields{"error": err.Error()}). + Debug("received error") + socket.mux.Lock() + socket.conn = nil + socket.mux.Unlock() return errs.Wrap(err, 0, "Connect() failed while creating socket") } - + socket.mux.Lock() socket.conn = websocket - socket.connected = true - - log.WithFields(log.Fields{ - "socketID": socket.socketID, - "url": socket.url.String(), - }).Debug("connection established") + socket.mux.Unlock() + + socket.logger.Debug("connection established") + + // launch the connection circuit breaker + go func() { + <-socket.disconnect + success := true + socket.mux.Lock() + if nil == socket.conn { + socket.mux.Unlock() + socket.logger.Warn("disconnect requested on nil connection") + } else { + socket.mux.Unlock() + err := socket.conn.Close() + if nil != err { + success = false + } + socket.mux.Lock() + socket.conn = nil + socket.mux.Unlock() + } + socket.disconnect <- success + + }() return nil } /* -Connected returns whether a connection exists. - -Connected is a Conner implementation. +Connected returns whether a connection exists. Connected is a Conner +implementation. */ func (socket *Socket) Connected() bool { - return socket.connected + socket.mux.Lock() + connected := nil != socket.conn + socket.mux.Unlock() + return connected } /* -Disconnect closes a websocket connection. - -Disconnect is a Conner implementation. +Disconnect closes a websocket connection. Disconnect is a Conner +implementation. */ func (socket *Socket) Disconnect() error { - if !socket.connected { - return fmt.Errorf("not connected") + socket.disconnect <- true + if !<-socket.disconnect { + return errs.New(0, "error disconnecting socket connection") } - socket.Stop() - err := socket.conn.Close() - if nil != err { - socket.listenErr.With(err, "could not close socket connection") - } - socket.conn = nil - socket.connected = false - if 0 == len(socket.listenErr) { - return nil - } - return socket.listenErr + return nil } /* -ReadJSON reads data from a websocket connection. - -ReadJSON is a Conner implementation. +ReadJSON reads data from a websocket connection. ReadJSON is a Conner +implementation. */ func (socket *Socket) ReadJSON(v interface{}) error { - err := socket.Connect() - if nil != err { - return errs.Wrap(err, 0, "not connected") + socket.mux.Lock() + if nil == socket.conn { + socket.mux.Unlock() + return errs.New(0, "not connected") } + socket.mux.Unlock() - err = socket.conn.ReadJSON(&v) + err := socket.conn.ReadJSON(&v) if nil != err { return errs.Wrap(err, 0, "socket read failed") } @@ -105,17 +110,18 @@ func (socket *Socket) ReadJSON(v interface{}) error { } /* -WriteJSON writes data to a websocket connection. - -WriteJSON is a Conner implementation. +WriteJSON writes data to a websocket connection. WriteJSON is a Conner +implementation. */ func (socket *Socket) WriteJSON(v interface{}) error { - err := socket.Connect() - if nil != err { - return errs.Wrap(err, 0, "not connected") + socket.mux.Lock() + if nil == socket.conn { + socket.mux.Unlock() + return errs.New(0, "not connected") } + socket.mux.Unlock() - err = socket.conn.WriteJSON(v) + err := socket.conn.WriteJSON(v) if nil != err { return errs.Wrap(err, 0, "socket write failed") } diff --git a/tot/socket/socket.conner_test.go b/tot/socket/socket.conner_test.go index a64f586..e720731 100644 --- a/tot/socket/socket.conner_test.go +++ b/tot/socket/socket.conner_test.go @@ -1,26 +1,26 @@ package socket import ( - "net/url" "testing" ) func TestConner(t *testing.T) { var err error - socketURL, _ := url.Parse("http://test:9222/TestConner") - socket := NewMock(socketURL) - err = socket.Connect() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + err = soc.Connect() if nil != err { t.Errorf("Expected nil, got error: '%s'", err.Error()) } - if !socket.Connected() { + if !soc.Connected() { t.Errorf("Expected true, got false") } - err = socket.Disconnect() - if nil != err { - t.Errorf("Expected nil, got error: '%s'", err.Error()) - } + soc.Disconnect() } diff --git a/tot/socket/socket.event_handler_mapper.go b/tot/socket/socket.event_handler_mapper.go index fa4fe0f..12fe456 100644 --- a/tot/socket/socket.event_handler_mapper.go +++ b/tot/socket/socket.event_handler_mapper.go @@ -35,9 +35,6 @@ Add is an EventHandlerMapper implementation. func (stack *EventHandlerMap) Add( handler EventHandler, ) error { - stack.Lock() - defer stack.Unlock() - handlers, err := stack.Get(handler.Name()) if nil != err { handlers = make([]EventHandler, 0) @@ -64,7 +61,9 @@ Delete is an EventHandlerMapper implementation. func (stack *EventHandlerMap) Delete( name string, ) { + stack.Lock() delete(stack.stack, name) + stack.Unlock() } /* @@ -75,6 +74,8 @@ Get is an EventHandlerMapper implementation. func (stack *EventHandlerMap) Get( name string, ) ([]EventHandler, error) { + stack.Lock() + defer stack.Unlock() if handlers, ok := stack.stack[name]; ok { return handlers, nil } @@ -119,7 +120,9 @@ func (stack *EventHandlerMap) Set( eventName string, handlers []EventHandler, ) { + stack.Lock() stack.stack[eventName] = handlers + stack.Unlock() } /* diff --git a/tot/socket/socket.event_handler_test.go b/tot/socket/socket.event_handler_test.go index d0a95f3..2dd3e8d 100644 --- a/tot/socket/socket.event_handler_test.go +++ b/tot/socket/socket.event_handler_test.go @@ -2,58 +2,56 @@ package socket import ( "encoding/json" - "net/url" "testing" ) func TestHandleEvent(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestHandleEvent") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + chrome.IgnoreInput = true + defer chrome.Close() + soc := New(chrome.URL) + defer func() { soc.Stop() }() eventResponse1 := make(chan *Response) handler1 := NewEventHandler("Some.event", func(response *Response) { eventResponse1 <- response }) + soc.AddEventHandler(handler1) eventResponse2 := make(chan *Response) handler2 := NewEventHandler("Some.event", func(response *Response) { eventResponse2 <- response }) + soc.AddEventHandler(handler2) eventResponse3 := make(chan *Response) handler3 := NewEventHandler("Inspector.targetCrashed", func(response *Response) { eventResponse3 <- response }) + soc.AddEventHandler(handler3) - mockSocket.AddEventHandler(handler1) - mockSocket.AddEventHandler(handler2) - mockSocket.AddEventHandler(handler3) - - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: "Mock Event Result", Method: "Some.event", - Result: []byte(`"Mock Event Result"`), }) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: &Error{}, + chrome.AddData(MockData{ + Err: &Error{}, + Result: "Mock Target Crashed", Method: "Inspector.targetCrashed", - Result: []byte(`"Mock Target Crashed"`), }) response1 := <-eventResponse1 response2 := <-eventResponse2 response3 := <-eventResponse3 - if nil == response1.Result { + if nil == response1.Params { t.Errorf("Invalid result: expected 'Mock Event Result', received nil") } - if `"Mock Event Result"` != string(response1.Result) { - t.Errorf("Invalid result: expected 'Mock Event Result', received '%s'", response1.Result) + if `"Mock Event Result"` != string(response1.Params) { + t.Errorf("Invalid result: expected 'Mock Event Result', received '%v'", string(response1.Result)) } response1JSON, _ := json.Marshal(response1) @@ -62,11 +60,11 @@ func TestHandleEvent(t *testing.T) { t.Errorf("Event handlers returned mismatched data") } - if nil == response3.Result { + if nil == response3.Params { t.Errorf("Invalid result: expected 'Mock Target Crashed', received nil") } - if `"Mock Target Crashed"` != string(response3.Result) { - t.Errorf("Invalid result: expected 'Mock Target Crashed', received '%s'", response3.Result) + if `"Mock Target Crashed"` != string(response3.Params) { + t.Errorf("Invalid result: expected 'Mock Target Crashed', received '%v'", string(response3.Result)) } } diff --git a/tot/socket/socket.socketer.go b/tot/socket/socket.socketer.go index b5b6d88..e66efc6 100644 --- a/tot/socket/socket.socketer.go +++ b/tot/socket/socket.socketer.go @@ -5,7 +5,6 @@ import ( "fmt" "net/url" "sync" - "time" errs "github.com/bdlm/errors" "github.com/bdlm/log" @@ -19,12 +18,18 @@ func New(url *url.URL) *Socket { socket := &Socket{ commandIDMux: &sync.Mutex{}, commands: NewCommandMap(), + disconnect: make(chan bool), handlers: NewEventHandlerMap(), mux: &sync.Mutex{}, newSocket: NewWebsocket, socketID: NextSocketID(), url: url, + stop: make(chan bool), } + socket.logger = log.WithFields(log.Fields{ + "socket.id": socket.socketID, + "socket.url": socket.url.String(), + }) // Init the protocol interfaces for the API. socket.accessibility = &AccessibilityProtocol{Socket: socket} @@ -67,10 +72,7 @@ func New(url *url.URL) *Socket { socket.tracing = &TracingProtocol{Socket: socket} socket.Listen() - log.WithFields(log.Fields{ - "socketID": socket.socketID, - "url": socket.url.String(), - }).Info("New socket connection listening") + socket.logger.Info("New socket connection listening") return socket } @@ -97,17 +99,18 @@ type Socket struct { commandID int commandIDMux *sync.Mutex commands CommandMapper - conn WebSocketer - connected bool handlers EventHandlerMapper - listenCh chan bool - listenErr errs.Err - listening bool - mux *sync.Mutex + logger *log.Entry newSocket func(socketURL *url.URL) (WebSocketer, error) socketID int url *url.URL + disconnect chan bool + stop chan bool + + mux *sync.Mutex + conn WebSocketer + // Protocol interfaces for the API. accessibility *AccessibilityProtocol animation *AnimationProtocol @@ -177,29 +180,17 @@ handleResponse receives the responses to requests sent to the websocket connection. */ func (socket *Socket) handleResponse(response *Response) { - // Log a message on error if command, err := socket.commands.Get(response.ID); nil != err { - err = errs.Wrap(err, 0, fmt.Sprintf("command #%d not found", response.ID)) - log.WithFields(log.Fields{ - "error": err, - "result": response.Result, - "socketID": socket.socketID, - }).Debug(response.Error) + socket.logger.WithFields(log.Fields{"error": err, "response": response}). + Debugf("%-v", errs.Wrap(err, 0, fmt.Sprintf("command #%d not found", response.ID))) } else { - log.WithFields(log.Fields{ - "commandID": command.ID(), - "method": command.Method(), - "socketID": socket.socketID, - }).Debug("executing handler") + socket.logger.WithFields(log.Fields{"command.id": command.ID(), "command.method": command.Method()}). + Debug("executing handler") command.Respond(response) socket.commands.Delete(command.ID()) - log.WithFields(log.Fields{ - "commandID": command.ID(), - "method": command.Method(), - "socketID": socket.socketID, - "url": socket.url.String(), - }).Debug("Command complete") + socket.logger.WithFields(log.Fields{"response": response, "command.id": command.ID(), "command.method": command.Method()}). + Debug("Command complete") } } @@ -207,33 +198,21 @@ func (socket *Socket) handleResponse(response *Response) { handleEvent receives all events and associated data read from the websocket connection. */ -func (socket *Socket) handleEvent( - response *Response, -) { - log.WithFields(log.Fields{ - "event": response.Method, - "socketID": socket.socketID, - "url": socket.url.String(), - }).Debug("handling event") +func (socket *Socket) handleEvent(response *Response) { + socket.logger.WithFields(log.Fields{"response": response}). + Debug("handling event") if response.Method == "Inspector.targetCrashed" { - log.WithFields(log.Fields{ - "socketID": socket.socketID, - }).Error("Chrome has crashed!") + socket.logger.Warn("Chrome has crashed!") } if handlers, err := socket.handlers.Get(response.Method); nil != err { - log.WithFields(log.Fields{ - "error": err, - "socketID": socket.socketID, - }).Debug(err) + socket.logger.WithFields(log.Fields{"error": err}). + Debug(err) } else { for a, event := range handlers { - log.WithFields(log.Fields{ - "event": response.Method, - "handler#": a, - "socketID": socket.socketID, - }).Info("Executing handler") + socket.logger.WithFields(log.Fields{"event": response.Method, "handler#": a}). + Info("Executing handler") go event.Handle(response) } } @@ -245,34 +224,26 @@ handleUnknown receives all other socket responses. func (socket *Socket) handleUnknown( response *Response, ) { - log.WithFields(log.Fields{ - "socketID": socket.socketID, - "url": socket.url.String(), - }).Debug("handling unexpected data") var command Commander var err error - // Check for a command listening for ID 0 + socket.logger.WithFields(log.Fields{"response": response}). + Debug("handling unexpected data") + + // Check for a command listening for ID 0. if command, err = socket.commands.Get(response.ID); nil != err { err = errs.Wrap(err, 0, fmt.Sprintf("command #%d not found", response.ID)) if nil != response.Error && 0 != response.Error.Code { - err = err.(errs.Err).With(response.Error, err.Error()) + err = err.(*errs.Err).With(response.Error, err.Error()) } - log.WithFields(log.Fields{ - "error": err, - "result": response.Result, - "socketID": socket.socketID, - }).Debug(err) + socket.logger.WithFields(log.Fields{"error": err, "response": response}). + Debugf("%-v", err) return } command.Respond(response) - log.WithFields(log.Fields{ - "commandID": command.ID(), - "error": response.Error, - "method": command.Method(), - "socketID": socket.socketID, - }).Debug("Unrecognised socket message") + socket.logger.WithFields(log.Fields{"command.id": command.ID(), "error": response.Error, "command.method": command.Method()}). + Debug("Unrecognised socket message") } /* @@ -282,89 +253,106 @@ handleEvent() as appropriate. Listen is a Socketer implementation. */ func (socket *Socket) Listen() { - socket.listenCh = make(chan bool) - socket.listening = true + socket.Connect() go socket.listen() } func (socket *Socket) listen() error { - var err error - - err = socket.Connect() - if nil != err { - return errs.Wrap(err, 0, "socket connection failed") + var failures int + breaker := make(chan bool) + type ReadLoopData struct { + Err error + Response *Response } - defer socket.Disconnect() + readLoopChan := make(chan ReadLoopData) - for { - response := &Response{} - err = socket.ReadJSON(&response) - if nil != err { - log.WithFields(log.Fields{ - "socketID": socket.socketID, - }).Error(err) - socket.listenErr.With(err, fmt.Sprintf("socket #%d - socket read failed", socket.socketID)) - } - if 0 == response.ID && - "" == response.Method && - 0 == len(response.Params) && - 0 == len(response.Result) { - log.WithFields(log.Fields{ - "socketID": socket.socketID, - }).Error("nil response from socket") - } + // launch the main read loop + go func() { + for { + select { + // stop signal, stop the socket read loop and end the listner loop. + case <-socket.stop: + socket.logger.Info("socket read loop shutting down") + breaker <- true + socket.logger.Info("breaker stopped") + <-breaker + socket.logger.Info("'breaker stopped' signal sent") + socket.stop <- true + socket.logger.Info("'socket stopped' signal sent") + return + + case data := <-readLoopChan: + // read failure. + if nil != data.Err { + socket.logger.WithFields(log.Fields{"error": data.Err, "data": data}). + Warnf("%-v", data.Err) + failures++ + } else { + failures = 0 + } + + // too many read failures. + if failures > 20 { + socket.logger.Error("too many read failures, shutting down") + socket.Stop() + continue + } - if response.ID > 0 { - log.WithFields(log.Fields{ - "responseID": response.ID, - "socketID": socket.socketID, - }).Debug("sending to command handler") - socket.handleResponse(response) - - } else if "" != response.Method { - log.WithFields(log.Fields{ - "method": response.Method, - "socketID": socket.socketID, - }).Debug("sending to event handler") - socket.handleEvent(response) - - } else { - tmp, _ := json.Marshal(response) - log.WithFields(log.Fields{ - "data": string(tmp), - "method": response.Method, - "responseID": response.ID, - "socketID": socket.socketID, - }).Error("Unknown response from web socket") - - if nil == response.Error { - response.Error = &Error{ - Message: "Unknown response from web socket", + switch true { + // command responses. + case data.Response.ID > 0: + socket.logger.WithFields(log.Fields{"responseID": data.Response.ID}).Debug("sending socket message to command handler") + socket.handleResponse(data.Response) + + // event responses. + case "" != data.Response.Method: + socket.logger.WithFields(log.Fields{"command.method": data.Response.Method}).Debug("sending socket message to event handler") + socket.handleEvent(data.Response) + + // unknown responses. + default: + tmp, _ := json.Marshal(data.Response) + if nil == data.Response.Error { + data.Response.Error = &Error{ + Message: "Unknown response from web socket", + } + } + + socket.logger.WithFields(log.Fields{"data": data, "error": data.Response.Error, "response": string(tmp)}). + Debugf("%-v", data.Response.Error) + socket.handleUnknown(data.Response) } } - socket.handleUnknown(response) } + }() - if !socket.listening { - log.WithFields(log.Fields{ - "socketID": socket.socketID, - "url": socket.url.String(), - }).Info("Socket shutting down") - go func() { + // launch the socket reader. + readLoopBreaker := make(chan bool) + readLoopFeed := make(chan ReadLoopData) + for { + go func() { + for { + data := ReadLoopData{ + Response: &Response{}, + } select { - case socket.listenCh <- true: - case <-time.After(10 * time.Second): + case <-readLoopBreaker: + readLoopBreaker <- true + return + default: + data.Err = socket.ReadJSON(&data.Response) + readLoopFeed <- data } - }() - break + } + }() + select { + case <-breaker: + go func() { readLoopBreaker <- true }() + breaker <- true + return nil + case readLoopChan <- <-readLoopFeed: } } - - if nil != err { - err = errs.Wrap(err, 0, "socket read failed") - } - socket.listening = false - return err } /* @@ -388,15 +376,11 @@ RemoveEventHandler is a Socketer implementation. func (socket *Socket) RemoveEventHandler( handler EventHandler, ) error { - socket.handlers.Lock() - defer socket.handlers.Unlock() handlers, err := socket.handlers.Get(handler.Name()) if nil != err { - log.WithFields(log.Fields{ - "error": err, - "socketID": socket.socketID, - }).Warn("Could not remove handler") + socket.logger.WithFields(log.Fields{"error": err}). + Warn("Could not remove handler") return errs.Wrap(err, 0, fmt.Sprintf("failed to remove event handler '%s'", handler.Name())) } @@ -404,18 +388,13 @@ func (socket *Socket) RemoveEventHandler( if hndlr == handler { handlers = append(handlers[:i], handlers[i+1:]...) socket.handlers.Set(handler.Name(), handlers) - log.WithFields(log.Fields{ - "handler": handler.Name(), - "handlerID": i, - "socketID": socket.socketID, - }).Info("Removed event handler") + socket.logger.WithFields(log.Fields{"handler": handler.Name(), "handlerID": i}). + Info("Removed event handler") return nil } } - log.WithFields(log.Fields{ - "socketID": socket.socketID, - }).Warn("handler not found") + socket.logger.Warn("handler not found") return nil } @@ -434,11 +413,10 @@ Workflow: response and the command unlocks itself. */ func (socket *Socket) SendCommand(command Commander) chan *Response { - log.WithFields(log.Fields{ - "commandID": command.ID(), - "method": command.Method(), - "socketID": socket.socketID, - }).Debug("sending command payload to socket") + log.WithFields(log.Fields{"command.ID": command.ID(), "command.Method": command.Method(), "command.Params": command.Params()}). + Debug("sending command payload to socket") + + socket.commands.Set(command) go func() { payload := &Payload{ ID: command.ID(), @@ -455,8 +433,6 @@ func (socket *Socket) SendCommand(command Commander) chan *Response { }}) return } - - socket.commands.Set(command) }() return command.Response() @@ -469,21 +445,9 @@ websocket connection. Stop is a Socketer implementation. */ func (socket *Socket) Stop() error { - if socket.listening { - socket.listening = false - select { - case <-socket.listenCh: - case <-time.After(1 * time.Second): - socket.conn.Close() - } - log.WithFields(log.Fields{ - "socketID": socket.socketID, - }).Debug("socket stopped") - } - if 0 == len(socket.listenErr) { - return nil - } - return socket.listenErr + socket.stop <- true + <-socket.stop + return socket.Disconnect() } /* diff --git a/tot/socket/socket.socketer_test.go b/tot/socket/socket.socketer_test.go index 8b7f0ab..bada95b 100644 --- a/tot/socket/socket.socketer_test.go +++ b/tot/socket/socket.socketer_test.go @@ -1,78 +1,71 @@ package socket import ( - "net/url" "reflect" "testing" "time" ) func TestNewSocket(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestNewSocket") - socket := New(socketURL) - if err := socket.Disconnect(); nil != err && "*errors.errorString" != reflect.TypeOf(err).String() { - t.Errorf("Socketer.Disconnect() must return an error or nil, %s found", reflect.TypeOf(err).String()) - } + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + + soc := New(chrome.URL) + defer soc.Stop() + + soc.Disconnect() } func TestCommandNotFound(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestCommandNotFound") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + chrome.AddData(MockData{ ID: 999, - Error: &Error{}, + Err: &Error{}, Method: "Some.methodError", - Result: []byte(`"Mock Command Result"`), + Result: "Mock Command Result", }) time.Sleep(1 * time.Second) } func TestSocketStop(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSocketStop") - mockSocket := NewMock(socketURL) - mockSocket.Listen() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + time.Sleep(1 * time.Second) - if err := mockSocket.Stop(); nil != err { - t.Errorf("Expected nil, got error: %v", err) - } + soc.Stop() } func TestSocketDisconnect(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestSocketDisconnect") - mockSocket := NewMock(socketURL) - if err := mockSocket.Disconnect(); nil != err && "*errors.errorString" != reflect.TypeOf(err).String() && "errors.Err" != reflect.TypeOf(err).String() { - t.Errorf("Socketer.Disconnect() must return an error or nil, %s found", reflect.TypeOf(err).String()) - } + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) - // Test the disconnect timeout - mockSocket = NewMock(socketURL) - mockSocket.Listen() - mockSocket.Conn().(*MockChromeWebSocket).Sleep(10 * time.Second) - start := time.Now() - if err := mockSocket.Disconnect(); nil != err && "*errors.errorString" != reflect.TypeOf(err).String() && "errors.Err" != reflect.TypeOf(err).String() { - t.Errorf("Socketer.Disconnect() must return an error or nil, %s found", reflect.TypeOf(err).String()) - } - elapsed := time.Since(start) - if elapsed < 1*time.Second { - t.Errorf("Expected disconnect timeout in 1 seconds, %s elapsed", elapsed) - } + soc.Disconnect() } func TestListenCommand(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestListenCommand") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - - command := NewCommand(mockSocket, "Some.method", nil) - resultChan := mockSocket.SendCommand(command) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + command := NewCommand(soc, "Some.method", nil) + resultChan := soc.SendCommand(command) + chrome.AddData(MockData{ ID: command.ID(), - Error: &Error{}, + Err: &Error{}, Method: "Some.method", - Result: []byte(`"Mock Command Result"`), + Result: "Mock Command Result", }) result := <-resultChan if `"Mock Command Result"` != string(result.Result) { @@ -81,18 +74,19 @@ func TestListenCommand(t *testing.T) { } func TestListenCommandError(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestListenCommandError") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() - - command := NewCommand(mockSocket, "Some.methodError", nil) - resultChan := mockSocket.SendCommand(command) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + command := NewCommand(soc, "Some.methodError", nil) + resultChan := soc.SendCommand(command) + chrome.AddData(MockData{ ID: command.ID(), - Error: &Error{}, + Err: &Error{}, Method: "Some.methodError", - Result: []byte(`"Mock Command Result"`), + Result: "Mock Command Result", }) result := <-resultChan if `"Mock Command Result"` != string(result.Result) { @@ -101,18 +95,18 @@ func TestListenCommandError(t *testing.T) { } func TestListenCommandUnknown(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestListenCommandUnknown") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() - command := NewCommand(mockSocket, "", nil) + command := NewCommand(soc, "", nil) command.SetID(0) - resultChan := mockSocket.SendCommand(command) - mockSocket.Conn().(*MockChromeWebSocket).AddMockData(&Response{ - ID: 0, - Error: nil, - Method: "", + resultChan := soc.SendCommand(command) + chrome.AddData(MockData{ + ID: 0, + Err: nil, }) result := <-resultChan if nil == result.Error { @@ -122,10 +116,11 @@ func TestListenCommandUnknown(t *testing.T) { func TestRemoveEventHandler(t *testing.T) { var err error - socketURL, _ := url.Parse("https://test:9222/TestRemoveEventHandler") - mockSocket := NewMock(socketURL) - mockSocket.Listen() - defer mockSocket.Stop() + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() handler1 := NewEventHandler( "Test.event", @@ -137,20 +132,20 @@ func TestRemoveEventHandler(t *testing.T) { ) // Remove before added - err = mockSocket.RemoveEventHandler(handler1) + err = soc.RemoveEventHandler(handler1) if nil == err { t.Errorf("Expected error, received nil") } // Remove added handler - mockSocket.AddEventHandler(handler1) - err = mockSocket.RemoveEventHandler(handler1) + soc.AddEventHandler(handler1) + err = soc.RemoveEventHandler(handler1) if nil != err { t.Errorf("Expected nil, received error: %s", err.Error()) } // Removed but never added - err = mockSocket.RemoveEventHandler(handler2) + err = soc.RemoveEventHandler(handler2) if nil != err { t.Errorf("Expected nil, received error: %s", err.Error()) } @@ -182,9 +177,13 @@ func TestRemoveEventHandler(t *testing.T) { //} func TestURL(t *testing.T) { - socketURL, _ := url.Parse("https://test:9222/TestURL") - mockSocket := NewMock(socketURL) - if "https://test:9222/TestURL" != mockSocket.URL().String() { + chrome := NewMockChrome() + chrome.ListenAndServe() + defer chrome.Close() + soc := New(chrome.URL) + defer soc.Stop() + + if chrome.URL.String() != soc.URL().String() { t.Errorf("Socketer.URL() failed to return the correct URL") } } diff --git a/tot/socket/socket.web_socketer.go b/tot/socket/socket.web_socketer.go index 74be87e..90ea29e 100644 --- a/tot/socket/socket.web_socketer.go +++ b/tot/socket/socket.web_socketer.go @@ -3,8 +3,8 @@ package socket import ( "encoding/json" "fmt" - "net/http" "net/url" + "sync" errs "github.com/bdlm/errors" "github.com/bdlm/log" @@ -23,9 +23,8 @@ func NewWebsocket(socketURL *url.URL) (WebSocketer, error) { // Chrome does not support payloads larger than 1MB: https://chromium.googlesource.com/chromium/src/+/master/net/server/http_connection.h#33 WriteBufferSize: 1 * 1024 * 1024, } - header := http.Header{"Origin": []string{}} - websocket, response, err := dialer.Dial(socketURL.String(), header) + websocket, response, err := dialer.Dial(socketURL.String(), nil) if err != nil { return nil, errs.Wrap(err, 0, fmt.Sprintf( "%s websocket connection failed", @@ -35,9 +34,9 @@ func NewWebsocket(socketURL *url.URL) (WebSocketer, error) { log.WithFields(log.Fields{ "status": response.Status, "url": socketURL.String(), - }).Info("Websocket connection to %s established: %s") + }).Info("Websocket connection established") - return &ChromeWebSocket{conn: websocket}, nil + return &ChromeWebSocket{conn: websocket, mux: &sync.Mutex{}}, nil } /* @@ -49,6 +48,7 @@ ChromeWebSocket represents a WebSocketer interface type ChromeWebSocket struct { conn *websocket.Conn mockResponses []*Response + mux *sync.Mutex } /* @@ -56,9 +56,11 @@ Close closes the current websocket connection. Close is a WebSocketer implementation. */ -func (socket *ChromeWebSocket) Close() error { - if nil != socket.conn { - return socket.conn.Close() +func (websocket *ChromeWebSocket) Close() error { + websocket.mux.Lock() + defer websocket.mux.Unlock() + if nil != websocket.conn { + return websocket.conn.Close() } return nil } @@ -74,11 +76,13 @@ reads from a stack of manually populated responses in an attempt to emulate the Chromium DevProtocol behavior. To populate the mock response stack, add a Response{} pointer with the AddMockData() method. */ -func (socket *ChromeWebSocket) ReadJSON(v interface{}) error { - if nil == socket.conn { +func (websocket *ChromeWebSocket) ReadJSON(v interface{}) error { + websocket.mux.Lock() + if nil == websocket.conn { + websocket.mux.Unlock() return errs.New(0, "not connected") } - return socket.conn.ReadJSON(&v) + return websocket.conn.ReadJSON(&v) } /* @@ -86,13 +90,15 @@ WriteJSON marshalls the provided data as JSON and writes it to the websocket. WriteJSON is a WebSocketer implementation. */ -func (socket *ChromeWebSocket) WriteJSON(v interface{}) error { - if nil == socket.conn { +func (websocket *ChromeWebSocket) WriteJSON(v interface{}) error { + websocket.mux.Lock() + defer websocket.mux.Unlock() + if nil == websocket.conn { return errs.New(0, "not connected") } tmp, _ := json.Marshal(v) if len(tmp) > 1*1024*1024 { return fmt.Errorf("payload too large. chrome supports a maximum payload size of 1MB. See https://github.com/gorilla/websocket/issues/245") } - return socket.conn.WriteJSON(v) + return websocket.conn.WriteJSON(v) } diff --git a/tot/tab.tabber.go b/tot/tab.tabber.go index 7cb708a..4a4735f 100644 --- a/tot/tab.tabber.go +++ b/tot/tab.tabber.go @@ -80,7 +80,8 @@ func (tab *Tab) Close() (interface{}, error) { if nil != err { log.WithFields(log.Fields{ "result": result, - }).Warn("%s", err) + "error": err, + }).Warnf("%v", err) return nil, errs.Wrap(err, 0, fmt.Sprintf("close/%s query failed", tab.Data().ID)) } tab.Chromium().RemoveTab(tab)