Add Get Bucket Retention Config Api (#520)

This commit is contained in:
Cesar N
2020-12-15 19:25:43 -06:00
committed by GitHub
parent 369ae9342e
commit d7de170105
12 changed files with 880 additions and 3 deletions

View File

@@ -69,6 +69,7 @@ type MinioClient interface {
putObjectTagging(ctx context.Context, bucketName, objectName string, otags *tags.Tags, opts minio.PutObjectTaggingOptions) error
getObjectTagging(ctx context.Context, bucketName, objectName string, opts minio.GetObjectTaggingOptions) (*tags.Tags, error)
setObjectLockConfig(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error
getBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error)
}
// Interface implementation
@@ -174,6 +175,10 @@ func (c minioClient) setObjectLockConfig(ctx context.Context, bucketName string,
return c.client.SetObjectLockConfig(ctx, bucketName, mode, validity, unit)
}
func (c minioClient) getBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
return c.client.GetBucketObjectLockConfig(ctx, bucketName)
}
// MCClient interface with all functions to be implemented
// by mock when testing, it should include all mc/S3Client respective api calls
// that are used within this project.

View File

@@ -940,6 +940,35 @@ func init() {
}
},
"/buckets/{bucket_name}/retention": {
"get": {
"tags": [
"UserAPI"
],
"summary": "Get Bucket's retention config",
"operationId": "GetBucketRetentionConfig",
"parameters": [
{
"type": "string",
"name": "bucket_name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/getBucketRetentionConfig"
}
},
"default": {
"description": "Generic error response.",
"schema": {
"$ref": "#/definitions/error"
}
}
}
},
"put": {
"tags": [
"UserAPI"
@@ -3563,6 +3592,21 @@ func init() {
}
}
},
"getBucketRetentionConfig": {
"type": "object",
"properties": {
"mode": {
"$ref": "#/definitions/objectRetentionMode"
},
"unit": {
"$ref": "#/definitions/objectRetentionUnit"
},
"validity": {
"type": "integer",
"format": "int32"
}
}
},
"group": {
"type": "object",
"properties": {
@@ -6020,6 +6064,35 @@ func init() {
}
},
"/buckets/{bucket_name}/retention": {
"get": {
"tags": [
"UserAPI"
],
"summary": "Get Bucket's retention config",
"operationId": "GetBucketRetentionConfig",
"parameters": [
{
"type": "string",
"name": "bucket_name",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "A successful response.",
"schema": {
"$ref": "#/definitions/getBucketRetentionConfig"
}
},
"default": {
"description": "Generic error response.",
"schema": {
"$ref": "#/definitions/error"
}
}
}
},
"put": {
"tags": [
"UserAPI"
@@ -9166,6 +9239,21 @@ func init() {
}
}
},
"getBucketRetentionConfig": {
"type": "object",
"properties": {
"mode": {
"$ref": "#/definitions/objectRetentionMode"
},
"unit": {
"$ref": "#/definitions/objectRetentionUnit"
},
"validity": {
"type": "integer",
"format": "int32"
}
}
},
"group": {
"type": "object",
"properties": {

View File

@@ -151,6 +151,9 @@ func NewConsoleAPI(spec *loads.Document) *ConsoleAPI {
UserAPIGetBucketReplicationHandler: user_api.GetBucketReplicationHandlerFunc(func(params user_api.GetBucketReplicationParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user_api.GetBucketReplication has not yet been implemented")
}),
UserAPIGetBucketRetentionConfigHandler: user_api.GetBucketRetentionConfigHandlerFunc(func(params user_api.GetBucketRetentionConfigParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user_api.GetBucketRetentionConfig has not yet been implemented")
}),
UserAPIGetBucketVersioningHandler: user_api.GetBucketVersioningHandlerFunc(func(params user_api.GetBucketVersioningParams, principal *models.Principal) middleware.Responder {
return middleware.NotImplemented("operation user_api.GetBucketVersioning has not yet been implemented")
}),
@@ -423,6 +426,8 @@ type ConsoleAPI struct {
UserAPIGetBucketQuotaHandler user_api.GetBucketQuotaHandler
// UserAPIGetBucketReplicationHandler sets the operation handler for the get bucket replication operation
UserAPIGetBucketReplicationHandler user_api.GetBucketReplicationHandler
// UserAPIGetBucketRetentionConfigHandler sets the operation handler for the get bucket retention config operation
UserAPIGetBucketRetentionConfigHandler user_api.GetBucketRetentionConfigHandler
// UserAPIGetBucketVersioningHandler sets the operation handler for the get bucket versioning operation
UserAPIGetBucketVersioningHandler user_api.GetBucketVersioningHandler
// AdminAPIGetMaxAllocatableMemHandler sets the operation handler for the get max allocatable mem operation
@@ -694,6 +699,9 @@ func (o *ConsoleAPI) Validate() error {
if o.UserAPIGetBucketReplicationHandler == nil {
unregistered = append(unregistered, "user_api.GetBucketReplicationHandler")
}
if o.UserAPIGetBucketRetentionConfigHandler == nil {
unregistered = append(unregistered, "user_api.GetBucketRetentionConfigHandler")
}
if o.UserAPIGetBucketVersioningHandler == nil {
unregistered = append(unregistered, "user_api.GetBucketVersioningHandler")
}
@@ -1077,6 +1085,10 @@ func (o *ConsoleAPI) initHandlerCache() {
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/buckets/{bucket_name}/retention"] = user_api.NewGetBucketRetentionConfig(o.context, o.UserAPIGetBucketRetentionConfigHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/buckets/{bucket_name}/versioning"] = user_api.NewGetBucketVersioning(o.context, o.UserAPIGetBucketVersioningHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)

View File

@@ -0,0 +1,90 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2020 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package user_api
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/minio/console/models"
)
// GetBucketRetentionConfigHandlerFunc turns a function with the right signature into a get bucket retention config handler
type GetBucketRetentionConfigHandlerFunc func(GetBucketRetentionConfigParams, *models.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn GetBucketRetentionConfigHandlerFunc) Handle(params GetBucketRetentionConfigParams, principal *models.Principal) middleware.Responder {
return fn(params, principal)
}
// GetBucketRetentionConfigHandler interface for that can handle valid get bucket retention config params
type GetBucketRetentionConfigHandler interface {
Handle(GetBucketRetentionConfigParams, *models.Principal) middleware.Responder
}
// NewGetBucketRetentionConfig creates a new http.Handler for the get bucket retention config operation
func NewGetBucketRetentionConfig(ctx *middleware.Context, handler GetBucketRetentionConfigHandler) *GetBucketRetentionConfig {
return &GetBucketRetentionConfig{Context: ctx, Handler: handler}
}
/*GetBucketRetentionConfig swagger:route GET /buckets/{bucket_name}/retention UserAPI getBucketRetentionConfig
Get Bucket's retention config
*/
type GetBucketRetentionConfig struct {
Context *middleware.Context
Handler GetBucketRetentionConfigHandler
}
func (o *GetBucketRetentionConfig) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
r = rCtx
}
var Params = NewGetBucketRetentionConfigParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
r = aCtx
}
var principal *models.Principal
if uprinc != nil {
principal = uprinc.(*models.Principal) // this is really a models.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}

View File

@@ -0,0 +1,89 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2020 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package user_api
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
)
// NewGetBucketRetentionConfigParams creates a new GetBucketRetentionConfigParams object
// no default values defined in spec.
func NewGetBucketRetentionConfigParams() GetBucketRetentionConfigParams {
return GetBucketRetentionConfigParams{}
}
// GetBucketRetentionConfigParams contains all the bound params for the get bucket retention config operation
// typically these are obtained from a http.Request
//
// swagger:parameters GetBucketRetentionConfig
type GetBucketRetentionConfigParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
BucketName string
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewGetBucketRetentionConfigParams() beforehand.
func (o *GetBucketRetentionConfigParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rBucketName, rhkBucketName, _ := route.Params.GetOK("bucket_name")
if err := o.bindBucketName(rBucketName, rhkBucketName, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindBucketName binds and validates parameter BucketName from path.
func (o *GetBucketRetentionConfigParams) bindBucketName(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.BucketName = raw
return nil
}

View File

@@ -0,0 +1,133 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2020 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package user_api
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
"github.com/minio/console/models"
)
// GetBucketRetentionConfigOKCode is the HTTP code returned for type GetBucketRetentionConfigOK
const GetBucketRetentionConfigOKCode int = 200
/*GetBucketRetentionConfigOK A successful response.
swagger:response getBucketRetentionConfigOK
*/
type GetBucketRetentionConfigOK struct {
/*
In: Body
*/
Payload *models.GetBucketRetentionConfig `json:"body,omitempty"`
}
// NewGetBucketRetentionConfigOK creates GetBucketRetentionConfigOK with default headers values
func NewGetBucketRetentionConfigOK() *GetBucketRetentionConfigOK {
return &GetBucketRetentionConfigOK{}
}
// WithPayload adds the payload to the get bucket retention config o k response
func (o *GetBucketRetentionConfigOK) WithPayload(payload *models.GetBucketRetentionConfig) *GetBucketRetentionConfigOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get bucket retention config o k response
func (o *GetBucketRetentionConfigOK) SetPayload(payload *models.GetBucketRetentionConfig) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetBucketRetentionConfigOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
/*GetBucketRetentionConfigDefault Generic error response.
swagger:response getBucketRetentionConfigDefault
*/
type GetBucketRetentionConfigDefault struct {
_statusCode int
/*
In: Body
*/
Payload *models.Error `json:"body,omitempty"`
}
// NewGetBucketRetentionConfigDefault creates GetBucketRetentionConfigDefault with default headers values
func NewGetBucketRetentionConfigDefault(code int) *GetBucketRetentionConfigDefault {
if code <= 0 {
code = 500
}
return &GetBucketRetentionConfigDefault{
_statusCode: code,
}
}
// WithStatusCode adds the status to the get bucket retention config default response
func (o *GetBucketRetentionConfigDefault) WithStatusCode(code int) *GetBucketRetentionConfigDefault {
o._statusCode = code
return o
}
// SetStatusCode sets the status to the get bucket retention config default response
func (o *GetBucketRetentionConfigDefault) SetStatusCode(code int) {
o._statusCode = code
}
// WithPayload adds the payload to the get bucket retention config default response
func (o *GetBucketRetentionConfigDefault) WithPayload(payload *models.Error) *GetBucketRetentionConfigDefault {
o.Payload = payload
return o
}
// SetPayload sets the payload to the get bucket retention config default response
func (o *GetBucketRetentionConfigDefault) SetPayload(payload *models.Error) {
o.Payload = payload
}
// WriteResponse to the client
func (o *GetBucketRetentionConfigDefault) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(o._statusCode)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}

View File

@@ -0,0 +1,116 @@
// Code generated by go-swagger; DO NOT EDIT.
// This file is part of MinIO Console Server
// Copyright (c) 2020 MinIO, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package user_api
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
"strings"
)
// GetBucketRetentionConfigURL generates an URL for the get bucket retention config operation
type GetBucketRetentionConfigURL struct {
BucketName string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetBucketRetentionConfigURL) WithBasePath(bp string) *GetBucketRetentionConfigURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *GetBucketRetentionConfigURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *GetBucketRetentionConfigURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/buckets/{bucket_name}/retention"
bucketName := o.BucketName
if bucketName != "" {
_path = strings.Replace(_path, "{bucket_name}", bucketName, -1)
} else {
return nil, errors.New("bucketName is required on GetBucketRetentionConfigURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *GetBucketRetentionConfigURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *GetBucketRetentionConfigURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *GetBucketRetentionConfigURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on GetBucketRetentionConfigURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on GetBucketRetentionConfigURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *GetBucketRetentionConfigURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@@ -24,6 +24,7 @@ import (
"strings"
"time"
"github.com/minio/mc/pkg/probe"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/replication"
"github.com/minio/minio-go/v7/pkg/sse"
@@ -134,6 +135,14 @@ func registerBucketsHandlers(api *operations.ConsoleAPI) {
}
return user_api.NewSetBucketRetentionConfigOK()
})
// get bucket retention config
api.UserAPIGetBucketRetentionConfigHandler = user_api.GetBucketRetentionConfigHandlerFunc(func(params user_api.GetBucketRetentionConfigParams, session *models.Principal) middleware.Responder {
response, err := getBucketRetentionConfigResponse(session, params.BucketName)
if err != nil {
return user_api.NewGetBucketRetentionConfigDefault(int(err.Code)).WithPayload(err)
}
return user_api.NewGetBucketRetentionConfigOK().WithPayload(response)
})
}
func getAddBucketReplicationdResponse(session *models.Principal, bucketName string, params *user_api.AddBucketReplicationParams) error {
@@ -636,3 +645,58 @@ func getSetBucketRetentionConfigResponse(session *models.Principal, params user_
}
return nil
}
func getBucketRetentionConfig(ctx context.Context, client MinioClient, bucketName string) (*models.GetBucketRetentionConfig, error) {
m, v, u, err := client.getBucketObjectLockConfig(ctx, bucketName)
if err != nil {
errResp := minio.ToErrorResponse(probe.NewError(err).ToGoError())
if errResp.Code == "ObjectLockConfigurationNotFoundError" {
return &models.GetBucketRetentionConfig{}, nil
}
return nil, err
}
var mode models.ObjectRetentionMode
var unit models.ObjectRetentionUnit
switch *m {
case minio.Governance:
mode = models.ObjectRetentionModeGovernance
case minio.Compliance:
mode = models.ObjectRetentionModeCompliance
default:
return nil, errors.New("invalid retention mode")
}
switch *u {
case minio.Days:
unit = models.ObjectRetentionUnitDays
case minio.Years:
unit = models.ObjectRetentionUnitYears
default:
return nil, errors.New("invalid retention unit")
}
config := &models.GetBucketRetentionConfig{
Mode: mode,
Unit: unit,
Validity: int32(*v),
}
return config, nil
}
func getBucketRetentionConfigResponse(session *models.Principal, bucketName string) (*models.GetBucketRetentionConfig, *models.Error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*20)
defer cancel()
mClient, err := newMinioClient(session)
if err != nil {
return nil, prepareError(err)
}
// create a minioClient interface implementation
// defining the client to be used
minioClient := minioClient{client: mClient}
config, err := getBucketRetentionConfig(ctx, minioClient, bucketName)
if err != nil {
return nil, prepareError(err)
}
return config, nil
}

View File

@@ -42,7 +42,8 @@ var minioGetBucketPolicyMock func(bucketName string) (string, error)
var minioSetBucketEncryptionMock func(ctx context.Context, bucketName string, config *sse.Configuration) error
var minioRemoveBucketEncryptionMock func(ctx context.Context, bucketName string) error
var minioGetBucketEncryptionMock func(ctx context.Context, bucketName string) (*sse.Configuration, error)
var minioSetObjectLockConfig func(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error
var minioSetObjectLockConfigMock func(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error
var minioGetObjectLockConfigMock func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error)
// Define a mock struct of minio Client interface implementation
type minioClientMock struct {
@@ -86,7 +87,11 @@ func (mc minioClientMock) getBucketEncryption(ctx context.Context, bucketName st
}
func (mc minioClientMock) setObjectLockConfig(ctx context.Context, bucketName string, mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit) error {
return minioSetObjectLockConfig(ctx, bucketName, mode, validity, unit)
return minioSetObjectLockConfigMock(ctx, bucketName, mode, validity, unit)
}
func (mc minioClientMock) getBucketObjectLockConfig(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
return minioGetObjectLockConfigMock(ctx, bucketName)
}
var minioAccountInfoMock func(ctx context.Context) (madmin.AccountInfo, error)
@@ -632,7 +637,7 @@ func Test_SetBucketRetentionConfig(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
minioSetObjectLockConfig = tt.args.mockBucketRetentionFunc
minioSetObjectLockConfigMock = tt.args.mockBucketRetentionFunc
err := setBucketRetentionConfig(tt.args.ctx, tt.args.client, tt.args.bucketName, tt.args.mode, tt.args.unit, tt.args.validity)
if tt.expectedError != nil {
fmt.Println(t.Name())
@@ -643,3 +648,120 @@ func Test_SetBucketRetentionConfig(t *testing.T) {
})
}
}
func Test_GetBucketRetentionConfig(t *testing.T) {
assert := assert.New(t)
ctx := context.Background()
minClient := minioClientMock{}
type args struct {
ctx context.Context
client MinioClient
bucketName string
getRetentionFunc func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error)
}
tests := []struct {
name string
args args
expectedResponse *models.GetBucketRetentionConfig
expectedError error
}{
{
name: "Get Bucket Retention Config",
args: args{
ctx: ctx,
client: minClient,
bucketName: "test",
getRetentionFunc: func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
m := minio.Governance
u := minio.Days
return &m, swag.Uint(2), &u, nil
},
},
expectedResponse: &models.GetBucketRetentionConfig{
Mode: models.ObjectRetentionModeGovernance,
Unit: models.ObjectRetentionUnitDays,
Validity: int32(2),
},
expectedError: nil,
},
{
name: "Handle Error on minio func",
args: args{
ctx: ctx,
client: minClient,
bucketName: "test",
getRetentionFunc: func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
return nil, nil, nil, errors.New("error func")
},
},
expectedResponse: nil,
expectedError: errors.New("error func"),
},
{
// Description: if minio return NoSuchObjectLockConfiguration, don't panic
// and return empty response
name: "Handle NoLock Config error",
args: args{
ctx: ctx,
client: minClient,
bucketName: "test",
getRetentionFunc: func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
return nil, nil, nil, minio.ErrorResponse{
Code: "ObjectLockConfigurationNotFoundError",
Message: "Object Lock configuration does not exist for this bucket",
}
},
},
expectedResponse: &models.GetBucketRetentionConfig{},
expectedError: nil,
},
{
name: "Return error on invalid mode",
args: args{
ctx: ctx,
client: minClient,
bucketName: "test",
getRetentionFunc: func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
m := minio.RetentionMode("other")
u := minio.Days
return &m, swag.Uint(2), &u, nil
},
},
expectedResponse: nil,
expectedError: errors.New("invalid retention mode"),
},
{
name: "Return error on invalid unit",
args: args{
ctx: ctx,
client: minClient,
bucketName: "test",
getRetentionFunc: func(ctx context.Context, bucketName string) (mode *minio.RetentionMode, validity *uint, unit *minio.ValidityUnit, err error) {
m := minio.Governance
u := minio.ValidityUnit("otherUnit")
return &m, swag.Uint(2), &u, nil
},
},
expectedResponse: nil,
expectedError: errors.New("invalid retention unit"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
minioGetObjectLockConfigMock = tt.args.getRetentionFunc
resp, err := getBucketRetentionConfig(tt.args.ctx, tt.args.client, tt.args.bucketName)
if tt.expectedError != nil {
fmt.Println(t.Name())
assert.Equal(tt.expectedError.Error(), err.Error(), fmt.Sprintf("getBucketRetentionConfig() error: `%s`, wantErr: `%s`", err, tt.expectedError))
} else {
assert.Nil(err, fmt.Sprintf("getBucketRetentionConfig() error: %v, wantErr: %v", err, tt.expectedError))
if !reflect.DeepEqual(resp, tt.expectedResponse) {
t.Errorf("getBucketRetentionConfig() resp: %v, expectedResponse: %v", resp, tt.expectedResponse)
return
}
}
})
}
}