From 42a9620c9318be8b848e52c05f248a67715117da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Han?= Date: Tue, 13 Jul 2021 17:16:35 +0200 Subject: [PATCH] rgw/admin: add ability to mock HTTP Client MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We can now use a mocked client to be consumed by unit tests as well as various users of the API. Signed-off-by: Sébastien Han --- rgw/admin/mock.go | 18 ++++++++++++++++++ rgw/admin/user_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 rgw/admin/mock.go diff --git a/rgw/admin/mock.go b/rgw/admin/mock.go new file mode 100644 index 0000000..13b3746 --- /dev/null +++ b/rgw/admin/mock.go @@ -0,0 +1,18 @@ +package admin + +import ( + "net/http" +) + +// MockClient is the mock of the HTTP Client +// It can be used to mock HTTP request/response from the rgw admin ops API +type MockClient struct { + // MockDo is a type that mock the Do method from the HTTP package + MockDo MockDoType +} + +// MockDoType is a custom type that allows setting the function that our Mock Do func will run instead +type MockDoType func(req *http.Request) (*http.Response, error) + +// Do is the mock client's `Do` func +func (m *MockClient) Do(req *http.Request) (*http.Response, error) { return m.MockDo(req) } diff --git a/rgw/admin/user_test.go b/rgw/admin/user_test.go index ec3b19b..54dda22 100644 --- a/rgw/admin/user_test.go +++ b/rgw/admin/user_test.go @@ -1,10 +1,13 @@ package admin import ( + "bytes" "context" "encoding/json" "errors" "fmt" + "io/ioutil" + "net/http" "testing" "github.com/stretchr/testify/assert" @@ -135,3 +138,24 @@ func (suite *RadosGWTestSuite) TestUser() { assert.NoError(suite.T(), err) }) } + +func TestGetUserMockAPI(t *testing.T) { + r := ioutil.NopCloser(bytes.NewReader(fakeUserResponse)) + mockClient := &MockClient{ + MockDo: func(req *http.Request) (*http.Response, error) { + if req.URL.RawQuery == "format=json&uid=dashboard-admin" && req.Method == http.MethodGet && req.URL.Path == "127.0.0.1/admin/user" { + return &http.Response{ + StatusCode: 200, + Body: r, + }, nil + } + return nil, fmt.Errorf("unexpected request: %q. method %q. path %q", req.URL.RawQuery, req.Method, req.URL.Path) + }, + } + + api, err := New("127.0.0.1", "accessKey", "secretKey", mockClient) + assert.NoError(t, err) + u, err := api.GetUser(context.TODO(), User{ID: "dashboard-admin"}) + assert.NoError(t, err) + assert.Equal(t, "dashboard-admin", u.DisplayName, u) +}