Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve UT Coverage #83

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions api/api_logging.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
/*
Copyright (c) 2019 Dell Corporation
All Rights Reserved
*/
// Copyright © 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package api

Expand All @@ -21,6 +29,18 @@ func isBinOctetBody(h http.Header) bool {
return h.Get(HeaderKeyContentType) == headerValContentTypeBinaryOctetStream
}

type (
dumpRequestFunc func(req *http.Request, body bool) ([]byte, error)
dumpResponseFunc func(req *http.Response, body bool) ([]byte, error)
writeIndentedFunc func(w io.Writer, b []byte) error
)

var (
dumpRequest dumpRequestFunc = httputil.DumpRequest
dumpResponse dumpResponseFunc = httputil.DumpResponse
writeIndented writeIndentedFunc = WriteIndented
)

func logRequest(
_ context.Context,
req *http.Request,
Expand All @@ -33,12 +53,12 @@ func logRequest(
fmt.Fprint(w, "GOUNITY HTTP REQUEST")
fmt.Fprintln(w, " -------------------------")

buf, err := httputil.DumpRequest(req, !isBinOctetBody(req.Header))
buf, err := dumpRequest(req, !isBinOctetBody(req.Header))
if err != nil {
return
}

err2 := WriteIndented(w, buf)
err2 := writeIndented(w, buf)
if err2 != nil {
message := fmt.Sprintf("Indentation failed with error: %v", err2)
log.Info(message)
Expand All @@ -61,13 +81,13 @@ func logResponse(
fmt.Fprint(w, "GOUNITY HTTP RESPONSE")
fmt.Fprintln(w, " -------------------------")

buf, err := httputil.DumpResponse(res, !isBinOctetBody(res.Header))
buf, err := dumpResponse(res, !isBinOctetBody(res.Header))
if err != nil {
return
}

bw := &bytes.Buffer{}
err2 := WriteIndented(bw, buf)
err2 := writeIndented(bw, buf)
if err2 != nil {
message := fmt.Sprintf("Indentation failed with error: %v", err2)
log.Info(message)
Expand Down
128 changes: 128 additions & 0 deletions api/api_logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,26 @@ package api
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"testing"
)

// Custom writer that fails after a certain number of writes
type errorWriter struct {
maxWrites int
writes int
}

func (ew *errorWriter) Write(p []byte) (n int, err error) {
if ew.writes >= ew.maxWrites {
return 0, errors.New("write error")
}
ew.writes++
return len(p), nil
}

func TestIsBinOctetBody(t *testing.T) {
// Test case: header with correct content type
header := http.Header{}
Expand Down Expand Up @@ -84,6 +100,50 @@ func TestLogRequest(t *testing.T) {

logRequest(context.TODO(), req, nil)
})

// // Test case: Request with error in DumpRequest
t.Run("Request with error in DumpRequest", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
t.Fatal(err)
}

// Mock the DumpRequest function to return an error
originalDumpRequest := dumpRequest
defer func() { dumpRequest = originalDumpRequest }()

dumpRequest = func(_ *http.Request, _ bool) ([]byte, error) {
return nil, errors.New("DumpRequest failed")
}

// Call the logRequest function
logRequest(context.TODO(), req, nil)
})

// Test case: Request with error in WriteIndented
t.Run("Request with error in WriteIndented", func(t *testing.T) {
req, err := http.NewRequest("GET", "http://example.com", nil)
if err != nil {
t.Fatal(err)
}

// Mock DumpRequest to succeed
originalDumpRequest := dumpRequest
defer func() { dumpRequest = originalDumpRequest }()
dumpRequest = func(_ *http.Request, _ bool) ([]byte, error) {
return []byte("request body"), nil
}

// Mock WriteIndented to return an error
originalWriteIndented := writeIndented
defer func() { writeIndented = originalWriteIndented }()
writeIndented = func(_ io.Writer, _ []byte) error {
return errors.New("WriteIndented failed")
}

// Call the logRequest function
logRequest(context.TODO(), req, nil)
})
}

func TestLogResponse(t *testing.T) {
Expand Down Expand Up @@ -128,6 +188,52 @@ func TestLogResponse(t *testing.T) {
logResponse(context.Background(), res, nil)
// Add assertions to check if the indentation error is logged correctly
})

// Test case: Response with error in DumpResponse
t.Run("Response with error in DumpResponse", func(_ *testing.T) {
res := &http.Response{
Header: http.Header{
"Content-Type": []string{"application/json"},
},
}

// Mock the DumpResponse function to return an error
originalDumpResponse := dumpResponse
defer func() { dumpResponse = originalDumpResponse }()

dumpResponse = func(_ *http.Response, _ bool) ([]byte, error) {
return nil, errors.New("DumpResponse failed")
}

// Call the logResponse function
logResponse(context.TODO(), res, nil)
})

// Test case: Response with error in WriteIndented
t.Run("Failure in WriteIndented", func(_ *testing.T) {
res := &http.Response{
Header: http.Header{
"Content-Type": []string{"application/json"},
},
}

// Mock DumpResponse to succeed
originalDumpResponse := dumpResponse
defer func() { dumpResponse = originalDumpResponse }()
dumpResponse = func(_ *http.Response, _ bool) ([]byte, error) {
return []byte("response body"), nil
}

// Mock WriteIndented to return an error
originalWriteIndented := writeIndented
defer func() { writeIndented = originalWriteIndented }()
writeIndented = func(_ io.Writer, _ []byte) error {
return errors.New("WriteIndented failed")
}

// Call the logResponse function
logResponse(context.TODO(), res, nil)
})
}

