Skip to content

Commit de7bb1b

Browse files
committed
Refactor file paths in msgraph_api_url.go and msgraph_api_headers.go + added new tests
1 parent de9439f commit de7bb1b

11 files changed

+207
-260
lines changed

apiintegrations/msgraph/msgraph_api_exceptions.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// msgraph_api_exceptions.go
1+
// apiintegrations/msgraph/msgraph_api_exceptions.go
22
package msgraph
33

44
import (

apiintegrations/msgraph/msgraph_api_handler.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// msgraph_api_handler.go
1+
// apiintegrations/msgraph/msgraph_api_handler.go
22
package msgraph
33

44
import "github.com/deploymenttheory/go-api-http-client/logger"

apiintegrations/msgraph/msgraph_api_handler_constants.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// msgraph_api_handler_constants.go
1+
// apiintegrations/msgraph/msgraph_api_handler_constants.go
22
package msgraph
33

44
// Endpoint constants represent the URL suffixes used for graph API token interactions.

apiintegrations/msgraph/msgraph_api_headers.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// msgraph_api_headers.go
1+
// apiintegrations/msgraph/msgraph_api_headers.go
22
package msgraph
33

44
import (
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// apiintegrations/msgraph/msgraph_api_headers_test.go
2+
package msgraph
3+
4+
import (
5+
"testing"
6+
7+
"github.com/deploymenttheory/go-api-http-client/mocklogger"
8+
"github.com/stretchr/testify/assert"
9+
"github.com/stretchr/testify/mock"
10+
)
11+
12+
// TestGetAPIRequestHeaders tests the GetAPIRequestHeaders function.
13+
func TestGetAPIRequestHeaders(t *testing.T) {
14+
handler := GraphAPIHandler{Logger: mocklogger.NewMockLogger()}
15+
endpoint := "/api/data"
16+
handler.Logger.(*mocklogger.MockLogger).On("Debug", mock.Anything, mock.Anything).Maybe()
17+
18+
expectedHeaders := map[string]string{
19+
"Accept": "application/x-x509-ca-cert;q=0.95,application/pkix-cert;q=0.94,application/pem-certificate-chain;q=0.93,application/octet-stream;q=0.8,image/png;q=0.75,image/jpeg;q=0.74,image/*;q=0.7,application/xml;q=0.65,text/xml;q=0.64,text/xml;charset=UTF-8;q=0.63,application/json;q=0.5,text/html;q=0.5,text/plain;q=0.4,*/*;q=0.05",
20+
"Content-Type": "application/json",
21+
"Authorization": "",
22+
"User-Agent": "go-api-http-client-msgraph-handler",
23+
}
24+
25+
headers := handler.GetAPIRequestHeaders(endpoint)
26+
assert.Equal(t, expectedHeaders, headers)
27+
handler.Logger.(*mocklogger.MockLogger).AssertExpectations(t)
28+
}
29+
30+
// TestGetContentTypeHeader tests the GetContentTypeHeader function.
31+
func TestGetAcceptHeader(t *testing.T) {
32+
handler := GraphAPIHandler{}
33+
acceptHeader := handler.GetAcceptHeader()
34+
expectedHeader := "application/x-x509-ca-cert;q=0.95,application/pkix-cert;q=0.94,application/pem-certificate-chain;q=0.93,application/octet-stream;q=0.8,image/png;q=0.75,image/jpeg;q=0.74,image/*;q=0.7,application/xml;q=0.65,text/xml;q=0.64,text/xml;charset=UTF-8;q=0.63,application/json;q=0.5,text/html;q=0.5,text/plain;q=0.4,*/*;q=0.05"
35+
assert.Equal(t, expectedHeader, acceptHeader, "The Accept header should correctly prioritize MIME types.")
36+
}

apiintegrations/msgraph/msgraph_api_request.go

+10-36
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,29 @@
1-
// msgraph_api_request.go
1+
// apiintegrations/msgraph/msgraph_api_request.go
22
package msgraph
33

44
import (
55
"bytes"
66
"encoding/json"
7-
"encoding/xml"
87
"io"
98
"mime/multipart"
109
"os"
11-
"strings"
1210

1311
"github.com/deploymenttheory/go-api-http-client/logger"
1412
"go.uber.org/zap"
1513
)
1614

17-
// MarshalRequest encodes the request body according to the endpoint for the API.
15+
// MarshalRequest encodes the request body as JSON for the Microsoft Graph API.
1816
func (g *GraphAPIHandler) MarshalRequest(body interface{}, method string, endpoint string, log logger.Logger) ([]byte, error) {
19-
var (
20-
data []byte
21-
err error
22-
)
23-
24-
// Determine the format based on the endpoint
25-
format := "json"
26-
if strings.Contains(endpoint, "/JSSResource") {
27-
format = "xml"
28-
} else if strings.Contains(endpoint, "/api") {
29-
format = "json"
17+
// Marshal the body as JSON
18+
data, err := json.Marshal(body)
19+
if err != nil {
20+
g.Logger.Error("Failed marshaling JSON request", zap.Error(err))
21+
return nil, err
3022
}
3123

32-
switch format {
33-
case "xml":
34-
data, err = xml.Marshal(body)
35-
if err != nil {
36-
return nil, err
37-
}
38-
39-
if method == "POST" || method == "PUT" {
40-
g.Logger.Debug("XML Request Body", zap.String("Body", string(data)))
41-
}
42-
43-
case "json":
44-
data, err = json.Marshal(body)
45-
if err != nil {
46-
g.Logger.Error("Failed marshaling JSON request", zap.Error(err))
47-
return nil, err
48-
}
49-
50-
if method == "POST" || method == "PUT" || method == "PATCH" {
51-
g.Logger.Debug("JSON Request Body", zap.String("Body", string(data)))
52-
}
24+
// Log the JSON request body for POST, PUT, or PATCH methods
25+
if method == "POST" || method == "PUT" || method == "PATCH" {
26+
g.Logger.Debug("JSON Request Body", zap.String("Body", string(data)))
5327
}
5428

5529
return data, nil
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
// apiintegrations/msgraph/msgraph_api_request_test.go
2+
package msgraph
3+
4+
import (
5+
"bytes"
6+
"encoding/json"
7+
"io"
8+
"mime/multipart"
9+
"os"
10+
"path/filepath"
11+
"strings"
12+
"testing"
13+
14+
"github.com/deploymenttheory/go-api-http-client/mocklogger"
15+
"github.com/stretchr/testify/assert"
16+
"github.com/stretchr/testify/mock"
17+
"go.uber.org/zap"
18+
)
19+
20+
// TestMarshalRequest tests the MarshalRequest function.
21+
func TestMarshalRequest(t *testing.T) {
22+
body := map[string]interface{}{
23+
"name": "John Doe",
24+
"age": 30,
25+
}
26+
method := "POST"
27+
endpoint := "/users"
28+
mockLog := mocklogger.NewMockLogger()
29+
handler := GraphAPIHandler{Logger: mockLog}
30+
31+
expectedData, _ := json.Marshal(body)
32+
33+
// Correct the way we setup the logger mock
34+
mockLog.On("Debug", "JSON Request Body", mock.MatchedBy(func(fields []zap.Field) bool {
35+
if len(fields) != 1 {
36+
return false
37+
}
38+
return fields[0].Key == "Body" && fields[0].String == string(expectedData)
39+
})).Once()
40+
41+
data, err := handler.MarshalRequest(body, method, endpoint, mockLog)
42+
43+
assert.NoError(t, err)
44+
assert.Equal(t, expectedData, data)
45+
mockLog.AssertExpectations(t)
46+
}
47+
48+
func TestMarshalMultipartRequest(t *testing.T) {
49+
// Prepare the logger mock
50+
mockLog := mocklogger.NewMockLogger()
51+
52+
// Setting up a temporary file to simulate a file upload
53+
tempDir := t.TempDir() // Create a temporary directory for test files
54+
tempFile, err := os.CreateTemp(tempDir, "upload-*.txt")
55+
assert.NoError(t, err)
56+
defer os.Remove(tempFile.Name()) // Ensure the file is removed after the test
57+
58+
_, err = tempFile.WriteString("Test file content")
59+
assert.NoError(t, err)
60+
tempFile.Close()
61+
62+
handler := GraphAPIHandler{Logger: mockLog}
63+
64+
fields := map[string]string{"field1": "value1"}
65+
files := map[string]string{"fileField": tempFile.Name()}
66+
67+
// Execute the function
68+
body, contentType, err := handler.MarshalMultipartRequest(fields, files, mockLog)
69+
assert.NoError(t, err)
70+
assert.Contains(t, contentType, "multipart/form-data; boundary=")
71+
72+
// Check if the multipart form data contains the correct fields and file data
73+
reader := multipart.NewReader(bytes.NewReader(body), strings.TrimPrefix(contentType, "multipart/form-data; boundary="))
74+
var foundField, foundFile bool
75+
76+
for {
77+
part, err := reader.NextPart()
78+
if err == io.EOF {
79+
break
80+
}
81+
assert.NoError(t, err)
82+
83+
if part.FormName() == "field1" {
84+
buf := new(bytes.Buffer)
85+
_, err = buf.ReadFrom(part)
86+
assert.NoError(t, err)
87+
assert.Equal(t, "value1", buf.String())
88+
foundField = true
89+
} else if part.FileName() == filepath.Base(tempFile.Name()) {
90+
buf := new(bytes.Buffer)
91+
_, err = buf.ReadFrom(part)
92+
assert.NoError(t, err)
93+
assert.Equal(t, "Test file content", buf.String())
94+
foundFile = true
95+
}
96+
}
97+
98+
// Ensure all expected parts were found
99+
assert.True(t, foundField, "Text field not found in the multipart form data")
100+
assert.True(t, foundFile, "File not found in the multipart form data")
101+
}

apiintegrations/msgraph/msgraph_api_url.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// msgraph_api_url.go
1+
// apiintegrations/msgraph/msgraph_api_url.go
22
package msgraph
33

44
import (
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// apiintegrations/msgraph/msgraph_api_url_test.go
2+
package msgraph
3+
4+
import (
5+
"fmt"
6+
"testing"
7+
8+
"github.com/deploymenttheory/go-api-http-client/mocklogger"
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/mock"
11+
)
12+
13+
// TestConstructAPIResourceEndpoint tests the ConstructAPIResourceEndpoint function.
14+
func TestConstructAPIResourceEndpoint(t *testing.T) {
15+
const baseURL = "https://graph.microsoft.com"
16+
const endpointPath = "/v1.0/users"
17+
18+
// Mock logger
19+
mockLog := mocklogger.NewMockLogger()
20+
mockLog.On("Debug", mock.AnythingOfType("string"), mock.Anything).Once()
21+
22+
handler := GraphAPIHandler{
23+
TenantID: "dummy-tenant-id",
24+
Logger: mockLog,
25+
}
26+
27+
// Set base domain assuming it's being mocked or controlled internally
28+
expectedURL := fmt.Sprintf("%s%s", baseURL, endpointPath)
29+
resultURL := handler.ConstructAPIResourceEndpoint(endpointPath, mockLog)
30+
31+
assert.Equal(t, expectedURL, resultURL, "URL should match expected format")
32+
mockLog.AssertExpectations(t)
33+
}
34+
35+
// TestConstructAPIAuthEndpoint tests the ConstructAPIAuthEndpoint function.
36+
func TestConstructAPIAuthEndpoint(t *testing.T) {
37+
const baseURL = "https://login.microsoftonline.com"
38+
const endpointPath = "/oauth2/v2.0/token"
39+
40+
// Mock logger
41+
mockLog := mocklogger.NewMockLogger()
42+
mockLog.On("Debug", mock.AnythingOfType("string"), mock.Anything).Once()
43+
44+
handler := GraphAPIHandler{
45+
TenantID: "dummy-tenant-id",
46+
Logger: mockLog,
47+
}
48+
49+
// Construct the full URL by combining the base URL, tenant ID, and endpoint path.
50+
expectedURL := fmt.Sprintf("%s/%s%s", baseURL, handler.TenantID, endpointPath)
51+
resultURL := handler.ConstructAPIAuthEndpoint(endpointPath, mockLog)
52+
53+
assert.Equal(t, expectedURL, resultURL, "URL should match expected format")
54+
mockLog.AssertExpectations(t)
55+
}

0 commit comments

Comments
 (0)