From 8301bd09644d2cd0952a65adda05a166c60706d2 Mon Sep 17 00:00:00 2001 From: Kirill Sysoev Date: Sat, 17 Aug 2024 18:46:10 +0800 Subject: [PATCH] Address linter complains --- api.go | 19 ++++++++-------- api_test.go | 11 +++++++-- bin/generate_calls.go | 14 +++++++++--- errors_test.go | 10 ++++----- helpers_test.go | 4 +--- subscriptions_test.go | 52 +++++++++++++++++++++++++++++++++---------- 6 files changed, 74 insertions(+), 36 deletions(-) diff --git a/api.go b/api.go index 4173435..15fbf6a 100644 --- a/api.go +++ b/api.go @@ -51,7 +51,7 @@ type APIResponseReqID struct { ReqID int `json:"req_id"` } -type DerivApiOption func(api *DerivAPI) +type APIOption func(api *DerivAPI) // NewDerivAPI creates a new instance of DerivAPI by parsing and validating the given // endpoint URL, appID, language, and origin URL. It returns a pointer to a DerivAPI object @@ -62,9 +62,9 @@ type DerivApiOption func(api *DerivAPI) // - appID: int - The app ID for the DerivAPI server // - lang: string - The language code (ISO 639-1) for the DerivAPI server // - origin: string - The origin URL for the DerivAPI server -// - opts: DerivApiOption - A variadic list of DerivApiOption functions to configure the DerivAPI object (optional) -// - KeepAlive: A DerivApiOption function to keep the connection alive by sending ping requests. -// - Debug: A DerivApiOption function to enable debug messages. +// - opts: APIOption - A variadic list of APIOption functions to configure the DerivAPI object (optional) +// - KeepAlive: A APIOption function to keep the connection alive by sending ping requests. +// - Debug: A APIOption function to enable debug messages. // // Returns: // - *DerivAPI: A pointer to a new instance of DerivAPI with the validated endpoint, appID, @@ -77,7 +77,7 @@ type DerivApiOption func(api *DerivAPI) // if err != nil { // log.Fatal(err) // } -func NewDerivAPI(endpoint string, appID int, lang string, origin string, opts ...DerivApiOption) (*DerivAPI, error) { +func NewDerivAPI(endpoint string, appID int, lang, origin string, opts ...APIOption) (*DerivAPI, error) { urlEnpoint, err := url.Parse(endpoint) if err != nil { return nil, err @@ -281,7 +281,7 @@ func (api *DerivAPI) handleResponses(wsConn *websocket.Conn, respChan chan []byt // requestMapper forward requests to the Deriv API server and // responses from the WebSocket server to the appropriate channels. -func (api *DerivAPI) requestMapper(respChan chan []byte, outputChan chan []byte, reqChan chan APIReqest, closingChan chan int) { +func (api *DerivAPI) requestMapper(respChan, outputChan chan []byte, reqChan chan APIReqest, closingChan chan int) { responseMap := make(map[int]chan []byte) defer func() { @@ -346,7 +346,7 @@ func (api *DerivAPI) Send(reqID int, request any) (chan []byte, error) { } // SendRequest sends a request to the Deriv API and returns the response -func (api *DerivAPI) SendRequest(reqID int, request any, response any) (err error) { +func (api *DerivAPI) SendRequest(reqID int, request, response any) error { respChan, err := api.Send(reqID, request) if err != nil { @@ -365,12 +365,11 @@ func (api *DerivAPI) SendRequest(reqID int, request any, response any) (err erro return fmt.Errorf("connection closed") } - if err = parseError(responseJSON); err != nil { + if err := parseError(responseJSON); err != nil { return err } - err = json.Unmarshal(responseJSON, response) - if err != nil { + if err := json.Unmarshal(responseJSON, response); err != nil { api.logDebugf("Failed to parse response for request %d: %s", reqID, err.Error()) return err } diff --git a/api_test.go b/api_test.go index cdfe94a..fb6885d 100644 --- a/api_test.go +++ b/api_test.go @@ -430,7 +430,11 @@ func TestKeepConnectionAlive(t *testing.T) { api, _ := NewDerivAPI(url, 123, "en", "http://example.com", KeepAlive) api.keepAliveInterval = time.Millisecond - api.Connect() + + if err := api.Connect(); err != nil { + t.Errorf("Failed to connect to mocked WebSocket server: %v", err) + } + select { case msg := <-resChan: if msg == "" { @@ -442,7 +446,10 @@ func TestKeepConnectionAlive(t *testing.T) { api.Disconnect() api.keepAlive = false - api.Connect() + + if err := api.Connect(); err != nil { + t.Errorf("Failed to connect to mocked WebSocket server: %v", err) + } select { case msg, ok := <-resChan: diff --git a/bin/generate_calls.go b/bin/generate_calls.go index 008b8aa..2915d08 100644 --- a/bin/generate_calls.go +++ b/bin/generate_calls.go @@ -20,6 +20,8 @@ const ( // SCHEMA_PATH is the path to the schema files SchemaPath = "./deriv-api-docs/config/v3/" + + fileMode = 0o600 ) func main() { @@ -57,8 +59,13 @@ func main() { } } - os.WriteFile(APICalls, []byte(apiCalls), 0644) - os.WriteFile(SubscriptionCalls, []byte(subcriptionCalls), 0644) + if err := os.WriteFile(APICalls, []byte(apiCalls), fileMode); err != nil { + log.Fatal(err) + } + + if err := os.WriteFile(SubscriptionCalls, []byte(subcriptionCalls), fileMode); err != nil { + log.Fatal(err) + } } func HasSubscribe(r map[string]any) bool { @@ -82,7 +89,8 @@ func CreateTitle(name string) string { for _, s := range strings.Split(name, "_") { if s == "p2p" { - s = "P2P" + title += "P2P" + continue } title += cases.Title(language.Tag{}).String(s) diff --git a/errors_test.go b/errors_test.go index f781e87..0ad96a3 100644 --- a/errors_test.go +++ b/errors_test.go @@ -57,11 +57,10 @@ func TestParseError_InvalidResponse(t *testing.T) { func TestParseError_EmptyErrorResponse(t *testing.T) { rawResponse := []byte("{}") - expected := (error)(nil) actual := parseError(rawResponse) - if actual != expected { - t.Errorf("parseError() returned %v, expected %v", actual, expected) + if actual != nil { + t.Errorf("parseError() returned %v, expected %v", actual, nil) } } @@ -75,10 +74,9 @@ func TestParseError_EmptyAPIError(t *testing.T) { t.Errorf("Unexpected error: %v", err) } - expected := (error)(nil) actual := parseError(rawResponse) - if actual != expected { - t.Errorf("parseError() returned %v, expected %v", actual, expected) + if actual != nil { + t.Errorf("parseError() returned %v, expected %v", actual, nil) } } diff --git a/helpers_test.go b/helpers_test.go index 30e9d37..cf7cac6 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -18,7 +18,7 @@ func newMockWSServer(cb func(ws *websocket.Conn)) *httptest.Server { if err != nil { return } - defer c.CloseNow() + defer func() { _ = c.CloseNow() }() cb(c) @@ -29,8 +29,6 @@ func newMockWSServer(cb func(ws *websocket.Conn)) *httptest.Server { } func echoHandler(ws *websocket.Conn) { - defer ws.CloseNow() - for { msgType, reader, err := ws.Reader(context.TODO()) if err != nil { diff --git a/subscriptions_test.go b/subscriptions_test.go index 04e39ee..0027806 100644 --- a/subscriptions_test.go +++ b/subscriptions_test.go @@ -101,8 +101,13 @@ func TestStart(t *testing.T) { }` server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { - ws.Write(context.Background(), websocket.MessageText, []byte(testResp)) - ws.Write(context.Background(), websocket.MessageText, []byte(testResp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } time.Sleep(time.Second) // to keep the connection open })) @@ -150,7 +155,9 @@ func TestStart(t *testing.T) { t.Errorf("Expected to get a response, but got nothing") } - sub.Start(reqID, req) + if _, err := sub.Start(reqID, req); err != nil { + t.Errorf("Unexpected error: %v", err) + } if sub.IsActive() == false { t.Errorf("Expected subscription to be active, but got inactive") @@ -160,7 +167,9 @@ func TestStart(t *testing.T) { func TestStartFailed(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { - ws.Write(context.Background(), websocket.MessageText, []byte("")) + if err := ws.Write(context.Background(), websocket.MessageText, []byte("")); err != nil { + t.Errorf("Unexpected error: %v", err) + } time.Sleep(time.Second) // to keep the connection open })) @@ -210,7 +219,9 @@ func TestForget(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { for resp := range responses { - ws.Write(context.Background(), websocket.MessageText, []byte(resp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(resp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } } time.Sleep(time.Second) // to keep the connection open @@ -261,13 +272,18 @@ func TestForget(t *testing.T) { "msg_type": "forget" }` }() - sub.Forget() + + if err := sub.Forget(); err != nil { + t.Errorf("Unexpected error: %v", err) + } if sub.IsActive() == true { t.Errorf("Expected subscription to be deactivated, but got true") } - sub.Forget() + if err := sub.Forget(); err != nil { + t.Errorf("Unexpected error: %v", err) + } if sub.IsActive() == true { t.Errorf("Expected subscription to be deactivated, but got true") @@ -301,7 +317,9 @@ func TestForgetFailed(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { for resp := range responses { - ws.Write(context.Background(), websocket.MessageText, []byte(resp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(resp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } } time.Sleep(time.Second) // to keep the connection open @@ -381,7 +399,10 @@ func TestStartAPIError(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { - ws.Write(context.Background(), websocket.MessageText, []byte(testResp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } + time.Sleep(time.Second) // to keep the connection open })) @@ -422,7 +443,10 @@ func TestStartInvalidResponse(t *testing.T) { }` server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { - ws.Write(context.Background(), websocket.MessageText, []byte(testResp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(testResp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } + time.Sleep(time.Second) // to keep the connection open })) @@ -478,7 +502,9 @@ func TestStartInvalidResponseInSubscription(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { for _, resp := range responses { - ws.Write(context.Background(), websocket.MessageText, []byte(resp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(resp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } } time.Sleep(time.Second) // to keep the connection open @@ -562,7 +588,9 @@ func TestStartAPIErrorInSubscription(t *testing.T) { server := newMockWSServer( onMessageHanler(func(ws *websocket.Conn, _ websocket.MessageType, _ []byte) { for _, resp := range responses { - ws.Write(context.Background(), websocket.MessageText, []byte(resp)) + if err := ws.Write(context.Background(), websocket.MessageText, []byte(resp)); err != nil { + t.Errorf("Unexpected error: %v", err) + } } time.Sleep(time.Second) // to keep the connection open