func TestWriteIndentedN(t *testing.T) {
Expand Down Expand Up @@ -162,4 +268,26 @@ func TestWriteIndentedN(t *testing.T) {
if buf.String() != expected {
t.Errorf("Expected %q, got %q", expected, buf.String())
}

// Error conditions using errorWriter
// Test case: Error at initial indent
ew := &errorWriter{maxWrites: 0}
err = WriteIndentedN(ew, []byte("Hello, world!"), 4)
if err == nil || err.Error() != "write error" {
t.Errorf("Expected write error, got %v", err)
}

// Test case: Error in writing line content
ew = &errorWriter{maxWrites: 4}
err = WriteIndentedN(ew, []byte("Hello, world!"), 4)
if err == nil || err.Error() != "write error" {
t.Errorf("Expected write error, got %v", err)
}

// Test case: Error in writing newline
ew = &errorWriter{maxWrites: 9} // Enough for " Hello"
err = WriteIndentedN(ew, []byte("Hello\nworld!"), 4)
if err == nil || err.Error() != "write error" {
t.Errorf("Expected write error, got %v", err)
}
}
9 changes: 5 additions & 4 deletions api/restclient.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright © 2019-2024 Dell Inc. or its subsidiaries. All Rights Reserved.
Copyright © 2019-2025 Dell Inc. or its subsidiaries. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -43,8 +43,9 @@ const (
)

var (
errNewClient = errors.New("missing endpoint")
errSysCerts = errors.New("unable to initialize certificate pool from system")
errNewClient = errors.New("missing endpoint")
errSysCerts = errors.New("unable to initialize certificate pool from system")
systemCertPoolFunc = x509.SystemCertPool
)

// Client Interface defines the methods.
Expand Down Expand Up @@ -151,7 +152,7 @@ func New(_ context.Context, host string, opts ClientOptions, debug bool) (Client
},
}
} else {
pool, err := x509.SystemCertPool()
pool, err := systemCertPoolFunc()
if err != nil {
return nil, errSysCerts
}
Expand Down
100 changes: 100 additions & 0 deletions api/restclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ package api

import (
"context"
"crypto/x509"
"encoding/json"
"errors"
"io"
"net/http"
Expand Down Expand Up @@ -189,6 +191,43 @@ func TestDoWithHeaders(t *testing.T) {
}
assert.Equal(t, &expectedError, err)

// for 401 response - when json Decode err is nil
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method)
assert.Equal(t, "/api/v1/endpoint", r.URL.String())
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(types.Error{
ErrorContent: types.ErrorContent{
Message: []types.ErrorMessage{
{
EnUS: "Unauthorized",
},
},
HTTPStatusCode: 401,
ErrorCode: 0,
},
})
}))
defer server.Close()
c.host = server.URL
err = c.DoWithHeaders(ctx, http.MethodGet, "api/v1/endpoint", nil, body, &responseData)
errorContent = types.ErrorContent{
Message: []types.ErrorMessage{
{
EnUS: "Unauthorized",
},
{
EnUS: "401 Unauthorized",
},
},
HTTPStatusCode: 401,
ErrorCode: 0,
}
expectedError = types.Error{
ErrorContent: errorContent,
}
assert.Equal(t, &expectedError, err)

// for 400 response
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, http.MethodGet, r.Method)
Expand Down Expand Up @@ -233,6 +272,22 @@ func TestNew(t *testing.T) {
}
_, err = New(ctx, host, opts, debug)
assert.Equal(t, nil, err)

// Test the System Cert Pool Error
originalFunc := systemCertPoolFunc
defer func() { systemCertPoolFunc = originalFunc }()

systemCertPoolFunc = func() (*x509.CertPool, error) {
return nil, errors.New("mock system cert pool error")
}

opts = ClientOptions{
Insecure: false,
Timeout: 0,
ShowHTTP: false,
}
_, err = New(ctx, host, opts, debug)
assert.Equal(t, errSysCerts, err)
}

func TestDoLog(t *testing.T) {
Expand All @@ -248,3 +303,48 @@ func TestDoLog(t *testing.T) {
c.doLog(logger, "Test message")
assert.Equal(t, "Test message", loggedMessage)
}

func TestClientGet(t *testing.T) {
c := &client{
http: http.DefaultClient,
host: "https://example.com",
}
err := c.Get(context.Background(), c.host, nil, nil)
assert.Error(t, err)
}

func TestClientPost(t *testing.T) {
c := &client{
http: http.DefaultClient,
host: "https://example.com",
}
err := c.Post(context.Background(), c.host, nil, nil, nil)
assert.Error(t, err)
}

func TestClientPut(t *testing.T) {
c := &client{
http: http.DefaultClient,
host: "https://example.com",
}
err := c.Put(context.Background(), c.host, nil, nil, nil)
assert.Error(t, err)
}

func TestClientDelete(t *testing.T) {
c := &client{
http: http.DefaultClient,
host: "https://example.com",
}
err := c.Delete(context.Background(), c.host, nil, nil)
assert.Error(t, err)
}

func TestClientDo(t *testing.T) {
c := &client{
http: http.DefaultClient,
host: "https://example.com",
}
err := c.Do(context.Background(), http.MethodGet, c.host, nil, nil)
assert.Error(t, err)
}
Loading