From 1b39a22386a0d5540c7f51d2164283b3d1f7e95b Mon Sep 17 00:00:00 2001 From: Ivan Krutov Date: Sun, 31 Dec 2023 11:17:29 +0300 Subject: [PATCH 1/2] Minor code style fixes --- README.md | 2 +- config_test.go | 4 +-- proxy.go | 24 ++++++++-------- proxy_test.go | 78 +++++++++++++++++++++++++------------------------- 4 files changed, 54 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index 97cbe59..077ea6e 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ $ cat /etc/grid-router/quota/test.xml ``` -***Note***: file name should correspond to user name you added to htpasswd file. For user ```test``` we added on previous steps you should create ```test.xml```. +***Note***: file name should correspond to username you added to htpasswd file. For user ```test``` we added on previous steps you should create ```test.xml```. 6) Start Ggr container: ``` diff --git a/config_test.go b/config_test.go index 9390eb3..3223594 100644 --- a/config_test.go +++ b/config_test.go @@ -245,9 +245,9 @@ func TestConfDirDoesNotExist(t *testing.T) { func TestConcurrentReload(t *testing.T) { go func() { - loadQuotaFiles("quota") + _ = loadQuotaFiles("quota") }() - loadQuotaFiles("quota") + _ = loadQuotaFiles("quota") } func TestChoosingAllHosts(t *testing.T) { diff --git a/proxy.go b/proxy.go index 1a81e04..b217cf0 100644 --- a/proxy.go +++ b/proxy.go @@ -149,7 +149,7 @@ func (c caps) capabilityJsonWireW3C(jsonWire, W3C string) string { return result } -func (c *caps) browser() string { +func (c caps) browser() string { browserName := c.capability("browserName") if browserName != "" { return browserName @@ -237,7 +237,7 @@ func session(ctx context.Context, h *Host, header http.Header, c caps) (map[stri func reply(w http.ResponseWriter, msg map[string]interface{}, status int) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) - json.NewEncoder(w).Encode(msg) + _ = json.NewEncoder(w).Encode(msg) } func serial() uint64 { @@ -402,7 +402,7 @@ loop: } func secondsSince(start time.Time) float64 { - return float64(time.Now().Sub(start).Seconds()) + return time.Now().Sub(start).Seconds() } func proxy(w http.ResponseWriter, r *http.Request) { @@ -420,7 +420,7 @@ func proxy(w http.ResponseWriter, r *http.Request) { if ok { if r.Body != nil { if body, err := io.ReadAll(r.Body); err == nil { - r.Body.Close() + _ = r.Body.Close() var msg map[string]interface{} if err := json.Unmarshal(body, &msg); err == nil { delete(msg, "sessionId") @@ -462,7 +462,7 @@ func ping(w http.ResponseWriter, _ *http.Request) { lrt := lastReloadTime.Format(time.RFC3339) confLock.RUnlock() w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(struct { + _ = json.NewEncoder(w).Encode(struct { Uptime string `json:"uptime"` LastReloadTime string `json:"lastReloadTime"` NumRequests uint64 `json:"numRequests"` @@ -479,7 +479,7 @@ func ping(w http.ResponseWriter, _ *http.Request) { func status(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode( + _ = json.NewEncoder(w).Encode( map[string]interface{}{ "value": map[string]interface{}{ "message": fmt.Sprintf("Ggr %s built at %s", gitRevision, buildStamp), @@ -500,7 +500,7 @@ func host(w http.ResponseWriter, r *http.Request) { path := r.URL.Path if len(path) < tail { w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("invalid session ID")) + _, _ = w.Write([]byte("invalid session ID")) return } sum := path[head:tail] @@ -509,12 +509,12 @@ func host(w http.ResponseWriter, r *http.Request) { confLock.RUnlock() if !ok { w.WriteHeader(http.StatusNotFound) - w.Write([]byte("unknown host")) + _, _ = w.Write([]byte("unknown host")) return } log.Printf("[%d] [-] [HOST_INFO_REQUESTED] [%s] [%s] [-] [%s] [%s] [-] [-]\n", id, user, remote, h.Name, sum) w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(Host{Name: h.Name, Port: h.Port, Count: h.Count}) + _ = json.NewEncoder(w).Encode(Host{Name: h.Name, Port: h.Port, Count: h.Count}) } func quotaInfo(w http.ResponseWriter, r *http.Request) { @@ -539,7 +539,7 @@ func quotaInfo(w http.ResponseWriter, r *http.Request) { } } } - json.NewEncoder(w).Encode(browsers.Browsers.Browsers) + _ = json.NewEncoder(w).Encode(browsers.Browsers.Browsers) } func postOnly(handler http.HandlerFunc) http.HandlerFunc { @@ -726,10 +726,10 @@ func proxyConn(id uint64, wsconn *websocket.Conn, conn net.Conn, err error, sess wsconn.PayloadType = websocket.BinaryFrame go func() { io.Copy(wsconn, conn) - wsconn.Close() + _ = wsconn.Close() log.Printf("[%d] [-] [WS_SESSION_CLOSED] [-] [-] [-] [%s] [%s] [-] [-]", id, address, sessionID) }() - io.Copy(conn, wsconn) + _, _ = io.Copy(conn, wsconn) log.Printf("[%d] [-] [WS_CLIENT_DISCONNECTED] [-] [-] [-] [%s] [%s] [-] [-]", id, address, sessionID) } diff --git a/proxy_test.go b/proxy_test.go index 7d563ff..ea9693f 100644 --- a/proxy_test.go +++ b/proxy_test.go @@ -50,7 +50,7 @@ func (m Message) Match(i interface{}) bool { rsp := i.(*http.Response) var reply map[string]interface{} err := json.NewDecoder(rsp.Body).Decode(&reply) - rsp.Body.Close() + _ = rsp.Body.Close() if err != nil { return false } @@ -189,7 +189,7 @@ func testGetHost(t *testing.T, sessionID string, statusCode int) *Host { return nil } var host Host - json.NewDecoder(rsp.Body).Decode(&host) + _ = json.NewDecoder(rsp.Body).Decode(&host) return &host } @@ -278,7 +278,7 @@ func testTCPServer(data string) net.Listener { continue } defer conn.Close() - io.WriteString(conn, data) + _, _ = io.WriteString(conn, data) return } }() @@ -293,7 +293,7 @@ func TestProxyScreenWebSocketsProtocol(t *testing.T) { const testData = "ws-data" mux := http.NewServeMux() mux.Handle("/vnc/123", websocket.Handler(func(wsconn *websocket.Conn) { - wsconn.Write([]byte(testData)) + _, _ = wsconn.Write([]byte(testData)) })) wsServer := httptest.NewServer(mux) @@ -322,7 +322,7 @@ func TestProxyDevtools(t *testing.T) { const testData = "devtools-data" mux := http.NewServeMux() mux.Handle("/devtools/123", websocket.Handler(func(wsconn *websocket.Conn) { - wsconn.Write([]byte(testData)) + _, _ = wsconn.Write([]byte(testData)) })) wsServer := httptest.NewServer(mux) @@ -660,7 +660,7 @@ func TestSessionWrongHash(t *testing.T) { func TestStartSession(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) browsersProvider := func(node Host) Browsers { @@ -737,7 +737,7 @@ func testStartSession(t *testing.T, mux *http.ServeMux, browsersProvider func(Ho func TestStartSessionWithJsonSpecChars(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) browsersProvider := func(node Host) Browsers { @@ -759,7 +759,7 @@ func TestStartSessionWithOverriddenBasicAuth(t *testing.T) { mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { username, password, ok := r.BasicAuth() if ok && username == "test" && password == "test-password" { - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) } else { w.WriteHeader(http.StatusUnauthorized) } @@ -785,7 +785,7 @@ func TestStartSessionWithPrefixVersion(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) - r.Body.Close() + _ = r.Body.Close() var sess map[string]map[string]string err := json.Unmarshal(body, &sess) AssertThat(t, err, Is{nil}) @@ -811,7 +811,7 @@ func TestStartSessionWithPrefixVersion(t *testing.T) { }}}} updateQuota(user, browsers) - createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1"}}`) + _, _ = createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1"}}`) } func TestCreateSessionW3CBrowserNotSet0(t *testing.T) { @@ -839,8 +839,8 @@ func TestStartSessionWithDefaultVersion(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) - r.Body.Close() - w.Write([]byte(`{"sessionId":"123"}`)) + _ = r.Body.Close() + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) var sess map[string]map[string]string err := json.Unmarshal(body, &sess) AssertThat(t, err, Is{nil}) @@ -871,17 +871,17 @@ func TestStartSessionWithDefaultVersion(t *testing.T) { }}}} updateQuota(user, browsers) - createSession(`{"desiredCapabilities":{"browserName":"browser"}}`) + _, _ = createSession(`{"desiredCapabilities":{"browserName":"browser"}}`) } func TestStartSessionWithDefaultVersionW3C(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) - r.Body.Close() + _ = r.Body.Close() var sess map[string]map[string]map[string]interface{} err := json.Unmarshal(body, &sess) - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) AssertThat(t, err, Is{nil}) AssertThat(t, sess["capabilities"]["alwaysMatch"]["browserVersion"], EqualTo{"2.0"}) @@ -916,7 +916,7 @@ func TestStartSessionWithDefaultVersionW3C(t *testing.T) { }}}} updateQuota(user, browsers) - createSession(`{"capabilities":{"alwaysMatch":{"browserName":"browser", "selenoid:options": {"labels": {"some-key": "some-value"}}}}}`) + _, _ = createSession(`{"capabilities":{"alwaysMatch":{"browserName":"browser", "selenoid:options": {"labels": {"some-key": "some-value"}}}}}`) } func TestClientClosedConnection(t *testing.T) { @@ -1043,7 +1043,7 @@ func TestStartSessionBrowserFail(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) - w.Write([]byte(`{"value": {"message" : "Browser startup failure..."}}`)) + _, _ = w.Write([]byte(`{"value": {"message" : "Browser startup failure..."}}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1074,7 +1074,7 @@ func TestStartSessionBrowserFailUnknownError(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) - w.Write([]byte(`{}`)) + _, _ = w.Write([]byte(`{}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1105,7 +1105,7 @@ func TestStartSessionBrowserFailWrongValue(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) - w.Write([]byte(`{"value": 1}`)) + _, _ = w.Write([]byte(`{"value": 1}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1136,7 +1136,7 @@ func TestStartSessionBrowserFailWrongMsg(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) - w.Write([]byte(`{"value": {"message" : true}}`)) + _, _ = w.Write([]byte(`{"value": {"message" : true}}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1167,7 +1167,7 @@ func TestStartSessionFailJSONWireProtocol(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { //w.WriteHeader(http.StatusBadGateway) - w.Write([]byte(`{}`)) + _, _ = w.Write([]byte(`{}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1197,7 +1197,7 @@ func TestStartSessionFailJSONWireProtocol(t *testing.T) { func TestStartSessionFailJSONWireProtocolNoSessionID(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{}}`)) + _, _ = w.Write([]byte(`{"value":{}}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1227,7 +1227,7 @@ func TestStartSessionFailJSONWireProtocolNoSessionID(t *testing.T) { func TestStartSessionFailJSONWireProtocolWrongType(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{"sessionId":123}}`)) + _, _ = w.Write([]byte(`{"value":{"sessionId":123}}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1257,7 +1257,7 @@ func TestStartSessionFailJSONWireProtocolWrongType(t *testing.T) { func TestStartSessionJSONWireProtocol(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{"sessionId":"123"}}`)) + _, _ = w.Write([]byte(`{"value":{"sessionId":"123"}}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1289,7 +1289,7 @@ func TestStartSessionJSONWireProtocol(t *testing.T) { func TestPanicRouteProtocolError(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":[]}`)) + _, _ = w.Write([]byte(`{"value":[]}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1350,7 +1350,7 @@ func TestDeleteSession(t *testing.T) { func TestProxyRequest(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session/", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{"message":"response"}}`)) + _, _ = w.Write([]byte(`{"value":{"message":"response"}}`)) }) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1383,7 +1383,7 @@ func TestProxyJsonRequest(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session/", func(w http.ResponseWriter, r *http.Request) { var msg map[string]interface{} - json.NewDecoder(r.Body).Decode(&msg) + _ = json.NewDecoder(r.Body).Decode(&msg) AssertThat(t, msg["sessionId"], Is{nil}) }) selenium := httptest.NewServer(mux) @@ -1409,14 +1409,14 @@ func TestProxyJsonRequest(t *testing.T) { updateQuota(user, browsers) }() - doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte(`{"sessionId":"123"}`))) + _, _ = doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte(`{"sessionId":"123"}`))) } func TestProxyPlainRequest(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session/", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) - r.Body.Close() + _ = r.Body.Close() AssertThat(t, string(body), EqualTo{"request"}) }) selenium := httptest.NewServer(mux) @@ -1483,7 +1483,7 @@ func TestRequest(t *testing.T) { })) r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) - http.DefaultClient.Do(r) + _, _ = http.DefaultClient.Do(r) } func TestRequestAuth(t *testing.T) { @@ -1495,7 +1495,7 @@ func TestRequestAuth(t *testing.T) { r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) r.SetBasicAuth("user", "password") - http.DefaultClient.Do(r) + _, _ = http.DefaultClient.Do(r) } func TestRequestForwarded(t *testing.T) { @@ -1507,7 +1507,7 @@ func TestRequestForwarded(t *testing.T) { r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) r.Header.Set("X-Forwarded-For", "proxy") - http.DefaultClient.Do(r) + _, _ = http.DefaultClient.Do(r) } func TestRequestAuthForwarded(t *testing.T) { @@ -1520,7 +1520,7 @@ func TestRequestAuthForwarded(t *testing.T) { r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) r.Header.Set("X-Forwarded-For", "proxy") r.SetBasicAuth("user", "password") - http.DefaultClient.Do(r) + _, _ = http.DefaultClient.Do(r) } func TestStartSessionProxyHeaders(t *testing.T) { @@ -1528,7 +1528,7 @@ func TestStartSessionProxyHeaders(t *testing.T) { mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { u, _, _ := r.BasicAuth() AssertThat(t, u, EqualTo{user}) - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1562,7 +1562,7 @@ func TestStartSessionGuest(t *testing.T) { dummyMux := http.NewServeMux() dummyMux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{"sessionId":"123"}}`)) + _, _ = w.Write([]byte(`{"value":{"sessionId":"123"}}`)) })) selenium := httptest.NewServer(dummyMux) defer selenium.Close() @@ -1595,7 +1595,7 @@ func TestStartSessionGuestFailNoQuota(t *testing.T) { dummyMux := http.NewServeMux() dummyMux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"value":{"sessionId":"123"}}`)) + _, _ = w.Write([]byte(`{"value":{"sessionId":"123"}}`)) })) selenium := httptest.NewServer(dummyMux) defer selenium.Close() @@ -1615,7 +1615,7 @@ func TestStartSessionGuestAndCorrectBasicAuth(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) browsersProvider := func(node Host) Browsers { @@ -1637,7 +1637,7 @@ func TestStartSessionGuestModeAndWrongBasicAuth(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"sessionId":"123"}`)) + _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) selenium := httptest.NewServer(mux) @@ -1716,7 +1716,7 @@ func TestPanicGuestQuotaMissingUsersFileAuthPresent(t *testing.T) { func TestPlatformCapability(t *testing.T) { var caps caps testCaps := `{"desiredCapabilities": {"platformName": "WINDOWS"}, "capabilities": {"platformName": "windows"}}` - json.Unmarshal([]byte(testCaps), &caps) + _ = json.Unmarshal([]byte(testCaps), &caps) AssertThat(t, caps.platform(), EqualTo{"WINDOWS"}) } From 73c4590ed6533a2f2e89267cbde8edcb1642bbdb Mon Sep 17 00:00:00 2001 From: Ivan Krutov Date: Sun, 31 Dec 2023 12:22:35 +0300 Subject: [PATCH 2/2] Switched to github.com/stretchr/testify in tests --- config_test.go | 110 ++++++------ go.mod | 5 +- go.sum | 17 +- proxy_test.go | 445 ++++++++++++++++++++++++++----------------------- 4 files changed, 303 insertions(+), 274 deletions(-) diff --git a/config_test.go b/config_test.go index 3223594..44b74e0 100644 --- a/config_test.go +++ b/config_test.go @@ -2,10 +2,10 @@ package main import ( "fmt" + assert "github.com/stretchr/testify/require" "os" "testing" - . "github.com/aandryashin/matchers" . "github.com/aerokube/ggr/config" ) @@ -15,32 +15,32 @@ func init() { func TestEmptyListOfHosts(t *testing.T) { host, index := choose(Hosts{}) - AssertThat(t, host, Is{(*Host)(nil)}) - AssertThat(t, index, EqualTo{-1}) + assert.Nil(t, host) + assert.Equal(t, index, -1) } func TestNothingToChoose(t *testing.T) { host, index := choose(Hosts{Host{Count: 0}, Host{Count: 0}}) - AssertThat(t, host, Is{(*Host)(nil)}) - AssertThat(t, index, EqualTo{-1}) + assert.Nil(t, host) + assert.Equal(t, index, -1) } func TestChooseFirst(t *testing.T) { host, index := choose(Hosts{Host{Name: "first", Count: 1}, Host{Name: "mid", Count: 0}, Host{Name: "last", Count: 0}}) - AssertThat(t, host.Name, EqualTo{"first"}) - AssertThat(t, index, EqualTo{0}) + assert.Equal(t, host.Name, "first") + assert.Equal(t, index, 0) } func TestChooseMid(t *testing.T) { host, index := choose(Hosts{Host{Name: "first", Count: 0}, Host{Name: "mid", Count: 1}, Host{Name: "last", Count: 0}}) - AssertThat(t, host.Name, EqualTo{"mid"}) - AssertThat(t, index, EqualTo{1}) + assert.Equal(t, host.Name, "mid") + assert.Equal(t, index, 1) } func TestChooseLast(t *testing.T) { host, index := choose(Hosts{Host{Name: "first", Count: 0}, Host{Name: "mid", Count: 0}, Host{Name: "last", Count: 1}}) - AssertThat(t, host.Name, EqualTo{"last"}) - AssertThat(t, index, EqualTo{2}) + assert.Equal(t, host.Name, "last") + assert.Equal(t, index, 2) } var ( @@ -92,84 +92,84 @@ var ( func TestFindDefaultVersion(t *testing.T) { hosts, version, _ := browsersWithMultipleVersions.find("browser", "", "", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0") } func TestFindVersion(t *testing.T) { hosts, version, _ := browsersWithMultipleVersions.find("browser", "1.0", "LINUX", newSet(), newSet()) - AssertThat(t, version, EqualTo{"1.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-1.0"}) + assert.Equal(t, version, "1.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-1.0") } func TestFindVersionByPrefix(t *testing.T) { hosts, version, _ := browsersWithMultipleVersions.find("browser", "1", "", newSet(), newSet()) - AssertThat(t, version, EqualTo{"1.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-1.0"}) + assert.Equal(t, version, "1.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-1.0") } func TestVersionNotFound(t *testing.T) { hosts, version, _ := browsersWithMultipleVersions.find("browser", "missing", "", newSet(), newSet()) - AssertThat(t, version, EqualTo{"missing"}) - AssertThat(t, len(hosts), EqualTo{0}) + assert.Equal(t, version, "missing") + assert.Empty(t, hosts) } func TestFindWithExcludedRegions(t *testing.T) { hosts, version, _ := browsersWithMultipleRegions.find("browser", "1.0", "", newSet(), newSet("f")) - AssertThat(t, version, EqualTo{"1.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-e-1.0"}) + assert.Equal(t, version, "1.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-e-1.0") } func TestFindWithExcludedRegionsExhausted(t *testing.T) { hosts, _, excludedRegions := browsersWithMultipleRegions.find("browser", "1.0", "", newSet(), newSet("e", "f")) - AssertThat(t, len(hosts), EqualTo{2}) - AssertThat(t, excludedRegions.size(), EqualTo{0}) + assert.Len(t, hosts, 2) + assert.Equal(t, excludedRegions.size(), 0) } func TestFindWithExcludedHosts(t *testing.T) { hosts, version, _ := browsersWithMultipleRegions.find("browser", "1.0", "", newSet("browser-e-1.0:4444"), newSet()) - AssertThat(t, version, EqualTo{"1.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-f-1.0"}) + assert.Equal(t, version, "1.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-f-1.0") } func TestFindWithDefaultPlatform(t *testing.T) { hosts, version, _ := browsersWithMultiplePlatforms.find("browser", "2.0", "", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0-linux"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0-linux") } func TestFindWithAnyPlatform(t *testing.T) { hosts, version, _ := browsersWithMultiplePlatforms.find("browser", "2.0", "ANY", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0-linux"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0-linux") } func TestFindWithPlatform(t *testing.T) { hosts, version, _ := browsersWithMultiplePlatforms.find("browser", "2.0", "LINUX", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0-linux"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0-linux") } func TestFindWithPlatformLowercase(t *testing.T) { hosts, version, _ := browsersWithMultiplePlatforms.find("browser", "2.0", "windows", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0-windows"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0-windows") } func TestFindWithPlatformPrefix(t *testing.T) { hosts, version, _ := browsersWithMultiplePlatforms.find("browser", "2.0", "WIN", newSet(), newSet()) - AssertThat(t, version, EqualTo{"2.0"}) - AssertThat(t, len(hosts), EqualTo{1}) - AssertThat(t, hosts[0].Name, EqualTo{"browser-2.0-windows"}) + assert.Equal(t, version, "2.0") + assert.Len(t, hosts, 1) + assert.Equal(t, hosts[0].Name, "browser-2.0-windows") } func TestReadNotExistingConfig(t *testing.T) { @@ -184,8 +184,8 @@ func TestReadNotExistingConfig(t *testing.T) { var browsers Browsers err = readConfig(tmp.Name(), &browsers) - AssertThat(t, err, Is{Not{nil}}) - AssertThat(t, err.Error(), EqualTo{fmt.Sprintf("error reading configuration file %s: open %s: no such file or directory", tmp.Name(), tmp.Name())}) + assert.Error(t, err) + assert.Equal(t, err.Error(), fmt.Sprintf("error reading configuration file %s: open %s: no such file or directory", tmp.Name(), tmp.Name())) } func TestParseInvalidConfig(t *testing.T) { @@ -205,8 +205,8 @@ func TestParseInvalidConfig(t *testing.T) { var browsers Browsers err = readConfig(tmp.Name(), &browsers) - AssertThat(t, err, Is{Not{nil}}) - AssertThat(t, err.Error(), EqualTo{fmt.Sprintf("error parsing configuration file %s: EOF", tmp.Name())}) + assert.Error(t, err) + assert.Equal(t, err.Error(), fmt.Sprintf("error parsing configuration file %s: EOF", tmp.Name())) } func TestParseConfig(t *testing.T) { @@ -234,13 +234,13 @@ func testParseConfig(t *testing.T, config string) { var browsers Browsers err = readConfig(tmp.Name(), &browsers) - AssertThat(t, err, Is{nil}) - AssertThat(t, browsers.Browsers[0].Name, EqualTo{"browser"}) + assert.NoError(t, err) + assert.Equal(t, browsers.Browsers[0].Name, "browser") } func TestConfDirDoesNotExist(t *testing.T) { err := loadQuotaFiles("missing-dir") - AssertThat(t, err, Is{Not{nil}}) + assert.Error(t, err) } func TestConcurrentReload(t *testing.T) { @@ -258,7 +258,7 @@ func TestChoosingAllHosts(t *testing.T) { host, _ := choose(hosts) chosenHosts[host.Name]++ } - AssertThat(t, chosenHosts["first"] > 0, Is{true}) - AssertThat(t, chosenHosts["mid"] > 0, Is{true}) - AssertThat(t, chosenHosts["last"] > 0, Is{true}) + assert.True(t, chosenHosts["first"] > 0) + assert.True(t, chosenHosts["mid"] > 0) + assert.True(t, chosenHosts["last"] > 0) } diff --git a/go.mod b/go.mod index 377a473..69d26c9 100644 --- a/go.mod +++ b/go.mod @@ -3,14 +3,17 @@ module github.com/aerokube/ggr go 1.21 require ( - github.com/aandryashin/matchers v0.0.0-20161126170413-435295ea180e github.com/aandryashin/reloader v0.0.0-20161127125235-da4f1b43ce40 github.com/abbot/go-http-auth v0.4.1-0.20220112235402-e1cee1c72f2f + github.com/stretchr/testify v1.8.4 golang.org/x/net v0.19.0 ) require ( + github.com/davecgh/go-spew v1.1.1 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/crypto v0.17.0 // indirect golang.org/x/sys v0.15.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index adfe306..43c32cf 100644 --- a/go.sum +++ b/go.sum @@ -1,26 +1,29 @@ -github.com/aandryashin/matchers v0.0.0-20161126170413-435295ea180e h1:ogUKYFNcdYUIBSLibE4+EjbTJazoHr5JsWWx21Lpn8c= -github.com/aandryashin/matchers v0.0.0-20161126170413-435295ea180e/go.mod h1:cbmYNkm9xeQlNoWEPtOUcvNok2gSD7ErMnYkRW+eHi8= github.com/aandryashin/reloader v0.0.0-20161127125235-da4f1b43ce40 h1:zSKVi4h3Kv0HvNGjWPOsOEJIxtvd3PRMlVA/fcCB45g= github.com/aandryashin/reloader v0.0.0-20161127125235-da4f1b43ce40/go.mod h1:gvg2/m9OQ4ZwK4Qk/mnfgokCb4qDN4BGyle+QGw4VOc= github.com/abbot/go-http-auth v0.4.1-0.20220112235402-e1cee1c72f2f h1:R2ZVGCZzU95oXFJxncosHS9LsX8N4/MYUdGGWOb2cFk= github.com/abbot/go-http-auth v0.4.1-0.20220112235402-e1cee1c72f2f/go.mod h1:l2P3JyHa+fjy5Bxol6y1u2o4DV/mv3QMBdBu2cNR53w= -github.com/fsnotify/fsnotify v1.5.4 h1:jRbGcIw6P2Meqdwuo0H1p6JVLbL5DHKAKlYndzMwVZI= -github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.17.0 h1:r8bRNjWL3GshPW3gkd+RpvzWrZAwPS49OmTGZ/uhM4k= golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= -golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/proxy_test.go b/proxy_test.go index ea9693f..f5e6d75 100644 --- a/proxy_test.go +++ b/proxy_test.go @@ -18,10 +18,9 @@ import ( "strings" - . "github.com/aandryashin/matchers" - . "github.com/aandryashin/matchers/httpresp" "github.com/abbot/go-http-auth" . "github.com/aerokube/ggr/config" + assert "github.com/stretchr/testify/require" "golang.org/x/net/websocket" "os" "path/filepath" @@ -42,31 +41,23 @@ const ( password = "test" ) -type Message struct { - B string -} - -func (m Message) Match(i interface{}) bool { +func message(i interface{}) string { rsp := i.(*http.Response) var reply map[string]interface{} err := json.NewDecoder(rsp.Body).Decode(&reply) _ = rsp.Body.Close() if err != nil { - return false + return "" } val, ok := reply["value"].(map[string]interface{}) if !ok { - return false + return "" } msg, ok := val["message"].(string) if !ok { - return false + return "" } - return EqualTo{m.B}.Match(msg) -} - -func (m Message) String() string { - return fmt.Sprintf("json error message %v", m.B) + return msg } func hostport(u string) string { @@ -94,68 +85,69 @@ func gridrouter(p string) string { func TestPing(t *testing.T) { rsp, err := http.Get(gridrouter("/ping")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) - AssertThat(t, rsp.Body, Is{Not{nil}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NotNil(t, rsp.Body) var data map[string]interface{} bt, readErr := io.ReadAll(rsp.Body) - AssertThat(t, readErr, Is{nil}) + assert.NoError(t, readErr) jsonErr := json.Unmarshal(bt, &data) - AssertThat(t, jsonErr, Is{nil}) + assert.NoError(t, jsonErr) _, hasUptime := data["uptime"] - AssertThat(t, hasUptime, Is{true}) + assert.True(t, hasUptime) _, hasLastReloadTime := data["lastReloadTime"] - AssertThat(t, hasLastReloadTime, Is{true}) + assert.True(t, hasLastReloadTime) _, hasNumRequests := data["numRequests"] - AssertThat(t, hasNumRequests, Is{true}) + assert.True(t, hasNumRequests) _, hasNumSessions := data["numSessions"] - AssertThat(t, hasNumSessions, Is{true}) + assert.True(t, hasNumSessions) version, hasVersion := data["version"] - AssertThat(t, hasVersion, Is{true}) - AssertThat(t, version, EqualTo{"test-revision"}) + assert.True(t, hasVersion) + assert.Equal(t, version, "test-revision") } func TestStatus(t *testing.T) { rsp, err := http.Get(gridrouter("/wd/hub/status")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) - AssertThat(t, rsp.Body, Is{Not{nil}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NotNil(t, rsp.Body) var data map[string]interface{} bt, readErr := io.ReadAll(rsp.Body) - AssertThat(t, readErr, Is{nil}) + assert.NoError(t, readErr) jsonErr := json.Unmarshal(bt, &data) - AssertThat(t, jsonErr, Is{nil}) + assert.NoError(t, jsonErr) value, hasValue := data["value"] - AssertThat(t, hasValue, Is{true}) + assert.True(t, hasValue) valueMap := value.(map[string]interface{}) ready, hasReady := valueMap["ready"] - AssertThat(t, hasReady, Is{true}) - AssertThat(t, ready, Is{true}) + assert.True(t, hasReady) + assert.Equal(t, ready, true) _, hasMessage := valueMap["message"] - AssertThat(t, hasMessage, Is{true}) + assert.True(t, hasMessage) } func TestErr(t *testing.T) { rsp, err := http.Get(gridrouter("/err")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusNotFound}, Message{"route not found"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) + assert.Equal(t, message(rsp), "route not found") } func TestGetHostUnauthorized(t *testing.T) { rsp, err := http.Get(gridrouter("/host/some-id")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestGetExistingHost(t *testing.T) { correctHost := Host{Name: "example.com", Port: 4444, Count: 1} host := testGetHost(t, correctHost.Sum()+"123", http.StatusOK) - AssertThat(t, host, Not{nil}) - AssertThat(t, *host, EqualTo{correctHost}) + assert.NotNil(t, host) + assert.Equal(t, *host, correctHost) } func TestGetMissingHost(t *testing.T) { @@ -183,8 +175,8 @@ func testGetHost(t *testing.T, sessionID string, statusCode int) *Host { updateQuota(user, browsers) rsp, err := doBasicHTTPRequest(http.MethodPost, gridrouter(fmt.Sprintf("/host/%s", sessionID)), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{statusCode}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, statusCode) if statusCode != http.StatusOK { return nil } @@ -195,8 +187,8 @@ func testGetHost(t *testing.T, sessionID string, statusCode int) *Host { func TestGetQuotaInfoUnauthorized(t *testing.T) { rsp, err := http.Get(gridrouter("/quota")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestGetQuotaInfo(t *testing.T) { @@ -213,12 +205,12 @@ func TestGetQuotaInfo(t *testing.T) { updateQuota(user, browsers) rsp, err := doBasicHTTPRequest(http.MethodPost, gridrouter("/quota"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) var fetchedBrowsers []Browser err = json.NewDecoder(rsp.Body).Decode(&fetchedBrowsers) - AssertThat(t, err, Is{nil}) + assert.NoError(t, err) browsersWithoutCredentials := []Browser{ {Name: "browser", DefaultVersion: "1.0", Versions: []Version{ @@ -228,7 +220,7 @@ func TestGetQuotaInfo(t *testing.T) { }}, }}, }}} - AssertThat(t, fetchedBrowsers, EqualTo{browsersWithoutCredentials}) + assert.Equal(t, fetchedBrowsers, browsersWithoutCredentials) } func TestProxyScreenVNCProtocol(t *testing.T) { @@ -261,12 +253,12 @@ func testDataReceived(host Host, api string, correctData string, t *testing.T) { origin := "http://localhost/" u := fmt.Sprintf("ws://%s/%s/%s", srv.Listener.Addr(), api, sessionID) ws, err := websocket.Dial(u, "", origin) - AssertThat(t, err, Is{nil}) + assert.NoError(t, err) var data = make([]byte, len(correctData)) _, err = ws.Read(data) - AssertThat(t, err, Is{nil}) - AssertThat(t, strings.TrimSpace(string(data)), EqualTo{correctData}) + assert.NoError(t, err) + assert.Equal(t, strings.TrimSpace(string(data)), correctData) } func testTCPServer(data string) net.Listener { @@ -277,8 +269,8 @@ func testTCPServer(data string) net.Listener { if err != nil { continue } - defer conn.Close() _, _ = io.WriteString(conn, data) + _ = conn.Close() return } }() @@ -348,8 +340,8 @@ func TestProxyDevtools(t *testing.T) { func TestProxyVideoFileWithoutAuth(t *testing.T) { rsp, err := http.Get(gridrouter("/video/123")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestProxyVideoFileIncorrectRootToken(t *testing.T) { @@ -357,8 +349,8 @@ func TestProxyVideoFileIncorrectRootToken(t *testing.T) { req.Header.Add("X-Ggr-Root-Token", "wrong-token") rsp, err := http.DefaultClient.Do(req) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestProxyVideoFile(t *testing.T) { @@ -370,8 +362,8 @@ func TestProxyVideoFile(t *testing.T) { defer fileServer.Close() rsp, err := doBasicHTTPRequest(http.MethodGet, gridrouter(fmt.Sprintf("/video/%s", sessionID)), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) rootToken = "correct-token" defer func() { @@ -380,16 +372,16 @@ func TestProxyVideoFile(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, gridrouter(fmt.Sprintf("/video/%s", sessionID)), nil) req.Header.Add("X-Ggr-Root-Token", "correct-token") rsp, err = http.DefaultClient.Do(req) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/video/missing-file"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/video/f7fd94f75c79c36e547c091632da440f_missing-file"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) } func TestProxyVideoFileBadGateway(t *testing.T) { @@ -408,9 +400,9 @@ func TestProxyVideoFileBadGateway(t *testing.T) { }}}} updateQuota(user, browsers) - resp, err := doBasicHTTPRequest(http.MethodPost, gridrouter("/video/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) - AssertThat(t, err, Is{nil}) - AssertThat(t, resp, Code{http.StatusBadGateway}) + rsp, err := doBasicHTTPRequest(http.MethodPost, gridrouter("/video/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadGateway) } func prepareMockFileServer(path string) (*httptest.Server, string) { @@ -442,8 +434,8 @@ func prepareMockFileServer(path string) (*httptest.Server, string) { func TestProxyLogsWithoutAuth(t *testing.T) { rsp, err := http.Get(gridrouter("/logs/123")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestProxyLogs(t *testing.T) { @@ -455,23 +447,23 @@ func TestProxyLogs(t *testing.T) { defer fileServer.Close() rsp, err := doBasicHTTPRequest(http.MethodGet, gridrouter(fmt.Sprintf("/logs/%s", sessionID)), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/logs/missing-session-id"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/logs/f7fd94f75c79c36e547c091632da440f_missing-file"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) } func TestProxyDownloadWithoutAuth(t *testing.T) { rsp, err := http.Get(gridrouter("/download/123")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestProxyDownload(t *testing.T) { @@ -483,23 +475,23 @@ func TestProxyDownload(t *testing.T) { defer fileServer.Close() rsp, err := doBasicHTTPRequest(http.MethodGet, gridrouter(fmt.Sprintf("/download/%s/somefile.txt", sessionID)), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/download/missing-file"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/download/f7fd94f75c79c36e547c091632da440f_missing-file"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) } func TestProxyClipboardWithoutAuth(t *testing.T) { rsp, err := http.Get(gridrouter("/clipboard/123")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestProxyClipboard(t *testing.T) { @@ -511,16 +503,16 @@ func TestProxyClipboard(t *testing.T) { defer fileServer.Close() rsp, err := doBasicHTTPRequest(http.MethodGet, gridrouter(fmt.Sprintf("/clipboard/%s", sessionID)), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/clipboard/missing-session"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) rsp, err = doBasicHTTPRequest(http.MethodGet, gridrouter("/clipboard/f7fd94f75c79c36e547c091632da440f_missing-session"), nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusNotFound}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) } func TestCreateSessionGet(t *testing.T) { @@ -529,64 +521,72 @@ func TestCreateSessionGet(t *testing.T) { client := &http.Client{} rsp, err := client.Do(req) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusMethodNotAllowed}, Message{"method not allowed"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusMethodNotAllowed) + assert.Equal(t, message(rsp), "method not allowed") } func TestUnauthorized(t *testing.T) { rsp, err := http.Post(gridrouter("/wd/hub/session"), "", bytes.NewReader([]byte(`{"desiredCapabilities":{}}`))) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func TestCreateSessionEmptyBody(t *testing.T) { rsp, err := createSessionFromReader(nil) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"bad json format: EOF"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "bad json format: EOF") } func TestCreateSessionBadJson(t *testing.T) { rsp, err := createSession("") - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"bad json format: EOF"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "bad json format: EOF") } func TestCreateSessionCapsNotSet(t *testing.T) { rsp, err := createSession("{}") - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestCreateSessionBrowserNotSet(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestCreateSessionBadBrowserName(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":false}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestCreateSessionUnsupportedBrowser(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"mosaic"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusNotFound}, Message{"unsupported browser: mosaic"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) + assert.Equal(t, message(rsp), "unsupported browser: mosaic") } func TestCreateSessionUnsupportedBrowserVersion(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"mosaic", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusNotFound}, Message{"unsupported browser: mosaic-1.0"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) + assert.Equal(t, message(rsp), "unsupported browser: mosaic-1.0") } func createSession(capabilities string) (*http.Response, error) { @@ -620,8 +620,10 @@ func TestCreateSessionNoHosts(t *testing.T) { updateQuota(user, browsers) rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestCreateSessionHostDown(t *testing.T) { @@ -639,22 +641,25 @@ func TestCreateSessionHostDown(t *testing.T) { updateQuota(user, browsers) rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestSessionEmptyHash(t *testing.T) { rsp, err := http.Get(gridrouter("/wd/hub/session/")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusNotFound}, Message{"route not found"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) + assert.Equal(t, message(rsp), "route not found") } func TestSessionWrongHash(t *testing.T) { rsp, err := http.Get(gridrouter("/wd/hub/session/012345678901234567890123456789012")) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusNotFound}, Message{"route not found"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusNotFound) + assert.Equal(t, message(rsp), "route not found") } func TestStartSession(t *testing.T) { @@ -724,10 +729,11 @@ func testStartSessionCustomCaps(t *testing.T, mux *http.ServeMux, browsersProvid rsp, err := createSession(capsJSON) - AssertThat(t, err, Is{nil}) + assert.NoError(t, err) var sess map[string]interface{} - AssertThat(t, rsp, AllOf{Code{http.StatusOK}, IsJson{&sess}}) - AssertThat(t, sess["sessionId"], EqualTo{fmt.Sprintf("%s123", node.Sum())}) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NoError(t, json.NewDecoder(rsp.Body).Decode(&sess)) + assert.Equal(t, sess["sessionId"], fmt.Sprintf("%s123", node.Sum())) } func testStartSession(t *testing.T, mux *http.ServeMux, browsersProvider func(Host) Browsers, browserName string, version string) { @@ -788,8 +794,8 @@ func TestStartSessionWithPrefixVersion(t *testing.T) { _ = r.Body.Close() var sess map[string]map[string]string err := json.Unmarshal(body, &sess) - AssertThat(t, err, Is{nil}) - AssertThat(t, sess["desiredCapabilities"]["version"], EqualTo{"1.0"}) + assert.NoError(t, err) + assert.Equal(t, sess["desiredCapabilities"]["version"], "1.0") })) selenium := httptest.NewServer(mux) @@ -817,22 +823,25 @@ func TestStartSessionWithPrefixVersion(t *testing.T) { func TestCreateSessionW3CBrowserNotSet0(t *testing.T) { rsp, err := createSession(`{"capabilities":{}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestCreateSessionW3CBrowserNotSet1(t *testing.T) { rsp, err := createSession(`{"capabilities":{"alwaysMatch":{}}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestCreateSessionW3CBrowserNotSet2(t *testing.T) { rsp, err := createSession(`{"capabilities":{"alwaysMatch":{"browserName":false}}}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadRequest}, Message{"browser not set"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadRequest) + assert.Equal(t, message(rsp), "browser not set") } func TestStartSessionWithDefaultVersion(t *testing.T) { @@ -843,8 +852,8 @@ func TestStartSessionWithDefaultVersion(t *testing.T) { _, _ = w.Write([]byte(`{"sessionId":"123"}`)) var sess map[string]map[string]string err := json.Unmarshal(body, &sess) - AssertThat(t, err, Is{nil}) - AssertThat(t, sess["desiredCapabilities"]["version"], EqualTo{"2.0"}) + assert.NoError(t, err) + assert.Equal(t, sess["desiredCapabilities"]["version"], "2.0") })) selenium := httptest.NewServer(mux) @@ -882,15 +891,15 @@ func TestStartSessionWithDefaultVersionW3C(t *testing.T) { var sess map[string]map[string]map[string]interface{} err := json.Unmarshal(body, &sess) _, _ = w.Write([]byte(`{"sessionId":"123"}`)) - AssertThat(t, err, Is{nil}) - AssertThat(t, sess["capabilities"]["alwaysMatch"]["browserVersion"], EqualTo{"2.0"}) + assert.NoError(t, err) + assert.Equal(t, sess["capabilities"]["alwaysMatch"]["browserVersion"], "2.0") so, ok := sess["capabilities"]["alwaysMatch"]["selenoid:options"] - AssertThat(t, ok, Is{true}) + assert.True(t, ok) selenoidOptions, ok := so.(map[string]interface{}) - AssertThat(t, ok, Is{true}) + assert.True(t, ok) _, ok = selenoidOptions["browserVersion"] - AssertThat(t, ok, Is{false}) + assert.False(t, ok) })) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -988,21 +997,22 @@ func TestStartSessionFail(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestStartSessionFailMultiRegion(t *testing.T) { node := []Host{ - Host{Name: "localhost", Port: 9991, Count: 1}, - Host{Name: "localhost", Port: 9992, Count: 1}, - Host{Name: "localhost", Port: 9993, Count: 1}, - Host{Name: "localhost", Port: 9994, Count: 1}, - Host{Name: "localhost", Port: 9995, Count: 1}, - Host{Name: "localhost", Port: 9996, Count: 1}, - Host{Name: "localhost", Port: 9997, Count: 1}, - Host{Name: "localhost", Port: 9998, Count: 1}, - Host{Name: "localhost", Port: 9999, Count: 1}, + {Name: "localhost", Port: 9991, Count: 1}, + {Name: "localhost", Port: 9992, Count: 1}, + {Name: "localhost", Port: 9993, Count: 1}, + {Name: "localhost", Port: 9994, Count: 1}, + {Name: "localhost", Port: 9995, Count: 1}, + {Name: "localhost", Port: 9996, Count: 1}, + {Name: "localhost", Port: 9997, Count: 1}, + {Name: "localhost", Port: 9998, Count: 1}, + {Name: "localhost", Port: 9999, Count: 1}, } test.Lock() @@ -1011,19 +1021,19 @@ func TestStartSessionFailMultiRegion(t *testing.T) { browsers := Browsers{Browsers: []Browser{ {Name: "browser", DefaultVersion: "1.0", Versions: []Version{ {Number: "1.0", Regions: []Region{ - Region{ + { Name: "us-west-1", Hosts: Hosts{ node[0], node[1], node[2], }, }, - Region{ + { Name: "us-west-2", Hosts: Hosts{ node[3], node[4], node[5], }, }, - Region{ + { Name: "us-west-3", Hosts: Hosts{ node[6], node[7], node[8], @@ -1035,8 +1045,9 @@ func TestStartSessionFailMultiRegion(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 9 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 9 attempt(s)") } func TestStartSessionBrowserFail(t *testing.T) { @@ -1066,8 +1077,9 @@ func TestStartSessionBrowserFail(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 5 attempt(s), last host error was: Browser startup failure..."}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 5 attempt(s), last host error was: Browser startup failure...") } func TestStartSessionBrowserFailUnknownError(t *testing.T) { @@ -1097,8 +1109,9 @@ func TestStartSessionBrowserFailUnknownError(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestStartSessionBrowserFailWrongValue(t *testing.T) { @@ -1128,8 +1141,9 @@ func TestStartSessionBrowserFailWrongValue(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestStartSessionBrowserFailWrongMsg(t *testing.T) { @@ -1159,8 +1173,9 @@ func TestStartSessionBrowserFailWrongMsg(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusInternalServerError}, Message{"cannot create session browser-1.0 on any hosts after 1 attempt(s)"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusInternalServerError) + assert.Equal(t, message(rsp), "cannot create session browser-1.0 on any hosts after 1 attempt(s)") } func TestStartSessionFailJSONWireProtocol(t *testing.T) { @@ -1190,8 +1205,9 @@ func TestStartSessionFailJSONWireProtocol(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadGateway}, Message{"protocol error"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadGateway) + assert.Equal(t, message(rsp), "protocol error") } func TestStartSessionFailJSONWireProtocolNoSessionID(t *testing.T) { @@ -1220,8 +1236,9 @@ func TestStartSessionFailJSONWireProtocolNoSessionID(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadGateway}, Message{"protocol error"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadGateway) + assert.Equal(t, message(rsp), "protocol error") } func TestStartSessionFailJSONWireProtocolWrongType(t *testing.T) { @@ -1250,8 +1267,9 @@ func TestStartSessionFailJSONWireProtocolWrongType(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusBadGateway}, Message{"protocol error"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadGateway) + assert.Equal(t, message(rsp), "protocol error") } func TestStartSessionJSONWireProtocol(t *testing.T) { @@ -1280,10 +1298,11 @@ func TestStartSessionJSONWireProtocol(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"{browser}", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) + assert.NoError(t, err) var value map[string]interface{} - AssertThat(t, rsp, AllOf{Code{http.StatusOK}, IsJson{&value}}) - AssertThat(t, value["value"].(map[string]interface{})["sessionId"], EqualTo{fmt.Sprintf("%s123", node.Sum())}) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NoError(t, json.NewDecoder(rsp.Body).Decode(&value)) + assert.Equal(t, value["value"].(map[string]interface{})["sessionId"], fmt.Sprintf("%s123", node.Sum())) } func TestPanicRouteProtocolError(t *testing.T) { @@ -1312,8 +1331,8 @@ func TestPanicRouteProtocolError(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp.StatusCode, Is{http.StatusBadGateway}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusBadGateway) } func TestDeleteSession(t *testing.T) { @@ -1343,8 +1362,8 @@ func TestDeleteSession(t *testing.T) { r.SetBasicAuth("test", "test") rsp, err := http.DefaultClient.Do(r) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, Code{http.StatusOK}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) } func TestProxyRequest(t *testing.T) { @@ -1375,8 +1394,9 @@ func TestProxyRequest(t *testing.T) { r.SetBasicAuth("test", "test") rsp, err := http.DefaultClient.Do(r) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusOK}, Message{"response"}}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.Equal(t, message(rsp), "response") } func TestProxyJsonRequest(t *testing.T) { @@ -1384,7 +1404,7 @@ func TestProxyJsonRequest(t *testing.T) { mux.HandleFunc("/wd/hub/session/", func(w http.ResponseWriter, r *http.Request) { var msg map[string]interface{} _ = json.NewDecoder(r.Body).Decode(&msg) - AssertThat(t, msg["sessionId"], Is{nil}) + assert.Nil(t, msg["sessionId"]) }) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1417,7 +1437,7 @@ func TestProxyPlainRequest(t *testing.T) { mux.HandleFunc("/wd/hub/session/", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) _ = r.Body.Close() - AssertThat(t, string(body), EqualTo{"request"}) + assert.Equal(t, string(body), "request") }) selenium := httptest.NewServer(mux) defer selenium.Close() @@ -1438,7 +1458,7 @@ func TestProxyPlainRequest(t *testing.T) { }}}} updateQuota(user, browsers) - doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) + _, _ = doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) } func TestProxyHttpsHost(t *testing.T) { @@ -1470,16 +1490,17 @@ func TestProxyHttpsHost(t *testing.T) { http.DefaultTransport = oldTransport }() - resp, err := doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) - AssertThat(t, err, Is{nil}) - AssertThat(t, resp, Code{http.StatusOK}) + rsp, err := doBasicHTTPRequest(http.MethodPost, gridrouter("/wd/hub/session/"+node.Sum()+"123"), bytes.NewReader([]byte("request"))) + + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) } func TestRequest(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, remote := info(r) - AssertThat(t, user, EqualTo{"unknown"}) - AssertThat(t, remote, EqualTo{"127.0.0.1"}) + assert.Equal(t, user, "unknown") + assert.Equal(t, remote, "127.0.0.1") })) r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) @@ -1489,8 +1510,8 @@ func TestRequest(t *testing.T) { func TestRequestAuth(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, remote := info(r) - AssertThat(t, user, EqualTo{"user"}) - AssertThat(t, remote, EqualTo{"127.0.0.1"}) + assert.Equal(t, user, "user") + assert.Equal(t, remote, "127.0.0.1") })) r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) @@ -1501,8 +1522,8 @@ func TestRequestAuth(t *testing.T) { func TestRequestForwarded(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, remote := info(r) - AssertThat(t, user, EqualTo{"unknown"}) - AssertThat(t, remote, EqualTo{"proxy"}) + assert.Equal(t, user, "unknown") + assert.Equal(t, remote, "proxy") })) r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) @@ -1513,8 +1534,8 @@ func TestRequestForwarded(t *testing.T) { func TestRequestAuthForwarded(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, remote := info(r) - AssertThat(t, user, EqualTo{"user"}) - AssertThat(t, remote, EqualTo{"proxy"}) + assert.Equal(t, user, "user") + assert.Equal(t, remote, "proxy") })) r, _ := http.NewRequest(http.MethodGet, srv.URL, nil) @@ -1527,7 +1548,7 @@ func TestStartSessionProxyHeaders(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/wd/hub/session", postOnly(func(w http.ResponseWriter, r *http.Request) { u, _, _ := r.BasicAuth() - AssertThat(t, u, EqualTo{user}) + assert.Equal(t, u, user) _, _ = w.Write([]byte(`{"sessionId":"123"}`)) })) selenium := httptest.NewServer(mux) @@ -1551,10 +1572,11 @@ func TestStartSessionProxyHeaders(t *testing.T) { rsp, err := createSession(`{"desiredCapabilities":{"browserName":"browser", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - var sess map[string]string - AssertThat(t, rsp, AllOf{Code{http.StatusOK}, IsJson{&sess}}) - AssertThat(t, sess["sessionId"], EqualTo{fmt.Sprintf("%s123", node.Sum())}) + assert.NoError(t, err) + var sess map[string]interface{} + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NoError(t, json.NewDecoder(rsp.Body).Decode(&sess)) + assert.Equal(t, sess["sessionId"], fmt.Sprintf("%s123", node.Sum())) } func TestStartSessionGuest(t *testing.T) { @@ -1584,10 +1606,11 @@ func TestStartSessionGuest(t *testing.T) { updateQuota(guestUserName, browsers) rsp, err := createSessionWithoutAuthentication(`{"desiredCapabilities":{"browserName":"{browser}", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) + assert.NoError(t, err) var value map[string]interface{} - AssertThat(t, rsp, AllOf{Code{http.StatusOK}, IsJson{&value}}) - AssertThat(t, value["value"].(map[string]interface{})["sessionId"], EqualTo{fmt.Sprintf("%s123", node.Sum())}) + assert.Equal(t, rsp.StatusCode, http.StatusOK) + assert.NoError(t, json.NewDecoder(rsp.Body).Decode(&value)) + assert.Equal(t, value["value"].(map[string]interface{})["sessionId"], fmt.Sprintf("%s123", node.Sum())) } func TestStartSessionGuestFailNoQuota(t *testing.T) { @@ -1605,9 +1628,9 @@ func TestStartSessionGuestFailNoQuota(t *testing.T) { defer test.Unlock() rsp, err := createSessionWithoutAuthentication(`{"desiredCapabilities":{"browserName":"{browser}", "version":"1.0"}}`) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp, AllOf{Code{http.StatusUnauthorized}, Message{"Guest access is unavailable"}}) - + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) + assert.Equal(t, message(rsp), "Guest access is unavailable") } func TestStartSessionGuestAndCorrectBasicAuth(t *testing.T) { @@ -1665,8 +1688,8 @@ func TestStartSessionGuestModeAndWrongBasicAuth(t *testing.T) { client := &http.Client{} rsp, err := client.Do(req) - AssertThat(t, err, Is{nil}) - AssertThat(t, rsp.StatusCode, Is{http.StatusUnauthorized}) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusUnauthorized) } func createSessionWithoutAuthentication(capabilities string) (*http.Response, error) { @@ -1682,11 +1705,11 @@ func doHTTPRequestWithoutAuthentication(method string, url string, body io.Reade func TestFileExists(t *testing.T) { tmpDir := os.TempDir() - AssertThat(t, fileExists(tmpDir), Is{false}) - AssertThat(t, fileExists(filepath.Join(tmpDir, "missing-file")), Is{false}) + assert.False(t, fileExists(tmpDir)) + assert.False(t, fileExists(filepath.Join(tmpDir, "missing-file"))) f, err := os.CreateTemp(tmpDir, "testfile") - AssertThat(t, err, Is{nil}) - AssertThat(t, fileExists(f.Name()), Is{true}) + assert.NoError(t, err) + assert.True(t, fileExists(f.Name())) } func TestPanicGuestQuotaMissingUsersFileAuthPresent(t *testing.T) { @@ -1708,9 +1731,9 @@ func TestPanicGuestQuotaMissingUsersFileAuthPresent(t *testing.T) { req, _ := http.NewRequest(http.MethodGet, srv.URL+"/", nil) req.SetBasicAuth("test", "test") - resp, err := http.DefaultClient.Do(req) - AssertThat(t, err, Is{nil}) - AssertThat(t, resp, Code{http.StatusOK}) + rsp, err := http.DefaultClient.Do(req) + assert.NoError(t, err) + assert.Equal(t, rsp.StatusCode, http.StatusOK) } func TestPlatformCapability(t *testing.T) { @@ -1718,12 +1741,12 @@ func TestPlatformCapability(t *testing.T) { testCaps := `{"desiredCapabilities": {"platformName": "WINDOWS"}, "capabilities": {"platformName": "windows"}}` _ = json.Unmarshal([]byte(testCaps), &caps) - AssertThat(t, caps.platform(), EqualTo{"WINDOWS"}) + assert.Equal(t, caps.platform(), "WINDOWS") } func TestLabelsCapabilityFromExtensions(t *testing.T) { var caps caps testCaps := `{"capabilities": {"alwaysMatch":{"ggr:options": {"labels": {"some-key": "some-value"}}}}}` _ = json.Unmarshal([]byte(testCaps), &caps) - AssertThat(t, caps.labels(), EqualTo{"some-key=some-value"}) + assert.Equal(t, caps.labels(), "some-key=some-value") }