mirror of
https://github.com/empayre/fleet.git
synced 2024-11-06 17:05:18 +00:00
842ebbb2ae
This adds a new API client named DeviceClient to server/service, meant to consume device endpoints and be used from Fleet Desktop. Some of the logic to make requests and parse responses was very repetitive, so I introduced a private baseClient type and moved some of the logic of the existent Client there. Related to #5685 and #5697
61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
package service
|
|
|
|
import (
|
|
"bytes"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
type mockHttpClient struct {
|
|
resBody string
|
|
statusCode int
|
|
err error
|
|
}
|
|
|
|
func (m *mockHttpClient) Do(req *http.Request) (*http.Response, error) {
|
|
if m.err != nil {
|
|
return nil, m.err
|
|
}
|
|
|
|
res := &http.Response{
|
|
StatusCode: m.statusCode,
|
|
Body: ioutil.NopCloser(bytes.NewBufferString(m.resBody)),
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
func TestDeviceClientListPolicies(t *testing.T) {
|
|
client, err := NewDeviceClient("https://test.com", "test-token", true, "")
|
|
require.NoError(t, err)
|
|
|
|
mockRequestDoer := &mockHttpClient{}
|
|
client.http = mockRequestDoer
|
|
|
|
t.Run("with wrong license", func(t *testing.T) {
|
|
mockRequestDoer.statusCode = http.StatusPaymentRequired
|
|
_, err = client.ListDevicePolicies()
|
|
require.ErrorIs(t, err, ErrMissingLicense)
|
|
})
|
|
|
|
t.Run("with empty policies", func(t *testing.T) {
|
|
mockRequestDoer.statusCode = http.StatusOK
|
|
mockRequestDoer.resBody = `{"policies": []}`
|
|
policies, err := client.ListDevicePolicies()
|
|
require.NoError(t, err)
|
|
require.Len(t, policies, 0)
|
|
})
|
|
|
|
t.Run("with policies", func(t *testing.T) {
|
|
mockRequestDoer.statusCode = http.StatusOK
|
|
mockRequestDoer.resBody = `{"policies": [{"id": 1}]}`
|
|
policies, err := client.ListDevicePolicies()
|
|
require.NoError(t, err)
|
|
require.Len(t, policies, 1)
|
|
require.Equal(t, uint(1), policies[0].ID)
|
|
})
|
|
}
|